_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
266a0d9ede9e78e61b5150f1e581a8ad9f85bf489f20b12669efa924970bba08
death/dbus
protocols.lisp
;;;; +----------------------------------------------------------------+ ;;;; | DBUS | ;;;; +----------------------------------------------------------------+ (defpackage #:dbus/protocols (:use #:cl) (:export #:server-address #:server-address-transport-name #:server-address-property #:open-connection #:connection #:connection-server-address #:connection-server-uuid #:connection-fd #:connection-pending-messages #:connection-next-serial #:drain-pending-messages #:close-connection #:wait-for-reply #:receive-message-no-hang #:receive-line #:send-message #:send-line #:supported-authentication-mechanisms #:authenticate #:supports-unix-fd-passing-p #:authentication-mechanism #:authentication-mechanism-name #:authentication-mechanism-textual-p #:feed-authentication-mechanism)) (in-package #:dbus/protocols) ;;;; Server address protocol (defclass server-address () () (:documentation "Represents a DBUS server address, consisting of a transport name and zero or more properties.")) (defgeneric server-address-transport-name (server-address) (:documentation "Return the transport name for the server address.")) (defgeneric server-address-property (name server-address &key if-does-not-exist) (:documentation "Return the value of the server address's property with the supplied name.")) (defgeneric open-connection (event-base server-address &key if-failed) (:documentation "Open a connection to the server designated by the server address and return a connection object. The default value for IF-FAILED is :ERROR. An IOLIB event base object must be passed. Should also send the initial \"nul byte\".")) Connection protocol (defclass connection () () (:documentation "Represents a DBUS connection to a server.")) (defgeneric connection-server-address (connection) (:documentation "Return the address of the server associated with the connection.")) (defgeneric connection-server-uuid (connection) (:documentation "Return the unique ID of the server associated with the connection.")) (defgeneric (setf connection-server-uuid) (uuid connection) (:documentation "Set the unique ID of the server associated with the connection. If an ID is already set and is not EQUAL to the new ID, signal a continuable error.")) (defgeneric connection-fd (connection) (:documentation "Return the file descriptor associated with the (open) connection.")) (defgeneric connection-pending-messages (connection) (:documentation "Return a list of the currently pending messages associated with the connection, from newest to oldest.")) (defgeneric (setf connection-pending-messages) (new-list connection) (:documentation "Set the list of currently pending messages associated with the connection.")) (defgeneric connection-next-serial (connection) (:documentation "Return a 32-bit integer for associating request messages and their replies.")) (defgeneric drain-pending-messages (connection) (:documentation "Return a list of the currently pending messages associated with the connection, from oldest to newest, and consider these messages no longer pending.")) (defgeneric close-connection (connection) (:documentation "Close an open connection.")) (defgeneric wait-for-reply (serial connection) (:documentation "Wait for a reply message with the supplied serial to be received via connection.")) (defgeneric receive-message-no-hang (connection) (:documentation "Read a D-BUS message from the server. If no message is available to read, return NIL.")) (defgeneric receive-line (connection) (:documentation "Read a line of text from the server and return it as a string. The operation blocks until a whole line can be read. The string will not contain newline characters.")) (defgeneric send-message (encoded-message connection) (:documentation "Send an encoded message to the server. The operation will force (but not finish) output before returning.")) (defgeneric send-line (line connection) (:documentation "Send a line of text, represented by a string, to the server. The operation will force (but not finish) output before returning. The string should not contain any newline characters.")) (defgeneric supported-authentication-mechanisms (connection) (:documentation "Return a list of authentication mechanisms supported by the server.")) (defgeneric authenticate (authentication-mechanisms connection &key if-failed) (:documentation "Attempt to authenticate with the server associated with the connection, and return true if successful. The default value for IF-FAILED is :ERROR.")) (defgeneric supports-unix-fd-passing-p (connection) (:documentation "Return true if Unix file descriptors can be passed over the connection, and false otherwise.")) ;;;; Authentication mechanism protocol (defclass authentication-mechanism () () (:documentation "Represents a way to authenticate a client with a server.")) (defgeneric authentication-mechanism-name (authentication-mechanism) (:documentation "Return the name for the authentication mechanism.")) (defgeneric authentication-mechanism-textual-p (authentication-mechanism) (:documentation "Return true if data from server should be converted to a string, and false if it should remain an octet vector.")) (defgeneric feed-authentication-mechanism (authentication-mechanism challenge) (:documentation "Feed authentication mechanism with a challenge, which is either a string or an octet vector in accordance with the mechanism's textuality, or :INITIAL-RESPONSE. The method should return one of the following: :CONTINUE <response> Continue with the authentication conversation and send <response> to the server. :OK <response> After sending <response> to the server the client is finished and expecting an :OK response. :ERROR The challenge was invalid."))
null
https://raw.githubusercontent.com/death/dbus/f4d1a99cfb38ded33f4fb58bb5522815f530b3c3/protocols.lisp
lisp
+----------------------------------------------------------------+ | DBUS | +----------------------------------------------------------------+ Server address protocol Authentication mechanism protocol
(defpackage #:dbus/protocols (:use #:cl) (:export #:server-address #:server-address-transport-name #:server-address-property #:open-connection #:connection #:connection-server-address #:connection-server-uuid #:connection-fd #:connection-pending-messages #:connection-next-serial #:drain-pending-messages #:close-connection #:wait-for-reply #:receive-message-no-hang #:receive-line #:send-message #:send-line #:supported-authentication-mechanisms #:authenticate #:supports-unix-fd-passing-p #:authentication-mechanism #:authentication-mechanism-name #:authentication-mechanism-textual-p #:feed-authentication-mechanism)) (in-package #:dbus/protocols) (defclass server-address () () (:documentation "Represents a DBUS server address, consisting of a transport name and zero or more properties.")) (defgeneric server-address-transport-name (server-address) (:documentation "Return the transport name for the server address.")) (defgeneric server-address-property (name server-address &key if-does-not-exist) (:documentation "Return the value of the server address's property with the supplied name.")) (defgeneric open-connection (event-base server-address &key if-failed) (:documentation "Open a connection to the server designated by the server address and return a connection object. The default value for IF-FAILED is :ERROR. An IOLIB event base object must be passed. Should also send the initial \"nul byte\".")) Connection protocol (defclass connection () () (:documentation "Represents a DBUS connection to a server.")) (defgeneric connection-server-address (connection) (:documentation "Return the address of the server associated with the connection.")) (defgeneric connection-server-uuid (connection) (:documentation "Return the unique ID of the server associated with the connection.")) (defgeneric (setf connection-server-uuid) (uuid connection) (:documentation "Set the unique ID of the server associated with the connection. If an ID is already set and is not EQUAL to the new ID, signal a continuable error.")) (defgeneric connection-fd (connection) (:documentation "Return the file descriptor associated with the (open) connection.")) (defgeneric connection-pending-messages (connection) (:documentation "Return a list of the currently pending messages associated with the connection, from newest to oldest.")) (defgeneric (setf connection-pending-messages) (new-list connection) (:documentation "Set the list of currently pending messages associated with the connection.")) (defgeneric connection-next-serial (connection) (:documentation "Return a 32-bit integer for associating request messages and their replies.")) (defgeneric drain-pending-messages (connection) (:documentation "Return a list of the currently pending messages associated with the connection, from oldest to newest, and consider these messages no longer pending.")) (defgeneric close-connection (connection) (:documentation "Close an open connection.")) (defgeneric wait-for-reply (serial connection) (:documentation "Wait for a reply message with the supplied serial to be received via connection.")) (defgeneric receive-message-no-hang (connection) (:documentation "Read a D-BUS message from the server. If no message is available to read, return NIL.")) (defgeneric receive-line (connection) (:documentation "Read a line of text from the server and return it as a string. The operation blocks until a whole line can be read. The string will not contain newline characters.")) (defgeneric send-message (encoded-message connection) (:documentation "Send an encoded message to the server. The operation will force (but not finish) output before returning.")) (defgeneric send-line (line connection) (:documentation "Send a line of text, represented by a string, to the server. The operation will force (but not finish) output before returning. The string should not contain any newline characters.")) (defgeneric supported-authentication-mechanisms (connection) (:documentation "Return a list of authentication mechanisms supported by the server.")) (defgeneric authenticate (authentication-mechanisms connection &key if-failed) (:documentation "Attempt to authenticate with the server associated with the connection, and return true if successful. The default value for IF-FAILED is :ERROR.")) (defgeneric supports-unix-fd-passing-p (connection) (:documentation "Return true if Unix file descriptors can be passed over the connection, and false otherwise.")) (defclass authentication-mechanism () () (:documentation "Represents a way to authenticate a client with a server.")) (defgeneric authentication-mechanism-name (authentication-mechanism) (:documentation "Return the name for the authentication mechanism.")) (defgeneric authentication-mechanism-textual-p (authentication-mechanism) (:documentation "Return true if data from server should be converted to a string, and false if it should remain an octet vector.")) (defgeneric feed-authentication-mechanism (authentication-mechanism challenge) (:documentation "Feed authentication mechanism with a challenge, which is either a string or an octet vector in accordance with the mechanism's textuality, or :INITIAL-RESPONSE. The method should return one of the following: :CONTINUE <response> Continue with the authentication conversation and send <response> to the server. :OK <response> After sending <response> to the server the client is finished and expecting an :OK response. :ERROR The challenge was invalid."))
82f92eb7a7eafacbaffa7e338270899c70f5dcaae007176edeb1f4748786b488
janestreet/base_quickcheck
base_quickcheck_examples.ml
(*_ This library deliberately exports nothing. *)
null
https://raw.githubusercontent.com/janestreet/base_quickcheck/b3dc5bda5084253f62362293977e451a6c4257de/examples/base_quickcheck_examples.ml
ocaml
_ This library deliberately exports nothing.
052ca491e811d4bb60341ce7f0bedddffdd034e44ca172d688027cebb557bb84
xapix-io/axel-f
autocomplete.cljc
(ns axel-f.autocomplete (:refer-clojure :exclude [flatten]) (:require [clj-fuzzy.metrics :as fuzzy] [clojure.string :as string])) (defn arg->doc [arg opts] (let [{:keys [doc]} (meta arg)] (merge {:desc doc} opts))) (defn arglist->doc [arglist] (loop [acc [] opts {} arg (first arglist) arglist (rest arglist)] (if arg (if (= arg '&) (recur acc (assoc opts :opt true :repeatable true) (first arglist) (rest arglist)) (if (vector? arg) (recur acc (dissoc opts :repeatable) (first arg) (concat (rest arg) (rest arglist))) (recur (conj acc (arg->doc arg opts)) {} (first arglist) (rest arglist)))) acc))) (defn ref-meta->doc [{:keys [doc arglists]}] {:type :FN :desc doc :args (arglist->doc (first arglists))}) (defn flatten "Transform a nested map into a seq of [keyseq leaf-val] pairs" [m] (when m ((fn flatten-helper [keyseq m] (when m (cond (map? m) (concat [[keyseq m]] (mapcat (fn [[k v]] (flatten-helper (concat keyseq (list k)) v)) m)) (and (sequential? m) (indexed? m)) (concat [[keyseq m] [(concat keyseq (list "*")) m]] (mapcat (fn [i v] (concat (flatten-helper (concat keyseq (list i)) v) (when (or (map? v) (and (sequential? v) (indexed? v))) (flatten-helper (concat keyseq (list "*")) v)))) (range) m)) :else [[keyseq m]]))) '() m))) (defn env->index [env] (loop [acc {} paths (flatten env)] (if (empty? paths) acc (let [[path v] (first paths)] (recur (cond ((some-fn fn? var?) v) (let [m (meta v)] (if (:deprecated m) acc (assoc acc path (ref-meta->doc m)))) (map? v) (reduce (fn [acc [p v]] (if (map? v) acc (let [m (meta v)] (if (:deprecated m) acc (assoc acc (list (string/join "." (concat path (list p)))) (ref-meta->doc m)))))) acc v) :else acc) (rest paths)))))) (defn context->index [context] (loop [acc {} paths (flatten context)] (if (empty? paths) acc (let [[path v] (first paths) visited? (contains? acc path)] (recur (if visited? (let [{:keys [sub-type value]} (get acc path)] (case sub-type nil (assoc acc path {:type :REF :desc "Field in the context" :sub-type :INDEX :value [value v]}) :INDEX (update-in acc [path :value] conj v))) (assoc acc path {:type :REF :desc "Field in the context" :value v})) (rest paths)))))) (defn index [obj] (let [env (dissoc obj :axel-f.runtime/context) context (:axel-f.runtime/context obj)] (merge (env->index env) (context->index context)))) (defn ->string [s] (if (keyword? s) (string/join "/" (filter identity ((juxt namespace name) s))) (str s))) (def ->lower-case-string (comp string/lower-case ->string)) (defn distance [s1 s2] (cond (empty? s2) 1 (empty? s1) 0 :else (fuzzy/jaccard s1 s2))) (defn search-index [index path] (sort-by (fn [[_ {:keys [distance]}]] distance) (sequence (comp (filter (fn [[ik _]] (and (= (count ik) (count path)) (= (map ->lower-case-string (butlast ik)) (map ->lower-case-string (butlast path))) (or (= (->lower-case-string (last path)) (->lower-case-string (last ik))) (string/starts-with? (->lower-case-string (last ik)) (->lower-case-string (last path))) (> (/ 2 3) (distance (->lower-case-string (last path)) (->lower-case-string (last ik)))))))) (map (fn [[ik v]] [ik (assoc v :distance (distance (->lower-case-string (last path)) (->lower-case-string (last ik))))]))) index)))
null
https://raw.githubusercontent.com/xapix-io/axel-f/ec8fca880033e0ae78a8d9f42538d4a71fba29bd/src/axel_f/autocomplete.cljc
clojure
(ns axel-f.autocomplete (:refer-clojure :exclude [flatten]) (:require [clj-fuzzy.metrics :as fuzzy] [clojure.string :as string])) (defn arg->doc [arg opts] (let [{:keys [doc]} (meta arg)] (merge {:desc doc} opts))) (defn arglist->doc [arglist] (loop [acc [] opts {} arg (first arglist) arglist (rest arglist)] (if arg (if (= arg '&) (recur acc (assoc opts :opt true :repeatable true) (first arglist) (rest arglist)) (if (vector? arg) (recur acc (dissoc opts :repeatable) (first arg) (concat (rest arg) (rest arglist))) (recur (conj acc (arg->doc arg opts)) {} (first arglist) (rest arglist)))) acc))) (defn ref-meta->doc [{:keys [doc arglists]}] {:type :FN :desc doc :args (arglist->doc (first arglists))}) (defn flatten "Transform a nested map into a seq of [keyseq leaf-val] pairs" [m] (when m ((fn flatten-helper [keyseq m] (when m (cond (map? m) (concat [[keyseq m]] (mapcat (fn [[k v]] (flatten-helper (concat keyseq (list k)) v)) m)) (and (sequential? m) (indexed? m)) (concat [[keyseq m] [(concat keyseq (list "*")) m]] (mapcat (fn [i v] (concat (flatten-helper (concat keyseq (list i)) v) (when (or (map? v) (and (sequential? v) (indexed? v))) (flatten-helper (concat keyseq (list "*")) v)))) (range) m)) :else [[keyseq m]]))) '() m))) (defn env->index [env] (loop [acc {} paths (flatten env)] (if (empty? paths) acc (let [[path v] (first paths)] (recur (cond ((some-fn fn? var?) v) (let [m (meta v)] (if (:deprecated m) acc (assoc acc path (ref-meta->doc m)))) (map? v) (reduce (fn [acc [p v]] (if (map? v) acc (let [m (meta v)] (if (:deprecated m) acc (assoc acc (list (string/join "." (concat path (list p)))) (ref-meta->doc m)))))) acc v) :else acc) (rest paths)))))) (defn context->index [context] (loop [acc {} paths (flatten context)] (if (empty? paths) acc (let [[path v] (first paths) visited? (contains? acc path)] (recur (if visited? (let [{:keys [sub-type value]} (get acc path)] (case sub-type nil (assoc acc path {:type :REF :desc "Field in the context" :sub-type :INDEX :value [value v]}) :INDEX (update-in acc [path :value] conj v))) (assoc acc path {:type :REF :desc "Field in the context" :value v})) (rest paths)))))) (defn index [obj] (let [env (dissoc obj :axel-f.runtime/context) context (:axel-f.runtime/context obj)] (merge (env->index env) (context->index context)))) (defn ->string [s] (if (keyword? s) (string/join "/" (filter identity ((juxt namespace name) s))) (str s))) (def ->lower-case-string (comp string/lower-case ->string)) (defn distance [s1 s2] (cond (empty? s2) 1 (empty? s1) 0 :else (fuzzy/jaccard s1 s2))) (defn search-index [index path] (sort-by (fn [[_ {:keys [distance]}]] distance) (sequence (comp (filter (fn [[ik _]] (and (= (count ik) (count path)) (= (map ->lower-case-string (butlast ik)) (map ->lower-case-string (butlast path))) (or (= (->lower-case-string (last path)) (->lower-case-string (last ik))) (string/starts-with? (->lower-case-string (last ik)) (->lower-case-string (last path))) (> (/ 2 3) (distance (->lower-case-string (last path)) (->lower-case-string (last ik)))))))) (map (fn [[ik v]] [ik (assoc v :distance (distance (->lower-case-string (last path)) (->lower-case-string (last ik))))]))) index)))
2088cdb638bee0c88822baf6a2497ebd7addb08e2bed9a13689af84b5c6dddae
softwarelanguageslab/maf
R5RS_scp1_fringe-1.scm
; Changes: * removed : 0 * added : 1 * swaps : 0 ; * negated predicates: 0 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((atom? (lambda (x) (not (pair? x)))) (fringe (lambda (l) (<change> () (display append)) (if (null? l) () (if (atom? l) (list l) (append (fringe (car l)) (fringe (cdr l)))))))) (equal? (fringe (__toplevel_cons (__toplevel_cons 1 ()) (__toplevel_cons (__toplevel_cons (__toplevel_cons (__toplevel_cons (__toplevel_cons 2 ()) ()) ()) ()) (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons (__toplevel_cons 4 (__toplevel_cons 5 ())) (__toplevel_cons 6 ()))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 7 ()) (__toplevel_cons 8 (__toplevel_cons 9 ()))) ()))))) (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 7 (__toplevel_cons 8 (__toplevel_cons 9 ())))))))))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_fringe-1.scm
scheme
Changes: * negated predicates: 0 * swapped branches: 0 * calls to id fun: 0
* removed : 0 * added : 1 * swaps : 0 (letrec ((atom? (lambda (x) (not (pair? x)))) (fringe (lambda (l) (<change> () (display append)) (if (null? l) () (if (atom? l) (list l) (append (fringe (car l)) (fringe (cdr l)))))))) (equal? (fringe (__toplevel_cons (__toplevel_cons 1 ()) (__toplevel_cons (__toplevel_cons (__toplevel_cons (__toplevel_cons (__toplevel_cons 2 ()) ()) ()) ()) (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons (__toplevel_cons 4 (__toplevel_cons 5 ())) (__toplevel_cons 6 ()))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 7 ()) (__toplevel_cons 8 (__toplevel_cons 9 ()))) ()))))) (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 7 (__toplevel_cons 8 (__toplevel_cons 9 ())))))))))))
17ffa8a99d7bfb2c86db701da3dda4af0fdc7e842ab0c6ded28d83f4f84a59b1
tezos/tezos-mirror
rpc_encodings.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2023 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. *) (* *) (*****************************************************************************) (** Encodings for the JSON-RPC standard. See . *) module JSONRPC = struct let version = "2.0" (** Ids in the JSON-RPC specification can be either a string, a number or NULL (which is represented by the option type). *) type id_repr = Id_string of string | Id_float of float let id_repr_encoding = let open Data_encoding in union [ case ~title:"id-string" (Tag 0) string (function Id_string s -> Some s | _ -> None) (fun s -> Id_string s); case ~title:"id-int" (Tag 1) float (function Id_float i -> Some i | _ -> None) (fun i -> Id_float i); ] type id = id_repr option type 'params request = { method_ : string; parameters : 'params option; id : id; } let request_encoding method_ parameters_encoding = Data_encoding.( conv (fun {parameters; id; _} -> ((), (), parameters, id)) (fun ((), (), parameters, id) -> {method_; parameters; id}) (obj4 (req "jsonrpc" (constant version)) (req "method" (constant method_)) (opt "params" parameters_encoding) (opt "id" id_repr_encoding))) type 'data error = {code : int; message : string; data : 'data option} let error_encoding data_encoding = Data_encoding.( conv (fun {code; message; data} -> (code, message, data)) (fun (code, message, data) -> {code; message; data}) (obj3 (req "code" int31) (req "message" string) (opt "data" data_encoding))) type ('result, 'data_error) response = { value : ('result, 'data_error error) result; id : id; } let response_encoding result_encoding error_data_encoding = Data_encoding.( conv (fun {value; id} -> let result, error = match value with Ok r -> (Some r, None) | Error e -> (None, Some e) in ((), result, error, id)) (fun ((), result, error, id) -> let value = match (result, error) with | Some r, None -> Ok r | None, Some e -> Error e | _ -> assert false (* Impossible case according to the JSON-RPC standard: result XOR error. *) in {value; id}) (obj4 (req "jsonrpc" (constant version)) (opt "result" result_encoding) (opt "error" (error_encoding error_data_encoding)) (req "id" (option id_repr_encoding)))) end type input = .. type output = .. module Error = struct type t = unit let encoding = Data_encoding.unit end type 'result rpc_result = ('result, Error.t JSONRPC.error) result module type METHOD_DEF = sig val method_ : string type input type output val input_encoding : input Data_encoding.t val output_encoding : output Data_encoding.t end module type METHOD = sig type m_input type m_output The parameters MAY be omitted . See JSONRPC Specification . type input += Input of m_input option type output += Output of m_output rpc_result val method_ : string val request_encoding : m_input JSONRPC.request Data_encoding.t val request : m_input option -> JSONRPC.id -> m_input JSONRPC.request val response_encoding : (m_output, Error.t) JSONRPC.response Data_encoding.t val response : (m_output, Error.t JSONRPC.error) result -> JSONRPC.id -> (m_output, Error.t) JSONRPC.response val response_ok : m_output -> JSONRPC.id -> (m_output, Error.t) JSONRPC.response end module MethodMaker (M : METHOD_DEF) : METHOD with type m_input = M.input and type m_output = M.output = struct type m_input = M.input type m_output = M.output type input += Input of m_input option type output += Output of m_output rpc_result let method_ = M.method_ let request_encoding = JSONRPC.request_encoding M.method_ M.input_encoding let request parameters id = JSONRPC.{method_; parameters; id} let response_encoding = JSONRPC.response_encoding M.output_encoding Error.encoding let response value id = JSONRPC.{value; id} let response_ok result id = response (Ok result) id end module Network_id = MethodMaker (struct type input = unit type output = string let input_encoding = Data_encoding.unit let output_encoding = Data_encoding.string let method_ = "net_version" end) module Chain_id = MethodMaker (struct type input = unit type output = Ethereum_types.quantity let input_encoding = Data_encoding.unit let output_encoding = Ethereum_types.quantity_encoding let method_ = "eth_chainId" end) module Accounts = MethodMaker (struct type input = unit type output = Ethereum_types.address list let input_encoding = Data_encoding.unit let output_encoding = Data_encoding.list Ethereum_types.address_encoding let method_ = "eth_accounts" end) module Get_balance = MethodMaker (struct open Ethereum_types type input = address * block_param type output = quantity let input_encoding = Data_encoding.tup2 address_encoding block_param_encoding let output_encoding = quantity_encoding let method_ = "eth_getBalance" end) module Block_number = MethodMaker (struct open Ethereum_types type input = unit type output = block_height let input_encoding = Data_encoding.unit let output_encoding = block_height_encoding let method_ = "eth_blockNumber" end) module Get_block_by_number = MethodMaker (struct open Ethereum_types type input = block_param * bool type output = block let input_encoding = Data_encoding.tup2 block_param_encoding Data_encoding.bool let output_encoding = block_encoding let method_ = "eth_getBlockByNumber" end) module Get_block_by_hash = MethodMaker (struct open Ethereum_types type input = hash * bool type output = block let input_encoding = Data_encoding.tup2 hash_encoding Data_encoding.bool let output_encoding = block_encoding let method_ = "eth_getBlockByHash" end) module Get_code = MethodMaker (struct open Ethereum_types type input = hash * block_param type output = hash let input_encoding = Data_encoding.tup2 hash_encoding block_param_encoding let output_encoding = hash_encoding let method_ = "eth_getCode" end) module Gas_price = MethodMaker (struct open Ethereum_types type input = unit type output = quantity let input_encoding = Data_encoding.unit let output_encoding = quantity_encoding let method_ = "eth_gasPrice" end) module Get_transaction_count = MethodMaker (struct open Ethereum_types type input = address * block_param type output = quantity let input_encoding = Data_encoding.tup2 address_encoding block_param_encoding let output_encoding = quantity_encoding let method_ = "eth_getTransactionCount" end) module Get_transaction_receipt = MethodMaker (struct open Ethereum_types type input = hash type output = transaction_receipt let input_encoding = Data_encoding.tup1 hash_encoding let output_encoding = transaction_receipt_encoding let method_ = "eth_getTransactionReceipt" end) module Send_raw_transaction = MethodMaker (struct open Ethereum_types type input = hash type output = hash let input_encoding = Data_encoding.tup1 hash_encoding let output_encoding = hash_encoding let method_ = "eth_sendRawTransaction" end) module Send_transaction = MethodMaker (struct open Ethereum_types type input = transaction type output = hash let input_encoding = transaction_encoding let output_encoding = hash_encoding let method_ = "eth_sendTransaction" end) module Eth_call = MethodMaker (struct open Ethereum_types type input = call * block_param type output = hash let input_encoding = Data_encoding.tup2 call_encoding block_param_encoding let output_encoding = hash_encoding let method_ = "eth_call" end) module Get_estimate_gas = MethodMaker (struct open Ethereum_types type input = call type output = quantity let input_encoding = Data_encoding.tup1 call_encoding let output_encoding = quantity_encoding let method_ = "eth_estimateGas" end) let methods : (module METHOD) list = [ (module Network_id); (module Chain_id); (module Accounts); (module Get_balance); (module Block_number); (module Get_block_by_number); (module Get_block_by_hash); (module Get_code); (module Gas_price); (module Get_transaction_count); (module Get_transaction_receipt); (module Send_transaction); (module Send_raw_transaction); (module Eth_call); (module Get_estimate_gas); ] module Input = struct type t = input let case_maker tag_id (module M : METHOD) = let open Data_encoding in case ~title:M.method_ (Tag tag_id) M.request_encoding (function M.Input input, id -> Some (M.request input id) | _ -> None) (fun {parameters; id; _} -> (M.Input parameters, id)) let encoding = let open Data_encoding in union @@ List.mapi case_maker methods end module Output = struct type nonrec 'a result = ('a, error JSONRPC.error) result let case_maker tag_id (module M : METHOD) = let open Data_encoding in case ~title:M.method_ (Tag tag_id) M.response_encoding (function | M.Output accounts, id -> Some JSONRPC.{value = accounts; id} | _ -> None) (fun {value = req; id} -> (M.Output req, id)) let encoding = let open Data_encoding in union @@ List.mapi case_maker methods end
null
https://raw.githubusercontent.com/tezos/tezos-mirror/c61377d496848a76aa607473c2f195bd4f8023d3/src/bin_evm_proxy/rpc_encodings.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. *************************************************************************** * Encodings for the JSON-RPC standard. See . * Ids in the JSON-RPC specification can be either a string, a number or NULL (which is represented by the option type). Impossible case according to the JSON-RPC standard: result XOR error.
Copyright ( c ) 2023 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 module JSONRPC = struct let version = "2.0" type id_repr = Id_string of string | Id_float of float let id_repr_encoding = let open Data_encoding in union [ case ~title:"id-string" (Tag 0) string (function Id_string s -> Some s | _ -> None) (fun s -> Id_string s); case ~title:"id-int" (Tag 1) float (function Id_float i -> Some i | _ -> None) (fun i -> Id_float i); ] type id = id_repr option type 'params request = { method_ : string; parameters : 'params option; id : id; } let request_encoding method_ parameters_encoding = Data_encoding.( conv (fun {parameters; id; _} -> ((), (), parameters, id)) (fun ((), (), parameters, id) -> {method_; parameters; id}) (obj4 (req "jsonrpc" (constant version)) (req "method" (constant method_)) (opt "params" parameters_encoding) (opt "id" id_repr_encoding))) type 'data error = {code : int; message : string; data : 'data option} let error_encoding data_encoding = Data_encoding.( conv (fun {code; message; data} -> (code, message, data)) (fun (code, message, data) -> {code; message; data}) (obj3 (req "code" int31) (req "message" string) (opt "data" data_encoding))) type ('result, 'data_error) response = { value : ('result, 'data_error error) result; id : id; } let response_encoding result_encoding error_data_encoding = Data_encoding.( conv (fun {value; id} -> let result, error = match value with Ok r -> (Some r, None) | Error e -> (None, Some e) in ((), result, error, id)) (fun ((), result, error, id) -> let value = match (result, error) with | Some r, None -> Ok r | None, Some e -> Error e | _ -> assert false in {value; id}) (obj4 (req "jsonrpc" (constant version)) (opt "result" result_encoding) (opt "error" (error_encoding error_data_encoding)) (req "id" (option id_repr_encoding)))) end type input = .. type output = .. module Error = struct type t = unit let encoding = Data_encoding.unit end type 'result rpc_result = ('result, Error.t JSONRPC.error) result module type METHOD_DEF = sig val method_ : string type input type output val input_encoding : input Data_encoding.t val output_encoding : output Data_encoding.t end module type METHOD = sig type m_input type m_output The parameters MAY be omitted . See JSONRPC Specification . type input += Input of m_input option type output += Output of m_output rpc_result val method_ : string val request_encoding : m_input JSONRPC.request Data_encoding.t val request : m_input option -> JSONRPC.id -> m_input JSONRPC.request val response_encoding : (m_output, Error.t) JSONRPC.response Data_encoding.t val response : (m_output, Error.t JSONRPC.error) result -> JSONRPC.id -> (m_output, Error.t) JSONRPC.response val response_ok : m_output -> JSONRPC.id -> (m_output, Error.t) JSONRPC.response end module MethodMaker (M : METHOD_DEF) : METHOD with type m_input = M.input and type m_output = M.output = struct type m_input = M.input type m_output = M.output type input += Input of m_input option type output += Output of m_output rpc_result let method_ = M.method_ let request_encoding = JSONRPC.request_encoding M.method_ M.input_encoding let request parameters id = JSONRPC.{method_; parameters; id} let response_encoding = JSONRPC.response_encoding M.output_encoding Error.encoding let response value id = JSONRPC.{value; id} let response_ok result id = response (Ok result) id end module Network_id = MethodMaker (struct type input = unit type output = string let input_encoding = Data_encoding.unit let output_encoding = Data_encoding.string let method_ = "net_version" end) module Chain_id = MethodMaker (struct type input = unit type output = Ethereum_types.quantity let input_encoding = Data_encoding.unit let output_encoding = Ethereum_types.quantity_encoding let method_ = "eth_chainId" end) module Accounts = MethodMaker (struct type input = unit type output = Ethereum_types.address list let input_encoding = Data_encoding.unit let output_encoding = Data_encoding.list Ethereum_types.address_encoding let method_ = "eth_accounts" end) module Get_balance = MethodMaker (struct open Ethereum_types type input = address * block_param type output = quantity let input_encoding = Data_encoding.tup2 address_encoding block_param_encoding let output_encoding = quantity_encoding let method_ = "eth_getBalance" end) module Block_number = MethodMaker (struct open Ethereum_types type input = unit type output = block_height let input_encoding = Data_encoding.unit let output_encoding = block_height_encoding let method_ = "eth_blockNumber" end) module Get_block_by_number = MethodMaker (struct open Ethereum_types type input = block_param * bool type output = block let input_encoding = Data_encoding.tup2 block_param_encoding Data_encoding.bool let output_encoding = block_encoding let method_ = "eth_getBlockByNumber" end) module Get_block_by_hash = MethodMaker (struct open Ethereum_types type input = hash * bool type output = block let input_encoding = Data_encoding.tup2 hash_encoding Data_encoding.bool let output_encoding = block_encoding let method_ = "eth_getBlockByHash" end) module Get_code = MethodMaker (struct open Ethereum_types type input = hash * block_param type output = hash let input_encoding = Data_encoding.tup2 hash_encoding block_param_encoding let output_encoding = hash_encoding let method_ = "eth_getCode" end) module Gas_price = MethodMaker (struct open Ethereum_types type input = unit type output = quantity let input_encoding = Data_encoding.unit let output_encoding = quantity_encoding let method_ = "eth_gasPrice" end) module Get_transaction_count = MethodMaker (struct open Ethereum_types type input = address * block_param type output = quantity let input_encoding = Data_encoding.tup2 address_encoding block_param_encoding let output_encoding = quantity_encoding let method_ = "eth_getTransactionCount" end) module Get_transaction_receipt = MethodMaker (struct open Ethereum_types type input = hash type output = transaction_receipt let input_encoding = Data_encoding.tup1 hash_encoding let output_encoding = transaction_receipt_encoding let method_ = "eth_getTransactionReceipt" end) module Send_raw_transaction = MethodMaker (struct open Ethereum_types type input = hash type output = hash let input_encoding = Data_encoding.tup1 hash_encoding let output_encoding = hash_encoding let method_ = "eth_sendRawTransaction" end) module Send_transaction = MethodMaker (struct open Ethereum_types type input = transaction type output = hash let input_encoding = transaction_encoding let output_encoding = hash_encoding let method_ = "eth_sendTransaction" end) module Eth_call = MethodMaker (struct open Ethereum_types type input = call * block_param type output = hash let input_encoding = Data_encoding.tup2 call_encoding block_param_encoding let output_encoding = hash_encoding let method_ = "eth_call" end) module Get_estimate_gas = MethodMaker (struct open Ethereum_types type input = call type output = quantity let input_encoding = Data_encoding.tup1 call_encoding let output_encoding = quantity_encoding let method_ = "eth_estimateGas" end) let methods : (module METHOD) list = [ (module Network_id); (module Chain_id); (module Accounts); (module Get_balance); (module Block_number); (module Get_block_by_number); (module Get_block_by_hash); (module Get_code); (module Gas_price); (module Get_transaction_count); (module Get_transaction_receipt); (module Send_transaction); (module Send_raw_transaction); (module Eth_call); (module Get_estimate_gas); ] module Input = struct type t = input let case_maker tag_id (module M : METHOD) = let open Data_encoding in case ~title:M.method_ (Tag tag_id) M.request_encoding (function M.Input input, id -> Some (M.request input id) | _ -> None) (fun {parameters; id; _} -> (M.Input parameters, id)) let encoding = let open Data_encoding in union @@ List.mapi case_maker methods end module Output = struct type nonrec 'a result = ('a, error JSONRPC.error) result let case_maker tag_id (module M : METHOD) = let open Data_encoding in case ~title:M.method_ (Tag tag_id) M.response_encoding (function | M.Output accounts, id -> Some JSONRPC.{value = accounts; id} | _ -> None) (fun {value = req; id} -> (M.Output req, id)) let encoding = let open Data_encoding in union @@ List.mapi case_maker methods end
b55d4a6627f3d7619f6163cb235a1c14b7c7d4f2620fbf6c6bc94b679eb0794e
ptaoussanis/tufte
hello.cljs
(ns example.hello (:require [taoensso.tufte :as tufte :refer-macros (defnp p profiled profile)])) (tufte/add-basic-println-handler! {}) (defn get-x [] (+ 1 1)) (defn get-y [] (+ 2 2)) (profile ; Profile any `p` forms called during body execution {} ; Profiling options; we'll use the defaults for now (dotimes [_ 5] (p :get-x (get-x)) (p :get-y (get-y))))
null
https://raw.githubusercontent.com/ptaoussanis/tufte/396ca0d5e05db9d9721635ca11bf4e00fb393ab8/examples/cljs/src/example/hello.cljs
clojure
Profile any `p` forms called during body execution Profiling options; we'll use the defaults for now
(ns example.hello (:require [taoensso.tufte :as tufte :refer-macros (defnp p profiled profile)])) (tufte/add-basic-println-handler! {}) (defn get-x [] (+ 1 1)) (defn get-y [] (+ 2 2)) (dotimes [_ 5] (p :get-x (get-x)) (p :get-y (get-y))))
cd304a08cae6c393ca88d0970335e59dfc2ce71979bad667db14db4a07559762
ml4tp/tcoq
nativenorm.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Pp open CErrors open Term open Vars open Environ open Reduction open Univ open Declarations open Names open Inductive open Util open Nativecode open Nativevalues open Context.Rel.Declaration (** This module implements normalization by evaluation to OCaml code *) exception Find_at of int let invert_tag cst tag reloc_tbl = try for j = 0 to Array.length reloc_tbl - 1 do let tagj,arity = reloc_tbl.(j) in if Int.equal tag tagj && (cst && Int.equal arity 0 || not(cst || Int.equal arity 0)) then raise (Find_at j) else () done;raise Not_found with Find_at j -> (j+1) let decompose_prod env t = let (name,dom,codom as res) = destProd (whd_all env t) in match name with | Anonymous -> (Name (id_of_string "x"),dom,codom) | _ -> res let app_type env c = let t = whd_all env c in try destApp t with DestKO -> (t,[||]) let find_rectype_a env c = let (t, l) = app_type env c in match kind_of_term t with | Ind ind -> (ind, l) | _ -> raise Not_found (* Instantiate inductives and parameters in constructor type *) let type_constructor mind mib u typ params = let s = ind_subst mind mib u in let ctyp = substl s typ in let nparams = Array.length params in if Int.equal nparams 0 then ctyp else let _,ctyp = decompose_prod_n nparams ctyp in substl (List.rev (Array.to_list params)) ctyp let construct_of_constr_notnative const env tag (mind, _ as ind) u allargs = let mib,mip = lookup_mind_specif env ind in let nparams = mib.mind_nparams in let params = Array.sub allargs 0 nparams in try if const then let ctyp = type_constructor mind mib u (mip.mind_nf_lc.(0)) params in retroknowledge Retroknowledge.get_vm_decompile_constant_info env (mkInd ind) tag, ctyp else raise Not_found with Not_found -> let i = invert_tag const tag mip.mind_reloc_tbl in let ctyp = type_constructor mind mib u (mip.mind_nf_lc.(i-1)) params in (mkApp(mkConstructU((ind,i),u), params), ctyp) let construct_of_constr const env tag typ = let t, l = app_type env typ in match kind_of_term t with | Ind (ind,u) -> construct_of_constr_notnative const env tag ind u l | _ -> assert false let construct_of_constr_const env tag typ = fst (construct_of_constr true env tag typ) let construct_of_constr_block = construct_of_constr false let build_branches_type env (mind,_ as _ind) mib mip u params dep p = let rtbl = mip.mind_reloc_tbl in (* [build_one_branch i cty] construit le type de la ieme branche (commence a 0) et les lambda correspondant aux realargs *) let build_one_branch i cty = let typi = type_constructor mind mib u cty params in let decl,indapp = Reductionops.splay_prod env Evd.empty typi in let decl_with_letin,_ = decompose_prod_assum typi in let ind,cargs = find_rectype_a env indapp in let nparams = Array.length params in let carity = snd (rtbl.(i)) in let crealargs = Array.sub cargs nparams (Array.length cargs - nparams) in let codom = let ndecl = List.length decl in let papp = mkApp(lift ndecl p,crealargs) in if dep then let cstr = ith_constructor_of_inductive (fst ind) (i+1) in let relargs = Array.init carity (fun i -> mkRel (carity-i)) in let params = Array.map (lift ndecl) params in let dep_cstr = mkApp(mkApp(mkConstructU (cstr,snd ind),params),relargs) in mkApp(papp,[|dep_cstr|]) else papp in decl, decl_with_letin, codom in Array.mapi build_one_branch mip.mind_nf_lc let build_case_type dep p realargs c = if dep then mkApp(mkApp(p, realargs), [|c|]) else mkApp(p, realargs) TODO move this function let type_of_rel env n = lookup_rel n env |> get_type |> lift n let type_of_prop = mkSort type1_sort let type_of_sort s = match s with | Prop _ -> type_of_prop | Type u -> mkType (Univ.super u) let type_of_var env id = let open Context.Named.Declaration in try lookup_named id env |> get_type with Not_found -> anomaly ~label:"type_of_var" (str "variable " ++ Id.print id ++ str " unbound") let sort_of_product env domsort rangsort = match (domsort, rangsort) with Product rule ( s , Prop , Prop ) | (_, Prop Null) -> rangsort Product rule ( Prop / Set , Set , Set ) | (Prop _, Prop Pos) -> rangsort (* Product rule (Type,Set,?) *) | (Type u1, Prop Pos) -> if is_impredicative_set env then (* Rule is (Type,Set,Set) in the Set-impredicative calculus *) rangsort else (* Rule is (Type_i,Set,Type_i) in the Set-predicative calculus *) Type (sup u1 type0_univ) (* Product rule (Prop,Type_i,Type_i) *) | (Prop Pos, Type u2) -> Type (sup type0_univ u2) (* Product rule (Prop,Type_i,Type_i) *) | (Prop Null, Type _) -> rangsort Product rule ( Type_i , Type_i , Type_i ) | (Type u1, Type u2) -> Type (sup u1 u2) (* normalisation of values *) let branch_of_switch lvl ans bs = let tbl = ans.asw_reloc in let branch i = let tag,arity = tbl.(i) in let ci = if Int.equal arity 0 then mk_const tag else mk_block tag (mk_rels_accu lvl arity) in bs ci in Array.init (Array.length tbl) branch let rec nf_val env v typ = match kind_of_value v with | Vaccu accu -> nf_accu env accu | Vfun f -> let lvl = nb_rel env in let name,dom,codom = try decompose_prod env typ with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let env = push_rel (LocalAssum (name,dom)) env in let body = nf_val env (f (mk_rel_accu lvl)) codom in mkLambda(name,dom,body) | Vconst n -> construct_of_constr_const env n typ | Vblock b -> let capp,ctyp = construct_of_constr_block env (block_tag b) typ in let args = nf_bargs env b ctyp in mkApp(capp,args) and nf_type env v = match kind_of_value v with | Vaccu accu -> nf_accu env accu | _ -> assert false and nf_type_sort env v = match kind_of_value v with | Vaccu accu -> let t,s = nf_accu_type env accu in let s = try destSort s with DestKO -> assert false in t, s | _ -> assert false and nf_accu env accu = let atom = atom_of_accu accu in if Int.equal (accu_nargs accu) 0 then nf_atom env atom else let a,typ = nf_atom_type env atom in let _, args = nf_args env accu typ in mkApp(a,Array.of_list args) and nf_accu_type env accu = let atom = atom_of_accu accu in if Int.equal (accu_nargs accu) 0 then nf_atom_type env atom else let a,typ = nf_atom_type env atom in let t, args = nf_args env accu typ in mkApp(a,Array.of_list args), t and nf_args env accu t = let aux arg (t,l) = let _,dom,codom = try decompose_prod env t with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let c = nf_val env arg dom in (subst1 c codom, c::l) in let t,l = List.fold_right aux (args_of_accu accu) (t,[]) in t, List.rev l and nf_bargs env b t = let t = ref t in let len = block_size b in Array.init len (fun i -> let _,dom,codom = try decompose_prod env !t with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let c = nf_val env (block_field b i) dom in t := subst1 c codom; c) and nf_atom env atom = match atom with | Arel i -> mkRel (nb_rel env - i) | Aconstant cst -> mkConstU cst | Aind ind -> mkIndU ind | Asort s -> mkSort s | Avar id -> mkVar id | Aprod(n,dom,codom) -> let dom = nf_type env dom in let vn = mk_rel_accu (nb_rel env) in let env = push_rel (LocalAssum (n,dom)) env in let codom = nf_type env (codom vn) in mkProd(n,dom,codom) | Ameta (mv,_) -> mkMeta mv | Aevar (ev,_) -> mkEvar ev | Aproj(p,c) -> let c = nf_accu env c in mkProj(Projection.make p true,c) | _ -> fst (nf_atom_type env atom) and nf_atom_type env atom = match atom with | Arel i -> let n = (nb_rel env - i) in mkRel n, type_of_rel env n | Aconstant cst -> mkConstU cst, Typeops.type_of_constant_in env cst | Aind ind -> mkIndU ind, Inductiveops.type_of_inductive env ind | Asort s -> mkSort s, type_of_sort s | Avar id -> mkVar id, type_of_var env id | Acase(ans,accu,p,bs) -> let a,ta = nf_accu_type env accu in let ((mind,_),u as ind),allargs = find_rectype_a env ta in let (mib,mip) = Inductive.lookup_mind_specif env (fst ind) in let nparams = mib.mind_nparams in let params,realargs = Array.chop nparams allargs in let pT = hnf_prod_applist env (Inductiveops.type_of_inductive env ind) (Array.to_list params) in let pT = whd_all env pT in let dep, p = nf_predicate env ind mip params p pT in (* Calcul du type des branches *) let btypes = build_branches_type env (fst ind) mib mip u params dep p in (* calcul des branches *) let bsw = branch_of_switch (nb_rel env) ans bs in let mkbranch i v = let decl,decl_with_letin,codom = btypes.(i) in let b = nf_val (Termops.push_rels_assum decl env) v codom in Termops.it_mkLambda_or_LetIn_from_no_LetIn b decl_with_letin in let branchs = Array.mapi mkbranch bsw in let tcase = build_case_type dep p realargs a in let ci = ans.asw_ci in mkCase(ci, p, a, branchs), tcase | Afix(tt,ft,rp,s) -> let tt = Array.map (fun t -> nf_type env t) tt in let name = Array.map (fun _ -> (Name (id_of_string "Ffix"))) tt in let lvl = nb_rel env in let nbfix = Array.length ft in let fargs = mk_rels_accu lvl (Array.length ft) in Third argument of the tuple is ignored by push_rec_types let env = push_rec_types (name,tt,[||]) env in (* We lift here because the types of arguments (in tt) will be evaluated in an environment where the fixpoints have been pushed *) let norm_body i v = nf_val env (napply v fargs) (lift nbfix tt.(i)) in let ft = Array.mapi norm_body ft in mkFix((rp,s),(name,tt,ft)), tt.(s) | Acofix(tt,ft,s,_) | Acofixe(tt,ft,s,_) -> let tt = Array.map (nf_type env) tt in let name = Array.map (fun _ -> (Name (id_of_string "Fcofix"))) tt in let lvl = nb_rel env in let fargs = mk_rels_accu lvl (Array.length ft) in let env = push_rec_types (name,tt,[||]) env in let ft = Array.mapi (fun i v -> nf_val env (napply v fargs) tt.(i)) ft in mkCoFix(s,(name,tt,ft)), tt.(s) | Aprod(n,dom,codom) -> let dom,s1 = nf_type_sort env dom in let vn = mk_rel_accu (nb_rel env) in let env = push_rel (LocalAssum (n,dom)) env in let codom,s2 = nf_type_sort env (codom vn) in mkProd(n,dom,codom), mkSort (sort_of_product env s1 s2) | Aevar(ev,ty) -> let ty = nf_type env ty in mkEvar ev, ty | Ameta(mv,ty) -> let ty = nf_type env ty in mkMeta mv, ty | Aproj(p,c) -> let c,tc = nf_accu_type env c in let cj = make_judge c tc in let uj = Typeops.judge_of_projection env (Projection.make p true) cj in uj.uj_val, uj.uj_type and nf_predicate env ind mip params v pT = match kind_of_value v, kind_of_term pT with | Vfun f, Prod _ -> let k = nb_rel env in let vb = f (mk_rel_accu k) in let name,dom,codom = try decompose_prod env pT with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let dep,body = nf_predicate (push_rel (LocalAssum (name,dom)) env) ind mip params vb codom in dep, mkLambda(name,dom,body) | Vfun f, _ -> let k = nb_rel env in let vb = f (mk_rel_accu k) in let name = Name (id_of_string "c") in let n = mip.mind_nrealargs in let rargs = Array.init n (fun i -> mkRel (n-i)) in let params = if Int.equal n 0 then params else Array.map (lift n) params in let dom = mkApp(mkIndU ind,Array.append params rargs) in let body = nf_type (push_rel (LocalAssum (name,dom)) env) vb in true, mkLambda(name,dom,body) | _, _ -> false, nf_type env v let evars_of_evar_map sigma = { Nativelambda.evars_val = Evd.existential_opt_value sigma; Nativelambda.evars_typ = Evd.existential_type sigma; Nativelambda.evars_metas = Evd.meta_type sigma } let native_norm env sigma c ty = if Coq_config.no_native_compiler then error "Native_compute reduction has been disabled at configure time." else let penv = Environ.pre_env env in let sigma = evars_of_evar_map sigma in Format.eprintf " Numbers of free variables ( named ): % i\n " ( ) ; Format.eprintf " Numbers of free variables ( rel ): % i\n " ( vl2 ) ; Format.eprintf "Numbers of free variables (named): %i\n" (List.length vl1); Format.eprintf "Numbers of free variables (rel): %i\n" (List.length vl2); *) let ml_filename, prefix = Nativelib.get_ml_filename () in let code, upd = mk_norm_code penv sigma prefix c in match Nativelib.compile ml_filename code with | true, fn -> if !Flags.debug then Feedback.msg_debug (Pp.str "Running norm ..."); let t0 = Sys.time () in Nativelib.call_linker ~fatal:true prefix fn (Some upd); let t1 = Sys.time () in let time_info = Format.sprintf "Evaluation done in %.5f@." (t1 -. t0) in if !Flags.debug then Feedback.msg_debug (Pp.str time_info); let res = nf_val env !Nativelib.rt1 ty in let t2 = Sys.time () in let time_info = Format.sprintf "Reification done in %.5f@." (t2 -. t1) in if !Flags.debug then Feedback.msg_debug (Pp.str time_info); res | _ -> anomaly (Pp.str "Compilation failure") let native_conv_generic pb sigma t = Nativeconv.native_conv_gen pb (evars_of_evar_map sigma) t let native_infer_conv ?(pb=Reduction.CUMUL) env sigma t1 t2 = Reductionops.infer_conv_gen (fun pb ~l2r sigma ts -> native_conv_generic pb sigma) ~catch_incon:true ~pb env sigma t1 t2
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/pretyping/nativenorm.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * This module implements normalization by evaluation to OCaml code Instantiate inductives and parameters in constructor type [build_one_branch i cty] construit le type de la ieme branche (commence a 0) et les lambda correspondant aux realargs Product rule (Type,Set,?) Rule is (Type,Set,Set) in the Set-impredicative calculus Rule is (Type_i,Set,Type_i) in the Set-predicative calculus Product rule (Prop,Type_i,Type_i) Product rule (Prop,Type_i,Type_i) normalisation of values Calcul du type des branches calcul des branches We lift here because the types of arguments (in tt) will be evaluated in an environment where the fixpoints have been pushed
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open CErrors open Term open Vars open Environ open Reduction open Univ open Declarations open Names open Inductive open Util open Nativecode open Nativevalues open Context.Rel.Declaration exception Find_at of int let invert_tag cst tag reloc_tbl = try for j = 0 to Array.length reloc_tbl - 1 do let tagj,arity = reloc_tbl.(j) in if Int.equal tag tagj && (cst && Int.equal arity 0 || not(cst || Int.equal arity 0)) then raise (Find_at j) else () done;raise Not_found with Find_at j -> (j+1) let decompose_prod env t = let (name,dom,codom as res) = destProd (whd_all env t) in match name with | Anonymous -> (Name (id_of_string "x"),dom,codom) | _ -> res let app_type env c = let t = whd_all env c in try destApp t with DestKO -> (t,[||]) let find_rectype_a env c = let (t, l) = app_type env c in match kind_of_term t with | Ind ind -> (ind, l) | _ -> raise Not_found let type_constructor mind mib u typ params = let s = ind_subst mind mib u in let ctyp = substl s typ in let nparams = Array.length params in if Int.equal nparams 0 then ctyp else let _,ctyp = decompose_prod_n nparams ctyp in substl (List.rev (Array.to_list params)) ctyp let construct_of_constr_notnative const env tag (mind, _ as ind) u allargs = let mib,mip = lookup_mind_specif env ind in let nparams = mib.mind_nparams in let params = Array.sub allargs 0 nparams in try if const then let ctyp = type_constructor mind mib u (mip.mind_nf_lc.(0)) params in retroknowledge Retroknowledge.get_vm_decompile_constant_info env (mkInd ind) tag, ctyp else raise Not_found with Not_found -> let i = invert_tag const tag mip.mind_reloc_tbl in let ctyp = type_constructor mind mib u (mip.mind_nf_lc.(i-1)) params in (mkApp(mkConstructU((ind,i),u), params), ctyp) let construct_of_constr const env tag typ = let t, l = app_type env typ in match kind_of_term t with | Ind (ind,u) -> construct_of_constr_notnative const env tag ind u l | _ -> assert false let construct_of_constr_const env tag typ = fst (construct_of_constr true env tag typ) let construct_of_constr_block = construct_of_constr false let build_branches_type env (mind,_ as _ind) mib mip u params dep p = let rtbl = mip.mind_reloc_tbl in let build_one_branch i cty = let typi = type_constructor mind mib u cty params in let decl,indapp = Reductionops.splay_prod env Evd.empty typi in let decl_with_letin,_ = decompose_prod_assum typi in let ind,cargs = find_rectype_a env indapp in let nparams = Array.length params in let carity = snd (rtbl.(i)) in let crealargs = Array.sub cargs nparams (Array.length cargs - nparams) in let codom = let ndecl = List.length decl in let papp = mkApp(lift ndecl p,crealargs) in if dep then let cstr = ith_constructor_of_inductive (fst ind) (i+1) in let relargs = Array.init carity (fun i -> mkRel (carity-i)) in let params = Array.map (lift ndecl) params in let dep_cstr = mkApp(mkApp(mkConstructU (cstr,snd ind),params),relargs) in mkApp(papp,[|dep_cstr|]) else papp in decl, decl_with_letin, codom in Array.mapi build_one_branch mip.mind_nf_lc let build_case_type dep p realargs c = if dep then mkApp(mkApp(p, realargs), [|c|]) else mkApp(p, realargs) TODO move this function let type_of_rel env n = lookup_rel n env |> get_type |> lift n let type_of_prop = mkSort type1_sort let type_of_sort s = match s with | Prop _ -> type_of_prop | Type u -> mkType (Univ.super u) let type_of_var env id = let open Context.Named.Declaration in try lookup_named id env |> get_type with Not_found -> anomaly ~label:"type_of_var" (str "variable " ++ Id.print id ++ str " unbound") let sort_of_product env domsort rangsort = match (domsort, rangsort) with Product rule ( s , Prop , Prop ) | (_, Prop Null) -> rangsort Product rule ( Prop / Set , Set , Set ) | (Prop _, Prop Pos) -> rangsort | (Type u1, Prop Pos) -> if is_impredicative_set env then rangsort else Type (sup u1 type0_univ) | (Prop Pos, Type u2) -> Type (sup type0_univ u2) | (Prop Null, Type _) -> rangsort Product rule ( Type_i , Type_i , Type_i ) | (Type u1, Type u2) -> Type (sup u1 u2) let branch_of_switch lvl ans bs = let tbl = ans.asw_reloc in let branch i = let tag,arity = tbl.(i) in let ci = if Int.equal arity 0 then mk_const tag else mk_block tag (mk_rels_accu lvl arity) in bs ci in Array.init (Array.length tbl) branch let rec nf_val env v typ = match kind_of_value v with | Vaccu accu -> nf_accu env accu | Vfun f -> let lvl = nb_rel env in let name,dom,codom = try decompose_prod env typ with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let env = push_rel (LocalAssum (name,dom)) env in let body = nf_val env (f (mk_rel_accu lvl)) codom in mkLambda(name,dom,body) | Vconst n -> construct_of_constr_const env n typ | Vblock b -> let capp,ctyp = construct_of_constr_block env (block_tag b) typ in let args = nf_bargs env b ctyp in mkApp(capp,args) and nf_type env v = match kind_of_value v with | Vaccu accu -> nf_accu env accu | _ -> assert false and nf_type_sort env v = match kind_of_value v with | Vaccu accu -> let t,s = nf_accu_type env accu in let s = try destSort s with DestKO -> assert false in t, s | _ -> assert false and nf_accu env accu = let atom = atom_of_accu accu in if Int.equal (accu_nargs accu) 0 then nf_atom env atom else let a,typ = nf_atom_type env atom in let _, args = nf_args env accu typ in mkApp(a,Array.of_list args) and nf_accu_type env accu = let atom = atom_of_accu accu in if Int.equal (accu_nargs accu) 0 then nf_atom_type env atom else let a,typ = nf_atom_type env atom in let t, args = nf_args env accu typ in mkApp(a,Array.of_list args), t and nf_args env accu t = let aux arg (t,l) = let _,dom,codom = try decompose_prod env t with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let c = nf_val env arg dom in (subst1 c codom, c::l) in let t,l = List.fold_right aux (args_of_accu accu) (t,[]) in t, List.rev l and nf_bargs env b t = let t = ref t in let len = block_size b in Array.init len (fun i -> let _,dom,codom = try decompose_prod env !t with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let c = nf_val env (block_field b i) dom in t := subst1 c codom; c) and nf_atom env atom = match atom with | Arel i -> mkRel (nb_rel env - i) | Aconstant cst -> mkConstU cst | Aind ind -> mkIndU ind | Asort s -> mkSort s | Avar id -> mkVar id | Aprod(n,dom,codom) -> let dom = nf_type env dom in let vn = mk_rel_accu (nb_rel env) in let env = push_rel (LocalAssum (n,dom)) env in let codom = nf_type env (codom vn) in mkProd(n,dom,codom) | Ameta (mv,_) -> mkMeta mv | Aevar (ev,_) -> mkEvar ev | Aproj(p,c) -> let c = nf_accu env c in mkProj(Projection.make p true,c) | _ -> fst (nf_atom_type env atom) and nf_atom_type env atom = match atom with | Arel i -> let n = (nb_rel env - i) in mkRel n, type_of_rel env n | Aconstant cst -> mkConstU cst, Typeops.type_of_constant_in env cst | Aind ind -> mkIndU ind, Inductiveops.type_of_inductive env ind | Asort s -> mkSort s, type_of_sort s | Avar id -> mkVar id, type_of_var env id | Acase(ans,accu,p,bs) -> let a,ta = nf_accu_type env accu in let ((mind,_),u as ind),allargs = find_rectype_a env ta in let (mib,mip) = Inductive.lookup_mind_specif env (fst ind) in let nparams = mib.mind_nparams in let params,realargs = Array.chop nparams allargs in let pT = hnf_prod_applist env (Inductiveops.type_of_inductive env ind) (Array.to_list params) in let pT = whd_all env pT in let dep, p = nf_predicate env ind mip params p pT in let btypes = build_branches_type env (fst ind) mib mip u params dep p in let bsw = branch_of_switch (nb_rel env) ans bs in let mkbranch i v = let decl,decl_with_letin,codom = btypes.(i) in let b = nf_val (Termops.push_rels_assum decl env) v codom in Termops.it_mkLambda_or_LetIn_from_no_LetIn b decl_with_letin in let branchs = Array.mapi mkbranch bsw in let tcase = build_case_type dep p realargs a in let ci = ans.asw_ci in mkCase(ci, p, a, branchs), tcase | Afix(tt,ft,rp,s) -> let tt = Array.map (fun t -> nf_type env t) tt in let name = Array.map (fun _ -> (Name (id_of_string "Ffix"))) tt in let lvl = nb_rel env in let nbfix = Array.length ft in let fargs = mk_rels_accu lvl (Array.length ft) in Third argument of the tuple is ignored by push_rec_types let env = push_rec_types (name,tt,[||]) env in let norm_body i v = nf_val env (napply v fargs) (lift nbfix tt.(i)) in let ft = Array.mapi norm_body ft in mkFix((rp,s),(name,tt,ft)), tt.(s) | Acofix(tt,ft,s,_) | Acofixe(tt,ft,s,_) -> let tt = Array.map (nf_type env) tt in let name = Array.map (fun _ -> (Name (id_of_string "Fcofix"))) tt in let lvl = nb_rel env in let fargs = mk_rels_accu lvl (Array.length ft) in let env = push_rec_types (name,tt,[||]) env in let ft = Array.mapi (fun i v -> nf_val env (napply v fargs) tt.(i)) ft in mkCoFix(s,(name,tt,ft)), tt.(s) | Aprod(n,dom,codom) -> let dom,s1 = nf_type_sort env dom in let vn = mk_rel_accu (nb_rel env) in let env = push_rel (LocalAssum (n,dom)) env in let codom,s2 = nf_type_sort env (codom vn) in mkProd(n,dom,codom), mkSort (sort_of_product env s1 s2) | Aevar(ev,ty) -> let ty = nf_type env ty in mkEvar ev, ty | Ameta(mv,ty) -> let ty = nf_type env ty in mkMeta mv, ty | Aproj(p,c) -> let c,tc = nf_accu_type env c in let cj = make_judge c tc in let uj = Typeops.judge_of_projection env (Projection.make p true) cj in uj.uj_val, uj.uj_type and nf_predicate env ind mip params v pT = match kind_of_value v, kind_of_term pT with | Vfun f, Prod _ -> let k = nb_rel env in let vb = f (mk_rel_accu k) in let name,dom,codom = try decompose_prod env pT with DestKO -> CErrors.anomaly (Pp.strbrk "Returned a functional value in a type not recognized as a product type.") in let dep,body = nf_predicate (push_rel (LocalAssum (name,dom)) env) ind mip params vb codom in dep, mkLambda(name,dom,body) | Vfun f, _ -> let k = nb_rel env in let vb = f (mk_rel_accu k) in let name = Name (id_of_string "c") in let n = mip.mind_nrealargs in let rargs = Array.init n (fun i -> mkRel (n-i)) in let params = if Int.equal n 0 then params else Array.map (lift n) params in let dom = mkApp(mkIndU ind,Array.append params rargs) in let body = nf_type (push_rel (LocalAssum (name,dom)) env) vb in true, mkLambda(name,dom,body) | _, _ -> false, nf_type env v let evars_of_evar_map sigma = { Nativelambda.evars_val = Evd.existential_opt_value sigma; Nativelambda.evars_typ = Evd.existential_type sigma; Nativelambda.evars_metas = Evd.meta_type sigma } let native_norm env sigma c ty = if Coq_config.no_native_compiler then error "Native_compute reduction has been disabled at configure time." else let penv = Environ.pre_env env in let sigma = evars_of_evar_map sigma in Format.eprintf " Numbers of free variables ( named ): % i\n " ( ) ; Format.eprintf " Numbers of free variables ( rel ): % i\n " ( vl2 ) ; Format.eprintf "Numbers of free variables (named): %i\n" (List.length vl1); Format.eprintf "Numbers of free variables (rel): %i\n" (List.length vl2); *) let ml_filename, prefix = Nativelib.get_ml_filename () in let code, upd = mk_norm_code penv sigma prefix c in match Nativelib.compile ml_filename code with | true, fn -> if !Flags.debug then Feedback.msg_debug (Pp.str "Running norm ..."); let t0 = Sys.time () in Nativelib.call_linker ~fatal:true prefix fn (Some upd); let t1 = Sys.time () in let time_info = Format.sprintf "Evaluation done in %.5f@." (t1 -. t0) in if !Flags.debug then Feedback.msg_debug (Pp.str time_info); let res = nf_val env !Nativelib.rt1 ty in let t2 = Sys.time () in let time_info = Format.sprintf "Reification done in %.5f@." (t2 -. t1) in if !Flags.debug then Feedback.msg_debug (Pp.str time_info); res | _ -> anomaly (Pp.str "Compilation failure") let native_conv_generic pb sigma t = Nativeconv.native_conv_gen pb (evars_of_evar_map sigma) t let native_infer_conv ?(pb=Reduction.CUMUL) env sigma t1 t2 = Reductionops.infer_conv_gen (fun pb ~l2r sigma ts -> native_conv_generic pb sigma) ~catch_incon:true ~pb env sigma t1 t2
75f17ac23e4cbd1d45710c5eccc2b84039a307cb78258354189d23b9ec9e469d
MarcKaufmann/congame
info.rkt
#lang info (define collection "studies") (define deps '("base" "component-lib" "congame-core" "forms-lib" "gregor-lib" "koyo-lib" "marionette-lib" "sentry-lib" "web-server-lib")) (define build-deps '()) (define congame-studies '((studies/real-effort/tasks task-study)))
null
https://raw.githubusercontent.com/MarcKaufmann/congame/56b05aa8eb0148ca31dfece96d2f6266aad5e7df/studies/real-effort/info.rkt
racket
#lang info (define collection "studies") (define deps '("base" "component-lib" "congame-core" "forms-lib" "gregor-lib" "koyo-lib" "marionette-lib" "sentry-lib" "web-server-lib")) (define build-deps '()) (define congame-studies '((studies/real-effort/tasks task-study)))
2f8e946506a285af59a3b83fc7406cc22a52a304bf9e377abc448964f4ac7c5b
AbstractMachinesLab/caramel
env.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. *) (* *) (**************************************************************************) (* Environment handling *) open Types type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_extension of summary * Ident.t * extension_constructor | Env_module of summary * Ident.t * module_presence * module_declaration | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * class_type_declaration | Env_open of summary * Path.t (** The string set argument of [Env_open] represents a list of module names to skip, i.e. that won't be imported in the toplevel namespace. *) | Env_functor_arg of summary * Ident.t | Env_constraints of summary * type_declaration Path.Map.t | Env_copy_types of summary * string list | Env_persistent of summary * Ident.t type address = | Aident of Ident.t | Adot of address * int type t val empty: t val initial_safe_string: t val initial_unsafe_string: t val diff: t -> t -> Ident.t list val copy_local: from:t -> t -> t type type_descriptions = constructor_description list * label_description list (* For short-paths *) type iter_cont val iter_types: (Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) -> t -> iter_cont val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list val same_types: t -> t -> bool val used_persistent: unit -> Concr.t val find_shadowed_types: Path.t -> t -> Path.t list val without_cmis: ('a -> 'b) -> 'a -> 'b [ without_cmis f arg ] applies [ f ] to [ arg ] , but does not allow opening cmis during its execution allow opening cmis during its execution *) (* Lookup by paths *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_type_descrs: Path.t -> t -> type_descriptions val find_module: Path.t -> t -> module_declaration val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> class_type_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr * int val find_type_expansion_opt: Path.t -> t -> type_expr list * type_expr * int (* Find the manifest type information associated to a type for the sake of the compiler's type-based optimisations. *) val find_modtype_expansion: Path.t -> t -> module_type val find_value_address: Path.t -> t -> address val find_module_address: Path.t -> t -> address val find_class_address: Path.t -> t -> address val find_constructor_address: Path.t -> t -> address val add_functor_arg: Ident.t -> t -> t val is_functor_arg: Path.t -> t -> bool val normalize_module_path: Location.t option -> t -> Path.t -> Path.t (* Normalize the path to a concrete module. If the option is None, allow returning dangling paths. Otherwise raise a Missing_module error, and may add forgotten head as required global. *) val normalize_type_path: Location.t option -> t -> Path.t -> Path.t (* Normalize the prefix part of the type path *) val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t Normalize the prefix part of other kinds of paths ( value / modtype / etc ) (value/modtype/etc) *) val reset_required_globals: unit -> unit val get_required_globals: unit -> Ident.t list val add_required_global: Ident.t -> unit val has_local_constraints: t -> bool (* Lookup by long identifiers *) ? loc is used to report ' deprecated module ' warnings and other alerts val lookup_value: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * value_description val lookup_constructor: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> constructor_description val lookup_all_constructors: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (constructor_description * (unit -> unit)) list val lookup_label: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> label_description val lookup_all_labels: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (label_description * (unit -> unit)) list val lookup_type: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t Since 4.04 , this function no longer returns [ type_description ] . To obtain it , you should either call [ Env.find_type ] , or replace it by [ Typetexp.find_type ] To obtain it, you should either call [Env.find_type], or replace it by [Typetexp.find_type] *) val lookup_module: load:bool -> ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t val lookup_modtype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * modtype_declaration val lookup_class: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_declaration val lookup_cltype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_type_declaration type copy_of_types val make_copy_of_types: string list -> t -> copy_of_types val do_copy_types: copy_of_types -> t -> t (** [do_copy_types copy env] will raise a fatal error if the values in [env] are different from the env passed to [make_copy_of_types]. *) exception Recmodule Raise by lookup_module when the identifier refers to one of the modules of a recursive definition during the computation of its approximation ( see # 5965 ) . to one of the modules of a recursive definition during the computation of its approximation (see #5965). *) (* Insertion by identifier *) val add_value: ?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t val add_type: check:bool -> Ident.t -> type_declaration -> t -> t val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t val add_module: ?arg:bool -> Ident.t -> module_presence -> module_type -> t -> t val add_module_declaration: ?arg:bool -> check:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> class_type_declaration -> t -> t val add_local_type: Path.t -> type_declaration -> t -> t (* Insertion of persistent signatures *) (* [add_persistent_structure id env] is an environment such that module [id] points to the persistent structure contained in the external compilation unit with the same name. The compilation unit itself is looked up in the load path when the contents of the module is accessed. *) val add_persistent_structure : Ident.t -> t -> t (* Returns the set of persistent structures found in the given directory. *) val persistent_structures_of_dir : Load_path.Dir.t -> Misc.Stdlib.String.Set.t (* [filter_non_loaded_persistent f env] removes all the persistent structures that are not yet loaded and for which [f] returns [false]. *) val filter_non_loaded_persistent : (Ident.t -> bool) -> t -> t (* Insertion of all fields of a signature. *) val add_item: signature_item -> t -> t val add_signature: signature -> t -> t (* Insertion of all fields of a signature, relative to the given path. Used to implement open. Returns None if the path refers to a functor, not a structure. *) val open_signature: ?used_slot:bool ref -> ?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t -> t -> t option val open_pers_signature: string -> t -> t (* Insertion by name *) val enter_value: ?check:(string -> Warnings.t) -> string -> value_description -> t -> Ident.t * t val enter_type: scope:int -> string -> type_declaration -> t -> Ident.t * t val enter_extension: scope:int -> string -> extension_constructor -> t -> Ident.t * t val enter_module: scope:int -> ?arg:bool -> string -> module_presence -> module_type -> t -> Ident.t * t val enter_module_declaration: ?arg:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val enter_modtype: scope:int -> string -> modtype_declaration -> t -> Ident.t * t val enter_class: scope:int -> string -> class_declaration -> t -> Ident.t * t val enter_cltype: scope:int -> string -> class_type_declaration -> t -> Ident.t * t (* Same as [add_signature] but refreshes (new stamp) and rescopes bound idents in the process. *) val enter_signature: scope:int -> signature -> t -> signature * t Initialize the cache of in - core module interfaces . val reset_cache: unit -> unit (* To be called before each toplevel phrase. *) val reset_cache_toplevel: unit -> unit (* Remember the name of the current compilation unit. *) val set_unit_name: string -> unit val get_unit_name: unit -> string (* Read, save a signature to/from a file *) val read_signature: string -> string -> signature (* Arguments: module name, file name. Results: signature. *) val save_signature: alerts:string Misc.Stdlib.String.Map.t -> signature -> string -> string -> Cmi_format.cmi_infos (* Arguments: signature, module name, file name. *) val save_signature_with_imports: alerts:string Misc.Stdlib.String.Map.t -> signature -> string -> string -> (string * Digest.t option) list -> Cmi_format.cmi_infos Arguments : signature , module name , file name , imported units with their CRCs . imported units with their CRCs. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imports: unit -> (string * Digest.t option) list (* [is_imported_opaque md] returns true if [md] is an opaque imported module *) val is_imported_opaque: string -> bool Direct access to the table of imported compilation units with their CRC val crc_units: Consistbl.t val add_import: string -> unit (* Summaries -- compact representation of an environment, to be exported in debugging information. *) val summary: t -> summary Return an equivalent environment where all fields have been reset , except the summary . The initial environment can be rebuilt from the summary , using Envaux.env_of_only_summary . except the summary. The initial environment can be rebuilt from the summary, using Envaux.env_of_only_summary. *) val keep_only_summary : t -> t val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t (* Error report *) type error = | Illegal_renaming of string * string * string | Inconsistent_import of string * string * string | Need_recursive_types of string * string | Depend_on_unsafe_string_unit of string * string | Missing_module of Location.t * Path.t * Path.t | Illegal_value_name of Location.t * string exception Error of error open Format val report_error: formatter -> error -> unit val mark_value_used: string -> value_description -> unit val mark_module_used: string -> Location.t -> unit val mark_type_used: string -> type_declaration -> unit type constructor_usage = Positive | Pattern | Privatize val mark_constructor_used: constructor_usage -> string -> type_declaration -> string -> unit val mark_constructor: constructor_usage -> t -> string -> constructor_description -> unit val mark_extension_used: constructor_usage -> extension_constructor -> string -> unit val in_signature: bool -> t -> t val is_in_signature: t -> bool val set_value_used_callback: string -> value_description -> (unit -> unit) -> unit val set_type_used_callback: string -> type_declaration -> ((unit -> unit) -> unit) -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref Forward declaration to break mutual recursion with . val check_well_formed_module: (t -> Location.t -> string -> module_type -> unit) ref Forward declaration to break mutual recursion with . val add_delayed_check_forward: ((unit -> unit) -> unit) ref Forward declaration to break mutual recursion with Mtype . val strengthen: (aliasable:bool -> t -> module_type -> Path.t -> module_type) ref Forward declaration to break mutual recursion with Ctype . val same_constr: (t -> type_expr -> type_expr -> bool) ref (** Folding over all identifiers (for analysis purpose) *) val fold_values: (string -> Path.t -> value_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_types: (string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_constructors: (constructor_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_labels: (label_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a (** Persistent structures are only traversed if they are already loaded. *) val fold_modules: (string -> Path.t -> module_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modtypes: (string -> Path.t -> modtype_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_classes: (string -> Path.t -> class_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_cltypes: (string -> Path.t -> class_type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a (** Utilities *) val scrape_alias: t -> module_type -> module_type val check_value_name: string -> Location.t -> unit val print_address : Format.formatter -> address -> unit module Persistent_signature : sig type t = { filename : string; (** Name of the file containing the signature. *) cmi : Cmi_format.cmi_infos } * Function used to load a persistent signature . The default is to look for the file in the load path . This function can be overridden to load it from memory , for instance to build a self - contained toplevel . the .cmi file in the load path. This function can be overridden to load it from memory, for instance to build a self-contained toplevel. *) val load : (unit_name:string -> t option) ref end
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/upstream/ocaml_408/typing/env.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. ************************************************************************ Environment handling * The string set argument of [Env_open] represents a list of module names to skip, i.e. that won't be imported in the toplevel namespace. For short-paths Lookup by paths Find the manifest type information associated to a type for the sake of the compiler's type-based optimisations. Normalize the path to a concrete module. If the option is None, allow returning dangling paths. Otherwise raise a Missing_module error, and may add forgotten head as required global. Normalize the prefix part of the type path Lookup by long identifiers * [do_copy_types copy env] will raise a fatal error if the values in [env] are different from the env passed to [make_copy_of_types]. Insertion by identifier Insertion of persistent signatures [add_persistent_structure id env] is an environment such that module [id] points to the persistent structure contained in the external compilation unit with the same name. The compilation unit itself is looked up in the load path when the contents of the module is accessed. Returns the set of persistent structures found in the given directory. [filter_non_loaded_persistent f env] removes all the persistent structures that are not yet loaded and for which [f] returns [false]. Insertion of all fields of a signature. Insertion of all fields of a signature, relative to the given path. Used to implement open. Returns None if the path refers to a functor, not a structure. Insertion by name Same as [add_signature] but refreshes (new stamp) and rescopes bound idents in the process. To be called before each toplevel phrase. Remember the name of the current compilation unit. Read, save a signature to/from a file Arguments: module name, file name. Results: signature. Arguments: signature, module name, file name. [is_imported_opaque md] returns true if [md] is an opaque imported module Summaries -- compact representation of an environment, to be exported in debugging information. Error report * Folding over all identifiers (for analysis purpose) * Persistent structures are only traversed if they are already loaded. * Utilities * Name of the file containing the signature.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Types type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_extension of summary * Ident.t * extension_constructor | Env_module of summary * Ident.t * module_presence * module_declaration | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * class_type_declaration | Env_open of summary * Path.t | Env_functor_arg of summary * Ident.t | Env_constraints of summary * type_declaration Path.Map.t | Env_copy_types of summary * string list | Env_persistent of summary * Ident.t type address = | Aident of Ident.t | Adot of address * int type t val empty: t val initial_safe_string: t val initial_unsafe_string: t val diff: t -> t -> Ident.t list val copy_local: from:t -> t -> t type type_descriptions = constructor_description list * label_description list type iter_cont val iter_types: (Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) -> t -> iter_cont val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list val same_types: t -> t -> bool val used_persistent: unit -> Concr.t val find_shadowed_types: Path.t -> t -> Path.t list val without_cmis: ('a -> 'b) -> 'a -> 'b [ without_cmis f arg ] applies [ f ] to [ arg ] , but does not allow opening cmis during its execution allow opening cmis during its execution *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_type_descrs: Path.t -> t -> type_descriptions val find_module: Path.t -> t -> module_declaration val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> class_type_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr * int val find_type_expansion_opt: Path.t -> t -> type_expr list * type_expr * int val find_modtype_expansion: Path.t -> t -> module_type val find_value_address: Path.t -> t -> address val find_module_address: Path.t -> t -> address val find_class_address: Path.t -> t -> address val find_constructor_address: Path.t -> t -> address val add_functor_arg: Ident.t -> t -> t val is_functor_arg: Path.t -> t -> bool val normalize_module_path: Location.t option -> t -> Path.t -> Path.t val normalize_type_path: Location.t option -> t -> Path.t -> Path.t val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t Normalize the prefix part of other kinds of paths ( value / modtype / etc ) (value/modtype/etc) *) val reset_required_globals: unit -> unit val get_required_globals: unit -> Ident.t list val add_required_global: Ident.t -> unit val has_local_constraints: t -> bool ? loc is used to report ' deprecated module ' warnings and other alerts val lookup_value: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * value_description val lookup_constructor: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> constructor_description val lookup_all_constructors: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (constructor_description * (unit -> unit)) list val lookup_label: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> label_description val lookup_all_labels: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (label_description * (unit -> unit)) list val lookup_type: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t Since 4.04 , this function no longer returns [ type_description ] . To obtain it , you should either call [ Env.find_type ] , or replace it by [ Typetexp.find_type ] To obtain it, you should either call [Env.find_type], or replace it by [Typetexp.find_type] *) val lookup_module: load:bool -> ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t val lookup_modtype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * modtype_declaration val lookup_class: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_declaration val lookup_cltype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_type_declaration type copy_of_types val make_copy_of_types: string list -> t -> copy_of_types val do_copy_types: copy_of_types -> t -> t exception Recmodule Raise by lookup_module when the identifier refers to one of the modules of a recursive definition during the computation of its approximation ( see # 5965 ) . to one of the modules of a recursive definition during the computation of its approximation (see #5965). *) val add_value: ?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t val add_type: check:bool -> Ident.t -> type_declaration -> t -> t val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t val add_module: ?arg:bool -> Ident.t -> module_presence -> module_type -> t -> t val add_module_declaration: ?arg:bool -> check:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> class_type_declaration -> t -> t val add_local_type: Path.t -> type_declaration -> t -> t val add_persistent_structure : Ident.t -> t -> t val persistent_structures_of_dir : Load_path.Dir.t -> Misc.Stdlib.String.Set.t val filter_non_loaded_persistent : (Ident.t -> bool) -> t -> t val add_item: signature_item -> t -> t val add_signature: signature -> t -> t val open_signature: ?used_slot:bool ref -> ?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t -> t -> t option val open_pers_signature: string -> t -> t val enter_value: ?check:(string -> Warnings.t) -> string -> value_description -> t -> Ident.t * t val enter_type: scope:int -> string -> type_declaration -> t -> Ident.t * t val enter_extension: scope:int -> string -> extension_constructor -> t -> Ident.t * t val enter_module: scope:int -> ?arg:bool -> string -> module_presence -> module_type -> t -> Ident.t * t val enter_module_declaration: ?arg:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val enter_modtype: scope:int -> string -> modtype_declaration -> t -> Ident.t * t val enter_class: scope:int -> string -> class_declaration -> t -> Ident.t * t val enter_cltype: scope:int -> string -> class_type_declaration -> t -> Ident.t * t val enter_signature: scope:int -> signature -> t -> signature * t Initialize the cache of in - core module interfaces . val reset_cache: unit -> unit val reset_cache_toplevel: unit -> unit val set_unit_name: string -> unit val get_unit_name: unit -> string val read_signature: string -> string -> signature val save_signature: alerts:string Misc.Stdlib.String.Map.t -> signature -> string -> string -> Cmi_format.cmi_infos val save_signature_with_imports: alerts:string Misc.Stdlib.String.Map.t -> signature -> string -> string -> (string * Digest.t option) list -> Cmi_format.cmi_infos Arguments : signature , module name , file name , imported units with their CRCs . imported units with their CRCs. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imports: unit -> (string * Digest.t option) list val is_imported_opaque: string -> bool Direct access to the table of imported compilation units with their CRC val crc_units: Consistbl.t val add_import: string -> unit val summary: t -> summary Return an equivalent environment where all fields have been reset , except the summary . The initial environment can be rebuilt from the summary , using Envaux.env_of_only_summary . except the summary. The initial environment can be rebuilt from the summary, using Envaux.env_of_only_summary. *) val keep_only_summary : t -> t val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t type error = | Illegal_renaming of string * string * string | Inconsistent_import of string * string * string | Need_recursive_types of string * string | Depend_on_unsafe_string_unit of string * string | Missing_module of Location.t * Path.t * Path.t | Illegal_value_name of Location.t * string exception Error of error open Format val report_error: formatter -> error -> unit val mark_value_used: string -> value_description -> unit val mark_module_used: string -> Location.t -> unit val mark_type_used: string -> type_declaration -> unit type constructor_usage = Positive | Pattern | Privatize val mark_constructor_used: constructor_usage -> string -> type_declaration -> string -> unit val mark_constructor: constructor_usage -> t -> string -> constructor_description -> unit val mark_extension_used: constructor_usage -> extension_constructor -> string -> unit val in_signature: bool -> t -> t val is_in_signature: t -> bool val set_value_used_callback: string -> value_description -> (unit -> unit) -> unit val set_type_used_callback: string -> type_declaration -> ((unit -> unit) -> unit) -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref Forward declaration to break mutual recursion with . val check_well_formed_module: (t -> Location.t -> string -> module_type -> unit) ref Forward declaration to break mutual recursion with . val add_delayed_check_forward: ((unit -> unit) -> unit) ref Forward declaration to break mutual recursion with Mtype . val strengthen: (aliasable:bool -> t -> module_type -> Path.t -> module_type) ref Forward declaration to break mutual recursion with Ctype . val same_constr: (t -> type_expr -> type_expr -> bool) ref val fold_values: (string -> Path.t -> value_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_types: (string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_constructors: (constructor_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_labels: (label_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modules: (string -> Path.t -> module_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modtypes: (string -> Path.t -> modtype_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_classes: (string -> Path.t -> class_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_cltypes: (string -> Path.t -> class_type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val scrape_alias: t -> module_type -> module_type val check_value_name: string -> Location.t -> unit val print_address : Format.formatter -> address -> unit module Persistent_signature : sig type t = cmi : Cmi_format.cmi_infos } * Function used to load a persistent signature . The default is to look for the file in the load path . This function can be overridden to load it from memory , for instance to build a self - contained toplevel . the .cmi file in the load path. This function can be overridden to load it from memory, for instance to build a self-contained toplevel. *) val load : (unit_name:string -> t option) ref end
136e4a39e69704a62d4793fa183f27ea5d119743b14c72218c17fbf6e8263d38
hypirion/clj-conduit
conduit_test.clj
(ns com.hypirion.conduit-test (:require [clojure.test :refer :all] [com.hypirion.conduit :refer :all]) (:refer-clojure :exclude [await])) (defn- taking "Transducer version of take, implemented via conduit." [n] (conduit (dotimes [_ n] (yield (await))))) (defn- dropping "Transducer version of drop, implemented via conduit." [n] (conduit (dotimes [_ n] (await)) (while true (yield (await))))) (def ^:private catting "cat implemented via conduit." (conduit (while true (doseq [val (await)] (yield val))))) (defn- partitioning-by "Transducer version of partition-by, implemented via conduit." [f] (conduit (let [first-val (await)] (loop [vs [first-val] to-cmp (f first-val)] (if-let-await! v (let [new-to-cmp (f v)] (if (= to-cmp new-to-cmp) (recur (conj vs v) to-cmp) (do (yield vs) (recur [v] new-to-cmp)))) ;; no more values, so flush out vs and exit (yield vs)))))) (defn- partitioning "Transducer version of partition, implemented via conduit. Presumably not that efficient." ([n] (partitioning n n)) ([n step] (conduit (loop [acc []] (let [chunk (loop [acc' acc] (if (= (count acc') n) acc' (recur (conj acc' (await)))))] (yield chunk) (recur (vec (drop step chunk)))))))) This one is slightly scary : ( take 10 ( sequence natural - numbers [ ] ) ) diverges , ;; which _makes sense_ but may be slightly surprising. (sequence (comp natural - numbers ( take 10 ) ) [ ] ) works as intended though . (def natural-numbers (conduit (loop [n 0] (yield n) (recur (inc' n))))) (deftest conduit-test (testing "basic usage" (is (= (reduce + (take 10 (range))) (transduce (taking 10) + (range)))) (is (= (reduce + (drop 10 (range 100))) (transduce (dropping 10) + (range 100)))) (is (= (partition 2 1 (range 10)) (sequence (partitioning 2 1) (range 10))))) (testing "short circuiting on infinities" (is (= (range 10) (sequence (taking 10) (range)))) (is (= (range 10) (sequence (comp natural-numbers (taking 10)) nil))) (is (= (range 10 20) (sequence (comp (dropping 10) (taking 10)) (range))))) (testing "composition" (is (= (take 10 (partition 2 1 (range))) (sequence (comp (partitioning 2 1) (taking 10)) (range)))) (is (= (sequence (comp (partitioning 2 1) cat) (range 10)) [0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9]))) (testing "completion" (is (= (sequence (partitioning-by identity) [0 1 1 2 2 3 4 3 3]) [[0] [1 1] [2 2] [3] [4] [3 3]])) (is (= (sequence (partitioning-by identity) []) []))))
null
https://raw.githubusercontent.com/hypirion/clj-conduit/a9278713542a8de6db096421e569cd3b72916415/test/com/hypirion/conduit_test.clj
clojure
no more values, so flush out vs and exit which _makes sense_ but may be slightly surprising. (sequence (comp
(ns com.hypirion.conduit-test (:require [clojure.test :refer :all] [com.hypirion.conduit :refer :all]) (:refer-clojure :exclude [await])) (defn- taking "Transducer version of take, implemented via conduit." [n] (conduit (dotimes [_ n] (yield (await))))) (defn- dropping "Transducer version of drop, implemented via conduit." [n] (conduit (dotimes [_ n] (await)) (while true (yield (await))))) (def ^:private catting "cat implemented via conduit." (conduit (while true (doseq [val (await)] (yield val))))) (defn- partitioning-by "Transducer version of partition-by, implemented via conduit." [f] (conduit (let [first-val (await)] (loop [vs [first-val] to-cmp (f first-val)] (if-let-await! v (let [new-to-cmp (f v)] (if (= to-cmp new-to-cmp) (recur (conj vs v) to-cmp) (do (yield vs) (recur [v] new-to-cmp)))) (yield vs)))))) (defn- partitioning "Transducer version of partition, implemented via conduit. Presumably not that efficient." ([n] (partitioning n n)) ([n step] (conduit (loop [acc []] (let [chunk (loop [acc' acc] (if (= (count acc') n) acc' (recur (conj acc' (await)))))] (yield chunk) (recur (vec (drop step chunk)))))))) This one is slightly scary : ( take 10 ( sequence natural - numbers [ ] ) ) diverges , natural - numbers ( take 10 ) ) [ ] ) works as intended though . (def natural-numbers (conduit (loop [n 0] (yield n) (recur (inc' n))))) (deftest conduit-test (testing "basic usage" (is (= (reduce + (take 10 (range))) (transduce (taking 10) + (range)))) (is (= (reduce + (drop 10 (range 100))) (transduce (dropping 10) + (range 100)))) (is (= (partition 2 1 (range 10)) (sequence (partitioning 2 1) (range 10))))) (testing "short circuiting on infinities" (is (= (range 10) (sequence (taking 10) (range)))) (is (= (range 10) (sequence (comp natural-numbers (taking 10)) nil))) (is (= (range 10 20) (sequence (comp (dropping 10) (taking 10)) (range))))) (testing "composition" (is (= (take 10 (partition 2 1 (range))) (sequence (comp (partitioning 2 1) (taking 10)) (range)))) (is (= (sequence (comp (partitioning 2 1) cat) (range 10)) [0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9]))) (testing "completion" (is (= (sequence (partitioning-by identity) [0 1 1 2 2 3 4 3 3]) [[0] [1 1] [2 2] [3] [4] [3 3]])) (is (= (sequence (partitioning-by identity) []) []))))
59a9170f7033ba602ca71301896e11033bb015eebd500981eaa5c3f54fef4d17
VictorNicollet/Ohm
action_Request.ml
Ohm is © 2012 open Util open BatPervasives open Action_Common class type ['server,'args] request = object method self : ('server,'args) Action_Endpoint.endpoint method server : 'server method path : string method post : [ `JSON of Json.t | `POST of (string,string) BatMap.t ] option method get : string -> string option method args : 'args method cookie : string -> string option end class ['server,'args] nilreq (server:'server) (args:'args) = object method self (_:'server) (_:'args) = "" val server = server method server = server val args = args method args = args method path = "" method get (_:string) = (None : string option) method cookie (_:string) = (None : string option) method post = (None : [ `JSON of Json_type.t | `POST of (string,string) BatMap.t ] option) end class ['server,'args] fcgi_request (endpoint:('server,'args) Action_Endpoint.endpoint) (server:'server) (args:'args) (cgi:Netcgi.cgi) = let env = cgi # environment in let post : [ `JSON of Json_type.t | `POST of (string,string) BatMap.t ] option Lazy.t = lazy begin if cgi # request_method = `POST then if BatString.starts_with (env # input_content_type_string) "application/json" then Some (`JSON (try let field = (cgi # argument "BODY") # value in match utf8 field with | Some field -> Json.unserialize field | None -> Json.Null with _ -> Json.Null)) else Some (`POST (List.fold_left begin fun acc arg -> try match utf8 (arg # name), utf8 (arg # value) with | Some name, Some value -> BatMap.add name value acc | _ -> acc with _ -> acc end BatMap.empty (cgi # arguments))) else None end in let path = lazy (path_clean (env # cgi_script_name)) in object val path = path val args = args val server = server val post = post val self = endpoint method self = self method args = args method server = server method path = Lazy.force path method post = Lazy.force post method get field = try let field = ((cgi # argument field) # value) in utf8 field with Not_found -> None method cookie name = try let cookie = env # cookie name in let value = Netcgi.Cookie.value cookie in utf8 value with Not_found -> None end
null
https://raw.githubusercontent.com/VictorNicollet/Ohm/ca90c162f6c49927c893114491f29d44aaf71feb/src/action_Request.ml
ocaml
Ohm is © 2012 open Util open BatPervasives open Action_Common class type ['server,'args] request = object method self : ('server,'args) Action_Endpoint.endpoint method server : 'server method path : string method post : [ `JSON of Json.t | `POST of (string,string) BatMap.t ] option method get : string -> string option method args : 'args method cookie : string -> string option end class ['server,'args] nilreq (server:'server) (args:'args) = object method self (_:'server) (_:'args) = "" val server = server method server = server val args = args method args = args method path = "" method get (_:string) = (None : string option) method cookie (_:string) = (None : string option) method post = (None : [ `JSON of Json_type.t | `POST of (string,string) BatMap.t ] option) end class ['server,'args] fcgi_request (endpoint:('server,'args) Action_Endpoint.endpoint) (server:'server) (args:'args) (cgi:Netcgi.cgi) = let env = cgi # environment in let post : [ `JSON of Json_type.t | `POST of (string,string) BatMap.t ] option Lazy.t = lazy begin if cgi # request_method = `POST then if BatString.starts_with (env # input_content_type_string) "application/json" then Some (`JSON (try let field = (cgi # argument "BODY") # value in match utf8 field with | Some field -> Json.unserialize field | None -> Json.Null with _ -> Json.Null)) else Some (`POST (List.fold_left begin fun acc arg -> try match utf8 (arg # name), utf8 (arg # value) with | Some name, Some value -> BatMap.add name value acc | _ -> acc with _ -> acc end BatMap.empty (cgi # arguments))) else None end in let path = lazy (path_clean (env # cgi_script_name)) in object val path = path val args = args val server = server val post = post val self = endpoint method self = self method args = args method server = server method path = Lazy.force path method post = Lazy.force post method get field = try let field = ((cgi # argument field) # value) in utf8 field with Not_found -> None method cookie name = try let cookie = env # cookie name in let value = Netcgi.Cookie.value cookie in utf8 value with Not_found -> None end
82ac2d111a75f7e9c18e8c821ffce49cb8836551b60f7bc8a7a57c2e08a617c3
seckcoder/iu_c311
lazy-list-monad.rkt
#lang racket Three methods to construct monad : unit , mzero and cons (define (unit a) (list a)) (define (mzero) '()) ;cons (define (bind ma f) (match ma [(list) (mzero)] [(list a) (f a)] [(cons a get-ma) (mplus (f a) (lambda () (bind (get-ma) f)))])) ;ma * get-ma -> mb (define (mplus ma get-ma) (match ma [(list) (get-ma)] [(list a) (cons a get-ma)] [(list a get-ma0) (cons a (lambda () (mplus (get-ma0) get-ma)))])) (define (mmap n p ma) ;(printf "~a\n" ma) (match ma [(list) (mzero)] [(list a) (unit (p a))] [(cons a get-ma) (cons (p a) (cond ((= n -1) (mmap n p (get-ma))) ((> n 1) (mmap (- n 1) p (get-ma))) (else '())))])) (define (mmap-inf p ma) (mmap -1 p ma)) (define (mtake n ma) (mmap n (lambda (v) v) ma)) ; lazy version of assoc (define (s-assoc l v) (cond ((null? l) (mzero)) ((eq? (car (car l)) v) (mplus (unit (car l)) (lambda () (s-assoc (cdr l) v)))) (else (s-assoc (cdr l) v)))) (mtake 1 (s-assoc '((1 . 'a) (2 . 'b) (3 . 'c) (2 . 'd) (2 . 'e)) 2))
null
https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/monad/lazy-list-monad.rkt
racket
cons ma * get-ma -> mb (printf "~a\n" ma) lazy version of assoc
#lang racket Three methods to construct monad : unit , mzero and cons (define (unit a) (list a)) (define (mzero) '()) (define (bind ma f) (match ma [(list) (mzero)] [(list a) (f a)] [(cons a get-ma) (mplus (f a) (lambda () (bind (get-ma) f)))])) (define (mplus ma get-ma) (match ma [(list) (get-ma)] [(list a) (cons a get-ma)] [(list a get-ma0) (cons a (lambda () (mplus (get-ma0) get-ma)))])) (define (mmap n p ma) (match ma [(list) (mzero)] [(list a) (unit (p a))] [(cons a get-ma) (cons (p a) (cond ((= n -1) (mmap n p (get-ma))) ((> n 1) (mmap (- n 1) p (get-ma))) (else '())))])) (define (mmap-inf p ma) (mmap -1 p ma)) (define (mtake n ma) (mmap n (lambda (v) v) ma)) (define (s-assoc l v) (cond ((null? l) (mzero)) ((eq? (car (car l)) v) (mplus (unit (car l)) (lambda () (s-assoc (cdr l) v)))) (else (s-assoc (cdr l) v)))) (mtake 1 (s-assoc '((1 . 'a) (2 . 'b) (3 . 'c) (2 . 'd) (2 . 'e)) 2))
936087a84bf06a78cf76ef0c7919e516b188b99e4994d8471398ef2c0e451be0
cartazio/tlaps
prep.mli
* prf / prep.ml --- ship obligations * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * prf/prep.ml --- ship obligations * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) (** Ship obligations to the backend *) open Proof.T open Types;; val make_task : out_channel -> out_channel -> (bool -> obligation -> unit) -> obligation -> Schedule.task ;; (** @raise Exit if the toolbox sent the "stop" command. *) val expand_defs : ?what:(Expr.T.wheredef -> bool) -> obligation -> obligation val normalize : obligation -> obligation
null
https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/backend/prep.mli
ocaml
* Ship obligations to the backend * @raise Exit if the toolbox sent the "stop" command.
* prf / prep.ml --- ship obligations * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * prf/prep.ml --- ship obligations * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) open Proof.T open Types;; val make_task : out_channel -> out_channel -> (bool -> obligation -> unit) -> obligation -> Schedule.task ;; val expand_defs : ?what:(Expr.T.wheredef -> bool) -> obligation -> obligation val normalize : obligation -> obligation
fa2e33b3e7ec48743a33fbb20f18994e6d0225a205c79e1f4fbcf1bd6b005fc0
g000001/MacLISP-compat
STEP.lisp
;;; LISP Stepping Package ;;; < comments and problems accepted > , TS-824 ;;; x3-6032 ;;; AI: RICH ;;; For complete instructions see .INFO.;STEP INFO ;;; Rewritten 11/03/76 ;;; ;;; ;;; User Interface Function ;;; Valid Forms : set EVALHOOK * ;;; (STEP) NIL ;;; (STEP T) T ;;; (STEP NIL) NIL ;;; (STEP FOO1 FOO2 ...) (FOO1 FOO2) ;;; (declare (special evalhook evalhook* evalhook# prinlevel prinlength) (fixnum i indent) (setq macros nil) (SETQ NEWIO NIL)) ;; should be compiled with RICH;UTIL > (DEFUN STEP FEXPR (ARG) (COND ((OR (NULL ARG) (CAR ARG)) (SETQ *RSET T) ;must be on for hook to work (SETQ EVALHOOK# 0.) ;initialize depth count (SETQ EVALHOOK NIL) ;for safety (SETQ EVALHOOK* (COND ((NULL ARG) NIL) ((EQ (CAR ARG) T)) (ARG))) (SETQ EVALHOOK 'EVALHOOK*)) ;turn system hook to my function (T (SETQ EVALHOOK* NIL)))) (macrodef PRINT* () ;; print with indentation (do ((i 1 (1+ i)) (indent (* 2 evalhook#)) (prinlevel 3) (prinlength 5)) ((> i indent)(cond (prin1 (funcall prin1 form)) (t (prin1 form)))) (tyo 32.))) ;;; LISP evaluator comes here whenever EVALHOOK is Non - NIL and points here ;;; It expects me to do the evaluation and return the value. ;;; (defun EVALHOOK* (form) ;; returns evaluation of form (cond (evalhook* ;; see if selective feature kicks in here (and (not (atom form)) (not (eq evalhook* t)) (memq (car form) evalhook*) (setq evalhook* t)) (cond ((eq evalhook* t) ;; print out form before evaluation (terpri) (print*) (cond ((atom form) (cond ((not (or (numberp form)(null form)(eq form t))) (princ '| = |) ((lambda (prinlevel prinlength) (setq form (evalhook form nil)) (cond (prin1 (funcall prin1 form)) (t (prin1 form)))) 3 5)))) (t ; s-expression (prog (cmd hookfn) cmdlp (setq cmd (tyi tyi)) uppercase alphabetics (cond ((alpha? cmd)(setq cmd (boole 2 32. cmd)))) ;; dispatch on command character (cond ((7bit cmd 32.) ;<sp> continue, but suppress (cond ((eq (car (getl (car form) ;macro expansion '(expr fexpr lexpr subr fsubr lsubr macro))) 'macro) ;; do macro expansion (setq form (funcall (get (car form) 'macro) form)) (terpri) (print*) (go cmdlp)) (t (setq hookfn 'evalhook*)))) ((7bit cmd 80.) ; "P" print in full (prog (prinlevel prinlength) (cond (prin1 (terpri)(funcall prin1 form)) (t (print form)))) (go cmdlp)) ((or (7bit cmd 9.)(7bit cmd 13.)) ;<tab> or <cr> (setq evalhook* nil ;stop everything hookfn nil)) ((7bit cmd 127.) ;<rubout> no deeper (setq hookfn nil)) ((7bit cmd 77.) ; "M" continue including macro expansion (setq hookfn 'evalhook*)) ((7bit cmd 66.) ; "B" give breakpoint (break step) (print* form) (go cmdlp)) (t (tyo 7.)(go cmdlp))) ;; evaluate form (let ((evalhook# (1+ evalhook#))) (setq form (evalhook form hookfn))) ;; print out evaluated form (cond ((and evalhook* (not (zerop evalhook#))) (terpri) (print*)))))) ;;return evaluated form form) (t (evalhook form 'evalhook*)))) ; keep looking (t (evalhook form 'evalhook*)))) ; skip out quick 
null
https://raw.githubusercontent.com/g000001/MacLISP-compat/a147d09b98dca4d7c089424c3cbaf832d2fd857a/STEP.lisp
lisp
LISP Stepping Package x3-6032 AI: RICH STEP INFO User Interface Function (STEP) NIL (STEP T) T (STEP NIL) NIL (STEP FOO1 FOO2 ...) (FOO1 FOO2) should be compiled with RICH;UTIL > must be on for hook to work initialize depth count for safety turn system hook to my function print with indentation It expects me to do the evaluation and return the value. returns evaluation of form see if selective feature kicks in here print out form before evaluation s-expression dispatch on command character <sp> continue, but suppress macro expansion do macro expansion "P" print in full <tab> or <cr> stop everything <rubout> no deeper "M" continue including macro expansion "B" give breakpoint evaluate form print out evaluated form return evaluated form keep looking skip out quick
< comments and problems accepted > , TS-824 Rewritten 11/03/76 Valid Forms : set EVALHOOK * (declare (special evalhook evalhook* evalhook# prinlevel prinlength) (fixnum i indent) (setq macros nil) (SETQ NEWIO NIL)) (DEFUN STEP FEXPR (ARG) (COND ((OR (NULL ARG) (CAR ARG)) (SETQ EVALHOOK* (COND ((NULL ARG) NIL) ((EQ (CAR ARG) T)) (ARG))) (T (SETQ EVALHOOK* NIL)))) (macrodef PRINT* () (do ((i 1 (1+ i)) (indent (* 2 evalhook#)) (prinlevel 3) (prinlength 5)) ((> i indent)(cond (prin1 (funcall prin1 form)) (t (prin1 form)))) (tyo 32.))) LISP evaluator comes here whenever EVALHOOK is Non - NIL and points here (defun EVALHOOK* (form) (cond (evalhook* (and (not (atom form)) (not (eq evalhook* t)) (memq (car form) evalhook*) (setq evalhook* t)) (cond ((eq evalhook* t) (terpri) (print*) (cond ((atom form) (cond ((not (or (numberp form)(null form)(eq form t))) (princ '| = |) ((lambda (prinlevel prinlength) (setq form (evalhook form nil)) (cond (prin1 (funcall prin1 form)) (t (prin1 form)))) 3 5)))) (prog (cmd hookfn) cmdlp (setq cmd (tyi tyi)) uppercase alphabetics (cond ((alpha? cmd)(setq cmd (boole 2 32. cmd)))) '(expr fexpr lexpr subr fsubr lsubr macro))) 'macro) (setq form (funcall (get (car form) 'macro) form)) (terpri) (print*) (go cmdlp)) (t (setq hookfn 'evalhook*)))) (prog (prinlevel prinlength) (cond (prin1 (terpri)(funcall prin1 form)) (t (print form)))) (go cmdlp)) hookfn nil)) (setq hookfn nil)) (setq hookfn 'evalhook*)) (break step) (print* form) (go cmdlp)) (t (tyo 7.)(go cmdlp))) (let ((evalhook# (1+ evalhook#))) (setq form (evalhook form hookfn))) (cond ((and evalhook* (not (zerop evalhook#))) (terpri) (print*)))))) form) 
b2c94b9702a5431b46dcb3aaf991cb9fae849a1ed763dcdf7960b856acb2f05d
kadena-io/chainweaver
Example.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE ExtendedDefaultRules # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # -- | Pact example files. -- Copyright : ( C ) 2020 - 2022 Kadena -- License : BSD-style (see the file LICENSE) -- module Frontend.ModuleExplorer.Example ( -- * Example References ExampleRef (..) , _ExampleRef_HelloWorld , _ExampleRef_SimplePayment -- * Available examples , examples -- * Get some information about examples , exampleName , exampleFileName , exampleDataName , exampleNamespacesFile -- * Retrieve example code , fetchExample ) where ------------------------------------------------------------------------------ import Control.Arrow ((***)) import Control.Error.Safe (justZ) import Control.Monad (void) import qualified Data.Aeson as A import Data.Default import Data.String.Here.Uninterpolated (here) import Data.Text (Text) import qualified Data.Text as T import Reflex import Reflex.Dom.Core (HasJSContext, XhrResponse (..), newXMLHttpRequest, xhrRequest) import Safe (readMay, tailDef) ------------------------------------------------------------------------------ import Obelisk.Generated.Static ------------------------------------------------------------------------------ import Frontend.Foundation import Common.RefPath as MP | A reference to one of the predefined example files . data ExampleRef = ExampleRef_HelloWorld | ExampleRef_HelloWorld_Keyset | ExampleRef_SimplePayment | ExampleRef_Verification deriving (Eq, Ord, Show, Enum, Bounded, Generic, Read) makePactPrisms ''ExampleRef instance A.ToJSON ExampleRef where toJSON = A.genericToJSON compactEncoding toEncoding = A.genericToEncoding compactEncoding instance A.FromJSON ExampleRef where parseJSON = A.genericParseJSON compactEncoding -- | List of all available examples. examples :: [ExampleRef] examples = [minBound .. maxBound] instance IsRefPath ExampleRef where renderRef = mkRefPath . shorten . T.pack . show where -- Only works for "ExampleRef_Blah" kind of names: shorten = T.intercalate "_" . tailDef [] . T.splitOn "_" parseRef = do n <- ("ExampleRef_" <>) <$> MP.anySingle justZ $ readMay . T.unpack $ n -- | Names of examples as shown to the user. exampleName :: ExampleRef -> Text exampleName = \case ExampleRef_HelloWorld -> "Hello World" ExampleRef_HelloWorld_Keyset -> "Hello World Keyset" ExampleRef_SimplePayment -> "Simple Payment" ExampleRef_Verification -> "Verification" -- | File name of Pact code for the given example. exampleFileName :: ExampleRef -> Text exampleFileName = \case ExampleRef_HelloWorld -> static @ "examples/helloWorld-1.0.pact" ExampleRef_HelloWorld_Keyset -> static @ "examples/helloWorld-keyset-1.0.pact" ExampleRef_SimplePayment -> static @ "examples/simplePayments-1.0.pact" ExampleRef_Verification -> static @ "examples/verification-1.0.pact" -- | File name of JSON data for example. exampleDataName :: ExampleRef -> Text exampleDataName = \case ExampleRef_HelloWorld -> static @ "examples/helloWorld-1.0.data.json" ExampleRef_HelloWorld_Keyset -> static @ "examples/helloWorld-keyset-1.0.data.json" ExampleRef_SimplePayment -> static @ "examples/simplePayments-1.0.data.json" ExampleRef_Verification -> static @ "examples/verification-1.0.data.json" -- | Actually fetch Example code and data. -- First value in returned pair is the Pact code , the second is the retrieved -- JSON data. -- TODO : We do n't actually use the json data right now , we maybe never will -- as I am not yet sure whether we actually want to store/restore JSON data -- and whether it would be useful/secure. fetchExample :: ( PerformEvent t m, TriggerEvent t m, MonadJSM (Performable m) , HasJSContext JSM ) => Event t ExampleRef -> m (Event t (ExampleRef, (Text, Text))) fetchExample onExampleModule = performEventAsync $ ffor onExampleModule $ \example cb -> void . liftJSM . forkJSM $ do let callback = liftIO . cb . (example,) . (codeFromResponse *** codeFromResponse) let codeReq = xhrRequest "GET" (exampleFileName example) def void $ newXMLHttpRequest codeReq $ \codeRes -> do let jsonReq = xhrRequest "GET" (exampleDataName example) def void $ newXMLHttpRequest jsonReq $ \jsonRes -> callback (codeRes, jsonRes) codeFromResponse :: XhrResponse -> Text codeFromResponse = fromMaybe "error: could not connect to server" . _xhrResponse_responseText TODO : Using ` file - embed ` errors on cabal build , using ` static ` and ` file - embed ` yields TH error exampleNamespacesFile :: Text exampleNamespacesFile = [here| ;; Stripped down version of -io/chainweb-node/blob/8edd0e7d8d64173a548a3fbf4414d1491f2b7d3e/pact/namespaces/ns.pact (module ns MODULE_ADMIN (defcap MODULE_ADMIN () true) (defun success () true) (defun failure () (enforce false "Disabled")) (defconst GUARD_SUCCESS (create-user-guard (success))) (defconst GUARD_FAILURE (create-user-guard (failure)))) (define-namespace "free" GUARD_SUCCESS GUARD_FAILURE) |]
null
https://raw.githubusercontent.com/kadena-io/chainweaver/5d40e91411995e0a9a7e782d6bb2d89ac1c65d52/frontend/src/Frontend/ModuleExplorer/Example.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE OverloadedStrings # | Pact example files. License : BSD-style (see the file LICENSE) * Example References * Available examples * Get some information about examples * Retrieve example code ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | List of all available examples. Only works for "ExampleRef_Blah" kind of names: | Names of examples as shown to the user. | File name of Pact code for the given example. | File name of JSON data for example. | Actually fetch Example code and data. JSON data. as I am not yet sure whether we actually want to store/restore JSON data and whether it would be useful/secure.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE ExtendedDefaultRules # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE LambdaCase # # LANGUAGE QuasiQuotes # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # Copyright : ( C ) 2020 - 2022 Kadena module Frontend.ModuleExplorer.Example ExampleRef (..) , _ExampleRef_HelloWorld , _ExampleRef_SimplePayment , examples , exampleName , exampleFileName , exampleDataName , exampleNamespacesFile , fetchExample ) where import Control.Arrow ((***)) import Control.Error.Safe (justZ) import Control.Monad (void) import qualified Data.Aeson as A import Data.Default import Data.String.Here.Uninterpolated (here) import Data.Text (Text) import qualified Data.Text as T import Reflex import Reflex.Dom.Core (HasJSContext, XhrResponse (..), newXMLHttpRequest, xhrRequest) import Safe (readMay, tailDef) import Obelisk.Generated.Static import Frontend.Foundation import Common.RefPath as MP | A reference to one of the predefined example files . data ExampleRef = ExampleRef_HelloWorld | ExampleRef_HelloWorld_Keyset | ExampleRef_SimplePayment | ExampleRef_Verification deriving (Eq, Ord, Show, Enum, Bounded, Generic, Read) makePactPrisms ''ExampleRef instance A.ToJSON ExampleRef where toJSON = A.genericToJSON compactEncoding toEncoding = A.genericToEncoding compactEncoding instance A.FromJSON ExampleRef where parseJSON = A.genericParseJSON compactEncoding examples :: [ExampleRef] examples = [minBound .. maxBound] instance IsRefPath ExampleRef where renderRef = mkRefPath . shorten . T.pack . show where shorten = T.intercalate "_" . tailDef [] . T.splitOn "_" parseRef = do n <- ("ExampleRef_" <>) <$> MP.anySingle justZ $ readMay . T.unpack $ n exampleName :: ExampleRef -> Text exampleName = \case ExampleRef_HelloWorld -> "Hello World" ExampleRef_HelloWorld_Keyset -> "Hello World Keyset" ExampleRef_SimplePayment -> "Simple Payment" ExampleRef_Verification -> "Verification" exampleFileName :: ExampleRef -> Text exampleFileName = \case ExampleRef_HelloWorld -> static @ "examples/helloWorld-1.0.pact" ExampleRef_HelloWorld_Keyset -> static @ "examples/helloWorld-keyset-1.0.pact" ExampleRef_SimplePayment -> static @ "examples/simplePayments-1.0.pact" ExampleRef_Verification -> static @ "examples/verification-1.0.pact" exampleDataName :: ExampleRef -> Text exampleDataName = \case ExampleRef_HelloWorld -> static @ "examples/helloWorld-1.0.data.json" ExampleRef_HelloWorld_Keyset -> static @ "examples/helloWorld-keyset-1.0.data.json" ExampleRef_SimplePayment -> static @ "examples/simplePayments-1.0.data.json" ExampleRef_Verification -> static @ "examples/verification-1.0.data.json" First value in returned pair is the Pact code , the second is the retrieved TODO : We do n't actually use the json data right now , we maybe never will fetchExample :: ( PerformEvent t m, TriggerEvent t m, MonadJSM (Performable m) , HasJSContext JSM ) => Event t ExampleRef -> m (Event t (ExampleRef, (Text, Text))) fetchExample onExampleModule = performEventAsync $ ffor onExampleModule $ \example cb -> void . liftJSM . forkJSM $ do let callback = liftIO . cb . (example,) . (codeFromResponse *** codeFromResponse) let codeReq = xhrRequest "GET" (exampleFileName example) def void $ newXMLHttpRequest codeReq $ \codeRes -> do let jsonReq = xhrRequest "GET" (exampleDataName example) def void $ newXMLHttpRequest jsonReq $ \jsonRes -> callback (codeRes, jsonRes) codeFromResponse :: XhrResponse -> Text codeFromResponse = fromMaybe "error: could not connect to server" . _xhrResponse_responseText TODO : Using ` file - embed ` errors on cabal build , using ` static ` and ` file - embed ` yields TH error exampleNamespacesFile :: Text exampleNamespacesFile = [here| ;; Stripped down version of -io/chainweb-node/blob/8edd0e7d8d64173a548a3fbf4414d1491f2b7d3e/pact/namespaces/ns.pact (module ns MODULE_ADMIN (defcap MODULE_ADMIN () true) (defun success () true) (defun failure () (enforce false "Disabled")) (defconst GUARD_SUCCESS (create-user-guard (success))) (defconst GUARD_FAILURE (create-user-guard (failure)))) (define-namespace "free" GUARD_SUCCESS GUARD_FAILURE) |]
7d4800ff2140c22010e9035606a2bd98edfa6736950c50efd80b1881e31a06f1
lenn0x/Event-Notifier
fb303_types.erl
%% Autogenerated by Thrift %% %% DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING %% -module(fb303_types). -include("fb303_types.hrl"). -export([struct_info/1]). struct_info('i am a dummy struct') -> undefined.
null
https://raw.githubusercontent.com/lenn0x/Event-Notifier/5b370624578f4610b4af71c989c13068c2cbbf58/if/fb303/if/gen-erl/fb303_types.erl
erlang
DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
Autogenerated by Thrift -module(fb303_types). -include("fb303_types.hrl"). -export([struct_info/1]). struct_info('i am a dummy struct') -> undefined.
19649a6f911157efedc853645a08fde4e44224c4081239120d5089289a6c6173
KestrelInstitute/Specware
Tests.lisp
(test-directories ".") (test ("Bug 0142 : Projections were printed out incorrectly" :show "Ob#BadObl1" :output '(";;; Elaborating obligator at $TESTDIR/Ob#BadObl1" ";;; Elaborating spec-morphism at $TESTDIR/Ob#BadObl1" ";;; Elaborating spec at $TESTDIR/Ob#S" ";;; Elaborating spec at $TESTDIR/Ob#T" (:optional "") "spec " " import $TESTDIR/Ob#T" ;; " conjecture pp is project b (project a (z)) = 0" "" " conjecture pp is (z.a).b = 0" (:optional "") (:alternatives "endspec" "end-spec") (:optional "") (:optional "") )) )
null
https://raw.githubusercontent.com/KestrelInstitute/Specware/2be6411c55f26432bf5c9e2f7778128898220c24/TestSuite/Bugs/Bug_0142/Tests.lisp
lisp
" conjecture pp is project b (project a (z)) = 0"
(test-directories ".") (test ("Bug 0142 : Projections were printed out incorrectly" :show "Ob#BadObl1" :output '(";;; Elaborating obligator at $TESTDIR/Ob#BadObl1" ";;; Elaborating spec-morphism at $TESTDIR/Ob#BadObl1" ";;; Elaborating spec at $TESTDIR/Ob#S" ";;; Elaborating spec at $TESTDIR/Ob#T" (:optional "") "spec " " import $TESTDIR/Ob#T" "" " conjecture pp is (z.a).b = 0" (:optional "") (:alternatives "endspec" "end-spec") (:optional "") (:optional "") )) )
b780ca4863d4dca8781e4255671c832898c7619e2ab926f762a0dda667c2c506
dQuadrant/kuber
Api.hs
module Kuber.Server.Api where
null
https://raw.githubusercontent.com/dQuadrant/kuber/43a00c8c761d424b27aa3a7b13a4879762e7e6a6/server/src/Kuber/Server/Api.hs
haskell
module Kuber.Server.Api where
4b501d2958fa2d0abb70288b4d2cb106e2f75c9aa0eac6b206ead1a784bb364d
pixlsus/registry.gimp.org_static
JMS-Space_Galaxy.scm
(define (fg/bg-selection image drawable) (gimp-edit-bucket-fill drawable FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0) (gimp-selection-invert image) (gimp-edit-bucket-fill drawable BG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0) ) (define (get-blending-mode-galaxy mode) (let* ((modenumbers #(0 1 3 15 4 5 16 17 18 19 20 21 6 7 8 9 10 11 12 13 14))) (vector-ref modenumbers mode) ) ) (define (math-round-galaxy input) (floor (+ input 0.5)) ) (define (get-layer-pos-galaxy img layer) (let* ((layerdata (gimp-image-get-layers img)) (numlayers (car layerdata)) (layerarray (cadr layerdata)) (i 0) (pos -1) ) (while (< i numlayers) (if (= layer (vector-ref layerarray i)) (begin (set! pos i) (set! i numlayers) ) (set! i (+ i 1)) ) ) pos ) ) (define (add-under-layer-galaxy img newlayer oldlayer) (gimp-image-add-layer img newlayer (+ (get-layer-pos-galaxy img oldlayer) 1)) ) (define (draw-blurshape-galaxy img drawable size initgrowth sel invert) (let* ((k initgrowth) (currshade 0) (i 0)) (while (< i size) (if (> k 0) (gimp-selection-grow img k) (if (< k 0) (gimp-selection-shrink img (abs k)) ) ) (if (= invert 1) (set! currshade (math-round-galaxy (* (/ (- size (+ i 1)) size) 255))) (set! currshade (math-round-galaxy (* (/ (+ i 1) size) 255))) ) (gimp-palette-set-foreground (list currshade currshade currshade)) (if (= (car (gimp-selection-is-empty img)) 0) (gimp-edit-fill drawable 0) ) (gimp-selection-load sel) (set! k (- k 1)) (set! i (+ i 1)) ) ) ) (define (apply-contour-galaxy drawable channel contour) (let* ((contourtypes #(0 0 0 0 0 0 0 0 0 1 1)) (contourlengths #(6 6 10 14 18 10 18 18 10 256 256)) (contours #(#(0 0 127 255 255 0) #(0 255 127 0 255 255) #(0 64 94 74 150 115 179 179 191 255) #(0 0 5 125 6 125 48 148 79 179 107 217 130 255) #(0 0 33 8 64 38 97 102 128 166 158 209 191 235 222 247 255 255) #(0 0 28 71 87 166 194 240 255 255) #(0 0 33 110 64 237 97 240 128 138 158 33 191 5 222 99 255 255) #(0 0 33 74 64 219 97 186 128 0 158 176 191 201 222 3 255 255) #(3 255 54 99 97 107 179 153 252 0) #(0 5 9 13 16 19 22 25 27 29 30 32 33 34 35 36 38 39 40 41 43 44 46 47 48 49 50 51 52 53 54 55 55 56 56 57 57 58 58 59 59 59 60 60 60 61 61 61 61 62 62 62 62 62 63 63 63 63 63 63 64 64 64 64 64 71 75 78 81 84 86 89 91 93 95 96 98 99 101 102 103 104 105 107 107 108 110 111 112 113 114 115 116 117 118 119 119 120 121 121 122 123 123 123 124 124 124 125 125 125 125 125 125 125 126 126 126 126 126 126 126 125 125 125 125 125 125 125 125 130 134 137 141 145 148 151 153 156 158 160 162 163 165 166 167 168 170 171 171 172 173 174 175 176 177 178 178 179 180 181 181 182 183 183 184 184 185 185 186 186 187 187 188 188 189 189 189 189 190 190 190 190 191 191 191 191 191 191 191 191 191 191 193 194 196 197 198 200 201 203 204 205 207 208 209 211 212 213 214 215 217 218 219 220 220 221 222 222 223 223 224 224 224 224 224 223 223 222 222 221 221 220 219 218 217 216 215 214 213 212 211 210 209 208 206 205 204 203 202 200 199 198 197 196 194 194) #(0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124 126 127 125 123 121 119 117 115 113 111 109 107 105 103 101 99 97 95 93 91 89 87 85 83 81 79 77 75 73 71 69 67 65 63 61 59 57 55 53 51 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 128 126 124 122 120 118 116 114 112 110 108 106 104 102 100 98 96 94 92 90 88 86 84 82 80 78 76 74 72 70 68 66 64 62 60 58 56 54 52 50 48 46 44 42 40 38 36 34 32 30 28 26 24 22 20 18 16 14 12 10 8 6 4 2)))) (if (= (vector-ref contourtypes (- contour 1)) 0) (gimp-curves-spline drawable channel (vector-ref contourlengths (- contour 1)) (vector-ref contours (- contour 1))) (gimp-curves-explicit drawable channel (vector-ref contourlengths (- contour 1)) (vector-ref contours (- contour 1))) ) ) ) (define (apply-noise-galaxy img drawable srclayer noise) (let* ((drwwidth (car (gimp-drawable-width srclayer))) (drwheight (car (gimp-drawable-height srclayer))) (layername (car (gimp-drawable-get-name drawable))) (drwoffsets (gimp-drawable-offsets srclayer)) (srcmask (car (gimp-layer-get-mask srclayer))) (noiselayer (car (gimp-layer-new img drwwidth drwheight (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-noise") 100 0))) (blanklayer (car (gimp-layer-new img drwwidth drwheight (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-noise") 100 0)))) (add-over-layer img noiselayer srclayer) (add-over-layer img blanklayer noiselayer) (gimp-layer-set-offsets noiselayer (car drwoffsets) (cadr drwoffsets)) (gimp-layer-set-offsets blanklayer (car drwoffsets) (cadr drwoffsets)) (gimp-selection-all img) (gimp-palette-set-foreground '(0 0 0)) (gimp-edit-fill noiselayer 0) (gimp-edit-fill blanklayer 0) (gimp-palette-set-foreground '(255 255 255)) (gimp-selection-load srcmask) (gimp-edit-fill blanklayer 0) (plug-in-hsv-noise 1 img noiselayer 1 0 0 255) (gimp-layer-set-mode blanklayer 5) (gimp-layer-set-opacity blanklayer noise) (set! noiselayer (car (gimp-image-merge-down img blanklayer 0))) (set! blanklayer (car (gimp-layer-create-mask noiselayer 5))) (gimp-channel-combine-masks srcmask blanklayer 2 0 0) (gimp-image-remove-layer img noiselayer) ) ) (define (script-fu-layerfx-outer-glow-galaxy img drawable color opacity contour noise mode spread size knockout merge) (let* ((origfgcolor (car (gimp-palette-get-foreground))) (origselection (car (gimp-selection-save img))) (drwwidth (car (gimp-drawable-width drawable))) (drwheight (car (gimp-drawable-height drawable))) (drwoffsets (gimp-drawable-offsets drawable)) (layername (car (gimp-drawable-get-name drawable))) (lyrgrowamt (math-round-galaxy (* size 1.2))) (glowlayer (car (gimp-layer-new img (+ drwwidth (* lyrgrowamt 2)) (+ drwheight (* lyrgrowamt 2)) (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-outerglow") opacity (get-blending-mode-galaxy mode)))) (glowmask 0) (alphaSel 0) (growamt (* (/ spread 100) size)) (steps (- size growamt)) (origmask 0) ) (add-under-layer-galaxy img glowlayer drawable) (gimp-layer-set-offsets glowlayer (- (car drwoffsets) lyrgrowamt) (- (cadr drwoffsets) lyrgrowamt)) (gimp-selection-all img) (gimp-palette-set-foreground color) (gimp-edit-fill glowlayer 0) (gimp-selection-none img) (set! glowmask (car (gimp-layer-create-mask glowlayer 1))) (gimp-layer-add-mask glowlayer glowmask) (gimp-selection-layer-alpha drawable) (if (> (car (gimp-layer-get-mask drawable)) -1) (gimp-selection-combine (car (gimp-layer-get-mask drawable)) 3) ) (set! alphaSel (car (gimp-selection-save img))) (draw-blurshape-galaxy img glowmask steps size alphaSel 0) (gimp-selection-none img) (if (> contour 0) (begin (apply-contour-galaxy glowmask 0 contour) (gimp-selection-load alphaSel) (gimp-selection-grow img size) (gimp-selection-invert img) (gimp-palette-set-foreground '(0 0 0)) (gimp-edit-fill glowmask 0) (gimp-selection-none img) ) ) (if (> noise 0) (apply-noise-galaxy img drawable glowlayer noise) ) (if (= knockout 1) (begin (gimp-palette-set-foreground '(0 0 0)) (gimp-selection-layer-alpha drawable) (gimp-edit-fill glowmask 0) ) ) (gimp-layer-remove-mask glowlayer 0) (gimp-selection-none img) (if (= merge 1) (begin (set! origmask (car (gimp-layer-get-mask drawable))) (if (> origmask -1) (gimp-layer-remove-mask drawable 0) ) (set! glowlayer (car (gimp-image-merge-down img drawable 0))) (gimp-drawable-set-name glowlayer layername) ) ) (gimp-palette-set-foreground origfgcolor) (gimp-selection-load origselection) (gimp-image-remove-channel img alphaSel) (gimp-image-remove-channel img origselection) (gimp-displays-flush) (gimp-selection-layer-alpha glowlayer) ) ) (define (script-fu-galaxy numArms holeSize innerRad armSize startAngle ArmCurve NumStars maxStar hSkew vSkew radSkew cloudColor seed ) (let* ( (imageSize (* 2 (+ innerRad armSize))) (centerPoint (/ imageSize 2.0)) (theImage (car (gimp-image-new imageSize imageSize RGB))) (baseLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Galaxy" 100 SCREEN-MODE))) (cloudLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Plasma" 100 OVERLAY-MODE))) (starLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Stars" 100 NORMAL-MODE))) (scratchLayer 0) (novaLayer 0) (area 0) (blackLayer 0) (testLayer 0) (diameter (* 2.0 holeSize)) (flag (* -1 ArmCurve)) (toothWidth (/ imageSize numArms)) (outerEdge (- (* 2.0 innerRad) diameter)) (centerX 0) (centerY 0) (rotAngle (* startAngle (/ *pi* 180.0))) (selection-bounds 0) (select-offset-x 0) (select-offset-y 0) (selection-width 0) (selection-height 0) (selArea 0.0) (x0 0) (x1 0) (x2 0) (x3 0) (y1 0) (y2 0) (pointArray (make-vector 8 0.0)) (starSize 0) (Star_X 0) (Star_Y 0) (squared 0) (starAngle 0.0) (starRad 0.0) (oldHeight 0) (oldWidth 0) (Wprime 0) (Hprime 0) (newHeight 0) (newWidth 0) (radAngle (* radSkew (/ *pi* 180.0))) (tanTheta (tan radAngle)) (size 0) (frameName "") (frameNum 0) ) (set! seed (if (number? seed) seed (realtime))) (srand seed) (gimp-image-add-layer theImage baseLayer 0) (gimp-context-set-foreground cloudColor) (gimp-context-set-background '(255 255 255)) (gimp-drawable-fill baseLayer BACKGROUND-FILL) (gimp-rect-select theImage 0 diameter imageSize outerEdge CHANNEL-OP-ADD FALSE 0) (while (< flag numArms) (begin (vector-set! pointArray 0 (* flag toothWidth)) (vector-set! pointArray 1 (+ outerEdge diameter)) (vector-set! pointArray 2 (* (+ ArmCurve 0.5 flag) toothWidth)) (vector-set! pointArray 3 (+ diameter outerEdge armSize)) (vector-set! pointArray 4 (* (+ 1 flag) toothWidth)) (vector-set! pointArray 5 (+ outerEdge diameter)) (vector-set! pointArray 6 (* flag toothWidth)) (vector-set! pointArray 7 (+ outerEdge diameter)) (gimp-free-select theImage 8 pointArray CHANNEL-OP-ADD 0 0 0) (set! flag (+ 1 flag)) ) ) (set! flag 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (gimp-selection-invert theImage) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage baseLayer '(255 255 255)) (gimp-selection-clear theImage) (plug-in-polar-coords RUN-NONINTERACTIVE theImage baseLayer 100 0 FALSE TRUE TRUE) (if (> startAngle 0) (gimp-drawable-transform-rotate-default baseLayer rotAngle TRUE centerPoint centerPoint TRUE TRANSFORM-RESIZE-ADJUST) ) (gimp-selection-layer-alpha baseLayer) (gimp-selection-grow theImage 2) (gimp-edit-clear baseLayer) (script-fu-distress-selection theImage baseLayer 127 8 4 2 0 0) (script-fu-distress-selection theImage baseLayer 127 8 4 2 0 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (set! selection-bounds (gimp-selection-bounds theImage)) (set! select-offset-x (cadr selection-bounds)) (set! select-offset-y (caddr selection-bounds)) (set! selection-width (- (cadr (cddr selection-bounds)) select-offset-x)) (set! selection-height (- (caddr (cddr selection-bounds)) select-offset-y)) (set! selArea (* 0.25 *pi* selection-width selection-height)) (set! scratchLayer (car (gimp-layer-copy baseLayer FALSE))) (gimp-image-add-layer theImage scratchLayer 0) (plug-in-autocrop-layer RUN-NONINTERACTIVE theImage scratchLayer) (gimp-context-set-background '(0 0 0)) (gimp-context-set-foreground '(255 0 0)) (fg/bg-selection theImage scratchLayer) (gimp-selection-none theImage) (let ( (histogram (gimp-histogram scratchLayer HISTOGRAM-RED 128 255))) (set! area (/ (list-ref histogram 4) selArea)) ) (gimp-selection-none theImage) (gimp-image-remove-layer theImage scratchLayer) (set! blackLayer (car (gimp-layer-copy baseLayer FALSE))) (gimp-image-add-layer theImage blackLayer 0) (gimp-layer-set-mode blackLayer NORMAL-MODE) (gimp-context-set-background '(0 0 0)) (gimp-drawable-fill blackLayer BACKGROUND-FILL) (gimp-drawable-set-name blackLayer "Blackness of Space") (gimp-image-lower-layer-to-bottom theImage blackLayer) (set! size (min selection-width selection-height)) (set! squared (* size size)) (gimp-image-add-layer theImage starLayer 0) (gimp-drawable-set-name starLayer "Stars") (while (< flag (/ NumStars area)) (begin (set! starSize (+ 1 (rand maxStar))) (set! starRad (rand squared)) (set! starAngle (/ (* *pi* (rand 3600.0)) 1800.0)) (set! Star_X (+ select-offset-x (/ size 2.0) (/ (+ size (- (* starRad (sin starAngle)) starSize)) (* 2.0 size)))) (set! Star_Y (+ select-offset-x (/ size 2.0) (/ (+ size (- (* starRad (cos starAngle)) starSize)) (* 2.0 size)))) (gimp-rect-select theImage Star_X Star_Y starSize starSize CHANNEL-OP-REPLACE FALSE 0) (gimp-context-set-foreground (list (rand 256) (rand 256) (rand 256))) (gimp-edit-bucket-fill starLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (set! flag (+ 1 flag)) ) ) (gimp-selection-none theImage) (gimp-image-add-layer theImage cloudLayer 0) (plug-in-plasma RUN-NONINTERACTIVE theImage cloudLayer (rand 1000000000) 7) (gimp-desaturate cloudLayer) (plug-in-whirl-pinch RUN-NONINTERACTIVE theImage cloudLayer (* 45.0 ArmCurve) 0 1.0) (gimp-image-crop theImage (+ 40 selection-width) (+ 40 selection-height) (- select-offset-x 20) (- select-offset-y 20)) (plug-in-cubism RUN-NONINTERACTIVE theImage baseLayer (/ selection-height 100.0) 1.5 0) (plug-in-gauss-rle2 RUN-NONINTERACTIVE theImage baseLayer (/ selection-width 100.0) (/ selection-height 100.0)) (gimp-selection-layer-alpha baseLayer) (gimp-selection-invert theImage) (gimp-edit-clear starLayer) (gimp-selection-none theImage) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (set! oldHeight (car (gimp-drawable-height testLayer))) (set! oldWidth (car (gimp-drawable-width testLayer))) (set! centerX (/ oldWidth 2.0)) (set! centerY (/ oldHeight 2.0)) (set! newHeight (* vSkew oldHeight)) (set! newWidth (* hSkew oldWidth)) (if (= radSkew 0) (gimp-image-scale theImage newWidth newHeight) (begin (set! Wprime newWidth) (set! Hprime newHeight) (set! x0 (- centerX (* 0.5 (+ newWidth (/ newHeight tanTheta))))) (set! x1 (+ centerX (* 0.5 (- newWidth (/ newHeight tanTheta))))) (set! x2 (- centerX (* 0.5 (- newWidth (/ newHeight tanTheta))))) (set! x3 (+ centerX (* 0.5 (+ newWidth (/ newHeight tanTheta))))) (set! y1 (- centerY (* 0.5 oldHeight))) (set! y2 (+ centerY (* 0.5 oldHeight))) (gimp-drawable-transform-perspective-default testLayer x0 y1 x1 y1 x2 y2 x3 y2 TRUE TRANSFORM-RESIZE-ADJUST) (gimp-image-resize-to-layers theImage) ) ) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (plug-in-zealouscrop RUN-NONINTERACTIVE theImage testLayer) (set! oldHeight (car (gimp-drawable-height testLayer))) (set! oldWidth (car (gimp-drawable-width testLayer))) (set! novaLayer (car (gimp-layer-copy testLayer FALSE))) (gimp-image-add-layer theImage novaLayer 0) (gimp-drawable-set-name novaLayer "Nova") (gimp-layer-set-mode novaLayer NORMAL-MODE) (gimp-context-set-background '(0 0 0)) (gimp-drawable-fill novaLayer BACKGROUND-FILL) (plug-in-nova RUN-NONINTERACTIVE theImage novaLayer (/ oldWidth 2) (/ oldHeight 2) cloudColor (min 100 (min (/ oldWidth 10) (/ oldHeight 10))) 1 0) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage novaLayer '(0 0 0)) (gimp-selection-layer-alpha novaLayer) (gimp-selection-invert theImage) (gimp-edit-clear novaLayer) (gimp-selection-none theImage) (plug-in-gauss-rle2 RUN-NONINTERACTIVE theImage novaLayer 100 100.0) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (set! scratchLayer (car (gimp-layer-copy testLayer FALSE))) (gimp-image-add-layer theImage scratchLayer 0) (gimp-drawable-fill scratchLayer BACKGROUND-FILL) (gimp-image-lower-layer-to-bottom theImage scratchLayer) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage testLayer '(0 0 0)) (gimp-selection-layer-alpha testLayer) (script-fu-layerfx-outer-glow-galaxy theImage testLayer cloudColor 50 0 0 0 0 5.0 FALSE FALSE) (set! novaLayer (car (gimp-image-get-active-layer theImage))) (plug-in-hsv-noise RUN-NONINTERACTIVE theImage scratchLayer 1 180 255 255) (gimp-selection-invert theImage) (gimp-edit-clear novaLayer) (gimp-edit-clear scratchLayer) (gimp-selection-none theImage) (gimp-image-flatten theImage) (set! baseLayer (car (gimp-image-get-active-layer theImage))) (set! frameName (string-append "Galaxy " (number->string seed frameNum))) (gimp-drawable-set-name baseLayer frameName) (gimp-display-new theImage) ) ) (script-fu-register "script-fu-galaxy" _"_Galaxy..." _"Creates a picture of a spiral galaxy..." "James Sambrook" "23 February 2011" "" "" SF-ADJUSTMENT _"Number of arms" '(8 4 36 1 5 0 0) SF-ADJUSTMENT _"Hole Size" '(25 0 100 1 10 0 0) SF-ADJUSTMENT _"Inner Radius" '(100 10 1000 1 10 0 0) SF-ADJUSTMENT _"Arm Size" '(500 10 1000 1 50 0 0) SF-ADJUSTMENT _"Angle first arm starts at" '(0 0 360 1 30 0 0) SF-ADJUSTMENT _"Arm Curvature" '(6 0 10 0.1 1 1 0) SF-ADJUSTMENT _"Number of Stars" '(200 0 3000 100 500 0 0) SF-ADJUSTMENT _"Maximum star size (in pixels)" '(3 1 10 1 1 0 0) SF-ADJUSTMENT _"Horizontal skew" '(1 0.1 5 0.1 1 1 0) SF-ADJUSTMENT _"Vertical skew" '(1 0.1 5 0.1 1 1 0) SF-ADJUSTMENT _"Skew Angle" '(60 -89 89 1 10 0 0) SF-COLOR _"Galaxy color" '(100 149 237) SF-VALUE _"Random seed" "random" ) (script-fu-menu-register "script-fu-galaxy" "<Image>/Filters/SambrookJM/")
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/JMS-Space_Galaxy.scm
scheme
(define (fg/bg-selection image drawable) (gimp-edit-bucket-fill drawable FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0) (gimp-selection-invert image) (gimp-edit-bucket-fill drawable BG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0) ) (define (get-blending-mode-galaxy mode) (let* ((modenumbers #(0 1 3 15 4 5 16 17 18 19 20 21 6 7 8 9 10 11 12 13 14))) (vector-ref modenumbers mode) ) ) (define (math-round-galaxy input) (floor (+ input 0.5)) ) (define (get-layer-pos-galaxy img layer) (let* ((layerdata (gimp-image-get-layers img)) (numlayers (car layerdata)) (layerarray (cadr layerdata)) (i 0) (pos -1) ) (while (< i numlayers) (if (= layer (vector-ref layerarray i)) (begin (set! pos i) (set! i numlayers) ) (set! i (+ i 1)) ) ) pos ) ) (define (add-under-layer-galaxy img newlayer oldlayer) (gimp-image-add-layer img newlayer (+ (get-layer-pos-galaxy img oldlayer) 1)) ) (define (draw-blurshape-galaxy img drawable size initgrowth sel invert) (let* ((k initgrowth) (currshade 0) (i 0)) (while (< i size) (if (> k 0) (gimp-selection-grow img k) (if (< k 0) (gimp-selection-shrink img (abs k)) ) ) (if (= invert 1) (set! currshade (math-round-galaxy (* (/ (- size (+ i 1)) size) 255))) (set! currshade (math-round-galaxy (* (/ (+ i 1) size) 255))) ) (gimp-palette-set-foreground (list currshade currshade currshade)) (if (= (car (gimp-selection-is-empty img)) 0) (gimp-edit-fill drawable 0) ) (gimp-selection-load sel) (set! k (- k 1)) (set! i (+ i 1)) ) ) ) (define (apply-contour-galaxy drawable channel contour) (let* ((contourtypes #(0 0 0 0 0 0 0 0 0 1 1)) (contourlengths #(6 6 10 14 18 10 18 18 10 256 256)) (contours #(#(0 0 127 255 255 0) #(0 255 127 0 255 255) #(0 64 94 74 150 115 179 179 191 255) #(0 0 5 125 6 125 48 148 79 179 107 217 130 255) #(0 0 33 8 64 38 97 102 128 166 158 209 191 235 222 247 255 255) #(0 0 28 71 87 166 194 240 255 255) #(0 0 33 110 64 237 97 240 128 138 158 33 191 5 222 99 255 255) #(0 0 33 74 64 219 97 186 128 0 158 176 191 201 222 3 255 255) #(3 255 54 99 97 107 179 153 252 0) #(0 5 9 13 16 19 22 25 27 29 30 32 33 34 35 36 38 39 40 41 43 44 46 47 48 49 50 51 52 53 54 55 55 56 56 57 57 58 58 59 59 59 60 60 60 61 61 61 61 62 62 62 62 62 63 63 63 63 63 63 64 64 64 64 64 71 75 78 81 84 86 89 91 93 95 96 98 99 101 102 103 104 105 107 107 108 110 111 112 113 114 115 116 117 118 119 119 120 121 121 122 123 123 123 124 124 124 125 125 125 125 125 125 125 126 126 126 126 126 126 126 125 125 125 125 125 125 125 125 130 134 137 141 145 148 151 153 156 158 160 162 163 165 166 167 168 170 171 171 172 173 174 175 176 177 178 178 179 180 181 181 182 183 183 184 184 185 185 186 186 187 187 188 188 189 189 189 189 190 190 190 190 191 191 191 191 191 191 191 191 191 191 193 194 196 197 198 200 201 203 204 205 207 208 209 211 212 213 214 215 217 218 219 220 220 221 222 222 223 223 224 224 224 224 224 223 223 222 222 221 221 220 219 218 217 216 215 214 213 212 211 210 209 208 206 205 204 203 202 200 199 198 197 196 194 194) #(0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124 126 127 125 123 121 119 117 115 113 111 109 107 105 103 101 99 97 95 93 91 89 87 85 83 81 79 77 75 73 71 69 67 65 63 61 59 57 55 53 51 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 128 126 124 122 120 118 116 114 112 110 108 106 104 102 100 98 96 94 92 90 88 86 84 82 80 78 76 74 72 70 68 66 64 62 60 58 56 54 52 50 48 46 44 42 40 38 36 34 32 30 28 26 24 22 20 18 16 14 12 10 8 6 4 2)))) (if (= (vector-ref contourtypes (- contour 1)) 0) (gimp-curves-spline drawable channel (vector-ref contourlengths (- contour 1)) (vector-ref contours (- contour 1))) (gimp-curves-explicit drawable channel (vector-ref contourlengths (- contour 1)) (vector-ref contours (- contour 1))) ) ) ) (define (apply-noise-galaxy img drawable srclayer noise) (let* ((drwwidth (car (gimp-drawable-width srclayer))) (drwheight (car (gimp-drawable-height srclayer))) (layername (car (gimp-drawable-get-name drawable))) (drwoffsets (gimp-drawable-offsets srclayer)) (srcmask (car (gimp-layer-get-mask srclayer))) (noiselayer (car (gimp-layer-new img drwwidth drwheight (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-noise") 100 0))) (blanklayer (car (gimp-layer-new img drwwidth drwheight (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-noise") 100 0)))) (add-over-layer img noiselayer srclayer) (add-over-layer img blanklayer noiselayer) (gimp-layer-set-offsets noiselayer (car drwoffsets) (cadr drwoffsets)) (gimp-layer-set-offsets blanklayer (car drwoffsets) (cadr drwoffsets)) (gimp-selection-all img) (gimp-palette-set-foreground '(0 0 0)) (gimp-edit-fill noiselayer 0) (gimp-edit-fill blanklayer 0) (gimp-palette-set-foreground '(255 255 255)) (gimp-selection-load srcmask) (gimp-edit-fill blanklayer 0) (plug-in-hsv-noise 1 img noiselayer 1 0 0 255) (gimp-layer-set-mode blanklayer 5) (gimp-layer-set-opacity blanklayer noise) (set! noiselayer (car (gimp-image-merge-down img blanklayer 0))) (set! blanklayer (car (gimp-layer-create-mask noiselayer 5))) (gimp-channel-combine-masks srcmask blanklayer 2 0 0) (gimp-image-remove-layer img noiselayer) ) ) (define (script-fu-layerfx-outer-glow-galaxy img drawable color opacity contour noise mode spread size knockout merge) (let* ((origfgcolor (car (gimp-palette-get-foreground))) (origselection (car (gimp-selection-save img))) (drwwidth (car (gimp-drawable-width drawable))) (drwheight (car (gimp-drawable-height drawable))) (drwoffsets (gimp-drawable-offsets drawable)) (layername (car (gimp-drawable-get-name drawable))) (lyrgrowamt (math-round-galaxy (* size 1.2))) (glowlayer (car (gimp-layer-new img (+ drwwidth (* lyrgrowamt 2)) (+ drwheight (* lyrgrowamt 2)) (cond ((= (car (gimp-image-base-type img)) 0) 1) ((= (car (gimp-image-base-type img)) 1) 3)) (string-append layername "-outerglow") opacity (get-blending-mode-galaxy mode)))) (glowmask 0) (alphaSel 0) (growamt (* (/ spread 100) size)) (steps (- size growamt)) (origmask 0) ) (add-under-layer-galaxy img glowlayer drawable) (gimp-layer-set-offsets glowlayer (- (car drwoffsets) lyrgrowamt) (- (cadr drwoffsets) lyrgrowamt)) (gimp-selection-all img) (gimp-palette-set-foreground color) (gimp-edit-fill glowlayer 0) (gimp-selection-none img) (set! glowmask (car (gimp-layer-create-mask glowlayer 1))) (gimp-layer-add-mask glowlayer glowmask) (gimp-selection-layer-alpha drawable) (if (> (car (gimp-layer-get-mask drawable)) -1) (gimp-selection-combine (car (gimp-layer-get-mask drawable)) 3) ) (set! alphaSel (car (gimp-selection-save img))) (draw-blurshape-galaxy img glowmask steps size alphaSel 0) (gimp-selection-none img) (if (> contour 0) (begin (apply-contour-galaxy glowmask 0 contour) (gimp-selection-load alphaSel) (gimp-selection-grow img size) (gimp-selection-invert img) (gimp-palette-set-foreground '(0 0 0)) (gimp-edit-fill glowmask 0) (gimp-selection-none img) ) ) (if (> noise 0) (apply-noise-galaxy img drawable glowlayer noise) ) (if (= knockout 1) (begin (gimp-palette-set-foreground '(0 0 0)) (gimp-selection-layer-alpha drawable) (gimp-edit-fill glowmask 0) ) ) (gimp-layer-remove-mask glowlayer 0) (gimp-selection-none img) (if (= merge 1) (begin (set! origmask (car (gimp-layer-get-mask drawable))) (if (> origmask -1) (gimp-layer-remove-mask drawable 0) ) (set! glowlayer (car (gimp-image-merge-down img drawable 0))) (gimp-drawable-set-name glowlayer layername) ) ) (gimp-palette-set-foreground origfgcolor) (gimp-selection-load origselection) (gimp-image-remove-channel img alphaSel) (gimp-image-remove-channel img origselection) (gimp-displays-flush) (gimp-selection-layer-alpha glowlayer) ) ) (define (script-fu-galaxy numArms holeSize innerRad armSize startAngle ArmCurve NumStars maxStar hSkew vSkew radSkew cloudColor seed ) (let* ( (imageSize (* 2 (+ innerRad armSize))) (centerPoint (/ imageSize 2.0)) (theImage (car (gimp-image-new imageSize imageSize RGB))) (baseLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Galaxy" 100 SCREEN-MODE))) (cloudLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Plasma" 100 OVERLAY-MODE))) (starLayer (car (gimp-layer-new theImage imageSize imageSize RGBA-IMAGE "Stars" 100 NORMAL-MODE))) (scratchLayer 0) (novaLayer 0) (area 0) (blackLayer 0) (testLayer 0) (diameter (* 2.0 holeSize)) (flag (* -1 ArmCurve)) (toothWidth (/ imageSize numArms)) (outerEdge (- (* 2.0 innerRad) diameter)) (centerX 0) (centerY 0) (rotAngle (* startAngle (/ *pi* 180.0))) (selection-bounds 0) (select-offset-x 0) (select-offset-y 0) (selection-width 0) (selection-height 0) (selArea 0.0) (x0 0) (x1 0) (x2 0) (x3 0) (y1 0) (y2 0) (pointArray (make-vector 8 0.0)) (starSize 0) (Star_X 0) (Star_Y 0) (squared 0) (starAngle 0.0) (starRad 0.0) (oldHeight 0) (oldWidth 0) (Wprime 0) (Hprime 0) (newHeight 0) (newWidth 0) (radAngle (* radSkew (/ *pi* 180.0))) (tanTheta (tan radAngle)) (size 0) (frameName "") (frameNum 0) ) (set! seed (if (number? seed) seed (realtime))) (srand seed) (gimp-image-add-layer theImage baseLayer 0) (gimp-context-set-foreground cloudColor) (gimp-context-set-background '(255 255 255)) (gimp-drawable-fill baseLayer BACKGROUND-FILL) (gimp-rect-select theImage 0 diameter imageSize outerEdge CHANNEL-OP-ADD FALSE 0) (while (< flag numArms) (begin (vector-set! pointArray 0 (* flag toothWidth)) (vector-set! pointArray 1 (+ outerEdge diameter)) (vector-set! pointArray 2 (* (+ ArmCurve 0.5 flag) toothWidth)) (vector-set! pointArray 3 (+ diameter outerEdge armSize)) (vector-set! pointArray 4 (* (+ 1 flag) toothWidth)) (vector-set! pointArray 5 (+ outerEdge diameter)) (vector-set! pointArray 6 (* flag toothWidth)) (vector-set! pointArray 7 (+ outerEdge diameter)) (gimp-free-select theImage 8 pointArray CHANNEL-OP-ADD 0 0 0) (set! flag (+ 1 flag)) ) ) (set! flag 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (gimp-selection-invert theImage) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage baseLayer '(255 255 255)) (gimp-selection-clear theImage) (plug-in-polar-coords RUN-NONINTERACTIVE theImage baseLayer 100 0 FALSE TRUE TRUE) (if (> startAngle 0) (gimp-drawable-transform-rotate-default baseLayer rotAngle TRUE centerPoint centerPoint TRUE TRANSFORM-RESIZE-ADJUST) ) (gimp-selection-layer-alpha baseLayer) (gimp-selection-grow theImage 2) (gimp-edit-clear baseLayer) (script-fu-distress-selection theImage baseLayer 127 8 4 2 0 0) (script-fu-distress-selection theImage baseLayer 127 8 4 2 0 0) (gimp-edit-bucket-fill baseLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (set! selection-bounds (gimp-selection-bounds theImage)) (set! select-offset-x (cadr selection-bounds)) (set! select-offset-y (caddr selection-bounds)) (set! selection-width (- (cadr (cddr selection-bounds)) select-offset-x)) (set! selection-height (- (caddr (cddr selection-bounds)) select-offset-y)) (set! selArea (* 0.25 *pi* selection-width selection-height)) (set! scratchLayer (car (gimp-layer-copy baseLayer FALSE))) (gimp-image-add-layer theImage scratchLayer 0) (plug-in-autocrop-layer RUN-NONINTERACTIVE theImage scratchLayer) (gimp-context-set-background '(0 0 0)) (gimp-context-set-foreground '(255 0 0)) (fg/bg-selection theImage scratchLayer) (gimp-selection-none theImage) (let ( (histogram (gimp-histogram scratchLayer HISTOGRAM-RED 128 255))) (set! area (/ (list-ref histogram 4) selArea)) ) (gimp-selection-none theImage) (gimp-image-remove-layer theImage scratchLayer) (set! blackLayer (car (gimp-layer-copy baseLayer FALSE))) (gimp-image-add-layer theImage blackLayer 0) (gimp-layer-set-mode blackLayer NORMAL-MODE) (gimp-context-set-background '(0 0 0)) (gimp-drawable-fill blackLayer BACKGROUND-FILL) (gimp-drawable-set-name blackLayer "Blackness of Space") (gimp-image-lower-layer-to-bottom theImage blackLayer) (set! size (min selection-width selection-height)) (set! squared (* size size)) (gimp-image-add-layer theImage starLayer 0) (gimp-drawable-set-name starLayer "Stars") (while (< flag (/ NumStars area)) (begin (set! starSize (+ 1 (rand maxStar))) (set! starRad (rand squared)) (set! starAngle (/ (* *pi* (rand 3600.0)) 1800.0)) (set! Star_X (+ select-offset-x (/ size 2.0) (/ (+ size (- (* starRad (sin starAngle)) starSize)) (* 2.0 size)))) (set! Star_Y (+ select-offset-x (/ size 2.0) (/ (+ size (- (* starRad (cos starAngle)) starSize)) (* 2.0 size)))) (gimp-rect-select theImage Star_X Star_Y starSize starSize CHANNEL-OP-REPLACE FALSE 0) (gimp-context-set-foreground (list (rand 256) (rand 256) (rand 256))) (gimp-edit-bucket-fill starLayer FG-BUCKET-FILL NORMAL-MODE 100 255 FALSE 0 0) (set! flag (+ 1 flag)) ) ) (gimp-selection-none theImage) (gimp-image-add-layer theImage cloudLayer 0) (plug-in-plasma RUN-NONINTERACTIVE theImage cloudLayer (rand 1000000000) 7) (gimp-desaturate cloudLayer) (plug-in-whirl-pinch RUN-NONINTERACTIVE theImage cloudLayer (* 45.0 ArmCurve) 0 1.0) (gimp-image-crop theImage (+ 40 selection-width) (+ 40 selection-height) (- select-offset-x 20) (- select-offset-y 20)) (plug-in-cubism RUN-NONINTERACTIVE theImage baseLayer (/ selection-height 100.0) 1.5 0) (plug-in-gauss-rle2 RUN-NONINTERACTIVE theImage baseLayer (/ selection-width 100.0) (/ selection-height 100.0)) (gimp-selection-layer-alpha baseLayer) (gimp-selection-invert theImage) (gimp-edit-clear starLayer) (gimp-selection-none theImage) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (set! oldHeight (car (gimp-drawable-height testLayer))) (set! oldWidth (car (gimp-drawable-width testLayer))) (set! centerX (/ oldWidth 2.0)) (set! centerY (/ oldHeight 2.0)) (set! newHeight (* vSkew oldHeight)) (set! newWidth (* hSkew oldWidth)) (if (= radSkew 0) (gimp-image-scale theImage newWidth newHeight) (begin (set! Wprime newWidth) (set! Hprime newHeight) (set! x0 (- centerX (* 0.5 (+ newWidth (/ newHeight tanTheta))))) (set! x1 (+ centerX (* 0.5 (- newWidth (/ newHeight tanTheta))))) (set! x2 (- centerX (* 0.5 (- newWidth (/ newHeight tanTheta))))) (set! x3 (+ centerX (* 0.5 (+ newWidth (/ newHeight tanTheta))))) (set! y1 (- centerY (* 0.5 oldHeight))) (set! y2 (+ centerY (* 0.5 oldHeight))) (gimp-drawable-transform-perspective-default testLayer x0 y1 x1 y1 x2 y2 x3 y2 TRUE TRANSFORM-RESIZE-ADJUST) (gimp-image-resize-to-layers theImage) ) ) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (plug-in-zealouscrop RUN-NONINTERACTIVE theImage testLayer) (set! oldHeight (car (gimp-drawable-height testLayer))) (set! oldWidth (car (gimp-drawable-width testLayer))) (set! novaLayer (car (gimp-layer-copy testLayer FALSE))) (gimp-image-add-layer theImage novaLayer 0) (gimp-drawable-set-name novaLayer "Nova") (gimp-layer-set-mode novaLayer NORMAL-MODE) (gimp-context-set-background '(0 0 0)) (gimp-drawable-fill novaLayer BACKGROUND-FILL) (plug-in-nova RUN-NONINTERACTIVE theImage novaLayer (/ oldWidth 2) (/ oldHeight 2) cloudColor (min 100 (min (/ oldWidth 10) (/ oldHeight 10))) 1 0) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage novaLayer '(0 0 0)) (gimp-selection-layer-alpha novaLayer) (gimp-selection-invert theImage) (gimp-edit-clear novaLayer) (gimp-selection-none theImage) (plug-in-gauss-rle2 RUN-NONINTERACTIVE theImage novaLayer 100 100.0) (gimp-image-flatten theImage) (set! testLayer (car (gimp-image-get-active-layer theImage))) (set! scratchLayer (car (gimp-layer-copy testLayer FALSE))) (gimp-image-add-layer theImage scratchLayer 0) (gimp-drawable-fill scratchLayer BACKGROUND-FILL) (gimp-image-lower-layer-to-bottom theImage scratchLayer) (plug-in-colortoalpha RUN-NONINTERACTIVE theImage testLayer '(0 0 0)) (gimp-selection-layer-alpha testLayer) (script-fu-layerfx-outer-glow-galaxy theImage testLayer cloudColor 50 0 0 0 0 5.0 FALSE FALSE) (set! novaLayer (car (gimp-image-get-active-layer theImage))) (plug-in-hsv-noise RUN-NONINTERACTIVE theImage scratchLayer 1 180 255 255) (gimp-selection-invert theImage) (gimp-edit-clear novaLayer) (gimp-edit-clear scratchLayer) (gimp-selection-none theImage) (gimp-image-flatten theImage) (set! baseLayer (car (gimp-image-get-active-layer theImage))) (set! frameName (string-append "Galaxy " (number->string seed frameNum))) (gimp-drawable-set-name baseLayer frameName) (gimp-display-new theImage) ) ) (script-fu-register "script-fu-galaxy" _"_Galaxy..." _"Creates a picture of a spiral galaxy..." "James Sambrook" "23 February 2011" "" "" SF-ADJUSTMENT _"Number of arms" '(8 4 36 1 5 0 0) SF-ADJUSTMENT _"Hole Size" '(25 0 100 1 10 0 0) SF-ADJUSTMENT _"Inner Radius" '(100 10 1000 1 10 0 0) SF-ADJUSTMENT _"Arm Size" '(500 10 1000 1 50 0 0) SF-ADJUSTMENT _"Angle first arm starts at" '(0 0 360 1 30 0 0) SF-ADJUSTMENT _"Arm Curvature" '(6 0 10 0.1 1 1 0) SF-ADJUSTMENT _"Number of Stars" '(200 0 3000 100 500 0 0) SF-ADJUSTMENT _"Maximum star size (in pixels)" '(3 1 10 1 1 0 0) SF-ADJUSTMENT _"Horizontal skew" '(1 0.1 5 0.1 1 1 0) SF-ADJUSTMENT _"Vertical skew" '(1 0.1 5 0.1 1 1 0) SF-ADJUSTMENT _"Skew Angle" '(60 -89 89 1 10 0 0) SF-COLOR _"Galaxy color" '(100 149 237) SF-VALUE _"Random seed" "random" ) (script-fu-menu-register "script-fu-galaxy" "<Image>/Filters/SambrookJM/")
767cf8099fe572e613c4af09687786a1ff765d4eaf152125eacfce26b36716d7
rmculpepper/gamble
intro-enum.rkt
Copyright ( c ) 2014 Released under the terms of the 2 - clause BSD license . ;; See the file COPYRIGHT for details. #lang gamble sum - n - flips : (define (sum-n-flips n) (if (zero? n) 0 (+ (bernoulli) (sum-n-flips (sub1 n))))) (printf "enumerate (sum-n-flips 10)\n") (enumerate (sum-n-flips 10)) ;; ------------------------------------------------------------ ;; geom : Prob -> Nat (define (geom p) (if (flip p) 0 (add1 (geom p)))) (printf "enumerate (geom 1/2) with limit 1e-3\n") (enumerate #:limit 1e-3 (geom 1/2)) (printf "enumerate (geom 1/2) with limit 1e-3, unnormalized\n") (enumerate #:limit 1e-3 #:normalize? #f (geom 1/2)) (newline) ;; ------------------------------------------------------------ (printf "enumerate 2 flips w/ at least one true\n") (enumerate (define A (flip)) (define B (flip)) (observe/fail (or A B)) A) (printf "lazy enumeration of infinite dists w/ limit\n") (enumerate #:limit 1e-3 (define A (geom 1/2)) (observe/fail (< 10 A 20)) A) (newline) ;; ------------------------------------------------------------ (printf "drunk-flip example from EPP\n") (enumerate #:normalize? #f (define (drunk-flip) (if (flip 0.9) (fail) ;; dropped the coin (flip .5))) (define (drunk-andflips n) (cond [(zero? n) #t] [else (and (drunk-flip) (drunk-andflips (sub1 n)))])) (drunk-andflips 10)) (newline) ;; ------------------------------------------------------------ ;; reify/reflect, aka enumerate/sample (define (xor a b) (and (or a b) (not (and a b)))) (define (xor-flips n) (let loop ([n n]) (if (zero? n) #f (xor (flip) (loop (sub1 n)))))) (printf "naive xor-flips is slow (exponential)\n") (time (enumerate (xor-flips 12))) (define (xor-flips* n) (let loop ([n n]) (if (zero? n) #f (let ([r (sample (enumerate (loop (sub1 n))))]) (xor (flip) r))))) (printf "enumerate then sample is faster (linear)\n") (time (enumerate (xor-flips* 120))) (newline) ;; ------------------------------------------------------------ mem generalizes EPP letlazy (define (flips-all-true n) (enumerate (define Flips (for/list ([i n]) (flip))) (andmap values Flips))) (printf "slow to generate all flips, despite many being unused\n") (time (flips-all-true 12)) (define (flips-all-true* n) (enumerate (define LFlips (for/list ([i n]) (mem flip))) (andmap (lambda (p) (p)) LFlips))) (printf "do flips lazily; only force when needed\n") (time (flips-all-true* 12)) (newline)
null
https://raw.githubusercontent.com/rmculpepper/gamble/a5231e2eb3dc0721eedc63a77ee6d9333846323e/gamble/examples/intro-enum.rkt
racket
See the file COPYRIGHT for details. ------------------------------------------------------------ geom : Prob -> Nat ------------------------------------------------------------ ------------------------------------------------------------ dropped the coin ------------------------------------------------------------ reify/reflect, aka enumerate/sample ------------------------------------------------------------
Copyright ( c ) 2014 Released under the terms of the 2 - clause BSD license . #lang gamble sum - n - flips : (define (sum-n-flips n) (if (zero? n) 0 (+ (bernoulli) (sum-n-flips (sub1 n))))) (printf "enumerate (sum-n-flips 10)\n") (enumerate (sum-n-flips 10)) (define (geom p) (if (flip p) 0 (add1 (geom p)))) (printf "enumerate (geom 1/2) with limit 1e-3\n") (enumerate #:limit 1e-3 (geom 1/2)) (printf "enumerate (geom 1/2) with limit 1e-3, unnormalized\n") (enumerate #:limit 1e-3 #:normalize? #f (geom 1/2)) (newline) (printf "enumerate 2 flips w/ at least one true\n") (enumerate (define A (flip)) (define B (flip)) (observe/fail (or A B)) A) (printf "lazy enumeration of infinite dists w/ limit\n") (enumerate #:limit 1e-3 (define A (geom 1/2)) (observe/fail (< 10 A 20)) A) (newline) (printf "drunk-flip example from EPP\n") (enumerate #:normalize? #f (define (drunk-flip) (if (flip 0.9) (flip .5))) (define (drunk-andflips n) (cond [(zero? n) #t] [else (and (drunk-flip) (drunk-andflips (sub1 n)))])) (drunk-andflips 10)) (newline) (define (xor a b) (and (or a b) (not (and a b)))) (define (xor-flips n) (let loop ([n n]) (if (zero? n) #f (xor (flip) (loop (sub1 n)))))) (printf "naive xor-flips is slow (exponential)\n") (time (enumerate (xor-flips 12))) (define (xor-flips* n) (let loop ([n n]) (if (zero? n) #f (let ([r (sample (enumerate (loop (sub1 n))))]) (xor (flip) r))))) (printf "enumerate then sample is faster (linear)\n") (time (enumerate (xor-flips* 120))) (newline) mem generalizes EPP letlazy (define (flips-all-true n) (enumerate (define Flips (for/list ([i n]) (flip))) (andmap values Flips))) (printf "slow to generate all flips, despite many being unused\n") (time (flips-all-true 12)) (define (flips-all-true* n) (enumerate (define LFlips (for/list ([i n]) (mem flip))) (andmap (lambda (p) (p)) LFlips))) (printf "do flips lazily; only force when needed\n") (time (flips-all-true* 12)) (newline)
48ec6ee5b922351ae1d8e843e40adbff266f04a7746bd145789bafd91aa82077
hexlet-basics/exercises-clojure
index.clj
(ns index) ;BEGIN (defn triple [x] (list x x x)) ;END
null
https://raw.githubusercontent.com/hexlet-basics/exercises-clojure/ede14102d01f9ef736e0af811cd92f5b22a83bc2/modules/25-lists/10-intro/index.clj
clojure
BEGIN END
(ns index) (defn triple [x] (list x x x))
4d481350ac6264c9db84a4d4be2a47eb1ef079787ed7749ce51d16e476ab1eed
jwiegley/notes
Ertes.hs
# LANGUAGE DeriveFunctor # # LANGUAGE ExistentialQuantification # module Ertes where data Stream f m r = Step (f (Stream f m r)) | Delay (m (Stream f m r)) | Return r data Step s a r = Done r | Skip s | Yield s a deriving Functor data Stream' a m r = forall s. Stream' (s -> m (Step s a r)) s
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Ertes.hs
haskell
# LANGUAGE DeriveFunctor # # LANGUAGE ExistentialQuantification # module Ertes where data Stream f m r = Step (f (Stream f m r)) | Delay (m (Stream f m r)) | Return r data Step s a r = Done r | Skip s | Yield s a deriving Functor data Stream' a m r = forall s. Stream' (s -> m (Step s a r)) s
c42e4f6697400466cf31aa54436511a8b71a5130401191908b38b1c05f4e1612
oral-health-and-disease-ontologies/ohd-ontology
data-resource-classes.lisp
;; this is the most general level class for data sources, resultsets, records, and iterators ;; all the classes inherit from this class (defclass data-resource () ())
null
https://raw.githubusercontent.com/oral-health-and-disease-ontologies/ohd-ontology/ba3f502b86487c8ba5fa04ff8ba33312a1679570/src/vdw-translation/development-library/classes/data-resource-classes.lisp
lisp
this is the most general level class for data sources, resultsets, records, and iterators all the classes inherit from this class
(defclass data-resource () ())
c664548dddf0014c163301f1d39731167ec8780463e0d5383e60962157b531a3
nikita-volkov/rebase
IO.hs
module Rebase.GHC.Conc.IO ( module GHC.Conc.IO ) where import GHC.Conc.IO
null
https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/GHC/Conc/IO.hs
haskell
module Rebase.GHC.Conc.IO ( module GHC.Conc.IO ) where import GHC.Conc.IO
3f5af23c573e9fe72760e55940453149745d2c0472e314c10f5c581957b035a3
ZeusWPI/contests
cheated.hs
import Control.Applicative ((<$>)) import Control.Arrow ((>>>), (***)) import Control.Monad (replicateM_) import Data.Ord (comparing) import Text.Printf (printf) type Student = (Int, Int) data Pair = Pair {unPair :: (Student, Student)} deriving (Eq) instance Ord Pair where compare = comparing diff diff :: Pair -> Int diff = unPair >>> snd *** snd >>> uncurry (-) >>> abs cheated :: [Student] -> Maybe Pair cheated students = case map Pair (zip students $ drop 1 students) of [] -> Nothing pairs -> Just $ minimum pairs main :: IO () main = do cases <- readLn replicateM_ cases $ do scores <- map read . drop 1 . words <$> getLine putStrLn $ case cheated (zip [1 ..] scores) of Nothing -> "spieken kon niet" Just pair@(Pair ((s1, _), (s2, _))) | diff pair > 0 -> printf "%d en %d zijn verdacht" s1 s2 | otherwise -> printf "%d en %d zijn zwaar verdacht" s1 s2
null
https://raw.githubusercontent.com/ZeusWPI/contests/d78aec91be3ce32a436d160cd7a13825d36bbf3a/2012-vpw/cheated.hs
haskell
import Control.Applicative ((<$>)) import Control.Arrow ((>>>), (***)) import Control.Monad (replicateM_) import Data.Ord (comparing) import Text.Printf (printf) type Student = (Int, Int) data Pair = Pair {unPair :: (Student, Student)} deriving (Eq) instance Ord Pair where compare = comparing diff diff :: Pair -> Int diff = unPair >>> snd *** snd >>> uncurry (-) >>> abs cheated :: [Student] -> Maybe Pair cheated students = case map Pair (zip students $ drop 1 students) of [] -> Nothing pairs -> Just $ minimum pairs main :: IO () main = do cases <- readLn replicateM_ cases $ do scores <- map read . drop 1 . words <$> getLine putStrLn $ case cheated (zip [1 ..] scores) of Nothing -> "spieken kon niet" Just pair@(Pair ((s1, _), (s2, _))) | diff pair > 0 -> printf "%d en %d zijn verdacht" s1 s2 | otherwise -> printf "%d en %d zijn zwaar verdacht" s1 s2
c6fa71045b5c6f6330dec3c606b4071c2825156fb49321b2abf8ce515e129bef
janestreet/bonsai
single_factor.mli
* @inline
null
https://raw.githubusercontent.com/janestreet/bonsai/c202b961f41e20e0b735c4e33c2bbac57a590941/web_ui/multi_select/src/single_factor.mli
ocaml
* @inline
5e3db2ae18b291866b94ca88420f9ca4ac7ddfb1ef85989294ac293c1140d5b5
oliyh/re-learn
views.cljs
(ns re-learn.views (:require [goog.style :as gs] [goog.string :as gstring] [re-frame.core :as re-frame] [re-learn.model :as model] [re-learn.dom :refer [->absolute-bounds ->dimensions]] [reagent.impl.component :as rc] [dommy.core :as dom] [reagent.core :as r])) (defn- container-position-style [dom-node position] (let [{:keys [top left height width] :as bounds} (->absolute-bounds dom-node)] {:position "absolute" :top top :left left :height 0 :width 0})) (def arrow-width 10) (defn- bubble-position-style [dom-node position] (let [{:keys [height width] :as bounds} (->dimensions dom-node)] (cond-> {} (or (nil? bounds) (= :unattached position)) (assoc :position "fixed" :left "50%" :top "20%" :transform (str "translate(-50%, -50%)")) (= :top position) (assoc :top -10 :left (/ width 2) :transform (str "translate(-50%, -100%)")) (= :right position) (assoc :top (/ height 2) :transform "translateY(-50%)" :left (+ width arrow-width)) (= :left position) (assoc :top (/ height 2) :left (- arrow-width) :transform "translate(-100%, -50%)") (= :bottom position) (assoc :top (+ height arrow-width) :left (/ width 2) :transform (str "translateX(-50%)")) (= :bottom-left position) (assoc :top (+ height (/ arrow-width 2)) :left (- (/ arrow-width 2)) :transform (str "translateX(-100%)")) (= :bottom-right position) (assoc :top (+ height (/ arrow-width 2)) :left (+ width (/ arrow-width 2))) (= :top-left position) (assoc :top (- arrow-width) :left (- (/ arrow-width 2)) :transform (str "translate(-100%, -100%)")) (= :top-right position) (assoc :top (- arrow-width) :left (+ width (/ arrow-width 2)) :transform (str "translateY(-100%)"))))) (defn- lesson-bubble [{:keys [id description dom-node position attach continue] :as lesson}] (let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] [:div {:id (name id) :class (str "lesson " (name position)) :style (bubble-position-style dom-node position)} (if (string? description) [:p description] description) (when-not continue [:button.lesson-learned {:style {:float "right"} :on-click #(re-frame/dispatch [::model/lesson-learned id])} (rand-nth ["Sweet!" "Cool!" "OK" "Got it"])])])) (defn- extract-lesson [component] (second (rc/get-argv component))) (def lesson-view (with-meta (fn [{:keys [id dom-node position attach] :as lesson}] (when lesson (let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] [:div {:id (str (name id) "-container") :class (str "lesson-container " (name position)) :style (container-position-style dom-node position)} [lesson-bubble lesson]]))) {:component-did-update #(re-frame/dispatch [::model/prepare-lesson (:id (extract-lesson %))])})) (defn lesson-context [context] (when @context [:div.context-container [:div.tutorial-description [:h2 (get-in @context [:tutorial :name])] [:p (get-in @context [:tutorial :description])]] (when (pos? (get-in @context [:completion :total])) [:div.lesson-navigation [:a {:on-click #(re-frame/dispatch [::model/lesson-unlearned (get-in @context [:previous-lesson :id])])} (gstring/unescapeEntities "&#10096;")] [:span (str (get-in @context [:completion :learned]) "/" (get-in @context [:completion :total]))] (let [lesson (get-in @context [:current-lesson])] [:a {:class (when (:continue lesson) "disabled") :on-click #(re-frame/dispatch [::model/lesson-learned (:id lesson)])} (gstring/unescapeEntities "&#10097;")])]) [:div.context-controls [:a {:on-click #(re-frame/dispatch [::model/skip-tutorial (get-in @context [:tutorial :id])])} "SKIP " (gstring/unescapeEntities "&#10219")]] (when (pos? (get-in @context [:completion :total])) [:div.tutorial-completion [:div.tutorial-progress [:div.tutorial-progress-bar {:style {:width (str (* 100 (get-in @context [:completion :ratio])) "%")}}]] [:div.tutorial-progress-steps (for [{:keys [id]} (:learned @context)] ^{:key (str "progress" id)} [:div.progress-step.complete [:div]]) (for [{:keys [id]} (:to-learn @context)] ^{:key (str "progress" id)} [:div.progress-step.incomplete [:div]])]])])) (defn- help-mode [] (let [selected-lesson-id (re-frame/subscribe [::model/highlighted-lesson-id]) all-lessons (re-frame/subscribe [::model/all-lessons])] (fn [] [:div (doall (for [{:keys [id description dom-node position attach continue] :as lesson} @all-lessons :let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] :when (not= :unattached position) :let [bounds (->absolute-bounds dom-node)]] ^{:key id} [:div {:id (str (name id) "-container") :class (str "help-outline " (name position)) :on-mouse-over #(re-frame/dispatch [::model/highlighted-lesson id]) :on-mouse-out #(re-frame/dispatch [::model/highlighted-lesson nil]) :style bounds} (when (= id @selected-lesson-id) [lesson-bubble (assoc lesson :continue true)])])) [:div.context-container [:h2 "Help mode"] [:p "Move your mouse over any highlighted element to learn about it"] [:div.context-controls [:a {:on-click #(re-frame/dispatch [::model/help-mode false])} "CLOSE " (gstring/unescapeEntities "&#10060")]]]]))) (defn all-lessons [] (let [current-lesson (re-frame/subscribe [::model/current-lesson]) help-mode? (re-frame/subscribe [::model/help-mode?])] (fn [] (if @help-mode? [help-mode] [lesson-view current-lesson])))) (defn tutorial "Root view for displaying unlearned tutorials on the page. The :context? key allows you to turn on the context view which shows progress through the tutorial at the bottom of the screen. The :auto-accept? key when false shows a notification that lessons are available allowing the user to choose to start one, rather than starting the tutorial straight away when true (legacy behaviour)" [{:keys [context? auto-accept?] :or {context? false auto-accept? false}}] (let [tutorial (re-frame/subscribe [::model/current-tutorial]) help-mode? (re-frame/subscribe [::model/help-mode?])] (fn [] (cond @help-mode? [help-mode] (and (false? auto-accept?) (false? (:accepted? @tutorial))) [:div.toast "There is a tutorial available" [:button.accept {:on-click #(re-frame/dispatch [::model/accept-tutorial (get-in @tutorial [:tutorial :id])])} "Start"] [:button.dismiss {:on-click #(re-frame/dispatch [::model/skip-tutorial (get-in @tutorial [:tutorial :id])])} "Dismiss"]] (or auto-accept? (:accepted? @tutorial)) [:div [lesson-view (:current-lesson @tutorial)] (when context? [lesson-context tutorial])]))))
null
https://raw.githubusercontent.com/oliyh/re-learn/8fb3307554debb28b6545a4d38fa3b1ccfa43419/src/re_learn/views.cljs
clojure
(ns re-learn.views (:require [goog.style :as gs] [goog.string :as gstring] [re-frame.core :as re-frame] [re-learn.model :as model] [re-learn.dom :refer [->absolute-bounds ->dimensions]] [reagent.impl.component :as rc] [dommy.core :as dom] [reagent.core :as r])) (defn- container-position-style [dom-node position] (let [{:keys [top left height width] :as bounds} (->absolute-bounds dom-node)] {:position "absolute" :top top :left left :height 0 :width 0})) (def arrow-width 10) (defn- bubble-position-style [dom-node position] (let [{:keys [height width] :as bounds} (->dimensions dom-node)] (cond-> {} (or (nil? bounds) (= :unattached position)) (assoc :position "fixed" :left "50%" :top "20%" :transform (str "translate(-50%, -50%)")) (= :top position) (assoc :top -10 :left (/ width 2) :transform (str "translate(-50%, -100%)")) (= :right position) (assoc :top (/ height 2) :transform "translateY(-50%)" :left (+ width arrow-width)) (= :left position) (assoc :top (/ height 2) :left (- arrow-width) :transform "translate(-100%, -50%)") (= :bottom position) (assoc :top (+ height arrow-width) :left (/ width 2) :transform (str "translateX(-50%)")) (= :bottom-left position) (assoc :top (+ height (/ arrow-width 2)) :left (- (/ arrow-width 2)) :transform (str "translateX(-100%)")) (= :bottom-right position) (assoc :top (+ height (/ arrow-width 2)) :left (+ width (/ arrow-width 2))) (= :top-left position) (assoc :top (- arrow-width) :left (- (/ arrow-width 2)) :transform (str "translate(-100%, -100%)")) (= :top-right position) (assoc :top (- arrow-width) :left (+ width (/ arrow-width 2)) :transform (str "translateY(-100%)"))))) (defn- lesson-bubble [{:keys [id description dom-node position attach continue] :as lesson}] (let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] [:div {:id (name id) :class (str "lesson " (name position)) :style (bubble-position-style dom-node position)} (if (string? description) [:p description] description) (when-not continue [:button.lesson-learned {:style {:float "right"} :on-click #(re-frame/dispatch [::model/lesson-learned id])} (rand-nth ["Sweet!" "Cool!" "OK" "Got it"])])])) (defn- extract-lesson [component] (second (rc/get-argv component))) (def lesson-view (with-meta (fn [{:keys [id dom-node position attach] :as lesson}] (when lesson (let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] [:div {:id (str (name id) "-container") :class (str "lesson-container " (name position)) :style (container-position-style dom-node position)} [lesson-bubble lesson]]))) {:component-did-update #(re-frame/dispatch [::model/prepare-lesson (:id (extract-lesson %))])})) (defn lesson-context [context] (when @context [:div.context-container [:div.tutorial-description [:h2 (get-in @context [:tutorial :name])] [:p (get-in @context [:tutorial :description])]] (when (pos? (get-in @context [:completion :total])) [:div.lesson-navigation [:a {:on-click #(re-frame/dispatch [::model/lesson-unlearned (get-in @context [:previous-lesson :id])])} (gstring/unescapeEntities "&#10096;")] [:span (str (get-in @context [:completion :learned]) "/" (get-in @context [:completion :total]))] (let [lesson (get-in @context [:current-lesson])] [:a {:class (when (:continue lesson) "disabled") :on-click #(re-frame/dispatch [::model/lesson-learned (:id lesson)])} (gstring/unescapeEntities "&#10097;")])]) [:div.context-controls [:a {:on-click #(re-frame/dispatch [::model/skip-tutorial (get-in @context [:tutorial :id])])} "SKIP " (gstring/unescapeEntities "&#10219")]] (when (pos? (get-in @context [:completion :total])) [:div.tutorial-completion [:div.tutorial-progress [:div.tutorial-progress-bar {:style {:width (str (* 100 (get-in @context [:completion :ratio])) "%")}}]] [:div.tutorial-progress-steps (for [{:keys [id]} (:learned @context)] ^{:key (str "progress" id)} [:div.progress-step.complete [:div]]) (for [{:keys [id]} (:to-learn @context)] ^{:key (str "progress" id)} [:div.progress-step.incomplete [:div]])]])])) (defn- help-mode [] (let [selected-lesson-id (re-frame/subscribe [::model/highlighted-lesson-id]) all-lessons (re-frame/subscribe [::model/all-lessons])] (fn [] [:div (doall (for [{:keys [id description dom-node position attach continue] :as lesson} @all-lessons :let [dom-node (if attach (dom/sel1 attach) dom-node) position (if dom-node position :unattached)] :when (not= :unattached position) :let [bounds (->absolute-bounds dom-node)]] ^{:key id} [:div {:id (str (name id) "-container") :class (str "help-outline " (name position)) :on-mouse-over #(re-frame/dispatch [::model/highlighted-lesson id]) :on-mouse-out #(re-frame/dispatch [::model/highlighted-lesson nil]) :style bounds} (when (= id @selected-lesson-id) [lesson-bubble (assoc lesson :continue true)])])) [:div.context-container [:h2 "Help mode"] [:p "Move your mouse over any highlighted element to learn about it"] [:div.context-controls [:a {:on-click #(re-frame/dispatch [::model/help-mode false])} "CLOSE " (gstring/unescapeEntities "&#10060")]]]]))) (defn all-lessons [] (let [current-lesson (re-frame/subscribe [::model/current-lesson]) help-mode? (re-frame/subscribe [::model/help-mode?])] (fn [] (if @help-mode? [help-mode] [lesson-view current-lesson])))) (defn tutorial "Root view for displaying unlearned tutorials on the page. The :context? key allows you to turn on the context view which shows progress through the tutorial at the bottom of the screen. The :auto-accept? key when false shows a notification that lessons are available allowing the user to choose to start one, rather than starting the tutorial straight away when true (legacy behaviour)" [{:keys [context? auto-accept?] :or {context? false auto-accept? false}}] (let [tutorial (re-frame/subscribe [::model/current-tutorial]) help-mode? (re-frame/subscribe [::model/help-mode?])] (fn [] (cond @help-mode? [help-mode] (and (false? auto-accept?) (false? (:accepted? @tutorial))) [:div.toast "There is a tutorial available" [:button.accept {:on-click #(re-frame/dispatch [::model/accept-tutorial (get-in @tutorial [:tutorial :id])])} "Start"] [:button.dismiss {:on-click #(re-frame/dispatch [::model/skip-tutorial (get-in @tutorial [:tutorial :id])])} "Dismiss"]] (or auto-accept? (:accepted? @tutorial)) [:div [lesson-view (:current-lesson @tutorial)] (when context? [lesson-context tutorial])]))))
827f078ac525e3aa03ee3789441104a47a7e34c8e063fcc2fa216bcc50f2674f
glaebhoerl/simplecompiler
Type.hs
module Type (TypeInfo (..), Type (..), TypedName, Error (..), checkTypes, typeOf, ValidationError (..), validateTypes) where import MyPrelude import qualified Data.Map as Map import qualified Data.Text as Text import qualified Pretty as P import qualified AST import AST (AST) import qualified Name import Name (Name, NameWith (NameWith), ResolvedName) ------------------------------------------------------------------------ types data TypeInfo = IsType Type -- stored for names of types in type annotations | HasType Type -- stored for value-level names deriving (Generic, Eq, Show) data Type = Int | Bool | Text | Unit | Function [Type] Type deriving (Generic, Eq, Show) type TypedName = NameWith TypeInfo typeOf :: AST.Expression metadata TypedName -> Type typeOf = \case AST.Named name -> case Name.info name of HasType ty -> ty IsType _ -> bug "Expression which IsType in typed AST" AST.NumberLiteral _ -> Int AST.TextLiteral _ -> Text AST.UnaryOperator op _ -> case op of Not -> Bool Negate -> Int AST.BinaryOperator _ op _ -> case op of ArithmeticOperator _ -> Int ComparisonOperator _ -> Bool LogicalOperator _ -> Bool AST.Call fn _ -> case typeOf (nodeWithout fn) of Function _ returnType -> returnType _ -> bug "Call of non-function in typed AST" ------------------------------------------------------------------------ pretty-printing instance P.Render TypeInfo where listSeparator = ", " render ty = P.note (P.Identifier (P.IdentInfo (typeText ty) P.Use P.Type True)) (P.pretty (typeText ty)) where typeText = \case HasType (Function argumentTypes returnType) -> "function(" ++ Text.intercalate ", " (map (typeText . HasType) argumentTypes) ++ ")" ++ case returnType of Unit -> "" otherType -> " returns " ++ typeText (HasType otherType) HasType otherType -> showText otherType IsType _ -> "Type" instance P.Render Type where listSeparator = ", " render = P.render . HasType instance AST.RenderName TypedName where renderName defOrUse (NameWith name ty) = maybeAppendTypeAnnotation (fmap setTypeInNote (AST.renderName defOrUse name)) where maybeAppendTypeAnnotation binding = binding ++ (if defOrUse == P.Definition then (P.colon ++ " " ++ P.render ty) else "") setTypeInNote = \case P.Identifier info -> P.Identifier (info { P.identType }) _ -> bug "Pretty-printing annotation on ResolvedName was not Identifier" identType = case ty of IsType _ -> P.Type HasType hasType -> case hasType of Int -> P.Int Bool -> P.Bool Text -> P.Text Unit -> P.Unit Function _ _ -> P.Function ------------------------------------------------------------------------ typechecker frontend TODO more info in here ? data Error = TypeMismatch Expected TypeInfo | WrongNumberOfArguments -- (can we move this into Expected?) | FunctionWithoutReturn | AssignToLet | LiteralOutOfRange deriving (Generic, Show) data Expected = Expected Type | ExpectedFunction | ExpectedExpression | ExpectedType deriving (Generic, Show) class (forall metadata. Monad (m metadata)) => TypeCheckM m where records ` HasType ` ; for now , the only things which are ` IsType ` are builtins lookupType :: ResolvedName -> m metadata TypeInfo reportError :: Error -> m metadata a enterMetadata :: metadata -> m metadata a -> m metadata a TODO deduplicate ? enterMetadataOf :: TypeCheckM m => NodeWith node metadata name -> m metadata a -> m metadata a enterMetadataOf = enterMetadata . nodeMetadata class CheckTypeOf node where inferType :: TypeCheckM m => node metadata ResolvedName -> m metadata TypeInfo checkUnit :: TypeCheckM m => node metadata ResolvedName -> m metadata () inferType node = do checkUnit node return (HasType Unit) checkUnit = checkType Unit checkType :: (TypeCheckM m, CheckTypeOf node) => Type -> node metadata ResolvedName -> m metadata () checkType expected node = do actual <- inferType node when (actual != HasType expected) do reportError (TypeMismatch (Expected expected) actual) instance CheckTypeOf AST.Expression where inferType = \case AST.Named name -> do nameType <- lookupType name case nameType of HasType _ -> return nameType IsType _ -> reportError (TypeMismatch ExpectedExpression nameType) AST.NumberLiteral int -> do when (int > fromIntegral (maxBound :: Int64) || int < fromIntegral (minBound :: Int64)) do reportError LiteralOutOfRange return (HasType Int) AST.TextLiteral _ -> do return (HasType Text) AST.UnaryOperator op expr -> do let type' = case op of Not -> Bool Negate -> Int checkType type' expr return (HasType type') AST.BinaryOperator expr1 op expr2 -> do let (inType, outType) = case op of ArithmeticOperator _ -> (Int, Int) ComparisonOperator _ -> (Int, Bool) LogicalOperator _ -> (Bool, Bool) checkType inType expr1 checkType inType expr2 return (HasType outType) AST.Call function arguments -> do functionType <- inferType function case functionType of HasType (Function argumentTypes returnType) -> do when (length argumentTypes != length arguments) do reportError WrongNumberOfArguments zipWithM checkType argumentTypes arguments return (HasType returnType) _ -> do reportError (TypeMismatch ExpectedFunction functionType) instance CheckTypeOf AST.Statement where checkUnit = \case AST.Binding _ name expr -> do inferred <- inferType expr case inferred of HasType hasType -> recordType hasType name IsType _ -> reportError (TypeMismatch ExpectedExpression inferred) AST.Assign name expr -> do when (Name.info name != AST.Var) do reportError AssignToLet nameType <- lookupType name case nameType of HasType hasType -> checkType hasType expr IsType _ -> reportError (TypeMismatch ExpectedExpression nameType) AST.IfThen expr block -> do checkType Bool expr checkUnit block AST.IfThenElse expr block1 block2 -> do checkType Bool expr checkUnit block1 checkUnit block2 AST.Forever block -> do checkBlock Unit block AST.While expr block -> do checkType Bool expr checkBlock Unit block AST.Return target maybeExpr -> do returnType <- lookupType target mapM_ (checkType (assert (match @"HasType" returnType))) maybeExpr when (maybeExpr == Nothing) do checkType Unit (AST.Named target) -- HACK? AST.Break target -> do breakType <- lookupType target assertEqM breakType (HasType Unit) AST.Expression expr -> do unused (inferType expr) instance CheckTypeOf AST.Block where checkUnit AST.Block { AST.statements } = do mapM_ checkUnit statements checkBlock :: TypeCheckM m => Type -> NodeWith AST.Block metadata ResolvedName -> m metadata () checkBlock exitTargetType block = do recordType exitTargetType (assert (AST.exitTarget (nodeWithout block))) checkUnit block resolveAsType :: TypeCheckM m => NodeWith AST.Type metadata ResolvedName -> m metadata Type resolveAsType typeNode = enterMetadataOf typeNode do resolved <- inferType (nodeWithout typeNode) return (msgAssert "type annotation resolved to a non-type" (match @"IsType" resolved)) instance CheckTypeOf AST.Function where checkUnit AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do argumentTypes <- forM arguments \argument -> do enterMetadataOf argument do let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument resolvedType <- resolveAsType argumentType recordType resolvedType argumentName return resolvedType maybeReturnType <- mapM resolveAsType returns let returnType = fromMaybe Unit maybeReturnType recordType (Function argumentTypes returnType) functionName checkBlock returnType body when (returnType != Unit && not (definitelyReturns (controlFlow body))) do reportError FunctionWithoutReturn instance CheckTypeOf AST.Type where inferType = \case AST.NamedType name -> do nameType <- lookupType name case nameType of IsType _ -> return nameType HasType _ -> reportError (TypeMismatch ExpectedType nameType) AST.FunctionType parameters returns -> do resolvedParameters <- mapM resolveAsType parameters resolvedReturns <- resolveAsType returns return (IsType (Function resolvedParameters resolvedReturns)) instance CheckTypeOf node => CheckTypeOf (NodeWith node) where inferType node = do enterMetadataOf node do inferType (nodeWithout node) data ControlFlow = ControlFlow { definitelyReturns :: Bool, -- guaranteed divergence also counts as "returning" potentiallyBreaks :: Bool } instance Semigroup ControlFlow where prev <> next = ControlFlow returns breaks where returns = definitelyReturns prev || (not (potentiallyBreaks prev) && definitelyReturns next) breaks = potentiallyBreaks prev || (not (definitelyReturns prev) && potentiallyBreaks next) instance Monoid ControlFlow where mempty = ControlFlow False False class CheckControlFlow node where controlFlow :: Eq name => node metadata name -> ControlFlow instance CheckControlFlow AST.Block where controlFlow = mconcat . map controlFlow . AST.statements instance CheckControlFlow AST.Statement where controlFlow = \case AST.Return {} -> ControlFlow True False AST.Break {} -> ControlFlow False True AST.Binding {} -> ControlFlow False False AST.Assign {} -> ControlFlow False False AST.Expression {} -> ControlFlow False False AST.While {} -> ControlFlow False False -- loops can't currently break out of the /outer/ context AST.IfThen _ block -> ControlFlow False (potentiallyBreaks (controlFlow block)) AST.IfThenElse _ block1 block2 -> ControlFlow (returns1 && returns2) (breaks1 || breaks2) where ControlFlow returns1 breaks1 = controlFlow block1 ControlFlow returns2 breaks2 = controlFlow block2 AST.Forever blockWith -> ControlFlow (noBreaks || doesReturn) False where -- we can check whether there is a `break` by whether the `exitTarget` is ever referred to -- (we make use of the Foldable instances for the AST) -- we have to make sure to leave out the `exitTarget` itself! noBreaks = not (any (== (assert (AST.exitTarget block))) (block { AST.exitTarget = Nothing })) doesReturn = definitelyReturns (controlFlow block) block = nodeWithout blockWith instance CheckControlFlow node => CheckControlFlow (NodeWith node) where controlFlow = controlFlow . nodeWithout ---------------------------------------------------------------------- typechecker backend newtype TypeCheck metadata a = TypeCheck { runTypeCheck :: (ExceptT Error) (State (TypeCheckState metadata)) a } deriving (Functor, Applicative, Monad, MonadState (TypeCheckState metadata), MonadError Error) data TypeCheckState metadata = TypeCheckState { types :: Map Name TypeInfo, metadata :: [metadata] } deriving (Generic, Show) checkTypes :: AST metadata ResolvedName -> Either (With metadata Error) (AST metadata TypedName) checkTypes ast = pipeline ast where pipeline = constructResult . runState initialState . runExceptT . runTypeCheck . mapM_ checkUnit initialState = TypeCheckState (Map.fromList builtinNames) [] builtinNames = map (\builtinName -> (Name.BuiltinName builtinName, inferBuiltin builtinName)) (enumerate @Name.BuiltinName) constructResult = \case (Right (), TypeCheckState { types }) -> Right (map (fmap (makeNameTyped types)) ast) (Left error, TypeCheckState { metadata }) -> Left (With (assert (head metadata)) error) makeNameTyped types (NameWith name _) = NameWith name (assert (Map.lookup name types)) instance TypeCheckM TypeCheck where recordType typeOfName name = do doModifyM (field @"types") \typeMap -> do assertM (not (Map.member (Name.name name) typeMap)) return (Map.insert (Name.name name) (HasType typeOfName) typeMap) return () lookupType name = do typeMap <- getM (field @"types") return (msgAssert "Name not found in types map!" (Map.lookup (Name.name name) typeMap)) reportError err = do throwError err enterMetadata metadata action = do -- TODO maybe deduplicate this from here and `Name`? modifyM (field @"metadata") (prepend metadata) result <- action modifyM (field @"metadata") (assert . tail) return result inferBuiltin :: Name.BuiltinName -> TypeInfo inferBuiltin = \case Name.Builtin_Int -> IsType Int Name.Builtin_Bool -> IsType Bool Name.Builtin_Text -> IsType Text Name.Builtin_Unit -> IsType Unit Name.Builtin_true -> HasType Bool Name.Builtin_false -> HasType Bool Name.Builtin_ask -> HasType (Function [Text] Int) Name.Builtin_say -> HasType (Function [Text] Unit) Name.Builtin_write -> HasType (Function [Int] Unit) ------------------------------------------------------------------------ validation -- TODO check presence/absence of exit targets (or in Name.validate??) data ValidationError metadata = BadType Expected (AST.Expression metadata TypedName) | BadAnnotation Type (AST.Type metadata TypedName) | BadArgumentCount Int (AST.Expression metadata TypedName) deriving (Generic, Show) type ValidateM metadata a = Except (ValidationError metadata) a class Validate node where validate :: node metadata TypedName -> ValidateM metadata () -- This checks that: * The AST is locally well - typed at each point , based on the types stored within ` Name`s . * The explicitly - written type annotations in the AST are accurate . -- This does NOT check that: -- * Names are actually in scope, and the info stored in `Name`s is consistent. Use `Name.validate` for that! -- * Literals are within range, and assignments match their binding types. validateTypes :: AST metadata TypedName -> Either (ValidationError metadata) () validateTypes = runExcept . mapM_ validate validateAnnotation :: Type -> AST.Type metadata TypedName -> ValidateM metadata () validateAnnotation = curry \case (expected@(Function expectedParams expectedReturns), annotated@(AST.FunctionType annotatedParams annotatedReturns)) -> do when (length expectedParams != length annotatedParams) do throwError (BadAnnotation expected annotated) zipWithM_ validateAnnotation expectedParams (map nodeWithout annotatedParams) validateAnnotation expectedReturns (nodeWithout annotatedReturns) (expectedType, AST.NamedType namedType) | Name.info namedType == IsType expectedType -> do return () (expectedType, annotation) -> do throwError (BadAnnotation expectedType annotation) instance Validate AST.Function where validate AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do argumentTypes <- forM arguments \argument -> do let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument case Name.info argumentName of HasType ty -> do validateAnnotation ty (nodeWithout argumentType) return ty IsType _ -> do throwError (BadType ExpectedExpression (AST.Named argumentName)) case Name.info functionName of HasType infoType@(Function infoParams infoReturns) -> do mapM_ (validateAnnotation infoReturns . nodeWithout) returns when (infoParams != argumentTypes) do throwError (BadType (Expected infoType) (AST.Named functionName)) -- ehhhhhh TODO check that it 's Just ! HasType _ -> do throwError (BadType ExpectedFunction (AST.Named functionName)) IsType _ -> do throwError (BadType ExpectedExpression (AST.Named functionName)) validate body instance Validate AST.Block where validate = mapM_ validate . AST.statements instance Validate AST.Statement where validate = \case AST.Binding _ name@(NameWith _ info) expr -> do case info of HasType ty -> validateExpr ty expr IsType _ -> throwError (BadType ExpectedExpression (AST.Named name)) AST.Assign name@(NameWith _ info) expr -> do case info of HasType ty -> validateExpr ty expr IsType _ -> throwError (BadType ExpectedExpression (AST.Named name)) AST.IfThen expr body -> do validateExpr Bool expr validate body AST.IfThenElse expr body1 body2 -> do validateExpr Bool expr mapM_ validate [body1, body2] AST.Forever body -> do validate body AST.While expr body -> do validateExpr Bool expr validate body AST.Return target maybeExpr -> do mapM_ (validateExpr (typeOf (AST.Named target))) maybeExpr when (maybeExpr == Nothing) do validateName Unit target AST.Break target -> do validateName Unit target AST.Expression expr -> do validate expr instance Validate AST.Expression where validate = \case AST.UnaryOperator op expr -> do validateExpr opExpectsType expr where opExpectsType = case op of Not -> Bool Negate -> Int AST.BinaryOperator expr1 op expr2 -> do mapM_ (validateExpr opExpectsType) [expr1, expr2] where opExpectsType = case op of ArithmeticOperator _ -> Int ComparisonOperator _ -> Int LogicalOperator _ -> Bool AST.Named _ -> do return () AST.NumberLiteral _ -> do return () AST.TextLiteral _ -> do return () AST.Call function args -> do case typeOf (nodeWithout function) of Function argTypes _ -> do when (length args != length argTypes) do throwError (BadArgumentCount (length argTypes) (AST.Call function args)) zipWithM_ validateExpr argTypes args _ -> do throwError (BadType ExpectedFunction (nodeWithout function)) instance Validate node => Validate (NodeWith node) where validate = validate . nodeWithout validateName :: Type -> TypedName -> ValidateM metadata () validateName ty = validateExprImpl ty . AST.Named validateExpr :: Type -> NodeWith AST.Expression metadata TypedName -> ValidateM metadata () validateExpr ty = validateExprImpl ty . nodeWithout validateExprImpl :: Type -> AST.Expression metadata TypedName -> ValidateM metadata () validateExprImpl expectedType expr = do when (typeOf expr != expectedType) do -- FIXME maybe `validate` shouldn't panic if it sees a `Type` in the wrong place, as `typeOf` does!! throwError (BadType (Expected expectedType) expr) validate expr
null
https://raw.githubusercontent.com/glaebhoerl/simplecompiler/a207ceca64147be99d9ca52fc18624e03e19376a/src/Type.hs
haskell
---------------------------------------------------------------------- types stored for names of types in type annotations stored for value-level names ---------------------------------------------------------------------- pretty-printing ---------------------------------------------------------------------- typechecker frontend (can we move this into Expected?) HACK? guaranteed divergence also counts as "returning" loops can't currently break out of the /outer/ context we can check whether there is a `break` by whether the `exitTarget` is ever referred to (we make use of the Foldable instances for the AST) we have to make sure to leave out the `exitTarget` itself! -------------------------------------------------------------------- typechecker backend TODO maybe deduplicate this from here and `Name`? ---------------------------------------------------------------------- validation TODO check presence/absence of exit targets (or in Name.validate??) This checks that: This does NOT check that: * Names are actually in scope, and the info stored in `Name`s is consistent. Use `Name.validate` for that! * Literals are within range, and assignments match their binding types. ehhhhhh FIXME maybe `validate` shouldn't panic if it sees a `Type` in the wrong place, as `typeOf` does!!
module Type (TypeInfo (..), Type (..), TypedName, Error (..), checkTypes, typeOf, ValidationError (..), validateTypes) where import MyPrelude import qualified Data.Map as Map import qualified Data.Text as Text import qualified Pretty as P import qualified AST import AST (AST) import qualified Name import Name (Name, NameWith (NameWith), ResolvedName) data TypeInfo deriving (Generic, Eq, Show) data Type = Int | Bool | Text | Unit | Function [Type] Type deriving (Generic, Eq, Show) type TypedName = NameWith TypeInfo typeOf :: AST.Expression metadata TypedName -> Type typeOf = \case AST.Named name -> case Name.info name of HasType ty -> ty IsType _ -> bug "Expression which IsType in typed AST" AST.NumberLiteral _ -> Int AST.TextLiteral _ -> Text AST.UnaryOperator op _ -> case op of Not -> Bool Negate -> Int AST.BinaryOperator _ op _ -> case op of ArithmeticOperator _ -> Int ComparisonOperator _ -> Bool LogicalOperator _ -> Bool AST.Call fn _ -> case typeOf (nodeWithout fn) of Function _ returnType -> returnType _ -> bug "Call of non-function in typed AST" instance P.Render TypeInfo where listSeparator = ", " render ty = P.note (P.Identifier (P.IdentInfo (typeText ty) P.Use P.Type True)) (P.pretty (typeText ty)) where typeText = \case HasType (Function argumentTypes returnType) -> "function(" ++ Text.intercalate ", " (map (typeText . HasType) argumentTypes) ++ ")" ++ case returnType of Unit -> "" otherType -> " returns " ++ typeText (HasType otherType) HasType otherType -> showText otherType IsType _ -> "Type" instance P.Render Type where listSeparator = ", " render = P.render . HasType instance AST.RenderName TypedName where renderName defOrUse (NameWith name ty) = maybeAppendTypeAnnotation (fmap setTypeInNote (AST.renderName defOrUse name)) where maybeAppendTypeAnnotation binding = binding ++ (if defOrUse == P.Definition then (P.colon ++ " " ++ P.render ty) else "") setTypeInNote = \case P.Identifier info -> P.Identifier (info { P.identType }) _ -> bug "Pretty-printing annotation on ResolvedName was not Identifier" identType = case ty of IsType _ -> P.Type HasType hasType -> case hasType of Int -> P.Int Bool -> P.Bool Text -> P.Text Unit -> P.Unit Function _ _ -> P.Function TODO more info in here ? data Error = TypeMismatch Expected TypeInfo | FunctionWithoutReturn | AssignToLet | LiteralOutOfRange deriving (Generic, Show) data Expected = Expected Type | ExpectedFunction | ExpectedExpression | ExpectedType deriving (Generic, Show) class (forall metadata. Monad (m metadata)) => TypeCheckM m where records ` HasType ` ; for now , the only things which are ` IsType ` are builtins lookupType :: ResolvedName -> m metadata TypeInfo reportError :: Error -> m metadata a enterMetadata :: metadata -> m metadata a -> m metadata a TODO deduplicate ? enterMetadataOf :: TypeCheckM m => NodeWith node metadata name -> m metadata a -> m metadata a enterMetadataOf = enterMetadata . nodeMetadata class CheckTypeOf node where inferType :: TypeCheckM m => node metadata ResolvedName -> m metadata TypeInfo checkUnit :: TypeCheckM m => node metadata ResolvedName -> m metadata () inferType node = do checkUnit node return (HasType Unit) checkUnit = checkType Unit checkType :: (TypeCheckM m, CheckTypeOf node) => Type -> node metadata ResolvedName -> m metadata () checkType expected node = do actual <- inferType node when (actual != HasType expected) do reportError (TypeMismatch (Expected expected) actual) instance CheckTypeOf AST.Expression where inferType = \case AST.Named name -> do nameType <- lookupType name case nameType of HasType _ -> return nameType IsType _ -> reportError (TypeMismatch ExpectedExpression nameType) AST.NumberLiteral int -> do when (int > fromIntegral (maxBound :: Int64) || int < fromIntegral (minBound :: Int64)) do reportError LiteralOutOfRange return (HasType Int) AST.TextLiteral _ -> do return (HasType Text) AST.UnaryOperator op expr -> do let type' = case op of Not -> Bool Negate -> Int checkType type' expr return (HasType type') AST.BinaryOperator expr1 op expr2 -> do let (inType, outType) = case op of ArithmeticOperator _ -> (Int, Int) ComparisonOperator _ -> (Int, Bool) LogicalOperator _ -> (Bool, Bool) checkType inType expr1 checkType inType expr2 return (HasType outType) AST.Call function arguments -> do functionType <- inferType function case functionType of HasType (Function argumentTypes returnType) -> do when (length argumentTypes != length arguments) do reportError WrongNumberOfArguments zipWithM checkType argumentTypes arguments return (HasType returnType) _ -> do reportError (TypeMismatch ExpectedFunction functionType) instance CheckTypeOf AST.Statement where checkUnit = \case AST.Binding _ name expr -> do inferred <- inferType expr case inferred of HasType hasType -> recordType hasType name IsType _ -> reportError (TypeMismatch ExpectedExpression inferred) AST.Assign name expr -> do when (Name.info name != AST.Var) do reportError AssignToLet nameType <- lookupType name case nameType of HasType hasType -> checkType hasType expr IsType _ -> reportError (TypeMismatch ExpectedExpression nameType) AST.IfThen expr block -> do checkType Bool expr checkUnit block AST.IfThenElse expr block1 block2 -> do checkType Bool expr checkUnit block1 checkUnit block2 AST.Forever block -> do checkBlock Unit block AST.While expr block -> do checkType Bool expr checkBlock Unit block AST.Return target maybeExpr -> do returnType <- lookupType target mapM_ (checkType (assert (match @"HasType" returnType))) maybeExpr when (maybeExpr == Nothing) do AST.Break target -> do breakType <- lookupType target assertEqM breakType (HasType Unit) AST.Expression expr -> do unused (inferType expr) instance CheckTypeOf AST.Block where checkUnit AST.Block { AST.statements } = do mapM_ checkUnit statements checkBlock :: TypeCheckM m => Type -> NodeWith AST.Block metadata ResolvedName -> m metadata () checkBlock exitTargetType block = do recordType exitTargetType (assert (AST.exitTarget (nodeWithout block))) checkUnit block resolveAsType :: TypeCheckM m => NodeWith AST.Type metadata ResolvedName -> m metadata Type resolveAsType typeNode = enterMetadataOf typeNode do resolved <- inferType (nodeWithout typeNode) return (msgAssert "type annotation resolved to a non-type" (match @"IsType" resolved)) instance CheckTypeOf AST.Function where checkUnit AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do argumentTypes <- forM arguments \argument -> do enterMetadataOf argument do let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument resolvedType <- resolveAsType argumentType recordType resolvedType argumentName return resolvedType maybeReturnType <- mapM resolveAsType returns let returnType = fromMaybe Unit maybeReturnType recordType (Function argumentTypes returnType) functionName checkBlock returnType body when (returnType != Unit && not (definitelyReturns (controlFlow body))) do reportError FunctionWithoutReturn instance CheckTypeOf AST.Type where inferType = \case AST.NamedType name -> do nameType <- lookupType name case nameType of IsType _ -> return nameType HasType _ -> reportError (TypeMismatch ExpectedType nameType) AST.FunctionType parameters returns -> do resolvedParameters <- mapM resolveAsType parameters resolvedReturns <- resolveAsType returns return (IsType (Function resolvedParameters resolvedReturns)) instance CheckTypeOf node => CheckTypeOf (NodeWith node) where inferType node = do enterMetadataOf node do inferType (nodeWithout node) data ControlFlow = ControlFlow { potentiallyBreaks :: Bool } instance Semigroup ControlFlow where prev <> next = ControlFlow returns breaks where returns = definitelyReturns prev || (not (potentiallyBreaks prev) && definitelyReturns next) breaks = potentiallyBreaks prev || (not (definitelyReturns prev) && potentiallyBreaks next) instance Monoid ControlFlow where mempty = ControlFlow False False class CheckControlFlow node where controlFlow :: Eq name => node metadata name -> ControlFlow instance CheckControlFlow AST.Block where controlFlow = mconcat . map controlFlow . AST.statements instance CheckControlFlow AST.Statement where controlFlow = \case AST.Return {} -> ControlFlow True False AST.Break {} -> ControlFlow False True AST.Binding {} -> ControlFlow False False AST.Assign {} -> ControlFlow False False AST.Expression {} -> ControlFlow False False AST.While {} -> AST.IfThen _ block -> ControlFlow False (potentiallyBreaks (controlFlow block)) AST.IfThenElse _ block1 block2 -> ControlFlow (returns1 && returns2) (breaks1 || breaks2) where ControlFlow returns1 breaks1 = controlFlow block1 ControlFlow returns2 breaks2 = controlFlow block2 AST.Forever blockWith -> ControlFlow (noBreaks || doesReturn) False where noBreaks = not (any (== (assert (AST.exitTarget block))) (block { AST.exitTarget = Nothing })) doesReturn = definitelyReturns (controlFlow block) block = nodeWithout blockWith instance CheckControlFlow node => CheckControlFlow (NodeWith node) where controlFlow = controlFlow . nodeWithout newtype TypeCheck metadata a = TypeCheck { runTypeCheck :: (ExceptT Error) (State (TypeCheckState metadata)) a } deriving (Functor, Applicative, Monad, MonadState (TypeCheckState metadata), MonadError Error) data TypeCheckState metadata = TypeCheckState { types :: Map Name TypeInfo, metadata :: [metadata] } deriving (Generic, Show) checkTypes :: AST metadata ResolvedName -> Either (With metadata Error) (AST metadata TypedName) checkTypes ast = pipeline ast where pipeline = constructResult . runState initialState . runExceptT . runTypeCheck . mapM_ checkUnit initialState = TypeCheckState (Map.fromList builtinNames) [] builtinNames = map (\builtinName -> (Name.BuiltinName builtinName, inferBuiltin builtinName)) (enumerate @Name.BuiltinName) constructResult = \case (Right (), TypeCheckState { types }) -> Right (map (fmap (makeNameTyped types)) ast) (Left error, TypeCheckState { metadata }) -> Left (With (assert (head metadata)) error) makeNameTyped types (NameWith name _) = NameWith name (assert (Map.lookup name types)) instance TypeCheckM TypeCheck where recordType typeOfName name = do doModifyM (field @"types") \typeMap -> do assertM (not (Map.member (Name.name name) typeMap)) return (Map.insert (Name.name name) (HasType typeOfName) typeMap) return () lookupType name = do typeMap <- getM (field @"types") return (msgAssert "Name not found in types map!" (Map.lookup (Name.name name) typeMap)) reportError err = do throwError err modifyM (field @"metadata") (prepend metadata) result <- action modifyM (field @"metadata") (assert . tail) return result inferBuiltin :: Name.BuiltinName -> TypeInfo inferBuiltin = \case Name.Builtin_Int -> IsType Int Name.Builtin_Bool -> IsType Bool Name.Builtin_Text -> IsType Text Name.Builtin_Unit -> IsType Unit Name.Builtin_true -> HasType Bool Name.Builtin_false -> HasType Bool Name.Builtin_ask -> HasType (Function [Text] Int) Name.Builtin_say -> HasType (Function [Text] Unit) Name.Builtin_write -> HasType (Function [Int] Unit) data ValidationError metadata = BadType Expected (AST.Expression metadata TypedName) | BadAnnotation Type (AST.Type metadata TypedName) | BadArgumentCount Int (AST.Expression metadata TypedName) deriving (Generic, Show) type ValidateM metadata a = Except (ValidationError metadata) a class Validate node where validate :: node metadata TypedName -> ValidateM metadata () * The AST is locally well - typed at each point , based on the types stored within ` Name`s . * The explicitly - written type annotations in the AST are accurate . validateTypes :: AST metadata TypedName -> Either (ValidationError metadata) () validateTypes = runExcept . mapM_ validate validateAnnotation :: Type -> AST.Type metadata TypedName -> ValidateM metadata () validateAnnotation = curry \case (expected@(Function expectedParams expectedReturns), annotated@(AST.FunctionType annotatedParams annotatedReturns)) -> do when (length expectedParams != length annotatedParams) do throwError (BadAnnotation expected annotated) zipWithM_ validateAnnotation expectedParams (map nodeWithout annotatedParams) validateAnnotation expectedReturns (nodeWithout annotatedReturns) (expectedType, AST.NamedType namedType) | Name.info namedType == IsType expectedType -> do return () (expectedType, annotation) -> do throwError (BadAnnotation expectedType annotation) instance Validate AST.Function where validate AST.Function { AST.functionName, AST.arguments, AST.returns, AST.body } = do argumentTypes <- forM arguments \argument -> do let AST.Argument { AST.argumentName, AST.argumentType } = nodeWithout argument case Name.info argumentName of HasType ty -> do validateAnnotation ty (nodeWithout argumentType) return ty IsType _ -> do throwError (BadType ExpectedExpression (AST.Named argumentName)) case Name.info functionName of HasType infoType@(Function infoParams infoReturns) -> do mapM_ (validateAnnotation infoReturns . nodeWithout) returns when (infoParams != argumentTypes) do TODO check that it 's Just ! HasType _ -> do throwError (BadType ExpectedFunction (AST.Named functionName)) IsType _ -> do throwError (BadType ExpectedExpression (AST.Named functionName)) validate body instance Validate AST.Block where validate = mapM_ validate . AST.statements instance Validate AST.Statement where validate = \case AST.Binding _ name@(NameWith _ info) expr -> do case info of HasType ty -> validateExpr ty expr IsType _ -> throwError (BadType ExpectedExpression (AST.Named name)) AST.Assign name@(NameWith _ info) expr -> do case info of HasType ty -> validateExpr ty expr IsType _ -> throwError (BadType ExpectedExpression (AST.Named name)) AST.IfThen expr body -> do validateExpr Bool expr validate body AST.IfThenElse expr body1 body2 -> do validateExpr Bool expr mapM_ validate [body1, body2] AST.Forever body -> do validate body AST.While expr body -> do validateExpr Bool expr validate body AST.Return target maybeExpr -> do mapM_ (validateExpr (typeOf (AST.Named target))) maybeExpr when (maybeExpr == Nothing) do validateName Unit target AST.Break target -> do validateName Unit target AST.Expression expr -> do validate expr instance Validate AST.Expression where validate = \case AST.UnaryOperator op expr -> do validateExpr opExpectsType expr where opExpectsType = case op of Not -> Bool Negate -> Int AST.BinaryOperator expr1 op expr2 -> do mapM_ (validateExpr opExpectsType) [expr1, expr2] where opExpectsType = case op of ArithmeticOperator _ -> Int ComparisonOperator _ -> Int LogicalOperator _ -> Bool AST.Named _ -> do return () AST.NumberLiteral _ -> do return () AST.TextLiteral _ -> do return () AST.Call function args -> do case typeOf (nodeWithout function) of Function argTypes _ -> do when (length args != length argTypes) do throwError (BadArgumentCount (length argTypes) (AST.Call function args)) zipWithM_ validateExpr argTypes args _ -> do throwError (BadType ExpectedFunction (nodeWithout function)) instance Validate node => Validate (NodeWith node) where validate = validate . nodeWithout validateName :: Type -> TypedName -> ValidateM metadata () validateName ty = validateExprImpl ty . AST.Named validateExpr :: Type -> NodeWith AST.Expression metadata TypedName -> ValidateM metadata () validateExpr ty = validateExprImpl ty . nodeWithout validateExprImpl :: Type -> AST.Expression metadata TypedName -> ValidateM metadata () validateExprImpl expectedType expr = do throwError (BadType (Expected expectedType) expr) validate expr
e45221ca0f96ecc0c22c82ce995eaa2dd05c2c2ea9e9c46ddcbac3ce4410ca26
modular-macros/ocaml-macros
printing.ml
(* PR#6650 *) module type S = sig class type c = object method m : int end module M : sig class type d = c end end;; module F (X : S) = X.M;; [%%expect{| module type S = sig class type c = object method m : int end module M : sig class type d = c end end module F : functor (X : S) -> sig class type d = X.c end |}];; (* PR#6648 *) module M = struct module N = struct let x = 1 end end;; #show_module M;; [%%expect{| module M : sig module N : sig val x : int end end module M : sig module N : sig ... end end |}];;
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/typing-modules/printing.ml
ocaml
PR#6650 PR#6648
module type S = sig class type c = object method m : int end module M : sig class type d = c end end;; module F (X : S) = X.M;; [%%expect{| module type S = sig class type c = object method m : int end module M : sig class type d = c end end module F : functor (X : S) -> sig class type d = X.c end |}];; module M = struct module N = struct let x = 1 end end;; #show_module M;; [%%expect{| module M : sig module N : sig val x : int end end module M : sig module N : sig ... end end |}];;
2763a210d7ec967ee8a12ba702b034978d0e484afdc70144375db785e61f5545
triffon/fp-2019-20
recursion.rkt
#lang racket ; Throwback: ; - Типове ; - Всичко е стойност - кода на scheme е на списъци ; - Функции (извикване, дефиниране) ; - quote и символи ; - define, if, cond - рекурсия ; Не упражнихме всичко , но ето някои вградени функции , ; показвани на лекции: ; *, +, -, / remainder , quotient , , min , gcd , lcm ; floor, ceiling, round exp , expt , sqrt , log , sin , cos , tan , asin , acos , atan ; <, >, =, <=, >= zero ? , negative ? , positive ? , even ? , odd ? ; boolean?, number?, char?, string?, symbol?, procedure? ; equal? ; Гледайте документацията за справка. ! (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))))) ако бележим factorial с f , изчислителния процес на 5 ! ; изглежда така: ;(f 5) ( * 5 ( f 4 ) ) ( * 5 ( * 4 ( f 3 ) ) ) ( * 5 ( * 4 ( * 3 ( f 2 ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( f 1 ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( * 1 ( f 0 ) ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( * 1 1 ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 1 ) ) ) ) ( * 5 ( * 4 ( * 3 2 ) ) ) ( * 5 ( * 4 6 ) ) ( * 5 24 ) 120 ; памет: O(n) време : О(n ) Това е същински рекурсивен заради отложените операции . Използвайки вложена дефиниция : (define (factorial-iter n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) изчислителния изглежда така : ( factorial - iter 5 ) ( iter 1 1 ) ( iter 1 2 ) ( iter 2 3 ) ( iter 6 4 ) ( iter 24 5 ) ( iter 120 6 ) 120 ; време: O(n) памет : O(1 ) Това е линеен итеративен отложени операции . ( опашкова рекурсия ) Scheme . всяка функция си има среда , се оценява ( думи за средите в scheme ) ; iter има достъп до аргументите на factorial-iter Тази реализация поражда дървовиден рекурсивен (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) Можем ли да го итеративно ? ( ) Ще намираме числата на фибоначи последователно и ще помним предходните две . Така няма да трябва да ги изчисляваме всеки път когато ни потрябват . (define (fib-iter n) (define (iter n1 n2 index) (if (= index 0) n1 (iter n2 (+ n1 n2) (- index 1)))) (iter 0 1 n)) (time (fib 42)) (time (fib-iter 42)) на подадената функция да звърши
null
https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-4/02/recursion.rkt
racket
Throwback: - Типове - Всичко е стойност - Функции (извикване, дефиниране) - quote и символи - define, if, cond Не упражнихме всичко , но ето някои вградени функции , показвани на лекции: *, +, -, / floor, ceiling, round <, >, =, <=, >= boolean?, number?, char?, string?, symbol?, procedure? equal? Гледайте документацията за справка. изглежда така: (f 5) памет: O(n) време: O(n) iter има достъп до аргументите на factorial-iter
#lang racket - кода на scheme е на списъци - рекурсия remainder , quotient , , min , gcd , lcm exp , expt , sqrt , log , sin , cos , tan , asin , acos , atan zero ? , negative ? , positive ? , even ? , odd ? ! (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))))) ако бележим factorial с f , изчислителния процес на 5 ! ( * 5 ( f 4 ) ) ( * 5 ( * 4 ( f 3 ) ) ) ( * 5 ( * 4 ( * 3 ( f 2 ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( f 1 ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( * 1 ( f 0 ) ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 ( * 1 1 ) ) ) ) ) ( * 5 ( * 4 ( * 3 ( * 2 1 ) ) ) ) ( * 5 ( * 4 ( * 3 2 ) ) ) ( * 5 ( * 4 6 ) ) ( * 5 24 ) 120 време : О(n ) Това е същински рекурсивен заради отложените операции . Използвайки вложена дефиниция : (define (factorial-iter n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) изчислителния изглежда така : ( factorial - iter 5 ) ( iter 1 1 ) ( iter 1 2 ) ( iter 2 3 ) ( iter 6 4 ) ( iter 24 5 ) ( iter 120 6 ) 120 памет : O(1 ) Това е линеен итеративен отложени операции . ( опашкова рекурсия ) Scheme . всяка функция си има среда , се оценява ( думи за средите в scheme ) Тази реализация поражда дървовиден рекурсивен (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) Можем ли да го итеративно ? ( ) Ще намираме числата на фибоначи последователно и ще помним предходните две . Така няма да трябва да ги изчисляваме всеки път когато ни потрябват . (define (fib-iter n) (define (iter n1 n2 index) (if (= index 0) n1 (iter n2 (+ n1 n2) (- index 1)))) (iter 0 1 n)) (time (fib 42)) (time (fib-iter 42)) на подадената функция да звърши
62afccf63c2d508ff4d2ccdb94a2c89d4bc5b346c32c9189f434e9d2aa8500ea
cedlemo/ctypes-stubs-generation-notes
discover.ml
open Base open Stdio module C = Configurator let write_sexp fn list_of_str = let data = sexp_of_list sexp_of_string list_of_str |> Sexp.to_string in Out_channel.write_all fn ~data let write_flags file list_of_str = let data = String.concat list_of_str ~sep:" " in Out_channel.write_all file ~data let () = C.main ~name:"GObject-Introspection" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-lgirepository-1.0"; "-lgobject-2.0"; "-lglib-2.0"; "-lffi"] ; cflags = ["-O2"; "-Wall"; "-Wextra"; "-Wno-unused-parameter"; "-pthread"; "-I/usr/include/gobject-introspection-1.0"; "-I/usr/lib/libffi-3.2.1/include"; "-I/usr/include/glib-2.0"; "-I/usr/lib/glib-2.0/include"] } in let default_ffi : C.Pkg_config.package_conf = { libs = ["-lffi"] ; cflags = ["-O2"; "-Wall"; "-Wextra"; "-Wno-unused-parameter"; "-I/usr/lib/libffi-3.2.1/include"; "-I/usr/include/x86_64-linux-gnu"; (* default ubuntu *) "-I/usr/include"] (* default ubuntu *) } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> let get_config package default = Option.value (C.Pkg_config.query pc ~package) ~default in let libffi = get_config "libffi" default_ffi in let gobject = get_config "gobject-introspection-1.0" default in let module P = C.Pkg_config in { libs = (libffi.P.libs @ gobject.P.libs); cflags = (libffi.P.cflags @ gobject.P.cflags) } in let os_type = C.ocaml_config_var_exn (C.create "") "system" in let ccopts = if Base.String.(os_type = "macosx") then [""] else ["-Wl,-no-as-needed"] in write_sexp "c_flags.sexp" conf.cflags; write_sexp "c_library_flags.sexp" conf.libs; write_sexp "ccopts.sexp" ccopts; write_flags "c_library_flags" conf.libs; write_flags "c_flags" conf.cflags)
null
https://raw.githubusercontent.com/cedlemo/ctypes-stubs-generation-notes/2a7d71919c38d90ddc1e54f4875e136b7398f36d/cstubs_gi_enums/config/discover.ml
ocaml
default ubuntu default ubuntu
open Base open Stdio module C = Configurator let write_sexp fn list_of_str = let data = sexp_of_list sexp_of_string list_of_str |> Sexp.to_string in Out_channel.write_all fn ~data let write_flags file list_of_str = let data = String.concat list_of_str ~sep:" " in Out_channel.write_all file ~data let () = C.main ~name:"GObject-Introspection" (fun c -> let default : C.Pkg_config.package_conf = { libs = ["-lgirepository-1.0"; "-lgobject-2.0"; "-lglib-2.0"; "-lffi"] ; cflags = ["-O2"; "-Wall"; "-Wextra"; "-Wno-unused-parameter"; "-pthread"; "-I/usr/include/gobject-introspection-1.0"; "-I/usr/lib/libffi-3.2.1/include"; "-I/usr/include/glib-2.0"; "-I/usr/lib/glib-2.0/include"] } in let default_ffi : C.Pkg_config.package_conf = { libs = ["-lffi"] ; cflags = ["-O2"; "-Wall"; "-Wextra"; "-Wno-unused-parameter"; "-I/usr/lib/libffi-3.2.1/include"; } in let conf = match C.Pkg_config.get c with | None -> default | Some pc -> let get_config package default = Option.value (C.Pkg_config.query pc ~package) ~default in let libffi = get_config "libffi" default_ffi in let gobject = get_config "gobject-introspection-1.0" default in let module P = C.Pkg_config in { libs = (libffi.P.libs @ gobject.P.libs); cflags = (libffi.P.cflags @ gobject.P.cflags) } in let os_type = C.ocaml_config_var_exn (C.create "") "system" in let ccopts = if Base.String.(os_type = "macosx") then [""] else ["-Wl,-no-as-needed"] in write_sexp "c_flags.sexp" conf.cflags; write_sexp "c_library_flags.sexp" conf.libs; write_sexp "ccopts.sexp" ccopts; write_flags "c_library_flags" conf.libs; write_flags "c_flags" conf.cflags)
4584e3cec7f9b7d3616aea24cae55cd29d972b7d7b2d587843dd09ed0eaa1e9c
yzhs/ocamlllvm
complex.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ (* Complex numbers *) type t = { re: float; im: float } let zero = { re = 0.0; im = 0.0 } let one = { re = 1.0; im = 0.0 } let i = { re = 0.0; im = 1.0 } let add x y = { re = x.re +. y.re; im = x.im +. y.im } let sub x y = { re = x.re -. y.re; im = x.im -. y.im } let neg x = { re = -. x.re; im = -. x.im } let conj x = { re = x.re; im = -. x.im } let mul x y = { re = x.re *. y.re -. x.im *. y.im; im = x.re *. y.im +. x.im *. y.re } let div x y = if abs_float y.re >= abs_float y.im then let r = y.im /. y.re in let d = y.re +. r *. y.im in { re = (x.re +. r *. x.im) /. d; im = (x.im -. r *. x.re) /. d } else let r = y.re /. y.im in let d = y.im +. r *. y.re in { re = (r *. x.re +. x.im) /. d; im = (r *. x.im -. x.re) /. d } let inv x = div one x let norm2 x = x.re *. x.re +. x.im *. x.im let norm x = Watch out for overflow in computing re^2 + im^2 let r = abs_float x.re and i = abs_float x.im in if r = 0.0 then i else if i = 0.0 then r else if r >= i then let q = i /. r in r *. sqrt(1.0 +. q *. q) else let q = r /. i in i *. sqrt(1.0 +. q *. q) let arg x = atan2 x.im x.re let polar n a = { re = cos a *. n; im = sin a *. n } let sqrt x = if x.re = 0.0 && x.im = 0.0 then { re = 0.0; im = 0.0 } else begin let r = abs_float x.re and i = abs_float x.im in let w = if r >= i then begin let q = i /. r in sqrt(r) *. sqrt(0.5 *. (1.0 +. sqrt(1.0 +. q *. q))) end else begin let q = r /. i in sqrt(i) *. sqrt(0.5 *. (q +. sqrt(1.0 +. q *. q))) end in if x.re >= 0.0 then { re = w; im = 0.5 *. x.im /. w } else { re = 0.5 *. i /. w; im = if x.im >= 0.0 then w else -. w } end let exp x = let e = exp x.re in { re = e *. cos x.im; im = e *. sin x.im } let log x = { re = log (norm x); im = atan2 x.im x.re } let pow x y = exp (mul y (log x))
null
https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/stdlib/complex.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* Complex numbers
, projet Cristal , INRIA Rocquencourt Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ type t = { re: float; im: float } let zero = { re = 0.0; im = 0.0 } let one = { re = 1.0; im = 0.0 } let i = { re = 0.0; im = 1.0 } let add x y = { re = x.re +. y.re; im = x.im +. y.im } let sub x y = { re = x.re -. y.re; im = x.im -. y.im } let neg x = { re = -. x.re; im = -. x.im } let conj x = { re = x.re; im = -. x.im } let mul x y = { re = x.re *. y.re -. x.im *. y.im; im = x.re *. y.im +. x.im *. y.re } let div x y = if abs_float y.re >= abs_float y.im then let r = y.im /. y.re in let d = y.re +. r *. y.im in { re = (x.re +. r *. x.im) /. d; im = (x.im -. r *. x.re) /. d } else let r = y.re /. y.im in let d = y.im +. r *. y.re in { re = (r *. x.re +. x.im) /. d; im = (r *. x.im -. x.re) /. d } let inv x = div one x let norm2 x = x.re *. x.re +. x.im *. x.im let norm x = Watch out for overflow in computing re^2 + im^2 let r = abs_float x.re and i = abs_float x.im in if r = 0.0 then i else if i = 0.0 then r else if r >= i then let q = i /. r in r *. sqrt(1.0 +. q *. q) else let q = r /. i in i *. sqrt(1.0 +. q *. q) let arg x = atan2 x.im x.re let polar n a = { re = cos a *. n; im = sin a *. n } let sqrt x = if x.re = 0.0 && x.im = 0.0 then { re = 0.0; im = 0.0 } else begin let r = abs_float x.re and i = abs_float x.im in let w = if r >= i then begin let q = i /. r in sqrt(r) *. sqrt(0.5 *. (1.0 +. sqrt(1.0 +. q *. q))) end else begin let q = r /. i in sqrt(i) *. sqrt(0.5 *. (q +. sqrt(1.0 +. q *. q))) end in if x.re >= 0.0 then { re = w; im = 0.5 *. x.im /. w } else { re = 0.5 *. i /. w; im = if x.im >= 0.0 then w else -. w } end let exp x = let e = exp x.re in { re = e *. cos x.im; im = e *. sin x.im } let log x = { re = log (norm x); im = atan2 x.im x.re } let pow x y = exp (mul y (log x))
da84ed3302515b28791886cdbfb9cff46d7c3036c1256f4736417eabf276f182
ocaml/ocaml
ocamltex.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Paris , Nagoya University (* *) Copyright 2018 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) [@@@warning "+a-4-6-40..42-44-48"] open StdLabels open Str let camlprefix = "caml" let latex_escape s = String.concat "" ["$"; s; "$"] let toplevel_prompt= latex_escape {|\?|} ^ " " let camlbunderline = "<<" let camleunderline = ">>" (** Restrict the number of latex environment *) type env = Env of string let main = Env "example" let input_env = Env "input" let ok_output = Env "output" let error = Env "error" let warning = Env "warn" let phrase_env = Env "" let start out (Env s) args = Format.fprintf out "\\begin{%s%s}" camlprefix s; List.iter (Format.fprintf out "{%s}") args; Format.fprintf out "\n" let stop out (Env s) = Format.fprintf out "\\end{%s%s}" camlprefix s; Format.fprintf out "\n" let code_env env out s = let sep = if s.[String.length s - 1] = '\n' then "" else "\n" in Format.fprintf out "%a%s%s%a" (fun ppf env -> start ppf env []) env s sep stop env type example_mode = Toplevel | Verbatim | Signature let string_of_mode = function | Toplevel -> "toplevel" | Verbatim -> "verbatim" | Signature -> "signature" let verbose = ref true let linelen = ref 72 let outfile = ref "" let cut_at_blanks = ref false let files = ref [] let repo_root = ref "" let (~!) = let memo = ref [] in fun key -> try List.assq key !memo with Not_found -> let data = Str.regexp key in memo := (key, data) :: !memo; data exception Phrase_parsing of string module Toplevel = struct (** Initialize the toplevel loop, redirect stdout and stderr, capture warnings and error messages *) type output = { error : string; (** error message text *) warnings : string list; (** warning messages text *) values : string; (** toplevel output *) stdout : string; (** output printed on the toplevel stdout *) underlined : (int * int) list (** locations to underline in input phrases *) } let buffer_fmt () = let b = Buffer.create 30 in b, Format.formatter_of_buffer b let error_fmt = buffer_fmt () let warning_fmt = buffer_fmt () let out_fmt = buffer_fmt () let flush_fmt (b,fmt) = Format.pp_print_flush fmt (); let r = Buffer.contents b in Buffer.reset b; r (** Redirect the stdout *) let stdout_out, stdout_in = Unix.pipe ~cloexec:true () let () = Unix.dup2 stdout_in Unix.stdout let self_error_fmt = Format.formatter_of_out_channel stderr let eprintf = Format.eprintf let read_stdout = let size = 50 in let b = Bytes.create size in let buffer = Buffer.create 100 in let rec read_toplevel_stdout () = match Unix.select[stdout_out][][] 0. with | [_a], _, _ -> let n = Unix.read stdout_out b 0 size in Buffer.add_subbytes buffer b 0 n; if n = size then read_toplevel_stdout () | _ -> () in fun () -> let () = flush stdout; read_toplevel_stdout () in let r = Buffer.contents buffer in Buffer.reset buffer; r (** Store character intervals directly *) let locs = ref [] let register_loc (loc : Location.t) = let startchar = loc.loc_start.pos_cnum in let endchar = loc.loc_end.pos_cnum in if startchar >= 0 then locs := (startchar, endchar) :: !locs (** Record locations in the main error and suberrors without printing them *) let printer_register_locs = let base = Location.batch_mode_printer in { Location.pp_main_loc = (fun _ _ _ loc -> register_loc loc); pp_submsg_loc = (fun _ _ _ loc -> register_loc loc); (* The following fields are kept identical to [base], listed explicitly so that future field additions result in an error -- using (Location.batch_mode_printer with ...) would be the symmetric problem to a fragile pattern-matching. *) pp = base.pp; pp_report_kind = base.pp_report_kind; pp_main_txt = base.pp_main_txt; pp_submsgs = base.pp_submsgs; pp_submsg = base.pp_submsg; pp_submsg_txt = base.pp_submsg_txt; } (** Capture warnings and keep them in a list *) let warnings = ref [] let report_printer = (* Extend [printer_register_locs] *) let pp self ppf report = match report.Location.kind with | Location.Report_warning _ | Location.Report_warning_as_error _ -> printer_register_locs.pp self (snd warning_fmt) report; let w = flush_fmt warning_fmt in warnings := w :: !warnings | _ -> printer_register_locs.pp self ppf report in { printer_register_locs with pp } let fatal ic oc fmt = Format.kfprintf (fun ppf -> Format.fprintf ppf "@]@."; close_in ic; close_out oc; exit 1) self_error_fmt ("@[<hov 2> Error " ^^ fmt) let init () = Location.report_printer := (fun () -> report_printer); Clflags.color := Some Misc.Color.Never; Clflags.no_std_include := true; Compenv.last_include_dirs := [Filename.concat !repo_root "stdlib"]; Compmisc.init_path ~auto_include:Load_path.no_auto_include (); try Toploop.initialize_toplevel_env (); Sys.interactive := false with _ -> (eprintf "Invalid repo root: %s?%!" !repo_root; exit 2) let exec (_,ppf) p = try ignore @@ Toploop.execute_phrase true ppf p with exn -> let bt = Printexc.get_raw_backtrace () in begin try Location.report_exception (snd error_fmt) exn with _ -> eprintf "Uncaught exception: %s\n%s\n" (Printexc.to_string exn) (Printexc.raw_backtrace_to_string bt) end let parse fname mode s = let lex = Lexing.from_string s in Location.init lex fname; Location.input_name := fname; Location.input_lexbuf := Some lex; try match mode with | Toplevel -> Parse.toplevel_phrase lex | Verbatim -> Parsetree.Ptop_def (Parse.implementation lex) | Signature -> let sign = Parse.interface lex in let name = Location.mknoloc "wrap" in let str = Ast_helper.[Str.modtype @@ Mtd.mk ~typ:(Mty.signature sign) name] in Parsetree.Ptop_def str with | Lexer.Error _ | Syntaxerr.Error _ -> raise (Phrase_parsing s) let take x = let r = !x in x := []; r let read_output () = let warnings = take warnings in let error = flush_fmt error_fmt in let values = replace_first ~!{|^#\( *\*\)* *|} "" @@ flush_fmt out_fmt in (* the inner ( *\* )* group is here to clean the starting "*" introduced for multiline comments *) let underlined = take locs in let stdout = read_stdout () in { values; warnings; error; stdout; underlined } (** exec and ignore all output from the toplevel *) let eval b = let s = Buffer.contents b in let ast = Parse.toplevel_phrase (Lexing.from_string s) in exec out_fmt ast; ignore (read_output()); Buffer.reset b end let () = Arg.parse ["-n", Arg.Int (fun n -> linelen := n), "line length"; "-o", Arg.String (fun s -> outfile := s), "output"; "-repo-root", Arg.String ((:=) repo_root ), "repo root"; "-w", Arg.Set cut_at_blanks, "cut at blanks"; "-v", Arg.Bool (fun b -> verbose := b ), "output result on stderr" ] (fun s -> files := s :: !files) "ocamltex: "; Toplevel.init () (** The Output module deals with the analysis and classification of the interpreter output and the parsing of status-related options or annotations for the caml_example environment *) module Output = struct (** Interpreter output status *) type status = | Ok | Warning of int | Error type kind = | Annotation (** Local annotation: [ [@@expect (*annotation*) ] ]*) | Option (** Global environment option: [\begin{caml_example}[option[=value]] ... \end{caml_example}] *) (** Pretty printer for status *) let pp_status ppf = function | Error -> Format.fprintf ppf "error" | Ok -> Format.fprintf ppf "ok" | Warning n -> Format.fprintf ppf "warning %d" n (** Pretty printer for status preceded with an undefined determinant *) let pp_a_status ppf = function | Error -> Format.fprintf ppf "an error" | Ok -> Format.fprintf ppf "an ok" | Warning n -> Format.fprintf ppf "a warning %d" n * { 1 Related latex environment } let env = function | Error -> error | Warning _ -> warning | Ok -> ok_output * { 1 Exceptions } exception Parsing_error of kind * string type source = { file : string; lines : int * int; phrase : string; output : string } type unexpected_report = {source : source; expected : status; got : status} exception Unexpected_status of unexpected_report let print_source ppf {file; lines = (start, stop); phrase; output} = Format.fprintf ppf "%s, lines %d to %d:\n\"\n%s\n\"\n\"\n%s\n\"." file start stop phrase output let print_unexpected {source; expected; got} = if expected = Ok then Toplevel.eprintf "Error when evaluating a caml_example environment in %a\n\ Unexpected %a status.\n\ If %a status was expected, add an [@@expect %a] annotation.\n" print_source source pp_status got pp_a_status got pp_status got else Toplevel.eprintf "Error when evaluating a guarded caml_example environment in %a\n\ Unexpected %a status, %a status was expected.\n\ If %a status was in fact expected, change the status annotation to \ [@@expect %a].\n" print_source source pp_status got pp_a_status expected pp_a_status got pp_status got; flush stderr let print_parsing_error k s = match k with | Option -> Toplevel.eprintf "Unknown caml_example option: [%s].\n\ Supported options are \"ok\",\"error\", or \"warning=n\" (with n \ a warning number).\n" s | Annotation -> Toplevel.eprintf "Unknown caml_example phrase annotation: [@@expect %s].\n\ Supported annotations are [@@expect ok], [@@expect error],\n\ and [@@expect warning n] (with n a warning number).\n" s (** {1 Output analysis} *) let catch_error = function | "" -> None | _ -> Some Error let catch_warning = function | [] -> None | s :: _ when string_match ~!{| *Warning \([0-9]+\)\( \[[a-z-]+\]\)?:|} s 0 -> Some (Warning (int_of_string @@ matched_group 1 s)) | _ -> None let status ws es = match catch_warning ws, catch_error es with | Some w, _ -> w | None, Some e -> e | None, None -> Ok * { 1 Parsing caml_example options } * [ warning = n ] options for caml_example options let parse_warning s = if string_match ~!{|warning=\([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None * [ warning n ] annotations let parse_local_warning s = if string_match ~!{|warning \([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None let parse_error s = if s="error" then Some Error else None let parse_ok s = if s = "ok" then Some Ok else None * the environment - wide expected status output let expected s = match parse_warning s, parse_error s with | Some w, _ -> w | None, Some e -> e | None, None -> raise (Parsing_error (Option,s)) * the local ( i.e. phrase - wide ) expected status output let local_expected s = match parse_local_warning s, parse_error s, parse_ok s with | Some w, _, _ -> w | None, Some e, _ -> e | None, None, Some ok -> ok | None, None, None -> raise (Parsing_error (Annotation,s)) end module Text_transform = struct type kind = | Underline | Ellipsis type t = { kind : kind; start : int; stop : int} exception Intersection of { line : int; file : string; left : t; right : t; } let pp ppf = function | Underline -> Format.fprintf ppf "underline" | Ellipsis -> Format.fprintf ppf "ellipsis" let underline start stop = { kind = Underline; start; stop} let escape_specials s = s |> global_replace ~!{|\$|} {|$\textdollar$|} let rec apply_transform input (pos,underline_stop,out) t = if pos >= String.length input then pos, underline_stop, out else match underline_stop with | Some stop when stop <= t.start -> let f = escape_specials (String.sub input ~pos ~len:(stop - pos)) in let out = camleunderline :: f :: out in apply_transform input (stop,None,out) t | _ -> let out = escape_specials (String.sub input ~pos ~len:(t.start - pos))::out in match t.kind with | Ellipsis -> t.stop, underline_stop, latex_escape {|\ldots|} :: out | Underline -> t.start, Some t.stop, camlbunderline :: out (** Merge consecutive transforms: - drop nested underline transform - raise an error with transforms nested under an ellipsis - raise an error when consecutive transforms partially overlap *) let merge_transforms file line ts = let rec merge (active, active_stack, acc) t = if active.stop <= t.start then (* no overlap, the next transform starts after the end of the current active transform *) match active_stack with | [] -> there were no other active transforms , the new transform becomes the active one the active one *) t, [], t :: acc | last :: active_stack -> (* we check that [t] is still conflict-free with our parent transforms *) merge (last, active_stack,acc) t else if active.stop < t.stop (* not nested *) then raise (Intersection {line; file; left = active; right=t}) else (* nested transforms *) match active.kind, t.kind with | Ellipsis, _ -> (* no nesting allowed under an ellipsis *) raise (Intersection {line; file; left = active; right=t}) | Underline, Ellipsis -> (* underlined ellipsis are allowed *) (t , active :: active_stack, t :: acc) | Underline, Underline -> multiple underlining are flattened to one (t, active :: active_stack, acc) in match ts with | [] -> [] | a :: q -> let _, _, ts = List.fold_left ~f:merge ~init:(a,[],[a]) q in List.rev ts let apply ts file line s = remove duplicated transforms that can appear due to duplicated parse tree elements . For instance , [ let f : ( _ [ @ellipsis ] = ( ) ] is transformed to [ let f : ( _ [ @ellipsis ] ) = ( ( ): ( _ [ @ellipsis ] ) ] with the same location for the two ellipses . duplicated parse tree elements. For instance, [let f : (_ [@ellipsis] = ()] is transformed to [let f: (_ [@ellipsis]) = (():(_ [@ellipsis])] with the same location for the two ellipses. *) let ts = List.sort_uniq compare ts in let ts = List.sort (fun x y -> compare x.start y.start) ts in let ts = merge_transforms file line ts in let last, underline, ls = List.fold_left ~f:(apply_transform s) ~init:(0,None,[]) ts in let last, ls = match underline with | None -> last, ls | Some stop -> let f = escape_specials (String.sub s ~pos:last ~len:(stop - last)) in stop, camleunderline :: f :: ls in let ls = let n = String.length s in if last = n then ls else escape_specials (String.sub s last (n-last)) :: ls in String.concat "" (List.rev ls) end exception Missing_double_semicolon of string * int exception Missing_mode of string * int type incompatibility = | Signature_with_visible_answer of string * int exception Incompatible_options of incompatibility module Ellipsis = struct (** This module implements the extraction of ellipsis locations from phrases. An ellipsis is either an [[@ellipsis]] attribute, or a pair of [[@@@ellipsis.start]...[@@@ellipsis.stop]] attributes. *) exception Unmatched_ellipsis of {kind : string; start : int; stop : int} (** raised when an [[@@@ellipsis.start]] or [[@@@ellipsis.stop]] is not paired with another ellipsis attribute *) exception Nested_ellipses of {first : int ; second : int} (** raised by [[@@@ellipsis.start][@@@ellipsis.start]] *) let extract f x = let transforms = ref [] in let last_loc = ref Location.none in let left_mark = ref None (* stored position of [@@@ellipsis.start]*) in let location _this loc = we rely on the fact that the default iterator calls first the location subiterator , then the attribute subiterator the location subiterator, then the attribute subiterator *) last_loc := loc in let attribute _this attr = let module L = Location in let module P = Parsetree in let name = attr.P.attr_name.L.txt in let loc = !last_loc in let start = loc.L.loc_start.Lexing.pos_cnum in let attr_start = attr.P.attr_loc.L.loc_start.Lexing.pos_cnum in let attr_stop = attr.P.attr_loc.L.loc_end.Lexing.pos_cnum in let stop = max loc.L.loc_end.Lexing.pos_cnum attr_stop in let check_nested () = match !left_mark with | Some (first,_) -> raise (Nested_ellipses {first; second=attr_start}) | None -> () in match name with | "ellipsis" -> check_nested (); transforms := {Text_transform.kind=Ellipsis; start; stop } :: !transforms | "ellipsis.start" -> check_nested (); left_mark := Some (start, stop) | "ellipsis.stop" -> begin match !left_mark with | None -> raise (Unmatched_ellipsis {kind="right"; start; stop}) | Some (start', stop' ) -> let start, stop = min start start', max stop stop' in let transform = {Text_transform.kind=Ellipsis; start ; stop } in transforms := transform :: !transforms; left_mark := None end | _ -> () in f {Ast_iterator.default_iterator with location; attribute} x; (match !left_mark with | None -> () | Some (start,stop) -> raise (Unmatched_ellipsis {kind="left"; start; stop }) ); !transforms let find = function | Parsetree.Ptop_def ast -> extract (fun it -> it.structure it) ast | Parsetree.Ptop_dir _ -> [] end let format_input mode s = match mode with | Verbatim | Signature -> s | Toplevel -> match String.split_on_char '\n' s with | [] -> assert false | a :: q -> String.concat ~sep:"\n " ((toplevel_prompt^a)::q) let process_file file = let ic = try open_in file with _ -> failwith "Cannot read input file" in let phrase_start = ref 1 and phrase_stop = ref 1 in let incr_phrase_start () = incr phrase_start; phrase_stop := !phrase_start in let oc = try if !outfile = "-" then stdout else if !outfile = "" then open_out (replace_first ~!"\\.tex$" "" file ^ ".ml.tex") else open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0x666 !outfile with _ -> failwith "Cannot open output file" in let tex_fmt = Format.formatter_of_out_channel oc in let fatal x = Toplevel.fatal ic oc x in let re_spaces = "[ \t]*" in let re_start = ~!( {|\\begin{caml_example\(\*?\)}|} ^ re_spaces ^ {|\({toplevel}\|{verbatim}\|{signature}\)?|} ^ re_spaces ^ {|\(\[\(.*\)\]\)?|} ^ re_spaces ^ "$" ) in try while true do let input = ref (input_line ic) in incr_phrase_start(); if string_match re_start !input 0 then begin let omit_answer = matched_group 1 !input = "*" in let mode = match matched_group 2 !input with | exception Not_found -> raise (Missing_mode(file, !phrase_stop)) | "{toplevel}" -> Toplevel | "{verbatim}" -> Verbatim | "{signature}" -> Signature | _ -> assert false in if mode = Signature && not omit_answer then raise (Incompatible_options( Signature_with_visible_answer(file,!phrase_stop)) ); let explicit_stop = match mode with | Verbatim | Signature -> false | Toplevel -> true in let global_expected = try Output.expected @@ matched_group 4 !input with Not_found -> Output.Ok in start tex_fmt main [string_of_mode mode]; let first = ref true in let read_phrase () = let phrase = Buffer.create 256 in let rec read () = let input = incr phrase_stop; input_line ic in let implicit_stop = if string_match ~!"\\\\end{caml_example\\*?}[ \t]*$" input 0 then begin if !phrase_stop = 1 + !phrase_start then raise End_of_file else if explicit_stop then raise @@ Missing_double_semicolon (file,!phrase_stop) else true end else false in if Buffer.length phrase > 0 then Buffer.add_char phrase '\n'; let stop = implicit_stop || ( not (mode = Signature) && string_match ~!"\\(.*\\)[ \t]*;;[ \t]*$" input 0 ) in if not stop then ( Buffer.add_string phrase input; read () ) else begin decr phrase_stop; let last_input = if implicit_stop then "" else matched_group 1 input in let expected = if string_match ~!{|\(.*\)\[@@expect \(.*\)\]|} last_input 0 then ( Buffer.add_string phrase (matched_group 1 last_input); Output.local_expected @@ matched_group 2 last_input ) else (Buffer.add_string phrase last_input; global_expected) in if not implicit_stop then Buffer.add_string phrase ";;"; implicit_stop, Buffer.contents phrase, expected end in read () in try while true do let implicit_stop, phrase, expected = read_phrase () in let ast = Toplevel.parse file mode phrase in let ellipses = Ellipsis.find ast in let () = Location.reset () in let () = Toplevel.(exec out_fmt) ast in let out = Toplevel.read_output () in let error_msgs = String.concat "" (out.warnings @ [out.error]) in let output = String.concat "" [error_msgs; out.stdout; out.values] in let status = Output.status out.warnings out.error in if status <> expected then ( let source = Output.{ file; lines = (!phrase_start, !phrase_stop); phrase; output } in raise (Output.Unexpected_status {Output.got=status; expected; source} ) ) else ( incr phrase_stop; phrase_start := !phrase_stop ); let phrase = let underline = List.map (fun (x,y) -> Text_transform.underline x y) out.underlined in Text_transform.apply (underline @ ellipses) file !phrase_stop phrase in (* Special characters may also appear in output strings -Didier *) let output = Text_transform.escape_specials output in let phrase = format_input mode phrase in let final_output = if omit_answer then error_msgs else output in start tex_fmt phrase_env []; code_env input_env tex_fmt phrase; if String.length final_output > 0 then code_env (Output.env status) tex_fmt final_output; stop tex_fmt phrase_env; flush oc; first := false; if implicit_stop then raise End_of_file done with End_of_file -> phrase_start:= !phrase_stop; stop tex_fmt main end else if string_match ~!"\\\\begin{caml_eval}[ \t]*$" !input 0 then begin let eval_buffer = Buffer.create 256 in while input := input_line ic; not (string_match ~!"\\\\end{caml_eval}[ \t]*$" !input 0) do Buffer.add_string eval_buffer !input; Buffer.add_char eval_buffer '\n'; if string_match ~!".*;;[ \t]*$" !input 0 then begin Toplevel.eval eval_buffer end done; if Buffer.length eval_buffer > 0 then ( Buffer.add_string eval_buffer ";;\n"; Toplevel.eval eval_buffer ) end else begin Format.fprintf tex_fmt "%s\n" !input; Format.pp_print_flush tex_fmt () end done with | End_of_file -> close_in ic; close_out oc | Output.Unexpected_status r -> ( Output.print_unexpected r; close_in ic; close_out oc; exit 1 ) | Output.Parsing_error (k,s) -> ( Output.print_parsing_error k s; close_in ic; close_out oc; exit 1 ) | Phrase_parsing s -> fatal "when parsing the following phrase:@ %s" s | Missing_double_semicolon (file, line_number) -> fatal "when evaluating a caml_example environment in %s:@;\ missing \";;\" at line %d" file (line_number-2) | Missing_mode (file, line_number) -> fatal "when parsing a caml_example environment in %s:@;\ missing mode argument at line %d,@ \ available modes {toplevel,verbatim}" file (line_number-2) | Incompatible_options Signature_with_visible_answer (file, line_number) -> fatal "when parsing a caml_example environment in@ \ %s, line %d:@,\ the signature mode is only compatible with \"caml_example*\"@ \ @{<hint>Hint@}: did you forget to add \"*\"?" file (line_number-2); | Text_transform.Intersection {line;file;left;right} -> fatal "when evaluating a caml_example environment in %s, line %d:@ \ Textual transforms must be well-separated.@ The \"%a\" transform \ spanned the interval %d-%d,@ \ intersecting with another \"%a\" transform @ \ on the %d-%d interval.@ \ @{<hint>Hint@}: did you try to elide a code fragment \ which raised a warning?" file (line-2) Text_transform.pp left.kind left.start left.stop Text_transform.pp right.kind right.start right.stop | Ellipsis.Unmatched_ellipsis {kind;start;stop} -> fatal "when evaluating a caml_example environment,@ \ the %s mark at position %d-%d was unmatched" kind start stop | Ellipsis.Nested_ellipses {first;second} -> fatal "when evaluating a caml_example environment,@ \ there were two nested ellipsis attribute.@ The first one \ started at position %d,@ the second one at %d" first second let _ = if !outfile <> "-" && !outfile <> "" then begin try close_out (open_out !outfile) with _ -> failwith "Cannot open output file" end; List.iter process_file (List.rev !files);
null
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/tools/ocamltex.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. ************************************************************************ * Restrict the number of latex environment * Initialize the toplevel loop, redirect stdout and stderr, capture warnings and error messages * error message text * warning messages text * toplevel output * output printed on the toplevel stdout * locations to underline in input phrases * Redirect the stdout * Store character intervals directly * Record locations in the main error and suberrors without printing them The following fields are kept identical to [base], listed explicitly so that future field additions result in an error -- using (Location.batch_mode_printer with ...) would be the symmetric problem to a fragile pattern-matching. * Capture warnings and keep them in a list Extend [printer_register_locs] the inner ( *\* )* group is here to clean the starting "*" introduced for multiline comments * exec and ignore all output from the toplevel * The Output module deals with the analysis and classification of the interpreter output and the parsing of status-related options or annotations for the caml_example environment * Interpreter output status * Local annotation: [ [@@expect (*annotation * Global environment option: [\begin{caml_example}[option[=value]] ... \end{caml_example}] * Pretty printer for status * Pretty printer for status preceded with an undefined determinant * {1 Output analysis} * Merge consecutive transforms: - drop nested underline transform - raise an error with transforms nested under an ellipsis - raise an error when consecutive transforms partially overlap no overlap, the next transform starts after the end of the current active transform we check that [t] is still conflict-free with our parent transforms not nested nested transforms no nesting allowed under an ellipsis underlined ellipsis are allowed * This module implements the extraction of ellipsis locations from phrases. An ellipsis is either an [[@ellipsis]] attribute, or a pair of [[@@@ellipsis.start]...[@@@ellipsis.stop]] attributes. * raised when an [[@@@ellipsis.start]] or [[@@@ellipsis.stop]] is not paired with another ellipsis attribute * raised by [[@@@ellipsis.start][@@@ellipsis.start]] stored position of [@@@ellipsis.start] Special characters may also appear in output strings -Didier
, projet Gallium , INRIA Paris , Nagoya University Copyright 2018 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the [@@@warning "+a-4-6-40..42-44-48"] open StdLabels open Str let camlprefix = "caml" let latex_escape s = String.concat "" ["$"; s; "$"] let toplevel_prompt= latex_escape {|\?|} ^ " " let camlbunderline = "<<" let camleunderline = ">>" type env = Env of string let main = Env "example" let input_env = Env "input" let ok_output = Env "output" let error = Env "error" let warning = Env "warn" let phrase_env = Env "" let start out (Env s) args = Format.fprintf out "\\begin{%s%s}" camlprefix s; List.iter (Format.fprintf out "{%s}") args; Format.fprintf out "\n" let stop out (Env s) = Format.fprintf out "\\end{%s%s}" camlprefix s; Format.fprintf out "\n" let code_env env out s = let sep = if s.[String.length s - 1] = '\n' then "" else "\n" in Format.fprintf out "%a%s%s%a" (fun ppf env -> start ppf env []) env s sep stop env type example_mode = Toplevel | Verbatim | Signature let string_of_mode = function | Toplevel -> "toplevel" | Verbatim -> "verbatim" | Signature -> "signature" let verbose = ref true let linelen = ref 72 let outfile = ref "" let cut_at_blanks = ref false let files = ref [] let repo_root = ref "" let (~!) = let memo = ref [] in fun key -> try List.assq key !memo with Not_found -> let data = Str.regexp key in memo := (key, data) :: !memo; data exception Phrase_parsing of string module Toplevel = struct type output = { underlined : (int * int) list } let buffer_fmt () = let b = Buffer.create 30 in b, Format.formatter_of_buffer b let error_fmt = buffer_fmt () let warning_fmt = buffer_fmt () let out_fmt = buffer_fmt () let flush_fmt (b,fmt) = Format.pp_print_flush fmt (); let r = Buffer.contents b in Buffer.reset b; r let stdout_out, stdout_in = Unix.pipe ~cloexec:true () let () = Unix.dup2 stdout_in Unix.stdout let self_error_fmt = Format.formatter_of_out_channel stderr let eprintf = Format.eprintf let read_stdout = let size = 50 in let b = Bytes.create size in let buffer = Buffer.create 100 in let rec read_toplevel_stdout () = match Unix.select[stdout_out][][] 0. with | [_a], _, _ -> let n = Unix.read stdout_out b 0 size in Buffer.add_subbytes buffer b 0 n; if n = size then read_toplevel_stdout () | _ -> () in fun () -> let () = flush stdout; read_toplevel_stdout () in let r = Buffer.contents buffer in Buffer.reset buffer; r let locs = ref [] let register_loc (loc : Location.t) = let startchar = loc.loc_start.pos_cnum in let endchar = loc.loc_end.pos_cnum in if startchar >= 0 then locs := (startchar, endchar) :: !locs let printer_register_locs = let base = Location.batch_mode_printer in { Location.pp_main_loc = (fun _ _ _ loc -> register_loc loc); pp_submsg_loc = (fun _ _ _ loc -> register_loc loc); pp = base.pp; pp_report_kind = base.pp_report_kind; pp_main_txt = base.pp_main_txt; pp_submsgs = base.pp_submsgs; pp_submsg = base.pp_submsg; pp_submsg_txt = base.pp_submsg_txt; } let warnings = ref [] let report_printer = let pp self ppf report = match report.Location.kind with | Location.Report_warning _ | Location.Report_warning_as_error _ -> printer_register_locs.pp self (snd warning_fmt) report; let w = flush_fmt warning_fmt in warnings := w :: !warnings | _ -> printer_register_locs.pp self ppf report in { printer_register_locs with pp } let fatal ic oc fmt = Format.kfprintf (fun ppf -> Format.fprintf ppf "@]@."; close_in ic; close_out oc; exit 1) self_error_fmt ("@[<hov 2> Error " ^^ fmt) let init () = Location.report_printer := (fun () -> report_printer); Clflags.color := Some Misc.Color.Never; Clflags.no_std_include := true; Compenv.last_include_dirs := [Filename.concat !repo_root "stdlib"]; Compmisc.init_path ~auto_include:Load_path.no_auto_include (); try Toploop.initialize_toplevel_env (); Sys.interactive := false with _ -> (eprintf "Invalid repo root: %s?%!" !repo_root; exit 2) let exec (_,ppf) p = try ignore @@ Toploop.execute_phrase true ppf p with exn -> let bt = Printexc.get_raw_backtrace () in begin try Location.report_exception (snd error_fmt) exn with _ -> eprintf "Uncaught exception: %s\n%s\n" (Printexc.to_string exn) (Printexc.raw_backtrace_to_string bt) end let parse fname mode s = let lex = Lexing.from_string s in Location.init lex fname; Location.input_name := fname; Location.input_lexbuf := Some lex; try match mode with | Toplevel -> Parse.toplevel_phrase lex | Verbatim -> Parsetree.Ptop_def (Parse.implementation lex) | Signature -> let sign = Parse.interface lex in let name = Location.mknoloc "wrap" in let str = Ast_helper.[Str.modtype @@ Mtd.mk ~typ:(Mty.signature sign) name] in Parsetree.Ptop_def str with | Lexer.Error _ | Syntaxerr.Error _ -> raise (Phrase_parsing s) let take x = let r = !x in x := []; r let read_output () = let warnings = take warnings in let error = flush_fmt error_fmt in let values = replace_first ~!{|^#\( *\*\)* *|} "" @@ flush_fmt out_fmt in let underlined = take locs in let stdout = read_stdout () in { values; warnings; error; stdout; underlined } let eval b = let s = Buffer.contents b in let ast = Parse.toplevel_phrase (Lexing.from_string s) in exec out_fmt ast; ignore (read_output()); Buffer.reset b end let () = Arg.parse ["-n", Arg.Int (fun n -> linelen := n), "line length"; "-o", Arg.String (fun s -> outfile := s), "output"; "-repo-root", Arg.String ((:=) repo_root ), "repo root"; "-w", Arg.Set cut_at_blanks, "cut at blanks"; "-v", Arg.Bool (fun b -> verbose := b ), "output result on stderr" ] (fun s -> files := s :: !files) "ocamltex: "; Toplevel.init () module Output = struct type status = | Ok | Warning of int | Error type kind = let pp_status ppf = function | Error -> Format.fprintf ppf "error" | Ok -> Format.fprintf ppf "ok" | Warning n -> Format.fprintf ppf "warning %d" n let pp_a_status ppf = function | Error -> Format.fprintf ppf "an error" | Ok -> Format.fprintf ppf "an ok" | Warning n -> Format.fprintf ppf "a warning %d" n * { 1 Related latex environment } let env = function | Error -> error | Warning _ -> warning | Ok -> ok_output * { 1 Exceptions } exception Parsing_error of kind * string type source = { file : string; lines : int * int; phrase : string; output : string } type unexpected_report = {source : source; expected : status; got : status} exception Unexpected_status of unexpected_report let print_source ppf {file; lines = (start, stop); phrase; output} = Format.fprintf ppf "%s, lines %d to %d:\n\"\n%s\n\"\n\"\n%s\n\"." file start stop phrase output let print_unexpected {source; expected; got} = if expected = Ok then Toplevel.eprintf "Error when evaluating a caml_example environment in %a\n\ Unexpected %a status.\n\ If %a status was expected, add an [@@expect %a] annotation.\n" print_source source pp_status got pp_a_status got pp_status got else Toplevel.eprintf "Error when evaluating a guarded caml_example environment in %a\n\ Unexpected %a status, %a status was expected.\n\ If %a status was in fact expected, change the status annotation to \ [@@expect %a].\n" print_source source pp_status got pp_a_status expected pp_a_status got pp_status got; flush stderr let print_parsing_error k s = match k with | Option -> Toplevel.eprintf "Unknown caml_example option: [%s].\n\ Supported options are \"ok\",\"error\", or \"warning=n\" (with n \ a warning number).\n" s | Annotation -> Toplevel.eprintf "Unknown caml_example phrase annotation: [@@expect %s].\n\ Supported annotations are [@@expect ok], [@@expect error],\n\ and [@@expect warning n] (with n a warning number).\n" s let catch_error = function | "" -> None | _ -> Some Error let catch_warning = function | [] -> None | s :: _ when string_match ~!{| *Warning \([0-9]+\)\( \[[a-z-]+\]\)?:|} s 0 -> Some (Warning (int_of_string @@ matched_group 1 s)) | _ -> None let status ws es = match catch_warning ws, catch_error es with | Some w, _ -> w | None, Some e -> e | None, None -> Ok * { 1 Parsing caml_example options } * [ warning = n ] options for caml_example options let parse_warning s = if string_match ~!{|warning=\([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None * [ warning n ] annotations let parse_local_warning s = if string_match ~!{|warning \([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None let parse_error s = if s="error" then Some Error else None let parse_ok s = if s = "ok" then Some Ok else None * the environment - wide expected status output let expected s = match parse_warning s, parse_error s with | Some w, _ -> w | None, Some e -> e | None, None -> raise (Parsing_error (Option,s)) * the local ( i.e. phrase - wide ) expected status output let local_expected s = match parse_local_warning s, parse_error s, parse_ok s with | Some w, _, _ -> w | None, Some e, _ -> e | None, None, Some ok -> ok | None, None, None -> raise (Parsing_error (Annotation,s)) end module Text_transform = struct type kind = | Underline | Ellipsis type t = { kind : kind; start : int; stop : int} exception Intersection of { line : int; file : string; left : t; right : t; } let pp ppf = function | Underline -> Format.fprintf ppf "underline" | Ellipsis -> Format.fprintf ppf "ellipsis" let underline start stop = { kind = Underline; start; stop} let escape_specials s = s |> global_replace ~!{|\$|} {|$\textdollar$|} let rec apply_transform input (pos,underline_stop,out) t = if pos >= String.length input then pos, underline_stop, out else match underline_stop with | Some stop when stop <= t.start -> let f = escape_specials (String.sub input ~pos ~len:(stop - pos)) in let out = camleunderline :: f :: out in apply_transform input (stop,None,out) t | _ -> let out = escape_specials (String.sub input ~pos ~len:(t.start - pos))::out in match t.kind with | Ellipsis -> t.stop, underline_stop, latex_escape {|\ldots|} :: out | Underline -> t.start, Some t.stop, camlbunderline :: out let merge_transforms file line ts = let rec merge (active, active_stack, acc) t = if active.stop <= t.start then match active_stack with | [] -> there were no other active transforms , the new transform becomes the active one the active one *) t, [], t :: acc | last :: active_stack -> merge (last, active_stack,acc) t raise (Intersection {line; file; left = active; right=t}) match active.kind, t.kind with raise (Intersection {line; file; left = active; right=t}) (t , active :: active_stack, t :: acc) | Underline, Underline -> multiple underlining are flattened to one (t, active :: active_stack, acc) in match ts with | [] -> [] | a :: q -> let _, _, ts = List.fold_left ~f:merge ~init:(a,[],[a]) q in List.rev ts let apply ts file line s = remove duplicated transforms that can appear due to duplicated parse tree elements . For instance , [ let f : ( _ [ @ellipsis ] = ( ) ] is transformed to [ let f : ( _ [ @ellipsis ] ) = ( ( ): ( _ [ @ellipsis ] ) ] with the same location for the two ellipses . duplicated parse tree elements. For instance, [let f : (_ [@ellipsis] = ()] is transformed to [let f: (_ [@ellipsis]) = (():(_ [@ellipsis])] with the same location for the two ellipses. *) let ts = List.sort_uniq compare ts in let ts = List.sort (fun x y -> compare x.start y.start) ts in let ts = merge_transforms file line ts in let last, underline, ls = List.fold_left ~f:(apply_transform s) ~init:(0,None,[]) ts in let last, ls = match underline with | None -> last, ls | Some stop -> let f = escape_specials (String.sub s ~pos:last ~len:(stop - last)) in stop, camleunderline :: f :: ls in let ls = let n = String.length s in if last = n then ls else escape_specials (String.sub s last (n-last)) :: ls in String.concat "" (List.rev ls) end exception Missing_double_semicolon of string * int exception Missing_mode of string * int type incompatibility = | Signature_with_visible_answer of string * int exception Incompatible_options of incompatibility module Ellipsis = struct exception Unmatched_ellipsis of {kind : string; start : int; stop : int} exception Nested_ellipses of {first : int ; second : int} let extract f x = let transforms = ref [] in let last_loc = ref Location.none in let location _this loc = we rely on the fact that the default iterator calls first the location subiterator , then the attribute subiterator the location subiterator, then the attribute subiterator *) last_loc := loc in let attribute _this attr = let module L = Location in let module P = Parsetree in let name = attr.P.attr_name.L.txt in let loc = !last_loc in let start = loc.L.loc_start.Lexing.pos_cnum in let attr_start = attr.P.attr_loc.L.loc_start.Lexing.pos_cnum in let attr_stop = attr.P.attr_loc.L.loc_end.Lexing.pos_cnum in let stop = max loc.L.loc_end.Lexing.pos_cnum attr_stop in let check_nested () = match !left_mark with | Some (first,_) -> raise (Nested_ellipses {first; second=attr_start}) | None -> () in match name with | "ellipsis" -> check_nested (); transforms := {Text_transform.kind=Ellipsis; start; stop } :: !transforms | "ellipsis.start" -> check_nested (); left_mark := Some (start, stop) | "ellipsis.stop" -> begin match !left_mark with | None -> raise (Unmatched_ellipsis {kind="right"; start; stop}) | Some (start', stop' ) -> let start, stop = min start start', max stop stop' in let transform = {Text_transform.kind=Ellipsis; start ; stop } in transforms := transform :: !transforms; left_mark := None end | _ -> () in f {Ast_iterator.default_iterator with location; attribute} x; (match !left_mark with | None -> () | Some (start,stop) -> raise (Unmatched_ellipsis {kind="left"; start; stop }) ); !transforms let find = function | Parsetree.Ptop_def ast -> extract (fun it -> it.structure it) ast | Parsetree.Ptop_dir _ -> [] end let format_input mode s = match mode with | Verbatim | Signature -> s | Toplevel -> match String.split_on_char '\n' s with | [] -> assert false | a :: q -> String.concat ~sep:"\n " ((toplevel_prompt^a)::q) let process_file file = let ic = try open_in file with _ -> failwith "Cannot read input file" in let phrase_start = ref 1 and phrase_stop = ref 1 in let incr_phrase_start () = incr phrase_start; phrase_stop := !phrase_start in let oc = try if !outfile = "-" then stdout else if !outfile = "" then open_out (replace_first ~!"\\.tex$" "" file ^ ".ml.tex") else open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0x666 !outfile with _ -> failwith "Cannot open output file" in let tex_fmt = Format.formatter_of_out_channel oc in let fatal x = Toplevel.fatal ic oc x in let re_spaces = "[ \t]*" in let re_start = ~!( {|\\begin{caml_example\(\*?\)}|} ^ re_spaces ^ {|\({toplevel}\|{verbatim}\|{signature}\)?|} ^ re_spaces ^ {|\(\[\(.*\)\]\)?|} ^ re_spaces ^ "$" ) in try while true do let input = ref (input_line ic) in incr_phrase_start(); if string_match re_start !input 0 then begin let omit_answer = matched_group 1 !input = "*" in let mode = match matched_group 2 !input with | exception Not_found -> raise (Missing_mode(file, !phrase_stop)) | "{toplevel}" -> Toplevel | "{verbatim}" -> Verbatim | "{signature}" -> Signature | _ -> assert false in if mode = Signature && not omit_answer then raise (Incompatible_options( Signature_with_visible_answer(file,!phrase_stop)) ); let explicit_stop = match mode with | Verbatim | Signature -> false | Toplevel -> true in let global_expected = try Output.expected @@ matched_group 4 !input with Not_found -> Output.Ok in start tex_fmt main [string_of_mode mode]; let first = ref true in let read_phrase () = let phrase = Buffer.create 256 in let rec read () = let input = incr phrase_stop; input_line ic in let implicit_stop = if string_match ~!"\\\\end{caml_example\\*?}[ \t]*$" input 0 then begin if !phrase_stop = 1 + !phrase_start then raise End_of_file else if explicit_stop then raise @@ Missing_double_semicolon (file,!phrase_stop) else true end else false in if Buffer.length phrase > 0 then Buffer.add_char phrase '\n'; let stop = implicit_stop || ( not (mode = Signature) && string_match ~!"\\(.*\\)[ \t]*;;[ \t]*$" input 0 ) in if not stop then ( Buffer.add_string phrase input; read () ) else begin decr phrase_stop; let last_input = if implicit_stop then "" else matched_group 1 input in let expected = if string_match ~!{|\(.*\)\[@@expect \(.*\)\]|} last_input 0 then ( Buffer.add_string phrase (matched_group 1 last_input); Output.local_expected @@ matched_group 2 last_input ) else (Buffer.add_string phrase last_input; global_expected) in if not implicit_stop then Buffer.add_string phrase ";;"; implicit_stop, Buffer.contents phrase, expected end in read () in try while true do let implicit_stop, phrase, expected = read_phrase () in let ast = Toplevel.parse file mode phrase in let ellipses = Ellipsis.find ast in let () = Location.reset () in let () = Toplevel.(exec out_fmt) ast in let out = Toplevel.read_output () in let error_msgs = String.concat "" (out.warnings @ [out.error]) in let output = String.concat "" [error_msgs; out.stdout; out.values] in let status = Output.status out.warnings out.error in if status <> expected then ( let source = Output.{ file; lines = (!phrase_start, !phrase_stop); phrase; output } in raise (Output.Unexpected_status {Output.got=status; expected; source} ) ) else ( incr phrase_stop; phrase_start := !phrase_stop ); let phrase = let underline = List.map (fun (x,y) -> Text_transform.underline x y) out.underlined in Text_transform.apply (underline @ ellipses) file !phrase_stop phrase in let output = Text_transform.escape_specials output in let phrase = format_input mode phrase in let final_output = if omit_answer then error_msgs else output in start tex_fmt phrase_env []; code_env input_env tex_fmt phrase; if String.length final_output > 0 then code_env (Output.env status) tex_fmt final_output; stop tex_fmt phrase_env; flush oc; first := false; if implicit_stop then raise End_of_file done with End_of_file -> phrase_start:= !phrase_stop; stop tex_fmt main end else if string_match ~!"\\\\begin{caml_eval}[ \t]*$" !input 0 then begin let eval_buffer = Buffer.create 256 in while input := input_line ic; not (string_match ~!"\\\\end{caml_eval}[ \t]*$" !input 0) do Buffer.add_string eval_buffer !input; Buffer.add_char eval_buffer '\n'; if string_match ~!".*;;[ \t]*$" !input 0 then begin Toplevel.eval eval_buffer end done; if Buffer.length eval_buffer > 0 then ( Buffer.add_string eval_buffer ";;\n"; Toplevel.eval eval_buffer ) end else begin Format.fprintf tex_fmt "%s\n" !input; Format.pp_print_flush tex_fmt () end done with | End_of_file -> close_in ic; close_out oc | Output.Unexpected_status r -> ( Output.print_unexpected r; close_in ic; close_out oc; exit 1 ) | Output.Parsing_error (k,s) -> ( Output.print_parsing_error k s; close_in ic; close_out oc; exit 1 ) | Phrase_parsing s -> fatal "when parsing the following phrase:@ %s" s | Missing_double_semicolon (file, line_number) -> fatal "when evaluating a caml_example environment in %s:@;\ missing \";;\" at line %d" file (line_number-2) | Missing_mode (file, line_number) -> fatal "when parsing a caml_example environment in %s:@;\ missing mode argument at line %d,@ \ available modes {toplevel,verbatim}" file (line_number-2) | Incompatible_options Signature_with_visible_answer (file, line_number) -> fatal "when parsing a caml_example environment in@ \ %s, line %d:@,\ the signature mode is only compatible with \"caml_example*\"@ \ @{<hint>Hint@}: did you forget to add \"*\"?" file (line_number-2); | Text_transform.Intersection {line;file;left;right} -> fatal "when evaluating a caml_example environment in %s, line %d:@ \ Textual transforms must be well-separated.@ The \"%a\" transform \ spanned the interval %d-%d,@ \ intersecting with another \"%a\" transform @ \ on the %d-%d interval.@ \ @{<hint>Hint@}: did you try to elide a code fragment \ which raised a warning?" file (line-2) Text_transform.pp left.kind left.start left.stop Text_transform.pp right.kind right.start right.stop | Ellipsis.Unmatched_ellipsis {kind;start;stop} -> fatal "when evaluating a caml_example environment,@ \ the %s mark at position %d-%d was unmatched" kind start stop | Ellipsis.Nested_ellipses {first;second} -> fatal "when evaluating a caml_example environment,@ \ there were two nested ellipsis attribute.@ The first one \ started at position %d,@ the second one at %d" first second let _ = if !outfile <> "-" && !outfile <> "" then begin try close_out (open_out !outfile) with _ -> failwith "Cannot open output file" end; List.iter process_file (List.rev !files);
67ab51d24baab60ab0272c2184b238e33319c8e2514a7dfa79bb56555fca99c4
sharplispers/montezuma
packages.lisp
packages.lisp --- create an index from a directory tree Copyright ( C ) 2008 , Yoni Rabkin < > ;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the ;; License, or (at your option) any later version. ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA ;;; Code: (defpackage #:montezuma-indexfiles (:use #:common-lisp #:cl-fad #:montezuma) I took this right from the Montezuma 0.1.1 source . Hopefully all ;; this shadowing will be fixed in a future release. (:shadowing-import-from #:common-lisp #:directory #:read-byte #:write-byte #:write-string #:close #:delete-file #:rename-file #:count #:search #:merge #:file-length #:read #:write #:optimize #:sort)) packages.lisp ends here .
null
https://raw.githubusercontent.com/sharplispers/montezuma/ee2129eece7065760de4ebbaeffaadcb27644738/contrib/montezuma-indexfiles/_darcs/pristine/packages.lisp
lisp
This program is free software; you can redistribute it and/or either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software Code: this shadowing will be fixed in a future release.
packages.lisp --- create an index from a directory tree Copyright ( C ) 2008 , Yoni Rabkin < > modify it under the terms of the GNU General Public License as You should have received a copy of the GNU General Public License Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA (defpackage #:montezuma-indexfiles (:use #:common-lisp #:cl-fad #:montezuma) I took this right from the Montezuma 0.1.1 source . Hopefully all (:shadowing-import-from #:common-lisp #:directory #:read-byte #:write-byte #:write-string #:close #:delete-file #:rename-file #:count #:search #:merge #:file-length #:read #:write #:optimize #:sort)) packages.lisp ends here .
f779d01a6d566561fe1bf5d8b390bc3bfe2998730313680feb3012c1b19f08c1
mzp/coq-ide-for-ios
refl_omega.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author : France Télécom R&D Licence : LGPL version 2.1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author: Pierre Crégut - France Télécom R&D Licence : LGPL version 2.1 *************************************************************************) open Util open Const_omega module OmegaSolver = Omega.MakeOmegaSolver (Bigint) open OmegaSolver (* \section{Useful functions and flags} *) (* Especially useful debugging functions *) let debug = ref false let show_goal gl = if !debug then Pp.ppnl (Tacmach.pr_gls gl); Tacticals.tclIDTAC gl let pp i = print_int i; print_newline (); flush stdout (* More readable than the prefix notation *) let (>>) = Tacticals.tclTHEN let mkApp = Term.mkApp (* \section{Types} \subsection{How to walk in a term} To represent how to get to a proposition. Only choice points are kept (branch to choose in a disjunction and identifier of the disjunctive connector) *) type direction = Left of int | Right of int (* Step to find a proposition (operators are at most binary). A list is a path *) type occ_step = O_left | O_right | O_mono type occ_path = occ_step list chemin identifiant une proposition d'une liste de pas à partir de la racine de l'hypothèse d'une liste de pas à partir de la racine de l'hypothèse *) type occurence = {o_hyp : Names.identifier; o_path : occ_path} (* \subsection{refiable formulas} *) type oformula = (* integer *) | Oint of Bigint.bigint (* recognized binary and unary operations *) | Oplus of oformula * oformula | Omult of oformula * oformula | Ominus of oformula * oformula | Oopp of oformula (* an atome in the environment *) | Oatom of int (* weird expression that cannot be translated *) | Oufo of oformula Operators for comparison recognized by Omega type comparaison = Eq | Leq | Geq | Gt | Lt | Neq Type des prédicats réifiés ( fragment de calcul . Les * quantifications sont externes au langage ) * quantifications sont externes au langage) *) type oproposition = Pequa of Term.constr * oequation | Ptrue | Pfalse | Pnot of oproposition | Por of int * oproposition * oproposition | Pand of int * oproposition * oproposition | Pimp of int * oproposition * oproposition | Pprop of Term.constr (* Les équations ou proposiitions atomiques utiles du calcul *) and oequation = { e_comp: comparaison; (* comparaison *) e_left: oformula; (* formule brute gauche *) e_right: oformula; (* formule brute droite *) tactique de normalisation e_origin: occurence; (* l'hypothèse dont vient le terme *) e_negated: bool; (* vrai si apparait en position nié après normalisation *) liste des points do nt dépend l'accès à l'équation avec la direction ( branche ) pour y accéder dépend l'accès à l'équation avec la direction (branche) pour y accéder *) e_omega: afine (* la fonction normalisée *) } \subsection{Proof context } This environment codes \begin{itemize } \item the terms and propositions that are given as parameters of the reified proof ( and are represented as variables in the reified goals ) \item translation functions linking the decision procedure and the Coq proof \end{itemize } This environment codes \begin{itemize} \item the terms and propositions that are given as parameters of the reified proof (and are represented as variables in the reified goals) \item translation functions linking the decision procedure and the Coq proof \end{itemize} *) type environment = { La liste des termes non reifies constituant l'environnement global mutable terms : Term.constr list; (* La meme chose pour les propositions *) mutable props : Term.constr list; (* Les variables introduites par omega *) mutable om_vars : (oformula * int) list; Traduction des indices utilisés ici en les indices utilisés par * la tactique Omega après dénombrement des variables utiles * la tactique Omega après dénombrement des variables utiles *) real_indices : (int,int) Hashtbl.t; mutable cnt_connectors : int; equations : (int,oequation) Hashtbl.t; constructors : (int, occurence) Hashtbl.t } \subsection{Solution tree } Définition d'une solution trouvée par forme , d'un ensemble d'équation do nt dépend la solution et d'une trace Définition d'une solution trouvée par Omega sous la forme d'un identifiant, d'un ensemble d'équation dont dépend la solution et d'une trace *) La liste des dépendances est triée et sans redondance type solution = { s_index : int; s_equa_deps : int list; s_trace : action list } Arbre de solution résolvant complètement un ensemble de systèmes type solution_tree = Leaf of solution un noeud interne représente un point correspondant à l'élimination d'un connecteur ( typ . disjonction ) . Le premier argument est l'identifiant du connecteur l'élimination d'un connecteur générant plusieurs buts (typ. disjonction). Le premier argument est l'identifiant du connecteur *) | Tree of int * solution_tree * solution_tree (* Représentation de l'environnement extrait du but initial sous forme de chemins pour extraire des equations ou d'hypothèses *) type context_content = CCHyp of occurence | CCEqua of int (* \section{Specific utility functions to handle base types} *) négation du but final let id_concl = Names.id_of_string "__goal__" Initialisation de l'environnement de réification de la tactique let new_environment () = { terms = []; props = []; om_vars = []; cnt_connectors = 0; real_indices = Hashtbl.create 7; equations = Hashtbl.create 7; constructors = Hashtbl.create 7; } Génération d'un nom d'équation let new_connector_id env = env.cnt_connectors <- succ env.cnt_connectors; env.cnt_connectors (* Calcul de la branche complémentaire *) let barre = function Left x -> Right x | Right x -> Left x (* Identifiant associé à une branche *) let indice = function Left x | Right x -> x Affichage de l'environnement de réification ( termes et propositions ) let print_env_reification env = let rec loop c i = function [] -> Printf.printf " ===============================\n\n" | t :: l -> Printf.printf " (%c%02d) := " c i; Pp.ppnl (Printer.pr_lconstr t); Pp.flush_all (); loop c (succ i) l in print_newline (); Printf.printf " ENVIRONMENT OF PROPOSITIONS :\n\n"; loop 'P' 0 env.props; Printf.printf " ENVIRONMENT OF TERMS :\n\n"; loop 'V' 0 env.terms (* \subsection{Gestion des environnements de variable pour Omega} *) generation pour Omega let new_omega_eq, rst_omega_eq = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) generation variable pour Omega let new_omega_var, rst_omega_var = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) (* Affichage des variables d'un système *) let display_omega_var i = Printf.sprintf "OV%d" i Recherche la variable codant un terme pour Omega et crée la variable dans l'environnement . Cas ou la variable dans ( le plus souvent ) l'environnement si il n'existe pas. Cas ou la variable dans Omega représente le terme d'un monome (le plus souvent un atome) *) let intern_omega env t = begin try List.assoc t env.om_vars with Not_found -> let v = new_omega_var () in env.om_vars <- (t,v) :: env.om_vars; v end Ajout forcé d'un lien entre un terme et une variable Cas où la variable est créée par Omega et où il faut la lier à un atome variable est créée par Omega et où il faut la lier après coup à un atome réifié introduit de force *) let intern_omega_force env t v = env.om_vars <- (t,v) :: env.om_vars (* Récupère le terme associé à une variable *) let unintern_omega env id = let rec loop = function [] -> failwith "unintern" | ((t,j)::l) -> if id = j then t else loop l in loop env.om_vars \subsection{Gestion des environnements de variable pour la réflexion } Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies . Attention il s'agit de l'environnement initial contenant tout . calcul des variables utiles . Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies. Attention il s'agit de l'environnement initial contenant tout. Il faudra le réduire après calcul des variables utiles. *) let add_reified_atom t env = try list_index0 t env.terms with Not_found -> let i = List.length env.terms in env.terms <- env.terms @ [t]; i let get_reified_atom env = try List.nth env.terms with _ -> failwith "get_reified_atom" \subsection{Gestion de l'environnement de proposition pour Omega } (* ajout d'une proposition *) let add_prop env t = try list_index0 t env.props with Not_found -> let i = List.length env.props in env.props <- env.props @ [t]; i accès a une proposition let get_prop v env = try List.nth v env with _ -> failwith "get_prop" (* \subsection{Gestion du nommage des équations} *) (* Ajout d'une equation dans l'environnement de reification *) let add_equation env e = let id = e.e_omega.id in try let _ = Hashtbl.find env.equations id in () with Not_found -> Hashtbl.add env.equations id e (* accès a une equation *) let get_equation env id = try Hashtbl.find env.equations id with e -> Printf.printf "Omega Equation %d non trouvée\n" id; raise e (* Affichage des termes réifiés *) let rec oprint ch = function | Oint n -> Printf.fprintf ch "%s" (Bigint.to_string n) | Oplus (t1,t2) -> Printf.fprintf ch "(%a + %a)" oprint t1 oprint t2 | Omult (t1,t2) -> Printf.fprintf ch "(%a * %a)" oprint t1 oprint t2 | Ominus(t1,t2) -> Printf.fprintf ch "(%a - %a)" oprint t1 oprint t2 | Oopp t1 ->Printf.fprintf ch "~ %a" oprint t1 | Oatom n -> Printf.fprintf ch "V%02d" n | Oufo x -> Printf.fprintf ch "?" let rec pprint ch = function Pequa (_,{ e_comp=comp; e_left=t1; e_right=t2 }) -> let connector = match comp with Eq -> "=" | Leq -> "<=" | Geq -> ">=" | Gt -> ">" | Lt -> "<" | Neq -> "!=" in Printf.fprintf ch "%a %s %a" oprint t1 connector oprint t2 | Ptrue -> Printf.fprintf ch "TT" | Pfalse -> Printf.fprintf ch "FF" | Pnot t -> Printf.fprintf ch "not(%a)" pprint t | Por (_,t1,t2) -> Printf.fprintf ch "(%a or %a)" pprint t1 pprint t2 | Pand(_,t1,t2) -> Printf.fprintf ch "(%a and %a)" pprint t1 pprint t2 | Pimp(_,t1,t2) -> Printf.fprintf ch "(%a => %a)" pprint t1 pprint t2 | Pprop c -> Printf.fprintf ch "Prop" let rec weight env = function | Oint _ -> -1 | Oopp c -> weight env c | Omult(c,_) -> weight env c | Oplus _ -> failwith "weight" | Ominus _ -> failwith "weight minus" | Oufo _ -> -1 | Oatom _ as c -> (intern_omega env c) \section{Passage entre oformules et représentation interne de Omega } (* \subsection{Oformula vers Omega} *) let omega_of_oformula env kind = let rec loop accu = function | Oplus(Omult(v,Oint n),r) -> loop ({v=intern_omega env v; c=n} :: accu) r | Oint n -> let id = new_omega_eq () in (*i tag_equation name id; i*) {kind = kind; body = List.rev accu; constant = n; id = id} | t -> print_string "CO"; oprint stdout t; failwith "compile_equation" in loop [] \subsection{Omega vers Oformula } let rec oformula_of_omega env af = let rec loop = function | ({v=v; c=n}::r) -> Oplus(Omult(unintern_omega env v,Oint n),loop r) | [] -> Oint af.constant in loop af.body let app f v = mkApp(Lazy.force f,v) \subsection{Oformula vers COQ reel } let rec coq_of_formula env t = let rec loop = function | Oplus (t1,t2) -> app Z.plus [| loop t1; loop t2 |] | Oopp t -> app Z.opp [| loop t |] | Omult(t1,t2) -> app Z.mult [| loop t1; loop t2 |] | Oint v -> Z.mk v | Oufo t -> loop t | Oatom var -> (* attention ne traite pas les nouvelles variables si on ne les * met pas dans env.term *) get_reified_atom env var | Ominus(t1,t2) -> app Z.minus [| loop t1; loop t2 |] in loop t \subsection{Oformula vers COQ reifié } let reified_of_atom env i = try Hashtbl.find env.real_indices i with Not_found -> Printf.printf "Atome %d non trouvé\n" i; Hashtbl.iter (fun k v -> Printf.printf "%d -> %d\n" k v) env.real_indices; raise Not_found let rec reified_of_formula env = function | Oplus (t1,t2) -> app coq_t_plus [| reified_of_formula env t1; reified_of_formula env t2 |] | Oopp t -> app coq_t_opp [| reified_of_formula env t |] | Omult(t1,t2) -> app coq_t_mult [| reified_of_formula env t1; reified_of_formula env t2 |] | Oint v -> app coq_t_int [| Z.mk v |] | Oufo t -> reified_of_formula env t | Oatom i -> app coq_t_var [| mk_nat (reified_of_atom env i) |] | Ominus(t1,t2) -> app coq_t_minus [| reified_of_formula env t1; reified_of_formula env t2 |] let reified_of_formula env f = begin try reified_of_formula env f with e -> oprint stderr f; raise e end let rec reified_of_proposition env = function Pequa (_,{ e_comp=Eq; e_left=t1; e_right=t2 }) -> app coq_p_eq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa (_,{ e_comp=Leq; e_left=t1; e_right=t2 }) -> app coq_p_leq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Geq; e_left=t1; e_right=t2 }) -> app coq_p_geq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Gt; e_left=t1; e_right=t2 }) -> app coq_p_gt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Lt; e_left=t1; e_right=t2 }) -> app coq_p_lt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Neq; e_left=t1; e_right=t2 }) -> app coq_p_neq [| reified_of_formula env t1; reified_of_formula env t2 |] | Ptrue -> Lazy.force coq_p_true | Pfalse -> Lazy.force coq_p_false | Pnot t -> app coq_p_not [| reified_of_proposition env t |] | Por (_,t1,t2) -> app coq_p_or [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pand(_,t1,t2) -> app coq_p_and [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pimp(_,t1,t2) -> app coq_p_imp [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pprop t -> app coq_p_prop [| mk_nat (add_prop env t) |] let reified_of_proposition env f = begin try reified_of_proposition env f with e -> pprint stderr f; raise e end \subsection{Omega vers COQ réifié } let reified_of_omega env body constant = let coeff_constant = app coq_t_int [| Z.mk constant |] in let mk_coeff {c=c; v=v} t = let coef = app coq_t_mult [| reified_of_formula env (unintern_omega env v); app coq_t_int [| Z.mk c |] |] in app coq_t_plus [|coef; t |] in List.fold_right mk_coeff body coeff_constant let reified_of_omega env body c = begin try reified_of_omega env body c with e -> display_eq display_omega_var (body,c); raise e end \section{Opérations sur les équations } Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations . Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations. *) \subsection{Extractions des variables d'une équation } (* Extraction des variables d'une équation. *) Chaque fonction retourne une liste triée sans redondance let (@@) = list_merge_uniq compare let rec vars_of_formula = function | Oint _ -> [] | Oplus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Omult (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Ominus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Oopp e -> vars_of_formula e | Oatom i -> [i] | Oufo _ -> [] let rec vars_of_equations = function | [] -> [] | e::l -> (vars_of_formula e.e_left) @@ (vars_of_formula e.e_right) @@ (vars_of_equations l) let rec vars_of_prop = function | Pequa(_,e) -> vars_of_equations [e] | Pnot p -> vars_of_prop p | Por(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pand(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pimp(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pprop _ | Ptrue | Pfalse -> [] (* \subsection{Multiplication par un scalaire} *) let rec scalar n = function Oplus(t1,t2) -> let tac1,t1' = scalar n t1 and tac2,t2' = scalar n t2 in do_list [Lazy.force coq_c_mult_plus_distr; do_both tac1 tac2], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_mult_opp_left], Omult(t,Oint(Bigint.neg n)) | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_mult_assoc_reduced], Omult(t1,Oint (n*x)) | Omult(t1,t2) -> Util.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [], Omult(t,Oint n) | Oint i -> do_list [Lazy.force coq_c_reduce],Oint(n*i) | (Oufo _ as t)-> do_list [], Oufo (Omult(t,Oint n)) | Ominus _ -> failwith "scalar minus" (* \subsection{Propagation de l'inversion} *) let rec negate = function Oplus(t1,t2) -> let tac1,t1' = negate t1 and tac2,t2' = negate t2 in do_list [Lazy.force coq_c_opp_plus ; (do_both tac1 tac2)], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_opp_opp], t | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_opp_mult_r], Omult(t1,Oint (Bigint.neg x)) | Omult(t1,t2) -> Util.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [Lazy.force coq_c_opp_one], Omult(t,Oint(negone)) | Oint i -> do_list [Lazy.force coq_c_reduce] ,Oint(Bigint.neg i) | Oufo c -> do_list [], Oufo (Oopp c) | Ominus _ -> failwith "negate minus" let rec norm l = (List.length l) (* \subsection{Mélange (fusion) de deux équations} *) (* \subsubsection{Version avec coefficients} *) let rec shuffle_path k1 e1 k2 e2 = let rec loop = function (({c=c1;v=v1}::l1) as l1'), (({c=c2;v=v2}::l2) as l2') -> if v1 = v2 then if k1*c1 + k2 * c2 = zero then ( Lazy.force coq_f_cancel :: loop (l1,l2)) else ( Lazy.force coq_f_equal :: loop (l1,l2) ) else if v1 > v2 then ( Lazy.force coq_f_left :: loop(l1,l2')) else ( Lazy.force coq_f_right :: loop(l1',l2)) | ({c=c1;v=v1}::l1), [] -> Lazy.force coq_f_left :: loop(l1,[]) | [],({c=c2;v=v2}::l2) -> Lazy.force coq_f_right :: loop([],l2) | [],[] -> flush stdout; [] in mk_shuffle_list (loop (e1,e2)) (* \subsubsection{Version sans coefficients} *) let rec shuffle env (t1,t2) = match t1,t2 with Oplus(l1,r1), Oplus(l2,r2) -> if weight env l1 > weight env l2 then let l_action,t' = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action], Oplus(l1,t') else let l_action,t' = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') | Oplus(l1,r1), t2 -> if weight env l1 > weight env t2 then let (l_action,t') = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action],Oplus(l1, t') else do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) | t1,Oplus(l2,r2) -> if weight env l2 > weight env t1 then let (l_action,t') = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') else do_list [],Oplus(t1,t2) | Oint t1,Oint t2 -> do_list [Lazy.force coq_c_reduce], Oint(t1+t2) | t1,t2 -> if weight env t1 < weight env t2 then do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) else do_list [],Oplus(t1,t2) \subsection{Fusion avec réduction } let shrink_pair f1 f2 = begin match f1,f2 with Oatom v,Oatom _ -> Lazy.force coq_c_red1, Omult(Oatom v,Oint two) | Oatom v, Omult(_,c2) -> Lazy.force coq_c_red2, Omult(Oatom v,Oplus(c2,Oint one)) | Omult (v1,c1),Oatom v -> Lazy.force coq_c_red3, Omult(Oatom v,Oplus(c1,Oint one)) | Omult (Oatom v,c1),Omult (v2,c2) -> Lazy.force coq_c_red4, Omult(Oatom v,Oplus(c1,c2)) | t1,t2 -> oprint stdout t1; print_newline (); oprint stdout t2; print_newline (); flush Pervasives.stdout; Util.error "shrink.1" end (* \subsection{Calcul d'une sous formule constante} *) let reduce_factor = function Oatom v -> let r = Omult(Oatom v,Oint one) in [Lazy.force coq_c_red0],r | Omult(Oatom v,Oint n) as f -> [],f | Omult(Oatom v,c) -> let rec compute = function Oint n -> n | Oplus(t1,t2) -> compute t1 + compute t2 | _ -> Util.error "condense.1" in [Lazy.force coq_c_reduce], Omult(Oatom v,Oint(compute c)) | t -> Util.error "reduce_factor.1" (* \subsection{Réordonnancement} *) let rec condense env = function Oplus(f1,(Oplus(f2,r) as t)) -> if weight env f1 = weight env f2 then begin let shrink_tac,t = shrink_pair f1 f2 in let assoc_tac = Lazy.force coq_c_plus_assoc_l in let tac_list,t' = condense env (Oplus(t,r)) in assoc_tac :: do_left (do_list [shrink_tac]) :: tac_list, t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env t in [do_both (do_list tac) (do_list tac')], Oplus(f,t') end | Oplus(f1,Oint n) -> let tac,f1' = reduce_factor f1 in [do_left (do_list tac)],Oplus(f1',Oint n) | Oplus(f1,f2) -> if weight env f1 = weight env f2 then begin let tac_shrink,t = shrink_pair f1 f2 in let tac,t' = condense env t in tac_shrink :: tac,t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env f2 in [do_both (do_list tac) (do_list tac')],Oplus(f,t') end | (Oint _ as t)-> [],t | t -> let tac,t' = reduce_factor t in let final = Oplus(t',Oint zero) in tac @ [Lazy.force coq_c_red6], final (* \subsection{Elimination des zéros} *) let rec clear_zero = function Oplus(Omult(Oatom v,Oint n),r) when n=zero -> let tac',t = clear_zero r in Lazy.force coq_c_red5 :: tac',t | Oplus(f,r) -> let tac,t = clear_zero r in (if tac = [] then [] else [do_right (do_list tac)]),Oplus(f,t) | t -> [],t;; (* \subsection{Transformation des hypothèses} *) let rec reduce env = function Oplus(t1,t2) -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in let trace3,t' = shuffle env (t1',t2') in t', do_list [do_both trace1 trace2; trace3] | Ominus(t1,t2) -> let t,trace = reduce env (Oplus(t1, Oopp t2)) in t, do_list [Lazy.force coq_c_minus; trace] | Omult(t1,t2) as t -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in begin match t1',t2' with | (_, Oint n) -> let tac,t' = scalar n t1' in t', do_list [do_both trace1 trace2; tac] | (Oint n,_) -> let tac,t' = scalar n t2' in t', do_list [do_both trace1 trace2; Lazy.force coq_c_mult_comm; tac] | _ -> Oufo t, Lazy.force coq_c_nop end | Oopp t -> let t',trace = reduce env t in let trace',t'' = negate t' in t'', do_list [do_left trace; trace'] | (Oint _ | Oatom _ | Oufo _) as t -> t, Lazy.force coq_c_nop let normalize_linear_term env t = let t1,trace1 = reduce env t in let trace2,t2 = condense env t1 in let trace3,t3 = clear_zero t2 in do_list [trace1; do_list trace2; do_list trace3], t3 Cette fonction reproduit très exactement le comportement de [ p_invert ] let negate_oper = function Eq -> Neq | Neq -> Eq | Leq -> Gt | Geq -> Lt | Lt -> Geq | Gt -> Leq let normalize_equation env (negated,depends,origin,path) (oper,t1,t2) = let mk_step t1 t2 f kind = let t = f t1 t2 in let trace, oterm = normalize_linear_term env t in let equa = omega_of_oformula env kind oterm in { e_comp = oper; e_left = t1; e_right = t2; e_negated = negated; e_depends = depends; e_origin = { o_hyp = origin; o_path = List.rev path }; e_trace = trace; e_omega = equa } in try match (if negated then (negate_oper oper) else oper) with | Eq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) EQUA | Neq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) DISE | Leq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o2,Oopp o1)) INEQ | Geq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) INEQ | Lt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o2,Oint negone),Oopp o1)) INEQ | Gt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o1,Oint negone),Oopp o2)) INEQ with e when Logic.catchable_exception e -> raise e (* \section{Compilation des hypothèses} *) let rec oformula_of_constr env t = match Z.parse_term t with | Tplus (t1,t2) -> binop env (fun x y -> Oplus(x,y)) t1 t2 | Tminus (t1,t2) -> binop env (fun x y -> Ominus(x,y)) t1 t2 | Tmult (t1,t2) when Z.is_scalar t1 || Z.is_scalar t2 -> binop env (fun x y -> Omult(x,y)) t1 t2 | Topp t -> Oopp(oformula_of_constr env t) | Tsucc t -> Oplus(oformula_of_constr env t, Oint one) | Tnum n -> Oint n | _ -> Oatom (add_reified_atom t env) and binop env c t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in c t1' t2' and binprop env (neg2,depends,origin,path) add_to_depends neg1 gl c t1 t2 = let i = new_connector_id env in let depends1 = if add_to_depends then Left i::depends else depends in let depends2 = if add_to_depends then Right i::depends else depends in if add_to_depends then Hashtbl.add env.constructors i {o_hyp = origin; o_path = List.rev path}; let t1' = oproposition_of_constr env (neg1,depends1,origin,O_left::path) gl t1 in let t2' = oproposition_of_constr env (neg2,depends2,origin,O_right::path) gl t2 in On numérote le connecteur dans l'environnement . c i t1' t2' and mk_equation env ctxt c connector t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in (* On ajoute l'equation dans l'environnement. *) let omega = normalize_equation env ctxt (connector,t1',t2') in add_equation env omega; Pequa (c,omega) and oproposition_of_constr env ((negated,depends,origin,path) as ctxt) gl c = match Z.parse_rel gl c with | Req (t1,t2) -> mk_equation env ctxt c Eq t1 t2 | Rne (t1,t2) -> mk_equation env ctxt c Neq t1 t2 | Rle (t1,t2) -> mk_equation env ctxt c Leq t1 t2 | Rlt (t1,t2) -> mk_equation env ctxt c Lt t1 t2 | Rge (t1,t2) -> mk_equation env ctxt c Geq t1 t2 | Rgt (t1,t2) -> mk_equation env ctxt c Gt t1 t2 | Rtrue -> Ptrue | Rfalse -> Pfalse | Rnot t -> let t' = oproposition_of_constr env (not negated, depends, origin,(O_mono::path)) gl t in Pnot t' | Ror (t1,t2) -> binprop env ctxt (not negated) negated gl (fun i x y -> Por(i,x,y)) t1 t2 | Rand (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) t1 t2 | Rimp (t1,t2) -> binprop env ctxt (not negated) (not negated) gl (fun i x y -> Pimp(i,x,y)) t1 t2 | Riff (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) (Term.mkArrow t1 t2) (Term.mkArrow t2 t1) | _ -> Pprop c Destructuration des hypothèses et de la conclusion let reify_gl env gl = let concl = Tacmach.pf_concl gl in let t_concl = Pnot (oproposition_of_constr env (true,[],id_concl,[O_mono]) gl concl) in if !debug then begin Printf.printf "REIFED PROBLEM\n\n"; Printf.printf " CONCL: "; pprint stdout t_concl; Printf.printf "\n" end; let rec loop = function (i,t) :: lhyps -> let t' = oproposition_of_constr env (false,[],i,[]) gl t in if !debug then begin Printf.printf " %s: " (Names.string_of_id i); pprint stdout t'; Printf.printf "\n" end; (i,t') :: loop lhyps | [] -> if !debug then print_env_reification env; [] in let t_lhyps = loop (Tacmach.pf_hyps_types gl) in (id_concl,t_concl) :: t_lhyps let rec destructurate_pos_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_neg_hyp orig list_equations list_depends t | Por (i,t1,t2) -> let s1 = destructurate_pos_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Pand(i,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations (list_depends) t1 in let rec loop = function le1 :: ll -> destructurate_pos_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 and destructurate_neg_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_pos_hyp orig list_equations list_depends t | Pand (i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_neg_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Por(_,t1,t2) -> let list_s1 = destructurate_neg_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(_,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 let destructurate_hyps syst = let rec loop = function (i,t) :: l -> let l_syst1 = destructurate_pos_hyp i [] [] t in let l_syst2 = loop l in list_cartesian (@) l_syst1 l_syst2 | [] -> [[]] in loop syst (* \subsection{Affichage d'un système d'équation} *) Affichage des dépendances de système let display_depend = function Left i -> Printf.printf " L%d" i | Right i -> Printf.printf " R%d" i let display_systems syst_list = let display_omega om_e = Printf.printf " E%d : %a %s 0\n" om_e.id (fun _ -> display_eq display_omega_var) (om_e.body, om_e.constant) (operator_of_eq om_e.kind) in let display_equation oformula_eq = pprint stdout (Pequa (Lazy.force coq_c_nop,oformula_eq)); print_newline (); display_omega oformula_eq.e_omega; Printf.printf " Depends on:"; List.iter display_depend oformula_eq.e_depends; Printf.printf "\n Path: %s" (String.concat "" (List.map (function O_left -> "L" | O_right -> "R" | O_mono -> "M") oformula_eq.e_origin.o_path)); Printf.printf "\n Origin: %s (negated : %s)\n\n" (Names.string_of_id oformula_eq.e_origin.o_hyp) (if oformula_eq.e_negated then "yes" else "no") in let display_system syst = Printf.printf "=SYSTEM===================================\n"; List.iter display_equation syst in List.iter display_system syst_list Extraction des prédicats utilisées dans une trace . calcul des hypothèses calcul des hypothèses *) let rec hyps_used_in_trace = function | act :: l -> begin match act with | HYP e -> [e.id] @@ (hyps_used_in_trace l) | SPLIT_INEQ (_,(_,act1),(_,act2)) -> hyps_used_in_trace act1 @@ hyps_used_in_trace act2 | _ -> hyps_used_in_trace l end | [] -> [] Extraction des variables déclarées dans une équation . de les déclarer dans l'environnement de la procédure réflexive et les créations de variable au vol de les déclarer dans l'environnement de la procédure réflexive et éviter les créations de variable au vol *) let rec variable_stated_in_trace = function | act :: l -> begin match act with | STATE action -> i nlle_equa : afine , def : afine , eq_orig : afine , i i : int , var : int i action :: variable_stated_in_trace l | SPLIT_INEQ (_,(_,act1),(_,act2)) -> variable_stated_in_trace act1 @ variable_stated_in_trace act2 | _ -> variable_stated_in_trace l end | [] -> [] ;; let add_stated_equations env tree = (* Il faut trier les variables par ordre d'introduction pour ne pas risquer de définir dans le mauvais ordre *) let stated_equations = let cmpvar x y = Pervasives.(-) x.st_var y.st_var in let rec loop = function | Tree(_,t1,t2) -> List.merge cmpvar (loop t1) (loop t2) | Leaf s -> List.sort cmpvar (variable_stated_in_trace s.s_trace) in loop tree in let add_env st = On retransforme la définition de v en formule let v_def = oformula_of_omega env st.st_def in que si l'ordre de création des variables n'est pas respecté , * ca va planter * ca va planter *) let coq_v = coq_of_formula env v_def in let v = add_reified_atom coq_v env in (* Le terme qu'il va falloir introduire *) let term_to_generalize = app coq_refl_equal [|Lazy.force Z.typ; coq_v|] in sa représentation forme d'équation mais non réifié car on n'a pas * l'environnement pour le faire correctement * l'environnement pour le faire correctement *) let term_to_reify = (v_def,Oatom v) in enregistre le lien entre la variable omega et la variable Coq intern_omega_force env (Oatom v) st.st_var; (v, term_to_generalize,term_to_reify,st.st_def.id) in List.map add_env stated_equations Calcule la liste des éclatements à réaliser sur les hypothèses nécessaires pour extraire une liste d'équations donnée nécessaires pour extraire une liste d'équations donnée *) PL : experimentally , the result order of the following function seems _ very _ crucial for efficiency . No idea why . Do not remove the List.rev or modify the current semantics of Util.list_union ( some elements of first arg , then second arg ) , unless you know what you 're doing . _very_ crucial for efficiency. No idea why. Do not remove the List.rev or modify the current semantics of Util.list_union (some elements of first arg, then second arg), unless you know what you're doing. *) let rec get_eclatement env = function i :: r -> let l = try (get_equation env i).e_depends with Not_found -> [] in list_union (List.rev l) (get_eclatement env r) | [] -> [] let select_smaller l = let comp (_,x) (_,y) = Pervasives.(-) (List.length x) (List.length y) in try List.hd (List.sort comp l) with Failure _ -> failwith "select_smaller" let filter_compatible_systems required systems = let rec select = function (x::l) -> if List.mem x required then select l else if List.mem (barre x) required then failwith "Exit" else x :: select l | [] -> [] in map_succeed (function (sol,splits) -> (sol,select splits)) systems let rec equas_of_solution_tree = function Tree(_,t1,t2) -> (equas_of_solution_tree t1)@@(equas_of_solution_tree t2) | Leaf s -> s.s_equa_deps [ really_useful_prop ] pushes useless props in a new Pprop variable Things get shorter , but may also get wrong , since a Prop is considered to be undecidable in ReflOmegaCore.concl_to_hyp , whereas for instance Pfalse is decidable . So should not be used on conclusion ( ? ? ) to be undecidable in ReflOmegaCore.concl_to_hyp, whereas for instance Pfalse is decidable. So should not be used on conclusion (??) *) let really_useful_prop l_equa c = let rec real_of = function Pequa(t,_) -> t | Ptrue -> app coq_True [||] | Pfalse -> app coq_False [||] | Pnot t1 -> app coq_not [|real_of t1|] | Por(_,t1,t2) -> app coq_or [|real_of t1; real_of t2|] | Pand(_,t1,t2) -> app coq_and [|real_of t1; real_of t2|] Attention : implications sur le lifting des variables à comprendre ! | Pimp(_,t1,t2) -> Term.mkArrow (real_of t1) (real_of t2) | Pprop t -> t in let rec loop c = match c with Pequa(_,e) -> if List.mem e.e_omega.id l_equa then Some c else None | Ptrue -> None | Pfalse -> None | Pnot t1 -> begin match loop t1 with None -> None | Some t1' -> Some (Pnot t1') end | Por(i,t1,t2) -> binop (fun (t1,t2) -> Por(i,t1,t2)) t1 t2 | Pand(i,t1,t2) -> binop (fun (t1,t2) -> Pand(i,t1,t2)) t1 t2 | Pimp(i,t1,t2) -> binop (fun (t1,t2) -> Pimp(i,t1,t2)) t1 t2 | Pprop t -> None and binop f t1 t2 = begin match loop t1, loop t2 with None, None -> None | Some t1',Some t2' -> Some (f(t1',t2')) | Some t1',None -> Some (f(t1',Pprop (real_of t2))) | None,Some t2' -> Some (f(Pprop (real_of t1),t2')) end in match loop c with None -> Pprop (real_of c) | Some t -> t let rec display_solution_tree ch = function Leaf t -> output_string ch (Printf.sprintf "%d[%s]" t.s_index (String.concat " " (List.map string_of_int t.s_equa_deps))) | Tree(i,t1,t2) -> Printf.fprintf ch "S%d(%a,%a)" i display_solution_tree t1 display_solution_tree t2 let rec solve_with_constraints all_solutions path = let rec build_tree sol buf = function [] -> Leaf sol | (Left i :: remainder) -> Tree(i, build_tree sol (Left i :: buf) remainder, solve_with_constraints all_solutions (List.rev(Right i :: buf))) | (Right i :: remainder) -> Tree(i, solve_with_constraints all_solutions (List.rev (Left i :: buf)), build_tree sol (Right i :: buf) remainder) in let weighted = filter_compatible_systems path all_solutions in let (winner_sol,winner_deps) = try select_smaller weighted with e -> Printf.printf "%d - %d\n" (List.length weighted) (List.length all_solutions); List.iter display_depend path; raise e in build_tree winner_sol (List.rev path) winner_deps let find_path {o_hyp=id;o_path=p} env = let rec loop_path = function ([],l) -> Some l | (x1::l1,x2::l2) when x1 = x2 -> loop_path (l1,l2) | _ -> None in let rec loop_id i = function CCHyp{o_hyp=id';o_path=p'} :: l when id = id' -> begin match loop_path (p',p) with Some r -> i,r | None -> loop_id (succ i) l end | _ :: l -> loop_id (succ i) l | [] -> failwith "find_path" in loop_id 0 env let mk_direction_list l = let trans = function O_left -> coq_d_left | O_right -> coq_d_right | O_mono -> coq_d_mono in mk_list (Lazy.force coq_direction) (List.map (fun d-> Lazy.force(trans d)) l) (* \section{Rejouer l'historique} *) let get_hyp env_hyp i = try list_index0 (CCEqua i) env_hyp with Not_found -> failwith (Printf.sprintf "get_hyp %d" i) let replay_history env env_hyp = let rec loop env_hyp t = match t with | CONTRADICTION (e1,e2) :: l -> let trace = mk_nat (List.length e1.body) in mkApp (Lazy.force coq_s_contradiction, [| trace ; mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | DIVIDE_AND_APPROX (e1,e2,k,d) :: l -> mkApp (Lazy.force coq_s_div_approx, [| Z.mk k; Z.mk d; reified_of_omega env e2.body e2.constant; mk_nat (List.length e2.body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id) |]) | NOT_EXACT_DIVIDE (e1,k) :: l -> let e2_constant = floor_div e1.constant k in let d = e1.constant - e2_constant * k in let e2_body = map_eq_linear (fun c -> c / k) e1.body in mkApp (Lazy.force coq_s_not_exact_divide, [|Z.mk k; Z.mk d; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); mk_nat (get_hyp env_hyp e1.id)|]) | EXACT_DIVIDE (e1,k) :: l -> let e2_body = map_eq_linear (fun c -> c / k) e1.body in let e2_constant = floor_div e1.constant k in mkApp (Lazy.force coq_s_exact_divide, [|Z.mk k; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id)|]) | (MERGE_EQ(e3,e1,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2 in mkApp (Lazy.force coq_s_merge_eq, [| mk_nat (List.length e1.body); mk_nat n1; mk_nat n2; loop (CCEqua e3:: env_hyp) l |]) | SUM(e3,(k1,e1),(k2,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2.id in let trace = shuffle_path k1 e1.body k2 e2.body in mkApp (Lazy.force coq_s_sum, [| Z.mk k1; mk_nat n1; Z.mk k2; mk_nat n2; trace; (loop (CCEqua e3 :: env_hyp) l) |]) | CONSTANT_NOT_NUL(e,k) :: l -> mkApp (Lazy.force coq_s_constant_not_nul, [| mk_nat (get_hyp env_hyp e) |]) | CONSTANT_NEG(e,k) :: l -> mkApp (Lazy.force coq_s_constant_neg, [| mk_nat (get_hyp env_hyp e) |]) | STATE {st_new_eq=new_eq; st_def =def; st_orig=orig; st_coef=m; st_var=sigma } :: l -> let n1 = get_hyp env_hyp orig.id and n2 = get_hyp env_hyp def.id in let v = unintern_omega env sigma in let o_def = oformula_of_omega env def in let o_orig = oformula_of_omega env orig in let body = Oplus (o_orig,Omult (Oplus (Oopp v,o_def), Oint m)) in let trace,_ = normalize_linear_term env body in mkApp (Lazy.force coq_s_state, [| Z.mk m; trace; mk_nat n1; mk_nat n2; loop (CCEqua new_eq.id :: env_hyp) l |]) | HYP _ :: l -> loop env_hyp l | CONSTANT_NUL e :: l -> mkApp (Lazy.force coq_s_constant_nul, [| mk_nat (get_hyp env_hyp e) |]) | NEGATE_CONTRADICT(e1,e2,true) :: l -> mkApp (Lazy.force coq_s_negate_contradict, [| mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | NEGATE_CONTRADICT(e1,e2,false) :: l -> mkApp (Lazy.force coq_s_negate_contradict_inv, [| mk_nat (List.length e2.body); mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | SPLIT_INEQ(e,(e1,l1),(e2,l2)) :: l -> let i = get_hyp env_hyp e.id in let r1 = loop (CCEqua e1 :: env_hyp) l1 in let r2 = loop (CCEqua e2 :: env_hyp) l2 in mkApp (Lazy.force coq_s_split_ineq, [| mk_nat (List.length e.body); mk_nat i; r1 ; r2 |]) | (FORGET_C _ | FORGET _ | FORGET_I _) :: l -> loop env_hyp l | (WEAKEN _ ) :: l -> failwith "not_treated" | [] -> failwith "no contradiction" in loop env_hyp let rec decompose_tree env ctxt = function Tree(i,left,right) -> let org = try Hashtbl.find env.constructors i with Not_found -> failwith (Printf.sprintf "Cannot find constructor %d" i) in let (index,path) = find_path org ctxt in let left_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_left]} in let right_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_right]} in app coq_e_split [| mk_nat index; mk_direction_list path; decompose_tree env (left_hyp::ctxt) left; decompose_tree env (right_hyp::ctxt) right |] | Leaf s -> decompose_tree_hyps s.s_trace env ctxt s.s_equa_deps and decompose_tree_hyps trace env ctxt = function [] -> app coq_e_solve [| replay_history env ctxt trace |] | (i::l) -> let equation = try Hashtbl.find env.equations i with Not_found -> failwith (Printf.sprintf "Cannot find equation %d" i) in let (index,path) = find_path equation.e_origin ctxt in let full_path = if equation.e_negated then path @ [O_mono] else path in let cont = decompose_tree_hyps trace env (CCEqua equation.e_omega.id :: ctxt) l in app coq_e_extract [|mk_nat index; mk_direction_list full_path; cont |] (* \section{La fonction principale} *) Cette fonction construit la trace pour la procédure de décision réflexive . A partir des résultats de l'extraction des systèmes , elle lance la résolution par Omega , puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive . trace pour la procédure de décision réflexive. A partir des résultats de l'extraction des systèmes, elle lance la résolution par Omega, puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive. *) let resolution env full_reified_goal systems_list = let num = ref 0 in let solve_system list_eq = let index = !num in let system = List.map (fun eq -> eq.e_omega) list_eq in let trace = simplify_strong (new_omega_eq,new_omega_var,display_omega_var) system in (* calcule les hypotheses utilisées pour la solution *) let vars = hyps_used_in_trace trace in let splits = get_eclatement env vars in if !debug then begin Printf.printf "SYSTEME %d\n" index; display_action display_omega_var trace; print_string "\n Depend :"; List.iter (fun i -> Printf.printf " %d" i) vars; print_string "\n Split points :"; List.iter display_depend splits; Printf.printf "\n------------------------------------\n" end; incr num; {s_index = index; s_trace = trace; s_equa_deps = vars}, splits in if !debug then Printf.printf "\n====================================\n"; let all_solutions = List.map solve_system systems_list in let solution_tree = solve_with_constraints all_solutions [] in if !debug then begin display_solution_tree stdout solution_tree; print_newline() end; (* calcule la liste de toutes les hypothèses utilisées dans l'arbre de solution *) let useful_equa_id = equas_of_solution_tree solution_tree in (* recupere explicitement ces equations *) let equations = List.map (get_equation env) useful_equa_id in let l_hyps' = list_uniquize (List.map (fun e -> e.e_origin.o_hyp) equations) in let l_hyps = id_concl :: list_remove id_concl l_hyps' in let useful_hyps = List.map (fun id -> List.assoc id full_reified_goal) l_hyps in let useful_vars = let really_useful_vars = vars_of_equations equations in let concl_vars = vars_of_prop (List.assoc id_concl full_reified_goal) in really_useful_vars @@ concl_vars in (* variables a introduire *) let to_introduce = add_stated_equations env solution_tree in let stated_vars = List.map (fun (v,_,_,_) -> v) to_introduce in let l_generalize_arg = List.map (fun (_,t,_,_) -> t) to_introduce in let hyp_stated_vars = List.map (fun (_,_,_,id) -> CCEqua id) to_introduce in L'environnement de base se construit en : - les variables des équations utiles ( et de la conclusion ) - les nouvelles variables declarées durant les preuves - les variables des équations utiles (et de la conclusion) - les nouvelles variables declarées durant les preuves *) let all_vars_env = useful_vars @ stated_vars in let basic_env = let rec loop i = function var :: l -> let t = get_reified_atom env var in Hashtbl.add env.real_indices var i; t :: loop (succ i) l | [] -> [] in loop 0 all_vars_env in let env_terms_reified = mk_list (Lazy.force Z.typ) basic_env in On peut maintenant but : env est a jour let l_reified_stated = List.map (fun (_,_,(l,r),_) -> app coq_p_eq [| reified_of_formula env l; reified_of_formula env r |]) to_introduce in let reified_concl = match useful_hyps with (Pnot p) :: _ -> reified_of_proposition env p | _ -> reified_of_proposition env Pfalse in let l_reified_terms = (List.map (fun p -> reified_of_proposition env (really_useful_prop useful_equa_id p)) (List.tl useful_hyps)) in let env_props_reified = mk_plist env.props in let reified_goal = mk_list (Lazy.force coq_proposition) (l_reified_stated @ l_reified_terms) in let reified = app coq_interp_sequent [| reified_concl;env_props_reified;env_terms_reified;reified_goal|] in let normalize_equation e = let rec loop = function [] -> app (if e.e_negated then coq_p_invert else coq_p_step) [| e.e_trace |] | ((O_left | O_mono) :: l) -> app coq_p_left [| loop l |] | (O_right :: l) -> app coq_p_right [| loop l |] in let correct_index = let i = list_index0 e.e_origin.o_hyp l_hyps in PL : it seems that additionnally introduced hyps are in the way during normalization , hence this index shifting ... normalization, hence this index shifting... *) if i=0 then 0 else Pervasives.(+) i (List.length to_introduce) in app coq_pair_step [| mk_nat correct_index; loop e.e_origin.o_path |] in let normalization_trace = mk_list (Lazy.force coq_h_step) (List.map normalize_equation equations) in let initial_context = List.map (fun id -> CCHyp{o_hyp=id;o_path=[]}) (List.tl l_hyps) in let context = CCHyp{o_hyp=id_concl;o_path=[]} :: hyp_stated_vars @ initial_context in let decompose_tactic = decompose_tree env context solution_tree in Tactics.generalize (l_generalize_arg @ List.map Term.mkVar (List.tl l_hyps)) >> Tactics.change_in_concl None reified >> Tactics.apply (app coq_do_omega [|decompose_tactic; normalization_trace|]) >> show_goal >> Tactics.normalise_vm_in_concl >> i Alternatives to the previous line : - Normalisation without VM : Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED : Tacmach.convert_concl_no_check ( Lazy.force coq_True ) Term . VMcast > > i - Normalisation without VM: Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED: Tacmach.convert_concl_no_check (Lazy.force coq_True) Term.VMcast >> i*) Tactics.apply (Lazy.force coq_I) let total_reflexive_omega_tactic gl = Coqlib.check_required_library ["Coq";"romega";"ROmega"]; rst_omega_eq (); rst_omega_var (); try let env = new_environment () in let full_reified_goal = reify_gl env gl in let systems_list = destructurate_hyps full_reified_goal in if !debug then display_systems systems_list; resolution env full_reified_goal systems_list gl with NO_CONTRADICTION -> Util.error "ROmega can't solve this system" i let tester = Tacmach.hide_atomic_tactic " TestOmega " test_tactic i
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/plugins/romega/refl_omega.ml
ocaml
\section{Useful functions and flags} Especially useful debugging functions More readable than the prefix notation \section{Types} \subsection{How to walk in a term} To represent how to get to a proposition. Only choice points are kept (branch to choose in a disjunction and identifier of the disjunctive connector) Step to find a proposition (operators are at most binary). A list is a path \subsection{refiable formulas} integer recognized binary and unary operations an atome in the environment weird expression that cannot be translated Les équations ou proposiitions atomiques utiles du calcul comparaison formule brute gauche formule brute droite l'hypothèse dont vient le terme vrai si apparait en position nié après normalisation la fonction normalisée La meme chose pour les propositions Les variables introduites par omega Représentation de l'environnement extrait du but initial sous forme de chemins pour extraire des equations ou d'hypothèses \section{Specific utility functions to handle base types} Calcul de la branche complémentaire Identifiant associé à une branche \subsection{Gestion des environnements de variable pour Omega} Affichage des variables d'un système Récupère le terme associé à une variable ajout d'une proposition \subsection{Gestion du nommage des équations} Ajout d'une equation dans l'environnement de reification accès a une equation Affichage des termes réifiés \subsection{Oformula vers Omega} i tag_equation name id; i attention ne traite pas les nouvelles variables si on ne les * met pas dans env.term Extraction des variables d'une équation. \subsection{Multiplication par un scalaire} \subsection{Propagation de l'inversion} \subsection{Mélange (fusion) de deux équations} \subsubsection{Version avec coefficients} \subsubsection{Version sans coefficients} \subsection{Calcul d'une sous formule constante} \subsection{Réordonnancement} \subsection{Elimination des zéros} \subsection{Transformation des hypothèses} \section{Compilation des hypothèses} On ajoute l'equation dans l'environnement. \subsection{Affichage d'un système d'équation} Il faut trier les variables par ordre d'introduction pour ne pas risquer de définir dans le mauvais ordre Le terme qu'il va falloir introduire \section{Rejouer l'historique} \section{La fonction principale} calcule les hypotheses utilisées pour la solution calcule la liste de toutes les hypothèses utilisées dans l'arbre de solution recupere explicitement ces equations variables a introduire
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author : France Télécom R&D Licence : LGPL version 2.1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author: Pierre Crégut - France Télécom R&D Licence : LGPL version 2.1 *************************************************************************) open Util open Const_omega module OmegaSolver = Omega.MakeOmegaSolver (Bigint) open OmegaSolver let debug = ref false let show_goal gl = if !debug then Pp.ppnl (Tacmach.pr_gls gl); Tacticals.tclIDTAC gl let pp i = print_int i; print_newline (); flush stdout let (>>) = Tacticals.tclTHEN let mkApp = Term.mkApp type direction = Left of int | Right of int type occ_step = O_left | O_right | O_mono type occ_path = occ_step list chemin identifiant une proposition d'une liste de pas à partir de la racine de l'hypothèse d'une liste de pas à partir de la racine de l'hypothèse *) type occurence = {o_hyp : Names.identifier; o_path : occ_path} type oformula = | Oint of Bigint.bigint | Oplus of oformula * oformula | Omult of oformula * oformula | Ominus of oformula * oformula | Oopp of oformula | Oatom of int | Oufo of oformula Operators for comparison recognized by Omega type comparaison = Eq | Leq | Geq | Gt | Lt | Neq Type des prédicats réifiés ( fragment de calcul . Les * quantifications sont externes au langage ) * quantifications sont externes au langage) *) type oproposition = Pequa of Term.constr * oequation | Ptrue | Pfalse | Pnot of oproposition | Por of int * oproposition * oproposition | Pand of int * oproposition * oproposition | Pimp of int * oproposition * oproposition | Pprop of Term.constr and oequation = { tactique de normalisation liste des points do nt dépend l'accès à l'équation avec la direction ( branche ) pour y accéder dépend l'accès à l'équation avec la direction (branche) pour y accéder *) } \subsection{Proof context } This environment codes \begin{itemize } \item the terms and propositions that are given as parameters of the reified proof ( and are represented as variables in the reified goals ) \item translation functions linking the decision procedure and the Coq proof \end{itemize } This environment codes \begin{itemize} \item the terms and propositions that are given as parameters of the reified proof (and are represented as variables in the reified goals) \item translation functions linking the decision procedure and the Coq proof \end{itemize} *) type environment = { La liste des termes non reifies constituant l'environnement global mutable terms : Term.constr list; mutable props : Term.constr list; mutable om_vars : (oformula * int) list; Traduction des indices utilisés ici en les indices utilisés par * la tactique Omega après dénombrement des variables utiles * la tactique Omega après dénombrement des variables utiles *) real_indices : (int,int) Hashtbl.t; mutable cnt_connectors : int; equations : (int,oequation) Hashtbl.t; constructors : (int, occurence) Hashtbl.t } \subsection{Solution tree } Définition d'une solution trouvée par forme , d'un ensemble d'équation do nt dépend la solution et d'une trace Définition d'une solution trouvée par Omega sous la forme d'un identifiant, d'un ensemble d'équation dont dépend la solution et d'une trace *) La liste des dépendances est triée et sans redondance type solution = { s_index : int; s_equa_deps : int list; s_trace : action list } Arbre de solution résolvant complètement un ensemble de systèmes type solution_tree = Leaf of solution un noeud interne représente un point correspondant à l'élimination d'un connecteur ( typ . disjonction ) . Le premier argument est l'identifiant du connecteur l'élimination d'un connecteur générant plusieurs buts (typ. disjonction). Le premier argument est l'identifiant du connecteur *) | Tree of int * solution_tree * solution_tree type context_content = CCHyp of occurence | CCEqua of int négation du but final let id_concl = Names.id_of_string "__goal__" Initialisation de l'environnement de réification de la tactique let new_environment () = { terms = []; props = []; om_vars = []; cnt_connectors = 0; real_indices = Hashtbl.create 7; equations = Hashtbl.create 7; constructors = Hashtbl.create 7; } Génération d'un nom d'équation let new_connector_id env = env.cnt_connectors <- succ env.cnt_connectors; env.cnt_connectors let barre = function Left x -> Right x | Right x -> Left x let indice = function Left x | Right x -> x Affichage de l'environnement de réification ( termes et propositions ) let print_env_reification env = let rec loop c i = function [] -> Printf.printf " ===============================\n\n" | t :: l -> Printf.printf " (%c%02d) := " c i; Pp.ppnl (Printer.pr_lconstr t); Pp.flush_all (); loop c (succ i) l in print_newline (); Printf.printf " ENVIRONMENT OF PROPOSITIONS :\n\n"; loop 'P' 0 env.props; Printf.printf " ENVIRONMENT OF TERMS :\n\n"; loop 'V' 0 env.terms generation pour Omega let new_omega_eq, rst_omega_eq = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) generation variable pour Omega let new_omega_var, rst_omega_var = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) let display_omega_var i = Printf.sprintf "OV%d" i Recherche la variable codant un terme pour Omega et crée la variable dans l'environnement . Cas ou la variable dans ( le plus souvent ) l'environnement si il n'existe pas. Cas ou la variable dans Omega représente le terme d'un monome (le plus souvent un atome) *) let intern_omega env t = begin try List.assoc t env.om_vars with Not_found -> let v = new_omega_var () in env.om_vars <- (t,v) :: env.om_vars; v end Ajout forcé d'un lien entre un terme et une variable Cas où la variable est créée par Omega et où il faut la lier à un atome variable est créée par Omega et où il faut la lier après coup à un atome réifié introduit de force *) let intern_omega_force env t v = env.om_vars <- (t,v) :: env.om_vars let unintern_omega env id = let rec loop = function [] -> failwith "unintern" | ((t,j)::l) -> if id = j then t else loop l in loop env.om_vars \subsection{Gestion des environnements de variable pour la réflexion } Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies . Attention il s'agit de l'environnement initial contenant tout . calcul des variables utiles . Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies. Attention il s'agit de l'environnement initial contenant tout. Il faudra le réduire après calcul des variables utiles. *) let add_reified_atom t env = try list_index0 t env.terms with Not_found -> let i = List.length env.terms in env.terms <- env.terms @ [t]; i let get_reified_atom env = try List.nth env.terms with _ -> failwith "get_reified_atom" \subsection{Gestion de l'environnement de proposition pour Omega } let add_prop env t = try list_index0 t env.props with Not_found -> let i = List.length env.props in env.props <- env.props @ [t]; i accès a une proposition let get_prop v env = try List.nth v env with _ -> failwith "get_prop" let add_equation env e = let id = e.e_omega.id in try let _ = Hashtbl.find env.equations id in () with Not_found -> Hashtbl.add env.equations id e let get_equation env id = try Hashtbl.find env.equations id with e -> Printf.printf "Omega Equation %d non trouvée\n" id; raise e let rec oprint ch = function | Oint n -> Printf.fprintf ch "%s" (Bigint.to_string n) | Oplus (t1,t2) -> Printf.fprintf ch "(%a + %a)" oprint t1 oprint t2 | Omult (t1,t2) -> Printf.fprintf ch "(%a * %a)" oprint t1 oprint t2 | Ominus(t1,t2) -> Printf.fprintf ch "(%a - %a)" oprint t1 oprint t2 | Oopp t1 ->Printf.fprintf ch "~ %a" oprint t1 | Oatom n -> Printf.fprintf ch "V%02d" n | Oufo x -> Printf.fprintf ch "?" let rec pprint ch = function Pequa (_,{ e_comp=comp; e_left=t1; e_right=t2 }) -> let connector = match comp with Eq -> "=" | Leq -> "<=" | Geq -> ">=" | Gt -> ">" | Lt -> "<" | Neq -> "!=" in Printf.fprintf ch "%a %s %a" oprint t1 connector oprint t2 | Ptrue -> Printf.fprintf ch "TT" | Pfalse -> Printf.fprintf ch "FF" | Pnot t -> Printf.fprintf ch "not(%a)" pprint t | Por (_,t1,t2) -> Printf.fprintf ch "(%a or %a)" pprint t1 pprint t2 | Pand(_,t1,t2) -> Printf.fprintf ch "(%a and %a)" pprint t1 pprint t2 | Pimp(_,t1,t2) -> Printf.fprintf ch "(%a => %a)" pprint t1 pprint t2 | Pprop c -> Printf.fprintf ch "Prop" let rec weight env = function | Oint _ -> -1 | Oopp c -> weight env c | Omult(c,_) -> weight env c | Oplus _ -> failwith "weight" | Ominus _ -> failwith "weight minus" | Oufo _ -> -1 | Oatom _ as c -> (intern_omega env c) \section{Passage entre oformules et représentation interne de Omega } let omega_of_oformula env kind = let rec loop accu = function | Oplus(Omult(v,Oint n),r) -> loop ({v=intern_omega env v; c=n} :: accu) r | Oint n -> let id = new_omega_eq () in {kind = kind; body = List.rev accu; constant = n; id = id} | t -> print_string "CO"; oprint stdout t; failwith "compile_equation" in loop [] \subsection{Omega vers Oformula } let rec oformula_of_omega env af = let rec loop = function | ({v=v; c=n}::r) -> Oplus(Omult(unintern_omega env v,Oint n),loop r) | [] -> Oint af.constant in loop af.body let app f v = mkApp(Lazy.force f,v) \subsection{Oformula vers COQ reel } let rec coq_of_formula env t = let rec loop = function | Oplus (t1,t2) -> app Z.plus [| loop t1; loop t2 |] | Oopp t -> app Z.opp [| loop t |] | Omult(t1,t2) -> app Z.mult [| loop t1; loop t2 |] | Oint v -> Z.mk v | Oufo t -> loop t | Oatom var -> get_reified_atom env var | Ominus(t1,t2) -> app Z.minus [| loop t1; loop t2 |] in loop t \subsection{Oformula vers COQ reifié } let reified_of_atom env i = try Hashtbl.find env.real_indices i with Not_found -> Printf.printf "Atome %d non trouvé\n" i; Hashtbl.iter (fun k v -> Printf.printf "%d -> %d\n" k v) env.real_indices; raise Not_found let rec reified_of_formula env = function | Oplus (t1,t2) -> app coq_t_plus [| reified_of_formula env t1; reified_of_formula env t2 |] | Oopp t -> app coq_t_opp [| reified_of_formula env t |] | Omult(t1,t2) -> app coq_t_mult [| reified_of_formula env t1; reified_of_formula env t2 |] | Oint v -> app coq_t_int [| Z.mk v |] | Oufo t -> reified_of_formula env t | Oatom i -> app coq_t_var [| mk_nat (reified_of_atom env i) |] | Ominus(t1,t2) -> app coq_t_minus [| reified_of_formula env t1; reified_of_formula env t2 |] let reified_of_formula env f = begin try reified_of_formula env f with e -> oprint stderr f; raise e end let rec reified_of_proposition env = function Pequa (_,{ e_comp=Eq; e_left=t1; e_right=t2 }) -> app coq_p_eq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa (_,{ e_comp=Leq; e_left=t1; e_right=t2 }) -> app coq_p_leq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Geq; e_left=t1; e_right=t2 }) -> app coq_p_geq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Gt; e_left=t1; e_right=t2 }) -> app coq_p_gt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Lt; e_left=t1; e_right=t2 }) -> app coq_p_lt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Neq; e_left=t1; e_right=t2 }) -> app coq_p_neq [| reified_of_formula env t1; reified_of_formula env t2 |] | Ptrue -> Lazy.force coq_p_true | Pfalse -> Lazy.force coq_p_false | Pnot t -> app coq_p_not [| reified_of_proposition env t |] | Por (_,t1,t2) -> app coq_p_or [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pand(_,t1,t2) -> app coq_p_and [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pimp(_,t1,t2) -> app coq_p_imp [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pprop t -> app coq_p_prop [| mk_nat (add_prop env t) |] let reified_of_proposition env f = begin try reified_of_proposition env f with e -> pprint stderr f; raise e end \subsection{Omega vers COQ réifié } let reified_of_omega env body constant = let coeff_constant = app coq_t_int [| Z.mk constant |] in let mk_coeff {c=c; v=v} t = let coef = app coq_t_mult [| reified_of_formula env (unintern_omega env v); app coq_t_int [| Z.mk c |] |] in app coq_t_plus [|coef; t |] in List.fold_right mk_coeff body coeff_constant let reified_of_omega env body c = begin try reified_of_omega env body c with e -> display_eq display_omega_var (body,c); raise e end \section{Opérations sur les équations } Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations . Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations. *) \subsection{Extractions des variables d'une équation } Chaque fonction retourne une liste triée sans redondance let (@@) = list_merge_uniq compare let rec vars_of_formula = function | Oint _ -> [] | Oplus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Omult (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Ominus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Oopp e -> vars_of_formula e | Oatom i -> [i] | Oufo _ -> [] let rec vars_of_equations = function | [] -> [] | e::l -> (vars_of_formula e.e_left) @@ (vars_of_formula e.e_right) @@ (vars_of_equations l) let rec vars_of_prop = function | Pequa(_,e) -> vars_of_equations [e] | Pnot p -> vars_of_prop p | Por(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pand(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pimp(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pprop _ | Ptrue | Pfalse -> [] let rec scalar n = function Oplus(t1,t2) -> let tac1,t1' = scalar n t1 and tac2,t2' = scalar n t2 in do_list [Lazy.force coq_c_mult_plus_distr; do_both tac1 tac2], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_mult_opp_left], Omult(t,Oint(Bigint.neg n)) | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_mult_assoc_reduced], Omult(t1,Oint (n*x)) | Omult(t1,t2) -> Util.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [], Omult(t,Oint n) | Oint i -> do_list [Lazy.force coq_c_reduce],Oint(n*i) | (Oufo _ as t)-> do_list [], Oufo (Omult(t,Oint n)) | Ominus _ -> failwith "scalar minus" let rec negate = function Oplus(t1,t2) -> let tac1,t1' = negate t1 and tac2,t2' = negate t2 in do_list [Lazy.force coq_c_opp_plus ; (do_both tac1 tac2)], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_opp_opp], t | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_opp_mult_r], Omult(t1,Oint (Bigint.neg x)) | Omult(t1,t2) -> Util.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [Lazy.force coq_c_opp_one], Omult(t,Oint(negone)) | Oint i -> do_list [Lazy.force coq_c_reduce] ,Oint(Bigint.neg i) | Oufo c -> do_list [], Oufo (Oopp c) | Ominus _ -> failwith "negate minus" let rec norm l = (List.length l) let rec shuffle_path k1 e1 k2 e2 = let rec loop = function (({c=c1;v=v1}::l1) as l1'), (({c=c2;v=v2}::l2) as l2') -> if v1 = v2 then if k1*c1 + k2 * c2 = zero then ( Lazy.force coq_f_cancel :: loop (l1,l2)) else ( Lazy.force coq_f_equal :: loop (l1,l2) ) else if v1 > v2 then ( Lazy.force coq_f_left :: loop(l1,l2')) else ( Lazy.force coq_f_right :: loop(l1',l2)) | ({c=c1;v=v1}::l1), [] -> Lazy.force coq_f_left :: loop(l1,[]) | [],({c=c2;v=v2}::l2) -> Lazy.force coq_f_right :: loop([],l2) | [],[] -> flush stdout; [] in mk_shuffle_list (loop (e1,e2)) let rec shuffle env (t1,t2) = match t1,t2 with Oplus(l1,r1), Oplus(l2,r2) -> if weight env l1 > weight env l2 then let l_action,t' = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action], Oplus(l1,t') else let l_action,t' = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') | Oplus(l1,r1), t2 -> if weight env l1 > weight env t2 then let (l_action,t') = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action],Oplus(l1, t') else do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) | t1,Oplus(l2,r2) -> if weight env l2 > weight env t1 then let (l_action,t') = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') else do_list [],Oplus(t1,t2) | Oint t1,Oint t2 -> do_list [Lazy.force coq_c_reduce], Oint(t1+t2) | t1,t2 -> if weight env t1 < weight env t2 then do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) else do_list [],Oplus(t1,t2) \subsection{Fusion avec réduction } let shrink_pair f1 f2 = begin match f1,f2 with Oatom v,Oatom _ -> Lazy.force coq_c_red1, Omult(Oatom v,Oint two) | Oatom v, Omult(_,c2) -> Lazy.force coq_c_red2, Omult(Oatom v,Oplus(c2,Oint one)) | Omult (v1,c1),Oatom v -> Lazy.force coq_c_red3, Omult(Oatom v,Oplus(c1,Oint one)) | Omult (Oatom v,c1),Omult (v2,c2) -> Lazy.force coq_c_red4, Omult(Oatom v,Oplus(c1,c2)) | t1,t2 -> oprint stdout t1; print_newline (); oprint stdout t2; print_newline (); flush Pervasives.stdout; Util.error "shrink.1" end let reduce_factor = function Oatom v -> let r = Omult(Oatom v,Oint one) in [Lazy.force coq_c_red0],r | Omult(Oatom v,Oint n) as f -> [],f | Omult(Oatom v,c) -> let rec compute = function Oint n -> n | Oplus(t1,t2) -> compute t1 + compute t2 | _ -> Util.error "condense.1" in [Lazy.force coq_c_reduce], Omult(Oatom v,Oint(compute c)) | t -> Util.error "reduce_factor.1" let rec condense env = function Oplus(f1,(Oplus(f2,r) as t)) -> if weight env f1 = weight env f2 then begin let shrink_tac,t = shrink_pair f1 f2 in let assoc_tac = Lazy.force coq_c_plus_assoc_l in let tac_list,t' = condense env (Oplus(t,r)) in assoc_tac :: do_left (do_list [shrink_tac]) :: tac_list, t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env t in [do_both (do_list tac) (do_list tac')], Oplus(f,t') end | Oplus(f1,Oint n) -> let tac,f1' = reduce_factor f1 in [do_left (do_list tac)],Oplus(f1',Oint n) | Oplus(f1,f2) -> if weight env f1 = weight env f2 then begin let tac_shrink,t = shrink_pair f1 f2 in let tac,t' = condense env t in tac_shrink :: tac,t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env f2 in [do_both (do_list tac) (do_list tac')],Oplus(f,t') end | (Oint _ as t)-> [],t | t -> let tac,t' = reduce_factor t in let final = Oplus(t',Oint zero) in tac @ [Lazy.force coq_c_red6], final let rec clear_zero = function Oplus(Omult(Oatom v,Oint n),r) when n=zero -> let tac',t = clear_zero r in Lazy.force coq_c_red5 :: tac',t | Oplus(f,r) -> let tac,t = clear_zero r in (if tac = [] then [] else [do_right (do_list tac)]),Oplus(f,t) | t -> [],t;; let rec reduce env = function Oplus(t1,t2) -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in let trace3,t' = shuffle env (t1',t2') in t', do_list [do_both trace1 trace2; trace3] | Ominus(t1,t2) -> let t,trace = reduce env (Oplus(t1, Oopp t2)) in t, do_list [Lazy.force coq_c_minus; trace] | Omult(t1,t2) as t -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in begin match t1',t2' with | (_, Oint n) -> let tac,t' = scalar n t1' in t', do_list [do_both trace1 trace2; tac] | (Oint n,_) -> let tac,t' = scalar n t2' in t', do_list [do_both trace1 trace2; Lazy.force coq_c_mult_comm; tac] | _ -> Oufo t, Lazy.force coq_c_nop end | Oopp t -> let t',trace = reduce env t in let trace',t'' = negate t' in t'', do_list [do_left trace; trace'] | (Oint _ | Oatom _ | Oufo _) as t -> t, Lazy.force coq_c_nop let normalize_linear_term env t = let t1,trace1 = reduce env t in let trace2,t2 = condense env t1 in let trace3,t3 = clear_zero t2 in do_list [trace1; do_list trace2; do_list trace3], t3 Cette fonction reproduit très exactement le comportement de [ p_invert ] let negate_oper = function Eq -> Neq | Neq -> Eq | Leq -> Gt | Geq -> Lt | Lt -> Geq | Gt -> Leq let normalize_equation env (negated,depends,origin,path) (oper,t1,t2) = let mk_step t1 t2 f kind = let t = f t1 t2 in let trace, oterm = normalize_linear_term env t in let equa = omega_of_oformula env kind oterm in { e_comp = oper; e_left = t1; e_right = t2; e_negated = negated; e_depends = depends; e_origin = { o_hyp = origin; o_path = List.rev path }; e_trace = trace; e_omega = equa } in try match (if negated then (negate_oper oper) else oper) with | Eq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) EQUA | Neq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) DISE | Leq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o2,Oopp o1)) INEQ | Geq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) INEQ | Lt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o2,Oint negone),Oopp o1)) INEQ | Gt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o1,Oint negone),Oopp o2)) INEQ with e when Logic.catchable_exception e -> raise e let rec oformula_of_constr env t = match Z.parse_term t with | Tplus (t1,t2) -> binop env (fun x y -> Oplus(x,y)) t1 t2 | Tminus (t1,t2) -> binop env (fun x y -> Ominus(x,y)) t1 t2 | Tmult (t1,t2) when Z.is_scalar t1 || Z.is_scalar t2 -> binop env (fun x y -> Omult(x,y)) t1 t2 | Topp t -> Oopp(oformula_of_constr env t) | Tsucc t -> Oplus(oformula_of_constr env t, Oint one) | Tnum n -> Oint n | _ -> Oatom (add_reified_atom t env) and binop env c t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in c t1' t2' and binprop env (neg2,depends,origin,path) add_to_depends neg1 gl c t1 t2 = let i = new_connector_id env in let depends1 = if add_to_depends then Left i::depends else depends in let depends2 = if add_to_depends then Right i::depends else depends in if add_to_depends then Hashtbl.add env.constructors i {o_hyp = origin; o_path = List.rev path}; let t1' = oproposition_of_constr env (neg1,depends1,origin,O_left::path) gl t1 in let t2' = oproposition_of_constr env (neg2,depends2,origin,O_right::path) gl t2 in On numérote le connecteur dans l'environnement . c i t1' t2' and mk_equation env ctxt c connector t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in let omega = normalize_equation env ctxt (connector,t1',t2') in add_equation env omega; Pequa (c,omega) and oproposition_of_constr env ((negated,depends,origin,path) as ctxt) gl c = match Z.parse_rel gl c with | Req (t1,t2) -> mk_equation env ctxt c Eq t1 t2 | Rne (t1,t2) -> mk_equation env ctxt c Neq t1 t2 | Rle (t1,t2) -> mk_equation env ctxt c Leq t1 t2 | Rlt (t1,t2) -> mk_equation env ctxt c Lt t1 t2 | Rge (t1,t2) -> mk_equation env ctxt c Geq t1 t2 | Rgt (t1,t2) -> mk_equation env ctxt c Gt t1 t2 | Rtrue -> Ptrue | Rfalse -> Pfalse | Rnot t -> let t' = oproposition_of_constr env (not negated, depends, origin,(O_mono::path)) gl t in Pnot t' | Ror (t1,t2) -> binprop env ctxt (not negated) negated gl (fun i x y -> Por(i,x,y)) t1 t2 | Rand (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) t1 t2 | Rimp (t1,t2) -> binprop env ctxt (not negated) (not negated) gl (fun i x y -> Pimp(i,x,y)) t1 t2 | Riff (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) (Term.mkArrow t1 t2) (Term.mkArrow t2 t1) | _ -> Pprop c Destructuration des hypothèses et de la conclusion let reify_gl env gl = let concl = Tacmach.pf_concl gl in let t_concl = Pnot (oproposition_of_constr env (true,[],id_concl,[O_mono]) gl concl) in if !debug then begin Printf.printf "REIFED PROBLEM\n\n"; Printf.printf " CONCL: "; pprint stdout t_concl; Printf.printf "\n" end; let rec loop = function (i,t) :: lhyps -> let t' = oproposition_of_constr env (false,[],i,[]) gl t in if !debug then begin Printf.printf " %s: " (Names.string_of_id i); pprint stdout t'; Printf.printf "\n" end; (i,t') :: loop lhyps | [] -> if !debug then print_env_reification env; [] in let t_lhyps = loop (Tacmach.pf_hyps_types gl) in (id_concl,t_concl) :: t_lhyps let rec destructurate_pos_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_neg_hyp orig list_equations list_depends t | Por (i,t1,t2) -> let s1 = destructurate_pos_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Pand(i,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations (list_depends) t1 in let rec loop = function le1 :: ll -> destructurate_pos_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 and destructurate_neg_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_pos_hyp orig list_equations list_depends t | Pand (i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_neg_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Por(_,t1,t2) -> let list_s1 = destructurate_neg_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(_,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 let destructurate_hyps syst = let rec loop = function (i,t) :: l -> let l_syst1 = destructurate_pos_hyp i [] [] t in let l_syst2 = loop l in list_cartesian (@) l_syst1 l_syst2 | [] -> [[]] in loop syst Affichage des dépendances de système let display_depend = function Left i -> Printf.printf " L%d" i | Right i -> Printf.printf " R%d" i let display_systems syst_list = let display_omega om_e = Printf.printf " E%d : %a %s 0\n" om_e.id (fun _ -> display_eq display_omega_var) (om_e.body, om_e.constant) (operator_of_eq om_e.kind) in let display_equation oformula_eq = pprint stdout (Pequa (Lazy.force coq_c_nop,oformula_eq)); print_newline (); display_omega oformula_eq.e_omega; Printf.printf " Depends on:"; List.iter display_depend oformula_eq.e_depends; Printf.printf "\n Path: %s" (String.concat "" (List.map (function O_left -> "L" | O_right -> "R" | O_mono -> "M") oformula_eq.e_origin.o_path)); Printf.printf "\n Origin: %s (negated : %s)\n\n" (Names.string_of_id oformula_eq.e_origin.o_hyp) (if oformula_eq.e_negated then "yes" else "no") in let display_system syst = Printf.printf "=SYSTEM===================================\n"; List.iter display_equation syst in List.iter display_system syst_list Extraction des prédicats utilisées dans une trace . calcul des hypothèses calcul des hypothèses *) let rec hyps_used_in_trace = function | act :: l -> begin match act with | HYP e -> [e.id] @@ (hyps_used_in_trace l) | SPLIT_INEQ (_,(_,act1),(_,act2)) -> hyps_used_in_trace act1 @@ hyps_used_in_trace act2 | _ -> hyps_used_in_trace l end | [] -> [] Extraction des variables déclarées dans une équation . de les déclarer dans l'environnement de la procédure réflexive et les créations de variable au vol de les déclarer dans l'environnement de la procédure réflexive et éviter les créations de variable au vol *) let rec variable_stated_in_trace = function | act :: l -> begin match act with | STATE action -> i nlle_equa : afine , def : afine , eq_orig : afine , i i : int , var : int i action :: variable_stated_in_trace l | SPLIT_INEQ (_,(_,act1),(_,act2)) -> variable_stated_in_trace act1 @ variable_stated_in_trace act2 | _ -> variable_stated_in_trace l end | [] -> [] ;; let add_stated_equations env tree = let stated_equations = let cmpvar x y = Pervasives.(-) x.st_var y.st_var in let rec loop = function | Tree(_,t1,t2) -> List.merge cmpvar (loop t1) (loop t2) | Leaf s -> List.sort cmpvar (variable_stated_in_trace s.s_trace) in loop tree in let add_env st = On retransforme la définition de v en formule let v_def = oformula_of_omega env st.st_def in que si l'ordre de création des variables n'est pas respecté , * ca va planter * ca va planter *) let coq_v = coq_of_formula env v_def in let v = add_reified_atom coq_v env in let term_to_generalize = app coq_refl_equal [|Lazy.force Z.typ; coq_v|] in sa représentation forme d'équation mais non réifié car on n'a pas * l'environnement pour le faire correctement * l'environnement pour le faire correctement *) let term_to_reify = (v_def,Oatom v) in enregistre le lien entre la variable omega et la variable Coq intern_omega_force env (Oatom v) st.st_var; (v, term_to_generalize,term_to_reify,st.st_def.id) in List.map add_env stated_equations Calcule la liste des éclatements à réaliser sur les hypothèses nécessaires pour extraire une liste d'équations donnée nécessaires pour extraire une liste d'équations donnée *) PL : experimentally , the result order of the following function seems _ very _ crucial for efficiency . No idea why . Do not remove the List.rev or modify the current semantics of Util.list_union ( some elements of first arg , then second arg ) , unless you know what you 're doing . _very_ crucial for efficiency. No idea why. Do not remove the List.rev or modify the current semantics of Util.list_union (some elements of first arg, then second arg), unless you know what you're doing. *) let rec get_eclatement env = function i :: r -> let l = try (get_equation env i).e_depends with Not_found -> [] in list_union (List.rev l) (get_eclatement env r) | [] -> [] let select_smaller l = let comp (_,x) (_,y) = Pervasives.(-) (List.length x) (List.length y) in try List.hd (List.sort comp l) with Failure _ -> failwith "select_smaller" let filter_compatible_systems required systems = let rec select = function (x::l) -> if List.mem x required then select l else if List.mem (barre x) required then failwith "Exit" else x :: select l | [] -> [] in map_succeed (function (sol,splits) -> (sol,select splits)) systems let rec equas_of_solution_tree = function Tree(_,t1,t2) -> (equas_of_solution_tree t1)@@(equas_of_solution_tree t2) | Leaf s -> s.s_equa_deps [ really_useful_prop ] pushes useless props in a new Pprop variable Things get shorter , but may also get wrong , since a Prop is considered to be undecidable in ReflOmegaCore.concl_to_hyp , whereas for instance Pfalse is decidable . So should not be used on conclusion ( ? ? ) to be undecidable in ReflOmegaCore.concl_to_hyp, whereas for instance Pfalse is decidable. So should not be used on conclusion (??) *) let really_useful_prop l_equa c = let rec real_of = function Pequa(t,_) -> t | Ptrue -> app coq_True [||] | Pfalse -> app coq_False [||] | Pnot t1 -> app coq_not [|real_of t1|] | Por(_,t1,t2) -> app coq_or [|real_of t1; real_of t2|] | Pand(_,t1,t2) -> app coq_and [|real_of t1; real_of t2|] Attention : implications sur le lifting des variables à comprendre ! | Pimp(_,t1,t2) -> Term.mkArrow (real_of t1) (real_of t2) | Pprop t -> t in let rec loop c = match c with Pequa(_,e) -> if List.mem e.e_omega.id l_equa then Some c else None | Ptrue -> None | Pfalse -> None | Pnot t1 -> begin match loop t1 with None -> None | Some t1' -> Some (Pnot t1') end | Por(i,t1,t2) -> binop (fun (t1,t2) -> Por(i,t1,t2)) t1 t2 | Pand(i,t1,t2) -> binop (fun (t1,t2) -> Pand(i,t1,t2)) t1 t2 | Pimp(i,t1,t2) -> binop (fun (t1,t2) -> Pimp(i,t1,t2)) t1 t2 | Pprop t -> None and binop f t1 t2 = begin match loop t1, loop t2 with None, None -> None | Some t1',Some t2' -> Some (f(t1',t2')) | Some t1',None -> Some (f(t1',Pprop (real_of t2))) | None,Some t2' -> Some (f(Pprop (real_of t1),t2')) end in match loop c with None -> Pprop (real_of c) | Some t -> t let rec display_solution_tree ch = function Leaf t -> output_string ch (Printf.sprintf "%d[%s]" t.s_index (String.concat " " (List.map string_of_int t.s_equa_deps))) | Tree(i,t1,t2) -> Printf.fprintf ch "S%d(%a,%a)" i display_solution_tree t1 display_solution_tree t2 let rec solve_with_constraints all_solutions path = let rec build_tree sol buf = function [] -> Leaf sol | (Left i :: remainder) -> Tree(i, build_tree sol (Left i :: buf) remainder, solve_with_constraints all_solutions (List.rev(Right i :: buf))) | (Right i :: remainder) -> Tree(i, solve_with_constraints all_solutions (List.rev (Left i :: buf)), build_tree sol (Right i :: buf) remainder) in let weighted = filter_compatible_systems path all_solutions in let (winner_sol,winner_deps) = try select_smaller weighted with e -> Printf.printf "%d - %d\n" (List.length weighted) (List.length all_solutions); List.iter display_depend path; raise e in build_tree winner_sol (List.rev path) winner_deps let find_path {o_hyp=id;o_path=p} env = let rec loop_path = function ([],l) -> Some l | (x1::l1,x2::l2) when x1 = x2 -> loop_path (l1,l2) | _ -> None in let rec loop_id i = function CCHyp{o_hyp=id';o_path=p'} :: l when id = id' -> begin match loop_path (p',p) with Some r -> i,r | None -> loop_id (succ i) l end | _ :: l -> loop_id (succ i) l | [] -> failwith "find_path" in loop_id 0 env let mk_direction_list l = let trans = function O_left -> coq_d_left | O_right -> coq_d_right | O_mono -> coq_d_mono in mk_list (Lazy.force coq_direction) (List.map (fun d-> Lazy.force(trans d)) l) let get_hyp env_hyp i = try list_index0 (CCEqua i) env_hyp with Not_found -> failwith (Printf.sprintf "get_hyp %d" i) let replay_history env env_hyp = let rec loop env_hyp t = match t with | CONTRADICTION (e1,e2) :: l -> let trace = mk_nat (List.length e1.body) in mkApp (Lazy.force coq_s_contradiction, [| trace ; mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | DIVIDE_AND_APPROX (e1,e2,k,d) :: l -> mkApp (Lazy.force coq_s_div_approx, [| Z.mk k; Z.mk d; reified_of_omega env e2.body e2.constant; mk_nat (List.length e2.body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id) |]) | NOT_EXACT_DIVIDE (e1,k) :: l -> let e2_constant = floor_div e1.constant k in let d = e1.constant - e2_constant * k in let e2_body = map_eq_linear (fun c -> c / k) e1.body in mkApp (Lazy.force coq_s_not_exact_divide, [|Z.mk k; Z.mk d; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); mk_nat (get_hyp env_hyp e1.id)|]) | EXACT_DIVIDE (e1,k) :: l -> let e2_body = map_eq_linear (fun c -> c / k) e1.body in let e2_constant = floor_div e1.constant k in mkApp (Lazy.force coq_s_exact_divide, [|Z.mk k; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id)|]) | (MERGE_EQ(e3,e1,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2 in mkApp (Lazy.force coq_s_merge_eq, [| mk_nat (List.length e1.body); mk_nat n1; mk_nat n2; loop (CCEqua e3:: env_hyp) l |]) | SUM(e3,(k1,e1),(k2,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2.id in let trace = shuffle_path k1 e1.body k2 e2.body in mkApp (Lazy.force coq_s_sum, [| Z.mk k1; mk_nat n1; Z.mk k2; mk_nat n2; trace; (loop (CCEqua e3 :: env_hyp) l) |]) | CONSTANT_NOT_NUL(e,k) :: l -> mkApp (Lazy.force coq_s_constant_not_nul, [| mk_nat (get_hyp env_hyp e) |]) | CONSTANT_NEG(e,k) :: l -> mkApp (Lazy.force coq_s_constant_neg, [| mk_nat (get_hyp env_hyp e) |]) | STATE {st_new_eq=new_eq; st_def =def; st_orig=orig; st_coef=m; st_var=sigma } :: l -> let n1 = get_hyp env_hyp orig.id and n2 = get_hyp env_hyp def.id in let v = unintern_omega env sigma in let o_def = oformula_of_omega env def in let o_orig = oformula_of_omega env orig in let body = Oplus (o_orig,Omult (Oplus (Oopp v,o_def), Oint m)) in let trace,_ = normalize_linear_term env body in mkApp (Lazy.force coq_s_state, [| Z.mk m; trace; mk_nat n1; mk_nat n2; loop (CCEqua new_eq.id :: env_hyp) l |]) | HYP _ :: l -> loop env_hyp l | CONSTANT_NUL e :: l -> mkApp (Lazy.force coq_s_constant_nul, [| mk_nat (get_hyp env_hyp e) |]) | NEGATE_CONTRADICT(e1,e2,true) :: l -> mkApp (Lazy.force coq_s_negate_contradict, [| mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | NEGATE_CONTRADICT(e1,e2,false) :: l -> mkApp (Lazy.force coq_s_negate_contradict_inv, [| mk_nat (List.length e2.body); mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | SPLIT_INEQ(e,(e1,l1),(e2,l2)) :: l -> let i = get_hyp env_hyp e.id in let r1 = loop (CCEqua e1 :: env_hyp) l1 in let r2 = loop (CCEqua e2 :: env_hyp) l2 in mkApp (Lazy.force coq_s_split_ineq, [| mk_nat (List.length e.body); mk_nat i; r1 ; r2 |]) | (FORGET_C _ | FORGET _ | FORGET_I _) :: l -> loop env_hyp l | (WEAKEN _ ) :: l -> failwith "not_treated" | [] -> failwith "no contradiction" in loop env_hyp let rec decompose_tree env ctxt = function Tree(i,left,right) -> let org = try Hashtbl.find env.constructors i with Not_found -> failwith (Printf.sprintf "Cannot find constructor %d" i) in let (index,path) = find_path org ctxt in let left_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_left]} in let right_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_right]} in app coq_e_split [| mk_nat index; mk_direction_list path; decompose_tree env (left_hyp::ctxt) left; decompose_tree env (right_hyp::ctxt) right |] | Leaf s -> decompose_tree_hyps s.s_trace env ctxt s.s_equa_deps and decompose_tree_hyps trace env ctxt = function [] -> app coq_e_solve [| replay_history env ctxt trace |] | (i::l) -> let equation = try Hashtbl.find env.equations i with Not_found -> failwith (Printf.sprintf "Cannot find equation %d" i) in let (index,path) = find_path equation.e_origin ctxt in let full_path = if equation.e_negated then path @ [O_mono] else path in let cont = decompose_tree_hyps trace env (CCEqua equation.e_omega.id :: ctxt) l in app coq_e_extract [|mk_nat index; mk_direction_list full_path; cont |] Cette fonction construit la trace pour la procédure de décision réflexive . A partir des résultats de l'extraction des systèmes , elle lance la résolution par Omega , puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive . trace pour la procédure de décision réflexive. A partir des résultats de l'extraction des systèmes, elle lance la résolution par Omega, puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive. *) let resolution env full_reified_goal systems_list = let num = ref 0 in let solve_system list_eq = let index = !num in let system = List.map (fun eq -> eq.e_omega) list_eq in let trace = simplify_strong (new_omega_eq,new_omega_var,display_omega_var) system in let vars = hyps_used_in_trace trace in let splits = get_eclatement env vars in if !debug then begin Printf.printf "SYSTEME %d\n" index; display_action display_omega_var trace; print_string "\n Depend :"; List.iter (fun i -> Printf.printf " %d" i) vars; print_string "\n Split points :"; List.iter display_depend splits; Printf.printf "\n------------------------------------\n" end; incr num; {s_index = index; s_trace = trace; s_equa_deps = vars}, splits in if !debug then Printf.printf "\n====================================\n"; let all_solutions = List.map solve_system systems_list in let solution_tree = solve_with_constraints all_solutions [] in if !debug then begin display_solution_tree stdout solution_tree; print_newline() end; let useful_equa_id = equas_of_solution_tree solution_tree in let equations = List.map (get_equation env) useful_equa_id in let l_hyps' = list_uniquize (List.map (fun e -> e.e_origin.o_hyp) equations) in let l_hyps = id_concl :: list_remove id_concl l_hyps' in let useful_hyps = List.map (fun id -> List.assoc id full_reified_goal) l_hyps in let useful_vars = let really_useful_vars = vars_of_equations equations in let concl_vars = vars_of_prop (List.assoc id_concl full_reified_goal) in really_useful_vars @@ concl_vars in let to_introduce = add_stated_equations env solution_tree in let stated_vars = List.map (fun (v,_,_,_) -> v) to_introduce in let l_generalize_arg = List.map (fun (_,t,_,_) -> t) to_introduce in let hyp_stated_vars = List.map (fun (_,_,_,id) -> CCEqua id) to_introduce in L'environnement de base se construit en : - les variables des équations utiles ( et de la conclusion ) - les nouvelles variables declarées durant les preuves - les variables des équations utiles (et de la conclusion) - les nouvelles variables declarées durant les preuves *) let all_vars_env = useful_vars @ stated_vars in let basic_env = let rec loop i = function var :: l -> let t = get_reified_atom env var in Hashtbl.add env.real_indices var i; t :: loop (succ i) l | [] -> [] in loop 0 all_vars_env in let env_terms_reified = mk_list (Lazy.force Z.typ) basic_env in On peut maintenant but : env est a jour let l_reified_stated = List.map (fun (_,_,(l,r),_) -> app coq_p_eq [| reified_of_formula env l; reified_of_formula env r |]) to_introduce in let reified_concl = match useful_hyps with (Pnot p) :: _ -> reified_of_proposition env p | _ -> reified_of_proposition env Pfalse in let l_reified_terms = (List.map (fun p -> reified_of_proposition env (really_useful_prop useful_equa_id p)) (List.tl useful_hyps)) in let env_props_reified = mk_plist env.props in let reified_goal = mk_list (Lazy.force coq_proposition) (l_reified_stated @ l_reified_terms) in let reified = app coq_interp_sequent [| reified_concl;env_props_reified;env_terms_reified;reified_goal|] in let normalize_equation e = let rec loop = function [] -> app (if e.e_negated then coq_p_invert else coq_p_step) [| e.e_trace |] | ((O_left | O_mono) :: l) -> app coq_p_left [| loop l |] | (O_right :: l) -> app coq_p_right [| loop l |] in let correct_index = let i = list_index0 e.e_origin.o_hyp l_hyps in PL : it seems that additionnally introduced hyps are in the way during normalization , hence this index shifting ... normalization, hence this index shifting... *) if i=0 then 0 else Pervasives.(+) i (List.length to_introduce) in app coq_pair_step [| mk_nat correct_index; loop e.e_origin.o_path |] in let normalization_trace = mk_list (Lazy.force coq_h_step) (List.map normalize_equation equations) in let initial_context = List.map (fun id -> CCHyp{o_hyp=id;o_path=[]}) (List.tl l_hyps) in let context = CCHyp{o_hyp=id_concl;o_path=[]} :: hyp_stated_vars @ initial_context in let decompose_tactic = decompose_tree env context solution_tree in Tactics.generalize (l_generalize_arg @ List.map Term.mkVar (List.tl l_hyps)) >> Tactics.change_in_concl None reified >> Tactics.apply (app coq_do_omega [|decompose_tactic; normalization_trace|]) >> show_goal >> Tactics.normalise_vm_in_concl >> i Alternatives to the previous line : - Normalisation without VM : Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED : Tacmach.convert_concl_no_check ( Lazy.force coq_True ) Term . VMcast > > i - Normalisation without VM: Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED: Tacmach.convert_concl_no_check (Lazy.force coq_True) Term.VMcast >> i*) Tactics.apply (Lazy.force coq_I) let total_reflexive_omega_tactic gl = Coqlib.check_required_library ["Coq";"romega";"ROmega"]; rst_omega_eq (); rst_omega_var (); try let env = new_environment () in let full_reified_goal = reify_gl env gl in let systems_list = destructurate_hyps full_reified_goal in if !debug then display_systems systems_list; resolution env full_reified_goal systems_list gl with NO_CONTRADICTION -> Util.error "ROmega can't solve this system" i let tester = Tacmach.hide_atomic_tactic " TestOmega " test_tactic i
2504917f451b64ba7603716d6d98adcbd61be2d5b867cfc73f80459184ad106b
justinkirby/emetric
emetric_cmd_stop.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 %%% @end %%% This source file is subject to the New BSD License . You should have received %%% a copy of the New BSD license with this software. If not, it can be %%% retrieved from: -license.php %%%------------------------------------------------------------------- -module(emetric_cmd_stop). -behaviour(emetric_command). -export([command_help/0, deps/0, run/0 ]). command_help() -> {"stop","skip=true|false","Shutdown the emetric app on the --node "}. deps() -> case emetric_config:get_global(skip,"false") of "true" -> []; "false" -> [emetric_cmd_inject] end. run() -> Node = list_to_atom(emetric_config:get_global(node)), rpc:call(Node,emetric_appsrv,stop,[]), ok.
null
https://raw.githubusercontent.com/justinkirby/emetric/6310f8f74a787100eb9d6356d2beffabc91fda1e/src/emetric_cmd_stop.erl
erlang
------------------------------------------------------------------- @end a copy of the New BSD license with this software. If not, it can be retrieved from: -license.php -------------------------------------------------------------------
@author < > ( C ) 2011 This source file is subject to the New BSD License . You should have received -module(emetric_cmd_stop). -behaviour(emetric_command). -export([command_help/0, deps/0, run/0 ]). command_help() -> {"stop","skip=true|false","Shutdown the emetric app on the --node "}. deps() -> case emetric_config:get_global(skip,"false") of "true" -> []; "false" -> [emetric_cmd_inject] end. run() -> Node = list_to_atom(emetric_config:get_global(node)), rpc:call(Node,emetric_appsrv,stop,[]), ok.
8d7f76c557537782b57e9b1105955b8b393602ca1eec6e58c673a58e13f4ab94
mikpe/pdp10-tools
ld_output.erl
-*- erlang - indent - level : 2 -*- %%% ELF output for pdp10 - elf - ld Copyright ( C ) 2020 %%% This file is part of pdp10 - tools . %%% pdp10 - tools is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %%% (at your option) any later version. %%% pdp10 - tools 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 pdp10 - tools . If not , see < / > . -module(ld_output). -export([ output/5 , format_error/1 ]). -include("ld_internal.hrl"). %% Output ====================================================================== -spec output(string(), string() | non_neg_integer(), [#segment{}], global(), filemap()) -> ok | {error, {module(), term()}}. output(File, Entry, Segments, GlobalMap, FileMap) -> case resolve(Entry, GlobalMap) of {ok, NewEntry} -> case pdp10_stdio:fopen(File, [raw, write, delayed_write]) of {ok, FP} -> try Funs = [ fun output_elf_header/6 , fun output_phtab/6 , fun output_segments/6 ], output(Funs, NewEntry, Segments, GlobalMap, FileMap, FP, _Offset = 0) after pdp10_stdio:fclose(FP) end; {error, Reason} -> {error, {?MODULE, {cannot_open, File, Reason}}} end; {error, _Reason} = Error -> Error end. output([], _Entry, _Segments, _GlobalMap, _FileMap, _FP, _Offset) -> ok; output([Fun | Funs], Entry, Segments, GlobalMap, FileMap, FP, Offset) -> case Fun(Entry, Segments, GlobalMap, FileMap, FP, Offset) of {ok, NewOffset} -> output(Funs, Entry, Segments, GlobalMap, FileMap, FP, NewOffset); {error, _Reason} = Error -> Error end. resolve(Value, _GlobalMap) when is_integer(Value) -> {ok, Value}; resolve(Symbol, GlobalMap) -> case maps:get(Symbol, GlobalMap, false) of Value when is_integer(Value) -> {ok, Value}; false -> {error, {?MODULE, {undefined_symbol, Symbol}}} end. output_padding(0, _FP) -> ok; output_padding(N, FP) when N > 0 -> case pdp10_stdio:fputc(0, FP) of ok -> output_padding(N - 1, FP); {error, _Reason} = Error -> Error end. %% ELF Header Output ----------------------------------------------------------- output_elf_header(Entry, Segments, _GlobalMap, _FileMap, FP, Offset = 0) -> PhNum = length(Segments), assert ; TODO : otherwise store PhNum in Shdr0.sh_info PhOff = ?ELF36_EHDR_SIZEOF, Ehdr0 = pdp10_elf36:make_Ehdr(), Ehdr = Ehdr0#elf36_Ehdr{ e_type = ?ET_EXEC , e_entry = Entry , e_phoff = PhOff , e_phnum = PhNum }, case pdp10_elf36:write_Ehdr(FP, Ehdr) of ok -> {ok, Offset + ?ELF36_EHDR_SIZEOF}; {error, _Reason} = Error -> Error end. %% Program Header Table Output ------------------------------------------------- output_phtab(_Entry, Segments, _GlobalMap, _FileMap, FP, Offset = ?ELF36_EHDR_SIZEOF) -> %% no need to emit alignment padding output_phtab(Segments, FP, Offset). output_phtab(_Segments = [], _FP, Offset) -> {ok, Offset}; output_phtab([#segment{phdr = Phdr} | Segments], FP, Offset) -> case pdp10_elf36:write_Phdr(FP, Phdr) of ok -> output_phtab(Segments, FP, Offset + ?ELF36_PHDR_SIZEOF); {error, _Reason} = Error -> Error end. %% Segments Output ------------------------------------------------------------- output_segments(_Entry, Segments, GlobalMap, FileMap, FP, Offset) -> output_segments(Segments, GlobalMap, FileMap, FP, Offset). output_segments(_Segments = [], _GlobalMap, _FileMap, _FP, Offset) -> {ok, Offset}; output_segments([Segment | Segments], GlobalMap, FileMap, FP, Offset) -> case output_segment(Segment, GlobalMap, FileMap, FP, Offset) of {ok, NewOffset} -> output_segments(Segments, GlobalMap, FileMap, FP, NewOffset); {error, _Reason} = Error -> Error end. output_segment(Segment, GlobalMap, FileMap, FP, Offset) -> #segment{phdr = Phdr, sections = Sections} = Segment, #elf36_Phdr{p_offset = SegOffset, p_vaddr = SegVAddr} = Phdr, case output_padding(SegOffset - Offset, FP) of ok -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr); {error, _Reason} = Error -> Error end. %% Sections Output ------------------------------------------------------------- output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr) -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr, _Offset = 0). output_sections(_Sections = [], _GlobalMap, _FileMap, _FP, SegOffset, _SegVAddr, Offset) -> {ok, SegOffset + Offset}; output_sections([Section | Sections], GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) -> case output_section(Section, GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) of {ok, NewOffset} -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr, NewOffset); {error, _Reason} = Error -> Error end. output_section(Section, GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) -> #section{shdr = Shdr, frags = Frags} = Section, #elf36_Shdr{sh_offset = ShOffset} = Shdr, case output_padding(ShOffset - Offset, FP) of ok -> output_frags(Frags, GlobalMap, FileMap, FP, SegOffset + ShOffset, SegVAddr + ShOffset); {error, _Reason} = Error -> Error end. %% Fragments Output ------------------------------------------------------------ output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr) -> output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr, _Offset = 0). output_frags(_Frags = [], _GlobalMap, _FileMap, _FP, SectOffset, _SectVAddr, Offset) -> {ok, SectOffset + Offset}; output_frags([Frag | Frags], GlobalMap, FileMap, FP, SectOffset, SectVAddr, Offset) -> case output_frag(Frag, GlobalMap, FileMap, FP, SectOffset, SectVAddr, Offset) of {ok, NewOffset} -> output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr, NewOffset); {error, _Reason} = Error -> Error end. %% Single Fragment Output ------------------------------------------------------ %% %% Copy a section from an input file and append it to the output file. %% Simultaneously apply associated relocations. output_frag(Frag, GlobalMap, FileMap, FP, _SectOffset, _SectVAddr, Offset) -> case input_init(Frag) of {ok, {Input, Relocs}} -> Output = output_init(Frag, GlobalMap, FileMap, FP, Relocs), case output_frag(Input, Output) of {ok, FragOffset} -> {ok, Offset + FragOffset}; {error, _Reason} = Error -> Error end; {error, _Reason} = Error -> Error end. output_frag(Input, Output) -> case input(Input) of {ok, {Byte, NewInput}} -> case output(Output, Byte) of {ok, {Pushback, NewOutput}} -> output_frag(input_pushback(NewInput, Pushback), NewOutput); {ok, NewOutput} -> output_frag(NewInput, NewOutput); {error, _Reason} = Error -> Error end; eof -> input_fini(Input), output_fini(Output); {error, _Reason} = Error -> Error end. -record(frag_input, {fp, file, sh_name, size, pushback}). input_init(Frag) -> #sectfrag{file = File, shdr = Shdr, relocs = RelocShdr} = Frag, case pdp10_stdio:fopen(File, [raw, read]) of {ok, FP} -> case input_relocs(FP, RelocShdr) of {ok, Relocs} -> #elf36_Shdr{sh_offset = ShOffset, sh_size = ShSize, sh_name = ShName} = Shdr, case pdp10_stdio:fseek(FP, {bof, ShOffset}) of ok -> Input = #frag_input{fp = FP, file = File, sh_name = ShName, size = ShSize, pushback = []}, {ok, {Input, Relocs}}; {error, _Reason} = Error -> Error end; {error, _Reason} = Error -> Error end; {error, Reason} -> {error, {?MODULE, {cannot_open, File, Reason}}} end. input_relocs(_FP, false) -> {ok, []}; input_relocs(FP, Shdr) -> pdp10_elf36:read_RelaTab(FP, Shdr). input_fini(#frag_input{fp = FP}) -> pdp10_stdio:fclose(FP). input_pushback(#frag_input{pushback = Pushback} = Input, Buffer) -> Input#frag_input{pushback = Buffer ++ Pushback}. input(#frag_input{pushback = [Byte | Pushback]} = Input) -> {ok, {Byte, Input#frag_input{pushback = Pushback}}}; input(#frag_input{size = 0}) -> eof; input(#frag_input{fp = FP, size = Size} = Input) when Size > 0 -> case pdp10_stdio:fgetc(FP) of {ok, Byte} -> {ok, {Byte, Input#frag_input{size = Size - 1}}}; eof -> #frag_input{file = File, sh_name = ShName} = Input, {error, {?MODULE, {premature_eof, File, ShName}}}; {error, _Reason} = Error -> Error end. -record(frag_output, { file , sh_name , globalmap , filemap , fp , relocs , frag_offset , buffer }). output_init(Frag, GlobalMap, FileMap, FP, Relocs) -> #sectfrag{file = File, shdr = #elf36_Shdr{sh_name = ShName}} = Frag, SortedRelocs = lists:keysort(#elf36_Rela.r_offset, Relocs), #frag_output{file = File, sh_name = ShName, globalmap = GlobalMap, filemap = FileMap, fp = FP, relocs = SortedRelocs, frag_offset = 0, buffer = []}. output_fini(#frag_output{relocs = [], frag_offset = FragOffset}) -> {ok, FragOffset}; output_fini(#frag_output{file = File, sh_name = ShName}) -> {error, {?MODULE, {unresolved_relocs, File, ShName}}}. output(Output, Byte) -> case Output#frag_output.relocs of [] -> output_directly(Output, Byte); [#elf36_Rela{r_offset = RelOffset} = Rela | _] -> FragOffset = Output#frag_output.frag_offset, case FragOffset < RelOffset of true -> output_directly(Output, Byte); false -> NewBuffer = [Byte | Output#frag_output.buffer], NewFragOffset = FragOffset + 1, NewOutput = Output#frag_output{frag_offset = NewFragOffset, buffer = NewBuffer}, case length(NewBuffer) =:= sizeof_reloc(Rela) of true -> output_reloc(NewOutput); false -> {ok, NewOutput} end end end. output_reloc(Output) -> #frag_output{ file = File , filemap = FileMap , globalmap = GlobalMap , relocs = [Reloc | Relocs] , buffer = Buffer0 , frag_offset = FragOffset } = Output, #elf36_Rela{ r_info = Info , r_addend = Addend } = Reloc, Type = ?ELF36_R_TYPE(Info), SymNdx = ?ELF36_R_SYM(Info), case symbol_value(SymNdx, File, FileMap, GlobalMap) of {ok, SymbolValue} -> Buffer1 = lists:reverse(Buffer0), Length = length(Buffer1), Word = buffer_word(Length, Buffer1), %% TODO: handle {error,_} returns {ok, NewWord} = apply_reloc(Type, SymbolValue + Addend, Word), Pushback = word_buffer(Length, NewWord), {ok, {Pushback, Output#frag_output{relocs = Relocs, buffer = [], frag_offset = FragOffset - Length}}}; {error, _Reason} = Error -> Error end. symbol_value(SymNdx, File, FileMap, GlobalMap) -> LocalMap = maps:get(File, FileMap), case maps:get(SymNdx, LocalMap) of Value when is_integer(Value) -> {ok, Value}; Symbol when is_list(Symbol) -> case maps:get(Symbol, GlobalMap, false) of Value when is_integer(Value) -> {ok, Value}; false -> {error, {?MODULE, {undefined_symbol, Symbol}}} end end. buffer_word(4, Buffer) -> pdp10_extint:uint36_from_ext(Buffer); buffer_word(2, Buffer) -> pdp10_extint:uint18_from_ext(Buffer); buffer_word(1, [Byte]) -> Byte. word_buffer(4, Word) -> pdp10_extint:uint36_to_ext(Word); word_buffer(2, Word) -> pdp10_extint:uint18_to_ext(Word); word_buffer(1, Byte) -> [Byte]. sizeof_reloc(#elf36_Rela{r_info = Info}) -> case ?ELF36_R_TYPE(Info) of ?R_PDP10_IFIW -> 4; ?R_PDP10_EFIW -> 4; ?R_PDP10_LOCAL_W -> 2; ?R_PDP10_LOCAL_B -> 4; ?R_PDP10_LOCAL_H -> 4; ?R_PDP10_GLOBAL_B -> 4; ?R_PDP10_GLOBAL_H -> 4; ?R_PDP10_LITERAL_W -> 4; ?R_PDP10_LITERAL_H -> 2; ?R_PDP10_LITERAL_B -> 1 end. apply_reloc(Type, Value, Word) -> case Type of ?R_PDP10_IFIW -> 0 = (Value band 3), % assert alignment Address = Value div 4, %% TODO: check that location and value are in same section %% TODO: handle cross-section references {ok, (Word band bnot ?PDP10_UINT18_MAX) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_EFIW -> 0 = (Value band 3), % assert alignment Address = Value div 4, 0 = (Address band bnot ((1 bsl 30) - 1)), % assert clear bit 0 , preserve bits 1 to 5 {ok, (Word band Mask) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_LOCAL_W -> 0 = (Value band 3), % assert alignment Address = Value div 4, TODO : handle non - zero sections 0 = (Address band bnot ?PDP10_UINT18_MAX), % assert section {ok, Address band ?PDP10_UINT18_MAX}; ?R_PDP10_LOCAL_B -> Address = Value div 4, TODO : handle non - zero sections 0 = (Address band bnot ?PDP10_UINT18_MAX), % assert section P \in { 0 , 9 , 18 , 27 } S = 9, {ok, (P bsl 30) bor (S bsl 24) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_LOCAL_H -> 0 = (Value band 1), % assert alignment Address = Value div 4, TODO : handle non - zero sections 0 = (Address band bnot ?PDP10_UINT18_MAX), % assert section P \in { 0 , 18 } S = 18, {ok, (P bsl 30) bor (S bsl 24) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_GLOBAL_B -> Address = Value div 4, 0 = (Address band bnot ((1 bsl 30) - 1)), % assert PS = 8#70 + (Value band 3), {ok, (PS bsl 30) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_GLOBAL_H -> 0 = (Value band 1), % assert alignment Address = Value div 4, PS = 8#75 + ((Value band 2) bsr 1), {ok, (PS bsl 30) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_LITERAL_W -> Value = (Value band ?PDP10_UINT36_MAX), % assert {ok, Value}; ?R_PDP10_LITERAL_H -> Value = (Value band ?PDP10_UINT18_MAX), % assert {ok, Value}; ?R_PDP10_LITERAL_B -> Value = (Value band ?PDP10_UINT9_MAX), % assert {ok, Value} end. output_directly(Output, Byte) -> #frag_output{fp = FP, frag_offset = FragOffset} = Output, case pdp10_stdio:fputc(Byte, FP) of ok -> {ok, Output#frag_output{frag_offset = FragOffset + 1}}; {error, _Reason} = Error -> Error end. %% Error reporting ------------------------------------------------------------- -spec format_error(term()) -> io_lib:chars(). format_error(Reason) -> case Reason of {cannot_open, File, Reason0} -> io_lib:format("cannot open ~s: ~s", [File, error:format(Reason0)]); {premature_eof, File, ShName} -> io_lib:format("premature eof: ~s:~s", [File, ShName]); {undefined_symbol, Symbol} -> io_lib:format("undefined symbol: ~s", [Symbol]); {unresolved_relocs, File, ShName} -> io_lib:format("unresolved relocations: ~s:~s", [File, ShName]) end.
null
https://raw.githubusercontent.com/mikpe/pdp10-tools/99216b63317fe5b5ac18f1a0d3c81b464f8b8f40/erlang/apps/ld/src/ld_output.erl
erlang
(at your option) any later version. 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. Output ====================================================================== ELF Header Output ----------------------------------------------------------- Program Header Table Output ------------------------------------------------- no need to emit alignment padding Segments Output ------------------------------------------------------------- Sections Output ------------------------------------------------------------- Fragments Output ------------------------------------------------------------ Single Fragment Output ------------------------------------------------------ Copy a section from an input file and append it to the output file. Simultaneously apply associated relocations. TODO: handle {error,_} returns assert alignment TODO: check that location and value are in same section TODO: handle cross-section references assert alignment assert assert alignment assert section assert section assert alignment assert section assert assert alignment assert assert assert Error reporting -------------------------------------------------------------
-*- erlang - indent - level : 2 -*- ELF output for pdp10 - elf - ld Copyright ( C ) 2020 This file is part of pdp10 - tools . pdp10 - tools is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or pdp10 - tools is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with pdp10 - tools . If not , see < / > . -module(ld_output). -export([ output/5 , format_error/1 ]). -include("ld_internal.hrl"). -spec output(string(), string() | non_neg_integer(), [#segment{}], global(), filemap()) -> ok | {error, {module(), term()}}. output(File, Entry, Segments, GlobalMap, FileMap) -> case resolve(Entry, GlobalMap) of {ok, NewEntry} -> case pdp10_stdio:fopen(File, [raw, write, delayed_write]) of {ok, FP} -> try Funs = [ fun output_elf_header/6 , fun output_phtab/6 , fun output_segments/6 ], output(Funs, NewEntry, Segments, GlobalMap, FileMap, FP, _Offset = 0) after pdp10_stdio:fclose(FP) end; {error, Reason} -> {error, {?MODULE, {cannot_open, File, Reason}}} end; {error, _Reason} = Error -> Error end. output([], _Entry, _Segments, _GlobalMap, _FileMap, _FP, _Offset) -> ok; output([Fun | Funs], Entry, Segments, GlobalMap, FileMap, FP, Offset) -> case Fun(Entry, Segments, GlobalMap, FileMap, FP, Offset) of {ok, NewOffset} -> output(Funs, Entry, Segments, GlobalMap, FileMap, FP, NewOffset); {error, _Reason} = Error -> Error end. resolve(Value, _GlobalMap) when is_integer(Value) -> {ok, Value}; resolve(Symbol, GlobalMap) -> case maps:get(Symbol, GlobalMap, false) of Value when is_integer(Value) -> {ok, Value}; false -> {error, {?MODULE, {undefined_symbol, Symbol}}} end. output_padding(0, _FP) -> ok; output_padding(N, FP) when N > 0 -> case pdp10_stdio:fputc(0, FP) of ok -> output_padding(N - 1, FP); {error, _Reason} = Error -> Error end. output_elf_header(Entry, Segments, _GlobalMap, _FileMap, FP, Offset = 0) -> PhNum = length(Segments), assert ; TODO : otherwise store PhNum in Shdr0.sh_info PhOff = ?ELF36_EHDR_SIZEOF, Ehdr0 = pdp10_elf36:make_Ehdr(), Ehdr = Ehdr0#elf36_Ehdr{ e_type = ?ET_EXEC , e_entry = Entry , e_phoff = PhOff , e_phnum = PhNum }, case pdp10_elf36:write_Ehdr(FP, Ehdr) of ok -> {ok, Offset + ?ELF36_EHDR_SIZEOF}; {error, _Reason} = Error -> Error end. output_phtab(_Entry, Segments, _GlobalMap, _FileMap, FP, Offset = ?ELF36_EHDR_SIZEOF) -> output_phtab(Segments, FP, Offset). output_phtab(_Segments = [], _FP, Offset) -> {ok, Offset}; output_phtab([#segment{phdr = Phdr} | Segments], FP, Offset) -> case pdp10_elf36:write_Phdr(FP, Phdr) of ok -> output_phtab(Segments, FP, Offset + ?ELF36_PHDR_SIZEOF); {error, _Reason} = Error -> Error end. output_segments(_Entry, Segments, GlobalMap, FileMap, FP, Offset) -> output_segments(Segments, GlobalMap, FileMap, FP, Offset). output_segments(_Segments = [], _GlobalMap, _FileMap, _FP, Offset) -> {ok, Offset}; output_segments([Segment | Segments], GlobalMap, FileMap, FP, Offset) -> case output_segment(Segment, GlobalMap, FileMap, FP, Offset) of {ok, NewOffset} -> output_segments(Segments, GlobalMap, FileMap, FP, NewOffset); {error, _Reason} = Error -> Error end. output_segment(Segment, GlobalMap, FileMap, FP, Offset) -> #segment{phdr = Phdr, sections = Sections} = Segment, #elf36_Phdr{p_offset = SegOffset, p_vaddr = SegVAddr} = Phdr, case output_padding(SegOffset - Offset, FP) of ok -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr); {error, _Reason} = Error -> Error end. output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr) -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr, _Offset = 0). output_sections(_Sections = [], _GlobalMap, _FileMap, _FP, SegOffset, _SegVAddr, Offset) -> {ok, SegOffset + Offset}; output_sections([Section | Sections], GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) -> case output_section(Section, GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) of {ok, NewOffset} -> output_sections(Sections, GlobalMap, FileMap, FP, SegOffset, SegVAddr, NewOffset); {error, _Reason} = Error -> Error end. output_section(Section, GlobalMap, FileMap, FP, SegOffset, SegVAddr, Offset) -> #section{shdr = Shdr, frags = Frags} = Section, #elf36_Shdr{sh_offset = ShOffset} = Shdr, case output_padding(ShOffset - Offset, FP) of ok -> output_frags(Frags, GlobalMap, FileMap, FP, SegOffset + ShOffset, SegVAddr + ShOffset); {error, _Reason} = Error -> Error end. output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr) -> output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr, _Offset = 0). output_frags(_Frags = [], _GlobalMap, _FileMap, _FP, SectOffset, _SectVAddr, Offset) -> {ok, SectOffset + Offset}; output_frags([Frag | Frags], GlobalMap, FileMap, FP, SectOffset, SectVAddr, Offset) -> case output_frag(Frag, GlobalMap, FileMap, FP, SectOffset, SectVAddr, Offset) of {ok, NewOffset} -> output_frags(Frags, GlobalMap, FileMap, FP, SectOffset, SectVAddr, NewOffset); {error, _Reason} = Error -> Error end. output_frag(Frag, GlobalMap, FileMap, FP, _SectOffset, _SectVAddr, Offset) -> case input_init(Frag) of {ok, {Input, Relocs}} -> Output = output_init(Frag, GlobalMap, FileMap, FP, Relocs), case output_frag(Input, Output) of {ok, FragOffset} -> {ok, Offset + FragOffset}; {error, _Reason} = Error -> Error end; {error, _Reason} = Error -> Error end. output_frag(Input, Output) -> case input(Input) of {ok, {Byte, NewInput}} -> case output(Output, Byte) of {ok, {Pushback, NewOutput}} -> output_frag(input_pushback(NewInput, Pushback), NewOutput); {ok, NewOutput} -> output_frag(NewInput, NewOutput); {error, _Reason} = Error -> Error end; eof -> input_fini(Input), output_fini(Output); {error, _Reason} = Error -> Error end. -record(frag_input, {fp, file, sh_name, size, pushback}). input_init(Frag) -> #sectfrag{file = File, shdr = Shdr, relocs = RelocShdr} = Frag, case pdp10_stdio:fopen(File, [raw, read]) of {ok, FP} -> case input_relocs(FP, RelocShdr) of {ok, Relocs} -> #elf36_Shdr{sh_offset = ShOffset, sh_size = ShSize, sh_name = ShName} = Shdr, case pdp10_stdio:fseek(FP, {bof, ShOffset}) of ok -> Input = #frag_input{fp = FP, file = File, sh_name = ShName, size = ShSize, pushback = []}, {ok, {Input, Relocs}}; {error, _Reason} = Error -> Error end; {error, _Reason} = Error -> Error end; {error, Reason} -> {error, {?MODULE, {cannot_open, File, Reason}}} end. input_relocs(_FP, false) -> {ok, []}; input_relocs(FP, Shdr) -> pdp10_elf36:read_RelaTab(FP, Shdr). input_fini(#frag_input{fp = FP}) -> pdp10_stdio:fclose(FP). input_pushback(#frag_input{pushback = Pushback} = Input, Buffer) -> Input#frag_input{pushback = Buffer ++ Pushback}. input(#frag_input{pushback = [Byte | Pushback]} = Input) -> {ok, {Byte, Input#frag_input{pushback = Pushback}}}; input(#frag_input{size = 0}) -> eof; input(#frag_input{fp = FP, size = Size} = Input) when Size > 0 -> case pdp10_stdio:fgetc(FP) of {ok, Byte} -> {ok, {Byte, Input#frag_input{size = Size - 1}}}; eof -> #frag_input{file = File, sh_name = ShName} = Input, {error, {?MODULE, {premature_eof, File, ShName}}}; {error, _Reason} = Error -> Error end. -record(frag_output, { file , sh_name , globalmap , filemap , fp , relocs , frag_offset , buffer }). output_init(Frag, GlobalMap, FileMap, FP, Relocs) -> #sectfrag{file = File, shdr = #elf36_Shdr{sh_name = ShName}} = Frag, SortedRelocs = lists:keysort(#elf36_Rela.r_offset, Relocs), #frag_output{file = File, sh_name = ShName, globalmap = GlobalMap, filemap = FileMap, fp = FP, relocs = SortedRelocs, frag_offset = 0, buffer = []}. output_fini(#frag_output{relocs = [], frag_offset = FragOffset}) -> {ok, FragOffset}; output_fini(#frag_output{file = File, sh_name = ShName}) -> {error, {?MODULE, {unresolved_relocs, File, ShName}}}. output(Output, Byte) -> case Output#frag_output.relocs of [] -> output_directly(Output, Byte); [#elf36_Rela{r_offset = RelOffset} = Rela | _] -> FragOffset = Output#frag_output.frag_offset, case FragOffset < RelOffset of true -> output_directly(Output, Byte); false -> NewBuffer = [Byte | Output#frag_output.buffer], NewFragOffset = FragOffset + 1, NewOutput = Output#frag_output{frag_offset = NewFragOffset, buffer = NewBuffer}, case length(NewBuffer) =:= sizeof_reloc(Rela) of true -> output_reloc(NewOutput); false -> {ok, NewOutput} end end end. output_reloc(Output) -> #frag_output{ file = File , filemap = FileMap , globalmap = GlobalMap , relocs = [Reloc | Relocs] , buffer = Buffer0 , frag_offset = FragOffset } = Output, #elf36_Rela{ r_info = Info , r_addend = Addend } = Reloc, Type = ?ELF36_R_TYPE(Info), SymNdx = ?ELF36_R_SYM(Info), case symbol_value(SymNdx, File, FileMap, GlobalMap) of {ok, SymbolValue} -> Buffer1 = lists:reverse(Buffer0), Length = length(Buffer1), Word = buffer_word(Length, Buffer1), {ok, NewWord} = apply_reloc(Type, SymbolValue + Addend, Word), Pushback = word_buffer(Length, NewWord), {ok, {Pushback, Output#frag_output{relocs = Relocs, buffer = [], frag_offset = FragOffset - Length}}}; {error, _Reason} = Error -> Error end. symbol_value(SymNdx, File, FileMap, GlobalMap) -> LocalMap = maps:get(File, FileMap), case maps:get(SymNdx, LocalMap) of Value when is_integer(Value) -> {ok, Value}; Symbol when is_list(Symbol) -> case maps:get(Symbol, GlobalMap, false) of Value when is_integer(Value) -> {ok, Value}; false -> {error, {?MODULE, {undefined_symbol, Symbol}}} end end. buffer_word(4, Buffer) -> pdp10_extint:uint36_from_ext(Buffer); buffer_word(2, Buffer) -> pdp10_extint:uint18_from_ext(Buffer); buffer_word(1, [Byte]) -> Byte. word_buffer(4, Word) -> pdp10_extint:uint36_to_ext(Word); word_buffer(2, Word) -> pdp10_extint:uint18_to_ext(Word); word_buffer(1, Byte) -> [Byte]. sizeof_reloc(#elf36_Rela{r_info = Info}) -> case ?ELF36_R_TYPE(Info) of ?R_PDP10_IFIW -> 4; ?R_PDP10_EFIW -> 4; ?R_PDP10_LOCAL_W -> 2; ?R_PDP10_LOCAL_B -> 4; ?R_PDP10_LOCAL_H -> 4; ?R_PDP10_GLOBAL_B -> 4; ?R_PDP10_GLOBAL_H -> 4; ?R_PDP10_LITERAL_W -> 4; ?R_PDP10_LITERAL_H -> 2; ?R_PDP10_LITERAL_B -> 1 end. apply_reloc(Type, Value, Word) -> case Type of ?R_PDP10_IFIW -> Address = Value div 4, {ok, (Word band bnot ?PDP10_UINT18_MAX) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_EFIW -> Address = Value div 4, clear bit 0 , preserve bits 1 to 5 {ok, (Word band Mask) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_LOCAL_W -> Address = Value div 4, TODO : handle non - zero sections {ok, Address band ?PDP10_UINT18_MAX}; ?R_PDP10_LOCAL_B -> Address = Value div 4, TODO : handle non - zero sections P \in { 0 , 9 , 18 , 27 } S = 9, {ok, (P bsl 30) bor (S bsl 24) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_LOCAL_H -> Address = Value div 4, TODO : handle non - zero sections P \in { 0 , 18 } S = 18, {ok, (P bsl 30) bor (S bsl 24) bor (Address band ?PDP10_UINT18_MAX)}; ?R_PDP10_GLOBAL_B -> Address = Value div 4, PS = 8#70 + (Value band 3), {ok, (PS bsl 30) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_GLOBAL_H -> Address = Value div 4, PS = 8#75 + ((Value band 2) bsr 1), {ok, (PS bsl 30) bor (Address band ((1 bsl 30) - 1))}; ?R_PDP10_LITERAL_W -> {ok, Value}; ?R_PDP10_LITERAL_H -> {ok, Value}; ?R_PDP10_LITERAL_B -> {ok, Value} end. output_directly(Output, Byte) -> #frag_output{fp = FP, frag_offset = FragOffset} = Output, case pdp10_stdio:fputc(Byte, FP) of ok -> {ok, Output#frag_output{frag_offset = FragOffset + 1}}; {error, _Reason} = Error -> Error end. -spec format_error(term()) -> io_lib:chars(). format_error(Reason) -> case Reason of {cannot_open, File, Reason0} -> io_lib:format("cannot open ~s: ~s", [File, error:format(Reason0)]); {premature_eof, File, ShName} -> io_lib:format("premature eof: ~s:~s", [File, ShName]); {undefined_symbol, Symbol} -> io_lib:format("undefined symbol: ~s", [Symbol]); {unresolved_relocs, File, ShName} -> io_lib:format("unresolved relocations: ~s:~s", [File, ShName]) end.
141701154b799a4b10e6ec05f5c2299f42103ba1383e50495f5092f3ca877ce4
racket/web-server
iteration-9s.rkt
#lang web-server (require "model-2.rkt") ;; start: request -> doesn't return ;; Consumes a request and produces a page that displays ;; all of the web content. (define (start request) (render-blog-page (initialize-blog! (build-path (current-directory) "the-blog-data.db")) request)) ;; render-blog-page: blog request -> doesn't return ;; Sends an HTML page of the content of the ;; blog. (define (render-blog-page a-blog request) (define (response-generator embed/url) (response/xexpr `(html (head (title "My Blog")) (body (h1 "My Blog") ,(render-posts a-blog embed/url) (form ((action ,(embed/url insert-post-handler))) (input ((name "title"))) (input ((name "body"))) (input ((type "submit")))))))) (define (insert-post-handler request) (define bindings (request-bindings/raw request)) (blog-insert-post! a-blog (bytes->string/utf-8 (bindings-assq #"title" bindings)) (bytes->string/utf-8 (bindings-assq #"body" bindings))) (render-blog-page a-blog (redirect/get))) (send/suspend/dispatch response-generator)) ;; render-post-detail-page: post request -> doesn't return ;; Consumes a post and produces a detail page of the post. ;; The user will be able to either insert new comments ;; or go back to render-blog-page. (define (render-post-detail-page a-blog a-post request) (define (response-generator embed/url) (response/xexpr `(html (head (title "Post Details")) (body (h1 "Post Details") (h2 ,(post-title a-post)) (p ,(post-body a-post)) ,(render-as-itemized-list (post-comments a-post)) (form ((action ,(embed/url insert-comment-handler))) (input ((name "comment"))) (input ((type "submit")))) (a ((href ,(embed/url back-handler))) "Back to the blog"))))) (define (parse-comment bindings) (bytes->string/utf-8 (bindings-assq #"comment" bindings))) (define (insert-comment-handler request) (render-confirm-add-comment-page a-blog (parse-comment (request-bindings/raw request)) a-post request)) (define (back-handler request) (render-blog-page a-blog request)) (send/suspend/dispatch response-generator)) ;; render-confirm-add-comment-page : ;; blog comment post request -> doesn't return ;; Consumes a comment that we intend to add to a post, as well ;; as the request. If the user follows through, adds a comment ;; and goes back to the display page. Otherwise, goes back to ;; the detail page of the post. (define (render-confirm-add-comment-page a-blog a-comment a-post request) (define (response-generator embed/url) (response/xexpr `(html (head (title "Add a Comment")) (body (h1 "Add a Comment") "The comment: " (div (p ,a-comment)) "will be added to " (div ,(post-title a-post)) (p (a ((href ,(embed/url yes-handler))) "Yes, add the comment.")) (p (a ((href ,(embed/url cancel-handler))) "No, I changed my mind!")))))) (define (yes-handler request) (post-insert-comment! a-blog a-post a-comment) (render-post-detail-page a-blog a-post (redirect/get))) (define (cancel-handler request) (render-post-detail-page a-blog a-post request)) (send/suspend/dispatch response-generator)) ;; render-post: post (handler -> string) -> xexpr ;; Consumes a post, produces an xexpr fragment of the post. ;; The fragment contains a link to show a detailed view of the post. (define (render-post a-blog a-post embed/url) (define (view-post-handler request) (render-post-detail-page a-blog a-post request)) `(div ((class "post")) (a ((href ,(embed/url view-post-handler))) ,(post-title a-post)) (p ,(post-body a-post)) (div ,(number->string (length (post-comments a-post))) " comment(s)"))) ;; render-posts: blog (handler -> string) -> xexpr ;; Consumes a embed/url, produces an xexpr fragment ;; of all its posts. (define (render-posts a-blog embed/url) (define (render-post/embed/url a-post) (render-post a-blog a-post embed/url)) `(div ((class "posts")) ,@(map render-post/embed/url (blog-posts a-blog)))) render - as - itemized - list : ( ) - > xexpr ;; Consumes a list of items, and produces a rendering as ;; an unorderered list. (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr ;; Consumes an xexpr, and produces a rendering ;; as a list item. (define (render-as-item a-fragment) `(li ,a-fragment))
null
https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-doc/web-server/scribblings/tutorial/examples/iteration-9s.rkt
racket
start: request -> doesn't return Consumes a request and produces a page that displays all of the web content. render-blog-page: blog request -> doesn't return Sends an HTML page of the content of the blog. render-post-detail-page: post request -> doesn't return Consumes a post and produces a detail page of the post. The user will be able to either insert new comments or go back to render-blog-page. render-confirm-add-comment-page : blog comment post request -> doesn't return Consumes a comment that we intend to add to a post, as well as the request. If the user follows through, adds a comment and goes back to the display page. Otherwise, goes back to the detail page of the post. render-post: post (handler -> string) -> xexpr Consumes a post, produces an xexpr fragment of the post. The fragment contains a link to show a detailed view of the post. render-posts: blog (handler -> string) -> xexpr Consumes a embed/url, produces an xexpr fragment of all its posts. Consumes a list of items, and produces a rendering as an unorderered list. Consumes an xexpr, and produces a rendering as a list item.
#lang web-server (require "model-2.rkt") (define (start request) (render-blog-page (initialize-blog! (build-path (current-directory) "the-blog-data.db")) request)) (define (render-blog-page a-blog request) (define (response-generator embed/url) (response/xexpr `(html (head (title "My Blog")) (body (h1 "My Blog") ,(render-posts a-blog embed/url) (form ((action ,(embed/url insert-post-handler))) (input ((name "title"))) (input ((name "body"))) (input ((type "submit")))))))) (define (insert-post-handler request) (define bindings (request-bindings/raw request)) (blog-insert-post! a-blog (bytes->string/utf-8 (bindings-assq #"title" bindings)) (bytes->string/utf-8 (bindings-assq #"body" bindings))) (render-blog-page a-blog (redirect/get))) (send/suspend/dispatch response-generator)) (define (render-post-detail-page a-blog a-post request) (define (response-generator embed/url) (response/xexpr `(html (head (title "Post Details")) (body (h1 "Post Details") (h2 ,(post-title a-post)) (p ,(post-body a-post)) ,(render-as-itemized-list (post-comments a-post)) (form ((action ,(embed/url insert-comment-handler))) (input ((name "comment"))) (input ((type "submit")))) (a ((href ,(embed/url back-handler))) "Back to the blog"))))) (define (parse-comment bindings) (bytes->string/utf-8 (bindings-assq #"comment" bindings))) (define (insert-comment-handler request) (render-confirm-add-comment-page a-blog (parse-comment (request-bindings/raw request)) a-post request)) (define (back-handler request) (render-blog-page a-blog request)) (send/suspend/dispatch response-generator)) (define (render-confirm-add-comment-page a-blog a-comment a-post request) (define (response-generator embed/url) (response/xexpr `(html (head (title "Add a Comment")) (body (h1 "Add a Comment") "The comment: " (div (p ,a-comment)) "will be added to " (div ,(post-title a-post)) (p (a ((href ,(embed/url yes-handler))) "Yes, add the comment.")) (p (a ((href ,(embed/url cancel-handler))) "No, I changed my mind!")))))) (define (yes-handler request) (post-insert-comment! a-blog a-post a-comment) (render-post-detail-page a-blog a-post (redirect/get))) (define (cancel-handler request) (render-post-detail-page a-blog a-post request)) (send/suspend/dispatch response-generator)) (define (render-post a-blog a-post embed/url) (define (view-post-handler request) (render-post-detail-page a-blog a-post request)) `(div ((class "post")) (a ((href ,(embed/url view-post-handler))) ,(post-title a-post)) (p ,(post-body a-post)) (div ,(number->string (length (post-comments a-post))) " comment(s)"))) (define (render-posts a-blog embed/url) (define (render-post/embed/url a-post) (render-post a-blog a-post embed/url)) `(div ((class "posts")) ,@(map render-post/embed/url (blog-posts a-blog)))) render - as - itemized - list : ( ) - > xexpr (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr (define (render-as-item a-fragment) `(li ,a-fragment))
c61b45293cad200000d82a60865cfc817b79d5aadc1301836f9c90160aeb1269
freizl/dive-into-haskell
Contact.hs
# LANGUAGE TemplateHaskell , QuasiQuotes , OverloadedStrings # module Handler.Contact where import Helloyesod getContactR :: Handler RepHtml getContactR = do defaultLayout $ do setTitle "Contact" addWidget $(widgetFile "contact")
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/web/yesod/helloyesod/Handler/Contact.hs
haskell
# LANGUAGE TemplateHaskell , QuasiQuotes , OverloadedStrings # module Handler.Contact where import Helloyesod getContactR :: Handler RepHtml getContactR = do defaultLayout $ do setTitle "Contact" addWidget $(widgetFile "contact")
93fbc7d45051adf8cef0c1fc7e808d0150e2343925540b83082795b293f635d8
GaloisInc/ivory
Bits.hs
# LANGUAGE TypeOperators # # LANGUAGE DataKinds # module Bits (runBits, cmodule) where import Ivory.Compile.C.CmdlineFrontend import Ivory.Language hiding (setBit, clearBit, runBits) import MonadLib.Monads (runState, sets) runBits :: IO () runBits = runCompiler [cmodule] [] initialOpts {outDir = Nothing} cmodule :: Module cmodule = package "Bits" $ do incl test1 incl test2 incl test3 incl test4 incl test5 incl test6 test1 :: Def ('[Uint8, Uint16, Uint32, Uint64] ':-> Uint64) test1 = proc "test1" $ \u8 u16 u32 u64 -> body $ do a <- assign $ u8 .& 0xFF b <- assign $ u16 .& 0xFF00 c <- assign $ u32 .& 0xFF0000 d <- assign $ u64 .& 0xFF000000 ret $ (safeCast a) .| (safeCast b) .| (safeCast c) .| d | Convert an array of four 8 - bit integers into a 32 - bit integer . test2 :: Def ('[Ref s ('Array 4 ('Stored Uint8))] ':-> Uint32) test2 = proc "test2" $ \arr -> body $ do a <- deref (arr ! 0) b <- deref (arr ! 1) c <- deref (arr ! 2) d <- deref (arr ! 3) ret $ ((safeCast a) `iShiftL` 24) .| ((safeCast b) `iShiftL` 16) .| ((safeCast c) `iShiftL` 8) .| ((safeCast d) `iShiftL` 0) -- | Example of using "extractByte" with a state monad. extractUint32 :: Uint32 -> (Uint8, Uint8, Uint8, Uint8) extractUint32 x = fst $ runState x $ do a <- sets extractByte b <- sets extractByte c <- sets extractByte d <- sets extractByte return (a, b, c, d) | Convert a 32 - bit integer to an array of 8 - bit integers . test3 :: Def ('[Uint32, Ref s ('Array 4 ('Stored Uint8))] ':-> ()) test3 = proc "test3" $ \n arr -> body $ do let (a, b, c, d) = extractUint32 n store (arr ! 0) d store (arr ! 1) c store (arr ! 2) b store (arr ! 3) a setBit :: (IvoryBits a, IvoryStore a) => (Ref s ('Stored a)) -> Int -> Ivory eff () setBit ref bit = do val <- deref ref store ref (val .| (1 `iShiftL` (fromIntegral bit))) clearBit :: (IvoryBits a, IvoryStore a) => (Ref s ('Stored a)) -> Int -> Ivory eff () clearBit ref bit = do val <- deref ref store ref (val .& (iComplement (1 `iShiftL` (fromIntegral bit)))) test4 :: Def ('[] ':-> Uint32) test4 = proc "test4" $ body $ do n <- local (ival 0) setBit n 1 setBit n 3 setBit n 5 setBit n 8 clearBit n 3 ret =<< deref n test5 :: Def ('[Sint8] ':-> Uint8) test5 = proc "test5" $ \s -> body $ ret (twosComplementRep s) test6 :: Def ('[Uint8] ':-> Sint8) test6 = proc "test6" $ \s -> body $ ret (twosComplementCast s)
null
https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-examples/examples/Bits.hs
haskell
| Example of using "extractByte" with a state monad.
# LANGUAGE TypeOperators # # LANGUAGE DataKinds # module Bits (runBits, cmodule) where import Ivory.Compile.C.CmdlineFrontend import Ivory.Language hiding (setBit, clearBit, runBits) import MonadLib.Monads (runState, sets) runBits :: IO () runBits = runCompiler [cmodule] [] initialOpts {outDir = Nothing} cmodule :: Module cmodule = package "Bits" $ do incl test1 incl test2 incl test3 incl test4 incl test5 incl test6 test1 :: Def ('[Uint8, Uint16, Uint32, Uint64] ':-> Uint64) test1 = proc "test1" $ \u8 u16 u32 u64 -> body $ do a <- assign $ u8 .& 0xFF b <- assign $ u16 .& 0xFF00 c <- assign $ u32 .& 0xFF0000 d <- assign $ u64 .& 0xFF000000 ret $ (safeCast a) .| (safeCast b) .| (safeCast c) .| d | Convert an array of four 8 - bit integers into a 32 - bit integer . test2 :: Def ('[Ref s ('Array 4 ('Stored Uint8))] ':-> Uint32) test2 = proc "test2" $ \arr -> body $ do a <- deref (arr ! 0) b <- deref (arr ! 1) c <- deref (arr ! 2) d <- deref (arr ! 3) ret $ ((safeCast a) `iShiftL` 24) .| ((safeCast b) `iShiftL` 16) .| ((safeCast c) `iShiftL` 8) .| ((safeCast d) `iShiftL` 0) extractUint32 :: Uint32 -> (Uint8, Uint8, Uint8, Uint8) extractUint32 x = fst $ runState x $ do a <- sets extractByte b <- sets extractByte c <- sets extractByte d <- sets extractByte return (a, b, c, d) | Convert a 32 - bit integer to an array of 8 - bit integers . test3 :: Def ('[Uint32, Ref s ('Array 4 ('Stored Uint8))] ':-> ()) test3 = proc "test3" $ \n arr -> body $ do let (a, b, c, d) = extractUint32 n store (arr ! 0) d store (arr ! 1) c store (arr ! 2) b store (arr ! 3) a setBit :: (IvoryBits a, IvoryStore a) => (Ref s ('Stored a)) -> Int -> Ivory eff () setBit ref bit = do val <- deref ref store ref (val .| (1 `iShiftL` (fromIntegral bit))) clearBit :: (IvoryBits a, IvoryStore a) => (Ref s ('Stored a)) -> Int -> Ivory eff () clearBit ref bit = do val <- deref ref store ref (val .& (iComplement (1 `iShiftL` (fromIntegral bit)))) test4 :: Def ('[] ':-> Uint32) test4 = proc "test4" $ body $ do n <- local (ival 0) setBit n 1 setBit n 3 setBit n 5 setBit n 8 clearBit n 3 ret =<< deref n test5 :: Def ('[Sint8] ':-> Uint8) test5 = proc "test5" $ \s -> body $ ret (twosComplementRep s) test6 :: Def ('[Uint8] ':-> Sint8) test6 = proc "test6" $ \s -> body $ ret (twosComplementCast s)
6cac88b15ece43a1bddd92da366e53585af8204acf8506af83b930a7039b1a67
well-typed-lightbulbs/ocaml-esp32
static.ml
let f = Abstract.print
null
https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/lib-dynlink-pr4229/static.ml
ocaml
let f = Abstract.print
799480b9da69678a7f091a627befde7161e4ae8e47cd7ca246b83cd40c381342
utahstreetlabs/risingtide
set.clj
(ns risingtide.feed.set (:require [risingtide [dedupe :refer [dedupe]] [key :as key] [active-users :refer [active-users]]] [risingtide.feed [expiration :refer [expire]] [filters :refer [for-everything-feed?]] [persist :refer [encode-feed write-feed! load-feed delete-feeds! initialize-digest-feed]]] [risingtide.model [feed :refer [add remove-listing]] [timestamps :refer [timestamp]]] [risingtide.model.feed.digest :refer [new-digest-feed]])) (defn add! [redii feed-set-atom user-id story] (if-let [feed-atom (@feed-set-atom user-id)] (swap! feed-atom add story) (swap! feed-set-atom #(assoc % user-id (atom (initialize-digest-feed redii (key/user-feed user-id) story)))))) (defn remove! [redii feed-set-atom user-id listing-id] (if-let [feed-atom (@feed-set-atom user-id)] (swap! feed-atom remove-listing listing-id) (swap! feed-set-atom #(assoc % user-id (atom (remove-listing (initialize-digest-feed redii (key/user-feed user-id)) listing-id)))))) (defn expire-feed! [feed-atom] (swap! feed-atom #(apply new-digest-feed (expire %)))) (defn expire-inactive! [redii feed-set] (let [actives (active-users redii) active-feed-users (keys @feed-set)] (swap! feed-set #(select-keys % actives)) (delete-feeds! redii (clojure.set/difference (set active-feed-users) (set actives))))) (defn expire! [redii feed-set] (expire-inactive! redii feed-set) (doall (map expire-feed! (vals @feed-set))))
null
https://raw.githubusercontent.com/utahstreetlabs/risingtide/bc5b798396679739469b1bd8ee1b03db76178cde/src/risingtide/feed/set.clj
clojure
(ns risingtide.feed.set (:require [risingtide [dedupe :refer [dedupe]] [key :as key] [active-users :refer [active-users]]] [risingtide.feed [expiration :refer [expire]] [filters :refer [for-everything-feed?]] [persist :refer [encode-feed write-feed! load-feed delete-feeds! initialize-digest-feed]]] [risingtide.model [feed :refer [add remove-listing]] [timestamps :refer [timestamp]]] [risingtide.model.feed.digest :refer [new-digest-feed]])) (defn add! [redii feed-set-atom user-id story] (if-let [feed-atom (@feed-set-atom user-id)] (swap! feed-atom add story) (swap! feed-set-atom #(assoc % user-id (atom (initialize-digest-feed redii (key/user-feed user-id) story)))))) (defn remove! [redii feed-set-atom user-id listing-id] (if-let [feed-atom (@feed-set-atom user-id)] (swap! feed-atom remove-listing listing-id) (swap! feed-set-atom #(assoc % user-id (atom (remove-listing (initialize-digest-feed redii (key/user-feed user-id)) listing-id)))))) (defn expire-feed! [feed-atom] (swap! feed-atom #(apply new-digest-feed (expire %)))) (defn expire-inactive! [redii feed-set] (let [actives (active-users redii) active-feed-users (keys @feed-set)] (swap! feed-set #(select-keys % actives)) (delete-feeds! redii (clojure.set/difference (set active-feed-users) (set actives))))) (defn expire! [redii feed-set] (expire-inactive! redii feed-set) (doall (map expire-feed! (vals @feed-set))))
73d5b3f5a439ff9fb99960ea4e985c20e3692cf6be7300842de23daeb70885c4
biocom-uib/vpf-tools
Excepts.hs
{-# language DeriveAnyClass #-} # language DeriveGeneric # # language EmptyCase # # language QuantifiedConstraints # {-# language Strict #-} # language TemplateHaskell # {-# language UndecidableInstances #-} module Control.Carrier.Error.Excepts ( module Control.Effect.Error , Errors(..) , MemberError , ExceptsT(..) , runExceptsT , runPureExceptsT , runLastExceptT , handleErrorCase , ThrowErrors, throwErrors ) where import GHC.Generics (Generic) import Data.Functor.Identity import Data.Kind (Type) import Data.Store (Store) import Control.Algebra import Control.Algebra.Helpers (relayAlgebraUnwrap) import Control.Carrier.MTL.TH (deriveMonadTrans) import Control.Effect.Error import Control.Monad.Trans as MT import Control.Monad.Trans.Except as MT data family Errors (es :: [Type]) data instance Errors '[] deriving Generic deriving instance Store (Errors '[]) data instance Errors (e ': es) = Error e | InjError (Errors es) deriving Generic deriving instance (Store e, Store (Errors es)) => Store (Errors (e ': es)) class MemberError e es where injE :: e -> Errors es prjE :: Errors es -> Maybe e # overlappable # injE = Error prjE (Error e) = Just e prjE _ = Nothing # incoherent # injE = InjError . injE prjE (Error _) = Nothing prjE (InjError es) = prjE es newtype ExceptsT es m a = ExceptsT { unExceptsT :: MT.ExceptT (Errors es) m a } deriveMonadTrans ''ExceptsT runExceptsT :: ExceptsT es m a -> m (Either (Errors es) a) runExceptsT (ExceptsT m) = MT.runExceptT m runPureExceptsT :: Functor m => ExceptsT '[] m a -> m a runPureExceptsT = fmap noLeft . runExceptsT where noLeft :: Either (Errors '[]) a -> a noLeft (Left e) = case e of noLeft (Right a) = a runLastExceptT :: Functor m => ExceptsT '[e] m a -> m (Either e a) runLastExceptT (ExceptsT m) = MT.runExceptT (MT.withExceptT single m) where single :: Errors '[e] -> e single (Error e) = e class Algebra sig m => ThrowErrors es sig m | m -> sig where throwErrors :: Errors es -> m a instance Algebra sig m => ThrowErrors '[] sig m where throwErrors e = case e of instance (Has (Throw e) sig m, ThrowErrors es sig m) => ThrowErrors (e ': es) sig m where throwErrors (Error e) = throwError e throwErrors (InjError e) = throwErrors e handleErrorCase :: forall e es m a. Monad m => (e -> ExceptsT es m a) -> ExceptsT (e ': es) m a -> ExceptsT es m a handleErrorCase h m = ExceptsT (MT.catchE (unExceptsT m) (\es -> handleE es h)) where handleE :: Errors (e ': es) -> (e -> ExceptsT es m a) -> MT.ExceptT (Errors es) m a handleE (Error e) h = unExceptsT (h e) handleE (InjError es) _ = MT.throwE es interpretExceptsT :: (Monad m, MemberError e es) => Error e (ExceptsT es m) a -> ExceptsT es m a interpretExceptsT (L (Throw e)) = ExceptsT (MT.throwE (injE e)) interpretExceptsT (R (Catch mb emb bmk)) = ExceptsT $ MT.catchE (unExceptsT mb) (\es -> handleE es emb) >>= unExceptsT . bmk where handleE es h = case prjE es of Just e -> unExceptsT (h e) Nothing -> MT.throwE es class ErrorsAlgebra sig es where algErrs :: Monad m => sig (ExceptsT es m) a -> ExceptsT es m a instance MemberError e es => ErrorsAlgebra (Error e) es where algErrs = interpretExceptsT {-# inline algErrs #-} instance (ErrorsAlgebra sig es, MemberError e es) => ErrorsAlgebra (Error e :+: sig) es where algErrs (L e) = interpretExceptsT e algErrs (R other) = algErrs other {-# inline algErrs #-} instance Algebra sig m => Algebra sig (ExceptsT '[] m) where alg = MT.lift . handleIdentity runPureExceptsT # inline alg # instance ( Algebra sig m , Threads (Either (Errors '[e])) sig ) => Algebra (Error e :+: sig) (ExceptsT '[e] m) where alg (L e) = algErrs e alg (R other) = relayAlgebraUnwrap ExceptsT other # inline alg # instance ( Algebra sig m , Algebra (errsig :+: sig) (ExceptsT (e2 ': es) m) -- only required for the functional dependency , ErrorsAlgebra errsig (e1 ': e2 ': es) , Threads Identity errsig , Threads (Either (Errors (e1 ': e2 ': es))) sig ) => Algebra ((Error e1 :+: errsig) :+: sig) (ExceptsT (e1 ': e2 ': es) m) where alg (L e) = algErrs e alg (R other) = relayAlgebraUnwrap ExceptsT other # inline alg #
null
https://raw.githubusercontent.com/biocom-uib/vpf-tools/dd88a543f28eb339cf0dcb89f34479c84b3a8056/src/Control/Carrier/Error/Excepts.hs
haskell
# language DeriveAnyClass # # language Strict # # language UndecidableInstances # # inline algErrs # # inline algErrs # only required for the functional dependency
# language DeriveGeneric # # language EmptyCase # # language QuantifiedConstraints # # language TemplateHaskell # module Control.Carrier.Error.Excepts ( module Control.Effect.Error , Errors(..) , MemberError , ExceptsT(..) , runExceptsT , runPureExceptsT , runLastExceptT , handleErrorCase , ThrowErrors, throwErrors ) where import GHC.Generics (Generic) import Data.Functor.Identity import Data.Kind (Type) import Data.Store (Store) import Control.Algebra import Control.Algebra.Helpers (relayAlgebraUnwrap) import Control.Carrier.MTL.TH (deriveMonadTrans) import Control.Effect.Error import Control.Monad.Trans as MT import Control.Monad.Trans.Except as MT data family Errors (es :: [Type]) data instance Errors '[] deriving Generic deriving instance Store (Errors '[]) data instance Errors (e ': es) = Error e | InjError (Errors es) deriving Generic deriving instance (Store e, Store (Errors es)) => Store (Errors (e ': es)) class MemberError e es where injE :: e -> Errors es prjE :: Errors es -> Maybe e # overlappable # injE = Error prjE (Error e) = Just e prjE _ = Nothing # incoherent # injE = InjError . injE prjE (Error _) = Nothing prjE (InjError es) = prjE es newtype ExceptsT es m a = ExceptsT { unExceptsT :: MT.ExceptT (Errors es) m a } deriveMonadTrans ''ExceptsT runExceptsT :: ExceptsT es m a -> m (Either (Errors es) a) runExceptsT (ExceptsT m) = MT.runExceptT m runPureExceptsT :: Functor m => ExceptsT '[] m a -> m a runPureExceptsT = fmap noLeft . runExceptsT where noLeft :: Either (Errors '[]) a -> a noLeft (Left e) = case e of noLeft (Right a) = a runLastExceptT :: Functor m => ExceptsT '[e] m a -> m (Either e a) runLastExceptT (ExceptsT m) = MT.runExceptT (MT.withExceptT single m) where single :: Errors '[e] -> e single (Error e) = e class Algebra sig m => ThrowErrors es sig m | m -> sig where throwErrors :: Errors es -> m a instance Algebra sig m => ThrowErrors '[] sig m where throwErrors e = case e of instance (Has (Throw e) sig m, ThrowErrors es sig m) => ThrowErrors (e ': es) sig m where throwErrors (Error e) = throwError e throwErrors (InjError e) = throwErrors e handleErrorCase :: forall e es m a. Monad m => (e -> ExceptsT es m a) -> ExceptsT (e ': es) m a -> ExceptsT es m a handleErrorCase h m = ExceptsT (MT.catchE (unExceptsT m) (\es -> handleE es h)) where handleE :: Errors (e ': es) -> (e -> ExceptsT es m a) -> MT.ExceptT (Errors es) m a handleE (Error e) h = unExceptsT (h e) handleE (InjError es) _ = MT.throwE es interpretExceptsT :: (Monad m, MemberError e es) => Error e (ExceptsT es m) a -> ExceptsT es m a interpretExceptsT (L (Throw e)) = ExceptsT (MT.throwE (injE e)) interpretExceptsT (R (Catch mb emb bmk)) = ExceptsT $ MT.catchE (unExceptsT mb) (\es -> handleE es emb) >>= unExceptsT . bmk where handleE es h = case prjE es of Just e -> unExceptsT (h e) Nothing -> MT.throwE es class ErrorsAlgebra sig es where algErrs :: Monad m => sig (ExceptsT es m) a -> ExceptsT es m a instance MemberError e es => ErrorsAlgebra (Error e) es where algErrs = interpretExceptsT instance (ErrorsAlgebra sig es, MemberError e es) => ErrorsAlgebra (Error e :+: sig) es where algErrs (L e) = interpretExceptsT e algErrs (R other) = algErrs other instance Algebra sig m => Algebra sig (ExceptsT '[] m) where alg = MT.lift . handleIdentity runPureExceptsT # inline alg # instance ( Algebra sig m , Threads (Either (Errors '[e])) sig ) => Algebra (Error e :+: sig) (ExceptsT '[e] m) where alg (L e) = algErrs e alg (R other) = relayAlgebraUnwrap ExceptsT other # inline alg # instance ( Algebra sig m , ErrorsAlgebra errsig (e1 ': e2 ': es) , Threads Identity errsig , Threads (Either (Errors (e1 ': e2 ': es))) sig ) => Algebra ((Error e1 :+: errsig) :+: sig) (ExceptsT (e1 ': e2 ': es) m) where alg (L e) = algErrs e alg (R other) = relayAlgebraUnwrap ExceptsT other # inline alg #
fdaa08dfcca62c490e1f1e03ffa3f1f827a66a23ec18d89c9e38582b2f71268e
bennn/dissertation
tree.rkt
#lang typed/racket (provide tree-state lplaced% generate-tree tree-next hand-out? HandOut ) (require require-typed-check "../base/types.rkt" "board-adapted.rkt" "state-adapted.rkt" ) (require/typed/check "basics.rkt" (shares-available? (-> Shares (Listof Hotel) Boolean)) (shares-order? (-> Any Boolean)) ) ;; ============================================================================= (define-type Tree<%> (Class (to-state (-> State)) (next (-> Tile (Option Hotel) Decisions (Listof Hotel) (-> (Listof Tile) Tile) (Values (Option Tile) (Instance ATree%)))) (founding (-> Natural (Listof (Listof Hotel)) Natural)) ;; Precondition: share-order (traversal (-> Natural (Listof (Listof Hotel)) (-> (Instance Placed%) Natural) Natural)) (lookup-tile (-> (-> (Listof Tile) Tile) (Listof HandOut) (Values (Option Tile) (Instance ATree%)))) (merging (-> Natural (Listof (Listof Hotel)) Natural)))) (define-type ATree% (Class #:implements Tree<%> (init-field (state State)) (nothing-to-place? (-> Boolean)))) ;(define-type Tree (Instance ATree%)) (define-type Placed% (Class (init-field (state State) (tile Tile) (hotel (Option Hotel)) (state/tile State) (reason SpotType)) (purchase (-> Decisions (Listof Hotel) (U (Instance ATree%) (Listof HandOut)))) ;; Precondition: share-order? (to-trees (-> Decisions (Listof Hotel) (Listof (Instance ATree%)))) ;; Precondition: share-order? (acceptable-policies (-> (Listof (Listof Hotel)) (Listof (Listof Hotel)))))) (define-type LPlaced% (Class #:implements ATree% (init-field (lplaced (Listof (Instance Placed%))) (state State)) (nothing-to-place? (-> Boolean)) )) ;; ----------------------------------------------------------------------------- (struct hand-out ( [tile : Tile] [tree : (Instance ATree%)])) (define-type HandOut hand-out) ;; HandOut = (hand-out t st) denotes that player received tile t and st is the Tree generated from the resulting state (: placed-tile (-> (Instance Placed%) Tile)) (define (placed-tile p) (get-field tile p)) (: placed-hotel (-> (Instance Placed%) (Option Hotel))) (define (placed-hotel p) (get-field hotel p)) (: atree% ATree%) (define atree% (class object% ;(tree<%>) (init-field [state : State]) (super-new) (define/public (nothing-to-place?) #f) (define/public (to-state) (get-field state this)) ;(abstract next) (define/public (next t h d* h* pt) (error 'not-implemented)) ;; template hook pattern: template (define/public (founding n order-policies) (unless (shares-order? order-policies) (error 'atree-founding "Precondition")) (traversal n order-policies (is-action FOUNDING))) ;; template hook pattern: template (define/public (merging n order-policies) (traversal n order-policies (is-action MERGING))) ;; hook ;; how many transitions in THIS tree (up to depth n) satisfy the given predicate ;; Nat [Listof ShareOrder] [Placed -> Nat] -> Nat (define/public (traversal n order-policies i) (error 'not-impolementd)) private field : ACTION - > Placed - > { 0,1 } ;; is the alternative a merging action? (: is-action (-> Symbol (-> (Instance Placed%) (U 1 0)))) (define ((is-action tag) p) (if (and (placed-hotel p) (eq? (get-field reason p) tag)) 1 0)) ;; use pick-tile to hand out a tile; extract the corresponding subtree [ [ Listof Tile ] - > Tile ] [ ] - > * [ Maybe Tile ] Tree (define/public (lookup-tile pick-tile lo-handout) (values #f this)) )) (: state% ATree%) (define state% (class atree% ;(tree<%>) (super-new) (define/override (next . _) (error 'tree-next "finale state can't transition")) (define/override (traversal n policies p?) 0) (define/override (lookup-tile pick-tile lo-handout) (values #f this)))) (: lplaced% LPlaced%) (define lplaced% (class atree% ;(tree<%>) (super-new) (init-field (lplaced : (Listof (Instance Placed%)))) (define/override (nothing-to-place?) (null? lplaced)) (define/override (next tile hotel decisions shares-to-buy pick-tile) (define intermediate (send (lookup-purchase tile hotel) purchase decisions shares-to-buy)) (unless (list? intermediate) (error "Expected a HandOut, got a State%")) (send this lookup-tile pick-tile intermediate)) ;; Tile [Maybe Hotel] -> Placed ;; lookup the one and only Placed from lo-placed that represents the action of placing t (& h) (: lookup-purchase (-> Tile (Option Hotel) (Instance Placed%))) (define/private (lookup-purchase t h) (or (for/or : (Option (Instance Placed%)) ((p : (Instance Placed%) lplaced) #:when (and (equal? (placed-hotel p) h) (equal? (placed-tile p) t))) p) (error 'noplace))) (define/override (lookup-tile pick-tile lo-hand-out) (define tile (pick-tile (map hand-out-tile lo-hand-out))) (define st (for/or : (Option (Instance ATree%)) ((p : HandOut lo-hand-out) #:when (equal? (hand-out-tile p) tile)) (hand-out-tree p))) (values tile (or st (error 'lookupfailed)))) (define/override (traversal n policies p?) (if (= n 0) 0 (for/sum : Natural ((branch : (Instance Placed%) (in-list lplaced))) (define d* (map (lambda ([p : Player]) (list p '())) (state-players (get-field state/tile branch)))) (define a (send branch acceptable-policies policies)) (+ (p? branch) ;; do not inspect every subtree because share buying does not affect actions (if (empty? a) 0 (* (length a) (for/sum : Natural ((st : (Instance ATree%) (send branch to-trees d* (first a)))) (send st traversal (- n 1) policies p?)))))))))) (: placed% Placed%) (define placed% (class object% (init-field state tile hotel state/tile reason) (super-new) Decisions ShareOrder - > state% or [ ] ;; given merger decisions and a purchase order, generate the next stage from THIS decision point (define/public (purchase decisions share-order) ;; --------------------------------------------------------------------------------------------- ;; contract checking (when (eq? MERGING reason) (define players (state-players state/tile)) (unless (= (length decisions) (length players)) (printf "contract failure: received wrong number of decisions") ;; (pretty-print players) ( pretty - print ( map first decisions ) ) (error 'purchase "done"))) ;; --------------------------------------------------------------------------------------------- (define state/decisions (if (eq? MERGING reason) (state-return-shares state/tile decisions (state-board state)) state/tile)) (define state/bought (state-buy-shares state/decisions share-order)) (define available-tiles (state-tiles state/bought)) (if (empty? available-tiles) (new state% [state state/bought]) (for/list : (Listof HandOut) ((tile : Tile available-tiles)) (hand-out tile (generate-tree (state-next-turn (state-move-tile state/bought tile))))))) Decisions ShareOrder - > [ ] ;; given a purchase order, generate list of trees from THIS decision point's purchases (define/public (to-trees decisions share-order) (define state-or-hand-out (purchase decisions share-order)) (cond [(list? state-or-hand-out) (map hand-out-tree state-or-hand-out)] [else (list state-or-hand-out)])) [ [ ] ;; filter out those share orders that are acceptable given THIS decision point's state (define/public (acceptable-policies policies) (unless (andmap shares-order? policies) (error 'acceptable-policies "Precondigion")) (define state state/tile) (define budget (player-money (state-current-player state))) (define board (state-board state)) (define shares (state-shares state)) (for/list ((p : (Listof Hotel) policies) #:when (and (shares-available? shares p) (affordable? board p budget))) p)))) (: generate-tree (-> State (Instance ATree%))) (define (generate-tree state) (cond [(state-final? state) (new state% [state state])] [else (define board (state-board state)) (define available-hotels (state-hotels state)) (define lplaced (for/fold : (Listof (Instance Placed%)) ((lo-placed : (Listof (Instance Placed%)) '())) ((t : Tile (player-tiles (state-current-player state)))) (define kind (what-kind-of-spot board t)) (: hotels (Listof (Option Hotel))) (define hotels (cond [(eq? kind IMPOSSIBLE) '()] [(and (eq? FOUNDING kind) (cons? available-hotels)) available-hotels] [(eq? MERGING kind) (define-values (acquirers _) (merging-which board t)) acquirers] [else (list #f)])) (define new-placements (for/list : (Listof (Instance Placed%)) ((h : (Option Hotel) (in-list hotels))) (define state/tile (if h (state-place-tile state t h) (state-place-tile state t))) (new placed% [state state][tile t][hotel h][state/tile state/tile][reason kind]))) (append new-placements lo-placed))) (new lplaced% (state state) (lplaced lplaced))])) ;; ASSUME: current player has enough money to buy the desired shares (: tree-next (-> (Instance ATree%) Tile Hotel Decisions (Listof Hotel) (-> (Listof Tile) Tile) (Values (Option Tile) (Instance ATree%)))) (define (tree-next current-tree tile hotel decisions shares-to-buy pick-tile) (send current-tree next tile hotel decisions shares-to-buy pick-tile)) (: tree-state (-> (Instance ATree%) State)) (define (tree-state t) (send t to-state))
null
https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/acquire/typed/tree.rkt
racket
============================================================================= Precondition: share-order (define-type Tree (Instance ATree%)) Precondition: share-order? Precondition: share-order? ----------------------------------------------------------------------------- HandOut = (hand-out t st) (tree<%>) (abstract next) template hook pattern: template template hook pattern: template hook how many transitions in THIS tree (up to depth n) satisfy the given predicate Nat [Listof ShareOrder] [Placed -> Nat] -> Nat is the alternative a merging action? use pick-tile to hand out a tile; extract the corresponding subtree (tree<%>) (tree<%>) Tile [Maybe Hotel] -> Placed lookup the one and only Placed from lo-placed that represents the action of placing t (& h) do not inspect every subtree because share buying does not affect actions given merger decisions and a purchase order, generate the next stage from THIS decision point --------------------------------------------------------------------------------------------- contract checking (pretty-print players) --------------------------------------------------------------------------------------------- given a purchase order, generate list of trees from THIS decision point's purchases filter out those share orders that are acceptable given THIS decision point's state ASSUME: current player has enough money to buy the desired shares
#lang typed/racket (provide tree-state lplaced% generate-tree tree-next hand-out? HandOut ) (require require-typed-check "../base/types.rkt" "board-adapted.rkt" "state-adapted.rkt" ) (require/typed/check "basics.rkt" (shares-available? (-> Shares (Listof Hotel) Boolean)) (shares-order? (-> Any Boolean)) ) (define-type Tree<%> (Class (to-state (-> State)) (next (-> Tile (Option Hotel) Decisions (Listof Hotel) (-> (Listof Tile) Tile) (Values (Option Tile) (Instance ATree%)))) (founding (-> Natural (Listof (Listof Hotel)) Natural)) (traversal (-> Natural (Listof (Listof Hotel)) (-> (Instance Placed%) Natural) Natural)) (lookup-tile (-> (-> (Listof Tile) Tile) (Listof HandOut) (Values (Option Tile) (Instance ATree%)))) (merging (-> Natural (Listof (Listof Hotel)) Natural)))) (define-type ATree% (Class #:implements Tree<%> (init-field (state State)) (nothing-to-place? (-> Boolean)))) (define-type Placed% (Class (init-field (state State) (tile Tile) (hotel (Option Hotel)) (state/tile State) (reason SpotType)) (purchase (-> Decisions (Listof Hotel) (U (Instance ATree%) (Listof HandOut)))) (to-trees (-> Decisions (Listof Hotel) (Listof (Instance ATree%)))) (acceptable-policies (-> (Listof (Listof Hotel)) (Listof (Listof Hotel)))))) (define-type LPlaced% (Class #:implements ATree% (init-field (lplaced (Listof (Instance Placed%))) (state State)) (nothing-to-place? (-> Boolean)) )) (struct hand-out ( [tile : Tile] [tree : (Instance ATree%)])) (define-type HandOut hand-out) denotes that player received tile t and st is the Tree generated from the resulting state (: placed-tile (-> (Instance Placed%) Tile)) (define (placed-tile p) (get-field tile p)) (: placed-hotel (-> (Instance Placed%) (Option Hotel))) (define (placed-hotel p) (get-field hotel p)) (: atree% ATree%) (define atree% (init-field [state : State]) (super-new) (define/public (nothing-to-place?) #f) (define/public (to-state) (get-field state this)) (define/public (next t h d* h* pt) (error 'not-implemented)) (define/public (founding n order-policies) (unless (shares-order? order-policies) (error 'atree-founding "Precondition")) (traversal n order-policies (is-action FOUNDING))) (define/public (merging n order-policies) (traversal n order-policies (is-action MERGING))) (define/public (traversal n order-policies i) (error 'not-impolementd)) private field : ACTION - > Placed - > { 0,1 } (: is-action (-> Symbol (-> (Instance Placed%) (U 1 0)))) (define ((is-action tag) p) (if (and (placed-hotel p) (eq? (get-field reason p) tag)) 1 0)) [ [ Listof Tile ] - > Tile ] [ ] - > * [ Maybe Tile ] Tree (define/public (lookup-tile pick-tile lo-handout) (values #f this)) )) (: state% ATree%) (define state% (super-new) (define/override (next . _) (error 'tree-next "finale state can't transition")) (define/override (traversal n policies p?) 0) (define/override (lookup-tile pick-tile lo-handout) (values #f this)))) (: lplaced% LPlaced%) (define lplaced% (super-new) (init-field (lplaced : (Listof (Instance Placed%)))) (define/override (nothing-to-place?) (null? lplaced)) (define/override (next tile hotel decisions shares-to-buy pick-tile) (define intermediate (send (lookup-purchase tile hotel) purchase decisions shares-to-buy)) (unless (list? intermediate) (error "Expected a HandOut, got a State%")) (send this lookup-tile pick-tile intermediate)) (: lookup-purchase (-> Tile (Option Hotel) (Instance Placed%))) (define/private (lookup-purchase t h) (or (for/or : (Option (Instance Placed%)) ((p : (Instance Placed%) lplaced) #:when (and (equal? (placed-hotel p) h) (equal? (placed-tile p) t))) p) (error 'noplace))) (define/override (lookup-tile pick-tile lo-hand-out) (define tile (pick-tile (map hand-out-tile lo-hand-out))) (define st (for/or : (Option (Instance ATree%)) ((p : HandOut lo-hand-out) #:when (equal? (hand-out-tile p) tile)) (hand-out-tree p))) (values tile (or st (error 'lookupfailed)))) (define/override (traversal n policies p?) (if (= n 0) 0 (for/sum : Natural ((branch : (Instance Placed%) (in-list lplaced))) (define d* (map (lambda ([p : Player]) (list p '())) (state-players (get-field state/tile branch)))) (define a (send branch acceptable-policies policies)) (+ (p? branch) (if (empty? a) 0 (* (length a) (for/sum : Natural ((st : (Instance ATree%) (send branch to-trees d* (first a)))) (send st traversal (- n 1) policies p?)))))))))) (: placed% Placed%) (define placed% (class object% (init-field state tile hotel state/tile reason) (super-new) Decisions ShareOrder - > state% or [ ] (define/public (purchase decisions share-order) (when (eq? MERGING reason) (define players (state-players state/tile)) (unless (= (length decisions) (length players)) (printf "contract failure: received wrong number of decisions") ( pretty - print ( map first decisions ) ) (error 'purchase "done"))) (define state/decisions (if (eq? MERGING reason) (state-return-shares state/tile decisions (state-board state)) state/tile)) (define state/bought (state-buy-shares state/decisions share-order)) (define available-tiles (state-tiles state/bought)) (if (empty? available-tiles) (new state% [state state/bought]) (for/list : (Listof HandOut) ((tile : Tile available-tiles)) (hand-out tile (generate-tree (state-next-turn (state-move-tile state/bought tile))))))) Decisions ShareOrder - > [ ] (define/public (to-trees decisions share-order) (define state-or-hand-out (purchase decisions share-order)) (cond [(list? state-or-hand-out) (map hand-out-tree state-or-hand-out)] [else (list state-or-hand-out)])) [ [ ] (define/public (acceptable-policies policies) (unless (andmap shares-order? policies) (error 'acceptable-policies "Precondigion")) (define state state/tile) (define budget (player-money (state-current-player state))) (define board (state-board state)) (define shares (state-shares state)) (for/list ((p : (Listof Hotel) policies) #:when (and (shares-available? shares p) (affordable? board p budget))) p)))) (: generate-tree (-> State (Instance ATree%))) (define (generate-tree state) (cond [(state-final? state) (new state% [state state])] [else (define board (state-board state)) (define available-hotels (state-hotels state)) (define lplaced (for/fold : (Listof (Instance Placed%)) ((lo-placed : (Listof (Instance Placed%)) '())) ((t : Tile (player-tiles (state-current-player state)))) (define kind (what-kind-of-spot board t)) (: hotels (Listof (Option Hotel))) (define hotels (cond [(eq? kind IMPOSSIBLE) '()] [(and (eq? FOUNDING kind) (cons? available-hotels)) available-hotels] [(eq? MERGING kind) (define-values (acquirers _) (merging-which board t)) acquirers] [else (list #f)])) (define new-placements (for/list : (Listof (Instance Placed%)) ((h : (Option Hotel) (in-list hotels))) (define state/tile (if h (state-place-tile state t h) (state-place-tile state t))) (new placed% [state state][tile t][hotel h][state/tile state/tile][reason kind]))) (append new-placements lo-placed))) (new lplaced% (state state) (lplaced lplaced))])) (: tree-next (-> (Instance ATree%) Tile Hotel Decisions (Listof Hotel) (-> (Listof Tile) Tile) (Values (Option Tile) (Instance ATree%)))) (define (tree-next current-tree tile hotel decisions shares-to-buy pick-tile) (send current-tree next tile hotel decisions shares-to-buy pick-tile)) (: tree-state (-> (Instance ATree%) State)) (define (tree-state t) (send t to-state))
8196b8e3cbf07730e1880ef83672a7e80d6de1518d4adce1c794057fa623d54e
hopv/MoCHi
rose_tree.mli
type 'a t = Node of 'a * 'a t list type path = int list val leaf : 'a -> 'a t val decomp : 'a t -> 'a * 'a t list val label : 'a t -> 'a val children : 'a t -> 'a t list val root : 'a t -> 'a val flatten : 'a t -> 'a list val map : (path -> 'a -> 'b) -> 'a t -> 'b t val fold : ('a -> 'b list -> 'b) -> 'a t -> 'b val for_all : ('a -> bool) -> 'a t -> bool val exists : ('a -> bool) -> 'a t -> bool val proj : path -> 'a t -> 'a t val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit val update : path -> 'a t -> 'a t -> 'a t val zip : 'a t -> 'b t -> ('a * 'b) t val find_all_subtree : ('a t -> bool) -> 'a t -> 'a t list val find_all_label : ('a -> bool) -> 'a t -> 'a list val filter_map_subtree : ('a t -> 'b option) -> 'a t -> 'b list val filter_map_label : ('a -> 'b option) -> 'a t -> 'b list val is_leaf : 'a t -> bool
null
https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/src/rose_tree.mli
ocaml
type 'a t = Node of 'a * 'a t list type path = int list val leaf : 'a -> 'a t val decomp : 'a t -> 'a * 'a t list val label : 'a t -> 'a val children : 'a t -> 'a t list val root : 'a t -> 'a val flatten : 'a t -> 'a list val map : (path -> 'a -> 'b) -> 'a t -> 'b t val fold : ('a -> 'b list -> 'b) -> 'a t -> 'b val for_all : ('a -> bool) -> 'a t -> bool val exists : ('a -> bool) -> 'a t -> bool val proj : path -> 'a t -> 'a t val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit val update : path -> 'a t -> 'a t -> 'a t val zip : 'a t -> 'b t -> ('a * 'b) t val find_all_subtree : ('a t -> bool) -> 'a t -> 'a t list val find_all_label : ('a -> bool) -> 'a t -> 'a list val filter_map_subtree : ('a t -> 'b option) -> 'a t -> 'b list val filter_map_label : ('a -> 'b option) -> 'a t -> 'b list val is_leaf : 'a t -> bool
211e884f8e748a348abeff30f45e5421cbf43f657bf6717e6708c83071b457cd
marcoheisig/sb-simd
cpu-identification.lisp
(in-package #:sb-simd-internals) #+x86-64 (progn (defun cpuid (eax &optional (ecx 0)) (declare (type (unsigned-byte 32) eax ecx)) (sb-vm::%cpu-identification eax ecx)) (defun sse-supported-p () (and (>= (cpuid 0) 1) (logbitp 25 (nth-value 3 (cpuid 1))))) (defun sse2-supported-p () (and (>= (cpuid 0) 1) (logbitp 26 (nth-value 3 (cpuid 1))))) (defun sse3-supported-p () (and (>= (cpuid 0) 1) (logbitp 0 (nth-value 2 (cpuid 1))))) (defun ssse3-supported-p () (and (>= (cpuid 0) 1) (logbitp 9 (nth-value 2 (cpuid 1))))) (defun sse4.1-supported-p () (and (>= (cpuid 0) 1) (logbitp 19 (nth-value 2 (cpuid 1))))) (defun sse4.2-supported-p () (and (>= (cpuid 0) 1) (logbitp 20 (nth-value 2 (cpuid 1))))) (defun avx-supported-p () (and (>= (cpuid 0) 1) (logbitp 28 (nth-value 2 (cpuid 1))))) (defun avx2-supported-p () (and (>= (cpuid 0) 7) (logbitp 5 (nth-value 1 (cpuid 7))))) (defun fma-supported-p () (and (>= (cpuid 0) 1) (logbitp 12 (nth-value 2 (cpuid 1)))))) #-x86-64 (progn (defun sse-supported-p () nil) (defun sse2-supported-p () nil) (defun sse3-supported-p () nil) (defun ssse3-supported-p () nil) (defun sse4.1-supported-p () nil) (defun sse4.2-supported-p () nil) (defun avx-supported-p () nil) (defun avx2-supported-p () nil) (defun fma-supported-p () nil))
null
https://raw.githubusercontent.com/marcoheisig/sb-simd/fad8614bfb45b2faf331c3d88ee97412f084bb6f/code/cpu-identification.lisp
lisp
(in-package #:sb-simd-internals) #+x86-64 (progn (defun cpuid (eax &optional (ecx 0)) (declare (type (unsigned-byte 32) eax ecx)) (sb-vm::%cpu-identification eax ecx)) (defun sse-supported-p () (and (>= (cpuid 0) 1) (logbitp 25 (nth-value 3 (cpuid 1))))) (defun sse2-supported-p () (and (>= (cpuid 0) 1) (logbitp 26 (nth-value 3 (cpuid 1))))) (defun sse3-supported-p () (and (>= (cpuid 0) 1) (logbitp 0 (nth-value 2 (cpuid 1))))) (defun ssse3-supported-p () (and (>= (cpuid 0) 1) (logbitp 9 (nth-value 2 (cpuid 1))))) (defun sse4.1-supported-p () (and (>= (cpuid 0) 1) (logbitp 19 (nth-value 2 (cpuid 1))))) (defun sse4.2-supported-p () (and (>= (cpuid 0) 1) (logbitp 20 (nth-value 2 (cpuid 1))))) (defun avx-supported-p () (and (>= (cpuid 0) 1) (logbitp 28 (nth-value 2 (cpuid 1))))) (defun avx2-supported-p () (and (>= (cpuid 0) 7) (logbitp 5 (nth-value 1 (cpuid 7))))) (defun fma-supported-p () (and (>= (cpuid 0) 1) (logbitp 12 (nth-value 2 (cpuid 1)))))) #-x86-64 (progn (defun sse-supported-p () nil) (defun sse2-supported-p () nil) (defun sse3-supported-p () nil) (defun ssse3-supported-p () nil) (defun sse4.1-supported-p () nil) (defun sse4.2-supported-p () nil) (defun avx-supported-p () nil) (defun avx2-supported-p () nil) (defun fma-supported-p () nil))
ed5a4a55b33d7f96366d46a09c6f649d36d4db4061f6bd72612679c0233664a6
mogenslund/liq2
clojure_mode.cljc
(ns liq2.modes.clojure-mode (:require [clojure.string :as str] [liq2.modes.fundamental-mode :as fundamental-mode] [liq2.editor :as editor :refer [apply-to-buffer switch-to-buffer get-buffer]] [liq2.buffer :as buffer] [liq2.util :as util])) (def match {:keyword-begin #"(?<=(\s|\(|\[|\{)|^):[\w\#\.\-\_\:\+\=\>\<\/\!\?\*]+(?=(\s|\)|\]|\}|\,|$))" :keyword-end #".|$" :string-begin #"(?<!\\\\)(\")" :string-escape #"(\\\")" :string-end "\"" :comment-begin #"(?<!\\\\);.*$|^#+ .*$" :comment-end #"$" :special-begin #"(?<=\()(ns |def(n|n-|test|record|protocol|macro)? )" :green-begin "✔" :red-begin "✘" :yellow-begin "➜" :bold-begin #"(?<=\*)\w+" :bold-end #"\*" :definition-begin #"[\w\#\.\-\_\:\+\=\>\<\/\!\?\*]+" :definition-end #"."}) (def mode {:syntax {:plain ; Context {:style :plain1 ; style :matchers {(match :string-begin) :string (match :keyword-begin) :keyword (match :comment-begin) :comment (match :green-begin) :green (match :yellow-begin) :yellow (match :red-begin) :red (match :bold-begin) :bold (match :special-begin) :special}} :string {:style :string :matchers {(match :string-escape) :string (match :string-end) :string-end}} :string-end {:style :string :matchers {#".|$|^" :plain}} :comment {:style :comment :matchers {(match :comment-end) :plain}} :keyword {:style :keyword :matchers {(match :keyword-end) :plain}} :special {:style :special :matchers {(match :definition-begin) :definition}} :green {:style :green :matchers {#".|$|^" :plain}} :yellow {:style :yellow :matchers {#".|$|^" :plain}} :red {:style :red :matchers {#".|$|^" :plain}} :bold {:style :green :matchers {(match :bold-end) :plain}} :definition {:style :definition :matchers {(match :definition-end) :plain}}}})
null
https://raw.githubusercontent.com/mogenslund/liq2/66a323a75804154ea51c3ff9d3c23cbd26c9d24d/src/liq2/modes/clojure_mode.cljc
clojure
Context style
(ns liq2.modes.clojure-mode (:require [clojure.string :as str] [liq2.modes.fundamental-mode :as fundamental-mode] [liq2.editor :as editor :refer [apply-to-buffer switch-to-buffer get-buffer]] [liq2.buffer :as buffer] [liq2.util :as util])) (def match {:keyword-begin #"(?<=(\s|\(|\[|\{)|^):[\w\#\.\-\_\:\+\=\>\<\/\!\?\*]+(?=(\s|\)|\]|\}|\,|$))" :keyword-end #".|$" :string-begin #"(?<!\\\\)(\")" :string-escape #"(\\\")" :string-end "\"" :comment-begin #"(?<!\\\\);.*$|^#+ .*$" :comment-end #"$" :special-begin #"(?<=\()(ns |def(n|n-|test|record|protocol|macro)? )" :green-begin "✔" :red-begin "✘" :yellow-begin "➜" :bold-begin #"(?<=\*)\w+" :bold-end #"\*" :definition-begin #"[\w\#\.\-\_\:\+\=\>\<\/\!\?\*]+" :definition-end #"."}) (def mode {:syntax :matchers {(match :string-begin) :string (match :keyword-begin) :keyword (match :comment-begin) :comment (match :green-begin) :green (match :yellow-begin) :yellow (match :red-begin) :red (match :bold-begin) :bold (match :special-begin) :special}} :string {:style :string :matchers {(match :string-escape) :string (match :string-end) :string-end}} :string-end {:style :string :matchers {#".|$|^" :plain}} :comment {:style :comment :matchers {(match :comment-end) :plain}} :keyword {:style :keyword :matchers {(match :keyword-end) :plain}} :special {:style :special :matchers {(match :definition-begin) :definition}} :green {:style :green :matchers {#".|$|^" :plain}} :yellow {:style :yellow :matchers {#".|$|^" :plain}} :red {:style :red :matchers {#".|$|^" :plain}} :bold {:style :green :matchers {(match :bold-end) :plain}} :definition {:style :definition :matchers {(match :definition-end) :plain}}}})
1cad734aa8134ce71d88dddf34b93692001f2b256a356adc7a392191381b6324
AbstractMachinesLab/caramel
old_IO.ml
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > 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 . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> 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 Std let latest_version : Old_protocol.protocol_version = `V3 let current_version = ref `V2 let default_context = {Old_protocol.Context. document = None; printer_width = None; printer_verbosity = None} let invalid_arguments () = failwith "invalid arguments" open Query_protocol open Old_protocol let pos_of_json = function | `String "start" -> `Start | `String "end" -> `End | `Int offset -> `Offset offset | `Assoc props -> begin try match List.assoc "line" props, List.assoc "col" props with | `Int line, `Int col -> `Logical (line,col) | _ -> failwith "Incorrect position" with Not_found -> failwith "Incorrect position" end | _ -> failwith "Incorrect position" let mandatory_position = function | [`String "at"; jpos] -> pos_of_json jpos | _ -> invalid_arguments () let optional_string = function | [`String name] -> Some name | [] -> None | _ -> invalid_arguments () let string_list l = List.map ~f:(function `String s -> s | _ -> invalid_arguments ()) l let source_or_build = function | "source" -> `Source | "build" -> `Build | _ -> invalid_arguments () let ml_or_mli = function | "ml" -> `ML | "mli" -> `MLI | _ -> invalid_arguments () let auto_ml_or_mli = function | "auto" -> `Auto | x -> ml_or_mli x let add_or_remove = function | "add" -> `Add | "remove" -> `Rem | _ -> invalid_arguments () let with_failures failures assoc = match failures with | `Ok -> assoc | `Failures failures -> let flags, extensions = List.fold_left failures ~init:([],[]) ~f:( fun (flgs, exts) (str,exn) -> match exn with | Arg.Bad _ -> str :: flgs, exts | Extension.Unknown -> flgs, str :: exts | _ -> assert false ) in let flags = match flags with | [] -> [] | failures -> let str = String.concat ~sep:", " failures in [ `String ("Unknown flags " ^ str) ] in let extensions = match extensions with | [] -> [] | failures -> let str = String.concat ~sep:", " failures in [ `String ("Unknown extensions " ^ str) ] in ("failures", `List (flags @ extensions)) :: assoc let document_of_json = let make kind path dot_merlins = {Context.dot_merlins; kind = auto_ml_or_mli kind; path = optional_string path; } in function | (`String "dot_merlin" :: `List dot_merlins :: `String kind :: opt_name) -> make kind opt_name (Some (string_list dot_merlins)) | (`String kind :: opt_name) -> make kind opt_name None | _ -> invalid_arguments () let request_of_json context = let request x = Request (context, x) in function | (`String "type" :: `String "expression" :: `String expr :: opt_pos) -> request (Query (Type_expr (expr, mandatory_position opt_pos))) | [`String "type"; `String "enclosing"; `Assoc [ "expr", `String expr ; "offset", `Int offset] ; jpos] -> request (Query (Type_enclosing (Some (expr, offset), pos_of_json jpos, None))) | [`String "type"; `String "enclosing"; `String "at"; jpos] -> request (Query (Type_enclosing (None, pos_of_json jpos, None))) | [ `String "case"; `String "analysis"; `String "from"; x; `String "to"; y ] -> request (Query (Case_analysis (pos_of_json x, pos_of_json y))) | [`String "enclosing"; jpos] -> request (Query (Enclosing (pos_of_json jpos))) | [`String "complete"; `String "prefix"; `String prefix; `String "at"; jpos] -> request (Query (Complete_prefix (prefix, pos_of_json jpos, [], false, true))) | [`String "complete"; `String "prefix"; `String prefix; `String "at"; jpos; `String "with"; `String "doc"] -> request (Query (Complete_prefix (prefix, pos_of_json jpos, [], true, true))) | [`String "expand"; `String "prefix"; `String prefix; `String "at"; jpos] -> request (Query (Expand_prefix (prefix, pos_of_json jpos, [], true))) | [`String "search"; `String "polarity"; `String query; `String "at"; jpos] -> request (Query (Polarity_search (query, pos_of_json jpos))) | (`String "document" :: (`String "" | `Null) :: pos) -> request (Query (Document (None, mandatory_position pos))) | (`String "document" :: `String path :: pos) -> request (Query (Document (Some path, mandatory_position pos))) | (`String "locate" :: (`String "" | `Null) :: `String choice :: pos) -> request (Query (Locate (None, ml_or_mli choice, mandatory_position pos))) | (`String "locate" :: `String path :: `String choice :: pos) -> request (Query (Locate (Some path, ml_or_mli choice, mandatory_position pos))) | (`String "jump" :: `String target :: pos) -> request (Query (Jump (target, mandatory_position pos))) | [`String "outline"] -> request (Query Outline) | [`String "shape"; pos] -> request (Query (Shape (pos_of_json pos))) | [`String "occurrences"; `String "ident"; `String "at"; jpos] -> request (Query (Occurrences (`Ident_at (pos_of_json jpos)))) | (`String ("reset"|"checkout") :: document) -> request (Sync (Checkout (document_of_json document))) | [`String "refresh"] -> request (Sync Refresh) | [`String "errors"] -> request (Query (Errors { lexing = true; parsing = true; typing = true })) | (`String "dump" :: args) -> request (Query (Dump args)) | [`String "which"; `String "path"; `String name] -> request (Query (Path_of_source [name])) | [`String "which"; `String "path"; `List names] -> request (Query (Path_of_source (string_list names))) | [`String "which"; `String "with_ext"; `String ext] -> request (Query (List_modules [ext])) | [`String "which"; `String "with_ext"; `List exts] -> request (Query (List_modules (string_list exts))) | [`String "flags" ; `String "set" ; `List flags ] -> request (Sync (Flags_set (string_list flags))) | [`String "flags" ; `String "get" ] -> request (Sync (Flags_get)) | [`String "find"; `String "use"; `List packages] | (`String "find" :: `String "use" :: packages) -> request (Sync (Findlib_use (string_list packages))) | [`String "find"; `String "list"] -> request (Query Findlib_list) | [`String "extension"; `String "enable"; `List extensions] -> request (Sync (Extension_set (`Enabled,string_list extensions))) | [`String "extension"; `String "disable"; `List extensions] -> request (Sync (Extension_set (`Disabled,string_list extensions))) | [`String "extension"; `String "list"] -> request (Query (Extension_list `All)) | [`String "extension"; `String "list"; `String "enabled"] -> request (Query (Extension_list `Enabled)) | [`String "extension"; `String "list"; `String "disabled"] -> request (Query (Extension_list `Disabled)) | [`String "path"; `String "list"; `String ("source"|"build" as var)] -> request (Query (Path_list (source_or_build var))) | [`String "path"; `String "reset"] -> request (Sync Path_reset) | (`String "path" :: `String ("add"|"remove" as action) :: `String ("source"|"build" as var) :: ((`List pathes :: []) | pathes)) -> request (Sync (Path (source_or_build var, add_or_remove action, string_list pathes))) | [`String "tell"; pos_start; pos_end; `String content] -> request (Sync (Tell (pos_of_json pos_start, pos_of_json pos_end, content))) | [`String "project"; `String "get"] -> request (Sync Project_get) | [`String "version"] -> request (Query Version) | [`String "protocol"; `String "version"] -> request (Sync (Protocol_version None)) | [`String "protocol"; `String "version"; `Int n] -> request (Sync (Protocol_version (Some n))) | _ -> invalid_arguments () let json_of_protocol_version : Old_protocol.protocol_version -> _ = function | `V2 -> `Int 2 | `V3 -> `Int 3 let json_of_sync_command (type a) (command : a sync_command) (response : a) : json = match command, response with | Tell _, () -> `Bool true | Checkout _, () -> `Bool true | Refresh, () -> `Bool true | Flags_get, flags -> `List (List.map ~f:Json.string flags) | Flags_set _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Findlib_use _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Extension_set _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Path _, () -> `Bool true | Path_reset, () -> `Bool true | Protocol_version _, (`Selected v, `Latest vm, version) -> `Assoc ["selected", json_of_protocol_version v; "latest", json_of_protocol_version vm; "merlin", `String version ] | Project_get, (strs, fails) -> let failures = match fails with | `Failures ((_::_) as fails) -> ["failures", `List (List.map ~f:Json.string fails)] | _ -> [] in `Assoc (("result", `List (List.map ~f:Json.string strs))::failures) | Idle_job, b -> `Bool b let classify_response = function | Failure s | Exception (Failure s) -> ("failure", `String s) | Error error -> ("error", error) | Exception exn -> begin match Location.error_of_exn exn with | Some (`Ok error) -> ("error", Query_json.json_of_error error) | None | Some `Already_displayed -> ("exception", `String (Printexc.to_string exn)) end | Return (Query cmd, response) -> ("return", Query_json.json_of_response cmd response) | Return (Sync cmd, response) -> ("return", json_of_sync_command cmd response) let json_of_response_v2 response = let class_, value = classify_response response in `List [`String class_; value] let json_of_response_v3 ~notifications response = let class_, value = classify_response response in `Assoc [ "class", `String class_; "value", value; "notifications", `List (List.map ~f:(fun { Logger.section; msg } -> `Assoc ["section", `String section; "message", `String msg]) notifications); ] let json_of_response notifications response = match !current_version with | `V2 -> json_of_response_v2 response | `V3 -> json_of_response_v3 ~notifications response let request_of_json = function | `Assoc _ as json -> let open Json.Util in let document = let value = member "document" json in let value = if value = `Null then member "context" json else value in if value = `Null then None else Some (to_list value |> document_of_json) in let printer_width = member "printer_width" json |> to_int_option in let printer_verbosity = member "printer_verbosity" json |> to_int_option in let context = {Context. document; printer_verbosity; printer_width} in let query = member "query" json |> to_list in request_of_json context query | `List jsons -> request_of_json default_context jsons | _ -> invalid_arguments () let make_json ?(on_read=ignore) ~input ~output () = let rec read buf len = on_read input; try Unix.read input buf 0 len with Unix.Unix_error (Unix.EINTR,_,_) -> read buf len in let lexbuf = Lexing.from_function read in let input = Json.stream_from_lexbuf (Json.init_lexer ()) lexbuf in let input () = try Some (Stream.next input) with Stream.Failure -> None in let output = Unix.out_channel_of_descr output in let output' = Json.to_channel output in let output json = output' json; output_char output '\n'; flush output in input, output let make_sexp ?on_read ~input ~output () = (* Fix for emacs: emacs start-process doesn't distinguish between stdout and stderr. So we redirect stderr to /dev/null with sexp frontend. *) begin match begin try Some (Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o600) with | Unix.Unix_error _ -> if Sys.os_type = "Win32" then try Some (Unix.openfile "NUL" [Unix.O_WRONLY] 0o600) with Unix.Unix_error _ -> None else None end with | None -> () | Some fd -> Unix.dup2 fd Unix.stderr; Unix.close fd end; let input' = Sexp.of_file_descr ?on_read input in let input' () = Option.map ~f:Sexp.to_json (input' ()) in let buf = Buffer.create 8192 in let output json = let sexp = Sexp.of_json json in Sexp.to_buf sexp buf; Buffer.add_char buf '\n'; let contents = Buffer.to_bytes buf in let rec write_contents n l = if l > 0 then let l' = Unix.write output contents n l in if l' > 0 then write_contents (n + l') (l - l') in write_contents 0 (Bytes.length contents); if Buffer.length buf > 100_000 then Buffer.reset buf else Buffer.clear buf in input', output
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/frontend/ocamlmerlin/old/old_IO.ml
ocaml
Fix for emacs: emacs start-process doesn't distinguish between stdout and stderr. So we redirect stderr to /dev/null with sexp frontend.
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > 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 . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> 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 Std let latest_version : Old_protocol.protocol_version = `V3 let current_version = ref `V2 let default_context = {Old_protocol.Context. document = None; printer_width = None; printer_verbosity = None} let invalid_arguments () = failwith "invalid arguments" open Query_protocol open Old_protocol let pos_of_json = function | `String "start" -> `Start | `String "end" -> `End | `Int offset -> `Offset offset | `Assoc props -> begin try match List.assoc "line" props, List.assoc "col" props with | `Int line, `Int col -> `Logical (line,col) | _ -> failwith "Incorrect position" with Not_found -> failwith "Incorrect position" end | _ -> failwith "Incorrect position" let mandatory_position = function | [`String "at"; jpos] -> pos_of_json jpos | _ -> invalid_arguments () let optional_string = function | [`String name] -> Some name | [] -> None | _ -> invalid_arguments () let string_list l = List.map ~f:(function `String s -> s | _ -> invalid_arguments ()) l let source_or_build = function | "source" -> `Source | "build" -> `Build | _ -> invalid_arguments () let ml_or_mli = function | "ml" -> `ML | "mli" -> `MLI | _ -> invalid_arguments () let auto_ml_or_mli = function | "auto" -> `Auto | x -> ml_or_mli x let add_or_remove = function | "add" -> `Add | "remove" -> `Rem | _ -> invalid_arguments () let with_failures failures assoc = match failures with | `Ok -> assoc | `Failures failures -> let flags, extensions = List.fold_left failures ~init:([],[]) ~f:( fun (flgs, exts) (str,exn) -> match exn with | Arg.Bad _ -> str :: flgs, exts | Extension.Unknown -> flgs, str :: exts | _ -> assert false ) in let flags = match flags with | [] -> [] | failures -> let str = String.concat ~sep:", " failures in [ `String ("Unknown flags " ^ str) ] in let extensions = match extensions with | [] -> [] | failures -> let str = String.concat ~sep:", " failures in [ `String ("Unknown extensions " ^ str) ] in ("failures", `List (flags @ extensions)) :: assoc let document_of_json = let make kind path dot_merlins = {Context.dot_merlins; kind = auto_ml_or_mli kind; path = optional_string path; } in function | (`String "dot_merlin" :: `List dot_merlins :: `String kind :: opt_name) -> make kind opt_name (Some (string_list dot_merlins)) | (`String kind :: opt_name) -> make kind opt_name None | _ -> invalid_arguments () let request_of_json context = let request x = Request (context, x) in function | (`String "type" :: `String "expression" :: `String expr :: opt_pos) -> request (Query (Type_expr (expr, mandatory_position opt_pos))) | [`String "type"; `String "enclosing"; `Assoc [ "expr", `String expr ; "offset", `Int offset] ; jpos] -> request (Query (Type_enclosing (Some (expr, offset), pos_of_json jpos, None))) | [`String "type"; `String "enclosing"; `String "at"; jpos] -> request (Query (Type_enclosing (None, pos_of_json jpos, None))) | [ `String "case"; `String "analysis"; `String "from"; x; `String "to"; y ] -> request (Query (Case_analysis (pos_of_json x, pos_of_json y))) | [`String "enclosing"; jpos] -> request (Query (Enclosing (pos_of_json jpos))) | [`String "complete"; `String "prefix"; `String prefix; `String "at"; jpos] -> request (Query (Complete_prefix (prefix, pos_of_json jpos, [], false, true))) | [`String "complete"; `String "prefix"; `String prefix; `String "at"; jpos; `String "with"; `String "doc"] -> request (Query (Complete_prefix (prefix, pos_of_json jpos, [], true, true))) | [`String "expand"; `String "prefix"; `String prefix; `String "at"; jpos] -> request (Query (Expand_prefix (prefix, pos_of_json jpos, [], true))) | [`String "search"; `String "polarity"; `String query; `String "at"; jpos] -> request (Query (Polarity_search (query, pos_of_json jpos))) | (`String "document" :: (`String "" | `Null) :: pos) -> request (Query (Document (None, mandatory_position pos))) | (`String "document" :: `String path :: pos) -> request (Query (Document (Some path, mandatory_position pos))) | (`String "locate" :: (`String "" | `Null) :: `String choice :: pos) -> request (Query (Locate (None, ml_or_mli choice, mandatory_position pos))) | (`String "locate" :: `String path :: `String choice :: pos) -> request (Query (Locate (Some path, ml_or_mli choice, mandatory_position pos))) | (`String "jump" :: `String target :: pos) -> request (Query (Jump (target, mandatory_position pos))) | [`String "outline"] -> request (Query Outline) | [`String "shape"; pos] -> request (Query (Shape (pos_of_json pos))) | [`String "occurrences"; `String "ident"; `String "at"; jpos] -> request (Query (Occurrences (`Ident_at (pos_of_json jpos)))) | (`String ("reset"|"checkout") :: document) -> request (Sync (Checkout (document_of_json document))) | [`String "refresh"] -> request (Sync Refresh) | [`String "errors"] -> request (Query (Errors { lexing = true; parsing = true; typing = true })) | (`String "dump" :: args) -> request (Query (Dump args)) | [`String "which"; `String "path"; `String name] -> request (Query (Path_of_source [name])) | [`String "which"; `String "path"; `List names] -> request (Query (Path_of_source (string_list names))) | [`String "which"; `String "with_ext"; `String ext] -> request (Query (List_modules [ext])) | [`String "which"; `String "with_ext"; `List exts] -> request (Query (List_modules (string_list exts))) | [`String "flags" ; `String "set" ; `List flags ] -> request (Sync (Flags_set (string_list flags))) | [`String "flags" ; `String "get" ] -> request (Sync (Flags_get)) | [`String "find"; `String "use"; `List packages] | (`String "find" :: `String "use" :: packages) -> request (Sync (Findlib_use (string_list packages))) | [`String "find"; `String "list"] -> request (Query Findlib_list) | [`String "extension"; `String "enable"; `List extensions] -> request (Sync (Extension_set (`Enabled,string_list extensions))) | [`String "extension"; `String "disable"; `List extensions] -> request (Sync (Extension_set (`Disabled,string_list extensions))) | [`String "extension"; `String "list"] -> request (Query (Extension_list `All)) | [`String "extension"; `String "list"; `String "enabled"] -> request (Query (Extension_list `Enabled)) | [`String "extension"; `String "list"; `String "disabled"] -> request (Query (Extension_list `Disabled)) | [`String "path"; `String "list"; `String ("source"|"build" as var)] -> request (Query (Path_list (source_or_build var))) | [`String "path"; `String "reset"] -> request (Sync Path_reset) | (`String "path" :: `String ("add"|"remove" as action) :: `String ("source"|"build" as var) :: ((`List pathes :: []) | pathes)) -> request (Sync (Path (source_or_build var, add_or_remove action, string_list pathes))) | [`String "tell"; pos_start; pos_end; `String content] -> request (Sync (Tell (pos_of_json pos_start, pos_of_json pos_end, content))) | [`String "project"; `String "get"] -> request (Sync Project_get) | [`String "version"] -> request (Query Version) | [`String "protocol"; `String "version"] -> request (Sync (Protocol_version None)) | [`String "protocol"; `String "version"; `Int n] -> request (Sync (Protocol_version (Some n))) | _ -> invalid_arguments () let json_of_protocol_version : Old_protocol.protocol_version -> _ = function | `V2 -> `Int 2 | `V3 -> `Int 3 let json_of_sync_command (type a) (command : a sync_command) (response : a) : json = match command, response with | Tell _, () -> `Bool true | Checkout _, () -> `Bool true | Refresh, () -> `Bool true | Flags_get, flags -> `List (List.map ~f:Json.string flags) | Flags_set _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Findlib_use _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Extension_set _, failures -> `Assoc (with_failures failures ["result", `Bool true]) | Path _, () -> `Bool true | Path_reset, () -> `Bool true | Protocol_version _, (`Selected v, `Latest vm, version) -> `Assoc ["selected", json_of_protocol_version v; "latest", json_of_protocol_version vm; "merlin", `String version ] | Project_get, (strs, fails) -> let failures = match fails with | `Failures ((_::_) as fails) -> ["failures", `List (List.map ~f:Json.string fails)] | _ -> [] in `Assoc (("result", `List (List.map ~f:Json.string strs))::failures) | Idle_job, b -> `Bool b let classify_response = function | Failure s | Exception (Failure s) -> ("failure", `String s) | Error error -> ("error", error) | Exception exn -> begin match Location.error_of_exn exn with | Some (`Ok error) -> ("error", Query_json.json_of_error error) | None | Some `Already_displayed -> ("exception", `String (Printexc.to_string exn)) end | Return (Query cmd, response) -> ("return", Query_json.json_of_response cmd response) | Return (Sync cmd, response) -> ("return", json_of_sync_command cmd response) let json_of_response_v2 response = let class_, value = classify_response response in `List [`String class_; value] let json_of_response_v3 ~notifications response = let class_, value = classify_response response in `Assoc [ "class", `String class_; "value", value; "notifications", `List (List.map ~f:(fun { Logger.section; msg } -> `Assoc ["section", `String section; "message", `String msg]) notifications); ] let json_of_response notifications response = match !current_version with | `V2 -> json_of_response_v2 response | `V3 -> json_of_response_v3 ~notifications response let request_of_json = function | `Assoc _ as json -> let open Json.Util in let document = let value = member "document" json in let value = if value = `Null then member "context" json else value in if value = `Null then None else Some (to_list value |> document_of_json) in let printer_width = member "printer_width" json |> to_int_option in let printer_verbosity = member "printer_verbosity" json |> to_int_option in let context = {Context. document; printer_verbosity; printer_width} in let query = member "query" json |> to_list in request_of_json context query | `List jsons -> request_of_json default_context jsons | _ -> invalid_arguments () let make_json ?(on_read=ignore) ~input ~output () = let rec read buf len = on_read input; try Unix.read input buf 0 len with Unix.Unix_error (Unix.EINTR,_,_) -> read buf len in let lexbuf = Lexing.from_function read in let input = Json.stream_from_lexbuf (Json.init_lexer ()) lexbuf in let input () = try Some (Stream.next input) with Stream.Failure -> None in let output = Unix.out_channel_of_descr output in let output' = Json.to_channel output in let output json = output' json; output_char output '\n'; flush output in input, output let make_sexp ?on_read ~input ~output () = begin match begin try Some (Unix.openfile "/dev/null" [Unix.O_WRONLY] 0o600) with | Unix.Unix_error _ -> if Sys.os_type = "Win32" then try Some (Unix.openfile "NUL" [Unix.O_WRONLY] 0o600) with Unix.Unix_error _ -> None else None end with | None -> () | Some fd -> Unix.dup2 fd Unix.stderr; Unix.close fd end; let input' = Sexp.of_file_descr ?on_read input in let input' () = Option.map ~f:Sexp.to_json (input' ()) in let buf = Buffer.create 8192 in let output json = let sexp = Sexp.of_json json in Sexp.to_buf sexp buf; Buffer.add_char buf '\n'; let contents = Buffer.to_bytes buf in let rec write_contents n l = if l > 0 then let l' = Unix.write output contents n l in if l' > 0 then write_contents (n + l') (l - l') in write_contents 0 (Bytes.length contents); if Buffer.length buf > 100_000 then Buffer.reset buf else Buffer.clear buf in input', output
b26e6cfa23b614884204b35f4b601890da6edcd4133a01ff91b99198ffb6a3f7
psyeugenic/eplot
egd_chart.erl
%% Copyright ( C ) 2016 %% %% File: egd_chart.erl Author : Björn - Egil Dahlberg Created : 2016 - 05 - 02 %% -module(egd_chart). -export([graph/1, graph/2, bar2d/1, bar2d/2]). -export([smart_ticksize/3]). -type rgba() :: {byte(), byte(), byte(), byte()}. -record(chart, { type = png, render_engine = opaque, margin = 30 :: non_neg_integer(), % margin Graph boundingbox ( internal ) ibbx = undefined, ranges = {{0,0}, {100,100}}, % Data boundingbox width = 160 :: non_neg_integer(), % Total chart width height = 160 :: non_neg_integer(), % Total chart height dxdy = {1.0,1.0}, ticksize = {10,10}, precision = {2,2}, % colors bg_rgba = {230, 230, 255, 255} :: rgba(), margin_rgba = {255, 255, 255, 255} :: rgba(), graph_rgba = [], % ordered color convention % graph specific x_label = "X" :: string() | atom(), y_label = "Y" :: string() | atom(), graph_name_yo = 10 :: integer(), % Name offset from top graph_name_yh = 10 :: integer(), % Name drop offset graph_name_xo = 10 :: integer(), % Name offset from RHS % bar2d specific bar_width = 40, column_width = 40}). -define(float_error, 0.0000000000000001). graph/1 and graph/2 %% In: %% Data :: [{Graphname :: atom() | string(), [{X,Y}]}] %% Options :: [ %% % Metric options { width , integer ( ) } , ( 300 ) { height , integer ( ) } , ( 300 ) { margin , integer ( ) } , ( 30 ) %% { ticksize, { integer(), integer() }, %% { x_range, { float(), float() }, %% { y_range, { float(), float() }, %% %% % Naming options %% { x_label, string() | atom() }, %% { y_label, string() | atom() }, %% %% % Color options %% {bg_rgba, {byte(), byte(), byte()}} %% ] graph(Data) -> graph(Data, [{width,300},{height,300}]). graph(Data, Options) -> Chart = graph_chart(Options,Data), Im = egd:create(Chart#chart.width, Chart#chart.height), LightBlue = egd:color(Chart#chart.bg_rgba), {Pt1, Pt2} = Chart#chart.bbx, egd:filledRectangle(Im, Pt1, Pt2, LightBlue), % background % Fonts? Check for text enabling Font = load_font("6x11_latin1.wingsfont"), draw_graphs(Data, Chart, Im), % estetic crop, necessary? {{X0,Y0}, {X1,Y1}} = Chart#chart.bbx, W = Chart#chart.width, H = Chart#chart.height, White = egd:color(Chart#chart.margin_rgba), egd:filledRectangle(Im, {0,0}, {X0-1,H}, White), egd:filledRectangle(Im, {X1+1,0}, {W,H}, White), egd:filledRectangle(Im, {0,0}, {W,Y0-1}, White), egd:filledRectangle(Im, {0,Y1+1}, {W,H}, White), draw_ticks(Chart, Im, Font), draw crosshair draw_graph_names(Data, Chart, Font, Im), draw_xlabel(Chart, Im, Font), draw_ylabel(Chart, Im, Font), Png = egd:render(Im, Chart#chart.type, [{render_engine, Chart#chart.render_engine}]), egd:destroy(Im), try erlang:exit(Im, normal) catch _:_ -> ok end, Png. graph_chart(Opts, Data) -> {{X0,Y0}, {X1,Y1}} = proplists:get_value(ranges, Opts, ranges(Data)), Type = proplists:get_value(type, Opts, png), Width = proplists:get_value(width, Opts, 600), Height = proplists:get_value(height, Opts, 600), Xlabel = proplists:get_value(x_label, Opts, "X"), Ylabel = proplists:get_value(y_label, Opts, "Y"), %% multiple ways to set ranges XrangeMax = proplists:get_value(x_range_max, Opts, X1), XrangeMin = proplists:get_value(x_range_min, Opts, X0), YrangeMax = proplists:get_value(y_range_max, Opts, Y1), YrangeMin = proplists:get_value(y_range_min, Opts, Y0), {Xr0,Xr1} = proplists:get_value(x_range, Opts, {XrangeMin,XrangeMax}), {Yr0,Yr1} = proplists:get_value(y_range, Opts, {YrangeMin,YrangeMax}), Ranges = {{Xr0, Yr0}, {Xr1,Yr1}}, Precision = precision_level(Ranges, 10), {TsX,TsY} = smart_ticksize(Ranges, 10), XTicksize = proplists:get_value(x_ticksize, Opts, TsX), YTicksize = proplists:get_value(y_ticksize, Opts, TsY), Ticksize = proplists:get_value(ticksize, Opts, {XTicksize,YTicksize}), Margin = proplists:get_value(margin, Opts, 30), BGC = proplists:get_value(bg_rgba, Opts, {230,230, 255, 255}), Renderer = proplists:get_value(render_engine, Opts, opaque), BBX = {{Margin, Margin}, {Width - Margin, Height - Margin}}, DxDy = update_dxdy(Ranges,BBX), #chart{type = Type, width = Width, height = Height, x_label = Xlabel, y_label = Ylabel, ranges = Ranges, precision = Precision, ticksize = Ticksize, margin = Margin, bbx = BBX, dxdy = DxDy, render_engine = Renderer, bg_rgba = BGC}. draw_ylabel(Chart, Im, Font) -> Label = string(Chart#chart.y_label, 2), N = length(Label), {Fw,_Fh} = egd_font:size(Font), Width = N*Fw, {{Xbbx,Ybbx}, {_,_}} = Chart#chart.bbx, Pt = {Xbbx - trunc(Width/2), Ybbx - 20}, egd:text(Im, Pt, Font, Label, egd:color({0,0,0})). draw_xlabel(Chart, Im, Font) -> Label = string(Chart#chart.x_label, 2), N = length(Label), {Fw,_Fh} = egd_font:size(Font), Width = N*Fw, {{Xbbxl,_}, {Xbbxr,Ybbx}} = Chart#chart.bbx, Xc = trunc((Xbbxr - Xbbxl)/2) + Chart#chart.margin, Y = Ybbx + 20, Pt = {Xc - trunc(Width/2), Y}, egd:text(Im, Pt, Font, Label, egd:color({0,0,0})). draw_graphs(Datas, Chart, Im) -> draw_graphs(Datas, 0, Chart, Im). draw_graphs([],_,_,_) -> ok; draw_graphs([{_, Data}|Datas], ColorIndex, Chart, Im) -> Color = egd_colorscheme:select(default, ColorIndex), % convert data to graph data % fewer pass of xy2chart GraphData = [xy2chart(Pt, Chart) || Pt <- Data], draw_graph(GraphData, Color, Im), draw_graphs(Datas, ColorIndex + 1, Chart, Im). draw_graph([], _,_) -> ok; draw_graph([Pt1,Pt2|Data], Color, Im) -> draw_graph_dot(Pt1, Color, Im), draw_graph_line(Pt1,Pt2, Color, Im), draw_graph([Pt2|Data], Color, Im); draw_graph([Pt|Data], Color, Im) -> draw_graph_dot(Pt, Color, Im), draw_graph(Data, Color, Im). draw_graph_dot({X,Y}, Color, Im) -> egd:filledEllipse(Im, {X - 3, Y - 3}, {X + 3, Y + 3}, Color); draw_graph_dot({X,Y,Ey}, Color, Im) -> egd:line(Im, {X, Y - Ey}, {X, Y + Ey}, Color), egd:line(Im, {X - 4, Y - Ey}, {X + 4, Y - Ey}, Color), egd:line(Im, {X - 4, Y + Ey}, {X + 4, Y + Ey}, Color), egd:filledEllipse(Im, {X - 3, Y - 3}, {X + 3, Y + 3}, Color). draw_graph_line({X1,Y1,_},{X2,Y2,_}, Color, Im) -> egd:line(Im, {X1,Y1}, {X2,Y2}, Color); draw_graph_line(Pt1, Pt2, Color, Im) -> egd:line(Im, Pt1, Pt2, Color). %% name and color information draw_graph_names(Datas, Chart, Font, Im) -> draw_graph_names(Datas, 0, Chart, Font, Im, 0, Chart#chart.graph_name_yh). draw_graph_names([],_,_,_,_,_,_) -> ok; draw_graph_names([{Name, _}|Datas], ColorIndex, Chart, Font, Im, Yo, Yh) -> Color = egd_colorscheme:select(default, ColorIndex), draw_graph_name_color(Chart, Im, Font, Name, Color, Yo), draw_graph_names(Datas, ColorIndex + 1, Chart, Font, Im, Yo + Yh, Yh). draw_graph_name_color(#chart{bbx={{_,Y0},{X1,_}}}=Chart, Im, Font, Name, Color, Yh) -> Xo = Chart#chart.graph_name_xo, Yo = Chart#chart.graph_name_yo, Xl = 50, LPt1 = {X1 - Xo - Xl, Y0 + Yo + Yh}, LPt2 = {X1 - Xo, Y0 + Yo + Yh}, {Fw,Fh} = egd_font:size(Font), Str = string(Name,2), N = length(Str), TPt = {X1 - 2*Xo - Xl - Fw*N, Y0 + Yo + Yh - trunc(Fh/2) - 3}, egd:filledRectangle(Im, LPt1, LPt2, Color), egd:text(Im, TPt, Font, Str, egd:color({0,0,0})). %% origo crosshair draw_origo_lines(#chart{bbx={{X0,Y0},{X1,Y1}}}=Chart, Im) -> Black = egd:color({20,20,20}), Black1 = egd:color({50,50,50}), {X,Y} = xy2chart({0,0}, Chart), if X > X0, X < X1, Y > Y0, Y < Y1 -> egd:filledRectangle(Im, {X0,Y}, {X1,Y}, Black1), egd:filledRectangle(Im, {X,Y0}, {X,Y1}, Black1); true -> ok end, egd:rectangle(Im, {X0,Y0}, {X1,Y1}, Black), ok. % new ticks draw_ticks(Chart, Im, Font) -> {Xts, Yts} = Chart#chart.ticksize, {{Xmin,Ymin}, {Xmax,Ymax}} = Chart#chart.ranges, Ys = case Ymin of Ymin when Ymin < 0 -> trunc(Ymin/Yts) * Yts; _ -> (trunc(Ymin/Yts) + 1) * Yts end, Xs = case Xmin of Xmin when Xmin < 0 -> trunc(Xmin/Xts) * Xts; _ -> (trunc(Xmin/Xts) + 1) * Xts end, draw_yticks_lp(Im, Chart, Ys, Yts, Ymax, Font), draw_xticks_lp(Im, Chart, Xs, Xts, Xmax, Font). draw_yticks_lp(Im, Chart, Yi, Yts, Ymax, Font) when Yi < Ymax -> {_,Y} = xy2chart({0,Yi}, Chart), {{X,_}, _} = Chart#chart.bbx, {_, Precision} = Chart#chart.precision, draw_perf_ybar(Im, Chart, Y), egd:filledRectangle(Im, {X-2,Y}, {X+2,Y}, egd:color({0,0,0})), tick_text(Im, Font, Yi, {X,Y}, Precision, left), draw_yticks_lp(Im, Chart, Yi + Yts, Yts, Ymax, Font); draw_yticks_lp(_,_,_,_,_,_) -> ok. draw_xticks_lp(Im, Chart, Xi, Xts, Xmax, Font) when Xi < Xmax -> {X,_} = xy2chart({Xi,0}, Chart), {_, {_,Y}} = Chart#chart.bbx, { Precision, _} = Chart#chart.precision, draw_perf_xbar(Im, Chart, X), egd:filledRectangle(Im, {X,Y-2}, {X,Y+2}, egd:color({0,0,0})), tick_text(Im, Font, Xi, {X,Y}, Precision, below), draw_xticks_lp(Im, Chart, Xi + Xts, Xts, Xmax, Font); draw_xticks_lp(_,_,_,_,_,_) -> ok. tick_text(Im, Font, Tick, {X,Y}, Precision, Orientation) -> String = string(Tick, Precision), L = length(String), {Xl,Yl} = egd_font:size(Font), PxL = L*Xl, {Xo,Yo} = case Orientation of above -> {-round(PxL/2), -Yl - 3}; below -> {-round(PxL/2), 3}; left -> {round(-PxL - 4),-round(Yl/2) - 1}; right -> {3, -round(Yl/2)} end, egd:text(Im, {X + Xo,Y + Yo}, Font, String, egd:color({0,0,0})). % background tick bars, should be drawn with background draw_perf_ybar(Im, Chart, Yi) -> Pw = 5, Lw = 10, {{X0,_},{X1,_}} = Chart#chart.bbx, [Xl,Xr] = lists:sort([X0,X1]), Color = egd:color({180,180,190}), foreach_seq(fun(X) -> egd:filledRectangle(Im, {X,Yi}, {X+Pw, Yi}, Color) end, Xl,Xr,Lw), ok. draw_perf_xbar(Im, Chart, Xi) -> Pw = 5, Lw = 10, {{_,Y0},{_,Y1}} = Chart#chart.bbx, [Yu,Yl] = lists:sort([Y0,Y1]), Color = egd:color({130,130,130}), foreach_seq(fun(Y) -> egd:filledRectangle(Im, {Xi,Y}, {Xi, Y+Pw}, Color) end, Yu,Yl,Lw), ok. bar2d/1 and bar2d/2 %% In: Data : : [ { : : string ( ) , [ { Keyname : : atom ( ) | string ( ) , %% Value :: number()}]}] %% Datasetname = Name of this dataset (the color name) %% Keyname = The name of each grouping %% Options :: [{Key, Value}] Key = bar_width %% Key = column_width %% Colors? %% Abstract: %% The graph is devided into column where each column have one or more bars . %% Each column is associated with a name. %% Each bar may have a secondary name (a key). bar2d(Data) -> bar2d(Data, [{width, 600}, {height, 600}]). bar2d(Data0, Options) -> {ColorMap, Data} = bar2d_convert_data(Data0), Chart = bar2d_chart(Options, Data), Im = egd:create(Chart#chart.width, Chart#chart.height), LightBlue = egd:color(Chart#chart.bg_rgba), {Pt1, Pt2} = Chart#chart.bbx, egd:filledRectangle(Im, Pt1, Pt2, LightBlue), % background % Fonts? Check for text enabling Font = load_font("6x11_latin1.wingsfont"), draw_bar2d_ytick(Im, Chart, Font), % Color map texts for sets draw_bar2d_set_colormap(Im, Chart, Font, ColorMap), % Draw bars draw_bar2d_data(Data, Chart, Font, Im), egd:rectangle(Im, Pt1, Pt2, egd:color({0,0,0})), Png = egd:render(Im, Chart#chart.type, [{render_engine, Chart#chart.render_engine}]), egd:destroy(Im), try erlang:exit(Im, normal) catch _:_ -> ok end, Png. % [{Dataset, [{Key, Value}]}] -> [{Key, [{Dataset, Value}]}] bar2d_convert_data(Data) -> bar2d_convert_data(Data, 0,{[], []}). bar2d_convert_data([], _, {ColorMap, Out}) -> {lists:reverse(ColorMap), lists:sort(Out)}; bar2d_convert_data([{Set, KVs}|Data], ColorIndex, {ColorMap, Out}) -> Color = egd_colorscheme:select(default, ColorIndex), bar2d_convert_data(Data, ColorIndex + 1, {[{Set,Color}|ColorMap], bar2d_convert_data_kvs(KVs, Set, Color, Out)}). bar2d_convert_data_kvs([], _,_, Out) -> Out; bar2d_convert_data_kvs([{Key, Value,_} | KVs], Set, Color, Out) -> bar2d_convert_data_kvs([{Key, Value} | KVs], Set, Color, Out); bar2d_convert_data_kvs([{Key, Value}|KVs], Set, Color, Out) -> case proplists:get_value(Key, Out) of undefined -> bar2d_convert_data_kvs(KVs, Set, Color, [{Key,[{{Color, Set}, Value}]}|Out]); DVs -> bar2d_convert_data_kvs(KVs, Set, Color, [{Key,[{{Color, Set}, Value}|DVs]}|proplists:delete(Key, Out)]) end. % beta color map, static allocated bar2d_chart(Opts, Data) -> Values = lists:foldl(fun ({_, DVs}, Out) -> Vs = [V || {_,V} <- DVs], Out ++ Vs end, [], Data), Type = proplists:get_value(type, Opts, png), Margin = proplists:get_value(margin, Opts, 30), Width = proplists:get_value(width, Opts, 600), Height = proplists:get_value(height, Opts, 600), XrangeMax = proplists:get_value(x_range_max, Opts, length(Data)), XrangeMin = proplists:get_value(x_range_min, Opts, 0), YrangeMax = proplists:get_value(y_range_max, Opts, lists:max(Values)), YrangeMin = proplists:get_value(y_range_min, Opts, 0), {Yr0,Yr1} = proplists:get_value(y_range, Opts, {YrangeMin, YrangeMax}), {Xr0,Xr1} = proplists:get_value(x_range, Opts, {XrangeMin, XrangeMax}), Ranges = proplists:get_value(ranges, Opts, {{Xr0, Yr0}, {Xr1,Yr1}}), Ticksize = proplists:get_value(ticksize, Opts, smart_ticksize(Ranges, 10)), Cw = proplists:get_value(column_width, Opts, {ratio, 0.8}), Bw = proplists:get_value(bar_width, Opts, {ratio, 1.0}), InfoW = proplists:get_value(info_box, Opts, 0), Renderer = proplists:get_value(render_engine, Opts, opaque), % colors BGC = proplists:get_value(bg_rgba, Opts, {230, 230, 255, 255}), MGC = proplists:get_value(margin_rgba, Opts, {255, 255, 255, 255}), % bounding box IBBX = {{Width - Margin - InfoW, Margin}, {Width - Margin, Height - Margin}}, BBX = {{Margin, Margin}, {Width - Margin - InfoW - 10, Height - Margin}}, DxDy = update_dxdy(Ranges, BBX), #chart{type = Type, margin = Margin, width = Width, height = Height, ranges = Ranges, ticksize = Ticksize, bbx = BBX, ibbx = IBBX, dxdy = DxDy, column_width = Cw, bar_width = Bw, margin_rgba = MGC, bg_rgba = BGC, render_engine = Renderer}. draw_bar2d_set_colormap(Im, Chart, Font, ColorMap) -> Margin = Chart#chart.margin, draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {Margin, 3}, Margin). draw_bar2d_set_colormap(_, _, _, [], _, _) -> ok; draw_bar2d_set_colormap(Im, Chart, Font, [{Set, Color}|ColorMap], {X, Y}, Margin) -> String = string(Set, 2), egd:text(Im, {X + 10, Y}, Font, String, egd:color({0,0,0})), egd:filledRectangle(Im, {X,Y+3}, {X+5, Y+8}, Color), draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,Y}, Margin). draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,Y}, Margin) when (Y + 23) < Margin -> draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {X, Y + 12}, Margin); draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,_Y}, Margin) -> draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {X + 144, 3}, Margin). draw_bar2d_ytick(Im, Chart, Font) -> {_, Yts} = Chart#chart.ticksize, {{_, _}, {_, Ymax}} = Chart#chart.ranges, UPPER tick points draw_bar2d_yticks_up(Im, Chart, Yi, Yts, Ymax, Font) when Yi < Ymax -> {X, Y} = xy2chart({0,Yi}, Chart), {_, Precision} = Chart#chart.precision, draw_bar2d_ybar(Im, Chart, Y), egd:filledRectangle(Im, {X-2,Y}, {X+2,Y}, egd:color({0,0,0})), tick_text(Im, Font, Yi, {X,Y}, Precision, left), draw_bar2d_yticks_up(Im, Chart, Yi + Yts, Yts, Ymax, Font); draw_bar2d_yticks_up(_,_,_,_,_,_) -> ok. draw_bar2d_ybar(Im, Chart, Yi) -> Pw = 5, Lw = 10, {{X0,_},{X1,_}} = Chart#chart.bbx, [Xl,Xr] = lists:sort([X0,X1]), Color = egd:color({180,180,190}), foreach_seq(fun(X) -> egd:filledRectangle(Im, {X-Pw,Yi}, {X, Yi}, Color) end,Xl+Pw,Xr,Lw), ok. draw_bar2d_data(Columns, Chart, Font, Im) -> {{Xl,_}, {Xr,_}} = Chart#chart.bbx, Cn = length(Columns), % number of columns Co = (Xr - Xl)/(Cn), % column offset within chart Cx = Xl + Co/2, % start x of column draw_bar2d_data_columns(Columns, Chart, Font, Im, Cx, Co). draw_bar2d_data_columns([], _, _, _, _, _) -> ok; draw_bar2d_data_columns([{Name, Bars} | Columns], Chart, Font, Im, Cx, Co) -> {{_X0,_Y0}, {_X1,Y1}} = Chart#chart.bbx, Cwb = case Chart#chart.column_width of default -> Co; {ratio, P} when is_number(P) -> P*Co; Cw when is_number(Cw) -> lists:min([Cw,Co]) end, %% draw column text String = string(Name, 2), Ns = length(String), {Fw, Fh} = egd_font:size(Font), L = Fw*Ns, Tpt = {trunc(Cx - L/2 + 2), Y1 + Fh}, egd:text(Im, Tpt, Font, String, egd:color({0,0,0})), Bn = length(Bars), % number of bars Bo = Cwb/Bn, % bar offset within column Bx = Cx - Cwb/2 + Bo/2, % starting x of bar CS = 43, draw_bar2d_data_bars(Bars, Chart, Font, Im, Bx, Bo, CS), draw_bar2d_data_columns(Columns, Chart, Font, Im, Cx + Co, Co). draw_bar2d_data_bars([], _, _, _, _, _, _) -> ok; draw_bar2d_data_bars([{{Color,_Set}, Value}|Bars], Chart, Font, Im, Bx, Bo,CS) -> {{_X0,_Y0}, {_X1,Y1}} = Chart#chart.bbx, {_, Precision} = Chart#chart.precision, {_, Y} = xy2chart({0, Value}, Chart), Bwb = case Chart#chart.bar_width of default -> Bo; {ratio, P} when is_number(P) -> P*Bo; Bw when is_number(Bw) -> lists:min([Bw,Bo]) end, Black = egd:color({0,0,0}), % draw bar text String = string(Value, Precision), Ns = length(String), {Fw, Fh} = egd_font:size(Font), L = Fw*Ns, Tpt = {trunc(Bx - L/2 + 2), Y - Fh - 5}, egd:text(Im, Tpt, Font, String, Black), Pt1 = {trunc(Bx - Bwb/2), Y}, Pt2 = {trunc(Bx + Bwb/2), Y1}, egd:filledRectangle(Im, Pt1, Pt2, Color), egd:rectangle(Im, Pt1, Pt2, Black), draw_bar2d_data_bars(Bars, Chart, Font, Im, Bx + Bo, Bo, CS + CS). %%========================================================================== %% %% Aux functions %% %%========================================================================== xy2chart({X,Y}, #chart{ranges = {{Rx0,Ry0}, {_Rx1,_Ry1}}, bbx = {{Bx0,By0}, {_Bx1, By1}}, dxdy = {Dx, Dy}, margin = Margin}) -> {round(X*Dx + Bx0 - Rx0*Dx), round(By1 - (Y*Dy + By0 - Ry0*Dy - Margin))}; xy2chart({X,Y,Error}, Chart) -> {Xc,Yc} = xy2chart({X,Y}, #chart{ dxdy = {_,Dy} } = Chart), {Xc, Yc, round(Dy*Error)}. ranges([{_Name, Es}|Data]) when is_list(Es) -> Ranges = xy_minmax(Es), ranges(Data, Ranges). ranges([], Ranges) -> Ranges; ranges([{_Name, Es}|Data], CoRanges) when is_list(Es) -> Ranges = xy_minmax(Es), ranges(Data, xy_resulting_ranges(Ranges, CoRanges)). smart_ticksize({{X0, Y0}, {X1, Y1}}, N) -> {smart_ticksize(X0,X1,N), smart_ticksize(Y0,Y1,N)}. smart_ticksize(S, E, N) when is_number(S), is_number(E), is_number(N) -> % Calculate stepsize then 'humanize' the value to a human pleasing format. R = abs((E - S))/N, if abs(R) < ?float_error -> 2.0; true -> get the ratio on the form of 2 - 3 significant digits . P = precision_level(S, E, N), M = math:pow(10, P), Vsig = R*M, %% do magic Rsig = Vsig/50, Hsig = 50 * trunc(Rsig + 0.5), %% fin magic Hsig/M end; smart_ticksize(_, _, _) -> 2.0. precision_level({{X0, Y0}, {X1, Y1}}, N) -> { precision_level(X0,X1,N), precision_level(Y0,Y1,N)}. precision_level(S, E, N) when is_number(S), is_number(E) -> % Calculate stepsize then 'humanize' the value to a human pleasing format. R = abs((E - S))/N, if abs(R) < ?float_error -> 2; true -> get the ratio on the form of 2 - 3 significant digits . V = 2 - math:log10(R), trunc(V + 0.5) end; precision_level(_, _, _) -> 2. % on form [{X,Y}] | [{X,Y,E}] xy_minmax(Elements) -> {Xs, Ys} = lists:foldl(fun ({X,Y,_},{Xis, Yis}) -> {[X|Xis],[Y|Yis]}; ({X,Y}, {Xis, Yis}) -> {[X|Xis],[Y|Yis]} end, {[],[]}, Elements), {{lists:min(Xs),lists:min(Ys)},{lists:max(Xs), lists:max(Ys)}}. xy_resulting_ranges({{X0,Y0},{X1,Y1}},{{X2,Y2},{X3,Y3}}) -> {{lists:min([X0,X1,X2,X3]),lists:min([Y0,Y1,Y2,Y3])}, {lists:max([X0,X1,X2,X3]),lists:max([Y0,Y1,Y2,Y3])}}. update_dxdy({{Rx0, Ry0}, {Rx1, Ry1}}, {{Bx0,By0},{Bx1,By1}}) -> Dx = divide((Bx1 - Bx0),(Rx1 - Rx0)), Dy = divide((By1 - By0),(Ry1 - Ry0)), {Dx,Dy}. divide(_T,N) when abs(N) < ?float_error -> 0.0; divide(T,N) -> T/N. print_info_chart(Chart ) - > % io:format("Chart ->~n"), io : format ( " type : ~p ~ n " , [ Chart#chart.type ] ) , % io:format(" margin: ~p~n", [Chart#chart.margin]), % io:format(" bbx: ~p~n", [Chart#chart.bbx]), io : format ( " ticksize : ~p ~ n " , [ Chart#chart.ticksize ] ) , % io:format(" ranges: ~p~n", [Chart#chart.ranges]), % io:format(" width: ~p~n", [Chart#chart.width]), % io:format(" height: ~p~n", [Chart#chart.height]), % io:format(" dxdy: ~p~n", [Chart#chart.dxdy]), % ok. string(E, _P) when is_atom(E) -> atom_to_list(E); string(E, P) when is_float(E) -> float_to_maybe_integer_to_string(E, P); string(E, _P) when is_integer(E) -> s("~w", [E]); string(E, _P) when is_binary(E) -> lists:flatten(binary_to_list(E)); string(E, _P) when is_list(E) -> s("~s", [E]). float_to_maybe_integer_to_string(F, P) -> I = trunc(F), A = abs(I - F), if A < ?float_error -> s("~w", [I]); % integer true -> s(s("~~.~wf", [P]), [F]) % float end. s(Format, Terms) -> lists:flatten(io_lib:format(Format, Terms)). foreach_seq(Fun, First, Last, Inc) -> if Inc > 0, First - Inc =< Last; Inc < 0, First - Inc >= Last -> N = (Last - First + Inc) div Inc, foreach_seq_loop(N, First, Inc, Fun); First =:= Last -> foreach_seq_loop(1, First, Inc, Fun) end. foreach_seq_loop(0, _, _, _) -> ok; foreach_seq_loop(N, I, Inc, Fun) -> _ = Fun(I), foreach_seq_loop(N-1, I+Inc, Inc, Fun). load_font(Font) -> case erl_prim_loader:get_file(filename:join([code:priv_dir(eplot),"fonts",Font])) of {ok,FontBinary,_} -> %% archive egd_font:load_binary(FontBinary); _ -> {ok,FontBinary,_} = erl_prim_loader:get_file(filename:join([code:priv_dir(eplot),"eplot/priv/fonts",Font])), egd_font:load_binary(FontBinary) end.
null
https://raw.githubusercontent.com/psyeugenic/eplot/5d0d45b0afd38f10d430e4547cea4fd82f444d7e/src/egd_chart.erl
erlang
File: egd_chart.erl margin Data boundingbox Total chart width Total chart height colors ordered color convention graph specific Name offset from top Name drop offset Name offset from RHS bar2d specific In: Data :: [{Graphname :: atom() | string(), [{X,Y}]}] Options :: [ % Metric options { ticksize, { integer(), integer() }, { x_range, { float(), float() }, { y_range, { float(), float() }, % Naming options { x_label, string() | atom() }, { y_label, string() | atom() }, % Color options {bg_rgba, {byte(), byte(), byte()}} ] background Fonts? Check for text enabling estetic crop, necessary? multiple ways to set ranges convert data to graph data fewer pass of xy2chart name and color information origo crosshair new ticks background tick bars, should be drawn with background In: Value :: number()}]}] Datasetname = Name of this dataset (the color name) Keyname = The name of each grouping Options :: [{Key, Value}] Key = column_width Colors? Abstract: The graph is devided into column where each column have Each column is associated with a name. Each bar may have a secondary name (a key). background Fonts? Check for text enabling Color map texts for sets Draw bars [{Dataset, [{Key, Value}]}] -> [{Key, [{Dataset, Value}]}] beta color map, static allocated colors bounding box number of columns column offset within chart start x of column draw column text number of bars bar offset within column starting x of bar draw bar text ========================================================================== Aux functions ========================================================================== Calculate stepsize then 'humanize' the value to a human pleasing format. do magic fin magic Calculate stepsize then 'humanize' the value to a human pleasing format. on form [{X,Y}] | [{X,Y,E}] io:format("Chart ->~n"), io:format(" margin: ~p~n", [Chart#chart.margin]), io:format(" bbx: ~p~n", [Chart#chart.bbx]), io:format(" ranges: ~p~n", [Chart#chart.ranges]), io:format(" width: ~p~n", [Chart#chart.width]), io:format(" height: ~p~n", [Chart#chart.height]), io:format(" dxdy: ~p~n", [Chart#chart.dxdy]), ok. integer float archive
Copyright ( C ) 2016 Author : Björn - Egil Dahlberg Created : 2016 - 05 - 02 -module(egd_chart). -export([graph/1, graph/2, bar2d/1, bar2d/2]). -export([smart_ticksize/3]). -type rgba() :: {byte(), byte(), byte(), byte()}. -record(chart, { type = png, render_engine = opaque, Graph boundingbox ( internal ) ibbx = undefined, dxdy = {1.0,1.0}, ticksize = {10,10}, precision = {2,2}, bg_rgba = {230, 230, 255, 255} :: rgba(), margin_rgba = {255, 255, 255, 255} :: rgba(), x_label = "X" :: string() | atom(), y_label = "Y" :: string() | atom(), bar_width = 40, column_width = 40}). -define(float_error, 0.0000000000000001). graph/1 and graph/2 { width , integer ( ) } , ( 300 ) { height , integer ( ) } , ( 300 ) { margin , integer ( ) } , ( 30 ) graph(Data) -> graph(Data, [{width,300},{height,300}]). graph(Data, Options) -> Chart = graph_chart(Options,Data), Im = egd:create(Chart#chart.width, Chart#chart.height), LightBlue = egd:color(Chart#chart.bg_rgba), {Pt1, Pt2} = Chart#chart.bbx, Font = load_font("6x11_latin1.wingsfont"), draw_graphs(Data, Chart, Im), {{X0,Y0}, {X1,Y1}} = Chart#chart.bbx, W = Chart#chart.width, H = Chart#chart.height, White = egd:color(Chart#chart.margin_rgba), egd:filledRectangle(Im, {0,0}, {X0-1,H}, White), egd:filledRectangle(Im, {X1+1,0}, {W,H}, White), egd:filledRectangle(Im, {0,0}, {W,Y0-1}, White), egd:filledRectangle(Im, {0,Y1+1}, {W,H}, White), draw_ticks(Chart, Im, Font), draw crosshair draw_graph_names(Data, Chart, Font, Im), draw_xlabel(Chart, Im, Font), draw_ylabel(Chart, Im, Font), Png = egd:render(Im, Chart#chart.type, [{render_engine, Chart#chart.render_engine}]), egd:destroy(Im), try erlang:exit(Im, normal) catch _:_ -> ok end, Png. graph_chart(Opts, Data) -> {{X0,Y0}, {X1,Y1}} = proplists:get_value(ranges, Opts, ranges(Data)), Type = proplists:get_value(type, Opts, png), Width = proplists:get_value(width, Opts, 600), Height = proplists:get_value(height, Opts, 600), Xlabel = proplists:get_value(x_label, Opts, "X"), Ylabel = proplists:get_value(y_label, Opts, "Y"), XrangeMax = proplists:get_value(x_range_max, Opts, X1), XrangeMin = proplists:get_value(x_range_min, Opts, X0), YrangeMax = proplists:get_value(y_range_max, Opts, Y1), YrangeMin = proplists:get_value(y_range_min, Opts, Y0), {Xr0,Xr1} = proplists:get_value(x_range, Opts, {XrangeMin,XrangeMax}), {Yr0,Yr1} = proplists:get_value(y_range, Opts, {YrangeMin,YrangeMax}), Ranges = {{Xr0, Yr0}, {Xr1,Yr1}}, Precision = precision_level(Ranges, 10), {TsX,TsY} = smart_ticksize(Ranges, 10), XTicksize = proplists:get_value(x_ticksize, Opts, TsX), YTicksize = proplists:get_value(y_ticksize, Opts, TsY), Ticksize = proplists:get_value(ticksize, Opts, {XTicksize,YTicksize}), Margin = proplists:get_value(margin, Opts, 30), BGC = proplists:get_value(bg_rgba, Opts, {230,230, 255, 255}), Renderer = proplists:get_value(render_engine, Opts, opaque), BBX = {{Margin, Margin}, {Width - Margin, Height - Margin}}, DxDy = update_dxdy(Ranges,BBX), #chart{type = Type, width = Width, height = Height, x_label = Xlabel, y_label = Ylabel, ranges = Ranges, precision = Precision, ticksize = Ticksize, margin = Margin, bbx = BBX, dxdy = DxDy, render_engine = Renderer, bg_rgba = BGC}. draw_ylabel(Chart, Im, Font) -> Label = string(Chart#chart.y_label, 2), N = length(Label), {Fw,_Fh} = egd_font:size(Font), Width = N*Fw, {{Xbbx,Ybbx}, {_,_}} = Chart#chart.bbx, Pt = {Xbbx - trunc(Width/2), Ybbx - 20}, egd:text(Im, Pt, Font, Label, egd:color({0,0,0})). draw_xlabel(Chart, Im, Font) -> Label = string(Chart#chart.x_label, 2), N = length(Label), {Fw,_Fh} = egd_font:size(Font), Width = N*Fw, {{Xbbxl,_}, {Xbbxr,Ybbx}} = Chart#chart.bbx, Xc = trunc((Xbbxr - Xbbxl)/2) + Chart#chart.margin, Y = Ybbx + 20, Pt = {Xc - trunc(Width/2), Y}, egd:text(Im, Pt, Font, Label, egd:color({0,0,0})). draw_graphs(Datas, Chart, Im) -> draw_graphs(Datas, 0, Chart, Im). draw_graphs([],_,_,_) -> ok; draw_graphs([{_, Data}|Datas], ColorIndex, Chart, Im) -> Color = egd_colorscheme:select(default, ColorIndex), GraphData = [xy2chart(Pt, Chart) || Pt <- Data], draw_graph(GraphData, Color, Im), draw_graphs(Datas, ColorIndex + 1, Chart, Im). draw_graph([], _,_) -> ok; draw_graph([Pt1,Pt2|Data], Color, Im) -> draw_graph_dot(Pt1, Color, Im), draw_graph_line(Pt1,Pt2, Color, Im), draw_graph([Pt2|Data], Color, Im); draw_graph([Pt|Data], Color, Im) -> draw_graph_dot(Pt, Color, Im), draw_graph(Data, Color, Im). draw_graph_dot({X,Y}, Color, Im) -> egd:filledEllipse(Im, {X - 3, Y - 3}, {X + 3, Y + 3}, Color); draw_graph_dot({X,Y,Ey}, Color, Im) -> egd:line(Im, {X, Y - Ey}, {X, Y + Ey}, Color), egd:line(Im, {X - 4, Y - Ey}, {X + 4, Y - Ey}, Color), egd:line(Im, {X - 4, Y + Ey}, {X + 4, Y + Ey}, Color), egd:filledEllipse(Im, {X - 3, Y - 3}, {X + 3, Y + 3}, Color). draw_graph_line({X1,Y1,_},{X2,Y2,_}, Color, Im) -> egd:line(Im, {X1,Y1}, {X2,Y2}, Color); draw_graph_line(Pt1, Pt2, Color, Im) -> egd:line(Im, Pt1, Pt2, Color). draw_graph_names(Datas, Chart, Font, Im) -> draw_graph_names(Datas, 0, Chart, Font, Im, 0, Chart#chart.graph_name_yh). draw_graph_names([],_,_,_,_,_,_) -> ok; draw_graph_names([{Name, _}|Datas], ColorIndex, Chart, Font, Im, Yo, Yh) -> Color = egd_colorscheme:select(default, ColorIndex), draw_graph_name_color(Chart, Im, Font, Name, Color, Yo), draw_graph_names(Datas, ColorIndex + 1, Chart, Font, Im, Yo + Yh, Yh). draw_graph_name_color(#chart{bbx={{_,Y0},{X1,_}}}=Chart, Im, Font, Name, Color, Yh) -> Xo = Chart#chart.graph_name_xo, Yo = Chart#chart.graph_name_yo, Xl = 50, LPt1 = {X1 - Xo - Xl, Y0 + Yo + Yh}, LPt2 = {X1 - Xo, Y0 + Yo + Yh}, {Fw,Fh} = egd_font:size(Font), Str = string(Name,2), N = length(Str), TPt = {X1 - 2*Xo - Xl - Fw*N, Y0 + Yo + Yh - trunc(Fh/2) - 3}, egd:filledRectangle(Im, LPt1, LPt2, Color), egd:text(Im, TPt, Font, Str, egd:color({0,0,0})). draw_origo_lines(#chart{bbx={{X0,Y0},{X1,Y1}}}=Chart, Im) -> Black = egd:color({20,20,20}), Black1 = egd:color({50,50,50}), {X,Y} = xy2chart({0,0}, Chart), if X > X0, X < X1, Y > Y0, Y < Y1 -> egd:filledRectangle(Im, {X0,Y}, {X1,Y}, Black1), egd:filledRectangle(Im, {X,Y0}, {X,Y1}, Black1); true -> ok end, egd:rectangle(Im, {X0,Y0}, {X1,Y1}, Black), ok. draw_ticks(Chart, Im, Font) -> {Xts, Yts} = Chart#chart.ticksize, {{Xmin,Ymin}, {Xmax,Ymax}} = Chart#chart.ranges, Ys = case Ymin of Ymin when Ymin < 0 -> trunc(Ymin/Yts) * Yts; _ -> (trunc(Ymin/Yts) + 1) * Yts end, Xs = case Xmin of Xmin when Xmin < 0 -> trunc(Xmin/Xts) * Xts; _ -> (trunc(Xmin/Xts) + 1) * Xts end, draw_yticks_lp(Im, Chart, Ys, Yts, Ymax, Font), draw_xticks_lp(Im, Chart, Xs, Xts, Xmax, Font). draw_yticks_lp(Im, Chart, Yi, Yts, Ymax, Font) when Yi < Ymax -> {_,Y} = xy2chart({0,Yi}, Chart), {{X,_}, _} = Chart#chart.bbx, {_, Precision} = Chart#chart.precision, draw_perf_ybar(Im, Chart, Y), egd:filledRectangle(Im, {X-2,Y}, {X+2,Y}, egd:color({0,0,0})), tick_text(Im, Font, Yi, {X,Y}, Precision, left), draw_yticks_lp(Im, Chart, Yi + Yts, Yts, Ymax, Font); draw_yticks_lp(_,_,_,_,_,_) -> ok. draw_xticks_lp(Im, Chart, Xi, Xts, Xmax, Font) when Xi < Xmax -> {X,_} = xy2chart({Xi,0}, Chart), {_, {_,Y}} = Chart#chart.bbx, { Precision, _} = Chart#chart.precision, draw_perf_xbar(Im, Chart, X), egd:filledRectangle(Im, {X,Y-2}, {X,Y+2}, egd:color({0,0,0})), tick_text(Im, Font, Xi, {X,Y}, Precision, below), draw_xticks_lp(Im, Chart, Xi + Xts, Xts, Xmax, Font); draw_xticks_lp(_,_,_,_,_,_) -> ok. tick_text(Im, Font, Tick, {X,Y}, Precision, Orientation) -> String = string(Tick, Precision), L = length(String), {Xl,Yl} = egd_font:size(Font), PxL = L*Xl, {Xo,Yo} = case Orientation of above -> {-round(PxL/2), -Yl - 3}; below -> {-round(PxL/2), 3}; left -> {round(-PxL - 4),-round(Yl/2) - 1}; right -> {3, -round(Yl/2)} end, egd:text(Im, {X + Xo,Y + Yo}, Font, String, egd:color({0,0,0})). draw_perf_ybar(Im, Chart, Yi) -> Pw = 5, Lw = 10, {{X0,_},{X1,_}} = Chart#chart.bbx, [Xl,Xr] = lists:sort([X0,X1]), Color = egd:color({180,180,190}), foreach_seq(fun(X) -> egd:filledRectangle(Im, {X,Yi}, {X+Pw, Yi}, Color) end, Xl,Xr,Lw), ok. draw_perf_xbar(Im, Chart, Xi) -> Pw = 5, Lw = 10, {{_,Y0},{_,Y1}} = Chart#chart.bbx, [Yu,Yl] = lists:sort([Y0,Y1]), Color = egd:color({130,130,130}), foreach_seq(fun(Y) -> egd:filledRectangle(Im, {Xi,Y}, {Xi, Y+Pw}, Color) end, Yu,Yl,Lw), ok. bar2d/1 and bar2d/2 Data : : [ { : : string ( ) , [ { Keyname : : atom ( ) | string ( ) , Key = bar_width one or more bars . bar2d(Data) -> bar2d(Data, [{width, 600}, {height, 600}]). bar2d(Data0, Options) -> {ColorMap, Data} = bar2d_convert_data(Data0), Chart = bar2d_chart(Options, Data), Im = egd:create(Chart#chart.width, Chart#chart.height), LightBlue = egd:color(Chart#chart.bg_rgba), {Pt1, Pt2} = Chart#chart.bbx, Font = load_font("6x11_latin1.wingsfont"), draw_bar2d_ytick(Im, Chart, Font), draw_bar2d_set_colormap(Im, Chart, Font, ColorMap), draw_bar2d_data(Data, Chart, Font, Im), egd:rectangle(Im, Pt1, Pt2, egd:color({0,0,0})), Png = egd:render(Im, Chart#chart.type, [{render_engine, Chart#chart.render_engine}]), egd:destroy(Im), try erlang:exit(Im, normal) catch _:_ -> ok end, Png. bar2d_convert_data(Data) -> bar2d_convert_data(Data, 0,{[], []}). bar2d_convert_data([], _, {ColorMap, Out}) -> {lists:reverse(ColorMap), lists:sort(Out)}; bar2d_convert_data([{Set, KVs}|Data], ColorIndex, {ColorMap, Out}) -> Color = egd_colorscheme:select(default, ColorIndex), bar2d_convert_data(Data, ColorIndex + 1, {[{Set,Color}|ColorMap], bar2d_convert_data_kvs(KVs, Set, Color, Out)}). bar2d_convert_data_kvs([], _,_, Out) -> Out; bar2d_convert_data_kvs([{Key, Value,_} | KVs], Set, Color, Out) -> bar2d_convert_data_kvs([{Key, Value} | KVs], Set, Color, Out); bar2d_convert_data_kvs([{Key, Value}|KVs], Set, Color, Out) -> case proplists:get_value(Key, Out) of undefined -> bar2d_convert_data_kvs(KVs, Set, Color, [{Key,[{{Color, Set}, Value}]}|Out]); DVs -> bar2d_convert_data_kvs(KVs, Set, Color, [{Key,[{{Color, Set}, Value}|DVs]}|proplists:delete(Key, Out)]) end. bar2d_chart(Opts, Data) -> Values = lists:foldl(fun ({_, DVs}, Out) -> Vs = [V || {_,V} <- DVs], Out ++ Vs end, [], Data), Type = proplists:get_value(type, Opts, png), Margin = proplists:get_value(margin, Opts, 30), Width = proplists:get_value(width, Opts, 600), Height = proplists:get_value(height, Opts, 600), XrangeMax = proplists:get_value(x_range_max, Opts, length(Data)), XrangeMin = proplists:get_value(x_range_min, Opts, 0), YrangeMax = proplists:get_value(y_range_max, Opts, lists:max(Values)), YrangeMin = proplists:get_value(y_range_min, Opts, 0), {Yr0,Yr1} = proplists:get_value(y_range, Opts, {YrangeMin, YrangeMax}), {Xr0,Xr1} = proplists:get_value(x_range, Opts, {XrangeMin, XrangeMax}), Ranges = proplists:get_value(ranges, Opts, {{Xr0, Yr0}, {Xr1,Yr1}}), Ticksize = proplists:get_value(ticksize, Opts, smart_ticksize(Ranges, 10)), Cw = proplists:get_value(column_width, Opts, {ratio, 0.8}), Bw = proplists:get_value(bar_width, Opts, {ratio, 1.0}), InfoW = proplists:get_value(info_box, Opts, 0), Renderer = proplists:get_value(render_engine, Opts, opaque), BGC = proplists:get_value(bg_rgba, Opts, {230, 230, 255, 255}), MGC = proplists:get_value(margin_rgba, Opts, {255, 255, 255, 255}), IBBX = {{Width - Margin - InfoW, Margin}, {Width - Margin, Height - Margin}}, BBX = {{Margin, Margin}, {Width - Margin - InfoW - 10, Height - Margin}}, DxDy = update_dxdy(Ranges, BBX), #chart{type = Type, margin = Margin, width = Width, height = Height, ranges = Ranges, ticksize = Ticksize, bbx = BBX, ibbx = IBBX, dxdy = DxDy, column_width = Cw, bar_width = Bw, margin_rgba = MGC, bg_rgba = BGC, render_engine = Renderer}. draw_bar2d_set_colormap(Im, Chart, Font, ColorMap) -> Margin = Chart#chart.margin, draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {Margin, 3}, Margin). draw_bar2d_set_colormap(_, _, _, [], _, _) -> ok; draw_bar2d_set_colormap(Im, Chart, Font, [{Set, Color}|ColorMap], {X, Y}, Margin) -> String = string(Set, 2), egd:text(Im, {X + 10, Y}, Font, String, egd:color({0,0,0})), egd:filledRectangle(Im, {X,Y+3}, {X+5, Y+8}, Color), draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,Y}, Margin). draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,Y}, Margin) when (Y + 23) < Margin -> draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {X, Y + 12}, Margin); draw_bar2d_set_colormap_step(Im, Chart, Font, ColorMap, {X,_Y}, Margin) -> draw_bar2d_set_colormap(Im, Chart, Font, ColorMap, {X + 144, 3}, Margin). draw_bar2d_ytick(Im, Chart, Font) -> {_, Yts} = Chart#chart.ticksize, {{_, _}, {_, Ymax}} = Chart#chart.ranges, UPPER tick points draw_bar2d_yticks_up(Im, Chart, Yi, Yts, Ymax, Font) when Yi < Ymax -> {X, Y} = xy2chart({0,Yi}, Chart), {_, Precision} = Chart#chart.precision, draw_bar2d_ybar(Im, Chart, Y), egd:filledRectangle(Im, {X-2,Y}, {X+2,Y}, egd:color({0,0,0})), tick_text(Im, Font, Yi, {X,Y}, Precision, left), draw_bar2d_yticks_up(Im, Chart, Yi + Yts, Yts, Ymax, Font); draw_bar2d_yticks_up(_,_,_,_,_,_) -> ok. draw_bar2d_ybar(Im, Chart, Yi) -> Pw = 5, Lw = 10, {{X0,_},{X1,_}} = Chart#chart.bbx, [Xl,Xr] = lists:sort([X0,X1]), Color = egd:color({180,180,190}), foreach_seq(fun(X) -> egd:filledRectangle(Im, {X-Pw,Yi}, {X, Yi}, Color) end,Xl+Pw,Xr,Lw), ok. draw_bar2d_data(Columns, Chart, Font, Im) -> {{Xl,_}, {Xr,_}} = Chart#chart.bbx, draw_bar2d_data_columns(Columns, Chart, Font, Im, Cx, Co). draw_bar2d_data_columns([], _, _, _, _, _) -> ok; draw_bar2d_data_columns([{Name, Bars} | Columns], Chart, Font, Im, Cx, Co) -> {{_X0,_Y0}, {_X1,Y1}} = Chart#chart.bbx, Cwb = case Chart#chart.column_width of default -> Co; {ratio, P} when is_number(P) -> P*Co; Cw when is_number(Cw) -> lists:min([Cw,Co]) end, String = string(Name, 2), Ns = length(String), {Fw, Fh} = egd_font:size(Font), L = Fw*Ns, Tpt = {trunc(Cx - L/2 + 2), Y1 + Fh}, egd:text(Im, Tpt, Font, String, egd:color({0,0,0})), CS = 43, draw_bar2d_data_bars(Bars, Chart, Font, Im, Bx, Bo, CS), draw_bar2d_data_columns(Columns, Chart, Font, Im, Cx + Co, Co). draw_bar2d_data_bars([], _, _, _, _, _, _) -> ok; draw_bar2d_data_bars([{{Color,_Set}, Value}|Bars], Chart, Font, Im, Bx, Bo,CS) -> {{_X0,_Y0}, {_X1,Y1}} = Chart#chart.bbx, {_, Precision} = Chart#chart.precision, {_, Y} = xy2chart({0, Value}, Chart), Bwb = case Chart#chart.bar_width of default -> Bo; {ratio, P} when is_number(P) -> P*Bo; Bw when is_number(Bw) -> lists:min([Bw,Bo]) end, Black = egd:color({0,0,0}), String = string(Value, Precision), Ns = length(String), {Fw, Fh} = egd_font:size(Font), L = Fw*Ns, Tpt = {trunc(Bx - L/2 + 2), Y - Fh - 5}, egd:text(Im, Tpt, Font, String, Black), Pt1 = {trunc(Bx - Bwb/2), Y}, Pt2 = {trunc(Bx + Bwb/2), Y1}, egd:filledRectangle(Im, Pt1, Pt2, Color), egd:rectangle(Im, Pt1, Pt2, Black), draw_bar2d_data_bars(Bars, Chart, Font, Im, Bx + Bo, Bo, CS + CS). xy2chart({X,Y}, #chart{ranges = {{Rx0,Ry0}, {_Rx1,_Ry1}}, bbx = {{Bx0,By0}, {_Bx1, By1}}, dxdy = {Dx, Dy}, margin = Margin}) -> {round(X*Dx + Bx0 - Rx0*Dx), round(By1 - (Y*Dy + By0 - Ry0*Dy - Margin))}; xy2chart({X,Y,Error}, Chart) -> {Xc,Yc} = xy2chart({X,Y}, #chart{ dxdy = {_,Dy} } = Chart), {Xc, Yc, round(Dy*Error)}. ranges([{_Name, Es}|Data]) when is_list(Es) -> Ranges = xy_minmax(Es), ranges(Data, Ranges). ranges([], Ranges) -> Ranges; ranges([{_Name, Es}|Data], CoRanges) when is_list(Es) -> Ranges = xy_minmax(Es), ranges(Data, xy_resulting_ranges(Ranges, CoRanges)). smart_ticksize({{X0, Y0}, {X1, Y1}}, N) -> {smart_ticksize(X0,X1,N), smart_ticksize(Y0,Y1,N)}. smart_ticksize(S, E, N) when is_number(S), is_number(E), is_number(N) -> R = abs((E - S))/N, if abs(R) < ?float_error -> 2.0; true -> get the ratio on the form of 2 - 3 significant digits . P = precision_level(S, E, N), M = math:pow(10, P), Vsig = R*M, Rsig = Vsig/50, Hsig = 50 * trunc(Rsig + 0.5), Hsig/M end; smart_ticksize(_, _, _) -> 2.0. precision_level({{X0, Y0}, {X1, Y1}}, N) -> { precision_level(X0,X1,N), precision_level(Y0,Y1,N)}. precision_level(S, E, N) when is_number(S), is_number(E) -> R = abs((E - S))/N, if abs(R) < ?float_error -> 2; true -> get the ratio on the form of 2 - 3 significant digits . V = 2 - math:log10(R), trunc(V + 0.5) end; precision_level(_, _, _) -> 2. xy_minmax(Elements) -> {Xs, Ys} = lists:foldl(fun ({X,Y,_},{Xis, Yis}) -> {[X|Xis],[Y|Yis]}; ({X,Y}, {Xis, Yis}) -> {[X|Xis],[Y|Yis]} end, {[],[]}, Elements), {{lists:min(Xs),lists:min(Ys)},{lists:max(Xs), lists:max(Ys)}}. xy_resulting_ranges({{X0,Y0},{X1,Y1}},{{X2,Y2},{X3,Y3}}) -> {{lists:min([X0,X1,X2,X3]),lists:min([Y0,Y1,Y2,Y3])}, {lists:max([X0,X1,X2,X3]),lists:max([Y0,Y1,Y2,Y3])}}. update_dxdy({{Rx0, Ry0}, {Rx1, Ry1}}, {{Bx0,By0},{Bx1,By1}}) -> Dx = divide((Bx1 - Bx0),(Rx1 - Rx0)), Dy = divide((By1 - By0),(Ry1 - Ry0)), {Dx,Dy}. divide(_T,N) when abs(N) < ?float_error -> 0.0; divide(T,N) -> T/N. print_info_chart(Chart ) - > io : format ( " type : ~p ~ n " , [ Chart#chart.type ] ) , io : format ( " ticksize : ~p ~ n " , [ Chart#chart.ticksize ] ) , string(E, _P) when is_atom(E) -> atom_to_list(E); string(E, P) when is_float(E) -> float_to_maybe_integer_to_string(E, P); string(E, _P) when is_integer(E) -> s("~w", [E]); string(E, _P) when is_binary(E) -> lists:flatten(binary_to_list(E)); string(E, _P) when is_list(E) -> s("~s", [E]). float_to_maybe_integer_to_string(F, P) -> I = trunc(F), A = abs(I - F), end. s(Format, Terms) -> lists:flatten(io_lib:format(Format, Terms)). foreach_seq(Fun, First, Last, Inc) -> if Inc > 0, First - Inc =< Last; Inc < 0, First - Inc >= Last -> N = (Last - First + Inc) div Inc, foreach_seq_loop(N, First, Inc, Fun); First =:= Last -> foreach_seq_loop(1, First, Inc, Fun) end. foreach_seq_loop(0, _, _, _) -> ok; foreach_seq_loop(N, I, Inc, Fun) -> _ = Fun(I), foreach_seq_loop(N-1, I+Inc, Inc, Fun). load_font(Font) -> case erl_prim_loader:get_file(filename:join([code:priv_dir(eplot),"fonts",Font])) of {ok,FontBinary,_} -> egd_font:load_binary(FontBinary); _ -> {ok,FontBinary,_} = erl_prim_loader:get_file(filename:join([code:priv_dir(eplot),"eplot/priv/fonts",Font])), egd_font:load_binary(FontBinary) end.
b0b4e8b32cf190c9f9a39ec9393cf72cb6865d25d73b959f56667a3677f68493
bytekid/mkbtt
termIndex.ml
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * 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 MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt 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 MKBtt. If not, see </>. *) * module type for term indexing @author @since 2009/06/26 @author Sarah Winkler @since 2009/06/26 *) (*** OPENS ***************************************************************) open Util;; (*** MODULES *************************************************************) module Pos = Rewriting.Position;; module Term = U.Term;; module M = U.Monad;; (*** SUBMODULES **********************************************************) module type ENTRY_TYPE = sig type t val compare : t -> t -> int val to_string : t -> string end module type T = sig type entry type t val make : unit -> t val insert : t -> (Term.t * entry) -> t M.t val delete : t -> (Term.t * entry) -> t M.t val variant_candidates : t -> Term.t -> (entry list) M.t val generalization_candidates : t -> Term.t -> (entry list) M.t val unification_candidates : t -> Term.t -> (entry list) M.t val encompassment_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val encompassment_candidates_below_root : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap2_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap1_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap1_candidates_below_root : t -> Term.t -> ((entry * Pos.t) list) M.t val size : t -> int M.t val is_empty : t -> bool M.t end module TermEntry = struct type t = Term.t let compare = Term.compare let to_string t = Term.to_string t end module type TERMINDEX = T with type entry = TermEntry.t module EntryList = functor (Entry: ENTRY_TYPE) -> struct let lex f g (a, b) (a', b') = let c = f a a' in if c <> 0 then c else g b b' ;; let cmp = Entry.compare;; let inter = List.intersect ~c:cmp;; let union = List.union ~c:cmp;; let add x = union [x] let pair_union = List.union ~c:(lex cmp Pos.compare);; let diff = List.diff ~c:cmp;; let pair_diff = List.diff ~c:(lex cmp Pos.compare);; let mem = List.mem ~c:cmp;; let remove = List.remove ~c:cmp;; let pair_remove = List.remove ~c:(lex cmp Pos.compare);; let map_union f = List.fold_left union [] <.> (List.map f);; let pair_map_union f = List.fold_left pair_union [] <.> (List.map f);; let equal = List.equal ~c:cmp;; let pair_equal = List.equal ~c:(lex cmp Pos.compare);; end
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/termindexing/termIndex.ml
ocaml
** OPENS ************************************************************** ** MODULES ************************************************************ ** SUBMODULES *********************************************************
Copyright 2010 * GNU Lesser General Public License * * This file is part of MKBtt . * * is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * 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 MKBtt . If not , see < / > . * GNU Lesser General Public License * * This file is part of MKBtt. * * MKBtt is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * MKBtt 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 MKBtt. If not, see </>. *) * module type for term indexing @author @since 2009/06/26 @author Sarah Winkler @since 2009/06/26 *) open Util;; module Pos = Rewriting.Position;; module Term = U.Term;; module M = U.Monad;; module type ENTRY_TYPE = sig type t val compare : t -> t -> int val to_string : t -> string end module type T = sig type entry type t val make : unit -> t val insert : t -> (Term.t * entry) -> t M.t val delete : t -> (Term.t * entry) -> t M.t val variant_candidates : t -> Term.t -> (entry list) M.t val generalization_candidates : t -> Term.t -> (entry list) M.t val unification_candidates : t -> Term.t -> (entry list) M.t val encompassment_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val encompassment_candidates_below_root : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap2_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap1_candidates : t -> Term.t -> ((entry * Pos.t) list) M.t val overlap1_candidates_below_root : t -> Term.t -> ((entry * Pos.t) list) M.t val size : t -> int M.t val is_empty : t -> bool M.t end module TermEntry = struct type t = Term.t let compare = Term.compare let to_string t = Term.to_string t end module type TERMINDEX = T with type entry = TermEntry.t module EntryList = functor (Entry: ENTRY_TYPE) -> struct let lex f g (a, b) (a', b') = let c = f a a' in if c <> 0 then c else g b b' ;; let cmp = Entry.compare;; let inter = List.intersect ~c:cmp;; let union = List.union ~c:cmp;; let add x = union [x] let pair_union = List.union ~c:(lex cmp Pos.compare);; let diff = List.diff ~c:cmp;; let pair_diff = List.diff ~c:(lex cmp Pos.compare);; let mem = List.mem ~c:cmp;; let remove = List.remove ~c:cmp;; let pair_remove = List.remove ~c:(lex cmp Pos.compare);; let map_union f = List.fold_left union [] <.> (List.map f);; let pair_map_union f = List.fold_left pair_union [] <.> (List.map f);; let equal = List.equal ~c:cmp;; let pair_equal = List.equal ~c:(lex cmp Pos.compare);; end
4c18b3db60887fbe8cd1a6061cb918cae65eeab5bfe65afbf1d1942b7f27e3b3
rems-project/cerberus
tests.ml
open Global_ocaml open Core module E = Exception (* use this to print a halting error message *) let error str = prerr_endline $ Colour.ansi_format [Colour.Red] ("ERROR: " ^ str); exit 1 (* The return type of Core_run.run *) type execution_result_full = Driver_ocaml.execution_result (* The type we use to compare results of executions *) type execution_result = (string Pset.set, Errors.t9) Exception.t3 (* We forget the order of the results *) let simplify_result (result : execution_result_full) : execution_result = match result with | Result l1 -> Result (Pset.from_list Stdlib.compare (List.map String_core.string_of_expr l1) ) | Exception e -> Exception e let pp_execution_result (result:execution_result) : string = match result with | E.Result s -> "{" ^ (String.concat ", " (Pset.elements s)) ^ "}" | E.Exception e -> Pp_errors.to_string e type test_result = (unit, string) Exception.t3 let compare_results (expected:execution_result) (actual_full:execution_result_full) : test_result = let actual: execution_result = simplify_result actual_full in let expected_str = pp_execution_result expected in let actual_str = pp_execution_result actual in if expected_str = actual_str then E.Result () else E.Exception ("Expected: " ^ expected_str ^ ". " ^ "Actual: " ^ actual_str ^ ".") if expected = actual then ( ) else E.Exception ( " Expected : " ^ ( pp_execution_result expected ) ^ " . " ^ " Actual : " ^ ( pp_execution_result actual ) ^ " . " ) if expected = actual then E.Result () else E.Exception ("Expected: " ^ (pp_execution_result expected) ^ ". " ^ "Actual: " ^ (pp_execution_result actual) ^ ".") *) type test = { file_name: string; expected_result: execution_result; } let get_test (file_name:string) (def_results:int list) (undef_results:Undefined.undefined_behaviour list): test = let def_results2 = List.map (fun x -> Econst (Naive_memory.MV_integer (Symbolic.SYMBconst (Nat_big_num.of_int x) ) ) ) def_results in let undef_results2 = List.map (fun x -> Eundef x) undef_results in let results_full = E.Result (def_results2 @ undef_results2) in let results_simplified = simplify_result results_full in {file_name= file_name; expected_result= results_simplified; } let get_tests: test list = Core programs get_test "tests/concurrency/coherence+rel_rel_acq.core" [1] []; get_test "tests/concurrency/coherence+init+rel_acq.core" [1] []; get_test "tests/concurrency/datarace+Rna+Rna.core" [0] []; get_test "tests/concurrency/datarace+Wna+Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Rna+Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Rna+Rna_Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Wna_rel+acq_Rna.core" [1] [Undefined.Data_race]; get_test "tests/concurrency/hb-mo-cycle+rel_rel_acq+rel_rel_acq.core" [0; 1; 2; 3] []; get_test "tests/concurrency/hb-mo-cycle+Wsc_Wsc_Rsc+Wsc_Wsc_Rsc.core" [1; 2; 3] []; get_test "tests/concurrency/MP+na_rel+acq_na.core" [1; 2] []; get_test "tests/concurrency/LB+acq_rel+acq_rel.core" [0; 1; 2] []; get_test "tests/concurrency/LB+Rsc_Wsc+Rsc_Wsc.core" [0; 1; 2] []; get_test "tests/concurrency/LB+rlx_rlx+rlx_rlx.core" [0; 1; 2; 3] []; get_test "tests/concurrency/SB+rel_acq+rel_acq.core" [0; 1; 2; 3] []; get_test "tests/concurrency/SB+Wsc_Rsc+Wsc_Rsc.core" [1; 2; 3] []; get_test "tests/concurrency/WRC+rel+acq_rel+acq_acq.core" [1; 2] []; get_test " tests / concurrency / RMW - strong - equal.core " [ 5 ] [ ] ; get_test " tests / concurrency / RMW - strong - unequal.core " [ 0 ] [ ] ; get_test " tests / concurrency / RMW - weak - equal.core " [ 0 ; 5 ] [ ] ; get_test " tests / concurrency / RMW - weak - unequal.core " [ 0 ] [ ] ; get_test "tests/concurrency/IRIW+rel+rel+acq_acq+acq_acq.core" [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15] []; get_test "tests/concurrency/IRIW+Wsc+Wsc+Rsc_Rsc+Rsc_Rsc.core" [0; 1; 2; 3; 4; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15] []; (* C programs *) get_test " tests / concurrency / MP+na_rel+acq_na.c " [ 1 ; 2 ] [ ] ; get_test " tests / concurrency / LB+acq_rel+acq_rel.c " [ 0 ; 1 ; 2 ] [ ] ; get_test " tests / concurrency / SB+rel_acq+rel_acq.c " [ 0 ; 1 ; 2 ; 3 ] [ ] ]
null
https://raw.githubusercontent.com/rems-project/cerberus/e0f817cebf331b1d9f741c1f82e129c93c99f33c/backend/common/tests.ml
ocaml
use this to print a halting error message The return type of Core_run.run The type we use to compare results of executions We forget the order of the results C programs
open Global_ocaml open Core module E = Exception let error str = prerr_endline $ Colour.ansi_format [Colour.Red] ("ERROR: " ^ str); exit 1 type execution_result_full = Driver_ocaml.execution_result type execution_result = (string Pset.set, Errors.t9) Exception.t3 let simplify_result (result : execution_result_full) : execution_result = match result with | Result l1 -> Result (Pset.from_list Stdlib.compare (List.map String_core.string_of_expr l1) ) | Exception e -> Exception e let pp_execution_result (result:execution_result) : string = match result with | E.Result s -> "{" ^ (String.concat ", " (Pset.elements s)) ^ "}" | E.Exception e -> Pp_errors.to_string e type test_result = (unit, string) Exception.t3 let compare_results (expected:execution_result) (actual_full:execution_result_full) : test_result = let actual: execution_result = simplify_result actual_full in let expected_str = pp_execution_result expected in let actual_str = pp_execution_result actual in if expected_str = actual_str then E.Result () else E.Exception ("Expected: " ^ expected_str ^ ". " ^ "Actual: " ^ actual_str ^ ".") if expected = actual then ( ) else E.Exception ( " Expected : " ^ ( pp_execution_result expected ) ^ " . " ^ " Actual : " ^ ( pp_execution_result actual ) ^ " . " ) if expected = actual then E.Result () else E.Exception ("Expected: " ^ (pp_execution_result expected) ^ ". " ^ "Actual: " ^ (pp_execution_result actual) ^ ".") *) type test = { file_name: string; expected_result: execution_result; } let get_test (file_name:string) (def_results:int list) (undef_results:Undefined.undefined_behaviour list): test = let def_results2 = List.map (fun x -> Econst (Naive_memory.MV_integer (Symbolic.SYMBconst (Nat_big_num.of_int x) ) ) ) def_results in let undef_results2 = List.map (fun x -> Eundef x) undef_results in let results_full = E.Result (def_results2 @ undef_results2) in let results_simplified = simplify_result results_full in {file_name= file_name; expected_result= results_simplified; } let get_tests: test list = Core programs get_test "tests/concurrency/coherence+rel_rel_acq.core" [1] []; get_test "tests/concurrency/coherence+init+rel_acq.core" [1] []; get_test "tests/concurrency/datarace+Rna+Rna.core" [0] []; get_test "tests/concurrency/datarace+Wna+Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Rna+Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Rna+Rna_Wna.core" [] [Undefined.Data_race]; get_test "tests/concurrency/datarace+Wna_rel+acq_Rna.core" [1] [Undefined.Data_race]; get_test "tests/concurrency/hb-mo-cycle+rel_rel_acq+rel_rel_acq.core" [0; 1; 2; 3] []; get_test "tests/concurrency/hb-mo-cycle+Wsc_Wsc_Rsc+Wsc_Wsc_Rsc.core" [1; 2; 3] []; get_test "tests/concurrency/MP+na_rel+acq_na.core" [1; 2] []; get_test "tests/concurrency/LB+acq_rel+acq_rel.core" [0; 1; 2] []; get_test "tests/concurrency/LB+Rsc_Wsc+Rsc_Wsc.core" [0; 1; 2] []; get_test "tests/concurrency/LB+rlx_rlx+rlx_rlx.core" [0; 1; 2; 3] []; get_test "tests/concurrency/SB+rel_acq+rel_acq.core" [0; 1; 2; 3] []; get_test "tests/concurrency/SB+Wsc_Rsc+Wsc_Rsc.core" [1; 2; 3] []; get_test "tests/concurrency/WRC+rel+acq_rel+acq_acq.core" [1; 2] []; get_test " tests / concurrency / RMW - strong - equal.core " [ 5 ] [ ] ; get_test " tests / concurrency / RMW - strong - unequal.core " [ 0 ] [ ] ; get_test " tests / concurrency / RMW - weak - equal.core " [ 0 ; 5 ] [ ] ; get_test " tests / concurrency / RMW - weak - unequal.core " [ 0 ] [ ] ; get_test "tests/concurrency/IRIW+rel+rel+acq_acq+acq_acq.core" [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15] []; get_test "tests/concurrency/IRIW+Wsc+Wsc+Rsc_Rsc+Rsc_Rsc.core" [0; 1; 2; 3; 4; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15] []; get_test " tests / concurrency / MP+na_rel+acq_na.c " [ 1 ; 2 ] [ ] ; get_test " tests / concurrency / LB+acq_rel+acq_rel.c " [ 0 ; 1 ; 2 ] [ ] ; get_test " tests / concurrency / SB+rel_acq+rel_acq.c " [ 0 ; 1 ; 2 ; 3 ] [ ] ]
62973babc7b112b5bf2b2b0fd46dc9ec5b5ce26407a0b9a106ea538c4f6e0fe8
lavcraft/xmonad-config
xmobar.hs
Config { font = "xft:Droid Sans Mono:size=9:bold:antialias=true" bgColor = "#000000", fgColor = "#ffffff", position = Static { xpos = 0, ypos = 0, width = 1920, height = 16 }, lowerOnStart = True, commands = [ Run Weather " UUDD " [ " -t","<station > : < tempC > C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue " ] 36000 Run Weather "UUDD" ["-t","<tempC>°C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue"] 36000 ,Run Memory ["-t","<used>/<total>M (<cache>M)","-H","8192","-L","4096","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC"] 10 ,Run DynNetwork [ "-t" ,"<dev> rx:<rx>, tx:<tx>" ,"-H" ,"200" ,"-L" ,"10" ,"-h" ,"#FFB6B0" ,"-l" ,"#CEFFAC" ,"-n" ,"#FFFFCC" , "-c" , " " , "-w" , "2" , "-S" , "True" ] 10 ,Run Date "%Y.%m.%d %H:%M:%S" "date" 10 ,Run MultiCpu [ "--template" , "<autototal>" , "--Low" , "50" -- units: % , "--High" , "85" -- units: % , "--low" , "gray" , "--normal" , "darkorange" , "--high" , "darkred" , "-c" , " " , "-w" , "3" ] 10 ,Run PipeReader "/tmp/.volume-pipe" "vol" ,Run CoreTemp [ "--template" , "<core0> <core1> <core2> <core3> <core4>°C" , "--Low" , "70" -- units: °C , "--High" , "80" -- units: °C , "--low" , "darkgreen" , "--normal" , "darkorange" , "--high" , "darkred" ] 50 ,Run StdinReader ], sepChar = "%", alignSep = "}{", template = "%StdinReader% }{ <icon=/home/tolkv/.sysgit/dzen/bitmaps/music.xbm/> %vol% | %coretemp% | %multicpu% | %memory% | %dynnetwork% | %UUDD% | <fc=#FFFFCC>%date%</fc> " }
null
https://raw.githubusercontent.com/lavcraft/xmonad-config/7c0ce77526bfba4067d617ff91c6134c39c9be46/home/.xmonad/xmobar.hs
haskell
units: % units: % units: °C units: °C
Config { font = "xft:Droid Sans Mono:size=9:bold:antialias=true" bgColor = "#000000", fgColor = "#ffffff", position = Static { xpos = 0, ypos = 0, width = 1920, height = 16 }, lowerOnStart = True, commands = [ Run Weather " UUDD " [ " -t","<station > : < tempC > C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue " ] 36000 Run Weather "UUDD" ["-t","<tempC>°C","-L","18","-H","25","--normal","green","--high","red","--low","lightblue"] 36000 ,Run Memory ["-t","<used>/<total>M (<cache>M)","-H","8192","-L","4096","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC"] 10 ,Run DynNetwork [ "-t" ,"<dev> rx:<rx>, tx:<tx>" ,"-H" ,"200" ,"-L" ,"10" ,"-h" ,"#FFB6B0" ,"-l" ,"#CEFFAC" ,"-n" ,"#FFFFCC" , "-c" , " " , "-w" , "2" , "-S" , "True" ] 10 ,Run Date "%Y.%m.%d %H:%M:%S" "date" 10 ,Run MultiCpu [ "--template" , "<autototal>" , "--low" , "gray" , "--normal" , "darkorange" , "--high" , "darkred" , "-c" , " " , "-w" , "3" ] 10 ,Run PipeReader "/tmp/.volume-pipe" "vol" ,Run CoreTemp [ "--template" , "<core0> <core1> <core2> <core3> <core4>°C" , "--low" , "darkgreen" , "--normal" , "darkorange" , "--high" , "darkred" ] 50 ,Run StdinReader ], sepChar = "%", alignSep = "}{", template = "%StdinReader% }{ <icon=/home/tolkv/.sysgit/dzen/bitmaps/music.xbm/> %vol% | %coretemp% | %multicpu% | %memory% | %dynnetwork% | %UUDD% | <fc=#FFFFCC>%date%</fc> " }
1d63f98caaea3d9a03aee137a6c19a14ca2fdcd48c8ba88f0ebb3989756a353f
nodew/haskell-dapr
StateManagement.hs
-- | Module : . Client . HttpClient . StateManagement -- Description : Manages Dapr state -- Copyright : (c) -- License : Apache-2.0 This module manages Dapr state module Dapr.Client.HttpClient.StateManagement ( getState, getBulkState, saveState, deleteState, executeStateTransaction, queryState, ) where import Dapr.Client.HttpClient.Internal import Dapr.Client.HttpClient.Req import Dapr.Core.Types import Data.Aeson import Data.Bifunctor (bimap) import Data.Either.Extra (mapLeft) import qualified Data.Text as T import qualified Data.Text.Encoding as T import GHC.Generics (Generic) import Network.HTTP.Req data BulkStateRequestPayload = BulkStateRequestPayload { keys :: [StateKey], parallelism :: Int } deriving (Eq, Show, Generic, ToJSON) data ExecuteStateTransactionRequestPayload a = ExecuteStateTransactionRequestPayload { operations :: [TransactionalStateOperation a], metadata :: ExtendedMetadata } deriving (Eq, Show, Generic, ToJSON) | Tries to save the provided list of ` SaveStateRequest`s to the configured . saveState :: (ToJSON a) => SaveStateRequest a -> DaprHttpClient (Either DaprClientError ()) saveState SaveStateRequest {..} = do let url = ["state", getStoreName stateStore] response <- makeHttpRequest POST url (ReqBodyJson stateItems) ignoreResponse mempty return $ bimap DaprHttpException (const ()) response | Gets the current value associated with ` StateKey ` from the configured . getState :: (FromJSON a) => GetStateRequest -> DaprHttpClient (Either DaprClientError a) getState GetStateRequest {..} = do let url = ["state", getStoreName stateStore, getStateKey stateKey] metadataQueryParam = mapMetadataToQueryParam stateMetadata options = metadataQueryParam <> queryParam "consistency" (show <$> stateConsitency) response <- makeHttpRequest GET url NoReqBody lbsResponse options return $ case response of Right response' -> case responseStatusCode response' of 200 -> mapLeft (JsonDecodeError . T.pack) $ eitherDecode (responseBody response') 204 -> Left NotFound _ -> Left UnknownError Left e -> Left $ DaprHttpException e | Gets the values associated with provided list of ` StateKey`s from the configured in bulk . getBulkState :: (FromJSON a) => GetBulkStateRequest -> DaprHttpClient (Either DaprClientError (GetBulkStateResponse a)) getBulkState GetBulkStateRequest {..} = do let url = ["state", getStoreName stateStore, "bulk"] metadataQueryParam = mapMetadataToQueryParam stateMetadata response <- makeHttpRequest POST url (ReqBodyJson (BulkStateRequestPayload stateKeys stateParallelism)) jsonResponse metadataQueryParam return $ bimap DaprHttpException (GetBulkStateResponse . responseBody) response | Deletes the value associated with provided ` StateKey ` from the configured . deleteState :: DeleteStateRequest -> DaprHttpClient (Either DaprClientError ()) deleteState DeleteStateRequest {..} = do let url = ["state", getStoreName stateStore, getStateKey stateKey] metadataQueryParam = mapMetadataToQueryParam stateMetadata params = metadataQueryParam <> queryParam "concurrency" (show . concurrency <$> stateOption) <> queryParam "consistency" (show . consistency <$> stateOption) options = maybe mempty (header "If-Match" . T.encodeUtf8 . getEtagValue) stateEtag <> params response <- makeHttpRequest DELETE url NoReqBody ignoreResponse options return $ bimap DaprHttpException (const ()) response | Saves the provided trasaction of type ` StateTransaction ` to the configured store . executeStateTransaction :: (ToJSON a) => ExecuteStateTransactionRequest a -> DaprHttpClient (Either DaprClientError ()) executeStateTransaction ExecuteStateTransactionRequest {..} = do let url = ["state", getStoreName stateStore, "transaction"] response <- makeHttpRequest POST url (ReqBodyJson (ExecuteStateTransactionRequestPayload stateOperations stateMetadata)) ignoreResponse mempty return $ bimap DaprHttpException (const ()) response -- | Queries the specified state store with the given query of type `StateQuery`. Note that underlying state store must support queries. queryState :: (FromJSON a) => QueryStateRequest -> DaprHttpClient (Either DaprClientError (QueryStateResponse a)) queryState QueryStateRequest {..} = do let url = ["state", getStoreName stateStore, "query"] metadataQueryParam = mapMetadataToQueryParam stateMetadata response <- makeHttpRequest POST url (ReqBodyJson stateQuery) jsonResponse metadataQueryParam return $ bimap DaprHttpException responseBody response
null
https://raw.githubusercontent.com/nodew/haskell-dapr/7e3a47835b479f5a54f79bbe3fce303428e55c75/dapr-http-client/src/Dapr/Client/HttpClient/StateManagement.hs
haskell
| Description : Manages Dapr state Copyright : (c) License : Apache-2.0 | Queries the specified state store with the given query of type `StateQuery`. Note that underlying state store must support queries.
Module : . Client . HttpClient . StateManagement This module manages Dapr state module Dapr.Client.HttpClient.StateManagement ( getState, getBulkState, saveState, deleteState, executeStateTransaction, queryState, ) where import Dapr.Client.HttpClient.Internal import Dapr.Client.HttpClient.Req import Dapr.Core.Types import Data.Aeson import Data.Bifunctor (bimap) import Data.Either.Extra (mapLeft) import qualified Data.Text as T import qualified Data.Text.Encoding as T import GHC.Generics (Generic) import Network.HTTP.Req data BulkStateRequestPayload = BulkStateRequestPayload { keys :: [StateKey], parallelism :: Int } deriving (Eq, Show, Generic, ToJSON) data ExecuteStateTransactionRequestPayload a = ExecuteStateTransactionRequestPayload { operations :: [TransactionalStateOperation a], metadata :: ExtendedMetadata } deriving (Eq, Show, Generic, ToJSON) | Tries to save the provided list of ` SaveStateRequest`s to the configured . saveState :: (ToJSON a) => SaveStateRequest a -> DaprHttpClient (Either DaprClientError ()) saveState SaveStateRequest {..} = do let url = ["state", getStoreName stateStore] response <- makeHttpRequest POST url (ReqBodyJson stateItems) ignoreResponse mempty return $ bimap DaprHttpException (const ()) response | Gets the current value associated with ` StateKey ` from the configured . getState :: (FromJSON a) => GetStateRequest -> DaprHttpClient (Either DaprClientError a) getState GetStateRequest {..} = do let url = ["state", getStoreName stateStore, getStateKey stateKey] metadataQueryParam = mapMetadataToQueryParam stateMetadata options = metadataQueryParam <> queryParam "consistency" (show <$> stateConsitency) response <- makeHttpRequest GET url NoReqBody lbsResponse options return $ case response of Right response' -> case responseStatusCode response' of 200 -> mapLeft (JsonDecodeError . T.pack) $ eitherDecode (responseBody response') 204 -> Left NotFound _ -> Left UnknownError Left e -> Left $ DaprHttpException e | Gets the values associated with provided list of ` StateKey`s from the configured in bulk . getBulkState :: (FromJSON a) => GetBulkStateRequest -> DaprHttpClient (Either DaprClientError (GetBulkStateResponse a)) getBulkState GetBulkStateRequest {..} = do let url = ["state", getStoreName stateStore, "bulk"] metadataQueryParam = mapMetadataToQueryParam stateMetadata response <- makeHttpRequest POST url (ReqBodyJson (BulkStateRequestPayload stateKeys stateParallelism)) jsonResponse metadataQueryParam return $ bimap DaprHttpException (GetBulkStateResponse . responseBody) response | Deletes the value associated with provided ` StateKey ` from the configured . deleteState :: DeleteStateRequest -> DaprHttpClient (Either DaprClientError ()) deleteState DeleteStateRequest {..} = do let url = ["state", getStoreName stateStore, getStateKey stateKey] metadataQueryParam = mapMetadataToQueryParam stateMetadata params = metadataQueryParam <> queryParam "concurrency" (show . concurrency <$> stateOption) <> queryParam "consistency" (show . consistency <$> stateOption) options = maybe mempty (header "If-Match" . T.encodeUtf8 . getEtagValue) stateEtag <> params response <- makeHttpRequest DELETE url NoReqBody ignoreResponse options return $ bimap DaprHttpException (const ()) response | Saves the provided trasaction of type ` StateTransaction ` to the configured store . executeStateTransaction :: (ToJSON a) => ExecuteStateTransactionRequest a -> DaprHttpClient (Either DaprClientError ()) executeStateTransaction ExecuteStateTransactionRequest {..} = do let url = ["state", getStoreName stateStore, "transaction"] response <- makeHttpRequest POST url (ReqBodyJson (ExecuteStateTransactionRequestPayload stateOperations stateMetadata)) ignoreResponse mempty return $ bimap DaprHttpException (const ()) response queryState :: (FromJSON a) => QueryStateRequest -> DaprHttpClient (Either DaprClientError (QueryStateResponse a)) queryState QueryStateRequest {..} = do let url = ["state", getStoreName stateStore, "query"] metadataQueryParam = mapMetadataToQueryParam stateMetadata response <- makeHttpRequest POST url (ReqBodyJson stateQuery) jsonResponse metadataQueryParam return $ bimap DaprHttpException responseBody response
9b43c5f1127aa22b05f12ced77bbf9c73970745e6c33dbc5912c02d5315113b2
brendanhay/gogol
Update.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . ShoppingContent . Content . . Update Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- -- Updates the shipping settings of the account. Any fields that are not provided are deleted from the resource. -- /See:/ < API for Shopping Reference > for @content.shippingsettings.update@. module Gogol.ShoppingContent.Content.Shippingsettings.Update ( -- * Resource ContentShippingsettingsUpdateResource, -- ** Constructing a Request ContentShippingsettingsUpdate (..), newContentShippingsettingsUpdate, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types | A resource alias for @content.shippingsettings.update@ method which the ' ContentShippingsettingsUpdate ' request conforms to . type ContentShippingsettingsUpdateResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "shippingsettings" Core.:> Core.Capture "accountId" Core.Word64 Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] ShippingSettings Core.:> Core.Put '[Core.JSON] ShippingSettings -- | Updates the shipping settings of the account. Any fields that are not provided are deleted from the resource. -- -- /See:/ 'newContentShippingsettingsUpdate' smart constructor. data ContentShippingsettingsUpdate = ContentShippingsettingsUpdate { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), -- | The ID of the account for which to get\/update shipping settings. accountId :: Core.Word64, | JSONP callback :: (Core.Maybe Core.Text), | The ID of the managing account . If this parameter is not the same as accountId , then this account must be a multi - client account and @accountId@ must be the ID of a sub - account of this account . merchantId :: Core.Word64, -- | Multipart request metadata. payload :: ShippingSettings, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentShippingsettingsUpdate ' with the minimum fields required to make a request . newContentShippingsettingsUpdate :: -- | The ID of the account for which to get\/update shipping settings. See 'accountId'. Core.Word64 -> | The ID of the managing account . If this parameter is not the same as accountId , then this account must be a multi - client account and @accountId@ must be the ID of a sub - account of this account . See ' merchantId ' . Core.Word64 -> -- | Multipart request metadata. See 'payload'. ShippingSettings -> ContentShippingsettingsUpdate newContentShippingsettingsUpdate accountId merchantId payload = ContentShippingsettingsUpdate { xgafv = Core.Nothing, accessToken = Core.Nothing, accountId = accountId, callback = Core.Nothing, merchantId = merchantId, payload = payload, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentShippingsettingsUpdate where type Rs ContentShippingsettingsUpdate = ShippingSettings type Scopes ContentShippingsettingsUpdate = '[Content'FullControl] requestClient ContentShippingsettingsUpdate {..} = go merchantId accountId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) payload shoppingContentService where go = Core.buildClient ( Core.Proxy :: Core.Proxy ContentShippingsettingsUpdateResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-shopping-content/gen/Gogol/ShoppingContent/Content/Shippingsettings/Update.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated Updates the shipping settings of the account. Any fields that are not provided are deleted from the resource. * Resource ** Constructing a Request | Updates the shipping settings of the account. Any fields that are not provided are deleted from the resource. /See:/ 'newContentShippingsettingsUpdate' smart constructor. | V1 error format. | OAuth access token. | The ID of the account for which to get\/update shipping settings. | Multipart request metadata. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | The ID of the account for which to get\/update shipping settings. See 'accountId'. | Multipart request metadata. See 'payload'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . ShoppingContent . Content . . Update Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) /See:/ < API for Shopping Reference > for @content.shippingsettings.update@. module Gogol.ShoppingContent.Content.Shippingsettings.Update ContentShippingsettingsUpdateResource, ContentShippingsettingsUpdate (..), newContentShippingsettingsUpdate, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types | A resource alias for @content.shippingsettings.update@ method which the ' ContentShippingsettingsUpdate ' request conforms to . type ContentShippingsettingsUpdateResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "shippingsettings" Core.:> Core.Capture "accountId" Core.Word64 Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] ShippingSettings Core.:> Core.Put '[Core.JSON] ShippingSettings data ContentShippingsettingsUpdate = ContentShippingsettingsUpdate xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), accountId :: Core.Word64, | JSONP callback :: (Core.Maybe Core.Text), | The ID of the managing account . If this parameter is not the same as accountId , then this account must be a multi - client account and @accountId@ must be the ID of a sub - account of this account . merchantId :: Core.Word64, payload :: ShippingSettings, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentShippingsettingsUpdate ' with the minimum fields required to make a request . newContentShippingsettingsUpdate :: Core.Word64 -> | The ID of the managing account . If this parameter is not the same as accountId , then this account must be a multi - client account and @accountId@ must be the ID of a sub - account of this account . See ' merchantId ' . Core.Word64 -> ShippingSettings -> ContentShippingsettingsUpdate newContentShippingsettingsUpdate accountId merchantId payload = ContentShippingsettingsUpdate { xgafv = Core.Nothing, accessToken = Core.Nothing, accountId = accountId, callback = Core.Nothing, merchantId = merchantId, payload = payload, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentShippingsettingsUpdate where type Rs ContentShippingsettingsUpdate = ShippingSettings type Scopes ContentShippingsettingsUpdate = '[Content'FullControl] requestClient ContentShippingsettingsUpdate {..} = go merchantId accountId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) payload shoppingContentService where go = Core.buildClient ( Core.Proxy :: Core.Proxy ContentShippingsettingsUpdateResource ) Core.mempty
a60efe88e4800a4b78fca2673d5de4520379ba3ffd56b7c3b8681a136a4af1a2
mitchellwrosen/dohaskell
Utils.hs
module Handler.Utils ( SortBy(..) , addGetParam , getCurrentRouteWithGetParams , denyPermissionIfDifferentUser , denyPermissionIfDoesntHaveAuthorityOver , denyPermissionIfNotAdmin , prettyAgo ) where import Import import Model.Browse import Model.User (isAdministratorDB, userHasAuthorityOverDB) import Data.Maybe (fromJust) import qualified Data.Map as M import qualified Data.Text as T import Data.Time denyPermissionIfDifferentUser :: UserId -> Handler () denyPermissionIfDifferentUser requestedUser = maybeAuthId >>= \case Nothing -> deny Just thisUser -> runDB (get requestedUser) >>= \case Nothing -> notFound Just _ -> when (requestedUser /= thisUser) deny denyPermissionIfDoesntHaveAuthorityOver :: UserId -> Handler () denyPermissionIfDoesntHaveAuthorityOver nerd = maybeAuthId >>= \case Nothing -> deny Just bully -> runDB (get nerd) >>= \case Nothing -> notFound Just _ -> do ok <- runDB $ userHasAuthorityOverDB bully nerd when (not ok) deny denyPermissionIfNotAdmin :: Handler () denyPermissionIfNotAdmin = maybeAuthId >>= \case Nothing -> deny Just uid -> runDB (isAdministratorDB uid) >>= \b -> unless b deny deny :: Handler () deny = permissionDenied "You don't have permission to view this page." -- | Pretty-print a time "ago". -- TODO: Find a better home for this function. prettyAgo :: (Functor m, MonadIO m) => UTCTime -> m Text prettyAgo t = do secs_ago <- round . flip diffUTCTime t <$> liftIO getCurrentTime if | secs_ago < secsPerWeek -> return $ prettyAgo' secsPerDay "today" " day" secs_ago | secs_ago < secsPerMonth -> return $ prettyAgo' secsPerWeek "last week" " week" secs_ago | secs_ago < secsPerYear -> return $ prettyAgo' secsPerMonth "last month" " month" secs_ago | otherwise -> return $ prettyAgo' secsPerYear "last year" " year" secs_ago where prettyAgo' :: Integer -> Text -> Text -> Integer -> Text prettyAgo' divisor if_one_text if_many_text secs_ago = case secs_ago `div` divisor of 0 -> if_one_text n -> T.pack (show n) <> plural n if_many_text <> " ago" plural :: Integer -> Text -> Text plural 1 = id plural _ = flip T.snoc 's' secsPerDay, secsPerWeek, secsPerMonth, secsPerYear :: Integer 60 * 60 * 24 60 * 60 * 24 * 7 60 * 60 * 24 * 30 60 * 60 * 24 * 365 -- | Get the current route with the current GET params. -- Unsafe if getCurrentRoute would return Nothing. getCurrentRouteWithGetParams :: Handler (Route App, [(Text, Text)]) getCurrentRouteWithGetParams = (,) <$> (fromJust <$> getCurrentRoute) <*> (reqGetParams <$> getRequest) -- | Add a new GET param to a list of GET params. addGetParam :: (Text, Text) -> [(Text, Text)] -> [(Text, Text)] addGetParam (k,v) = M.toList . M.insert k v . M.fromList
null
https://raw.githubusercontent.com/mitchellwrosen/dohaskell/69aea7a42112557ac3e835b9dbdb9bf60a81f780/src/Handler/Utils.hs
haskell
| Pretty-print a time "ago". TODO: Find a better home for this function. | Get the current route with the current GET params. Unsafe if getCurrentRoute would return Nothing. | Add a new GET param to a list of GET params.
module Handler.Utils ( SortBy(..) , addGetParam , getCurrentRouteWithGetParams , denyPermissionIfDifferentUser , denyPermissionIfDoesntHaveAuthorityOver , denyPermissionIfNotAdmin , prettyAgo ) where import Import import Model.Browse import Model.User (isAdministratorDB, userHasAuthorityOverDB) import Data.Maybe (fromJust) import qualified Data.Map as M import qualified Data.Text as T import Data.Time denyPermissionIfDifferentUser :: UserId -> Handler () denyPermissionIfDifferentUser requestedUser = maybeAuthId >>= \case Nothing -> deny Just thisUser -> runDB (get requestedUser) >>= \case Nothing -> notFound Just _ -> when (requestedUser /= thisUser) deny denyPermissionIfDoesntHaveAuthorityOver :: UserId -> Handler () denyPermissionIfDoesntHaveAuthorityOver nerd = maybeAuthId >>= \case Nothing -> deny Just bully -> runDB (get nerd) >>= \case Nothing -> notFound Just _ -> do ok <- runDB $ userHasAuthorityOverDB bully nerd when (not ok) deny denyPermissionIfNotAdmin :: Handler () denyPermissionIfNotAdmin = maybeAuthId >>= \case Nothing -> deny Just uid -> runDB (isAdministratorDB uid) >>= \b -> unless b deny deny :: Handler () deny = permissionDenied "You don't have permission to view this page." prettyAgo :: (Functor m, MonadIO m) => UTCTime -> m Text prettyAgo t = do secs_ago <- round . flip diffUTCTime t <$> liftIO getCurrentTime if | secs_ago < secsPerWeek -> return $ prettyAgo' secsPerDay "today" " day" secs_ago | secs_ago < secsPerMonth -> return $ prettyAgo' secsPerWeek "last week" " week" secs_ago | secs_ago < secsPerYear -> return $ prettyAgo' secsPerMonth "last month" " month" secs_ago | otherwise -> return $ prettyAgo' secsPerYear "last year" " year" secs_ago where prettyAgo' :: Integer -> Text -> Text -> Integer -> Text prettyAgo' divisor if_one_text if_many_text secs_ago = case secs_ago `div` divisor of 0 -> if_one_text n -> T.pack (show n) <> plural n if_many_text <> " ago" plural :: Integer -> Text -> Text plural 1 = id plural _ = flip T.snoc 's' secsPerDay, secsPerWeek, secsPerMonth, secsPerYear :: Integer 60 * 60 * 24 60 * 60 * 24 * 7 60 * 60 * 24 * 30 60 * 60 * 24 * 365 getCurrentRouteWithGetParams :: Handler (Route App, [(Text, Text)]) getCurrentRouteWithGetParams = (,) <$> (fromJust <$> getCurrentRoute) <*> (reqGetParams <$> getRequest) addGetParam :: (Text, Text) -> [(Text, Text)] -> [(Text, Text)] addGetParam (k,v) = M.toList . M.insert k v . M.fromList
61c166a01f3704e1935becd33ecb87950c14c03c8b87591f529d98c7cf105453
vzwGrey/mu
Util.hs
module Mu.Util (prettyAST) where import qualified Data.Text as T import Mu.Parser -- | Turn an AST into a readable standard notation for lambda calculus terms. prettyAST :: AST -> T.Text prettyAST (Variable v) = v prettyAST (Abstraction v b@(Application _ _)) = "λ" <> v <> ".(" <> prettyAST b <> ")" prettyAST (Abstraction v b) = "λ" <> v <> "." <> prettyAST b prettyAST (Application f a@(Application _ _)) = prettyAST f <> " (" <> prettyAST a <> ")" prettyAST (Application f a) = prettyAST f <> " " <> prettyAST a
null
https://raw.githubusercontent.com/vzwGrey/mu/345b0392cdb25fb096d340e5414f493760c8a612/app/Mu/Util.hs
haskell
| Turn an AST into a readable standard notation for lambda calculus terms.
module Mu.Util (prettyAST) where import qualified Data.Text as T import Mu.Parser prettyAST :: AST -> T.Text prettyAST (Variable v) = v prettyAST (Abstraction v b@(Application _ _)) = "λ" <> v <> ".(" <> prettyAST b <> ")" prettyAST (Abstraction v b) = "λ" <> v <> "." <> prettyAST b prettyAST (Application f a@(Application _ _)) = prettyAST f <> " (" <> prettyAST a <> ")" prettyAST (Application f a) = prettyAST f <> " " <> prettyAST a
4a359b6c438b070a3baed10a422532ffada75fe0543af79c40e889a520efa748
clojure-lsp/clojure-lsp
stubs.clj
(ns clojure-lsp.feature.stubs (:require [babashka.fs :as fs] [clj-easy.stub.core :as stub] [clojure-lsp.db :as db] [clojure-lsp.kondo :as lsp.kondo] [clojure-lsp.logger :as logger] [clojure-lsp.shared :as shared] [clojure.java.io :as io] [clojure.string :as string]) (:import (java.io File))) (set! *warn-on-reflection* true) (defn ^:private stubs-output-dir [settings] (or (-> settings :stubs :generation :output-dir) ".lsp/.cache/stubs")) (defn ^:private delete-directory-recursive "Recursively delete a directory." [^java.io.File file] (when (.isDirectory file) (run! delete-directory-recursive (.listFiles file))) (io/delete-file file true)) (defn ^:private generate-stubs! [namespaces settings db] (try (if-let [classpath (string/join fs/path-separator (:classpath db))] (let [java-command (or (-> settings :stubs :generation :java-command) "java") output-dir ^File (io/file (stubs-output-dir settings))] (delete-directory-recursive output-dir) (logger/info (str "Generating stubs for analysis for namespaces " namespaces " on " (str output-dir))) (shared/logging-time "Stub generation process took %s." (stub/generate! {:output-dir output-dir :namespaces namespaces :classpath classpath :java-command java-command}))) {:result-code 2 :message "Classpath not found."}) (catch Exception e {:result-code 1 :message (str "Error: " e)}))) (defn ^:private analyze-stubs! [dirs db*] (let [normalization-config {:external? true :filter-analysis #(dissoc % :namespace-usages)} result (shared/logging-time "Stubs analyzed, took %s." (lsp.kondo/run-kondo-on-paths! dirs db* normalization-config nil))] (swap! db* lsp.kondo/db-with-results result) (db/read-and-update-cache! @db* (fn [db] (update db :analysis merge (:analysis result)))))) (defn generate-and-analyze-stubs! [settings db*] (let [db @db* namespaces (->> settings :stubs :generation :namespaces (map str) set) extra-dirs (-> settings :stubs :extra-dirs)] (if (and (seq namespaces) (or (:full-scan-analysis-startup db) (not= namespaces (:stubs-generation-namespaces db)))) (let [{:keys [result-code message]} (generate-stubs! namespaces settings db)] (if (= 0 result-code) (analyze-stubs! (concat [(stubs-output-dir settings)] extra-dirs) db*) (logger/error (str "Stub generation failed." message)))) (when (seq extra-dirs) (analyze-stubs! extra-dirs db*))))) (defn check-stubs? [settings] (or (-> settings :stubs :generation :namespaces seq) (-> settings :stubs :extra-dirs seq)))
null
https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/55752ff8999092ed5d2b7320c42a50dfb5936045/lib/src/clojure_lsp/feature/stubs.clj
clojure
(ns clojure-lsp.feature.stubs (:require [babashka.fs :as fs] [clj-easy.stub.core :as stub] [clojure-lsp.db :as db] [clojure-lsp.kondo :as lsp.kondo] [clojure-lsp.logger :as logger] [clojure-lsp.shared :as shared] [clojure.java.io :as io] [clojure.string :as string]) (:import (java.io File))) (set! *warn-on-reflection* true) (defn ^:private stubs-output-dir [settings] (or (-> settings :stubs :generation :output-dir) ".lsp/.cache/stubs")) (defn ^:private delete-directory-recursive "Recursively delete a directory." [^java.io.File file] (when (.isDirectory file) (run! delete-directory-recursive (.listFiles file))) (io/delete-file file true)) (defn ^:private generate-stubs! [namespaces settings db] (try (if-let [classpath (string/join fs/path-separator (:classpath db))] (let [java-command (or (-> settings :stubs :generation :java-command) "java") output-dir ^File (io/file (stubs-output-dir settings))] (delete-directory-recursive output-dir) (logger/info (str "Generating stubs for analysis for namespaces " namespaces " on " (str output-dir))) (shared/logging-time "Stub generation process took %s." (stub/generate! {:output-dir output-dir :namespaces namespaces :classpath classpath :java-command java-command}))) {:result-code 2 :message "Classpath not found."}) (catch Exception e {:result-code 1 :message (str "Error: " e)}))) (defn ^:private analyze-stubs! [dirs db*] (let [normalization-config {:external? true :filter-analysis #(dissoc % :namespace-usages)} result (shared/logging-time "Stubs analyzed, took %s." (lsp.kondo/run-kondo-on-paths! dirs db* normalization-config nil))] (swap! db* lsp.kondo/db-with-results result) (db/read-and-update-cache! @db* (fn [db] (update db :analysis merge (:analysis result)))))) (defn generate-and-analyze-stubs! [settings db*] (let [db @db* namespaces (->> settings :stubs :generation :namespaces (map str) set) extra-dirs (-> settings :stubs :extra-dirs)] (if (and (seq namespaces) (or (:full-scan-analysis-startup db) (not= namespaces (:stubs-generation-namespaces db)))) (let [{:keys [result-code message]} (generate-stubs! namespaces settings db)] (if (= 0 result-code) (analyze-stubs! (concat [(stubs-output-dir settings)] extra-dirs) db*) (logger/error (str "Stub generation failed." message)))) (when (seq extra-dirs) (analyze-stubs! extra-dirs db*))))) (defn check-stubs? [settings] (or (-> settings :stubs :generation :namespaces seq) (-> settings :stubs :extra-dirs seq)))
e3c363a466213d2bee8174f9d85f00971481a52141984a6004bb37e3691141e2
jordanthayer/ocaml-search
assoca.ml
$ I d : backedht.ml , v 1.1 2003/09/26 23:39:02 ruml Exp ruml $ associative arrays maps keys to values like alists but easier to modify destructively . associative arrays maps keys to values like alists but easier to modify destructively. *) type ('a * 'b) t = ('a array) * ('b array) let init_keys f keys = (** given list of keys that will be used, init values by mapping using [f] *) let a = Array.of_list keys in let b = Array.map f a in a, b let copy (a, b) = (Array.copy a), (Array.copy b) let get (a, b) key = (** can raise Not_found *) b.(Wrarray.index a key) let set (a, b) key value = (** can raise Not_found *) b.(Wrarray.index a key) <- value EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/structs/assoca.ml
ocaml
* given list of keys that will be used, init values by mapping using [f] * can raise Not_found * can raise Not_found
$ I d : backedht.ml , v 1.1 2003/09/26 23:39:02 ruml Exp ruml $ associative arrays maps keys to values like alists but easier to modify destructively . associative arrays maps keys to values like alists but easier to modify destructively. *) type ('a * 'b) t = ('a array) * ('b array) let init_keys f keys = let a = Array.of_list keys in let b = Array.map f a in a, b let copy (a, b) = (Array.copy a), (Array.copy b) let get (a, b) key = b.(Wrarray.index a key) let set (a, b) key value = b.(Wrarray.index a key) <- value EOF
9ea7b88101ac0d980fb82e4af7996d941266b8d733c7c272134c6f96452c4ee2
mariari/Misc-Lisp-Scripts
state.lisp
(defpackage #:state (:nicknames #:s) (:documentation "provides the state monad") (:use #:common-lisp #:tuple #:trivia #:generic) (:export :make-state :state-p :state-run :sget :put :modify :spure)) (in-package :state) (eval-when (:compile-toplevel :load-toplevel :execute) (SETF *ARITY-CHECK-BY-TEST-CALL* NIL)) newtype State s a = State { runState : : s - > ( a , s ) } (defstruct (state (:constructor make-state (run))) (run #'identity :type function)) (defparameter sget (make-state (lambda (x) (tup x x)))) (defun put (s) (make-state (constantly (tup nil s)))) (defun modify (f) (make-state (lambda (s) (tup nil (funcall f s))))) (defmethod spure (a) (make-state (lambda (s) (tup a s)))) (defun >>=% (f g) (make-state (lambda (s) (let-match1 (tup :fst a :snd s%) (funcall (state-run f) s) (funcall (state-run (funcall g a)) s%))))) (defmethod fmap (f (m State)) (make-state (lambda (s) (let-match1 (tup :fst a :snd s%) (funcall (state-run m) s) (tup (funcall f a) s%))))) (defmethod <*> ((k state) (m state)) (make-state (lambda (s) (let-match* (((tup :fst f :snd s%) (funcall (state-run k) s)) ((tup :fst a :snd s%%) (funcall (state-run m) s%))) (tup (funcall f a) s%%))))) (defmethod >>= ((f state) g) (>>=% f g)) (defmethod =<< (g (f state)) (>>=% f g))
null
https://raw.githubusercontent.com/mariari/Misc-Lisp-Scripts/acecadc75fcbe15e6b97e084d179aacdbbde06a8/data-structures/state.lisp
lisp
(defpackage #:state (:nicknames #:s) (:documentation "provides the state monad") (:use #:common-lisp #:tuple #:trivia #:generic) (:export :make-state :state-p :state-run :sget :put :modify :spure)) (in-package :state) (eval-when (:compile-toplevel :load-toplevel :execute) (SETF *ARITY-CHECK-BY-TEST-CALL* NIL)) newtype State s a = State { runState : : s - > ( a , s ) } (defstruct (state (:constructor make-state (run))) (run #'identity :type function)) (defparameter sget (make-state (lambda (x) (tup x x)))) (defun put (s) (make-state (constantly (tup nil s)))) (defun modify (f) (make-state (lambda (s) (tup nil (funcall f s))))) (defmethod spure (a) (make-state (lambda (s) (tup a s)))) (defun >>=% (f g) (make-state (lambda (s) (let-match1 (tup :fst a :snd s%) (funcall (state-run f) s) (funcall (state-run (funcall g a)) s%))))) (defmethod fmap (f (m State)) (make-state (lambda (s) (let-match1 (tup :fst a :snd s%) (funcall (state-run m) s) (tup (funcall f a) s%))))) (defmethod <*> ((k state) (m state)) (make-state (lambda (s) (let-match* (((tup :fst f :snd s%) (funcall (state-run k) s)) ((tup :fst a :snd s%%) (funcall (state-run m) s%))) (tup (funcall f a) s%%))))) (defmethod >>= ((f state) g) (>>=% f g)) (defmethod =<< (g (f state)) (>>=% f g))
387526ae00fb0a8d1f7b8c7c868fdf57fd3aec928067d715e1263ca1faca2061
polyfy/polylith
m107_missing_componens_in_project.clj
(ns polylith.clj.core.validator.m107-missing-componens-in-project (:require [clojure.set :as set] [clojure.string :as str] [polylith.clj.core.validator.shared :as shared] [polylith.clj.core.util.interface :as util] [polylith.clj.core.util.interface.color :as color]) (:refer-clojure :exclude [bases])) (defn missing-components-error [project-name interface-names test? color-mode] (let [interfaces (str/join ", " interface-names) message (str "Missing components in the " (color/project project-name color-mode) " project" (if test? ", for the test context," "") " for these interfaces: " (color/interface interfaces color-mode))] [(util/ordered-map :type "error" :code 107 :message (color/clean-colors message) :colorized-message message :interfaces interface-names :project project-name)])) (defn missing-components [deps src-type] (let [missing-ifc (mapcat #(-> % second src-type :missing-ifc) deps)] (set (mapcat val missing-ifc)))) (defn project-error [{:keys [name deps]} projects brick-name->ifc color-mode] (let [missing (vec (sort (missing-components deps :src))) all-missing-test (missing-components deps :test) bricks-to-test (get-in projects [name :test]) missing-test (if bricks-to-test (vec (sort (set/intersection all-missing-test (set (map brick-name->ifc bricks-to-test))))) (vec (sort all-missing-test)))] (cond (-> missing empty? not) (missing-components-error name missing false color-mode) (-> missing-test empty? not) (missing-components-error name missing-test true color-mode)))) (defn errors [cmd {:keys [profile-to-settings active-profiles] :as settings} projects components color-mode] (when (shared/show-error? cmd profile-to-settings active-profiles) (let [settings-projects (:projects settings) brick-name->ifc (into {} (map (juxt :name #(-> % :interface :name)) components))] (mapcat #(project-error % settings-projects brick-name->ifc color-mode) projects))))
null
https://raw.githubusercontent.com/polyfy/polylith/36b75565032dea88ee20cdc0bc5af18f6f4d4cf4/components/validator/src/polylith/clj/core/validator/m107_missing_componens_in_project.clj
clojure
(ns polylith.clj.core.validator.m107-missing-componens-in-project (:require [clojure.set :as set] [clojure.string :as str] [polylith.clj.core.validator.shared :as shared] [polylith.clj.core.util.interface :as util] [polylith.clj.core.util.interface.color :as color]) (:refer-clojure :exclude [bases])) (defn missing-components-error [project-name interface-names test? color-mode] (let [interfaces (str/join ", " interface-names) message (str "Missing components in the " (color/project project-name color-mode) " project" (if test? ", for the test context," "") " for these interfaces: " (color/interface interfaces color-mode))] [(util/ordered-map :type "error" :code 107 :message (color/clean-colors message) :colorized-message message :interfaces interface-names :project project-name)])) (defn missing-components [deps src-type] (let [missing-ifc (mapcat #(-> % second src-type :missing-ifc) deps)] (set (mapcat val missing-ifc)))) (defn project-error [{:keys [name deps]} projects brick-name->ifc color-mode] (let [missing (vec (sort (missing-components deps :src))) all-missing-test (missing-components deps :test) bricks-to-test (get-in projects [name :test]) missing-test (if bricks-to-test (vec (sort (set/intersection all-missing-test (set (map brick-name->ifc bricks-to-test))))) (vec (sort all-missing-test)))] (cond (-> missing empty? not) (missing-components-error name missing false color-mode) (-> missing-test empty? not) (missing-components-error name missing-test true color-mode)))) (defn errors [cmd {:keys [profile-to-settings active-profiles] :as settings} projects components color-mode] (when (shared/show-error? cmd profile-to-settings active-profiles) (let [settings-projects (:projects settings) brick-name->ifc (into {} (map (juxt :name #(-> % :interface :name)) components))] (mapcat #(project-error % settings-projects brick-name->ifc color-mode) projects))))
9acda6523d31319f1c585ce42b06a8805398b5d4ca459f48a509b0bbba21d3f9
vouillon/osm
line_smoothing.mli
OSM tools * Copyright ( C ) 2013 * * 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 exception ; * either version 2.1 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 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) 2013 Jérôme Vouillon * * 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 exception; * either version 2.1 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 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. *) val perform : float array -> float array -> (float array * float array) * (float array * float array) * (float array * float array)
null
https://raw.githubusercontent.com/vouillon/osm/a42d1bcc82a4ad73c26c81ac7a75f9f1c7470344/osm/line_smoothing.mli
ocaml
OSM tools * Copyright ( C ) 2013 * * 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 exception ; * either version 2.1 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 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) 2013 Jérôme Vouillon * * 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 exception; * either version 2.1 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 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. *) val perform : float array -> float array -> (float array * float array) * (float array * float array) * (float array * float array)
a6c559e65844f8145bd8b5425d1127df757d7c9319192bca69a7f4fb95b0ca43
Opetushallitus/aipal
project.clj
Copyright ( c ) 2013 The Finnish National Board of Education - Opetushallitus ;; This program is free software : Licensed under the EUPL , Version 1.1 or - as soon as they will be approved by the European Commission - subsequent versions of the EUPL ( the " Licence " ) ; ;; ;; You may not use this work except in compliance with the Licence. ;; You may obtain a copy of the Licence at: / ;; ;; 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 European Union Public Licence for more details . (defproject aipal-db "0.1.0-SNAPSHOT" :description "AIPAL projektin tietokannan rakentaminen" :dependencies [[org.clojure/clojure "1.5.1"] [stencil "0.3.2"] [com.googlecode.flyway/flyway-core "2.2"] [org.clojure/java.jdbc "0.3.0-alpha5"] [postgresql "9.1-901.jdbc4"] [org.clojure/tools.cli "0.3.0"] [clojure-csv "2.0.1"]] :profiles {:uberjar {:aot :all}} :resource-paths ["resources"] :main aipal-db.core :jar-name "aipal-db.jar" :uberjar-name "aipal-db-standalone.jar")
null
https://raw.githubusercontent.com/Opetushallitus/aipal/767bd14ec7153dc97fdf688443b9687cdb70082f/aipal-db/project.clj
clojure
You may not use this work except in compliance with the Licence. You may obtain a copy of the Licence at: / 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
Copyright ( c ) 2013 The Finnish National Board of Education - Opetushallitus This program is free software : Licensed under the EUPL , Version 1.1 or - as soon as they will be approved by the European Commission - subsequent versions European Union Public Licence for more details . (defproject aipal-db "0.1.0-SNAPSHOT" :description "AIPAL projektin tietokannan rakentaminen" :dependencies [[org.clojure/clojure "1.5.1"] [stencil "0.3.2"] [com.googlecode.flyway/flyway-core "2.2"] [org.clojure/java.jdbc "0.3.0-alpha5"] [postgresql "9.1-901.jdbc4"] [org.clojure/tools.cli "0.3.0"] [clojure-csv "2.0.1"]] :profiles {:uberjar {:aot :all}} :resource-paths ["resources"] :main aipal-db.core :jar-name "aipal-db.jar" :uberjar-name "aipal-db-standalone.jar")
5ffbed28596b442ec2b07bfcc9007d8068a8d325d50faf2ae1c15b9bf9ca6eae
binghe/PCL
inline.lisp
-*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- (in-package :pcl) ;; This file contains some of the things that will have to change to support ;; inlining of methods. (defun make-method-lambda-internal (method-lambda &optional env) (unless (and (consp method-lambda) (eq (car method-lambda) 'lambda)) (error "The method-lambda argument to make-method-lambda, ~S,~ is not a lambda form" method-lambda)) (multiple-value-bind (documentation declarations real-body) (extract-declarations (cddr method-lambda) env) (let* ((name-decl (get-declaration 'method-name declarations)) (sll-decl (get-declaration 'method-lambda-list declarations)) (method-name (when (consp name-decl) (car name-decl))) (generic-function-name (when method-name (car method-name))) (specialized-lambda-list (or sll-decl (cadr method-lambda)))) (multiple-value-bind (parameters lambda-list specializers) (parse-specialized-lambda-list specialized-lambda-list) (let* ((required-parameters (mapcar #'(lambda (r s) (declare (ignore s)) r) parameters specializers)) (slots (mapcar #'list required-parameters)) (calls (list nil)) (parameters-to-reference (make-parameter-references specialized-lambda-list required-parameters declarations method-name specializers)) (class-declarations `(declare ,@(remove nil (mapcar #'(lambda (a s) (and (symbolp s) (neq s 't) `(class ,a ,s))) parameters specializers)))) (method-lambda ;; Remove the documentation string and insert the ;; appropriate class declarations. The documentation ;; string is removed to make it easy for us to insert ;; new declarations later, they will just go after the cadr of the method lambda . The class declarations ;; are inserted to communicate the class of the method's ;; arguments to the code walk. `(lambda ,lambda-list ,class-declarations ,@declarations (progn ,@parameters-to-reference) (block ,(if (listp generic-function-name) (cadr generic-function-name) generic-function-name) ,@real-body))) (constant-value-p (and (null (cdr real-body)) (constantp (car real-body)))) (constant-value (and constant-value-p (eval (car real-body)))) (plist (if (and constant-value-p (or (typep constant-value '(or number character)) (and (symbolp constant-value) (symbol-package constant-value)))) (list :constant-value constant-value) ())) (applyp (dolist (p lambda-list nil) (cond ((memq p '(&optional &rest &key)) (return t)) ((eq p '&aux) (return nil)))))) (multiple-value-bind (walked-lambda call-next-method-p closurep next-method-p-p) (walk-method-lambda method-lambda required-parameters env slots calls) (multiple-value-bind (ignore walked-declarations walked-lambda-body) (extract-declarations (cddr walked-lambda)) (declare (ignore ignore)) (when (or next-method-p-p call-next-method-p) (setq plist (list* :needs-next-methods-p 't plist))) (when (some #'cdr slots) (multiple-value-bind (slot-name-lists call-list) (slot-name-lists-from-slots slots calls) (let ((pv-table-symbol (make-symbol "pv-table"))) (setq plist `(,@(when slot-name-lists `(:slot-name-lists ,slot-name-lists)) ,@(when call-list `(:call-list ,call-list)) :pv-table-symbol ,pv-table-symbol ,@plist)) (setq walked-lambda-body `((pv-binding (,required-parameters ,slot-name-lists ,pv-table-symbol) ,@walked-lambda-body)))))) (when (and (memq '&key lambda-list) (not (memq '&allow-other-keys lambda-list))) (let ((aux (memq '&aux lambda-list))) (setq lambda-list (nconc (ldiff lambda-list aux) (list '&allow-other-keys) aux)))) (values `(lambda (.method-args. .next-methods.) (simple-lexical-method-functions (,lambda-list .method-args. .next-methods. :call-next-method-p ,call-next-method-p :next-method-p-p ,next-method-p-p :closurep ,closurep :applyp ,applyp) ,@walked-declarations ,@walked-lambda-body)) `(,@(when plist `(:plist ,plist)) ,@(when documentation `(:documentation ,documentation))))))))))) (define-inline-function slot-value (instance slot-name) (form closure-p env) :predicate (and (not closure-p) (constantp slot-name)) :inline-arguments (required-parameters slots) :inline (optimize-slot-value slots (can-optimize-access form required-parameters env) form)) ;collect information about: ; uses of the required-parameters ; uses of call-next-method and next-method-p: ; called-p ; apply-p ; arglist info ;optimize calls to slot-value, set-slot-value, slot-boundp ;optimize calls to find-class ;optimize generic-function calls (defun make-walk-function (required-parameters info slots calls) #'(lambda (form context env) (cond ((not (eq context ':eval)) form) ((not (listp form)) form) ((eq (car form) 'call-next-method) (setq call-next-method-p 't) form) ((eq (car form) 'next-method-p) (setq next-method-p-p 't) form) ((and (eq (car form) 'function) (cond ((eq (cadr form) 'call-next-method) (setq call-next-method-p 't) (setq closurep t) form) ((eq (cadr form) 'next-method-p) (setq next-method-p-p 't) (setq closurep t) form) (t nil)))) ((and (or (eq (car form) 'slot-value) (eq (car form) 'set-slot-value) (eq (car form) 'slot-boundp)) (constantp (caddr form))) (let ((parameter (can-optimize-access form required-parameters env))) (ecase (car form) (slot-value (optimize-slot-value slots parameter form)) (set-slot-value (optimize-set-slot-value slots parameter form)) (slot-boundp (optimize-slot-boundp slots parameter form))))) ((and (or (symbolp (car form)) (and (consp (car form)) (eq (caar form) 'setf))) (gboundp (car form)) (if (eq *boot-state* 'complete) (standard-generic-function-p (gdefinition (car form))) (funcallable-instance-p (gdefinition (car form))))) (optimize-generic-function-call form required-parameters env slots calls)) (t form)))) (defun walk-method-lambda (method-lambda required-parameters env slots calls) (let* ((call-next-method-p nil) ;flag indicating that call-next-method ;should be in the method definition (closurep nil) ;flag indicating that #'call-next-method ;was seen in the body of a method (next-method-p-p nil) ;flag indicating that next-method-p ;should be in the method definition (walk-functions `((call-next-method-p ,#'(lambda (form closure-p env) (setq call-next-method-p 't) (when closure-p (setq closurep t)) form)) (next-method-p ,#'(lambda (form closure-p env) (setq next-method-p-p 't) (when closure-p (setq closurep t)) form)) ((slot-value set-slot-value slot-boundp) ,#'(lambda (form closure-p env) (if (and (not closure-p) (constantp (caddr form))) (let ((walked-lambda (walk-form method-lambda env (make-walk-function `((call-next-method-p ,#'(lambda (form closure-p env) (setq call-next-method-p 't) (when closure-p (setq closurep t)) form)) (next-method-p ,#'(lambda (form closure-p env) (setq next-method-p-p 't) (when closure-p (setq closurep t)) form)) ((slot-value set-slot-value slot-boundp) ,#'(lambda (form closure-p env) ( (values walked-lambda call-next-method-p closurep next-method-p-p))))) (defun initialize-method-function (initargs &optional return-function-p method) (let* ((mf (getf initargs ':function)) (method-spec (getf initargs ':method-spec)) (plist (getf initargs ':plist)) (pv-table-symbol (getf plist ':pv-table-symbol)) (pv-table nil) (mff (getf initargs ':fast-function))) (flet ((set-mf-property (p v) (when mf (setf (method-function-get mf p) v)) (when mff (setf (method-function-get mff p) v)))) (when method-spec (when mf (setq mf (set-function-name mf method-spec))) (when mff (let ((name `(,(or (get (car method-spec) 'fast-sym) (setf (get (car method-spec) 'fast-sym) (intern (format nil "FAST-~A" (car method-spec)) *the-pcl-package*))) ,@(cdr method-spec)))) (set-function-name mff name) (unless mf (set-mf-property :name name))))) (when plist (let ((snl (getf plist :slot-name-lists)) (cl (getf plist :call-list))) (when (or snl cl) (setq pv-table (intern-pv-table :slot-name-lists snl :call-list cl)) (when pv-table (set pv-table-symbol pv-table)) (set-mf-property :pv-table pv-table))) (loop (when (null plist) (return nil)) (set-mf-property (pop plist) (pop plist))) (when method (set-mf-property :method method)) (when return-function-p (or mf (method-function-from-fast-function mff)))))))
null
https://raw.githubusercontent.com/binghe/PCL/7021c061c5eef1466e563c4abb664ab468ee0d80/pcl/inline.lisp
lisp
Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- This file contains some of the things that will have to change to support inlining of methods. Remove the documentation string and insert the appropriate class declarations. The documentation string is removed to make it easy for us to insert new declarations later, they will just go after the are inserted to communicate the class of the method's arguments to the code walk. collect information about: uses of the required-parameters uses of call-next-method and next-method-p: called-p apply-p arglist info optimize calls to slot-value, set-slot-value, slot-boundp optimize calls to find-class optimize generic-function calls flag indicating that call-next-method should be in the method definition flag indicating that #'call-next-method was seen in the body of a method flag indicating that next-method-p should be in the method definition
(in-package :pcl) (defun make-method-lambda-internal (method-lambda &optional env) (unless (and (consp method-lambda) (eq (car method-lambda) 'lambda)) (error "The method-lambda argument to make-method-lambda, ~S,~ is not a lambda form" method-lambda)) (multiple-value-bind (documentation declarations real-body) (extract-declarations (cddr method-lambda) env) (let* ((name-decl (get-declaration 'method-name declarations)) (sll-decl (get-declaration 'method-lambda-list declarations)) (method-name (when (consp name-decl) (car name-decl))) (generic-function-name (when method-name (car method-name))) (specialized-lambda-list (or sll-decl (cadr method-lambda)))) (multiple-value-bind (parameters lambda-list specializers) (parse-specialized-lambda-list specialized-lambda-list) (let* ((required-parameters (mapcar #'(lambda (r s) (declare (ignore s)) r) parameters specializers)) (slots (mapcar #'list required-parameters)) (calls (list nil)) (parameters-to-reference (make-parameter-references specialized-lambda-list required-parameters declarations method-name specializers)) (class-declarations `(declare ,@(remove nil (mapcar #'(lambda (a s) (and (symbolp s) (neq s 't) `(class ,a ,s))) parameters specializers)))) (method-lambda cadr of the method lambda . The class declarations `(lambda ,lambda-list ,class-declarations ,@declarations (progn ,@parameters-to-reference) (block ,(if (listp generic-function-name) (cadr generic-function-name) generic-function-name) ,@real-body))) (constant-value-p (and (null (cdr real-body)) (constantp (car real-body)))) (constant-value (and constant-value-p (eval (car real-body)))) (plist (if (and constant-value-p (or (typep constant-value '(or number character)) (and (symbolp constant-value) (symbol-package constant-value)))) (list :constant-value constant-value) ())) (applyp (dolist (p lambda-list nil) (cond ((memq p '(&optional &rest &key)) (return t)) ((eq p '&aux) (return nil)))))) (multiple-value-bind (walked-lambda call-next-method-p closurep next-method-p-p) (walk-method-lambda method-lambda required-parameters env slots calls) (multiple-value-bind (ignore walked-declarations walked-lambda-body) (extract-declarations (cddr walked-lambda)) (declare (ignore ignore)) (when (or next-method-p-p call-next-method-p) (setq plist (list* :needs-next-methods-p 't plist))) (when (some #'cdr slots) (multiple-value-bind (slot-name-lists call-list) (slot-name-lists-from-slots slots calls) (let ((pv-table-symbol (make-symbol "pv-table"))) (setq plist `(,@(when slot-name-lists `(:slot-name-lists ,slot-name-lists)) ,@(when call-list `(:call-list ,call-list)) :pv-table-symbol ,pv-table-symbol ,@plist)) (setq walked-lambda-body `((pv-binding (,required-parameters ,slot-name-lists ,pv-table-symbol) ,@walked-lambda-body)))))) (when (and (memq '&key lambda-list) (not (memq '&allow-other-keys lambda-list))) (let ((aux (memq '&aux lambda-list))) (setq lambda-list (nconc (ldiff lambda-list aux) (list '&allow-other-keys) aux)))) (values `(lambda (.method-args. .next-methods.) (simple-lexical-method-functions (,lambda-list .method-args. .next-methods. :call-next-method-p ,call-next-method-p :next-method-p-p ,next-method-p-p :closurep ,closurep :applyp ,applyp) ,@walked-declarations ,@walked-lambda-body)) `(,@(when plist `(:plist ,plist)) ,@(when documentation `(:documentation ,documentation))))))))))) (define-inline-function slot-value (instance slot-name) (form closure-p env) :predicate (and (not closure-p) (constantp slot-name)) :inline-arguments (required-parameters slots) :inline (optimize-slot-value slots (can-optimize-access form required-parameters env) form)) (defun make-walk-function (required-parameters info slots calls) #'(lambda (form context env) (cond ((not (eq context ':eval)) form) ((not (listp form)) form) ((eq (car form) 'call-next-method) (setq call-next-method-p 't) form) ((eq (car form) 'next-method-p) (setq next-method-p-p 't) form) ((and (eq (car form) 'function) (cond ((eq (cadr form) 'call-next-method) (setq call-next-method-p 't) (setq closurep t) form) ((eq (cadr form) 'next-method-p) (setq next-method-p-p 't) (setq closurep t) form) (t nil)))) ((and (or (eq (car form) 'slot-value) (eq (car form) 'set-slot-value) (eq (car form) 'slot-boundp)) (constantp (caddr form))) (let ((parameter (can-optimize-access form required-parameters env))) (ecase (car form) (slot-value (optimize-slot-value slots parameter form)) (set-slot-value (optimize-set-slot-value slots parameter form)) (slot-boundp (optimize-slot-boundp slots parameter form))))) ((and (or (symbolp (car form)) (and (consp (car form)) (eq (caar form) 'setf))) (gboundp (car form)) (if (eq *boot-state* 'complete) (standard-generic-function-p (gdefinition (car form))) (funcallable-instance-p (gdefinition (car form))))) (optimize-generic-function-call form required-parameters env slots calls)) (t form)))) (defun walk-method-lambda (method-lambda required-parameters env slots calls) (walk-functions `((call-next-method-p ,#'(lambda (form closure-p env) (setq call-next-method-p 't) (when closure-p (setq closurep t)) form)) (next-method-p ,#'(lambda (form closure-p env) (setq next-method-p-p 't) (when closure-p (setq closurep t)) form)) ((slot-value set-slot-value slot-boundp) ,#'(lambda (form closure-p env) (if (and (not closure-p) (constantp (caddr form))) (let ((walked-lambda (walk-form method-lambda env (make-walk-function `((call-next-method-p ,#'(lambda (form closure-p env) (setq call-next-method-p 't) (when closure-p (setq closurep t)) form)) (next-method-p ,#'(lambda (form closure-p env) (setq next-method-p-p 't) (when closure-p (setq closurep t)) form)) ((slot-value set-slot-value slot-boundp) ,#'(lambda (form closure-p env) ( (values walked-lambda call-next-method-p closurep next-method-p-p))))) (defun initialize-method-function (initargs &optional return-function-p method) (let* ((mf (getf initargs ':function)) (method-spec (getf initargs ':method-spec)) (plist (getf initargs ':plist)) (pv-table-symbol (getf plist ':pv-table-symbol)) (pv-table nil) (mff (getf initargs ':fast-function))) (flet ((set-mf-property (p v) (when mf (setf (method-function-get mf p) v)) (when mff (setf (method-function-get mff p) v)))) (when method-spec (when mf (setq mf (set-function-name mf method-spec))) (when mff (let ((name `(,(or (get (car method-spec) 'fast-sym) (setf (get (car method-spec) 'fast-sym) (intern (format nil "FAST-~A" (car method-spec)) *the-pcl-package*))) ,@(cdr method-spec)))) (set-function-name mff name) (unless mf (set-mf-property :name name))))) (when plist (let ((snl (getf plist :slot-name-lists)) (cl (getf plist :call-list))) (when (or snl cl) (setq pv-table (intern-pv-table :slot-name-lists snl :call-list cl)) (when pv-table (set pv-table-symbol pv-table)) (set-mf-property :pv-table pv-table))) (loop (when (null plist) (return nil)) (set-mf-property (pop plist) (pop plist))) (when method (set-mf-property :method method)) (when return-function-p (or mf (method-function-from-fast-function mff)))))))
9f9c3893fc81ebc4d957f7921356cbdbb915efdd1488380ff5b7c120fc977261
dharmatech/abstracting
source.scm
by ;; ;; Original piece: ;; Ported to Abstracting by (size 500 500) (set! *frames-per-second* 30) (init-nodebox) (stroke 0.0) (set! *draw* (let ((rotate (let ((x 0) (y 0)) (lambda () (set! x (+ x 0.5)) (set! y (+ y 1.0)) (glRotated x 1.0 0.0 0.0) (glRotated y 0.0 1.0 0.0)))) (draw-triangle (let ((make-vertex (let ((r 100.0) (margin 20)) (lambda (n) (let ((t (cond ((<= *mouse-x* margin) 0.0) ((>= *mouse-x* (- *width* margin)) 2.0) (else (processing-map *mouse-x* margin (- *width* margin) 0.0 2.0))))) (let ((i (if (>= t 1) 1 t)) (j (if (<= t 1) 1 (processing-map t 1 2 1.0 0.0)))) (case n ((0) (pt (* r j ) 0.0 (* r i))) ((1) (pt (* r j ) 0.0 (* r (- i)))) ((2) (pt (* r (- j)) 0.0 (* r (- i)))) ((3) (pt (* r (- j)) 0.0 (* r i))) ((4) (pt (* r i ) (* r j ) 0.0)) ((5) (pt (* r (- i)) (* r j ) 0.0)) ((6) (pt (* r (- i)) (* r (- j)) 0.0)) ((7) (pt (* r i ) (* r (- j)) 0.0)) ((8) (pt 0.0 (* r i ) (* r j))) ((9) (pt 0.0 (* r (- i)) (* r j))) ((10) (pt 0.0 (* r (- i)) (* r (- j)))) ((11) (pt 0.0 (* r i ) (* r (- j))))))))))) (lambda (i j k) (triangle (make-vertex i) (make-vertex j) (make-vertex k)))))) (lambda () (background 1.0) (glTranslated (/ *width* 2.0) (/ *height* 2.0) -100.0) (rotate) (glLineWidth 2.0) (fill 0.0 0.5 1.0 0.5) (draw-triangle 0 4 8) (draw-triangle 3 5 8) (draw-triangle 0 7 9) (draw-triangle 3 6 9) (draw-triangle 1 4 11) (draw-triangle 2 5 11) (draw-triangle 1 7 10) (draw-triangle 2 6 10)))) (run-nodebox)
null
https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/examples/jitter-bug/source.scm
scheme
Original piece:
by Ported to Abstracting by (size 500 500) (set! *frames-per-second* 30) (init-nodebox) (stroke 0.0) (set! *draw* (let ((rotate (let ((x 0) (y 0)) (lambda () (set! x (+ x 0.5)) (set! y (+ y 1.0)) (glRotated x 1.0 0.0 0.0) (glRotated y 0.0 1.0 0.0)))) (draw-triangle (let ((make-vertex (let ((r 100.0) (margin 20)) (lambda (n) (let ((t (cond ((<= *mouse-x* margin) 0.0) ((>= *mouse-x* (- *width* margin)) 2.0) (else (processing-map *mouse-x* margin (- *width* margin) 0.0 2.0))))) (let ((i (if (>= t 1) 1 t)) (j (if (<= t 1) 1 (processing-map t 1 2 1.0 0.0)))) (case n ((0) (pt (* r j ) 0.0 (* r i))) ((1) (pt (* r j ) 0.0 (* r (- i)))) ((2) (pt (* r (- j)) 0.0 (* r (- i)))) ((3) (pt (* r (- j)) 0.0 (* r i))) ((4) (pt (* r i ) (* r j ) 0.0)) ((5) (pt (* r (- i)) (* r j ) 0.0)) ((6) (pt (* r (- i)) (* r (- j)) 0.0)) ((7) (pt (* r i ) (* r (- j)) 0.0)) ((8) (pt 0.0 (* r i ) (* r j))) ((9) (pt 0.0 (* r (- i)) (* r j))) ((10) (pt 0.0 (* r (- i)) (* r (- j)))) ((11) (pt 0.0 (* r i ) (* r (- j))))))))))) (lambda (i j k) (triangle (make-vertex i) (make-vertex j) (make-vertex k)))))) (lambda () (background 1.0) (glTranslated (/ *width* 2.0) (/ *height* 2.0) -100.0) (rotate) (glLineWidth 2.0) (fill 0.0 0.5 1.0 0.5) (draw-triangle 0 4 8) (draw-triangle 3 5 8) (draw-triangle 0 7 9) (draw-triangle 3 6 9) (draw-triangle 1 4 11) (draw-triangle 2 5 11) (draw-triangle 1 7 10) (draw-triangle 2 6 10)))) (run-nodebox)
523b578732796a527c9c6ceb6de091a829f5be71c205924b392417e0de9ae951
tek/polysemy-http
Request.hs
{-# options_haddock prune #-} -- |Description: Request Combinators, Internal module Polysemy.Http.Request where import qualified Data.Text as Text import Data.Time (UTCTime (UTCTime)) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Exon (exon) import Network.HTTP.Client (Cookie (Cookie)) import Network.HTTP.Client.Internal (CookieJar (CJ, expose)) import Prelude hiding (get, put) import Polysemy.Http.Data.Request ( Body, Host (Host), Method (..), Path (Path), Port (Port), Request (Request), Tls (Tls), ) invalidScheme :: Text -> Text -> Either Text a invalidScheme scheme url = Left [exon|invalid scheme `#{scheme}` in url: #{url}|] split :: Text -> Text -> (Text, Maybe Text) split target t = case Text.breakOn target t of (a, "") -> (a, Nothing) (a, b) -> (a, Just (Text.drop (Text.length target) b)) parseScheme :: Text -> (Text, Maybe Text) -> Either Text (Tls, Text) parseScheme url = \case (full, Nothing) -> Right (Tls True, full) ("https", Just rest) -> Right (Tls True, rest) ("http", Just rest) -> Right (Tls False, rest) (scheme, _) -> invalidScheme scheme url parseHostPort :: Text -> (Text, Maybe Text) -> Either Text (Host, Maybe Port) parseHostPort url = \case (host, Nothing) -> Right (Host host, Nothing) (host, Just (readMaybe . toString -> Just port)) -> Right (Host host, Just (Port port)) (_, Just port) -> Left [exon|invalid port `#{port}` in url: #{url}|] parseUrl :: Text -> Either Text (Tls, Host, Maybe Port, Path) parseUrl url = do (tls, split "/" -> (hostPort, path)) <- parseScheme url (split "://" url) (host, port) <- parseHostPort url (split ":" hostPort) pure (tls, host, port, Path (fromMaybe "" path)) -- |Create a request with empty headers, query and cookies. withPort :: Maybe Port -> Tls -> Method -> Host -> Path -> Body -> Request withPort port tls method host path = Request method host port tls path [] (CJ []) [] -- |Create a request with default port and empty headers, query and cookies. withTls :: Tls -> Method -> Host -> Path -> Body -> Request withTls = withPort Nothing |Create a TLS request with default port and empty headers , query and cookies . simple :: Method -> Host -> Path -> Body -> Request simple = withTls (Tls True) |Create a TLS GET request with default port and empty headers , query and cookies . get :: Host -> Path -> Request get host path = simple Get host path "" |Create a TLS POST request with default port and empty headers , query and cookies . post :: Host -> Path -> Body -> Request post host path = simple Post host path |Create a TLS PUT request with default port and empty headers , query and cookies . put :: Host -> Path -> Body -> Request put host path = simple Put host path |Create a TLS DELETE request with default port and empty headers , query and cookies . delete :: Host -> Path -> Request delete host path = simple Delete host path "" -- |Parse the URL and create a request or return a parse error. fromUrl :: Method -> Body -> Text -> Either Text Request fromUrl method body url = do (tls, host, port, path) <- parseUrl url pure (withPort port tls method host path body) -- |Parse URL for a GET. getUrl :: Text -> Either Text Request getUrl = fromUrl Get "" -- |Parse URL for a POST. postUrl :: Body -> Text -> Either Text Request postUrl = fromUrl Post |Parse URL for a PUT . putUrl :: Body -> Text -> Either Text Request putUrl = fromUrl Put -- |Parse URL for a DELETE. deleteUrl :: Text -> Either Text Request deleteUrl = fromUrl Delete "" neverExpire :: UTCTime neverExpire = UTCTime (fromGregorian 9999 1 1) 0 epoch :: UTCTime epoch = posixSecondsToUTCTime 0 -- |Create a cookie with default values. cookie :: Text -> Text -> Text -> Cookie cookie domain name value = Cookie (encodeUtf8 name) (encodeUtf8 value) neverExpire (encodeUtf8 domain) "/" epoch epoch False False False False -- |Add multiple cookies to a request. addCookies :: [Cookie] -> Request -> Request addCookies cookies = #cookies %~ update where update = CJ . (cookies <>) . expose -- |Add a cookie to a request, using default values. addCookie :: Text -> Text -> Text -> Request -> Request addCookie domain name value = addCookies (pure (cookie domain name value))
null
https://raw.githubusercontent.com/tek/polysemy-http/1e639e3e0f26074ec3aba366bd9a9ce8832f86ec/packages/polysemy-http/lib/Polysemy/Http/Request.hs
haskell
# options_haddock prune # |Description: Request Combinators, Internal |Create a request with empty headers, query and cookies. |Create a request with default port and empty headers, query and cookies. |Parse the URL and create a request or return a parse error. |Parse URL for a GET. |Parse URL for a POST. |Parse URL for a DELETE. |Create a cookie with default values. |Add multiple cookies to a request. |Add a cookie to a request, using default values.
module Polysemy.Http.Request where import qualified Data.Text as Text import Data.Time (UTCTime (UTCTime)) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Exon (exon) import Network.HTTP.Client (Cookie (Cookie)) import Network.HTTP.Client.Internal (CookieJar (CJ, expose)) import Prelude hiding (get, put) import Polysemy.Http.Data.Request ( Body, Host (Host), Method (..), Path (Path), Port (Port), Request (Request), Tls (Tls), ) invalidScheme :: Text -> Text -> Either Text a invalidScheme scheme url = Left [exon|invalid scheme `#{scheme}` in url: #{url}|] split :: Text -> Text -> (Text, Maybe Text) split target t = case Text.breakOn target t of (a, "") -> (a, Nothing) (a, b) -> (a, Just (Text.drop (Text.length target) b)) parseScheme :: Text -> (Text, Maybe Text) -> Either Text (Tls, Text) parseScheme url = \case (full, Nothing) -> Right (Tls True, full) ("https", Just rest) -> Right (Tls True, rest) ("http", Just rest) -> Right (Tls False, rest) (scheme, _) -> invalidScheme scheme url parseHostPort :: Text -> (Text, Maybe Text) -> Either Text (Host, Maybe Port) parseHostPort url = \case (host, Nothing) -> Right (Host host, Nothing) (host, Just (readMaybe . toString -> Just port)) -> Right (Host host, Just (Port port)) (_, Just port) -> Left [exon|invalid port `#{port}` in url: #{url}|] parseUrl :: Text -> Either Text (Tls, Host, Maybe Port, Path) parseUrl url = do (tls, split "/" -> (hostPort, path)) <- parseScheme url (split "://" url) (host, port) <- parseHostPort url (split ":" hostPort) pure (tls, host, port, Path (fromMaybe "" path)) withPort :: Maybe Port -> Tls -> Method -> Host -> Path -> Body -> Request withPort port tls method host path = Request method host port tls path [] (CJ []) [] withTls :: Tls -> Method -> Host -> Path -> Body -> Request withTls = withPort Nothing |Create a TLS request with default port and empty headers , query and cookies . simple :: Method -> Host -> Path -> Body -> Request simple = withTls (Tls True) |Create a TLS GET request with default port and empty headers , query and cookies . get :: Host -> Path -> Request get host path = simple Get host path "" |Create a TLS POST request with default port and empty headers , query and cookies . post :: Host -> Path -> Body -> Request post host path = simple Post host path |Create a TLS PUT request with default port and empty headers , query and cookies . put :: Host -> Path -> Body -> Request put host path = simple Put host path |Create a TLS DELETE request with default port and empty headers , query and cookies . delete :: Host -> Path -> Request delete host path = simple Delete host path "" fromUrl :: Method -> Body -> Text -> Either Text Request fromUrl method body url = do (tls, host, port, path) <- parseUrl url pure (withPort port tls method host path body) getUrl :: Text -> Either Text Request getUrl = fromUrl Get "" postUrl :: Body -> Text -> Either Text Request postUrl = fromUrl Post |Parse URL for a PUT . putUrl :: Body -> Text -> Either Text Request putUrl = fromUrl Put deleteUrl :: Text -> Either Text Request deleteUrl = fromUrl Delete "" neverExpire :: UTCTime neverExpire = UTCTime (fromGregorian 9999 1 1) 0 epoch :: UTCTime epoch = posixSecondsToUTCTime 0 cookie :: Text -> Text -> Text -> Cookie cookie domain name value = Cookie (encodeUtf8 name) (encodeUtf8 value) neverExpire (encodeUtf8 domain) "/" epoch epoch False False False False addCookies :: [Cookie] -> Request -> Request addCookies cookies = #cookies %~ update where update = CJ . (cookies <>) . expose addCookie :: Text -> Text -> Text -> Request -> Request addCookie domain name value = addCookies (pure (cookie domain name value))
0700f2c36a6ad1c6a6a6b98a0d108f206eb7d49684a97b990a30f76b629b0ffa
justinkirby/emetric
emetric_loadable.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 %%% @end %%% This source file is subject to the New BSD License . You should have received %%% a copy of the New BSD license with this software. If not, it can be %%% retrieved from: -license.php %%%------------------------------------------------------------------- -module(emetric_loadable). -export([behaviour_info/1]). behaviour_info(callbacks) -> [{deps,0}, {sup,0} ]; behaviour_info(_Other) -> undefined.
null
https://raw.githubusercontent.com/justinkirby/emetric/6310f8f74a787100eb9d6356d2beffabc91fda1e/src/emetric_loadable.erl
erlang
------------------------------------------------------------------- @end a copy of the New BSD license with this software. If not, it can be retrieved from: -license.php -------------------------------------------------------------------
@author < > ( C ) 2011 This source file is subject to the New BSD License . You should have received -module(emetric_loadable). -export([behaviour_info/1]). behaviour_info(callbacks) -> [{deps,0}, {sup,0} ]; behaviour_info(_Other) -> undefined.
26d95b738def0b32a36a98d48d96848980af4a099e03319bba02e573d1f85049
sneeuwballen/zipperposition
AC.mli
This file is free software , part of Zipperposition . See file " license " for more details . * { 1 AC redundancy } open Logtk type spec = AC_intf.spec module type S = AC_intf.S module Make(Env: Env.S) : S with module Env = Env val key_ac : (module S) Flex_state.key val extension : Extensions.t
null
https://raw.githubusercontent.com/sneeuwballen/zipperposition/7f1455fbe2e7509907f927649c288141b1a3a247/src/prover/AC.mli
ocaml
This file is free software , part of Zipperposition . See file " license " for more details . * { 1 AC redundancy } open Logtk type spec = AC_intf.spec module type S = AC_intf.S module Make(Env: Env.S) : S with module Env = Env val key_ac : (module S) Flex_state.key val extension : Extensions.t
720a3f27acda480b810e0b50668f9aba898016cee8511f4d68d8eb5ffef208b7
sadiqj/ocaml-esp32
find_recursive_functions.ml
(**************************************************************************) (* *) (* 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"] let in_function_declarations (function_decls : Flambda.function_declarations) ~backend = let module VCC = Strongly_connected_components.Make (Variable) in let directed_graph = Flambda_utils.fun_vars_referenced_in_decls function_decls ~backend in let connected_components = VCC.connected_components_sorted_from_roots_to_leaf directed_graph in Array.fold_left (fun rec_fun -> function | VCC.No_loop _ -> rec_fun | VCC.Has_loop elts -> List.fold_right Variable.Set.add elts rec_fun) Variable.Set.empty connected_components
null
https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/middle_end/find_recursive_functions.ml
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. ************************************************************************
, 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"] let in_function_declarations (function_decls : Flambda.function_declarations) ~backend = let module VCC = Strongly_connected_components.Make (Variable) in let directed_graph = Flambda_utils.fun_vars_referenced_in_decls function_decls ~backend in let connected_components = VCC.connected_components_sorted_from_roots_to_leaf directed_graph in Array.fold_left (fun rec_fun -> function | VCC.No_loop _ -> rec_fun | VCC.Has_loop elts -> List.fold_right Variable.Set.add elts rec_fun) Variable.Set.empty connected_components
58d57f13aa84afd9a334ba85239a71eee4f7111b381f2319ad5c201ecff8f567
grin-compiler/ghc-grin
Main.hs
module Main where import Prog (prog) # ifdef PAR --main input = prog input --#else -- partain: doesn't actually look at input; real input is wired into Key.lhs main = do str <- getContents putStr (prog str) --#endif
null
https://raw.githubusercontent.com/grin-compiler/ghc-grin/ebc4dca2e1f5b3581d4b84726730564ce909d786/ghc-grin-benchmark/boquist-grin-bench/spectral/cichelli/Main.hs
haskell
main input = prog input #else partain: doesn't actually look at input; #endif
module Main where import Prog (prog) # ifdef PAR real input is wired into Key.lhs main = do str <- getContents putStr (prog str)
c512ba3f2cb57db52cd65679db91a67e64872ec521589863956d341baee4f410
turquoise-hexagon/euler
solution.scm
(import (chicken fixnum)) (define (f n) (let loop ((n n) (acc 0)) (if (fx= n 0) acc (loop (fx/ n 10) (let ((_ (fxmod n 10))) (fx+ acc (fx* _ _))))))) (define (make-valid? n) (let ((acc (make-vector (fx+ n 1)))) (vector-set! acc 1 #f) (vector-set! acc 89 #t) (define (valid? n) (let ((_ (vector-ref acc n))) (if (boolean? _) _ (let ((_ (valid? (f n)))) (vector-set! acc n _) _)))) valid?)) (define (solve n) (let ((valid? (make-valid? n))) (let loop ((i 1) (acc 0)) (if (fx> i n) acc (loop (fx+ i 1) (if (valid? i) (fx+ acc 1) acc)))))) (let ((_ (solve #e1e7))) (print _) (assert (= _ 8581146)))
null
https://raw.githubusercontent.com/turquoise-hexagon/euler/5e4b99a08bc2e99803755c8cfc8df46e99dc8589/src/092/solution.scm
scheme
(import (chicken fixnum)) (define (f n) (let loop ((n n) (acc 0)) (if (fx= n 0) acc (loop (fx/ n 10) (let ((_ (fxmod n 10))) (fx+ acc (fx* _ _))))))) (define (make-valid? n) (let ((acc (make-vector (fx+ n 1)))) (vector-set! acc 1 #f) (vector-set! acc 89 #t) (define (valid? n) (let ((_ (vector-ref acc n))) (if (boolean? _) _ (let ((_ (valid? (f n)))) (vector-set! acc n _) _)))) valid?)) (define (solve n) (let ((valid? (make-valid? n))) (let loop ((i 1) (acc 0)) (if (fx> i n) acc (loop (fx+ i 1) (if (valid? i) (fx+ acc 1) acc)))))) (let ((_ (solve #e1e7))) (print _) (assert (= _ 8581146)))
e668f3d5473dbb70d034c05e80a8d3c9cbd4e12715df08c5e3572a1223c1024b
tnelson/Forge
reader.rkt
#lang racket/base (require racket/port) (require forge/check-ex-spec/library) (require (only-in racket/function curry)) (define (filter-commands parse-tree keep) (filter (lambda (line) (member (car line) keep)) parse-tree)) (define (read-syntax path port) (define assignment-name (read port)) (unless (string? assignment-name) (raise "Argument error: expected string after #lang forge/check-ex-spec; received ~a.~n" assignment-name)) (define assignment-info (check-ex-spec:get-info assignment-name)) (define wheats (map (curry format "~a.rkt" ) (hash-ref assignment-info 'wheats))) (define chaffs (map (curry format "~a.rkt" ) (hash-ref assignment-info 'chaffs))) (define provided (map string->symbol (hash-ref assignment-info 'provides))) (define parse-tree (port->list read port)) (define just-tests (filter-commands parse-tree '(example test inst fun))) (define module-datum `(module forge/check-ex-spec/core-mod racket (require forge/check-ex-spec/library) (require (prefix-in @ racket)) ; Auto-provide all defined values (provide (except-out (all-defined-out) forge:n)) ; Used for evaluator (define-namespace-anchor forge:n) (forge:nsa forge:n) (define wheat-results (list ,@(map (lambda (wheat) `(with (,@provided #:from ,wheat) (list ,@(for/list ([test just-tests]) test)))) wheats))) (define chaff-results (list ,@(map (lambda (chaff) `(with (,@provided #:from ,chaff) (list ,@(for/list ([test just-tests]) test)))) chaffs))) (for ([wheat-result wheat-results] [num (in-naturals)]) (for ([test wheat-result]) (unless (test-report-passed? test) (raise (format "Failed wheat ~a with test '~a'." num (test-report-name test)))))) (for ([chaff-result chaff-results] [num (in-naturals)]) (define test-results (for/list ([test chaff-result]) (if (test-report-passed? test) #f (test-report-name test)))) (define catchers (filter (lambda (name) name) test-results)) (if (@> (length catchers) 0) (displayln (format "Caught chaff ~a with tests ~a." num catchers)) (displayln (format "Missed chaff ~a." num)))) #;,@parse-tree)) (datum->syntax #f module-datum)) (provide read-syntax)
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/check-ex-spec/core/lang/reader.rkt
racket
Auto-provide all defined values Used for evaluator ,@parse-tree))
#lang racket/base (require racket/port) (require forge/check-ex-spec/library) (require (only-in racket/function curry)) (define (filter-commands parse-tree keep) (filter (lambda (line) (member (car line) keep)) parse-tree)) (define (read-syntax path port) (define assignment-name (read port)) (unless (string? assignment-name) (raise "Argument error: expected string after #lang forge/check-ex-spec; received ~a.~n" assignment-name)) (define assignment-info (check-ex-spec:get-info assignment-name)) (define wheats (map (curry format "~a.rkt" ) (hash-ref assignment-info 'wheats))) (define chaffs (map (curry format "~a.rkt" ) (hash-ref assignment-info 'chaffs))) (define provided (map string->symbol (hash-ref assignment-info 'provides))) (define parse-tree (port->list read port)) (define just-tests (filter-commands parse-tree '(example test inst fun))) (define module-datum `(module forge/check-ex-spec/core-mod racket (require forge/check-ex-spec/library) (require (prefix-in @ racket)) (provide (except-out (all-defined-out) forge:n)) (define-namespace-anchor forge:n) (forge:nsa forge:n) (define wheat-results (list ,@(map (lambda (wheat) `(with (,@provided #:from ,wheat) (list ,@(for/list ([test just-tests]) test)))) wheats))) (define chaff-results (list ,@(map (lambda (chaff) `(with (,@provided #:from ,chaff) (list ,@(for/list ([test just-tests]) test)))) chaffs))) (for ([wheat-result wheat-results] [num (in-naturals)]) (for ([test wheat-result]) (unless (test-report-passed? test) (raise (format "Failed wheat ~a with test '~a'." num (test-report-name test)))))) (for ([chaff-result chaff-results] [num (in-naturals)]) (define test-results (for/list ([test chaff-result]) (if (test-report-passed? test) #f (test-report-name test)))) (define catchers (filter (lambda (name) name) test-results)) (if (@> (length catchers) 0) (displayln (format "Caught chaff ~a with tests ~a." num catchers)) (displayln (format "Missed chaff ~a." num)))) (datum->syntax #f module-datum)) (provide read-syntax)
e54875b019572badef00b02191b6b30f22b878e51f3df16789b87e87f23b0264
elaforge/karya
Args_test.hs
Copyright 2020 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt module Derive.Args_test where import qualified Derive.Args as Args import qualified Derive.Call as Call import qualified Derive.Call.CallTest as CallTest import qualified Derive.Derive as Derive import qualified Derive.DeriveTest as DeriveTest import qualified Ui.UiTest as UiTest import Util.Test test_lookup_next_pitch :: Test test_lookup_next_pitch = do let run = DeriveTest.extract (DeriveTest.e_environ "next") . DeriveTest.derive_tracks_setup (CallTest.with_note_generator "g" c_gen) "tempo=.5" . UiTest.note_track1 c_gen = CallTest.generator $ \args -> do next <- Args.lookup_next_pitch args Derive.with_val "next" next Call.note equal (run ["g -- 4c", "g -- 4d"]) ([Just "<pitch: 62nn,4d(twelve)>", Nothing], [])
null
https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/Derive/Args_test.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt
Copyright 2020 module Derive.Args_test where import qualified Derive.Args as Args import qualified Derive.Call as Call import qualified Derive.Call.CallTest as CallTest import qualified Derive.Derive as Derive import qualified Derive.DeriveTest as DeriveTest import qualified Ui.UiTest as UiTest import Util.Test test_lookup_next_pitch :: Test test_lookup_next_pitch = do let run = DeriveTest.extract (DeriveTest.e_environ "next") . DeriveTest.derive_tracks_setup (CallTest.with_note_generator "g" c_gen) "tempo=.5" . UiTest.note_track1 c_gen = CallTest.generator $ \args -> do next <- Args.lookup_next_pitch args Derive.with_val "next" next Call.note equal (run ["g -- 4c", "g -- 4d"]) ([Just "<pitch: 62nn,4d(twelve)>", Nothing], [])
9570f74b7599b79cd67d4105d505e3e06d22dec29fc34f773e3155d7df6c5497
marcoheisig/Petalisp
machine-learning.lisp
(in-package :common-lisp-user) (defpackage #:petalisp.examples.machine-learning (:use #:common-lisp #:petalisp) (:export #:trainable-parameter #:softmax #:relu #:make-fully-connected-layer #:make-convolutional-layer #:make-maxpool-layer)) (in-package #:petalisp.examples.machine-learning) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Trainable Parameters (defclass trainable-parameter (parameter) ((%value :initarg :value :accessor trainable-parameter-value))) (defun make-trainable-parameter (initial-value) (let* ((value (lazy-array initial-value)) (element-type (lazy-array-element-type value))) (make-instance 'trainable-parameter :shape (lazy-array-shape value) :element-type (upgraded-array-element-type element-type) :value value))) (declaim (inline trainable-parameter-p)) (defun trainable-parameter-p (object) (typep object 'trainable-parameter)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Machine Learning Building Blocks (defun average (array) (let ((lazy-array (lazy-array array))) (lazy #'/ (lazy-multireduce (lazy-array-rank lazy-array) #'+ lazy-array) (lazy-array-size lazy-array)))) (defun make-random-array (dimensions &key (element-type 't)) (let ((array (make-array dimensions :element-type element-type))) (loop for index below (array-total-size array) do (setf (row-major-aref array index) (1- (random (coerce 2 (array-element-type array)))))) array)) (defun softmax (array) (let* ((lazy-array (lazy-array array)) (totals (lazy #'exp lazy-array))) (lazy #'/ totals (lazy-multireduce (lazy-array-rank lazy-array) #'+ totals)))) (defun relu (array) (let ((lazy-array (lazy-array array))) (lazy #'max (coerce 0 (lazy-array-element-type lazy-array)) lazy-array))) (defun make-fully-connected-layer (array output-shape) (let* ((lazy-array (lazy-array array)) (element-type (lazy-array-element-type lazy-array)) (m (shape-size output-shape)) (n (lazy-array-size lazy-array)) (weights (make-trainable-parameter (lazy #'/ (make-random-array (list m n) :element-type element-type) (* m n)))) (biases (make-trainable-parameter (lazy #'/ (make-random-array m :element-type element-type) m)))) (lazy-reshape (lazy #'+ (lazy-reduce #'+ (lazy #'* (lazy-reshape weights (transform m n to n m)) (lazy-reshape (lazy-flatten array) (transform n to n 0)))) biases) output-shape))) (define-modify-macro minf (&rest numbers) min) (define-modify-macro maxf (&rest numbers) max) (defun make-convolutional-layer (array &key (stencil '()) (n-filters 1)) (let* ((lazy-array (lazy-array array)) (rank (lazy-array-rank array)) (n-weights (length stencil)) (lower-bounds (make-array rank :initial-element 0)) (upper-bounds (make-array rank :initial-element 0)) (d nil)) ;; Determine the dimension of the stencil. (loop for offsets in stencil do (if (null d) (setf d (length offsets)) (assert (= (length offsets) d)))) ;; Determine the bounding box of the stencil. (loop for offsets in stencil do (loop for offset in offsets for index from (- rank d) do (minf (aref lower-bounds index) offset) (maxf (aref upper-bounds index) offset))) ;; Use the bounding box to compute the shape of the result. (let ((result-shape (apply ~ 1 ~* (loop for lb across lower-bounds for ub across upper-bounds for range in (shape-ranges (lazy-array-shape lazy-array)) collect (if (and (integerp lb) (integerp ub)) (let ((lo (- (range-start range) lb)) (hi (- (range-end range) ub))) (assert (< lo hi)) (range lo hi)) range)))) (filters (make-trainable-parameter (make-random-array (list* n-weights n-filters (make-list rank :initial-element 1)) :element-type (lazy-array-element-type lazy-array))))) ;; Compute the result. (lazy-collapse (apply #'lazy #'+ (loop for offsets in stencil for index from 0 collect (lazy #'* (lazy-slice filters index) (lazy-reshape lazy-array (make-transformation :offsets (append (make-list (- rank d) :initial-element 0) (mapcar #'- offsets))) result-shape)))))))) (defun make-maxpool-layer (array pooling-factors) (let* ((pooling-factors (coerce pooling-factors 'vector)) (lazy-array (lazy-array array)) (pooling-ranges (loop for pooling-factor across pooling-factors for range in (shape-ranges (lazy-array-shape lazy-array)) for index from 1 do (check-type pooling-factor (integer 1 *) "a positive integer") (unless (zerop (mod (range-size range) pooling-factor)) (error "~@<The ~:R range of the shape ~S is not ~ divisible by the corresponding pooling factor ~S.~:@>" index (lazy-array-shape lazy-array) pooling-factor)) collect (loop for offset below pooling-factor collect (range (+ (range-start range) offset) (range-end range) (* (range-step range) pooling-factor)))))) (lazy-collapse (apply #'lazy #'max (apply #'alexandria:map-product (lambda (&rest ranges) (lazy-reshape lazy-array (apply ~* ranges))) pooling-ranges))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Training (defun train (network output-training-data &rest training-data-plist &key learning-rate &allow-other-keys) (let* ((trainable-parameters (remove-if-not #'trainable-parameter-p (network-parameters network))) (output-parameters (loop for output in (network-outputs network) collect (make-instance 'parameter :element-type (lazy-array-element-type output) :shape (lazy-array-shape output)))) (gradient (differentiator (network-outputs network) (loop for output in (network-outputs network) for output-parameter in output-parameters collect (lazy #'- output output-parameter)))) (training-network (apply #'make-network (loop for trainable-parameter in trainable-parameters collect (lazy #'- trainable-parameter (lazy #'* learning-rate (funcall gradient trainable-parameter)))))) (n nil)) ;; Determine the training data size. (dolist (data output-training-data) (if (null n) (setf n (range-size (first (shape-ranges (lazy-array-shape data))))) (assert (= n (range-size (first (shape-ranges (lazy-array-shape data)))))))) (alexandria:doplist (parameter data training-data-plist) () (unless (symbolp parameter) (assert (= n (range-size (first (shape-ranges (lazy-array-shape data)))))))) ;; Iterate over the training data. (loop for index below n do (when (and (plusp index) (zerop (mod index 100))) (format t "Processed ~D slices of training data~%" index)) ;; Assemble the arguments. (let ((args '())) ;; Inputs. (alexandria:doplist (parameter data training-data-plist) (unless (symbolp parameter) (push parameter args) (push (lazy-slice data index) args))) ;; Outputs. (loop for data in output-training-data for output-parameter in output-parameters do (push output-parameter args) (push (lazy-slice data index) args)) ;; Trainable parameters. (dolist (trainable-parameter trainable-parameters) (push trainable-parameter args) (push (trainable-parameter-value trainable-parameter) args)) ;; Update all trainable parameters. (let ((new-values (multiple-value-list (apply #'call-network training-network (reverse args))))) (loop for trainable-parameter in trainable-parameters for new-value in new-values do (setf (trainable-parameter-value trainable-parameter) new-value))))) ;; Return the trained network. network)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Classification of MNIST Data Note : We only ship a very small sample of the MNIST data with , ;;; so learning will not be too good. If you want to run serious tests, you should replace these paths with paths to the full MNIST data set . (defparameter *mnist* (asdf:find-component (asdf:find-system "petalisp.examples") "mnist-data")) (defun load-array (&rest path) (numpy-file-format:load-array (asdf:component-pathname (asdf:find-component *mnist* path)))) (defparameter *train-images* (load-array "train-images.npy")) (defparameter *train-labels* (load-array "train-labels.npy")) (defparameter *test-images* (load-array "test-images.npy")) (defparameter *test-labels* (load-array "test-labels.npy")) (defun make-mnist-classification-network () (let* ((input (make-instance 'parameter :shape (~ 0 27 ~ 0 27) :element-type 'single-float))) (values (make-network (relu (make-fully-connected-layer (relu (make-maxpool-layer (make-convolutional-layer (relu (make-maxpool-layer (make-convolutional-layer input :stencil '((0 0) (1 0) (0 1) (-1 0) (0 -1)) :n-filters 12) '(1 2 2))) :stencil '((0 0) (2 0) (0 2) (-2 0) (0 -2)) :n-filters 2) '(1 1 3 3))) (~ 0 9)))) input))) (defun main (&key (n 100) (batch-size 100)) (multiple-value-bind (network input) (make-mnist-classification-network) (loop for offset below n by batch-size do (let* ((batch-range (range offset (+ offset 99))) (batch-data (lazy-slices *train-images* batch-range)) (batch-labels (lazy-slices *train-labels* batch-range)) (input-data (compute (lazy-collapse (lazy #'/ batch-data 255.0)))) (output-data (compute (lazy-collapse (lazy 'coerce (lazy (lambda (n i) (if (= n i) 1.0 0.0)) (lazy-reshape batch-labels (transform i to i 0)) #(0 1 2 3 4 5 6 7 8 9)) 'single-float))))) (format t "Training batch ~S.~%" batch-range) (train network (list output-data) :learning-rate 0.02 input input-data))) network)) (defun check-test-data (network index) (format t "Label: ~S Prediction: ~S~%" (compute (lazy-slice *test-labels* index)) (apply #'call-network network (loop for parameter in (network-parameters network) collect parameter collect (if (trainable-parameter-p parameter) (trainable-parameter-value parameter) (lazy-slice *train-images* index))))))
null
https://raw.githubusercontent.com/marcoheisig/Petalisp/63cfa80d5c482964a5ea9ea03019ab3223d506ec/examples/machine-learning.lisp
lisp
Trainable Parameters Machine Learning Building Blocks Determine the dimension of the stencil. Determine the bounding box of the stencil. Use the bounding box to compute the shape of the result. Compute the result. Training Determine the training data size. Iterate over the training data. Assemble the arguments. Inputs. Outputs. Trainable parameters. Update all trainable parameters. Return the trained network. Classification of MNIST Data so learning will not be too good. If you want to run serious tests,
(in-package :common-lisp-user) (defpackage #:petalisp.examples.machine-learning (:use #:common-lisp #:petalisp) (:export #:trainable-parameter #:softmax #:relu #:make-fully-connected-layer #:make-convolutional-layer #:make-maxpool-layer)) (in-package #:petalisp.examples.machine-learning) (defclass trainable-parameter (parameter) ((%value :initarg :value :accessor trainable-parameter-value))) (defun make-trainable-parameter (initial-value) (let* ((value (lazy-array initial-value)) (element-type (lazy-array-element-type value))) (make-instance 'trainable-parameter :shape (lazy-array-shape value) :element-type (upgraded-array-element-type element-type) :value value))) (declaim (inline trainable-parameter-p)) (defun trainable-parameter-p (object) (typep object 'trainable-parameter)) (defun average (array) (let ((lazy-array (lazy-array array))) (lazy #'/ (lazy-multireduce (lazy-array-rank lazy-array) #'+ lazy-array) (lazy-array-size lazy-array)))) (defun make-random-array (dimensions &key (element-type 't)) (let ((array (make-array dimensions :element-type element-type))) (loop for index below (array-total-size array) do (setf (row-major-aref array index) (1- (random (coerce 2 (array-element-type array)))))) array)) (defun softmax (array) (let* ((lazy-array (lazy-array array)) (totals (lazy #'exp lazy-array))) (lazy #'/ totals (lazy-multireduce (lazy-array-rank lazy-array) #'+ totals)))) (defun relu (array) (let ((lazy-array (lazy-array array))) (lazy #'max (coerce 0 (lazy-array-element-type lazy-array)) lazy-array))) (defun make-fully-connected-layer (array output-shape) (let* ((lazy-array (lazy-array array)) (element-type (lazy-array-element-type lazy-array)) (m (shape-size output-shape)) (n (lazy-array-size lazy-array)) (weights (make-trainable-parameter (lazy #'/ (make-random-array (list m n) :element-type element-type) (* m n)))) (biases (make-trainable-parameter (lazy #'/ (make-random-array m :element-type element-type) m)))) (lazy-reshape (lazy #'+ (lazy-reduce #'+ (lazy #'* (lazy-reshape weights (transform m n to n m)) (lazy-reshape (lazy-flatten array) (transform n to n 0)))) biases) output-shape))) (define-modify-macro minf (&rest numbers) min) (define-modify-macro maxf (&rest numbers) max) (defun make-convolutional-layer (array &key (stencil '()) (n-filters 1)) (let* ((lazy-array (lazy-array array)) (rank (lazy-array-rank array)) (n-weights (length stencil)) (lower-bounds (make-array rank :initial-element 0)) (upper-bounds (make-array rank :initial-element 0)) (d nil)) (loop for offsets in stencil do (if (null d) (setf d (length offsets)) (assert (= (length offsets) d)))) (loop for offsets in stencil do (loop for offset in offsets for index from (- rank d) do (minf (aref lower-bounds index) offset) (maxf (aref upper-bounds index) offset))) (let ((result-shape (apply ~ 1 ~* (loop for lb across lower-bounds for ub across upper-bounds for range in (shape-ranges (lazy-array-shape lazy-array)) collect (if (and (integerp lb) (integerp ub)) (let ((lo (- (range-start range) lb)) (hi (- (range-end range) ub))) (assert (< lo hi)) (range lo hi)) range)))) (filters (make-trainable-parameter (make-random-array (list* n-weights n-filters (make-list rank :initial-element 1)) :element-type (lazy-array-element-type lazy-array))))) (lazy-collapse (apply #'lazy #'+ (loop for offsets in stencil for index from 0 collect (lazy #'* (lazy-slice filters index) (lazy-reshape lazy-array (make-transformation :offsets (append (make-list (- rank d) :initial-element 0) (mapcar #'- offsets))) result-shape)))))))) (defun make-maxpool-layer (array pooling-factors) (let* ((pooling-factors (coerce pooling-factors 'vector)) (lazy-array (lazy-array array)) (pooling-ranges (loop for pooling-factor across pooling-factors for range in (shape-ranges (lazy-array-shape lazy-array)) for index from 1 do (check-type pooling-factor (integer 1 *) "a positive integer") (unless (zerop (mod (range-size range) pooling-factor)) (error "~@<The ~:R range of the shape ~S is not ~ divisible by the corresponding pooling factor ~S.~:@>" index (lazy-array-shape lazy-array) pooling-factor)) collect (loop for offset below pooling-factor collect (range (+ (range-start range) offset) (range-end range) (* (range-step range) pooling-factor)))))) (lazy-collapse (apply #'lazy #'max (apply #'alexandria:map-product (lambda (&rest ranges) (lazy-reshape lazy-array (apply ~* ranges))) pooling-ranges))))) (defun train (network output-training-data &rest training-data-plist &key learning-rate &allow-other-keys) (let* ((trainable-parameters (remove-if-not #'trainable-parameter-p (network-parameters network))) (output-parameters (loop for output in (network-outputs network) collect (make-instance 'parameter :element-type (lazy-array-element-type output) :shape (lazy-array-shape output)))) (gradient (differentiator (network-outputs network) (loop for output in (network-outputs network) for output-parameter in output-parameters collect (lazy #'- output output-parameter)))) (training-network (apply #'make-network (loop for trainable-parameter in trainable-parameters collect (lazy #'- trainable-parameter (lazy #'* learning-rate (funcall gradient trainable-parameter)))))) (n nil)) (dolist (data output-training-data) (if (null n) (setf n (range-size (first (shape-ranges (lazy-array-shape data))))) (assert (= n (range-size (first (shape-ranges (lazy-array-shape data)))))))) (alexandria:doplist (parameter data training-data-plist) () (unless (symbolp parameter) (assert (= n (range-size (first (shape-ranges (lazy-array-shape data)))))))) (loop for index below n do (when (and (plusp index) (zerop (mod index 100))) (format t "Processed ~D slices of training data~%" index)) (let ((args '())) (alexandria:doplist (parameter data training-data-plist) (unless (symbolp parameter) (push parameter args) (push (lazy-slice data index) args))) (loop for data in output-training-data for output-parameter in output-parameters do (push output-parameter args) (push (lazy-slice data index) args)) (dolist (trainable-parameter trainable-parameters) (push trainable-parameter args) (push (trainable-parameter-value trainable-parameter) args)) (let ((new-values (multiple-value-list (apply #'call-network training-network (reverse args))))) (loop for trainable-parameter in trainable-parameters for new-value in new-values do (setf (trainable-parameter-value trainable-parameter) new-value))))) network)) Note : We only ship a very small sample of the MNIST data with , you should replace these paths with paths to the full MNIST data set . (defparameter *mnist* (asdf:find-component (asdf:find-system "petalisp.examples") "mnist-data")) (defun load-array (&rest path) (numpy-file-format:load-array (asdf:component-pathname (asdf:find-component *mnist* path)))) (defparameter *train-images* (load-array "train-images.npy")) (defparameter *train-labels* (load-array "train-labels.npy")) (defparameter *test-images* (load-array "test-images.npy")) (defparameter *test-labels* (load-array "test-labels.npy")) (defun make-mnist-classification-network () (let* ((input (make-instance 'parameter :shape (~ 0 27 ~ 0 27) :element-type 'single-float))) (values (make-network (relu (make-fully-connected-layer (relu (make-maxpool-layer (make-convolutional-layer (relu (make-maxpool-layer (make-convolutional-layer input :stencil '((0 0) (1 0) (0 1) (-1 0) (0 -1)) :n-filters 12) '(1 2 2))) :stencil '((0 0) (2 0) (0 2) (-2 0) (0 -2)) :n-filters 2) '(1 1 3 3))) (~ 0 9)))) input))) (defun main (&key (n 100) (batch-size 100)) (multiple-value-bind (network input) (make-mnist-classification-network) (loop for offset below n by batch-size do (let* ((batch-range (range offset (+ offset 99))) (batch-data (lazy-slices *train-images* batch-range)) (batch-labels (lazy-slices *train-labels* batch-range)) (input-data (compute (lazy-collapse (lazy #'/ batch-data 255.0)))) (output-data (compute (lazy-collapse (lazy 'coerce (lazy (lambda (n i) (if (= n i) 1.0 0.0)) (lazy-reshape batch-labels (transform i to i 0)) #(0 1 2 3 4 5 6 7 8 9)) 'single-float))))) (format t "Training batch ~S.~%" batch-range) (train network (list output-data) :learning-rate 0.02 input input-data))) network)) (defun check-test-data (network index) (format t "Label: ~S Prediction: ~S~%" (compute (lazy-slice *test-labels* index)) (apply #'call-network network (loop for parameter in (network-parameters network) collect parameter collect (if (trainable-parameter-p parameter) (trainable-parameter-value parameter) (lazy-slice *train-images* index))))))
30bf42ec2abce621f2988d29ef50f451aa1a6c7c99decce7db100a53c452195c
noprompt/meander
epsilon.cljc
(ns ^:no-doc meander.match.runtime.epsilon "Functions used by the pattern matcher at runtime." (:require [meander.util.epsilon :as r.util] [clojure.walk :as walk] [clojure.set :as set] [clojure.zip :as zip])) (def permutations r.util/permutations) (def k-combinations r.util/k-combinations) (def ^{:arglists '([s k])} set-k-permutations-with-unselected r.util/set-k-permutations-with-unselected) (def ^{:arglists '([m k])} map-k-permutations-with-unselected r.util/map-k-permutations-with-unselected) (def partitions r.util/partitions) (def coll-zip r.util/coll-zip) (def coll-seq r.util/coll-seq) (def zip-next-seq r.util/zip-next-seq) (def knit r.util/knit) (def FAIL "Special value signaling a match failure. Generated code will often utilize this value for control flow purposes." (with-meta (list) {})) (defn fail? "true if the `x` is the special runtime value `FAIL`, false otherwise." [x] (identical? x FAIL)) (defn run-star-1 {:style/indent :defn} [coll rets body-f then-f] (let [result (reduce (fn [acc xs] (let [acc (body-f acc [xs])] (if (fail? acc) (reduced FAIL) acc))) rets coll)] (if (fail? result) FAIL (then-f result)))) (defn run-star-seq {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (take n coll)] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (drop n coll) rets))) (if (seq coll) FAIL (then-f rets)))))) (defn run-star-seq-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (take n coll)] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-seq-search (drop n coll) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets))))) (defn run-plus-seq-search {:style/indent :defn :arglists '([coll rets cat-length min-reps body-f then-f])} [coll rets n m body-f then-f] (let [m*n (* m n) xs (take m*n coll)] (if (= (count xs) m*n) (let [ys (drop m*n coll)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-seq-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))) (defn run-star-vec {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (subvec coll 0 (min n (count coll)))] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (subvec coll (min n (count coll))) rets))) (if (seq coll) FAIL (then-f rets)))))) (defn run-star-vec-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (subvec coll 0 (min n (count coll)))] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-vec-search (subvec coll n) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets))))) (defn run-plus-vec-search {:style/indent :defn :arglists '([coll rets cat-length min-reps body-f then-f])} [coll rets n m body-f then-f] (let [m*n (* m n) xs (subvec coll 0 (min m*n (count coll)))] (if (= (count xs) m*n) (let [ys (subvec coll m*n)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-vec-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))) #?(:cljs (defn run-star-js-array {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (.slice coll 0 (min (.-length coll) n))] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (.slice coll n) rets))) (if (seq coll) FAIL (then-f rets))))))) #?(:cljs (defn run-star-js-array-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (.slice coll 0 (min n (count coll)))] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-js-array-search (.slice coll n) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets)))))) #?(:cljs (defn run-plus-js-array-search {:style/indent :defn} [coll rets n m body-f then-f] (let [m*n (* m n) xs (.slice coll 0 (min m*n (count coll)))] (if (= (count xs) m*n) (let [ys (.slice coll m*n)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-js-array-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))))
null
https://raw.githubusercontent.com/noprompt/meander/8c0e9457befea5eee71a94a6d8726ed5916875dc/src/meander/match/runtime/epsilon.cljc
clojure
(ns ^:no-doc meander.match.runtime.epsilon "Functions used by the pattern matcher at runtime." (:require [meander.util.epsilon :as r.util] [clojure.walk :as walk] [clojure.set :as set] [clojure.zip :as zip])) (def permutations r.util/permutations) (def k-combinations r.util/k-combinations) (def ^{:arglists '([s k])} set-k-permutations-with-unselected r.util/set-k-permutations-with-unselected) (def ^{:arglists '([m k])} map-k-permutations-with-unselected r.util/map-k-permutations-with-unselected) (def partitions r.util/partitions) (def coll-zip r.util/coll-zip) (def coll-seq r.util/coll-seq) (def zip-next-seq r.util/zip-next-seq) (def knit r.util/knit) (def FAIL "Special value signaling a match failure. Generated code will often utilize this value for control flow purposes." (with-meta (list) {})) (defn fail? "true if the `x` is the special runtime value `FAIL`, false otherwise." [x] (identical? x FAIL)) (defn run-star-1 {:style/indent :defn} [coll rets body-f then-f] (let [result (reduce (fn [acc xs] (let [acc (body-f acc [xs])] (if (fail? acc) (reduced FAIL) acc))) rets coll)] (if (fail? result) FAIL (then-f result)))) (defn run-star-seq {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (take n coll)] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (drop n coll) rets))) (if (seq coll) FAIL (then-f rets)))))) (defn run-star-seq-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (take n coll)] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-seq-search (drop n coll) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets))))) (defn run-plus-seq-search {:style/indent :defn :arglists '([coll rets cat-length min-reps body-f then-f])} [coll rets n m body-f then-f] (let [m*n (* m n) xs (take m*n coll)] (if (= (count xs) m*n) (let [ys (drop m*n coll)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-seq-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))) (defn run-star-vec {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (subvec coll 0 (min n (count coll)))] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (subvec coll (min n (count coll))) rets))) (if (seq coll) FAIL (then-f rets)))))) (defn run-star-vec-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (subvec coll 0 (min n (count coll)))] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-vec-search (subvec coll n) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets))))) (defn run-plus-vec-search {:style/indent :defn :arglists '([coll rets cat-length min-reps body-f then-f])} [coll rets n m body-f then-f] (let [m*n (* m n) xs (subvec coll 0 (min m*n (count coll)))] (if (= (count xs) m*n) (let [ys (subvec coll m*n)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-vec-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))) #?(:cljs (defn run-star-js-array {:style/indent :defn} [coll rets n body-f then-f] (loop [coll coll rets rets] (let [xs (.slice coll 0 (min (.-length coll) n))] (if (= (count xs) n) (let [rets (body-f rets xs)] (if (fail? rets) FAIL (recur (.slice coll n) rets))) (if (seq coll) FAIL (then-f rets))))))) #?(:cljs (defn run-star-js-array-search {:style/indent :defn} [coll rets n body-f then-f] (let [xs (.slice coll 0 (min n (count coll)))] (if (= (count xs) n) (mapcat (fn [rets] (if (fail? rets) nil (run-star-js-array-search (.slice coll n) rets n body-f then-f))) (body-f rets xs)) (if (seq coll) nil (then-f rets)))))) #?(:cljs (defn run-plus-js-array-search {:style/indent :defn} [coll rets n m body-f then-f] (let [m*n (* m n) xs (.slice coll 0 (min m*n (count coll)))] (if (= (count xs) m*n) (let [ys (.slice coll m*n)] (mapcat (fn [rets] (if (fail? rets) nil (run-star-js-array-search ys rets n body-f then-f))) (sequence (apply comp (map (fn [chunk] (mapcat (fn [rets] (if (fail? rets) nil (body-f rets chunk))))) (partition n xs))) [rets]))) (if (seq coll) nil (then-f rets))))))
d352c86d7d3df5957d16798b5fc60da3985a17a30778aca94cc00668bd283169
fission-codes/fission
Prelude.hs
module Fission.Test.CLI.Prelude ( module Fission.Prelude -- , module Test.Tasty , module Test.Tasty.Hspec , module Test.QuickCheck -- , itsProp' , shouldHaveRun ) where import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.Hspec import Test.QuickCheck hiding (Result (..)) import Test.QuickCheck.Instances () import Fission.Prelude hiding (Result (..), log) | Prop test with the default number of tries ( 100 ) itsProp' :: (HasCallStack, Testable a) => String -> a -> SpecWith () itsProp' description prop = it ("🔀 " <> description) $ property prop shouldHaveRun :: ( Eq (OpenUnion logs) , Show (OpenUnion logs) , IsMember eff logs ) => [OpenUnion logs] -> eff -> Expectation shouldHaveRun effLog eff = effLog `shouldContain` [openUnionLift eff]
null
https://raw.githubusercontent.com/fission-codes/fission/9f28864905c1f39421ec08b05f31d1498770fe38/fission-cli/test/Fission/Test/CLI/Prelude.hs
haskell
module Fission.Test.CLI.Prelude ( module Fission.Prelude , module Test.Tasty , module Test.Tasty.Hspec , module Test.QuickCheck , itsProp' , shouldHaveRun ) where import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.Hspec import Test.QuickCheck hiding (Result (..)) import Test.QuickCheck.Instances () import Fission.Prelude hiding (Result (..), log) | Prop test with the default number of tries ( 100 ) itsProp' :: (HasCallStack, Testable a) => String -> a -> SpecWith () itsProp' description prop = it ("🔀 " <> description) $ property prop shouldHaveRun :: ( Eq (OpenUnion logs) , Show (OpenUnion logs) , IsMember eff logs ) => [OpenUnion logs] -> eff -> Expectation shouldHaveRun effLog eff = effLog `shouldContain` [openUnionLift eff]
1055dc46472270ae7b26134660c3525b89b5990687fa856bc29ae5d5bb085955
JoeKennedy/fantasy
LeagueSpec.hs
module Handler.LeagueSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getLeaguesR" $ do error "Spec not implemented: getLeaguesR"
null
https://raw.githubusercontent.com/JoeKennedy/fantasy/eb9dc9bf6074be5c5ca951e323c6497676424dda/test/Handler/LeagueSpec.hs
haskell
module Handler.LeagueSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getLeaguesR" $ do error "Spec not implemented: getLeaguesR"
c3d81ddf95640281346885b3cbe378537343b2651a7f92748272633bd6bf1c28
commercialhaskell/stack
Foo.hs
module Foo () where import Control.Monad.IO.Unlift ()
null
https://raw.githubusercontent.com/commercialhaskell/stack/255cd830627870cdef34b5e54d670ef07882523e/test/integration/tests/5272-only-locals/files/src/Foo.hs
haskell
module Foo () where import Control.Monad.IO.Unlift ()
dbe975c23504ac7e126d5c9b2d87d192f41df94eb9f61d817f995d186b877db4
hatsugai/CCLV
col.ml
open Printf exception Error of string module List = struct include List let iteri2 f xs ys = let rec loop i xs ys = match xs, ys with x::xs', y::ys' -> f i x y; loop (i+1) xs' ys' | _, _ -> () in loop 0 xs ys let fold_lefti f acc xs = let rec fold acc k xs = match xs with [] -> acc | x::xs -> fold (f acc k x) (k+1) xs in fold acc 0 xs let fold_left_map f acc tail xs = let rec g acc rs = function [] -> (acc, rev rs) | x::xs -> let (acc, y) = f acc x in g acc (y::rs) xs in g acc tail xs let find_index_opt pred xs = let rec loop i xs = match xs with [] -> None | x::xs' -> if pred x then Some i else loop (i+1) xs' in loop 0 xs let find_index pred xs = match find_index_opt pred xs with Some i -> i | None -> raise Not_found let assoc_index key alist = let rec loop i alist = match alist with [] -> raise Not_found | (k, v)::alist' -> if k=key then i else loop (i+1) alist' in loop 0 alist let rec member eq x xs = match xs with [] -> false | x'::xs' -> eq x x' || member eq x xs' let last xs = match xs with [] -> raise (Error "last") | x::xs -> let rec f x = function [] -> x | x'::xs -> f x' xs in f x xs let butlast xs = match xs with [] -> raise (Error "butlast") | x::xs -> let rec f rs x = function [] -> List.rev rs | x'::xs -> f (x::rs) x' xs in f [] x xs let take xs n = let rec f k xs rs = if k = n then List.rev rs else match xs with [] -> raise (Error "take: out of range") | x::xs' -> f (k+1) xs' (x::rs) in if n < 0 then raise (Error "take: out of range") else f 0 xs [] let rec drop xs n = let rec f xs n = if n = 0 then xs else match xs with [] -> raise (Error "drop: out of range") | x::xs' -> drop xs' (n-1) in if n < 0 then raise (Error "drop: out of range") else f xs n let rec update xs k x = if xs=[] then raise (Error "list_update: index out of range") else if k=0 then x::(List.tl xs) else (List.hd xs)::(update (List.tl xs) (k-1) x) let remove1 x xs = let rec f rs = function [] -> raise (Error "list_remove1: not found") | y::ys -> if x = y then List.rev_append rs ys else f (y::rs) ys in f [] xs let remove x xs = let rec loop rs xs = match xs with [] -> List.rev rs | y::ys' -> if x = y then loop rs ys' else loop (y::rs) ys' in loop [] xs let insert xs k x = let rec f k rs xs = if k = 0 then List.rev_append rs (x::xs) else match xs with [] -> raise (Error "list_insert: index out of range") | y::ys -> f (k-1) (y::rs) ys in if k < 0 then raise (Error "list_insert: index out of range") else f k [] xs let remove_index xs k = let rec f k rs = function [] -> raise (Error "list_remove_index: index out of range") | x::xs -> if k = 0 then List.rev_append rs xs else f (k-1) (x::rs) xs in if k < 0 then raise (Error "list_remove_index: index out of range") else f k [] xs end module IntSet = struct module X = Set.Make (struct type t = int let compare = compare end) include X let hash s = fold (+) s 0 end module IntMap = struct module X = Map.Make (struct type t = int let compare = compare end) include X let find key map = match find_opt key map with Some v -> v | None -> Error.error (sprintf "IntMap: unknown key: %d" key) let find_with_default key map default = match find_opt key map with Some v -> v | None -> default end
null
https://raw.githubusercontent.com/hatsugai/CCLV/c661c1814f31471ba1eba7ad1d9949e3c5ae9144/src/col.ml
ocaml
open Printf exception Error of string module List = struct include List let iteri2 f xs ys = let rec loop i xs ys = match xs, ys with x::xs', y::ys' -> f i x y; loop (i+1) xs' ys' | _, _ -> () in loop 0 xs ys let fold_lefti f acc xs = let rec fold acc k xs = match xs with [] -> acc | x::xs -> fold (f acc k x) (k+1) xs in fold acc 0 xs let fold_left_map f acc tail xs = let rec g acc rs = function [] -> (acc, rev rs) | x::xs -> let (acc, y) = f acc x in g acc (y::rs) xs in g acc tail xs let find_index_opt pred xs = let rec loop i xs = match xs with [] -> None | x::xs' -> if pred x then Some i else loop (i+1) xs' in loop 0 xs let find_index pred xs = match find_index_opt pred xs with Some i -> i | None -> raise Not_found let assoc_index key alist = let rec loop i alist = match alist with [] -> raise Not_found | (k, v)::alist' -> if k=key then i else loop (i+1) alist' in loop 0 alist let rec member eq x xs = match xs with [] -> false | x'::xs' -> eq x x' || member eq x xs' let last xs = match xs with [] -> raise (Error "last") | x::xs -> let rec f x = function [] -> x | x'::xs -> f x' xs in f x xs let butlast xs = match xs with [] -> raise (Error "butlast") | x::xs -> let rec f rs x = function [] -> List.rev rs | x'::xs -> f (x::rs) x' xs in f [] x xs let take xs n = let rec f k xs rs = if k = n then List.rev rs else match xs with [] -> raise (Error "take: out of range") | x::xs' -> f (k+1) xs' (x::rs) in if n < 0 then raise (Error "take: out of range") else f 0 xs [] let rec drop xs n = let rec f xs n = if n = 0 then xs else match xs with [] -> raise (Error "drop: out of range") | x::xs' -> drop xs' (n-1) in if n < 0 then raise (Error "drop: out of range") else f xs n let rec update xs k x = if xs=[] then raise (Error "list_update: index out of range") else if k=0 then x::(List.tl xs) else (List.hd xs)::(update (List.tl xs) (k-1) x) let remove1 x xs = let rec f rs = function [] -> raise (Error "list_remove1: not found") | y::ys -> if x = y then List.rev_append rs ys else f (y::rs) ys in f [] xs let remove x xs = let rec loop rs xs = match xs with [] -> List.rev rs | y::ys' -> if x = y then loop rs ys' else loop (y::rs) ys' in loop [] xs let insert xs k x = let rec f k rs xs = if k = 0 then List.rev_append rs (x::xs) else match xs with [] -> raise (Error "list_insert: index out of range") | y::ys -> f (k-1) (y::rs) ys in if k < 0 then raise (Error "list_insert: index out of range") else f k [] xs let remove_index xs k = let rec f k rs = function [] -> raise (Error "list_remove_index: index out of range") | x::xs -> if k = 0 then List.rev_append rs xs else f (k-1) (x::rs) xs in if k < 0 then raise (Error "list_remove_index: index out of range") else f k [] xs end module IntSet = struct module X = Set.Make (struct type t = int let compare = compare end) include X let hash s = fold (+) s 0 end module IntMap = struct module X = Map.Make (struct type t = int let compare = compare end) include X let find key map = match find_opt key map with Some v -> v | None -> Error.error (sprintf "IntMap: unknown key: %d" key) let find_with_default key map default = match find_opt key map with Some v -> v | None -> default end
7977721c5a0ba5e011bff21793ea5be9a2c6fe70830065b66016460b613ad179
RichiH/git-annex
Concurrent.hs
git - annex concurrent state - - Copyright 2015 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2015 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Annex.Concurrent where import Annex import Annex.Common import Annex.Action import qualified Annex.Queue import qualified Data.Map as M Allows forking off a thread that uses a copy of the current AnnexState - to run an Annex action . - - The returned IO action can be used to start the thread . - It returns an Annex action that must be run in the original - calling context to merge the forked AnnexState back into the - current AnnexState . - to run an Annex action. - - The returned IO action can be used to start the thread. - It returns an Annex action that must be run in the original - calling context to merge the forked AnnexState back into the - current AnnexState. -} forkState :: Annex a -> Annex (IO (Annex a)) forkState a = do st <- dupState return $ do (ret, newst) <- run st a return $ do mergeState newst return ret Returns a copy of the current AnnexState that is safe to be - used when forking off a thread . - - After an Annex action is run using this AnnexState , it - should be merged back into the current Annex 's state , - by calling mergeState . - used when forking off a thread. - - After an Annex action is run using this AnnexState, it - should be merged back into the current Annex's state, - by calling mergeState. -} dupState :: Annex AnnexState dupState = do st <- Annex.getState id -- avoid sharing eg, open file handles return $ st { Annex.workers = [] , Annex.catfilehandles = M.empty , Annex.checkattrhandle = Nothing , Annex.checkignorehandle = Nothing } Merges the passed AnnexState into the current Annex state . - Also closes various handles in it . - Also closes various handles in it. -} mergeState :: AnnexState -> Annex () mergeState st = do st' <- liftIO $ snd <$> run st stopCoProcesses forM_ (M.toList $ Annex.cleanup st') $ uncurry addCleanup Annex.Queue.mergeFrom st' changeState $ \s -> s { errcounter = errcounter s + errcounter st' }
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Annex/Concurrent.hs
haskell
avoid sharing eg, open file handles
git - annex concurrent state - - Copyright 2015 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2015 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Annex.Concurrent where import Annex import Annex.Common import Annex.Action import qualified Annex.Queue import qualified Data.Map as M Allows forking off a thread that uses a copy of the current AnnexState - to run an Annex action . - - The returned IO action can be used to start the thread . - It returns an Annex action that must be run in the original - calling context to merge the forked AnnexState back into the - current AnnexState . - to run an Annex action. - - The returned IO action can be used to start the thread. - It returns an Annex action that must be run in the original - calling context to merge the forked AnnexState back into the - current AnnexState. -} forkState :: Annex a -> Annex (IO (Annex a)) forkState a = do st <- dupState return $ do (ret, newst) <- run st a return $ do mergeState newst return ret Returns a copy of the current AnnexState that is safe to be - used when forking off a thread . - - After an Annex action is run using this AnnexState , it - should be merged back into the current Annex 's state , - by calling mergeState . - used when forking off a thread. - - After an Annex action is run using this AnnexState, it - should be merged back into the current Annex's state, - by calling mergeState. -} dupState :: Annex AnnexState dupState = do st <- Annex.getState id return $ st { Annex.workers = [] , Annex.catfilehandles = M.empty , Annex.checkattrhandle = Nothing , Annex.checkignorehandle = Nothing } Merges the passed AnnexState into the current Annex state . - Also closes various handles in it . - Also closes various handles in it. -} mergeState :: AnnexState -> Annex () mergeState st = do st' <- liftIO $ snd <$> run st stopCoProcesses forM_ (M.toList $ Annex.cleanup st') $ uncurry addCleanup Annex.Queue.mergeFrom st' changeState $ \s -> s { errcounter = errcounter s + errcounter st' }
3dfd6c733b6330fac9e7ec8e5256c007415f73543a4f01898e44268c647fa92f
rfkm/zou
generic_test.clj
(ns zou.web.view.generic-test (:require [clojure.test :as t] [midje.sweet :refer :all] [zou.component :as c] [zou.finder.proto :as fproto] [zou.web.view.generic :as sut] [zou.web.view.proto :as vproto])) (t/deftest generate-view-test (facts (let [tbl {:index identity}] (c/with-system [c {:view {:zou/constructor sut/map->GenericView :zou/dependencies {:renderable-finder :finder} :zou/optionals {:models :tag.view-model} :dynamic? true} :finder {:zou/constructor (constantly (reify fproto/Finder (find [this k] (get tbl k))))} :model-a {:zou/tags [:tag.view-model] :ak :av}}] (vproto/show (:view c) :index {:foo :bar}) => {:foo :bar :ak :av} (vproto/show (:view c) :index {:ak :av'}) => {:ak :av'} ; can override (vproto/show (:view c) :invalid ..model..) => (throws "Found no view fn") ;; callable ((:view c) :index) => {:ak :av} ((:view c) :index {:foo :bar}) => {:foo :bar :ak :av} (apply (:view c) [:index {:foo :bar}]) => {:foo :bar :ak :av}))))
null
https://raw.githubusercontent.com/rfkm/zou/228feefae3e008f56806589cb8019511981f7b01/web/test/zou/web/view/generic_test.clj
clojure
can override callable
(ns zou.web.view.generic-test (:require [clojure.test :as t] [midje.sweet :refer :all] [zou.component :as c] [zou.finder.proto :as fproto] [zou.web.view.generic :as sut] [zou.web.view.proto :as vproto])) (t/deftest generate-view-test (facts (let [tbl {:index identity}] (c/with-system [c {:view {:zou/constructor sut/map->GenericView :zou/dependencies {:renderable-finder :finder} :zou/optionals {:models :tag.view-model} :dynamic? true} :finder {:zou/constructor (constantly (reify fproto/Finder (find [this k] (get tbl k))))} :model-a {:zou/tags [:tag.view-model] :ak :av}}] (vproto/show (:view c) :index {:foo :bar}) => {:foo :bar :ak :av} (vproto/show (:view c) :invalid ..model..) => (throws "Found no view fn") ((:view c) :index) => {:ak :av} ((:view c) :index {:foo :bar}) => {:foo :bar :ak :av} (apply (:view c) [:index {:foo :bar}]) => {:foo :bar :ak :av}))))
08c9b70721481898a3449403c759c180b3182d9e20057ef2d5974649a799b123
finnishtransportagency/harja
hae_komponenttityypit.clj
(ns harja.palvelin.integraatiot.reimari.sanomat.hae-komponenttityypit "Harja-Reimari integraation HaeKomponenttiTyypit-operaation XML-sanomien luku. ks. resources/xsd/reimari/harja.xsd" (:require [harja.tyokalut.xml :as xml] [clojure.data.zip.xml :as z] [taoensso.timbre :as log] [harja.domain.vesivaylat.komponenttityyppi :as komponenttityyppi] [harja.palvelin.integraatiot.reimari.apurit :refer [paivamaara aikaleima]] [harja.domain.vesivaylat.alus :as alus] [harja.domain.vesivaylat.sopimus :as sopimus] [harja.domain.vesivaylat.turvalaite :as turvalaite] [harja.domain.vesivaylat.vayla :as vayla] [clojure.set :refer [rename-keys]] [harja.pvm :as pvm])) (def komponenttityyppi-attribuutit {:id identity :nimi identity :lisatiedot identity :luokan-id identity :luokan-nimi identity :luokan-lisatiedot identity :luokan-paivitysaika aikaleima :luokan-luontiaika aikaleima :merk-cod identity :luontiaika aikaleima :muokattu aikaleima :alkupvm paivamaara :loppupvm paivamaara}) (defn- lue-komponenttityyppi [komponenttityyppi] (xml/lue-attribuutit komponenttityyppi #(keyword "harja.domain.vesivaylat.komponenttityyppi" (name %)) komponenttityyppi-attribuutit)) (defn hae-komponenttityypit-vastaus [vastaus-xml] (if-let [ht (z/xml1-> vastaus-xml :S:Body :HaeKomponenttiTyypit)] (vec (z/xml-> ht :HaeKomponenttiTyypitResponse :komponenttityyppi lue-komponenttityyppi)) (log/warn "Reimarin komponenttityyppihaun vastaus ei sisällä :HaeKomponenttiTyypit -elementtiä"))) (defn lue-hae-komponenttityypit-vastaus [xml] (hae-komponenttityypit-vastaus (xml/lue xml "UTF-8")))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/8ce0e702df98ccabbda42b088b901f013f0c97d8/src/clj/harja/palvelin/integraatiot/reimari/sanomat/hae_komponenttityypit.clj
clojure
(ns harja.palvelin.integraatiot.reimari.sanomat.hae-komponenttityypit "Harja-Reimari integraation HaeKomponenttiTyypit-operaation XML-sanomien luku. ks. resources/xsd/reimari/harja.xsd" (:require [harja.tyokalut.xml :as xml] [clojure.data.zip.xml :as z] [taoensso.timbre :as log] [harja.domain.vesivaylat.komponenttityyppi :as komponenttityyppi] [harja.palvelin.integraatiot.reimari.apurit :refer [paivamaara aikaleima]] [harja.domain.vesivaylat.alus :as alus] [harja.domain.vesivaylat.sopimus :as sopimus] [harja.domain.vesivaylat.turvalaite :as turvalaite] [harja.domain.vesivaylat.vayla :as vayla] [clojure.set :refer [rename-keys]] [harja.pvm :as pvm])) (def komponenttityyppi-attribuutit {:id identity :nimi identity :lisatiedot identity :luokan-id identity :luokan-nimi identity :luokan-lisatiedot identity :luokan-paivitysaika aikaleima :luokan-luontiaika aikaleima :merk-cod identity :luontiaika aikaleima :muokattu aikaleima :alkupvm paivamaara :loppupvm paivamaara}) (defn- lue-komponenttityyppi [komponenttityyppi] (xml/lue-attribuutit komponenttityyppi #(keyword "harja.domain.vesivaylat.komponenttityyppi" (name %)) komponenttityyppi-attribuutit)) (defn hae-komponenttityypit-vastaus [vastaus-xml] (if-let [ht (z/xml1-> vastaus-xml :S:Body :HaeKomponenttiTyypit)] (vec (z/xml-> ht :HaeKomponenttiTyypitResponse :komponenttityyppi lue-komponenttityyppi)) (log/warn "Reimarin komponenttityyppihaun vastaus ei sisällä :HaeKomponenttiTyypit -elementtiä"))) (defn lue-hae-komponenttityypit-vastaus [xml] (hae-komponenttityypit-vastaus (xml/lue xml "UTF-8")))
bc4f4fe7c4a14c1704be21d44dd132e119dadeb0c9214bb9e4308fd291a25ad7
guibou/streamray
Sampling.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE DataKinds # # LANGUAGE ViewPatterns # -- | Sampling interface module Streamray.Sampling ( sampleCosinus, rotateVector, uniformF, uniform2F, makeBase, Sample2D (..), sampleCosinusMax, sampleSphere, sampleHemiSphere, sampleCosinusLobe, pdfSampleCosinusLobe, pdfSamplingCosinusMax, ) where import Streamray.Linear import System.Random.Stateful data Sample2D = Sample2D {-# UNPACK #-} !Float {-# UNPACK #-} !Float deriving (Show) -- | Sampling random point on unit sphere -- From /~philip.dutre/GI/TotalCompendium.pdf -- Formula 33 sampleSphere :: Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleSphere (Sample2D u v) = let phi = 2 * pi * u sqrt_v_one_minus_v = sqrt (v * (1 - v)) in ( 1 / (4 * pi), unsafeNormalized $ D (2 * cos phi * sqrt_v_one_minus_v) (2 * sin phi * sqrt_v_one_minus_v) (1 - 2 * v) ) -- | Sampling random point on unit hemisphere -- From /~philip.dutre/GI/TotalCompendium.pdf -- Formula 34 sampleHemiSphere :: Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleHemiSphere (Sample2D u v) = let phi = 2 * pi * u sqrt_one_minus_vv = sqrt (1 - v * v) in ( 1 / (2 * pi), unsafeNormalized $ D (cos phi * sqrt_one_minus_vv) (sin phi * sqrt_one_minus_vv) v ) -- | Sampling proportional to cosinus weighted on hemisphere -- From /~philip.dutre/GI/TotalCompendium.pdf Formula 35 : sampling proportional to cosinus weighted on hemisphere sampleCosinus :: -- | Random sample Sample2D -> -- | (pdf, sampledDirection) (Float, V3 ('Direction 'Normalized)) sampleCosinus (Sample2D u v) = let phi = 2 * pi * u sqrt_v = sqrt v theta = acos (sqrt v) sqrt_1_minus_v = sqrt (1 - v) in ( cos theta / pi, unsafeNormalized $ D (cos phi * sqrt_1_minus_v) (sin phi * sqrt_1_minus_v) sqrt_v ) -- | Sampling proportional to cosinus lobe around normal -- From /~philip.dutre/GI/TotalCompendium.pdf -- Formula 36 sampleCosinusLobe :: Float -> -- | Random sample Sample2D -> -- | (pdf, sampledDirection) (Float, V3 ('Direction 'Normalized)) sampleCosinusLobe n (Sample2D u v) = let phi = 2 * pi * u z = v ** (1 / (n + 1)) sqrt_1_minus_z2 = sqrt $ 1 - v ** (2 / (n + 1)) in ( (n + 1) / (2 * pi) * z ** n, unsafeNormalized $ D (cos phi * sqrt_1_minus_z2) (sin phi * sqrt_1_minus_z2) z ) # INLINE sampleCosinusLobe # # INLINE sampleCosinusMax # pdfSampleCosinusLobe :: Float -> Float -> Float pdfSampleCosinusLobe roughness cosTheta = (roughness + 1) / (2 * pi) * cosTheta ** roughness -- -- | Sampling proportional to cosinus weighted on spherical cap -- From /~philip.dutre/GI/TotalCompendium.pdf -- Formula 35(extended): sampling proportional to cosinus weighted on hemisphere sampleCosinusMax :: -- | Theta Max Float -> -- | Random sample Sample2D -> -- | (pdf, sampledDirection) (Float, V3 ('Direction 'Normalized)) sampleCosinusMax cos_theta_max (Sample2D u v) = let phi = 2 * pi * u sqrt_v = sqrt v theta = ( sqrt v ) theta = acos z z = sqrt (1 - v * sin_theta_max2) sin_theta_max2 = 1 - cos_theta_max * cos_theta_max sin_theta_max = sqrt sin_theta_max2 sin_theta_max_sqrt_v = sin_theta_max * sqrt_v in ( cos theta / (pi * sin_theta_max2), unsafeNormalized $ D (cos phi * sin_theta_max_sqrt_v) (sin phi * sin_theta_max_sqrt_v) z ) pdfSamplingCosinusMax :: Float -> Float -> Float pdfSamplingCosinusMax cosThetaMax cosTheta = cosTheta / (pi * sin_theta_max2) where sin_theta_max2 = 1 - cosThetaMax * cosThetaMax data Base = Base {-# UNPACK #-} !(V3 ('Direction 'Normalized)) {-# UNPACK #-} !(V3 ('Direction 'Normalized)) {- INLINE makeBase #-} | Basis rotation , based on / Building an Orthonormal Basis , Revisited makeBase :: -- | Normal (Z of the basis) V3 ('Direction 'Normalized) -> -- | (baseX, baseY) Base makeBase (N x y z) = Base baseX baseY where sign = if z == 0 then 1 else signum z a = -1.0 / (sign + z) b = x * y * a baseX = unsafeNormalized $ D (1 + sign * x * x * a) (sign * b) (- sign * x) baseY = unsafeNormalized $ D b (sign + y * y * a) (- y) -- | Rotate a vector around a normal rotateVector :: -- | Normal V3 ('Direction 'Normalized) -> -- | Vector V3 ('Direction 'Normalized) -> V3 ('Direction 'Normalized) rotateVector normal (N x y z) = let Base baseX baseY = makeBase normal in unsafeNormalized (x .*. baseX .+. y .*. baseY .+. z .*. normal) | Uniform sampling of a random number in [ 0 , 1 ] uniformF :: StatefulGen g m => g -> m Float uniformF = uniformRM (0, 1) uniform2F :: StatefulGen g m => g -> m Sample2D uniform2F g = Sample2D <$> uniformF g <*> uniformF g
null
https://raw.githubusercontent.com/guibou/streamray/a401f3b18b5afa571afcea32b928115155b68ef1/src/Streamray/Sampling.hs
haskell
# LANGUAGE BangPatterns # | Sampling interface # UNPACK # # UNPACK # | Sampling random point on unit sphere From /~philip.dutre/GI/TotalCompendium.pdf Formula 33 | Sampling random point on unit hemisphere From /~philip.dutre/GI/TotalCompendium.pdf Formula 34 | Sampling proportional to cosinus weighted on hemisphere From /~philip.dutre/GI/TotalCompendium.pdf | Random sample | (pdf, sampledDirection) | Sampling proportional to cosinus lobe around normal From /~philip.dutre/GI/TotalCompendium.pdf Formula 36 | Random sample | (pdf, sampledDirection) | Sampling proportional to cosinus weighted on spherical cap From /~philip.dutre/GI/TotalCompendium.pdf Formula 35(extended): sampling proportional to cosinus weighted on hemisphere | Theta Max | Random sample | (pdf, sampledDirection) # UNPACK # # UNPACK # INLINE makeBase # | Normal (Z of the basis) | (baseX, baseY) | Rotate a vector around a normal | Normal | Vector
# LANGUAGE DataKinds # # LANGUAGE ViewPatterns # module Streamray.Sampling ( sampleCosinus, rotateVector, uniformF, uniform2F, makeBase, Sample2D (..), sampleCosinusMax, sampleSphere, sampleHemiSphere, sampleCosinusLobe, pdfSampleCosinusLobe, pdfSamplingCosinusMax, ) where import Streamray.Linear import System.Random.Stateful deriving (Show) sampleSphere :: Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleSphere (Sample2D u v) = let phi = 2 * pi * u sqrt_v_one_minus_v = sqrt (v * (1 - v)) in ( 1 / (4 * pi), unsafeNormalized $ D (2 * cos phi * sqrt_v_one_minus_v) (2 * sin phi * sqrt_v_one_minus_v) (1 - 2 * v) ) sampleHemiSphere :: Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleHemiSphere (Sample2D u v) = let phi = 2 * pi * u sqrt_one_minus_vv = sqrt (1 - v * v) in ( 1 / (2 * pi), unsafeNormalized $ D (cos phi * sqrt_one_minus_vv) (sin phi * sqrt_one_minus_vv) v ) Formula 35 : sampling proportional to cosinus weighted on hemisphere sampleCosinus :: Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleCosinus (Sample2D u v) = let phi = 2 * pi * u sqrt_v = sqrt v theta = acos (sqrt v) sqrt_1_minus_v = sqrt (1 - v) in ( cos theta / pi, unsafeNormalized $ D (cos phi * sqrt_1_minus_v) (sin phi * sqrt_1_minus_v) sqrt_v ) sampleCosinusLobe :: Float -> Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleCosinusLobe n (Sample2D u v) = let phi = 2 * pi * u z = v ** (1 / (n + 1)) sqrt_1_minus_z2 = sqrt $ 1 - v ** (2 / (n + 1)) in ( (n + 1) / (2 * pi) * z ** n, unsafeNormalized $ D (cos phi * sqrt_1_minus_z2) (sin phi * sqrt_1_minus_z2) z ) # INLINE sampleCosinusLobe # # INLINE sampleCosinusMax # pdfSampleCosinusLobe :: Float -> Float -> Float pdfSampleCosinusLobe roughness cosTheta = (roughness + 1) / (2 * pi) * cosTheta ** roughness sampleCosinusMax :: Float -> Sample2D -> (Float, V3 ('Direction 'Normalized)) sampleCosinusMax cos_theta_max (Sample2D u v) = let phi = 2 * pi * u sqrt_v = sqrt v theta = ( sqrt v ) theta = acos z z = sqrt (1 - v * sin_theta_max2) sin_theta_max2 = 1 - cos_theta_max * cos_theta_max sin_theta_max = sqrt sin_theta_max2 sin_theta_max_sqrt_v = sin_theta_max * sqrt_v in ( cos theta / (pi * sin_theta_max2), unsafeNormalized $ D (cos phi * sin_theta_max_sqrt_v) (sin phi * sin_theta_max_sqrt_v) z ) pdfSamplingCosinusMax :: Float -> Float -> Float pdfSamplingCosinusMax cosThetaMax cosTheta = cosTheta / (pi * sin_theta_max2) where sin_theta_max2 = 1 - cosThetaMax * cosThetaMax | Basis rotation , based on / Building an Orthonormal Basis , Revisited makeBase :: V3 ('Direction 'Normalized) -> Base makeBase (N x y z) = Base baseX baseY where sign = if z == 0 then 1 else signum z a = -1.0 / (sign + z) b = x * y * a baseX = unsafeNormalized $ D (1 + sign * x * x * a) (sign * b) (- sign * x) baseY = unsafeNormalized $ D b (sign + y * y * a) (- y) rotateVector :: V3 ('Direction 'Normalized) -> V3 ('Direction 'Normalized) -> V3 ('Direction 'Normalized) rotateVector normal (N x y z) = let Base baseX baseY = makeBase normal in unsafeNormalized (x .*. baseX .+. y .*. baseY .+. z .*. normal) | Uniform sampling of a random number in [ 0 , 1 ] uniformF :: StatefulGen g m => g -> m Float uniformF = uniformRM (0, 1) uniform2F :: StatefulGen g m => g -> m Sample2D uniform2F g = Sample2D <$> uniformF g <*> uniformF g
8b93f686482faba31e66bf29d5f1f99a7c87e65c2679f033588b63ea7583a129
Snapbrillia/quadraticvoting
Help.hs
module CLI.Help ( generic , forGenerating , forEndpoint ) where import qualified Data.List as List generic :: String generic = -- {{{ "\nQVF off-chain assistive CLI application." ++ "\n" ++ "\nYou can separately print the guide for each endpoint with" ++ "\n(-h|--help|man) following the desired action. Available" ++ "\nendpoints are:" ++ "\n" ++ "\nSmart Contract Initiation:" ++ "\n\tqvf-cli generate scripts --help" ++ "\n" ++ "\nSmart Contract Interaction:" ++ "\n\tqvf-cli register-project --help" ++ "\n\tqvf-cli donate-to-project --help" ++ "\n\tqvf-cli contribute --help" ++ "\n\tqvf-cli fold-donations --help" ++ "\n\tqvf-cli consolidate-donations --help" ++ "\n\tqvf-cli traverse-donations --help" ++ "\n\tqvf-cli accumulate-prize-weights --help" ++ "\n\tqvf-cli eliminate-one-project --help" ++ "\n\tqvf-cli distribute-prize --help" ++ "\n\tqvf-cli remove-donationless-project --help" ++ "\n" ++ "\nUtility:" ++ "\n\tqvf-cli pretty-datum --help" ++ "\n\tqvf-cli datum-is --help" ++ "\n\tqvf-cli get-constr-index --help" ++ "\n\tqvf-cli data-to-cbor --help" ++ "\n\tqvf-cli cbor-to-data --help" ++ "\n\tqvf-cli string-to-hex --help" ++ "\n\tqvf-cli get-deadline-slot --help" ++ "\n\tqvf-cli emulate-outcome --help" ++ "\n\tqvf-cli pretty-leaderboard --help" ++ "\n" ++ "\nOr simply use (-h|--help|man) to print this help text." ++ "\n" ++ "\n" -- }}} forGenerating :: String -> String forGenerating genStr = -- {{{ case genStr of "scripts" -> scriptGeneration _ -> generic -- }}} forEndpoint :: String -> String forEndpoint action = -- {{{ case action of "register-project" -> projectRegistration "donate-to-project" -> donation "fold-donations" -> folding "consolidate-donations" -> consolidation "traverse-donations" -> traversal "accumulate-prize-weights" -> prizeWeightAccumulation "eliminate-one-project" -> projectElimination "distribute-prize" -> distribution "remove-donationless-project" -> donationlessRemoval "pretty-datum" -> prettyDatum "datum-is" -> checkDatum "get-constr-index" -> getConstr "data-to-cbor" -> dataToCBOR "cbor-to-data" -> cborToData "string-to-hex" -> stringToHex "get-deadline-slot" -> deadlineToSlot "emulate-outcome" -> emulateOutcome "pretty-leaderboard" -> prettyLeaderboard _ -> generic -- }}} -- {{{ ENDPOINTS: endpointDescriptionArgs :: String -> String -> String -> [String] -> String endpointDescriptionArgs elem0 description elem1 restOfElems = -- {{{ let elems = elem0 : elem1 : restOfElems cmd :: String cmd = "qvf-cli " makeBlank x = replicate x ' ' preBlank :: String preBlank = "\t" ++ makeBlank (length cmd) longest = -- {{{ length $ List.maximumBy (\arg0 arg1 -> compare (length arg0) (length arg1)) elems -- }}} withPostBlank e = e ++ makeBlank (longest - length e) ++ " \\\n" elemsWithBlanks = map ((preBlank ++) . withPostBlank) $ tail $ init elems in "\n\n\t" ++ description ++ "\n\n" ++ "\t" ++ cmd ++ withPostBlank elem0 ++ concat elemsWithBlanks ++ preBlank ++ last elems ++ "\n" -- }}} commonDescription :: String commonDescription = -- {{{ "Given properly formatted JSON representation of required UTxOs," ++ "\n\tthis endpoint writes the proper redeemer to disk, and also" ++ "\n\treturns a JSON comprising of the needed UTxOs, formatted as:" ++ "\n\t\t{\"inputs\": [{utxo-object}]" ++ "\n\t\t,\"refs\": [{utxo-object}]" ++ "\n\t\t,\"outputs\": [{utxo-object}]" ++ "\n\t\t,\"extra\": <extra-pieces-of-info-for-dev>" ++ "\n\t\t}\n" -- }}} scriptGeneration :: String scriptGeneration = -- {{{ endpointDescriptionArgs "generate scripts" ( "Generate the compiled Plutus validation and minting scripts.\n\n" ++ "\tThe JSON for file names should have these fields:\n\n" ++ "\t\t{ ocfnPreDir :: String\n" ++ "\t\t, ocfnProjectsPreDir :: String\n" ++ "\t\t, ocfnGovernanceMinter :: String\n" ++ "\t\t, ocfnRegistrationMinter :: String\n" ++ "\t\t, ocfnDonationMinter :: String\n" ++ "\t\t, ocfnQVFMainValidator :: String\n" ++ "\t\t, ocfnDeadlineSlot :: String\n" ++ "\t\t, ocfnDeadlineDatum :: String\n" ++ "\t\t, ocfnInitialGovDatum :: String\n" ++ "\t\t, ocfnCurrentDatum :: String\n" ++ "\t\t, ocfnUpdatedDatum :: String\n" ++ "\t\t, ocfnNewDatum :: String\n" ++ "\t\t, ocfnQVFRedeemer :: String\n" ++ "\t\t, ocfnMinterRedeemer :: String\n" ++ "\t\t, ocfnProjectTokenName :: String\n" ++ "\t\t}" ) "<key-holder-pub-key-hash>" [ "<txID>#<output-index>" , "<current-slot-number>" , "<deadline-posix-milliseconds>" , "{file-names-json}" ] -- }}} projectRegistration :: String projectRegistration = -- {{{ endpointDescriptionArgs "register-project" ( "Read the current datum from disk, and write the corresponding files:\n" ++ "\t\t- Updated governance datum,\n" ++ "\t\t- New initial project datum,\n" ++ "\t\t- Static datum for project's info,\n" ++ "\t\t- Redeemer for the QVF validator,\n" ++ "\t\t- Redeemer for the registration policy." ) "<project-owner-pub-key-hash>" [ "<project-name>" , "<project-requested-fund>" , "{file-names-json}" ] -- }}} donation :: String donation = -- {{{ endpointDescriptionArgs "donate-to-project" ( "Read the current datum from disk, and write the corresponding files:\n" ++ "\t\t- Updated project datum,\n" ++ "\t\t- New donation datum,\n" ++ "\t\t- Redeemer for the QVF validator,\n" ++ "\t\t- Redeemer for the donation policy." ) "<donors-pub-key-hash>" [ "<target-project-id>" , "<donation-amount>" , "{file-names-json}" ] -- }}} folding :: String folding = -- {{{ endpointDescriptionArgs "fold-donations" ( "Read the current project datum from disk, and write the\n" ++ "\tupdated project datum to disk. Also prints a JSON\n" ++ "\twith two fields of \"lovelace\" and \"mint\" to help\n" ++ "\tthe bash script construct the `tx-out` argument.\n" ) "<donation(s)-lovelace-count-0>" [ "<donation-count-------------0>" , "{donation-datum-json--------0}" , "<donation(s)-lovelace-count-1>" , "<donation-count-------------1>" , "{donation-datum-json--------1}" , "<...etc...>" , "{file-names-json}" ] -- }}} consolidation :: String consolidation = -- {{{ endpointDescriptionArgs "consolidate-donations" ( "Read the current project datum from disk, and write the\n" ++ "\tupdated project datum to disk. Also prints a JSON\n" ++ "\twith two fields of \"lovelace\" and \"mint\" to help\n" ++ "\tthe bash script construct the `tx-out` argument.\n" ++ "\tThe value in the \"lovelace\" field is the amound that\n" ++ "\tshould be added to the input main UTxO.\n" ) "<donation(s)-lovelace-count-0>" [ "<donation-count-------------0>" , "{folded-donation-datum-json-0}" , "<donation(s)-lovelace-count-1>" , "<donation-count-------------1>" , "{folded-donation-datum-json-1}" , "<...etc...>" , "{file-names-json}" ] -- }}} traversal :: String traversal = -- {{{ endpointDescriptionArgs "traverse-donations" ( "Takes information of two input fully folded donation UTxOs,\n" ++ "\tcompares their donations, and if duplicates where found,\n" ++ "\tit'll return a JSON object with \"lovelace0\" and \"lovelace1\"\n" ++ "\tfields (as resolving the duplication requires exchange of\n" ++ "\tsome Lovelaces). Reallocation of donation assets doesn't\n" ++ "\tseem necessary at this point.\n" ++ "\tIf there are no overlaps, the \"Nothing\" string is returned.\n" ) "<donations-lovelace-count-0>" [ "{donations-datum-json-----0}" , "<donations-lovelace-count-1>" , "{donations-datum-json-----1}" , "{file-names-json}" ] -- }}} prizeWeightAccumulation :: String prizeWeightAccumulation = -- {{{ endpointDescriptionArgs inputCntStr : govInputStr : infoInputsStr : projInputsStr : fileNamesJSON "accumulate-prize-weights" commonDescription "<number-of-projects-to-process>" [ "{governance-input-utxo}" , "[{array-of-project-info-utxos}]" , "[{array-of-project-state-utxos}]" , "{file-names-json}" ] -- }}} projectElimination :: String projectElimination = -- {{{ endpointDescriptionArgs govInputStr : infoInputsStr : projInputsStr : registeredProjsStr : fileNamesJSON "eliminate-one-project" ( commonDescription ++ "\n\tEach registered project's JSON should have 3 fields:" ++ "\n\t\t- \"pkh\": The public key hash (PKH) of the project owner," ++ "\n\t\t- \"address\": The encoded (CIP19) address of said PKH," ++ "\n\t\t- \"tn\": The token name (i.e. identifier) of the project." ++ "\n" ) "{governance-input-utxo}" [ "[{array-of-project-info-utxos}]" , "[{array-of-project-state-utxos}]" , "[{array-of-registered-projects}]" ] -- }}} distribution :: String distribution = -- {{{ endpointDescriptionArgs ownerAddrStr : govInputStr : infoInputStr : projInputStr : fileNamesJSON "distribute-prize" commonDescription "<project-owners-address>" [ "{governance-input-utxo}" , "{project-info-utxo}" , "{project-state-utxo}" , "{file-names-json}" ] -- }}} donationlessRemoval :: String donationlessRemoval = -- {{{ endpointDescriptionArgs -- govInputStr : infoInputStr : projInputStr : fileNamesJSON "remove-donationless-project" ( "Given properly formatted JSON representation of required UTxOs," ++ "\n\tthis endpoint writes the proper redeemers to disk, along with" ++ "\n\tthe updated datum." ) "{governance-input-utxo}" [ "{project-info-utxo}" , "{project-state-utxo}" , "{file-names-json}" ] -- }}} prettyDatum :: String prettyDatum = -- {{{ endpointDescriptionArgs "pretty-datum" "Print an easy-to-read parsing of a given datum JSON:" "{current-datum-json-value}" [] -- }}} checkDatum :: String checkDatum = -- {{{ endpointDescriptionArgs "datum-is" ( "Check whether a given data JSON decodes to a specific `QVFDatum`" ++ "\n\t(returns either \"True\" or \"False\"). Supported keywords are:" ++ "\n\t\tDeadlineDatum" ++ "\n\t\tProjectInfo" ++ "\n\t\tDonationAccumulationConcluded" ) "<predicate-keyword>" ["{current-datum-json-value}"] -- }}} getConstr :: String getConstr = -- {{{ endpointDescriptionArgs "get-constr-index" ( "Given a constructor from `QVFDatum`, this endpoints returns the\n" ++ "\tconstructor index of the `Data` equivalent.\n" ) "<datum-constructor>" [] -- }}} dataToCBOR :: String dataToCBOR = -- {{{ endpointDescriptionArgs "data-to-cbor" "Return the CBOR encoding of a given JSON formatted `Data` value:" "{arbitrary-data-json-value}" [] -- }}} cborToData :: String cborToData = -- {{{ endpointDescriptionArgs "cbor-to-data" "Attempt decoding a CBOR to a JSON formatted `Data` value:" "<cbor-hex-string>" [] -- }}} stringToHex :: String stringToHex = -- {{{ endpointDescriptionArgs "string-to-hex" "Export the hex serialization of a token name:" "<token-name>" ["<output.hex>"] -- }}} deadlineToSlot :: String deadlineToSlot = -- {{{ endpointDescriptionArgs "get-deadline-slot" "Convert the deadline in a given datum to the slot number:" "<current-slot-number>" ["<current.datum>"] -- }}} emulateOutcome :: String emulateOutcome = -- {{{ endpointDescriptionArgs "emulate-outcome" ( "Given all of the authentic UTxOs sitting at the script address, this" ++ "\n\tendpoint returns an object with 2 fields:" ++ "\n" ++ "\n\t1. \"infos\": An array of objecs that each carry distribution" ++ "\n\t information of a project:" ++ "\n" ++ "\n\t\tDistributionInformation" ++ "\n\t\t { \"tn\" : Hex string of project's token name" ++ "\n\t\t , \"requested\" : Project's funding goal" ++ "\n\t\t , \"raised\" : Donations received" ++ "\n\t\t , \"raisedAfterFee\" : Donations after deduction of the platform fee" ++ "\n\t\t , \"matchPool\" : Rightful portion from the match pool" ++ "\n\t\t , \"matchPoolAfterFee\" : Match pool portion after deduction of the fee" ++ "\n\t\t , \"prizeWeight\" : Sum of the square roots of all the received donations, squared" ++ "\n\t\t , \"ratio\" : Value showing how much of the funding goal had been reached" ++ "\n\t\t }" ++ "\n" ++ "\n\t Note that if `ratio` is less than 1, it means that the project" ++ "\n\t had not been eligible to take any money from the match pool." ++ "\n\t Therefore, the net Lovelace count they are going to get is the" ++ "\n\t same as `raisedAfterFee`. Since `ratio` is found by dividing the" ++ "\n\t sum of `raised` and `matchPool` by `requested` (where `matchPool`" ++ "\n\t is found through dividing `prizeWeight` by the total sum of all" ++ "\n\t the remaining projects' prize weights) at the time of elimination," ++ "\n\t this set of information allows a \"leaderboard\" to represent how" ++ "\n\t close an eliminated project had been at the time of elimination." ++ "\n" ++ "\n\t2. \"inputs\": A sorted array of UTxOs which, essentially, is a" ++ "\n\t shorter representation of the input UTxO objects that resulted" ++ "\n\t in the accompanied list of distribution information objects." ) "[{script-utxo}]" [] -- }}} prettyLeaderboard :: String prettyLeaderboard = -- {{{ endpointDescriptionArgs "pretty-leaderboard" ( "Given all of the authentic UTxOs sitting at the script address, this" ++ "\n\tendpoint prints a \"prettified\" representation of the current" ++ "\n\toutcome of the funding round:" ) "[{script-utxo}]" [] -- }}} -- }}}
null
https://raw.githubusercontent.com/Snapbrillia/quadraticvoting/f75cafee5df51d0b05a62a1af5573c874aaf7ba5/quadraticVoting/src/CLI/Help.hs
haskell
{{{ }}} {{{ }}} {{{ }}} {{{ ENDPOINTS: {{{ {{{ }}} }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ govInputStr : infoInputStr : projInputStr : fileNamesJSON }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} {{{ }}} }}}
module CLI.Help ( generic , forGenerating , forEndpoint ) where import qualified Data.List as List generic :: String generic = "\nQVF off-chain assistive CLI application." ++ "\n" ++ "\nYou can separately print the guide for each endpoint with" ++ "\n(-h|--help|man) following the desired action. Available" ++ "\nendpoints are:" ++ "\n" ++ "\nSmart Contract Initiation:" ++ "\n\tqvf-cli generate scripts --help" ++ "\n" ++ "\nSmart Contract Interaction:" ++ "\n\tqvf-cli register-project --help" ++ "\n\tqvf-cli donate-to-project --help" ++ "\n\tqvf-cli contribute --help" ++ "\n\tqvf-cli fold-donations --help" ++ "\n\tqvf-cli consolidate-donations --help" ++ "\n\tqvf-cli traverse-donations --help" ++ "\n\tqvf-cli accumulate-prize-weights --help" ++ "\n\tqvf-cli eliminate-one-project --help" ++ "\n\tqvf-cli distribute-prize --help" ++ "\n\tqvf-cli remove-donationless-project --help" ++ "\n" ++ "\nUtility:" ++ "\n\tqvf-cli pretty-datum --help" ++ "\n\tqvf-cli datum-is --help" ++ "\n\tqvf-cli get-constr-index --help" ++ "\n\tqvf-cli data-to-cbor --help" ++ "\n\tqvf-cli cbor-to-data --help" ++ "\n\tqvf-cli string-to-hex --help" ++ "\n\tqvf-cli get-deadline-slot --help" ++ "\n\tqvf-cli emulate-outcome --help" ++ "\n\tqvf-cli pretty-leaderboard --help" ++ "\n" ++ "\nOr simply use (-h|--help|man) to print this help text." ++ "\n" ++ "\n" forGenerating :: String -> String forGenerating genStr = case genStr of "scripts" -> scriptGeneration _ -> generic forEndpoint :: String -> String forEndpoint action = case action of "register-project" -> projectRegistration "donate-to-project" -> donation "fold-donations" -> folding "consolidate-donations" -> consolidation "traverse-donations" -> traversal "accumulate-prize-weights" -> prizeWeightAccumulation "eliminate-one-project" -> projectElimination "distribute-prize" -> distribution "remove-donationless-project" -> donationlessRemoval "pretty-datum" -> prettyDatum "datum-is" -> checkDatum "get-constr-index" -> getConstr "data-to-cbor" -> dataToCBOR "cbor-to-data" -> cborToData "string-to-hex" -> stringToHex "get-deadline-slot" -> deadlineToSlot "emulate-outcome" -> emulateOutcome "pretty-leaderboard" -> prettyLeaderboard _ -> generic endpointDescriptionArgs :: String -> String -> String -> [String] -> String endpointDescriptionArgs elem0 description elem1 restOfElems = let elems = elem0 : elem1 : restOfElems cmd :: String cmd = "qvf-cli " makeBlank x = replicate x ' ' preBlank :: String preBlank = "\t" ++ makeBlank (length cmd) longest = length $ List.maximumBy (\arg0 arg1 -> compare (length arg0) (length arg1)) elems withPostBlank e = e ++ makeBlank (longest - length e) ++ " \\\n" elemsWithBlanks = map ((preBlank ++) . withPostBlank) $ tail $ init elems in "\n\n\t" ++ description ++ "\n\n" ++ "\t" ++ cmd ++ withPostBlank elem0 ++ concat elemsWithBlanks ++ preBlank ++ last elems ++ "\n" commonDescription :: String commonDescription = "Given properly formatted JSON representation of required UTxOs," ++ "\n\tthis endpoint writes the proper redeemer to disk, and also" ++ "\n\treturns a JSON comprising of the needed UTxOs, formatted as:" ++ "\n\t\t{\"inputs\": [{utxo-object}]" ++ "\n\t\t,\"refs\": [{utxo-object}]" ++ "\n\t\t,\"outputs\": [{utxo-object}]" ++ "\n\t\t,\"extra\": <extra-pieces-of-info-for-dev>" ++ "\n\t\t}\n" scriptGeneration :: String scriptGeneration = endpointDescriptionArgs "generate scripts" ( "Generate the compiled Plutus validation and minting scripts.\n\n" ++ "\tThe JSON for file names should have these fields:\n\n" ++ "\t\t{ ocfnPreDir :: String\n" ++ "\t\t, ocfnProjectsPreDir :: String\n" ++ "\t\t, ocfnGovernanceMinter :: String\n" ++ "\t\t, ocfnRegistrationMinter :: String\n" ++ "\t\t, ocfnDonationMinter :: String\n" ++ "\t\t, ocfnQVFMainValidator :: String\n" ++ "\t\t, ocfnDeadlineSlot :: String\n" ++ "\t\t, ocfnDeadlineDatum :: String\n" ++ "\t\t, ocfnInitialGovDatum :: String\n" ++ "\t\t, ocfnCurrentDatum :: String\n" ++ "\t\t, ocfnUpdatedDatum :: String\n" ++ "\t\t, ocfnNewDatum :: String\n" ++ "\t\t, ocfnQVFRedeemer :: String\n" ++ "\t\t, ocfnMinterRedeemer :: String\n" ++ "\t\t, ocfnProjectTokenName :: String\n" ++ "\t\t}" ) "<key-holder-pub-key-hash>" [ "<txID>#<output-index>" , "<current-slot-number>" , "<deadline-posix-milliseconds>" , "{file-names-json}" ] projectRegistration :: String projectRegistration = endpointDescriptionArgs "register-project" ( "Read the current datum from disk, and write the corresponding files:\n" ++ "\t\t- Updated governance datum,\n" ++ "\t\t- New initial project datum,\n" ++ "\t\t- Static datum for project's info,\n" ++ "\t\t- Redeemer for the QVF validator,\n" ++ "\t\t- Redeemer for the registration policy." ) "<project-owner-pub-key-hash>" [ "<project-name>" , "<project-requested-fund>" , "{file-names-json}" ] donation :: String donation = endpointDescriptionArgs "donate-to-project" ( "Read the current datum from disk, and write the corresponding files:\n" ++ "\t\t- Updated project datum,\n" ++ "\t\t- New donation datum,\n" ++ "\t\t- Redeemer for the QVF validator,\n" ++ "\t\t- Redeemer for the donation policy." ) "<donors-pub-key-hash>" [ "<target-project-id>" , "<donation-amount>" , "{file-names-json}" ] folding :: String folding = endpointDescriptionArgs "fold-donations" ( "Read the current project datum from disk, and write the\n" ++ "\tupdated project datum to disk. Also prints a JSON\n" ++ "\twith two fields of \"lovelace\" and \"mint\" to help\n" ++ "\tthe bash script construct the `tx-out` argument.\n" ) "<donation(s)-lovelace-count-0>" [ "<donation-count-------------0>" , "{donation-datum-json--------0}" , "<donation(s)-lovelace-count-1>" , "<donation-count-------------1>" , "{donation-datum-json--------1}" , "<...etc...>" , "{file-names-json}" ] consolidation :: String consolidation = endpointDescriptionArgs "consolidate-donations" ( "Read the current project datum from disk, and write the\n" ++ "\tupdated project datum to disk. Also prints a JSON\n" ++ "\twith two fields of \"lovelace\" and \"mint\" to help\n" ++ "\tthe bash script construct the `tx-out` argument.\n" ++ "\tThe value in the \"lovelace\" field is the amound that\n" ++ "\tshould be added to the input main UTxO.\n" ) "<donation(s)-lovelace-count-0>" [ "<donation-count-------------0>" , "{folded-donation-datum-json-0}" , "<donation(s)-lovelace-count-1>" , "<donation-count-------------1>" , "{folded-donation-datum-json-1}" , "<...etc...>" , "{file-names-json}" ] traversal :: String traversal = endpointDescriptionArgs "traverse-donations" ( "Takes information of two input fully folded donation UTxOs,\n" ++ "\tcompares their donations, and if duplicates where found,\n" ++ "\tit'll return a JSON object with \"lovelace0\" and \"lovelace1\"\n" ++ "\tfields (as resolving the duplication requires exchange of\n" ++ "\tsome Lovelaces). Reallocation of donation assets doesn't\n" ++ "\tseem necessary at this point.\n" ++ "\tIf there are no overlaps, the \"Nothing\" string is returned.\n" ) "<donations-lovelace-count-0>" [ "{donations-datum-json-----0}" , "<donations-lovelace-count-1>" , "{donations-datum-json-----1}" , "{file-names-json}" ] prizeWeightAccumulation :: String prizeWeightAccumulation = endpointDescriptionArgs inputCntStr : govInputStr : infoInputsStr : projInputsStr : fileNamesJSON "accumulate-prize-weights" commonDescription "<number-of-projects-to-process>" [ "{governance-input-utxo}" , "[{array-of-project-info-utxos}]" , "[{array-of-project-state-utxos}]" , "{file-names-json}" ] projectElimination :: String projectElimination = endpointDescriptionArgs govInputStr : infoInputsStr : projInputsStr : registeredProjsStr : fileNamesJSON "eliminate-one-project" ( commonDescription ++ "\n\tEach registered project's JSON should have 3 fields:" ++ "\n\t\t- \"pkh\": The public key hash (PKH) of the project owner," ++ "\n\t\t- \"address\": The encoded (CIP19) address of said PKH," ++ "\n\t\t- \"tn\": The token name (i.e. identifier) of the project." ++ "\n" ) "{governance-input-utxo}" [ "[{array-of-project-info-utxos}]" , "[{array-of-project-state-utxos}]" , "[{array-of-registered-projects}]" ] distribution :: String distribution = endpointDescriptionArgs ownerAddrStr : govInputStr : infoInputStr : projInputStr : fileNamesJSON "distribute-prize" commonDescription "<project-owners-address>" [ "{governance-input-utxo}" , "{project-info-utxo}" , "{project-state-utxo}" , "{file-names-json}" ] donationlessRemoval :: String donationlessRemoval = endpointDescriptionArgs "remove-donationless-project" ( "Given properly formatted JSON representation of required UTxOs," ++ "\n\tthis endpoint writes the proper redeemers to disk, along with" ++ "\n\tthe updated datum." ) "{governance-input-utxo}" [ "{project-info-utxo}" , "{project-state-utxo}" , "{file-names-json}" ] prettyDatum :: String prettyDatum = endpointDescriptionArgs "pretty-datum" "Print an easy-to-read parsing of a given datum JSON:" "{current-datum-json-value}" [] checkDatum :: String checkDatum = endpointDescriptionArgs "datum-is" ( "Check whether a given data JSON decodes to a specific `QVFDatum`" ++ "\n\t(returns either \"True\" or \"False\"). Supported keywords are:" ++ "\n\t\tDeadlineDatum" ++ "\n\t\tProjectInfo" ++ "\n\t\tDonationAccumulationConcluded" ) "<predicate-keyword>" ["{current-datum-json-value}"] getConstr :: String getConstr = endpointDescriptionArgs "get-constr-index" ( "Given a constructor from `QVFDatum`, this endpoints returns the\n" ++ "\tconstructor index of the `Data` equivalent.\n" ) "<datum-constructor>" [] dataToCBOR :: String dataToCBOR = endpointDescriptionArgs "data-to-cbor" "Return the CBOR encoding of a given JSON formatted `Data` value:" "{arbitrary-data-json-value}" [] cborToData :: String cborToData = endpointDescriptionArgs "cbor-to-data" "Attempt decoding a CBOR to a JSON formatted `Data` value:" "<cbor-hex-string>" [] stringToHex :: String stringToHex = endpointDescriptionArgs "string-to-hex" "Export the hex serialization of a token name:" "<token-name>" ["<output.hex>"] deadlineToSlot :: String deadlineToSlot = endpointDescriptionArgs "get-deadline-slot" "Convert the deadline in a given datum to the slot number:" "<current-slot-number>" ["<current.datum>"] emulateOutcome :: String emulateOutcome = endpointDescriptionArgs "emulate-outcome" ( "Given all of the authentic UTxOs sitting at the script address, this" ++ "\n\tendpoint returns an object with 2 fields:" ++ "\n" ++ "\n\t1. \"infos\": An array of objecs that each carry distribution" ++ "\n\t information of a project:" ++ "\n" ++ "\n\t\tDistributionInformation" ++ "\n\t\t { \"tn\" : Hex string of project's token name" ++ "\n\t\t , \"requested\" : Project's funding goal" ++ "\n\t\t , \"raised\" : Donations received" ++ "\n\t\t , \"raisedAfterFee\" : Donations after deduction of the platform fee" ++ "\n\t\t , \"matchPool\" : Rightful portion from the match pool" ++ "\n\t\t , \"matchPoolAfterFee\" : Match pool portion after deduction of the fee" ++ "\n\t\t , \"prizeWeight\" : Sum of the square roots of all the received donations, squared" ++ "\n\t\t , \"ratio\" : Value showing how much of the funding goal had been reached" ++ "\n\t\t }" ++ "\n" ++ "\n\t Note that if `ratio` is less than 1, it means that the project" ++ "\n\t had not been eligible to take any money from the match pool." ++ "\n\t Therefore, the net Lovelace count they are going to get is the" ++ "\n\t same as `raisedAfterFee`. Since `ratio` is found by dividing the" ++ "\n\t sum of `raised` and `matchPool` by `requested` (where `matchPool`" ++ "\n\t is found through dividing `prizeWeight` by the total sum of all" ++ "\n\t the remaining projects' prize weights) at the time of elimination," ++ "\n\t this set of information allows a \"leaderboard\" to represent how" ++ "\n\t close an eliminated project had been at the time of elimination." ++ "\n" ++ "\n\t2. \"inputs\": A sorted array of UTxOs which, essentially, is a" ++ "\n\t shorter representation of the input UTxO objects that resulted" ++ "\n\t in the accompanied list of distribution information objects." ) "[{script-utxo}]" [] prettyLeaderboard :: String prettyLeaderboard = endpointDescriptionArgs "pretty-leaderboard" ( "Given all of the authentic UTxOs sitting at the script address, this" ++ "\n\tendpoint prints a \"prettified\" representation of the current" ++ "\n\toutcome of the funding round:" ) "[{script-utxo}]" []
514c8d441350d2f4970e6a334c70e9da4fbb102de17604c78c5c9753f58fc464
BranchTaken/Hemlock
test_push.ml
open! Basis.Rudiments open! Basis open Stream let test () = let rec test_push_up_to t i n = begin match i <= n with | false -> () | true -> begin let t' = push i t in File.Fmt.stdout |> Fmt.fmt "push " |> Uns.pp i |> Fmt.fmt " " |> (pp Uns.pp) t |> Fmt.fmt " = " |> (pp Uns.pp) t' |> Fmt.fmt "\n" |> ignore; test_push_up_to t' (succ i) n end end in test_push_up_to empty 0L 3L let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/stream/test_push.ml
ocaml
open! Basis.Rudiments open! Basis open Stream let test () = let rec test_push_up_to t i n = begin match i <= n with | false -> () | true -> begin let t' = push i t in File.Fmt.stdout |> Fmt.fmt "push " |> Uns.pp i |> Fmt.fmt " " |> (pp Uns.pp) t |> Fmt.fmt " = " |> (pp Uns.pp) t' |> Fmt.fmt "\n" |> ignore; test_push_up_to t' (succ i) n end end in test_push_up_to empty 0L 3L let _ = test ()
1042536a4f3da09effc97d7810e262a1a805b7fb8bf71dbd85aacd1b6aa268ae
alezost/stumpwm-config
stumpwm-user-attempt.lisp
2019 - 04 - 16 I tried to move from ` : stumpwm ' to ` : stumpwm - user ' module ;; by prepending the following code to my "init.lisp" (and replacing ` : stumpwm ' module name in other files ) . Unfortunately , it did n't work in one very important place ( maybe in some others as well , but ;; this one is enough). When I pressed "s-t c" (bound to `colon' ;; command), I got the following echo message: ;; Error In Command ' colon ' : unknown type specifier : FLOAT - GROUP ;; Apparently , it is some bug in stumpwm , but I did n't bother to dig it . So I will stick to : stumpwm module . It 's not a problem after all , since all my procedures , macros and variables are prefixed with ` al/ ' . Exporting missing symbols from : stumpwm " missing " means they are internal for ` : stumpwm ' module , so they can not be accessed directly from ` : stumpwm - user ' module ( without ;; prefixing them with `stumpwm::'). And since I use these symbols in ;; my config, I export them here. (in-package :stumpwm) (export '(run-prog ;; Key maps and procedures *tile-group-top-map* *tile-group-root-map* *float-group-top-map* *float-group-root-map* print-key-seq key-to-keycode+state Groups , frames and windows switch-to-group group-frames tile-group-last-frame tile-group-frame-head tile-group-current-frame make-frame focus-frame focus-frame-after screen-current-group window-frame frame-window populate-frames focus-frame sync-frame-windows dump-group restore-group *window-info-format* window-property find-matching-windows focus-all sort-windows *float-window-border* *float-window-title-height* float-window-move-resize ;; Colors *bar-hi-color* screen-fg-color screen-bg-color screen-focus-color screen-border-color update-colors-all-screens hex-to-xlib-color)) (in-package :stumpwm-user)
null
https://raw.githubusercontent.com/alezost/stumpwm-config/cb32c8c4e34a183d96b2069e4b23ee15931890da/unused/stumpwm-user-attempt.lisp
lisp
by prepending the following code to my "init.lisp" (and replacing this one is enough). When I pressed "s-t c" (bound to `colon' command), I got the following echo message: prefixing them with `stumpwm::'). And since I use these symbols in my config, I export them here. Key maps and procedures Colors
2019 - 04 - 16 I tried to move from ` : stumpwm ' to ` : stumpwm - user ' module ` : stumpwm ' module name in other files ) . Unfortunately , it did n't work in one very important place ( maybe in some others as well , but Error In Command ' colon ' : unknown type specifier : FLOAT - GROUP Apparently , it is some bug in stumpwm , but I did n't bother to dig it . So I will stick to : stumpwm module . It 's not a problem after all , since all my procedures , macros and variables are prefixed with ` al/ ' . Exporting missing symbols from : stumpwm " missing " means they are internal for ` : stumpwm ' module , so they can not be accessed directly from ` : stumpwm - user ' module ( without (in-package :stumpwm) (export '(run-prog *tile-group-top-map* *tile-group-root-map* *float-group-top-map* *float-group-root-map* print-key-seq key-to-keycode+state Groups , frames and windows switch-to-group group-frames tile-group-last-frame tile-group-frame-head tile-group-current-frame make-frame focus-frame focus-frame-after screen-current-group window-frame frame-window populate-frames focus-frame sync-frame-windows dump-group restore-group *window-info-format* window-property find-matching-windows focus-all sort-windows *float-window-border* *float-window-title-height* float-window-move-resize *bar-hi-color* screen-fg-color screen-bg-color screen-focus-color screen-border-color update-colors-all-screens hex-to-xlib-color)) (in-package :stumpwm-user)
e7736157a8a88092955d0b6166a0fcbe34b4f67e51dd4d8db4265294cdb8926a
jvf/scalaris
iblt.erl
2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > @doc Invertible Bloom Lookup Table Operations : Insert , Delete , Get , ListEntries %% @end 1 ) M.T. Goodrich , %% <em>Invertible Bloom Lookup Tables</em> 2011 ArXiv e - prints . 1101.2245 2 ) , M.T. Goodrich , , %% <em>Whats the Difference? Efficient Set Reconciliation without Prior Context</em> 2011 SIGCOMM'11 Vol.41(4 ) %% @version $Id$ -module(iblt). -author(''). -vsn('$Id$'). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([new/2, new/3, insert/3, delete/3, get/2, list_entries/1]). -export([is_element/2]). -export([get_fpr/1, get_prop/2]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -export_type([options/0]). -type value() :: integer(). -type cell() :: {Count :: non_neg_integer(), KeySum :: binary(), sum c(x ) of all inserted keys x , for c = any hashfunction not in hfs ValSum :: value(), sum c(y ) of all inserted values y , for c = any hashfunction not in hfs -type table() :: [] | [{ColNr :: pos_integer(), Cells :: [cell()]}]. -record(iblt, { HashFunctionSet table = [] :: table(), cell_count = 0 :: non_neg_integer(), col_size = 0 :: non_neg_integer(), %cells per column item_count = 0 :: non_neg_integer() %number of inserted items }). -type iblt() :: #iblt{}. -type option() :: prime. -type options() :: [] | [option()]. -type cell_operation() :: add | remove. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec new(?REP_HFS:hfs(), pos_integer()) -> iblt(). new(Hfs, CellCount) -> new(Hfs, CellCount, [prime]). -spec new(?REP_HFS:hfs(), pos_integer(), options()) -> iblt(). new(Hfs, CellCount, Options) -> K = ?REP_HFS:size(Hfs), {Cells, ColSize} = case proplists:get_bool(prime, Options) of true -> CCS = prime:get_nearest(erlang:round(CellCount / K)), {CCS * K, CCS}; false -> RCC = resize(CellCount, K), {RCC, erlang:round(RCC / K)} end, SubTable = [{0, <<0>> ,0, 0, 0} || _ <- lists:seq(1, ColSize)], Table = [ {I, SubTable} || I <- lists:seq(1, K)], #iblt{ hfs = Hfs, table = Table, cell_count = Cells, col_size = ColSize, item_count = 0 }. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec insert(iblt(), ?RT:key(), value()) -> iblt(). insert(IBLT, Key, Value) -> change_table(IBLT, add, Key, Value). -spec delete(iblt(), ?RT:key(), value()) -> iblt(). delete(IBLT, Key, Value) -> change_table(IBLT, remove, Key, Value). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec operation_val(cell_operation()) -> 1 | -1. operation_val(add) -> 1; operation_val(remove) -> -1. -spec change_table(iblt(), cell_operation(), ?RT:key(), value()) -> iblt(). change_table(#iblt{ hfs = Hfs, table = T, item_count = ItemCount, col_size = ColSize } = IBLT, Operation, Key, Value) -> NT = lists:foldl( fun({ColNr, Col}, NewT) -> NCol = change_cell(Col, ?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize, encode_key(Key), Value, Operation), [{ColNr, NCol} | NewT] end, [], T), IBLT#iblt{ table = NT, item_count = ItemCount + operation_val(Operation)}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec change_cell([cell()], pos_integer(), Key::binary(), value(), cell_operation()) -> [cell()]. change_cell(Column, CellNr, Key, Value, Operation) -> {HeadL, [Cell | TailL]} = lists:split(CellNr, Column), {Count, KeySum, KHSum, ValSum, VHSum} = Cell, lists:append(HeadL, [{Count + operation_val(Operation), util:bin_xor(KeySum, Key), KHSum bxor checksum_fun(Key), ValSum bxor Value, VHSum bxor checksum_fun(Value)} | TailL]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get(iblt(), ?RT:key()) -> value() | not_found. get(#iblt{ table = T, hfs = Hfs, col_size = ColSize }, Key) -> p_get(T, Hfs, ColSize, Key). -spec p_get(table(), ?REP_HFS:hfs(), non_neg_integer(), ?RT:key()) -> value() | not_found. p_get([], _, _, _) -> not_found; p_get([{ColNr, Col} | T], Hfs, ColSize, Key) -> Cell = lists:nth((?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize) + 1, Col), {_, _, _, Val, _} = Cell, case is_pure(Cell) of true -> Val; false -> p_get(T, Hfs, ColSize, Key) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc a cell is pure if count = -1 or 1 , and checksum of key and value correspond to their checksums -spec is_pure(cell()) -> boolean(). is_pure({Count, Key, KeyCheck, Val, ValCheck}) -> (Count =:= 1 orelse Count =:= -1) andalso checksum_fun(Key) =:= KeyCheck andalso checksum_fun(Val) =:= ValCheck. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc lists all correct entries of this structure % correct entries can be retrieved out of pure cells a pure cell : = count = 1 and check_sum(keySum)=keyHashSum and check_sum(valSum)=valHashSum -spec list_entries(iblt()) -> [{?RT:key(), value()}]. list_entries(IBLT) -> p_list_entries(IBLT, []). -spec p_list_entries(iblt(), Acc) -> Acc when is_subtype(Acc, [{?RT:key(), value()} | [{?RT:key(), value()}]]). p_list_entries(#iblt{ table = T } = IBLT, Acc) -> case get_any_entry(T, []) of [] -> lists:flatten(Acc); [_|_] = L -> NewIBLT = lists:foldl(fun({Key, Val}, NT) -> delete(NT, Key, Val) end, IBLT, L), p_list_entries(NewIBLT, [L, Acc]) end. % tries to find any pure entry -spec get_any_entry(table(), [{?RT:key(), value()}]) -> [{?RT:key(), value()}]. get_any_entry([], Acc) -> Acc; get_any_entry([{_, Col} | T], Acc) -> Result = [{decode_key(Key), Val} || {_, Key, _, Val, _} = Cell <- Col, is_pure(Cell)], if Result =:= [] -> get_any_entry(T, lists:append(Result, Acc)); true -> Result end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec is_element(iblt(), ?RT:key()) -> boolean(). is_element(#iblt{ hfs = Hfs, table = T, col_size = ColSize }, Key) -> Found = lists:foldl( fun({ColNr, Col}, Count) -> {C, _, _, _, _} = lists:nth((?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize) + 1, Col), Count + if C > 0 -> 1; true -> 0 end end, 0, T), Found =:= ?REP_HFS:size(Hfs). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc calculates actual false positive rate depending on saturation degree -spec get_fpr(iblt()) -> float(). get_fpr(#iblt{ hfs = Hfs, cell_count = M, item_count = N }) -> K = ?REP_HFS:size(Hfs), math:pow(1 - math:exp((-K * N) / M), K). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_prop(atom(), iblt()) -> any(). get_prop(Prop, IBLT) -> case Prop of item_count -> IBLT#iblt.item_count; col_size -> IBLT#iblt.col_size; cell_count -> IBLT#iblt.cell_count end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% helpers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Hash function for checksum building. -spec checksum_fun(binary() | integer()) -> non_neg_integer(). checksum_fun(X) when is_integer(X) -> erlang:crc32(integer_to_list(X)); checksum_fun(X) -> erlang:crc32(X). @doc Increases until = = 0 . -spec resize(Val::non_neg_integer(), Div::pos_integer()) -> NewVal::non_neg_integer(). resize(Val, Div) -> case Val rem Div of 0 -> Val; Rem -> Val + Div - Rem end. -spec encode_key(?RT:key()) -> binary(). encode_key(Key) -> term_to_binary(Key). -spec decode_key(binary()) -> ?RT:key(). decode_key(BinKey) -> binary_to_term(BinKey).
null
https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/rrepair/iblt.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @end <em>Invertible Bloom Lookup Tables</em> <em>Whats the Difference? Efficient Set Reconciliation without Prior Context</em> @version $Id$ Types cells per column number of inserted items @doc lists all correct entries of this structure correct entries can be retrieved out of pure cells tries to find any pure entry @doc calculates actual false positive rate depending on saturation degree helpers @doc Hash function for checksum building.
2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @doc Invertible Bloom Lookup Table Operations : Insert , Delete , Get , ListEntries 1 ) M.T. Goodrich , 2011 ArXiv e - prints . 1101.2245 2 ) , M.T. Goodrich , , 2011 SIGCOMM'11 Vol.41(4 ) -module(iblt). -author(''). -vsn('$Id$'). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([new/2, new/3, insert/3, delete/3, get/2, list_entries/1]). -export([is_element/2]). -export([get_fpr/1, get_prop/2]). -export_type([options/0]). -type value() :: integer(). -type cell() :: {Count :: non_neg_integer(), KeySum :: binary(), sum c(x ) of all inserted keys x , for c = any hashfunction not in hfs ValSum :: value(), sum c(y ) of all inserted values y , for c = any hashfunction not in hfs -type table() :: [] | [{ColNr :: pos_integer(), Cells :: [cell()]}]. -record(iblt, { HashFunctionSet table = [] :: table(), cell_count = 0 :: non_neg_integer(), }). -type iblt() :: #iblt{}. -type option() :: prime. -type options() :: [] | [option()]. -type cell_operation() :: add | remove. -spec new(?REP_HFS:hfs(), pos_integer()) -> iblt(). new(Hfs, CellCount) -> new(Hfs, CellCount, [prime]). -spec new(?REP_HFS:hfs(), pos_integer(), options()) -> iblt(). new(Hfs, CellCount, Options) -> K = ?REP_HFS:size(Hfs), {Cells, ColSize} = case proplists:get_bool(prime, Options) of true -> CCS = prime:get_nearest(erlang:round(CellCount / K)), {CCS * K, CCS}; false -> RCC = resize(CellCount, K), {RCC, erlang:round(RCC / K)} end, SubTable = [{0, <<0>> ,0, 0, 0} || _ <- lists:seq(1, ColSize)], Table = [ {I, SubTable} || I <- lists:seq(1, K)], #iblt{ hfs = Hfs, table = Table, cell_count = Cells, col_size = ColSize, item_count = 0 }. -spec insert(iblt(), ?RT:key(), value()) -> iblt(). insert(IBLT, Key, Value) -> change_table(IBLT, add, Key, Value). -spec delete(iblt(), ?RT:key(), value()) -> iblt(). delete(IBLT, Key, Value) -> change_table(IBLT, remove, Key, Value). -spec operation_val(cell_operation()) -> 1 | -1. operation_val(add) -> 1; operation_val(remove) -> -1. -spec change_table(iblt(), cell_operation(), ?RT:key(), value()) -> iblt(). change_table(#iblt{ hfs = Hfs, table = T, item_count = ItemCount, col_size = ColSize } = IBLT, Operation, Key, Value) -> NT = lists:foldl( fun({ColNr, Col}, NewT) -> NCol = change_cell(Col, ?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize, encode_key(Key), Value, Operation), [{ColNr, NCol} | NewT] end, [], T), IBLT#iblt{ table = NT, item_count = ItemCount + operation_val(Operation)}. -spec change_cell([cell()], pos_integer(), Key::binary(), value(), cell_operation()) -> [cell()]. change_cell(Column, CellNr, Key, Value, Operation) -> {HeadL, [Cell | TailL]} = lists:split(CellNr, Column), {Count, KeySum, KHSum, ValSum, VHSum} = Cell, lists:append(HeadL, [{Count + operation_val(Operation), util:bin_xor(KeySum, Key), KHSum bxor checksum_fun(Key), ValSum bxor Value, VHSum bxor checksum_fun(Value)} | TailL]). -spec get(iblt(), ?RT:key()) -> value() | not_found. get(#iblt{ table = T, hfs = Hfs, col_size = ColSize }, Key) -> p_get(T, Hfs, ColSize, Key). -spec p_get(table(), ?REP_HFS:hfs(), non_neg_integer(), ?RT:key()) -> value() | not_found. p_get([], _, _, _) -> not_found; p_get([{ColNr, Col} | T], Hfs, ColSize, Key) -> Cell = lists:nth((?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize) + 1, Col), {_, _, _, Val, _} = Cell, case is_pure(Cell) of true -> Val; false -> p_get(T, Hfs, ColSize, Key) end. @doc a cell is pure if count = -1 or 1 , and checksum of key and value correspond to their checksums -spec is_pure(cell()) -> boolean(). is_pure({Count, Key, KeyCheck, Val, ValCheck}) -> (Count =:= 1 orelse Count =:= -1) andalso checksum_fun(Key) =:= KeyCheck andalso checksum_fun(Val) =:= ValCheck. a pure cell : = count = 1 and check_sum(keySum)=keyHashSum and check_sum(valSum)=valHashSum -spec list_entries(iblt()) -> [{?RT:key(), value()}]. list_entries(IBLT) -> p_list_entries(IBLT, []). -spec p_list_entries(iblt(), Acc) -> Acc when is_subtype(Acc, [{?RT:key(), value()} | [{?RT:key(), value()}]]). p_list_entries(#iblt{ table = T } = IBLT, Acc) -> case get_any_entry(T, []) of [] -> lists:flatten(Acc); [_|_] = L -> NewIBLT = lists:foldl(fun({Key, Val}, NT) -> delete(NT, Key, Val) end, IBLT, L), p_list_entries(NewIBLT, [L, Acc]) end. -spec get_any_entry(table(), [{?RT:key(), value()}]) -> [{?RT:key(), value()}]. get_any_entry([], Acc) -> Acc; get_any_entry([{_, Col} | T], Acc) -> Result = [{decode_key(Key), Val} || {_, Key, _, Val, _} = Cell <- Col, is_pure(Cell)], if Result =:= [] -> get_any_entry(T, lists:append(Result, Acc)); true -> Result end. -spec is_element(iblt(), ?RT:key()) -> boolean(). is_element(#iblt{ hfs = Hfs, table = T, col_size = ColSize }, Key) -> Found = lists:foldl( fun({ColNr, Col}, Count) -> {C, _, _, _, _} = lists:nth((?REP_HFS:apply_val(Hfs, ColNr, Key) rem ColSize) + 1, Col), Count + if C > 0 -> 1; true -> 0 end end, 0, T), Found =:= ?REP_HFS:size(Hfs). -spec get_fpr(iblt()) -> float(). get_fpr(#iblt{ hfs = Hfs, cell_count = M, item_count = N }) -> K = ?REP_HFS:size(Hfs), math:pow(1 - math:exp((-K * N) / M), K). -spec get_prop(atom(), iblt()) -> any(). get_prop(Prop, IBLT) -> case Prop of item_count -> IBLT#iblt.item_count; col_size -> IBLT#iblt.col_size; cell_count -> IBLT#iblt.cell_count end. -spec checksum_fun(binary() | integer()) -> non_neg_integer(). checksum_fun(X) when is_integer(X) -> erlang:crc32(integer_to_list(X)); checksum_fun(X) -> erlang:crc32(X). @doc Increases until = = 0 . -spec resize(Val::non_neg_integer(), Div::pos_integer()) -> NewVal::non_neg_integer(). resize(Val, Div) -> case Val rem Div of 0 -> Val; Rem -> Val + Div - Rem end. -spec encode_key(?RT:key()) -> binary(). encode_key(Key) -> term_to_binary(Key). -spec decode_key(binary()) -> ?RT:key(). decode_key(BinKey) -> binary_to_term(BinKey).
ffc3e496ce836bcbf23c162c82568758788b6dfe7a43ebe141dac55641499ad1
matijapretnar/eff
substitution.ml
(** Substitution implementation *) open Utils type t = { type_param_to_type_coercions : Coercion.ty_coercion Type.TyCoercionParam.Map.t; type_param_to_type_subs : Type.ty Type.TyParam.Map.t; dirt_var_to_dirt_coercions : Coercion.dirt_coercion Type.DirtCoercionParam.Map.t; dirt_var_to_dirt_subs : Dirt.t Dirt.Param.Map.t; skel_param_to_skel_subs : Skeleton.t Skeleton.Param.Map.t; } let empty = { type_param_to_type_coercions = Type.TyCoercionParam.Map.empty; type_param_to_type_subs = Type.TyParam.Map.empty; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.empty; dirt_var_to_dirt_subs = Dirt.Param.Map.empty; skel_param_to_skel_subs = Skeleton.Param.Map.empty; } let is_empty sub = Type.TyCoercionParam.Map.is_empty sub.type_param_to_type_coercions && Type.TyParam.Map.is_empty sub.type_param_to_type_subs && Type.DirtCoercionParam.Map.is_empty sub.dirt_var_to_dirt_coercions && Dirt.Param.Map.is_empty sub.dirt_var_to_dirt_subs && Skeleton.Param.Map.is_empty sub.skel_param_to_skel_subs (* Substitution application *) open Type let apply_sub_dirt sub (dirt : Dirt.t) = match dirt.row with | Dirt.Row.Param p -> ( match Dirt.Param.Map.find_opt p sub.dirt_var_to_dirt_subs with | Some drt2 -> Dirt.add_effects dirt.effect_set drt2 | None -> dirt) | Dirt.Row.Empty -> dirt let rec apply_sub_skel sub skeleton = match skeleton with | Skeleton.Param p -> ( match Skeleton.Param.Map.find_opt p sub.skel_param_to_skel_subs with | Some sk1 -> sk1 | None -> skeleton) | Basic _ -> skeleton | Arrow (sk1, sk2) -> Arrow (apply_sub_skel sub sk1, apply_sub_skel sub sk2) | Handler (sk1, sk2) -> Handler (apply_sub_skel sub sk1, apply_sub_skel sub sk2) (* Really consider other cases *) | Apply { ty_name; skel_args } -> Apply { ty_name; skel_args = TyParam.Map.map (fun s -> apply_sub_skel sub s) skel_args; } | Tuple skels -> Tuple (List.map (apply_sub_skel sub) skels) let rec apply_sub_ty sub ty = let ty' = apply_sub_ty' sub ty in { ty' with ty = apply_sub_skel sub ty'.ty } and apply_sub_ty' sub ty : ty = match ty.term with | TyParam typ1 -> ( match Type.TyParam.Map.find_opt typ1 sub.type_param_to_type_subs with | Some ttype -> ttype | None -> { ty with ty = apply_sub_skel sub ty.ty }) | Arrow (tty1, tty2) -> arrow (apply_sub_ty sub tty1, apply_sub_dirty_ty sub tty2) | Apply { ty_name; ty_args } -> Type.apply ( ty_name, TyParam.Map.map (fun (ty, variance) -> (apply_sub_ty sub ty, variance)) ty_args ) | Tuple ttyl -> Type.tuple (List.map (fun x -> apply_sub_ty sub x) ttyl) | Handler (tydrty1, tydrty2) -> Type.handler (apply_sub_dirty_ty sub tydrty1, apply_sub_dirty_ty sub tydrty2) | TyBasic p -> tyBasic p and apply_sub_dirty_ty sub (ty, drt) = (apply_sub_ty sub ty, apply_sub_dirt sub drt) and apply_sub_abs_ty sub (ty, drty) = (apply_sub_ty sub ty, apply_sub_dirty_ty sub drty) and apply_sub_abs2_ty sub (ty1, ty2, drty) = (apply_sub_ty sub ty1, apply_sub_ty sub ty2, apply_sub_dirty_ty sub drty) and apply_sub_ct_ty sub (ty1, ty2) = (apply_sub_ty sub ty1, apply_sub_ty sub ty2) and apply_sub_ct_dirt sub (drt1, drt2) = (apply_sub_dirt sub drt1, apply_sub_dirt sub drt2) let rec apply_sub_tycoer sub ty_coer = match ty_coer.term with | Coercion.TyCoercionVar p -> ( match Type.TyCoercionParam.Map.find_opt p sub.type_param_to_type_coercions with | Some t_coer -> t_coer | None -> { ty_coer with ty = apply_sub_ct_ty sub ty_coer.ty }) | Coercion.ReflTy -> Coercion.reflTy (apply_sub_ty sub (fst ty_coer.ty)) | ArrowCoercion (tycoer1, dirtycoer) -> Coercion.arrowCoercion (apply_sub_tycoer sub tycoer1, apply_sub_dirtycoer sub dirtycoer) | HandlerCoercion (dirtycoer1, dirtycoer2) -> Coercion.handlerCoercion (apply_sub_dirtycoer sub dirtycoer1, apply_sub_dirtycoer sub dirtycoer2) | TupleCoercion tcl -> Coercion.tupleCoercion (List.map (fun x -> apply_sub_tycoer sub x) tcl) | ApplyCoercion { ty_name; tcoers } -> Coercion.applyCoercion ( ty_name, TyParam.Map.map (fun (x, variance) -> (apply_sub_tycoer sub x, variance)) tcoers ) and apply_sub_dirtcoer sub drt_coer = match drt_coer.term with | Coercion.ReflDirt | Empty -> { drt_coer with ty = apply_sub_ct_dirt sub drt_coer.ty } | Coercion.DirtCoercionVar p -> ( match Type.DirtCoercionParam.Map.find_opt p sub.dirt_var_to_dirt_coercions with | Some dc -> dc | None -> { drt_coer with ty = apply_sub_ct_dirt sub drt_coer.ty }) | UnionDirt (es, dirt_coer1) -> Coercion.unionDirt (es, apply_sub_dirtcoer sub dirt_coer1) and apply_sub_dirtycoer (sub : t) { term = ty_coer, dirt_coer; _ } : Coercion.dirty_coercion = let ty_coer' = apply_sub_tycoer sub ty_coer and dirt_coer' = apply_sub_dirtcoer sub dirt_coer in Coercion.bangCoercion (ty_coer', dirt_coer') let apply_substitutions_to_type = apply_sub_ty let apply_substitutions_to_dirt = apply_sub_dirt let apply_substitutions_to_skeleton = apply_sub_skel (* Other type information *) (* Printing and other debug stuff *) let print subs = [ subs.type_param_to_type_coercions |> Type.TyCoercionParam.Map.print Coercion.print_ty_coercion; subs.type_param_to_type_subs |> Type.TyParam.Map.print Type.print_ty; subs.dirt_var_to_dirt_subs |> Dirt.Param.Map.print Dirt.print; subs.dirt_var_to_dirt_coercions |> Type.DirtCoercionParam.Map.print Coercion.print_dirt_coercion; subs.skel_param_to_skel_subs |> Skeleton.Param.Map.print Skeleton.print; ] |> Print.printer_sequence ", " let of_tydef_parameters (params : Type.tydef_params) = let skel_params' = Skeleton.Param.Set.elements params.skel_params |> List.map (fun s -> (s, Skeleton.Param.refresh s)) |> Skeleton.Param.Map.of_bindings and dirt_params' = Dirt.Param.Set.elements params.dirt_params |> List.map (fun d -> (d, Dirt.Param.refresh d)) |> Dirt.Param.Map.of_bindings in let subst = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.map (fun d' -> Dirt.no_effect d') dirt_params'; skel_param_to_skel_subs = Skeleton.Param.Map.map (fun s' -> Skeleton.Param s') skel_params'; } in let ty_params' = Type.TyParam.Map.bindings params.type_params |> List.map (fun (p, (skel, variance)) -> ( p, ( TyParam.refresh p, (apply_substitutions_to_skeleton subst skel, variance) ) )) in let params' = { type_params = ty_params' |> List.map snd |> Type.TyParam.Map.of_bindings; dirt_params = Dirt.Param.Map.bindings dirt_params' |> List.map fst |> Dirt.Param.Set.of_list; skel_params = Skeleton.Param.Map.bindings skel_params' |> List.map fst |> Skeleton.Param.Set.of_list; } and subst' = { subst with type_param_to_type_subs = List.map (fun (k, (p', (skel, _))) -> (k, Type.tyParam p' skel)) ty_params' |> Type.TyParam.Map.of_bindings; } in ( params', subst', List.map (fun (p, (p', _)) -> (p, p')) ty_params' |> TyParam.Map.of_bindings ) let of_parameters (params : Type.Params.t) = let skel_params' = Skeleton.Param.Set.elements params.skel_params |> List.map (fun s -> (s, Skeleton.Param.refresh s)) |> Skeleton.Param.Map.of_bindings and dirt_params' = Dirt.Param.Set.elements params.dirt_params |> List.map (fun d -> (d, Dirt.Param.refresh d)) |> Dirt.Param.Map.of_bindings in let subst = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.map (fun d' -> Dirt.no_effect d') dirt_params'; skel_param_to_skel_subs = Skeleton.Param.Map.map (fun s' -> Skeleton.Param s') skel_params'; } in let ty_params' = Type.TyParam.Map.bindings params.ty_params |> List.map (fun (p, skel) -> ( p, (Type.TyParam.refresh p, apply_substitutions_to_skeleton subst skel) )) in let params' = { Type.Params.ty_params = ty_params' |> List.map snd |> Type.TyParam.Map.of_bindings; dirt_params = Dirt.Param.Map.bindings dirt_params' |> List.map fst |> Dirt.Param.Set.of_list; skel_params = Skeleton.Param.Map.bindings skel_params' |> List.map fst |> Skeleton.Param.Set.of_list; } and subst' = { subst with type_param_to_type_subs = List.map (fun (k, (p', skel)) -> (k, Type.tyParam p' skel)) ty_params' |> Type.TyParam.Map.of_bindings; } in (params', subst') let apply_substitutions_to_substitution new_sub old_sub = { type_param_to_type_coercions = Type.TyCoercionParam.Map.map (apply_sub_tycoer new_sub) old_sub.type_param_to_type_coercions; type_param_to_type_subs = Type.TyParam.Map.map (apply_sub_ty new_sub) old_sub.type_param_to_type_subs; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.map (apply_sub_dirtcoer new_sub) old_sub.dirt_var_to_dirt_coercions; dirt_var_to_dirt_subs = Dirt.Param.Map.map (apply_sub_dirt new_sub) old_sub.dirt_var_to_dirt_subs; skel_param_to_skel_subs = Skeleton.Param.Map.map (apply_sub_skel new_sub) old_sub.skel_param_to_skel_subs; } let merge new_sub old_sub = let old_sub' = apply_substitutions_to_substitution new_sub old_sub in { type_param_to_type_coercions = Type.TyCoercionParam.Map.compatible_union new_sub.type_param_to_type_coercions old_sub'.type_param_to_type_coercions; type_param_to_type_subs = Type.TyParam.Map.compatible_union new_sub.type_param_to_type_subs old_sub'.type_param_to_type_subs; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.compatible_union new_sub.dirt_var_to_dirt_coercions old_sub'.dirt_var_to_dirt_coercions; dirt_var_to_dirt_subs = Dirt.Param.Map.compatible_union new_sub.dirt_var_to_dirt_subs old_sub'.dirt_var_to_dirt_subs; skel_param_to_skel_subs = Skeleton.Param.Map.compatible_union new_sub.skel_param_to_skel_subs old_sub'.skel_param_to_skel_subs; } let add_type_coercion_e parameter t_coercion = { empty with type_param_to_type_coercions = Type.TyCoercionParam.Map.singleton parameter t_coercion; } let add_type_coercion parameter t_coercion sub = assert ( Coercion.equal_ty_coercion t_coercion (apply_sub_tycoer sub t_coercion)); merge (add_type_coercion_e parameter t_coercion) sub let add_type_substitution_e parameter ty = { empty with type_param_to_type_subs = Type.TyParam.Map.singleton parameter ty; } let add_type_substitution parameter ty sub = assert (ty = apply_sub_ty sub ty); merge (add_type_substitution_e parameter ty) sub let add_dirt_var_coercion_e dirt_var dc = { empty with dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.singleton dirt_var dc; } let add_dirt_var_coercion dirt_var dc sub = assert (dc = apply_sub_dirtcoer sub dc); merge (add_dirt_var_coercion_e dirt_var dc) sub let add_dirt_substitution_e dirt_var dirt = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.singleton dirt_var dirt } let add_dirt_substitution dirt_var dirt sub = assert (dirt = apply_sub_dirt sub dirt); merge (add_dirt_substitution_e dirt_var dirt) sub let empty_dirt_substitution empty_dirt_params = Dirt.Param.Set.fold (fun t sbst -> add_dirt_substitution t Dirt.empty sbst) empty_dirt_params empty let add_skel_param_substitution_e param skel = { empty with skel_param_to_skel_subs = Skeleton.Param.Map.singleton param skel; } let add_skel_param_substitution param skel sub = assert (skel = apply_sub_skel sub skel); merge (add_skel_param_substitution_e param skel) sub
null
https://raw.githubusercontent.com/matijapretnar/eff/1be07f0c7fbaadf5c28437bf11fe818aa76640e7/src/01-language/substitution.ml
ocaml
* Substitution implementation Substitution application Really consider other cases Other type information Printing and other debug stuff
open Utils type t = { type_param_to_type_coercions : Coercion.ty_coercion Type.TyCoercionParam.Map.t; type_param_to_type_subs : Type.ty Type.TyParam.Map.t; dirt_var_to_dirt_coercions : Coercion.dirt_coercion Type.DirtCoercionParam.Map.t; dirt_var_to_dirt_subs : Dirt.t Dirt.Param.Map.t; skel_param_to_skel_subs : Skeleton.t Skeleton.Param.Map.t; } let empty = { type_param_to_type_coercions = Type.TyCoercionParam.Map.empty; type_param_to_type_subs = Type.TyParam.Map.empty; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.empty; dirt_var_to_dirt_subs = Dirt.Param.Map.empty; skel_param_to_skel_subs = Skeleton.Param.Map.empty; } let is_empty sub = Type.TyCoercionParam.Map.is_empty sub.type_param_to_type_coercions && Type.TyParam.Map.is_empty sub.type_param_to_type_subs && Type.DirtCoercionParam.Map.is_empty sub.dirt_var_to_dirt_coercions && Dirt.Param.Map.is_empty sub.dirt_var_to_dirt_subs && Skeleton.Param.Map.is_empty sub.skel_param_to_skel_subs open Type let apply_sub_dirt sub (dirt : Dirt.t) = match dirt.row with | Dirt.Row.Param p -> ( match Dirt.Param.Map.find_opt p sub.dirt_var_to_dirt_subs with | Some drt2 -> Dirt.add_effects dirt.effect_set drt2 | None -> dirt) | Dirt.Row.Empty -> dirt let rec apply_sub_skel sub skeleton = match skeleton with | Skeleton.Param p -> ( match Skeleton.Param.Map.find_opt p sub.skel_param_to_skel_subs with | Some sk1 -> sk1 | None -> skeleton) | Basic _ -> skeleton | Arrow (sk1, sk2) -> Arrow (apply_sub_skel sub sk1, apply_sub_skel sub sk2) | Handler (sk1, sk2) -> Handler (apply_sub_skel sub sk1, apply_sub_skel sub sk2) | Apply { ty_name; skel_args } -> Apply { ty_name; skel_args = TyParam.Map.map (fun s -> apply_sub_skel sub s) skel_args; } | Tuple skels -> Tuple (List.map (apply_sub_skel sub) skels) let rec apply_sub_ty sub ty = let ty' = apply_sub_ty' sub ty in { ty' with ty = apply_sub_skel sub ty'.ty } and apply_sub_ty' sub ty : ty = match ty.term with | TyParam typ1 -> ( match Type.TyParam.Map.find_opt typ1 sub.type_param_to_type_subs with | Some ttype -> ttype | None -> { ty with ty = apply_sub_skel sub ty.ty }) | Arrow (tty1, tty2) -> arrow (apply_sub_ty sub tty1, apply_sub_dirty_ty sub tty2) | Apply { ty_name; ty_args } -> Type.apply ( ty_name, TyParam.Map.map (fun (ty, variance) -> (apply_sub_ty sub ty, variance)) ty_args ) | Tuple ttyl -> Type.tuple (List.map (fun x -> apply_sub_ty sub x) ttyl) | Handler (tydrty1, tydrty2) -> Type.handler (apply_sub_dirty_ty sub tydrty1, apply_sub_dirty_ty sub tydrty2) | TyBasic p -> tyBasic p and apply_sub_dirty_ty sub (ty, drt) = (apply_sub_ty sub ty, apply_sub_dirt sub drt) and apply_sub_abs_ty sub (ty, drty) = (apply_sub_ty sub ty, apply_sub_dirty_ty sub drty) and apply_sub_abs2_ty sub (ty1, ty2, drty) = (apply_sub_ty sub ty1, apply_sub_ty sub ty2, apply_sub_dirty_ty sub drty) and apply_sub_ct_ty sub (ty1, ty2) = (apply_sub_ty sub ty1, apply_sub_ty sub ty2) and apply_sub_ct_dirt sub (drt1, drt2) = (apply_sub_dirt sub drt1, apply_sub_dirt sub drt2) let rec apply_sub_tycoer sub ty_coer = match ty_coer.term with | Coercion.TyCoercionVar p -> ( match Type.TyCoercionParam.Map.find_opt p sub.type_param_to_type_coercions with | Some t_coer -> t_coer | None -> { ty_coer with ty = apply_sub_ct_ty sub ty_coer.ty }) | Coercion.ReflTy -> Coercion.reflTy (apply_sub_ty sub (fst ty_coer.ty)) | ArrowCoercion (tycoer1, dirtycoer) -> Coercion.arrowCoercion (apply_sub_tycoer sub tycoer1, apply_sub_dirtycoer sub dirtycoer) | HandlerCoercion (dirtycoer1, dirtycoer2) -> Coercion.handlerCoercion (apply_sub_dirtycoer sub dirtycoer1, apply_sub_dirtycoer sub dirtycoer2) | TupleCoercion tcl -> Coercion.tupleCoercion (List.map (fun x -> apply_sub_tycoer sub x) tcl) | ApplyCoercion { ty_name; tcoers } -> Coercion.applyCoercion ( ty_name, TyParam.Map.map (fun (x, variance) -> (apply_sub_tycoer sub x, variance)) tcoers ) and apply_sub_dirtcoer sub drt_coer = match drt_coer.term with | Coercion.ReflDirt | Empty -> { drt_coer with ty = apply_sub_ct_dirt sub drt_coer.ty } | Coercion.DirtCoercionVar p -> ( match Type.DirtCoercionParam.Map.find_opt p sub.dirt_var_to_dirt_coercions with | Some dc -> dc | None -> { drt_coer with ty = apply_sub_ct_dirt sub drt_coer.ty }) | UnionDirt (es, dirt_coer1) -> Coercion.unionDirt (es, apply_sub_dirtcoer sub dirt_coer1) and apply_sub_dirtycoer (sub : t) { term = ty_coer, dirt_coer; _ } : Coercion.dirty_coercion = let ty_coer' = apply_sub_tycoer sub ty_coer and dirt_coer' = apply_sub_dirtcoer sub dirt_coer in Coercion.bangCoercion (ty_coer', dirt_coer') let apply_substitutions_to_type = apply_sub_ty let apply_substitutions_to_dirt = apply_sub_dirt let apply_substitutions_to_skeleton = apply_sub_skel let print subs = [ subs.type_param_to_type_coercions |> Type.TyCoercionParam.Map.print Coercion.print_ty_coercion; subs.type_param_to_type_subs |> Type.TyParam.Map.print Type.print_ty; subs.dirt_var_to_dirt_subs |> Dirt.Param.Map.print Dirt.print; subs.dirt_var_to_dirt_coercions |> Type.DirtCoercionParam.Map.print Coercion.print_dirt_coercion; subs.skel_param_to_skel_subs |> Skeleton.Param.Map.print Skeleton.print; ] |> Print.printer_sequence ", " let of_tydef_parameters (params : Type.tydef_params) = let skel_params' = Skeleton.Param.Set.elements params.skel_params |> List.map (fun s -> (s, Skeleton.Param.refresh s)) |> Skeleton.Param.Map.of_bindings and dirt_params' = Dirt.Param.Set.elements params.dirt_params |> List.map (fun d -> (d, Dirt.Param.refresh d)) |> Dirt.Param.Map.of_bindings in let subst = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.map (fun d' -> Dirt.no_effect d') dirt_params'; skel_param_to_skel_subs = Skeleton.Param.Map.map (fun s' -> Skeleton.Param s') skel_params'; } in let ty_params' = Type.TyParam.Map.bindings params.type_params |> List.map (fun (p, (skel, variance)) -> ( p, ( TyParam.refresh p, (apply_substitutions_to_skeleton subst skel, variance) ) )) in let params' = { type_params = ty_params' |> List.map snd |> Type.TyParam.Map.of_bindings; dirt_params = Dirt.Param.Map.bindings dirt_params' |> List.map fst |> Dirt.Param.Set.of_list; skel_params = Skeleton.Param.Map.bindings skel_params' |> List.map fst |> Skeleton.Param.Set.of_list; } and subst' = { subst with type_param_to_type_subs = List.map (fun (k, (p', (skel, _))) -> (k, Type.tyParam p' skel)) ty_params' |> Type.TyParam.Map.of_bindings; } in ( params', subst', List.map (fun (p, (p', _)) -> (p, p')) ty_params' |> TyParam.Map.of_bindings ) let of_parameters (params : Type.Params.t) = let skel_params' = Skeleton.Param.Set.elements params.skel_params |> List.map (fun s -> (s, Skeleton.Param.refresh s)) |> Skeleton.Param.Map.of_bindings and dirt_params' = Dirt.Param.Set.elements params.dirt_params |> List.map (fun d -> (d, Dirt.Param.refresh d)) |> Dirt.Param.Map.of_bindings in let subst = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.map (fun d' -> Dirt.no_effect d') dirt_params'; skel_param_to_skel_subs = Skeleton.Param.Map.map (fun s' -> Skeleton.Param s') skel_params'; } in let ty_params' = Type.TyParam.Map.bindings params.ty_params |> List.map (fun (p, skel) -> ( p, (Type.TyParam.refresh p, apply_substitutions_to_skeleton subst skel) )) in let params' = { Type.Params.ty_params = ty_params' |> List.map snd |> Type.TyParam.Map.of_bindings; dirt_params = Dirt.Param.Map.bindings dirt_params' |> List.map fst |> Dirt.Param.Set.of_list; skel_params = Skeleton.Param.Map.bindings skel_params' |> List.map fst |> Skeleton.Param.Set.of_list; } and subst' = { subst with type_param_to_type_subs = List.map (fun (k, (p', skel)) -> (k, Type.tyParam p' skel)) ty_params' |> Type.TyParam.Map.of_bindings; } in (params', subst') let apply_substitutions_to_substitution new_sub old_sub = { type_param_to_type_coercions = Type.TyCoercionParam.Map.map (apply_sub_tycoer new_sub) old_sub.type_param_to_type_coercions; type_param_to_type_subs = Type.TyParam.Map.map (apply_sub_ty new_sub) old_sub.type_param_to_type_subs; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.map (apply_sub_dirtcoer new_sub) old_sub.dirt_var_to_dirt_coercions; dirt_var_to_dirt_subs = Dirt.Param.Map.map (apply_sub_dirt new_sub) old_sub.dirt_var_to_dirt_subs; skel_param_to_skel_subs = Skeleton.Param.Map.map (apply_sub_skel new_sub) old_sub.skel_param_to_skel_subs; } let merge new_sub old_sub = let old_sub' = apply_substitutions_to_substitution new_sub old_sub in { type_param_to_type_coercions = Type.TyCoercionParam.Map.compatible_union new_sub.type_param_to_type_coercions old_sub'.type_param_to_type_coercions; type_param_to_type_subs = Type.TyParam.Map.compatible_union new_sub.type_param_to_type_subs old_sub'.type_param_to_type_subs; dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.compatible_union new_sub.dirt_var_to_dirt_coercions old_sub'.dirt_var_to_dirt_coercions; dirt_var_to_dirt_subs = Dirt.Param.Map.compatible_union new_sub.dirt_var_to_dirt_subs old_sub'.dirt_var_to_dirt_subs; skel_param_to_skel_subs = Skeleton.Param.Map.compatible_union new_sub.skel_param_to_skel_subs old_sub'.skel_param_to_skel_subs; } let add_type_coercion_e parameter t_coercion = { empty with type_param_to_type_coercions = Type.TyCoercionParam.Map.singleton parameter t_coercion; } let add_type_coercion parameter t_coercion sub = assert ( Coercion.equal_ty_coercion t_coercion (apply_sub_tycoer sub t_coercion)); merge (add_type_coercion_e parameter t_coercion) sub let add_type_substitution_e parameter ty = { empty with type_param_to_type_subs = Type.TyParam.Map.singleton parameter ty; } let add_type_substitution parameter ty sub = assert (ty = apply_sub_ty sub ty); merge (add_type_substitution_e parameter ty) sub let add_dirt_var_coercion_e dirt_var dc = { empty with dirt_var_to_dirt_coercions = Type.DirtCoercionParam.Map.singleton dirt_var dc; } let add_dirt_var_coercion dirt_var dc sub = assert (dc = apply_sub_dirtcoer sub dc); merge (add_dirt_var_coercion_e dirt_var dc) sub let add_dirt_substitution_e dirt_var dirt = { empty with dirt_var_to_dirt_subs = Dirt.Param.Map.singleton dirt_var dirt } let add_dirt_substitution dirt_var dirt sub = assert (dirt = apply_sub_dirt sub dirt); merge (add_dirt_substitution_e dirt_var dirt) sub let empty_dirt_substitution empty_dirt_params = Dirt.Param.Set.fold (fun t sbst -> add_dirt_substitution t Dirt.empty sbst) empty_dirt_params empty let add_skel_param_substitution_e param skel = { empty with skel_param_to_skel_subs = Skeleton.Param.Map.singleton param skel; } let add_skel_param_substitution param skel sub = assert (skel = apply_sub_skel sub skel); merge (add_skel_param_substitution_e param skel) sub
d0e71c89900086249d7b4e20e68b8283df5e76e8aa5c5a09d877d7ba95a3d473
reanimate/reanimate
doc_pauseAround.hs
#!/usr/bin/env stack -- stack runghc --package reanimate module Main(main) where import Reanimate import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ pauseAround 1 1 drawProgress
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_pauseAround.hs
haskell
stack runghc --package reanimate
#!/usr/bin/env stack module Main(main) where import Reanimate import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ pauseAround 1 1 drawProgress
832497d3b13c818e4543939df98ff9bdf9654391041af7a5771c1d8a21ff237f
mbutterick/pollen
markdown.rkt
#lang s-exp pollen/private/dialect default-mode-markdown (module reader "private/reader-base.rkt" default-mode-markdown)
null
https://raw.githubusercontent.com/mbutterick/pollen/a4910a86dc62d1147f3aad94b56cecd6499d7aa6/pollen/markdown.rkt
racket
#lang s-exp pollen/private/dialect default-mode-markdown (module reader "private/reader-base.rkt" default-mode-markdown)
ce2b6ebaa7fb38775089fe24931af88a66c75eafc5339eb4f07d0d8ad2ff9906
circuithub/rel8
Each.hs
{-# language FlexibleContexts #-} # language MonoLocalBinds # module Rel8.Query.Each ( each ) where -- base import Prelude -- opaleye import qualified Opaleye.Table as Opaleye -- rel8 import Rel8.Query ( Query ) import Rel8.Query.Opaleye ( fromOpaleye ) import Rel8.Schema.Name ( Selects ) import Rel8.Schema.Table ( TableSchema ) import Rel8.Table.Cols ( fromCols, toCols ) import Rel8.Table.Opaleye ( table, unpackspec ) | Select each row from a table definition . This is equivalent to @FROM each :: Selects names exprs => TableSchema names -> Query exprs each = fmap fromCols . fromOpaleye . Opaleye.selectTableExplicit unpackspec . table . fmap toCols
null
https://raw.githubusercontent.com/circuithub/rel8/97d89cf8b01070fa7a9254f8a6834322474be48e/src/Rel8/Query/Each.hs
haskell
# language FlexibleContexts # base opaleye rel8
# language MonoLocalBinds # module Rel8.Query.Each ( each ) where import Prelude import qualified Opaleye.Table as Opaleye import Rel8.Query ( Query ) import Rel8.Query.Opaleye ( fromOpaleye ) import Rel8.Schema.Name ( Selects ) import Rel8.Schema.Table ( TableSchema ) import Rel8.Table.Cols ( fromCols, toCols ) import Rel8.Table.Opaleye ( table, unpackspec ) | Select each row from a table definition . This is equivalent to @FROM each :: Selects names exprs => TableSchema names -> Query exprs each = fmap fromCols . fromOpaleye . Opaleye.selectTableExplicit unpackspec . table . fmap toCols
06d7d017574a50962d0a2613e89d71fb0c46e2506f5d45a87a0cbb5f19c6676d
eugeneia/athens
encode.lisp
(in-package :cl-user) (defpackage jonathan.encode (:use :cl :annot.doc :jonathan.util) (:import-from :fast-io :fast-write-byte :make-output-buffer :finish-output-buffer) (:import-from :trivial-types :association-list-p) (:export :write-key :write-value :write-key-value :with-object :with-array :write-item :with-output :*octets* :*from* :*stream* :to-json :%to-json :%write-char :%write-string)) (in-package :jonathan.encode) (syntax:use-syntax :cl-annot) @doc "Default value of octets used by #'to-json." (defvar *octets* nil) @doc "Default value of from used by #'to-json." (defvar *from* nil) @doc "Stream used by #'to-json." (defvar *stream* nil) (declaim (inline %write-string)) @doc "Write string to *stream*." (defun %write-string (string) (declare (type simple-string string) (optimize (speed 3) (safety 0) (debug 0))) (if *octets* (loop for c across string do (fast-write-byte (char-code c) *stream*)) (write-string string *stream*)) nil) (declaim (inline %write-char)) @doc "Write character to *stream*." (defun %write-char (char) (declare (type character char) (optimize (speed 3) (safety 0) (debug 0))) (if *octets* (fast-write-byte (char-code char) *stream*) (write-char char *stream*)) nil) (declaim (inline string-to-json)) (defun string-to-json (string) (declare (type simple-string string) (optimize (speed 3) (safety 0) (debug 0))) (macrolet ((escape (char pairs) (declare (type list pairs)) (let* ((sorted (sort (copy-list pairs) #'char<= :key #'car)) (min-char (caar sorted)) (max-char (caar (last sorted)))) `(if (and (char<= ,char ,max-char) (char>= ,char ,min-char)) (cond ,@(mapcar #'(lambda (pair) `((char= ,char ,(car pair)) (%write-string ,(cdr pair)))) pairs) (t (%write-char ,char))) (%write-char ,char))))) (%write-char #\") (loop for char of-type character across string do (escape char ((#\Newline . "\\n") (#\Return . "\\r") (#\Tab . "\\t") (#\" . "\\\"") (#\\ . "\\\\")))) (%write-char #\"))) #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro with-macro-p (list) `(and (consp ,list) (member (car ,list) '(with-object with-array))))) #-allegro (defmacro with-macro-p (list) `(and (consp ,list) (member (car ,list) '(with-object with-array)))) @doc "Write key part of object." (defmacro write-key (key) (declare (ignore key))) @doc "Write value part of object." (defmacro write-value (value) (declare (ignore value))) @doc "Write key and value of object." (defmacro write-key-value (key value) (declare (ignore key value))) @doc "Make writing object safe." (defmacro with-object (&body body) (let ((first (gensym "first"))) `(let ((,first t)) (macrolet ((write-key (key) `(progn (if ,',first (setq ,',first nil) (%write-char #\,)) (string-to-json (princ-to-string ,key)))) (write-value (value) `(progn (%write-char #\:) ,(if (with-macro-p value) value `(%to-json ,value)))) (write-key-value (key value) `(progn (write-key ,key) (write-value ,value)))) (%write-char #\{) ,@body (%write-char #\}))))) @doc "Write item of array." (defmacro write-item (item) (declare (ignore item))) @doc "Make writing array safe." (defmacro with-array (&body body) (let ((first (gensym "first"))) `(let ((,first t)) (macrolet ((write-item (item) `(progn (if ,',first (setq ,',first nil) (%write-char #\,)) ,(if (with-macro-p item) item `(%to-json ,item))))) (%write-char #\[) ,@body (%write-char #\]))))) @doc "Bind *stream* to stream." (defmacro with-output ((stream) &body body) `(let ((*stream* ,stream)) ,@body)) (declaim (inline alist-to-json)) (defun alist-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-object (loop for (key . value) in list do (write-key-value key value)))) (declaim (inline plist-to-json)) (defun plist-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-object (loop for (key value) on list by #'cddr do (write-key-value key value)))) (declaim (inline list-to-json)) (defun list-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-array (loop for item in list do (write-item item)))) @doc "Convert LISP object to JSON String." (defun to-json (obj &key (octets *octets*) (from *from*)) (declare (optimize (speed 3) (safety 0) (debug 0))) (let ((*stream* (if octets (make-output-buffer :output :vector) (make-string-output-stream))) (*octets* octets) (*from* from)) (%to-json obj) (if octets (finish-output-buffer *stream*) (get-output-stream-string *stream*)))) @doc "Write obj as JSON string." (defgeneric %to-json (obj)) (defmethod %to-json ((string string)) (if (typep string 'simple-string) (string-to-json string) (string-to-json (coerce string 'simple-string)))) (defmethod %to-json ((number number)) (%write-string (princ-to-string number))) (defmethod %to-json ((float float)) (%write-string (format nil "~f" float))) (defmethod %to-json ((ratio ratio)) (%write-string (princ-to-string (coerce ratio 'float)))) (defmethod %to-json ((list list)) (cond ((and (eq *from* :alist) (association-list-p list)) (alist-to-json list)) ((and (eq *from* :jsown) (eq (car list) :obj)) (alist-to-json (cdr list))) ((and (or (eq *from* :plist) (null *from*)) (my-plist-p list)) (plist-to-json list)) (t (list-to-json list)))) (defmethod %to-json ((vector vector)) (with-array (loop for item across vector do (write-item item)))) (defmethod %to-json ((hash hash-table)) (with-object (loop for key being the hash-key of hash using (hash-value value) do (write-key-value key value)))) (defmethod %to-json ((symbol symbol)) (string-to-json (symbol-name symbol))) (defmethod %to-json ((_ (eql t))) (%write-string "true")) (defmethod %to-json ((_ (eql :false))) (%write-string "false")) (defmethod %to-json ((_ (eql :null))) (%write-string "null")) (defmethod %to-json ((_ (eql :empty))) (%write-string "{}")) (defmethod %to-json ((_ (eql nil))) (%write-string "[]"))
null
https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/jonathan-20180430-git/src/encode.lisp
lisp
(in-package :cl-user) (defpackage jonathan.encode (:use :cl :annot.doc :jonathan.util) (:import-from :fast-io :fast-write-byte :make-output-buffer :finish-output-buffer) (:import-from :trivial-types :association-list-p) (:export :write-key :write-value :write-key-value :with-object :with-array :write-item :with-output :*octets* :*from* :*stream* :to-json :%to-json :%write-char :%write-string)) (in-package :jonathan.encode) (syntax:use-syntax :cl-annot) @doc "Default value of octets used by #'to-json." (defvar *octets* nil) @doc "Default value of from used by #'to-json." (defvar *from* nil) @doc "Stream used by #'to-json." (defvar *stream* nil) (declaim (inline %write-string)) @doc "Write string to *stream*." (defun %write-string (string) (declare (type simple-string string) (optimize (speed 3) (safety 0) (debug 0))) (if *octets* (loop for c across string do (fast-write-byte (char-code c) *stream*)) (write-string string *stream*)) nil) (declaim (inline %write-char)) @doc "Write character to *stream*." (defun %write-char (char) (declare (type character char) (optimize (speed 3) (safety 0) (debug 0))) (if *octets* (fast-write-byte (char-code char) *stream*) (write-char char *stream*)) nil) (declaim (inline string-to-json)) (defun string-to-json (string) (declare (type simple-string string) (optimize (speed 3) (safety 0) (debug 0))) (macrolet ((escape (char pairs) (declare (type list pairs)) (let* ((sorted (sort (copy-list pairs) #'char<= :key #'car)) (min-char (caar sorted)) (max-char (caar (last sorted)))) `(if (and (char<= ,char ,max-char) (char>= ,char ,min-char)) (cond ,@(mapcar #'(lambda (pair) `((char= ,char ,(car pair)) (%write-string ,(cdr pair)))) pairs) (t (%write-char ,char))) (%write-char ,char))))) (%write-char #\") (loop for char of-type character across string do (escape char ((#\Newline . "\\n") (#\Return . "\\r") (#\Tab . "\\t") (#\" . "\\\"") (#\\ . "\\\\")))) (%write-char #\"))) #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro with-macro-p (list) `(and (consp ,list) (member (car ,list) '(with-object with-array))))) #-allegro (defmacro with-macro-p (list) `(and (consp ,list) (member (car ,list) '(with-object with-array)))) @doc "Write key part of object." (defmacro write-key (key) (declare (ignore key))) @doc "Write value part of object." (defmacro write-value (value) (declare (ignore value))) @doc "Write key and value of object." (defmacro write-key-value (key value) (declare (ignore key value))) @doc "Make writing object safe." (defmacro with-object (&body body) (let ((first (gensym "first"))) `(let ((,first t)) (macrolet ((write-key (key) `(progn (if ,',first (setq ,',first nil) (%write-char #\,)) (string-to-json (princ-to-string ,key)))) (write-value (value) `(progn (%write-char #\:) ,(if (with-macro-p value) value `(%to-json ,value)))) (write-key-value (key value) `(progn (write-key ,key) (write-value ,value)))) (%write-char #\{) ,@body (%write-char #\}))))) @doc "Write item of array." (defmacro write-item (item) (declare (ignore item))) @doc "Make writing array safe." (defmacro with-array (&body body) (let ((first (gensym "first"))) `(let ((,first t)) (macrolet ((write-item (item) `(progn (if ,',first (setq ,',first nil) (%write-char #\,)) ,(if (with-macro-p item) item `(%to-json ,item))))) (%write-char #\[) ,@body (%write-char #\]))))) @doc "Bind *stream* to stream." (defmacro with-output ((stream) &body body) `(let ((*stream* ,stream)) ,@body)) (declaim (inline alist-to-json)) (defun alist-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-object (loop for (key . value) in list do (write-key-value key value)))) (declaim (inline plist-to-json)) (defun plist-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-object (loop for (key value) on list by #'cddr do (write-key-value key value)))) (declaim (inline list-to-json)) (defun list-to-json (list) (declare (optimize (speed 3) (safety 0) (debug 0))) (with-array (loop for item in list do (write-item item)))) @doc "Convert LISP object to JSON String." (defun to-json (obj &key (octets *octets*) (from *from*)) (declare (optimize (speed 3) (safety 0) (debug 0))) (let ((*stream* (if octets (make-output-buffer :output :vector) (make-string-output-stream))) (*octets* octets) (*from* from)) (%to-json obj) (if octets (finish-output-buffer *stream*) (get-output-stream-string *stream*)))) @doc "Write obj as JSON string." (defgeneric %to-json (obj)) (defmethod %to-json ((string string)) (if (typep string 'simple-string) (string-to-json string) (string-to-json (coerce string 'simple-string)))) (defmethod %to-json ((number number)) (%write-string (princ-to-string number))) (defmethod %to-json ((float float)) (%write-string (format nil "~f" float))) (defmethod %to-json ((ratio ratio)) (%write-string (princ-to-string (coerce ratio 'float)))) (defmethod %to-json ((list list)) (cond ((and (eq *from* :alist) (association-list-p list)) (alist-to-json list)) ((and (eq *from* :jsown) (eq (car list) :obj)) (alist-to-json (cdr list))) ((and (or (eq *from* :plist) (null *from*)) (my-plist-p list)) (plist-to-json list)) (t (list-to-json list)))) (defmethod %to-json ((vector vector)) (with-array (loop for item across vector do (write-item item)))) (defmethod %to-json ((hash hash-table)) (with-object (loop for key being the hash-key of hash using (hash-value value) do (write-key-value key value)))) (defmethod %to-json ((symbol symbol)) (string-to-json (symbol-name symbol))) (defmethod %to-json ((_ (eql t))) (%write-string "true")) (defmethod %to-json ((_ (eql :false))) (%write-string "false")) (defmethod %to-json ((_ (eql :null))) (%write-string "null")) (defmethod %to-json ((_ (eql :empty))) (%write-string "{}")) (defmethod %to-json ((_ (eql nil))) (%write-string "[]"))
ad6868cedfac25773de0627a7bcb9d0dc9f5bc53acc3649640bc86d42f0ffe9e
rpeszek/typed-encoding
BoundedAlphaNums.hs
# LANGUAGE MultiParamTypeClasses # { - # LANGUAGE PolyKinds # - } # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # -- {-# LANGUAGE KindSignatures #-} # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # {-# LANGUAGE ConstraintKinds #-} -- | Restrictions @"r - ban:"@ cover commonly used fixed ( short ) size strings with restricted characters such as GUID , credit card numbers , etc . -- Alphanumeric chars are ordered : @0 - 9@ followed by , followed by @a - z@. Annotation specifies upper character bound . -- Any non alpha numeric characters are considered fixed delimiters -- and need to be present exactly as specified. For example @"r - ban:999 - 99 - 9999"@ could be used to describe SSN numbers , @"r - ban : FFFF " would describe strings consisting of 4 hex digits . -- -- This is a simple implementation that converts to @String@, should be used -- only with short length data. -- -- -- @since 0.2.1.0 module Data.TypedEncoding.Instances.Restriction.BoundedAlphaNums where import GHC.TypeLits import qualified Data.List as L import Data.Char import Data.Proxy import Data.Either import Data.TypedEncoding.Common.Util.TypeLits import Data.TypedEncoding.Common.Class.IsStringR import Data.TypedEncoding.Instances.Support -- $setup > > > : set -XOverloadedStrings -XMultiParamTypeClasses -XDataKinds -XTypeApplications -- >>> import qualified Data.Text as T > > > import Data . -- better compilation errors? type family IsBan (s :: Symbol) :: Bool where IsBan s = AcceptEq ('Text "Not ban restriction encoding " ':<>: ShowType s ) (CmpSymbol (TakeUntil s ":") "r-ban") type Ban s = (KnownSymbol s, IsBan s ~ 'True) type instance IsSupersetOpen "r-ASCII" x "r-ban" xs = 'True instance (Ban s, Algorithm s "r-ban", IsStringR str) => Encode (Either EncodeEx) s "r-ban" c str where encoding = encFBan -- | > > > runEncoding ' encFBan . toEncoding ( ) $ " C59F9FB7 - 4621 - 44D9 - 9020 - CE37BF6E2BD1 " : : Either EncodeEx ( Enc ' [ " r - ban : FFFFFFFF - FFFF - FFFF - FFFF - FFFFFFFFFFFF " ] ( ) T.Text ) Right ( UnsafeMkEnc Proxy ( ) " C59F9FB7 - 4621 - 44D9 - 9020 - CE37BF6E2BD1 " ) -- > > > ' @'["r - ban " ] . toEncoding ( ) $ " 211 - 22 - 9934 " : : Either RecreateEx ( Enc ' [ " r - ban:999 - 99 - 9999 " ] ( ) T.Text ) Right ( UnsafeMkEnc Proxy ( ) " 211 - 22 - 9934 " ) encFBan :: forall s c str . ( IsStringR str , Ban s , Algorithm s "r-ban" ) => Encoding (Either EncodeEx) s "r-ban" c str encFBan = _implEncodingEx @s (verifyBoundedAlphaNum (Proxy :: Proxy s)) -- * Decoding instance (KnownSymbol s, Restriction s, Algorithm s "r-ban", Applicative f) => Decode f s "r-ban" c str where decoding = decAnyR_ -- * Validation instance (KnownSymbol s , Ban s, Algorithm s "r-ban", IsStringR str, RecreateErr f, Applicative f) => Validate f s "r-ban" c str where validation = validRFromEnc' @"r-ban" encFBan -- * Implementation -- | > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 12 - 3E " ) -- Right "12-3E" > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 1G-3E " ) -- Left "'G' not bounded by 'F'" > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 13G3E " ) -- Left "'G' not matching '-'" -- >>> verifyBoundedAlphaNum (Proxy :: Proxy "r-ban:FFяFF") (T.pack "13я234") -- Left "Not ASCII char in annotation '\\1103'" -- verifyBoundedAlphaNum :: forall s str . (KnownSymbol s, IsStringR str) => Proxy s -> str -> Either String str verifyBoundedAlphaNum p str = case (lefts match, notAscii, pattl == inpl) of (_, Just ch, _) -> Left $ "Not ASCII char in annotation " ++ show ch (_, _, False) -> Left $ "Input list has wrong size expecting " ++ show pattl ++ " but length " ++ show input ++ " == " ++ show inpl (e: _, _, _) -> Left e _ -> Right str where patt = L.drop (L.length ("r-ban:" :: String)) . symbolVal $ p input = toString str pattl = L.length patt inpl = L.length input match = L.zipWith fn input patt notAscii = L.find (not . isAscii) patt fn ci cp = case (isAlphaNum ci, isAlphaNum cp, ci <= cp, ci == cp) of (True, True, True, _) -> Right () (_, _, _, True) -> Right () (_, True, _, False) -> Left $ show ci ++ " not bounded by " ++ show cp (_, False, _, False) -> Left $ show ci ++ " not matching " ++ show cp
null
https://raw.githubusercontent.com/rpeszek/typed-encoding/441f9f3bbf849f485f82eae66402ee2fd7b47a34/src/Data/TypedEncoding/Instances/Restriction/BoundedAlphaNums.hs
haskell
{-# LANGUAGE KindSignatures #-} # LANGUAGE ConstraintKinds # | Any non alpha numeric characters are considered fixed delimiters and need to be present exactly as specified. This is a simple implementation that converts to @String@, should be used only with short length data. @since 0.2.1.0 $setup >>> import qualified Data.Text as T better compilation errors? | * Decoding * Validation * Implementation | Right "12-3E" Left "'G' not bounded by 'F'" Left "'G' not matching '-'" >>> verifyBoundedAlphaNum (Proxy :: Proxy "r-ban:FFяFF") (T.pack "13я234") Left "Not ASCII char in annotation '\\1103'"
# LANGUAGE MultiParamTypeClasses # { - # LANGUAGE PolyKinds # - } # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # Restrictions @"r - ban:"@ cover commonly used fixed ( short ) size strings with restricted characters such as GUID , credit card numbers , etc . Alphanumeric chars are ordered : @0 - 9@ followed by , followed by @a - z@. Annotation specifies upper character bound . For example @"r - ban:999 - 99 - 9999"@ could be used to describe SSN numbers , @"r - ban : FFFF " would describe strings consisting of 4 hex digits . module Data.TypedEncoding.Instances.Restriction.BoundedAlphaNums where import GHC.TypeLits import qualified Data.List as L import Data.Char import Data.Proxy import Data.Either import Data.TypedEncoding.Common.Util.TypeLits import Data.TypedEncoding.Common.Class.IsStringR import Data.TypedEncoding.Instances.Support > > > : set -XOverloadedStrings -XMultiParamTypeClasses -XDataKinds -XTypeApplications > > > import Data . type family IsBan (s :: Symbol) :: Bool where IsBan s = AcceptEq ('Text "Not ban restriction encoding " ':<>: ShowType s ) (CmpSymbol (TakeUntil s ":") "r-ban") type Ban s = (KnownSymbol s, IsBan s ~ 'True) type instance IsSupersetOpen "r-ASCII" x "r-ban" xs = 'True instance (Ban s, Algorithm s "r-ban", IsStringR str) => Encode (Either EncodeEx) s "r-ban" c str where encoding = encFBan > > > runEncoding ' encFBan . toEncoding ( ) $ " C59F9FB7 - 4621 - 44D9 - 9020 - CE37BF6E2BD1 " : : Either EncodeEx ( Enc ' [ " r - ban : FFFFFFFF - FFFF - FFFF - FFFF - FFFFFFFFFFFF " ] ( ) T.Text ) Right ( UnsafeMkEnc Proxy ( ) " C59F9FB7 - 4621 - 44D9 - 9020 - CE37BF6E2BD1 " ) > > > ' @'["r - ban " ] . toEncoding ( ) $ " 211 - 22 - 9934 " : : Either RecreateEx ( Enc ' [ " r - ban:999 - 99 - 9999 " ] ( ) T.Text ) Right ( UnsafeMkEnc Proxy ( ) " 211 - 22 - 9934 " ) encFBan :: forall s c str . ( IsStringR str , Ban s , Algorithm s "r-ban" ) => Encoding (Either EncodeEx) s "r-ban" c str encFBan = _implEncodingEx @s (verifyBoundedAlphaNum (Proxy :: Proxy s)) instance (KnownSymbol s, Restriction s, Algorithm s "r-ban", Applicative f) => Decode f s "r-ban" c str where decoding = decAnyR_ instance (KnownSymbol s , Ban s, Algorithm s "r-ban", IsStringR str, RecreateErr f, Applicative f) => Validate f s "r-ban" c str where validation = validRFromEnc' @"r-ban" encFBan > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 12 - 3E " ) > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 1G-3E " ) > > > verifyBoundedAlphaNum ( Proxy : : Proxy " r - ban : FF - FF " ) ( T.pack " 13G3E " ) verifyBoundedAlphaNum :: forall s str . (KnownSymbol s, IsStringR str) => Proxy s -> str -> Either String str verifyBoundedAlphaNum p str = case (lefts match, notAscii, pattl == inpl) of (_, Just ch, _) -> Left $ "Not ASCII char in annotation " ++ show ch (_, _, False) -> Left $ "Input list has wrong size expecting " ++ show pattl ++ " but length " ++ show input ++ " == " ++ show inpl (e: _, _, _) -> Left e _ -> Right str where patt = L.drop (L.length ("r-ban:" :: String)) . symbolVal $ p input = toString str pattl = L.length patt inpl = L.length input match = L.zipWith fn input patt notAscii = L.find (not . isAscii) patt fn ci cp = case (isAlphaNum ci, isAlphaNum cp, ci <= cp, ci == cp) of (True, True, True, _) -> Right () (_, _, _, True) -> Right () (_, True, _, False) -> Left $ show ci ++ " not bounded by " ++ show cp (_, False, _, False) -> Left $ show ci ++ " not matching " ++ show cp
d4f616de6372cd57b3b7b1bac2f3214940746b2fa2e4e7596c1e9e5a8b64989a
ml4tp/tcoq
check.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Pp open CErrors open Util open Names let chk_pp = Pp.pp_with Format.std_formatter let pr_dirpath dp = str (DirPath.to_string dp) let default_root_prefix = DirPath.empty let split_dirpath d = let l = DirPath.repr d in (DirPath.make (List.tl l), List.hd l) let extend_dirpath p id = DirPath.make (id :: DirPath.repr p) type section_path = { dirpath : string list ; basename : string } let dir_of_path p = DirPath.make (List.map Id.of_string p.dirpath) let path_of_dirpath dir = match DirPath.repr dir with [] -> failwith "path_of_dirpath" | l::dir -> {dirpath=List.map Id.to_string dir;basename=Id.to_string l} let pr_dirlist dp = prlist_with_sep (fun _ -> str".") str (List.rev dp) let pr_path sp = match sp.dirpath with [] -> str sp.basename | sl -> pr_dirlist sl ++ str"." ++ str sp.basename (************************************************************************) (*s Modules loaded in memory contain the following informations. They are kept in the global table [libraries_table]. *) type library_t = { library_name : Cic.compilation_unit_name; library_filename : CUnix.physical_path; library_compiled : Cic.compiled_library; library_opaques : Cic.opaque_table; library_deps : Cic.library_deps; library_digest : Cic.vodigest; library_extra_univs : Univ.ContextSet.t } module LibraryOrdered = struct type t = DirPath.t let compare d1 d2 = Pervasives.compare (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) end module LibrarySet = Set.Make(LibraryOrdered) module LibraryMap = Map.Make(LibraryOrdered) (* This is a map from names to loaded libraries *) let libraries_table = ref LibraryMap.empty (* various requests to the tables *) let find_library dir = LibraryMap.find dir !libraries_table let try_find_library dir = try find_library dir with Not_found -> error ("Unknown library " ^ (DirPath.to_string dir)) let library_full_filename dir = (find_library dir).library_filename If a library is loaded several time , then the first occurrence must be performed first , thus the libraries_loaded_list ... be performed first, thus the libraries_loaded_list ... *) let register_loaded_library m = libraries_table := LibraryMap.add m.library_name m !libraries_table (* Map from library names to table of opaque terms *) let opaque_tables = ref LibraryMap.empty let opaque_univ_tables = ref LibraryMap.empty let access_opaque_table dp i = let t = try LibraryMap.find dp !opaque_tables with Not_found -> assert false in assert (i < Array.length t); Future.force t.(i) let access_opaque_univ_table dp i = try let t = LibraryMap.find dp !opaque_univ_tables in assert (i < Array.length t); Future.force t.(i) with Not_found -> Univ.ContextSet.empty let _ = Declarations.indirect_opaque_access := access_opaque_table let _ = Declarations.indirect_opaque_univ_access := access_opaque_univ_table let check_one_lib admit (dir,m) = let file = m.library_filename in let md = m.library_compiled in let dig = m.library_digest in (* Look up if the library is to be admitted correct. We could also check if it carries a validation certificate (yet to be implemented). *) if LibrarySet.mem dir admit then (Flags.if_verbose Feedback.msg_notice (str "Admitting library: " ++ pr_dirpath dir); Safe_typing.unsafe_import file md m.library_extra_univs dig) else (Flags.if_verbose Feedback.msg_notice (str "Checking library: " ++ pr_dirpath dir); Safe_typing.import file md m.library_extra_univs dig); register_loaded_library m (*************************************************************************) (*s Load path. Mapping from physical to logical paths etc.*) type logical_path = DirPath.t let load_paths = ref ([],[] : CUnix.physical_path list * logical_path list) let get_load_paths () = fst !load_paths Hints to partially detects if two paths refer to the same repertory let rec remove_path_dot p = let curdir = Filename.concat Filename.current_dir_name "" in (* Unix: "./" *) let n = String.length curdir in if String.length p > n && String.sub p 0 n = curdir then remove_path_dot (String.sub p n (String.length p - n)) else p let strip_path p = let cwd = Filename.concat (Sys.getcwd ()) "" in (* Unix: "`pwd`/" *) let n = String.length cwd in if String.length p > n && String.sub p 0 n = cwd then remove_path_dot (String.sub p n (String.length p - n)) else remove_path_dot p let canonical_path_name p = let current = Sys.getcwd () in try Sys.chdir p; let p' = Sys.getcwd () in Sys.chdir current; p' with Sys_error _ -> (* We give up to find a canonical name and just simplify it... *) strip_path p let find_logical_path phys_dir = let phys_dir = canonical_path_name phys_dir in let physical, logical = !load_paths in match List.filter2 (fun p d -> p = phys_dir) physical logical with | _,[dir] -> dir | _,[] -> default_root_prefix | _,l -> anomaly (Pp.str ("Two logical paths are associated to "^phys_dir)) let remove_load_path dir = let physical, logical = !load_paths in load_paths := List.filter2 (fun p d -> p <> dir) physical logical let add_load_path (phys_path,coq_path) = if !Flags.debug then Feedback.msg_notice (str "path: " ++ pr_dirpath coq_path ++ str " ->" ++ spc() ++ str phys_path); let phys_path = canonical_path_name phys_path in let physical, logical = !load_paths in match List.filter2 (fun p d -> p = phys_path) physical logical with | _,[dir] -> if coq_path <> dir (* If this is not the default -I . to coqtop *) && not (phys_path = canonical_path_name Filename.current_dir_name && coq_path = default_root_prefix) then begin (* Assume the user is concerned by library naming *) if dir <> default_root_prefix then Feedback.msg_warning (str phys_path ++ strbrk " was previously bound to " ++ pr_dirpath dir ++ strbrk "; it is remapped to " ++ pr_dirpath coq_path); remove_load_path phys_path; load_paths := (phys_path::fst !load_paths, coq_path::snd !load_paths) end | _,[] -> load_paths := (phys_path :: fst !load_paths, coq_path :: snd !load_paths) | _ -> anomaly (Pp.str ("Two logical paths are associated to "^phys_path)) let load_paths_of_dir_path dir = let physical, logical = !load_paths in fst (List.filter2 (fun p d -> d = dir) physical logical) (************************************************************************) (*s Locate absolute or partially qualified library names in the path *) exception LibUnmappedDir exception LibNotFound let locate_absolute_library dir = (* Search in loadpath *) let pref, base = split_dirpath dir in let loadpath = load_paths_of_dir_path pref in if loadpath = [] then raise LibUnmappedDir; try let name = Id.to_string base^".vo" in let _, file = System.where_in_path ~warn:false loadpath name in (dir, file) with Not_found -> (* Last chance, removed from the file system but still in memory *) try (dir, library_full_filename dir) with Not_found -> raise LibNotFound let locate_qualified_library qid = try let loadpath = (* Search library in loadpath *) if qid.dirpath=[] then get_load_paths () else (* we assume qid is an absolute dirpath *) load_paths_of_dir_path (dir_of_path qid) in if loadpath = [] then raise LibUnmappedDir; let name = qid.basename^".vo" in let path, file = System.where_in_path loadpath name in let dir = extend_dirpath (find_logical_path path) (Id.of_string qid.basename) in (* Look if loaded *) try (dir, library_full_filename dir) with Not_found -> (dir, file) with Not_found -> raise LibNotFound let error_unmapped_dir qid = let prefix = qid.dirpath in errorlabstrm "load_absolute_library_from" (str "Cannot load " ++ pr_path qid ++ str ":" ++ spc () ++ str "no physical path bound to" ++ spc () ++ pr_dirlist prefix ++ fnl ()) let error_lib_not_found qid = errorlabstrm "load_absolute_library_from" (str"Cannot find library " ++ pr_path qid ++ str" in loadpath") let try_locate_absolute_library dir = try locate_absolute_library dir with | LibUnmappedDir -> error_unmapped_dir (path_of_dirpath dir) | LibNotFound -> error_lib_not_found (path_of_dirpath dir) let try_locate_qualified_library qid = try locate_qualified_library qid with | LibUnmappedDir -> error_unmapped_dir qid | LibNotFound -> error_lib_not_found qid (************************************************************************) (*s Low-level interning of libraries from files *) let raw_intern_library f = System.raw_intern_state Coq_config.vo_magic_number f (************************************************************************) Internalise libraries open Cic let mk_library sd md f table digest cst = { library_name = sd.md_name; library_filename = f; library_compiled = md.md_compiled; library_opaques = table; library_deps = sd.md_deps; library_digest = digest; library_extra_univs = cst } let name_clash_message dir mdir f = str ("The file " ^ f ^ " contains library") ++ spc () ++ pr_dirpath mdir ++ spc () ++ str "and not library" ++ spc() ++ pr_dirpath dir (* Dependency graph *) let depgraph = ref LibraryMap.empty let intern_from_file (dir, f) = Flags.if_verbose chk_pp (str"[intern "++str f++str" ..."); let (sd,md,table,opaque_csts,digest) = try let ch = System.with_magic_number_check raw_intern_library f in let (sd:Cic.summary_disk), _, digest = System.marshal_in_segment f ch in let (md:Cic.library_disk), _, digest = System.marshal_in_segment f ch in let (opaque_csts:'a option), _, udg = System.marshal_in_segment f ch in let (discharging:'a option), _, _ = System.marshal_in_segment f ch in let (tasks:'a option), _, _ = System.marshal_in_segment f ch in let (table:Cic.opaque_table), pos, checksum = System.marshal_in_segment f ch in (* Verification of the final checksum *) let () = close_in ch in let ch = open_in_bin f in if not (String.equal (Digest.channel ch pos) checksum) then errorlabstrm "intern_from_file" (str "Checksum mismatch"); let () = close_in ch in if dir <> sd.md_name then errorlabstrm "intern_from_file" (name_clash_message dir sd.md_name f); if tasks <> None || discharging <> None then errorlabstrm "intern_from_file" (str "The file "++str f++str " contains unfinished tasks"); if opaque_csts <> None then begin chk_pp (str " (was a vio file) "); Option.iter (fun (_,_,b) -> if not b then errorlabstrm "intern_from_file" (str "The file "++str f++str " is still a .vio")) opaque_csts; Validate.validate !Flags.debug Values.v_univopaques opaque_csts; end; (* Verification of the unmarshalled values *) Validate.validate !Flags.debug Values.v_libsum sd; Validate.validate !Flags.debug Values.v_lib md; Validate.validate !Flags.debug Values.v_opaques table; Flags.if_verbose chk_pp (str" done]" ++ fnl ()); let digest = if opaque_csts <> None then Cic.Dviovo (digest,udg) else (Cic.Dvo digest) in sd,md,table,opaque_csts,digest with e -> Flags.if_verbose chk_pp (str" failed!]" ++ fnl ()); raise e in depgraph := LibraryMap.add sd.md_name sd.md_deps !depgraph; opaque_tables := LibraryMap.add sd.md_name table !opaque_tables; Option.iter (fun (opaque_csts,_,_) -> opaque_univ_tables := LibraryMap.add sd.md_name opaque_csts !opaque_univ_tables) opaque_csts; let extra_cst = Option.default Univ.ContextSet.empty (Option.map (fun (_,cs,_) -> cs) opaque_csts) in mk_library sd md f table digest extra_cst let get_deps (dir, f) = try LibraryMap.find dir !depgraph with Not_found -> let _ = intern_from_file (dir,f) in LibraryMap.find dir !depgraph (* Read a compiled library and all dependencies, in reverse order. Do not include files that are already in the context. *) let rec intern_library seen (dir, f) needed = if LibrarySet.mem dir seen then failwith "Recursive dependencies!"; (* Look if in the current logical environment *) try let _ = find_library dir in needed with Not_found -> (* Look if already listed and consequently its dependencies too *) if List.mem_assoc_f DirPath.equal dir needed then needed else (* [dir] is an absolute name which matches [f] which must be in loadpath *) let m = intern_from_file (dir,f) in let seen' = LibrarySet.add dir seen in let deps = Array.map (fun (d,_) -> try_locate_absolute_library d) m.library_deps in (dir,m) :: Array.fold_right (intern_library seen') deps needed (* Compute the reflexive transitive dependency closure *) let rec fold_deps seen ff (dir,f) (s,acc) = if LibrarySet.mem dir seen then failwith "Recursive dependencies!"; if LibrarySet.mem dir s then (s,acc) else let deps = get_deps (dir,f) in let deps = Array.map (fun (d,_) -> try_locate_absolute_library d) deps in let seen' = LibrarySet.add dir seen in let (s',acc') = Array.fold_right (fold_deps seen' ff) deps (s,acc) in (LibrarySet.add dir s', ff dir acc') and fold_deps_list seen ff modl needed = List.fold_right (fold_deps seen ff) modl needed let fold_deps_list ff modl acc = snd (fold_deps_list LibrarySet.empty ff modl (LibrarySet.empty,acc)) let recheck_library ~norec ~admit ~check = let ml = List.map try_locate_qualified_library check in let nrl = List.map try_locate_qualified_library norec in let al = List.map try_locate_qualified_library admit in let needed = List.rev (List.fold_right (intern_library LibrarySet.empty) (ml@nrl) []) in (* first compute the closure of norec, remove closure of check, add closure of admit, and finally remove norec and check *) let nochk = fold_deps_list LibrarySet.add nrl LibrarySet.empty in let nochk = fold_deps_list LibrarySet.remove ml nochk in let nochk = fold_deps_list LibrarySet.add al nochk in (* explicitly required modules cannot be skipped... *) let nochk = List.fold_right LibrarySet.remove (List.map fst (nrl@ml)) nochk in (* *) Flags.if_verbose Feedback.msg_notice (fnl()++hv 2 (str "Ordered list:" ++ fnl() ++ prlist (fun (dir,_) -> pr_dirpath dir ++ fnl()) needed)); List.iter (check_one_lib nochk) needed; Flags.if_verbose Feedback.msg_notice (str"Modules were successfully checked") open Printf let mem s = let m = try_find_library s in h 0 (str (sprintf "%dk" (CObj.size_kb m)))
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/checker/check.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** ********************************************************************** s Modules loaded in memory contain the following informations. They are kept in the global table [libraries_table]. This is a map from names to loaded libraries various requests to the tables Map from library names to table of opaque terms Look up if the library is to be admitted correct. We could also check if it carries a validation certificate (yet to be implemented). *********************************************************************** s Load path. Mapping from physical to logical paths etc. Unix: "./" Unix: "`pwd`/" We give up to find a canonical name and just simplify it... If this is not the default -I . to coqtop Assume the user is concerned by library naming ********************************************************************** s Locate absolute or partially qualified library names in the path Search in loadpath Last chance, removed from the file system but still in memory Search library in loadpath we assume qid is an absolute dirpath Look if loaded ********************************************************************** s Low-level interning of libraries from files ********************************************************************** Dependency graph Verification of the final checksum Verification of the unmarshalled values Read a compiled library and all dependencies, in reverse order. Do not include files that are already in the context. Look if in the current logical environment Look if already listed and consequently its dependencies too [dir] is an absolute name which matches [f] which must be in loadpath Compute the reflexive transitive dependency closure first compute the closure of norec, remove closure of check, add closure of admit, and finally remove norec and check explicitly required modules cannot be skipped...
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open CErrors open Util open Names let chk_pp = Pp.pp_with Format.std_formatter let pr_dirpath dp = str (DirPath.to_string dp) let default_root_prefix = DirPath.empty let split_dirpath d = let l = DirPath.repr d in (DirPath.make (List.tl l), List.hd l) let extend_dirpath p id = DirPath.make (id :: DirPath.repr p) type section_path = { dirpath : string list ; basename : string } let dir_of_path p = DirPath.make (List.map Id.of_string p.dirpath) let path_of_dirpath dir = match DirPath.repr dir with [] -> failwith "path_of_dirpath" | l::dir -> {dirpath=List.map Id.to_string dir;basename=Id.to_string l} let pr_dirlist dp = prlist_with_sep (fun _ -> str".") str (List.rev dp) let pr_path sp = match sp.dirpath with [] -> str sp.basename | sl -> pr_dirlist sl ++ str"." ++ str sp.basename type library_t = { library_name : Cic.compilation_unit_name; library_filename : CUnix.physical_path; library_compiled : Cic.compiled_library; library_opaques : Cic.opaque_table; library_deps : Cic.library_deps; library_digest : Cic.vodigest; library_extra_univs : Univ.ContextSet.t } module LibraryOrdered = struct type t = DirPath.t let compare d1 d2 = Pervasives.compare (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) end module LibrarySet = Set.Make(LibraryOrdered) module LibraryMap = Map.Make(LibraryOrdered) let libraries_table = ref LibraryMap.empty let find_library dir = LibraryMap.find dir !libraries_table let try_find_library dir = try find_library dir with Not_found -> error ("Unknown library " ^ (DirPath.to_string dir)) let library_full_filename dir = (find_library dir).library_filename If a library is loaded several time , then the first occurrence must be performed first , thus the libraries_loaded_list ... be performed first, thus the libraries_loaded_list ... *) let register_loaded_library m = libraries_table := LibraryMap.add m.library_name m !libraries_table let opaque_tables = ref LibraryMap.empty let opaque_univ_tables = ref LibraryMap.empty let access_opaque_table dp i = let t = try LibraryMap.find dp !opaque_tables with Not_found -> assert false in assert (i < Array.length t); Future.force t.(i) let access_opaque_univ_table dp i = try let t = LibraryMap.find dp !opaque_univ_tables in assert (i < Array.length t); Future.force t.(i) with Not_found -> Univ.ContextSet.empty let _ = Declarations.indirect_opaque_access := access_opaque_table let _ = Declarations.indirect_opaque_univ_access := access_opaque_univ_table let check_one_lib admit (dir,m) = let file = m.library_filename in let md = m.library_compiled in let dig = m.library_digest in if LibrarySet.mem dir admit then (Flags.if_verbose Feedback.msg_notice (str "Admitting library: " ++ pr_dirpath dir); Safe_typing.unsafe_import file md m.library_extra_univs dig) else (Flags.if_verbose Feedback.msg_notice (str "Checking library: " ++ pr_dirpath dir); Safe_typing.import file md m.library_extra_univs dig); register_loaded_library m type logical_path = DirPath.t let load_paths = ref ([],[] : CUnix.physical_path list * logical_path list) let get_load_paths () = fst !load_paths Hints to partially detects if two paths refer to the same repertory let rec remove_path_dot p = let n = String.length curdir in if String.length p > n && String.sub p 0 n = curdir then remove_path_dot (String.sub p n (String.length p - n)) else p let strip_path p = let n = String.length cwd in if String.length p > n && String.sub p 0 n = cwd then remove_path_dot (String.sub p n (String.length p - n)) else remove_path_dot p let canonical_path_name p = let current = Sys.getcwd () in try Sys.chdir p; let p' = Sys.getcwd () in Sys.chdir current; p' with Sys_error _ -> strip_path p let find_logical_path phys_dir = let phys_dir = canonical_path_name phys_dir in let physical, logical = !load_paths in match List.filter2 (fun p d -> p = phys_dir) physical logical with | _,[dir] -> dir | _,[] -> default_root_prefix | _,l -> anomaly (Pp.str ("Two logical paths are associated to "^phys_dir)) let remove_load_path dir = let physical, logical = !load_paths in load_paths := List.filter2 (fun p d -> p <> dir) physical logical let add_load_path (phys_path,coq_path) = if !Flags.debug then Feedback.msg_notice (str "path: " ++ pr_dirpath coq_path ++ str " ->" ++ spc() ++ str phys_path); let phys_path = canonical_path_name phys_path in let physical, logical = !load_paths in match List.filter2 (fun p d -> p = phys_path) physical logical with | _,[dir] -> if coq_path <> dir && not (phys_path = canonical_path_name Filename.current_dir_name && coq_path = default_root_prefix) then begin if dir <> default_root_prefix then Feedback.msg_warning (str phys_path ++ strbrk " was previously bound to " ++ pr_dirpath dir ++ strbrk "; it is remapped to " ++ pr_dirpath coq_path); remove_load_path phys_path; load_paths := (phys_path::fst !load_paths, coq_path::snd !load_paths) end | _,[] -> load_paths := (phys_path :: fst !load_paths, coq_path :: snd !load_paths) | _ -> anomaly (Pp.str ("Two logical paths are associated to "^phys_path)) let load_paths_of_dir_path dir = let physical, logical = !load_paths in fst (List.filter2 (fun p d -> d = dir) physical logical) exception LibUnmappedDir exception LibNotFound let locate_absolute_library dir = let pref, base = split_dirpath dir in let loadpath = load_paths_of_dir_path pref in if loadpath = [] then raise LibUnmappedDir; try let name = Id.to_string base^".vo" in let _, file = System.where_in_path ~warn:false loadpath name in (dir, file) with Not_found -> try (dir, library_full_filename dir) with Not_found -> raise LibNotFound let locate_qualified_library qid = try let loadpath = if qid.dirpath=[] then get_load_paths () else load_paths_of_dir_path (dir_of_path qid) in if loadpath = [] then raise LibUnmappedDir; let name = qid.basename^".vo" in let path, file = System.where_in_path loadpath name in let dir = extend_dirpath (find_logical_path path) (Id.of_string qid.basename) in try (dir, library_full_filename dir) with Not_found -> (dir, file) with Not_found -> raise LibNotFound let error_unmapped_dir qid = let prefix = qid.dirpath in errorlabstrm "load_absolute_library_from" (str "Cannot load " ++ pr_path qid ++ str ":" ++ spc () ++ str "no physical path bound to" ++ spc () ++ pr_dirlist prefix ++ fnl ()) let error_lib_not_found qid = errorlabstrm "load_absolute_library_from" (str"Cannot find library " ++ pr_path qid ++ str" in loadpath") let try_locate_absolute_library dir = try locate_absolute_library dir with | LibUnmappedDir -> error_unmapped_dir (path_of_dirpath dir) | LibNotFound -> error_lib_not_found (path_of_dirpath dir) let try_locate_qualified_library qid = try locate_qualified_library qid with | LibUnmappedDir -> error_unmapped_dir qid | LibNotFound -> error_lib_not_found qid let raw_intern_library f = System.raw_intern_state Coq_config.vo_magic_number f Internalise libraries open Cic let mk_library sd md f table digest cst = { library_name = sd.md_name; library_filename = f; library_compiled = md.md_compiled; library_opaques = table; library_deps = sd.md_deps; library_digest = digest; library_extra_univs = cst } let name_clash_message dir mdir f = str ("The file " ^ f ^ " contains library") ++ spc () ++ pr_dirpath mdir ++ spc () ++ str "and not library" ++ spc() ++ pr_dirpath dir let depgraph = ref LibraryMap.empty let intern_from_file (dir, f) = Flags.if_verbose chk_pp (str"[intern "++str f++str" ..."); let (sd,md,table,opaque_csts,digest) = try let ch = System.with_magic_number_check raw_intern_library f in let (sd:Cic.summary_disk), _, digest = System.marshal_in_segment f ch in let (md:Cic.library_disk), _, digest = System.marshal_in_segment f ch in let (opaque_csts:'a option), _, udg = System.marshal_in_segment f ch in let (discharging:'a option), _, _ = System.marshal_in_segment f ch in let (tasks:'a option), _, _ = System.marshal_in_segment f ch in let (table:Cic.opaque_table), pos, checksum = System.marshal_in_segment f ch in let () = close_in ch in let ch = open_in_bin f in if not (String.equal (Digest.channel ch pos) checksum) then errorlabstrm "intern_from_file" (str "Checksum mismatch"); let () = close_in ch in if dir <> sd.md_name then errorlabstrm "intern_from_file" (name_clash_message dir sd.md_name f); if tasks <> None || discharging <> None then errorlabstrm "intern_from_file" (str "The file "++str f++str " contains unfinished tasks"); if opaque_csts <> None then begin chk_pp (str " (was a vio file) "); Option.iter (fun (_,_,b) -> if not b then errorlabstrm "intern_from_file" (str "The file "++str f++str " is still a .vio")) opaque_csts; Validate.validate !Flags.debug Values.v_univopaques opaque_csts; end; Validate.validate !Flags.debug Values.v_libsum sd; Validate.validate !Flags.debug Values.v_lib md; Validate.validate !Flags.debug Values.v_opaques table; Flags.if_verbose chk_pp (str" done]" ++ fnl ()); let digest = if opaque_csts <> None then Cic.Dviovo (digest,udg) else (Cic.Dvo digest) in sd,md,table,opaque_csts,digest with e -> Flags.if_verbose chk_pp (str" failed!]" ++ fnl ()); raise e in depgraph := LibraryMap.add sd.md_name sd.md_deps !depgraph; opaque_tables := LibraryMap.add sd.md_name table !opaque_tables; Option.iter (fun (opaque_csts,_,_) -> opaque_univ_tables := LibraryMap.add sd.md_name opaque_csts !opaque_univ_tables) opaque_csts; let extra_cst = Option.default Univ.ContextSet.empty (Option.map (fun (_,cs,_) -> cs) opaque_csts) in mk_library sd md f table digest extra_cst let get_deps (dir, f) = try LibraryMap.find dir !depgraph with Not_found -> let _ = intern_from_file (dir,f) in LibraryMap.find dir !depgraph let rec intern_library seen (dir, f) needed = if LibrarySet.mem dir seen then failwith "Recursive dependencies!"; try let _ = find_library dir in needed with Not_found -> if List.mem_assoc_f DirPath.equal dir needed then needed else let m = intern_from_file (dir,f) in let seen' = LibrarySet.add dir seen in let deps = Array.map (fun (d,_) -> try_locate_absolute_library d) m.library_deps in (dir,m) :: Array.fold_right (intern_library seen') deps needed let rec fold_deps seen ff (dir,f) (s,acc) = if LibrarySet.mem dir seen then failwith "Recursive dependencies!"; if LibrarySet.mem dir s then (s,acc) else let deps = get_deps (dir,f) in let deps = Array.map (fun (d,_) -> try_locate_absolute_library d) deps in let seen' = LibrarySet.add dir seen in let (s',acc') = Array.fold_right (fold_deps seen' ff) deps (s,acc) in (LibrarySet.add dir s', ff dir acc') and fold_deps_list seen ff modl needed = List.fold_right (fold_deps seen ff) modl needed let fold_deps_list ff modl acc = snd (fold_deps_list LibrarySet.empty ff modl (LibrarySet.empty,acc)) let recheck_library ~norec ~admit ~check = let ml = List.map try_locate_qualified_library check in let nrl = List.map try_locate_qualified_library norec in let al = List.map try_locate_qualified_library admit in let needed = List.rev (List.fold_right (intern_library LibrarySet.empty) (ml@nrl) []) in let nochk = fold_deps_list LibrarySet.add nrl LibrarySet.empty in let nochk = fold_deps_list LibrarySet.remove ml nochk in let nochk = fold_deps_list LibrarySet.add al nochk in let nochk = List.fold_right LibrarySet.remove (List.map fst (nrl@ml)) nochk in Flags.if_verbose Feedback.msg_notice (fnl()++hv 2 (str "Ordered list:" ++ fnl() ++ prlist (fun (dir,_) -> pr_dirpath dir ++ fnl()) needed)); List.iter (check_one_lib nochk) needed; Flags.if_verbose Feedback.msg_notice (str"Modules were successfully checked") open Printf let mem s = let m = try_find_library s in h 0 (str (sprintf "%dk" (CObj.size_kb m)))
61b91d3739317efaa581452204dbc2eb3a9d0c87e3721fdd5b2cd96d805a4e58
tisnik/clojure-examples
project.clj
; ( C ) Copyright 2021 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (defproject clojure9-test "0.1.0-SNAPSHOT" :description "Projekt, který zajistí stažení Clojure verze 1.10.1" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.1"]] :plugins [[lein-codox "0.10.7"] [test2junit "1.1.0"] [ lein - test - out " 0.3.1 " ] [lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit "0.1.8"] [lein-clean-m2 "0.1.2"] [lein-project-edn "0.3.0"] [lein-marginalia "0.9.1"]] :main ^:skip-aot clojure9-test.core :target-path "target/%s" :profiles {:uberjar {:aot :all}})
null
https://raw.githubusercontent.com/tisnik/clojure-examples/78061b533c0755d0165002961334bbe98d994087/clojure9-test/project.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors:
( C ) Copyright 2021 -v10.html (defproject clojure9-test "0.1.0-SNAPSHOT" :description "Projekt, který zajistí stažení Clojure verze 1.10.1" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.1"]] :plugins [[lein-codox "0.10.7"] [test2junit "1.1.0"] [ lein - test - out " 0.3.1 " ] [lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit "0.1.8"] [lein-clean-m2 "0.1.2"] [lein-project-edn "0.3.0"] [lein-marginalia "0.9.1"]] :main ^:skip-aot clojure9-test.core :target-path "target/%s" :profiles {:uberjar {:aot :all}})
02cb179aa3a4cb62ea7d72a5e1bde2b18d0cec819c6a144153ae76818a8a235c
FranklinChen/learn-you-some-erlang
cards.erl
-module(cards). -export([kind/1, main/0]). -type suit() :: spades | clubs | hearts | diamonds. -type value() :: 1..10 | j | q | k. -type card() :: {suit(), value()}. -spec kind(card()) -> face | number. kind({_, A}) when A >= 1, A =< 10 -> number; kind(_) -> face. main() -> number = kind({spades, 7}), face = kind({hearts, k}), number = kind({rubies, 4}), face = kind({clubs, q}).
null
https://raw.githubusercontent.com/FranklinChen/learn-you-some-erlang/878c8bc2011a12862fe72dd7fdc6c921348c79d6/cards.erl
erlang
-module(cards). -export([kind/1, main/0]). -type suit() :: spades | clubs | hearts | diamonds. -type value() :: 1..10 | j | q | k. -type card() :: {suit(), value()}. -spec kind(card()) -> face | number. kind({_, A}) when A >= 1, A =< 10 -> number; kind(_) -> face. main() -> number = kind({spades, 7}), face = kind({hearts, k}), number = kind({rubies, 4}), face = kind({clubs, q}).
5bd30cfdaa3d338036578704beb13d901ed5d6779285834ab0d558f52f22cb44
RefactoringTools/HaRe
A2_AstOut.hs
module A2 where import D1 import C1 (Tree, isSame, myFringe) import C1 import B1 main :: (Tree Int) -> Bool main t = isSame (sumSquares (fringe t)) ((sumSquares (B1.myFringe t)) + (sumSquares (C1.myFringe t)))
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/mkImpExplicit/A2_AstOut.hs
haskell
module A2 where import D1 import C1 (Tree, isSame, myFringe) import C1 import B1 main :: (Tree Int) -> Bool main t = isSame (sumSquares (fringe t)) ((sumSquares (B1.myFringe t)) + (sumSquares (C1.myFringe t)))
b52b97d6c8c88b7ba9fa6d98ed38c7aec10ee84ca30c85bda02417edd2abaf5b
boot-clj/boot
main.clj
(ns boot.main (:import [boot App]) (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.pprint :as pp] [boot.pod :as pod] [boot.core :as core] [boot.file :as file] [boot.util :as util] [boot.from.clojure.tools.cli :as cli])) (def cli-opts [["-a" "--asset-paths PATH" "Add PATH to set of asset directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-b" "--boot-script" "Print generated boot script for debugging."] ["-B" "--no-boot-script" "Ignore boot script in current directory."] ["-c" "--checkouts SYM:VER" "Add checkout dependency (eg. -c foo/bar:1.2.3)." :assoc-fn #(let [[p v] (string/split %3 #":" 2)] (update-in %1 [%2] (fnil conj []) (pod/canonical-coord [(read-string p) (or v "(0,)")])))] ["-C" "--no-colors" "Remove ANSI escape codes from printed output."] ["-d" "--dependencies SYM:VER" "Add dependency to project (eg. -d foo/bar:1.2.3)." :assoc-fn #(let [[p v] (string/split %3 #":" 2)] (update-in %1 [%2] (fnil conj []) (pod/canonical-coord [(read-string p) (or v "RELEASE")])))] ["-E" "--exclusions SYM" "Add the SYM dependency to the set of global exclusions." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) (symbol %3))] ["-e" "--set-env KEY=VAL" "Add KEY => VAL to project env map." :assoc-fn #(let [[k v] (string/split %3 #"=" 2)] (update-in %1 [%2] (fnil assoc {}) (keyword k) v))] ["-i" "--init EXPR" "Evaluate EXPR in the boot.user context." :assoc-fn #(update-in %1 [%2] (fnil conj []) (read-string %3))] [nil "--disable-watchers" "Disable registering file watches (inotify/FSEvents) for constrained environments."] ["-f" "--file PATH" "Evaluate PATH (implies -BP). Args and options passed to -main."] ["-h" "--help" "Print basic usage and help info."] ["-o" "--offline" "Don't attempt to access remote repositories." :id :offline?] ["-P" "--no-profile" "Skip loading of profile.boot script."] ["-r" "--resource-paths PATH" "Add PATH to set of resource directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-q" "--quiet" "Suppress output from boot itself."] ["-s" "--source-paths PATH" "Add PATH to set of source directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-u" "--update" "Update boot to latest release version."] ["-U" "--update-snapshot" "Update boot to latest snapshot version."] ["-v" "--verbose" "More error info (-vv more verbose, etc.)" :assoc-fn (fn [x y _] (update-in x [y] (fnil inc 0)))] ["-V" "--version" "Print boot version info."] ["-x" "--exclude-clojure" "Add org.clojure/clojure to the set of global exclusions."]]) (defn- dep-ns-decls [jar] (binding [*print-meta* true] (pod/with-eval-worker (require '[clojure.tools.namespace.find :as nsf]) (with-open [jf (java.util.jar.JarFile. ~(.getPath (io/file jar)))] (into [] (nsf/find-ns-decls-in-jarfile jf)))))) (defn- export-tasks? [[_ name docstring? attr-map?]] (->> [docstring? attr-map?] (filter map?) first (merge (meta name)) :boot/export-tasks)) (defn- export-task-namespaces [env] (-> #(->> (pod/resolve-dependency-jar env %) dep-ns-decls (filter export-tasks?) (map second)) (mapcat (:dependencies env)))) (defn- parse-cli-opts [args] ((juxt :errors :options :arguments) (cli/parse-opts args cli-opts :in-order true))) (defn- with-comments [tag forms] (string/join "\n" [(format ";; start %s" tag) forms (format ";; end %s" tag)])) (defn pr-boot-form [form] (if (<= @util/*verbosity* 1) (pr-str form) (let [[op & [msg & more]] form] (with-out-str (pp/write form :dispatch pp/code-dispatch))))) (defn emit [boot? argv userscript localscript bootscript import-ns inits] (let [boot-use '[boot.core boot.util boot.task.built-in]] (str (string/join "\n\n" (remove nil? [(pr-boot-form `(ns boot.user (:use ~@(concat boot-use import-ns)))) (when userscript (with-comments "global profile" userscript)) (when localscript (with-comments "local profile" localscript)) (when inits (with-comments "--init exprs" inits)) (with-comments "boot script" bootscript) (pr-boot-form `(let [boot?# ~boot?] (if-not boot?# (when-let [main# (resolve 'boot.user/-main)] (main# ~@argv)) (core/boot ~@(or (seq argv) ["boot.task.built-in/help"])))))])) "\n"))) (defn shebang? [arg] (when (and (<= 0 (.indexOf arg (int \/))) (.exists (io/file arg))) (let [bang-line (str (first (string/split (slurp arg) #"\n"))) full-path (System/getProperty "boot.app.path") base-path (.getName (io/file full-path)) full-pat (re-pattern (format "^#!\\s*\\Q%s\\E(?:\\s+.*)?$" full-path)) base-pat (re-pattern (format "^#!\\s*/usr/bin/env\\s+\\Q%s\\E(?:\\s+.*)?$" base-path))] (or (re-find full-pat bang-line) (re-find base-pat bang-line))))) (defn parse-bootignore [f] (when (.isFile f) (->> (string/split (slurp f) #"\n") (remove string/blank?) (map re-pattern) set))) (defn -main [pod-id worker-pod shutdown-hooks [arg0 & args :as args*]] (when (not= (boot.App/getVersion) (boot.App/getBootVersion)) (let [url "-clj/boot#install"] (util/exit-error (println (format "Please download latest Boot binary: %s" url))))) (pod/set-pod-id! pod-id) (pod/set-worker-pod! worker-pod) (reset! pod/shutdown-hooks shutdown-hooks) (let [[arg0 args args*] (if (seq args*) [arg0 args args*] ["--help" nil ["--help"]]) bootscript (App/config "BOOT_FILE" "build.boot") exists? #(when (.isFile (io/file %)) %) have-bootscript? (exists? bootscript) [arg0 args] (cond (shebang? arg0) [arg0 args] have-bootscript? [bootscript args*] :else [nil args*]) boot? (contains? #{nil bootscript} arg0) [errs opts args] (if-not boot? [nil {} args] (parse-cli-opts args)) opts (if-let [x (:exclude-clojure opts)] (-> (dissoc opts :exclude-clojure) (update-in [:exclusions] (fnil conj #{}) 'org.clojure/clojure)) opts) arg0 (or (:file opts) (if (:no-boot-script opts) nil arg0)) boot? (and boot? (not (:file opts))) verbosity (if (:quiet opts) (* -1 @util/*verbosity*) (or (:verbose opts) 0)) watchers? (if (:disable-watchers opts) false @util/*watchers?*)] (when (seq errs) (util/exit-error (println (apply str (interpose "\n" errs))))) (when (:no-colors opts) (reset! util/*colorize?* false)) (swap! util/*verbosity* + verbosity) (reset! util/*watchers?* watchers?) (pod/with-eval-in worker-pod (require '[boot.util :as util]) (swap! util/*verbosity* + ~verbosity) (reset! util/*watchers?* ~watchers?)) (binding [*out* (util/auto-flush *out*) *err* (util/auto-flush *err*) core/*boot-opts* opts core/*boot-script* arg0 core/*boot-version* (boot.App/getBootVersion) core/*app-version* (boot.App/getVersion)] (util/exit-ok (let [userscript (util/with-let [x (-> (System/getProperty "user.home") (io/file ".profile.boot") exists?)] (when x (util/warn "** WARNING: ~/.profile.boot is deprecated.\n") (util/warn "** Please use $BOOT_HOME/profile.boot instead.\n") (util/warn "** See: -clj/boot/issues/157\n"))) userscript (or userscript (exists? (io/file (App/getBootDir) "profile.boot"))) localscript (exists? (io/file "profile.boot")) profile? (not (:no-profile opts)) bootstr (some->> arg0 slurp) userstr (when profile? (some->> userscript slurp)) localstr (when profile? (some->> localscript slurp)) initial-env (->> [:source-paths :resource-paths :asset-paths :dependencies :exclusions :checkouts :offline?] (reduce #(if-let [v (opts %2)] (assoc %1 %2 v) %1) {}) (merge {} (:set-env opts))) import-ns (export-task-namespaces initial-env) scriptstr (binding [*print-meta* true] (emit boot? args userstr localstr bootstr import-ns (:init opts)))] (when (:boot-script opts) (util/exit-ok (print scriptstr))) (when (:version opts) (util/exit-ok (boot.App/printVersion))) (reset! core/bootignore (parse-bootignore (io/file ".bootignore"))) (#'core/init!) (pod/with-call-worker (boot.aether/load-wagon-mappings)) (apply core/set-env! (->> initial-env (mapcat identity) seq)) (reset! @#'core/cli-base initial-env) (try (load-string scriptstr) (catch clojure.lang.Compiler$CompilerException cx (let [l (.-line cx) c (.getCause cx) m (.getMessage (or c cx)) x (or c cx)] (throw (ex-info m (merge (sorted-map :line l) (ex-data c)) x))))))))))
null
https://raw.githubusercontent.com/boot-clj/boot/64334b4d5744b1444634f4a5a5a52b3ae67dddeb/boot/core/src/boot/main.clj
clojure
(ns boot.main (:import [boot App]) (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.pprint :as pp] [boot.pod :as pod] [boot.core :as core] [boot.file :as file] [boot.util :as util] [boot.from.clojure.tools.cli :as cli])) (def cli-opts [["-a" "--asset-paths PATH" "Add PATH to set of asset directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-b" "--boot-script" "Print generated boot script for debugging."] ["-B" "--no-boot-script" "Ignore boot script in current directory."] ["-c" "--checkouts SYM:VER" "Add checkout dependency (eg. -c foo/bar:1.2.3)." :assoc-fn #(let [[p v] (string/split %3 #":" 2)] (update-in %1 [%2] (fnil conj []) (pod/canonical-coord [(read-string p) (or v "(0,)")])))] ["-C" "--no-colors" "Remove ANSI escape codes from printed output."] ["-d" "--dependencies SYM:VER" "Add dependency to project (eg. -d foo/bar:1.2.3)." :assoc-fn #(let [[p v] (string/split %3 #":" 2)] (update-in %1 [%2] (fnil conj []) (pod/canonical-coord [(read-string p) (or v "RELEASE")])))] ["-E" "--exclusions SYM" "Add the SYM dependency to the set of global exclusions." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) (symbol %3))] ["-e" "--set-env KEY=VAL" "Add KEY => VAL to project env map." :assoc-fn #(let [[k v] (string/split %3 #"=" 2)] (update-in %1 [%2] (fnil assoc {}) (keyword k) v))] ["-i" "--init EXPR" "Evaluate EXPR in the boot.user context." :assoc-fn #(update-in %1 [%2] (fnil conj []) (read-string %3))] [nil "--disable-watchers" "Disable registering file watches (inotify/FSEvents) for constrained environments."] ["-f" "--file PATH" "Evaluate PATH (implies -BP). Args and options passed to -main."] ["-h" "--help" "Print basic usage and help info."] ["-o" "--offline" "Don't attempt to access remote repositories." :id :offline?] ["-P" "--no-profile" "Skip loading of profile.boot script."] ["-r" "--resource-paths PATH" "Add PATH to set of resource directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-q" "--quiet" "Suppress output from boot itself."] ["-s" "--source-paths PATH" "Add PATH to set of source directories." :assoc-fn #(update-in %1 [%2] (fnil conj #{}) %3)] ["-u" "--update" "Update boot to latest release version."] ["-U" "--update-snapshot" "Update boot to latest snapshot version."] ["-v" "--verbose" "More error info (-vv more verbose, etc.)" :assoc-fn (fn [x y _] (update-in x [y] (fnil inc 0)))] ["-V" "--version" "Print boot version info."] ["-x" "--exclude-clojure" "Add org.clojure/clojure to the set of global exclusions."]]) (defn- dep-ns-decls [jar] (binding [*print-meta* true] (pod/with-eval-worker (require '[clojure.tools.namespace.find :as nsf]) (with-open [jf (java.util.jar.JarFile. ~(.getPath (io/file jar)))] (into [] (nsf/find-ns-decls-in-jarfile jf)))))) (defn- export-tasks? [[_ name docstring? attr-map?]] (->> [docstring? attr-map?] (filter map?) first (merge (meta name)) :boot/export-tasks)) (defn- export-task-namespaces [env] (-> #(->> (pod/resolve-dependency-jar env %) dep-ns-decls (filter export-tasks?) (map second)) (mapcat (:dependencies env)))) (defn- parse-cli-opts [args] ((juxt :errors :options :arguments) (cli/parse-opts args cli-opts :in-order true))) (defn- with-comments [tag forms] (string/join "\n" [(format ";; start %s" tag) forms (format ";; end %s" tag)])) (defn pr-boot-form [form] (if (<= @util/*verbosity* 1) (pr-str form) (let [[op & [msg & more]] form] (with-out-str (pp/write form :dispatch pp/code-dispatch))))) (defn emit [boot? argv userscript localscript bootscript import-ns inits] (let [boot-use '[boot.core boot.util boot.task.built-in]] (str (string/join "\n\n" (remove nil? [(pr-boot-form `(ns boot.user (:use ~@(concat boot-use import-ns)))) (when userscript (with-comments "global profile" userscript)) (when localscript (with-comments "local profile" localscript)) (when inits (with-comments "--init exprs" inits)) (with-comments "boot script" bootscript) (pr-boot-form `(let [boot?# ~boot?] (if-not boot?# (when-let [main# (resolve 'boot.user/-main)] (main# ~@argv)) (core/boot ~@(or (seq argv) ["boot.task.built-in/help"])))))])) "\n"))) (defn shebang? [arg] (when (and (<= 0 (.indexOf arg (int \/))) (.exists (io/file arg))) (let [bang-line (str (first (string/split (slurp arg) #"\n"))) full-path (System/getProperty "boot.app.path") base-path (.getName (io/file full-path)) full-pat (re-pattern (format "^#!\\s*\\Q%s\\E(?:\\s+.*)?$" full-path)) base-pat (re-pattern (format "^#!\\s*/usr/bin/env\\s+\\Q%s\\E(?:\\s+.*)?$" base-path))] (or (re-find full-pat bang-line) (re-find base-pat bang-line))))) (defn parse-bootignore [f] (when (.isFile f) (->> (string/split (slurp f) #"\n") (remove string/blank?) (map re-pattern) set))) (defn -main [pod-id worker-pod shutdown-hooks [arg0 & args :as args*]] (when (not= (boot.App/getVersion) (boot.App/getBootVersion)) (let [url "-clj/boot#install"] (util/exit-error (println (format "Please download latest Boot binary: %s" url))))) (pod/set-pod-id! pod-id) (pod/set-worker-pod! worker-pod) (reset! pod/shutdown-hooks shutdown-hooks) (let [[arg0 args args*] (if (seq args*) [arg0 args args*] ["--help" nil ["--help"]]) bootscript (App/config "BOOT_FILE" "build.boot") exists? #(when (.isFile (io/file %)) %) have-bootscript? (exists? bootscript) [arg0 args] (cond (shebang? arg0) [arg0 args] have-bootscript? [bootscript args*] :else [nil args*]) boot? (contains? #{nil bootscript} arg0) [errs opts args] (if-not boot? [nil {} args] (parse-cli-opts args)) opts (if-let [x (:exclude-clojure opts)] (-> (dissoc opts :exclude-clojure) (update-in [:exclusions] (fnil conj #{}) 'org.clojure/clojure)) opts) arg0 (or (:file opts) (if (:no-boot-script opts) nil arg0)) boot? (and boot? (not (:file opts))) verbosity (if (:quiet opts) (* -1 @util/*verbosity*) (or (:verbose opts) 0)) watchers? (if (:disable-watchers opts) false @util/*watchers?*)] (when (seq errs) (util/exit-error (println (apply str (interpose "\n" errs))))) (when (:no-colors opts) (reset! util/*colorize?* false)) (swap! util/*verbosity* + verbosity) (reset! util/*watchers?* watchers?) (pod/with-eval-in worker-pod (require '[boot.util :as util]) (swap! util/*verbosity* + ~verbosity) (reset! util/*watchers?* ~watchers?)) (binding [*out* (util/auto-flush *out*) *err* (util/auto-flush *err*) core/*boot-opts* opts core/*boot-script* arg0 core/*boot-version* (boot.App/getBootVersion) core/*app-version* (boot.App/getVersion)] (util/exit-ok (let [userscript (util/with-let [x (-> (System/getProperty "user.home") (io/file ".profile.boot") exists?)] (when x (util/warn "** WARNING: ~/.profile.boot is deprecated.\n") (util/warn "** Please use $BOOT_HOME/profile.boot instead.\n") (util/warn "** See: -clj/boot/issues/157\n"))) userscript (or userscript (exists? (io/file (App/getBootDir) "profile.boot"))) localscript (exists? (io/file "profile.boot")) profile? (not (:no-profile opts)) bootstr (some->> arg0 slurp) userstr (when profile? (some->> userscript slurp)) localstr (when profile? (some->> localscript slurp)) initial-env (->> [:source-paths :resource-paths :asset-paths :dependencies :exclusions :checkouts :offline?] (reduce #(if-let [v (opts %2)] (assoc %1 %2 v) %1) {}) (merge {} (:set-env opts))) import-ns (export-task-namespaces initial-env) scriptstr (binding [*print-meta* true] (emit boot? args userstr localstr bootstr import-ns (:init opts)))] (when (:boot-script opts) (util/exit-ok (print scriptstr))) (when (:version opts) (util/exit-ok (boot.App/printVersion))) (reset! core/bootignore (parse-bootignore (io/file ".bootignore"))) (#'core/init!) (pod/with-call-worker (boot.aether/load-wagon-mappings)) (apply core/set-env! (->> initial-env (mapcat identity) seq)) (reset! @#'core/cli-base initial-env) (try (load-string scriptstr) (catch clojure.lang.Compiler$CompilerException cx (let [l (.-line cx) c (.getCause cx) m (.getMessage (or c cx)) x (or c cx)] (throw (ex-info m (merge (sorted-map :line l) (ex-data c)) x))))))))))
b011ae3d113607ec4386e98fd699de4286f6b358aa5802e31f9b8f0bc9f3361f
clojure-vim/neovim-client
message.clj
(ns neovim-client.message) (def +request+ 0) (def +response+ 1) (def +notify+ 2) (let [last-id (atom 0)] (defn next-id [] (swap! last-id inc) @last-id)) (defn gen-msg-id "Get a unique message id." [] (next-id)) (defn ->request-msg "Construct a msgpack-rpc request message." [type args] [+request+ (gen-msg-id) type args]) (defn ->response-msg "Construct a msgpack-rpc response message." [id result] [+response+ id nil result]) ;; TODO - find better way to get [B type. (def byte-array-type (type (.getBytes "foo"))) (defn bytes->str [t] (condp = (type t) byte-array-type (String. t) t)) ;; ***** Accessor fns ***** (def msg-type first) ;; Only true for request & response, notify has no id (def id second) (defn request? [msg] (= +request+ (msg-type msg))) (defn response? [msg] (= +response+ (msg-type msg))) (defn notify? [msg] (= +notify+ (msg-type msg))) (defn value [msg] {:pre [(response? msg)]} (bytes->str (last msg))) (defn method [msg] {:pre [(or (request? msg) (notify? msg))]} (bytes->str (nth (reverse msg) 1))) (defn params [msg] {:pre [(or (request? msg) (response? msg) (notify? msg))]} (last msg))
null
https://raw.githubusercontent.com/clojure-vim/neovim-client/664813b6890b9acdf4cdf58ea72049744898159f/src/neovim_client/message.clj
clojure
TODO - find better way to get [B type. ***** Accessor fns ***** Only true for request & response, notify has no id
(ns neovim-client.message) (def +request+ 0) (def +response+ 1) (def +notify+ 2) (let [last-id (atom 0)] (defn next-id [] (swap! last-id inc) @last-id)) (defn gen-msg-id "Get a unique message id." [] (next-id)) (defn ->request-msg "Construct a msgpack-rpc request message." [type args] [+request+ (gen-msg-id) type args]) (defn ->response-msg "Construct a msgpack-rpc response message." [id result] [+response+ id nil result]) (def byte-array-type (type (.getBytes "foo"))) (defn bytes->str [t] (condp = (type t) byte-array-type (String. t) t)) (def msg-type first) (def id second) (defn request? [msg] (= +request+ (msg-type msg))) (defn response? [msg] (= +response+ (msg-type msg))) (defn notify? [msg] (= +notify+ (msg-type msg))) (defn value [msg] {:pre [(response? msg)]} (bytes->str (last msg))) (defn method [msg] {:pre [(or (request? msg) (notify? msg))]} (bytes->str (nth (reverse msg) 1))) (defn params [msg] {:pre [(or (request? msg) (response? msg) (notify? msg))]} (last msg))
f92d240b2be61c0d914697a1bebf146c1e742052b2834251cd4224b3dce29747
imrehg/ypsilon
gtk-hello.scm
#!/usr/bin/env ypsilon #!r6rs ;; gtk-hello.scm: ;; GTK hello world ;; ;; Requirements: : Gtk.framework Linux : : libgtk-x11-2.0.so ;; OpenBSD: libgtk-x11-2.0.so (import (rnrs) (srfi :48) (ypsilon gtk constants) (ypsilon gtk init) (ypsilon gtk main) (ypsilon gtk window) (ypsilon gtk container) (ypsilon gtk button) (ypsilon gtk widget) (ypsilon gobject signal) (ypsilon ffi)) (gtk_init (vector (length (command-line))) (apply vector (command-line))) (let ((window (gtk_window_new GTK_WINDOW_TOPLEVEL)) (button (gtk_button_new_with_label "Hello World")) (destroy (signal-callback gboolean (GtkObject* gpointer) (lambda (obj data) (format #t "[destory ~s ~s]~%" obj data) (gtk_main_quit)))) (clicked (signal-callback gboolean (GtkButton* gpointer) (lambda (button data) (format #t "[clicked ~s ~s]~%" button data))))) (gtk_container_set_border_width window 10) (gtk_window_set_title window "Hello World") (gtk_window_resize window 256 128) (g_signal_connect window "destroy" destroy 0) (g_signal_connect button "clicked" clicked 0) (g_signal_connect_swapped button "clicked" gtk_widget_destroy window) (gtk_container_add window button) (gtk_widget_show button) (gtk_widget_show window) (gtk_main))
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/example/gtk-hello.scm
scheme
gtk-hello.scm: GTK hello world Requirements: OpenBSD: libgtk-x11-2.0.so
#!/usr/bin/env ypsilon #!r6rs : Gtk.framework Linux : : libgtk-x11-2.0.so (import (rnrs) (srfi :48) (ypsilon gtk constants) (ypsilon gtk init) (ypsilon gtk main) (ypsilon gtk window) (ypsilon gtk container) (ypsilon gtk button) (ypsilon gtk widget) (ypsilon gobject signal) (ypsilon ffi)) (gtk_init (vector (length (command-line))) (apply vector (command-line))) (let ((window (gtk_window_new GTK_WINDOW_TOPLEVEL)) (button (gtk_button_new_with_label "Hello World")) (destroy (signal-callback gboolean (GtkObject* gpointer) (lambda (obj data) (format #t "[destory ~s ~s]~%" obj data) (gtk_main_quit)))) (clicked (signal-callback gboolean (GtkButton* gpointer) (lambda (button data) (format #t "[clicked ~s ~s]~%" button data))))) (gtk_container_set_border_width window 10) (gtk_window_set_title window "Hello World") (gtk_window_resize window 256 128) (g_signal_connect window "destroy" destroy 0) (g_signal_connect button "clicked" clicked 0) (g_signal_connect_swapped button "clicked" gtk_widget_destroy window) (gtk_container_add window button) (gtk_widget_show button) (gtk_widget_show window) (gtk_main))
807968c3c6fe68b35e49b9c277676b145c30a856c7e66ed4133a40ecb82e4d42
eburlingame/arinc-parser
latlong_test.clj
(ns arinc424.fields.latlong-test (:require [arinc424.fields.latlong :refer :all] [arinc424.helpers :refer :all] [clojure.test :refer :all])) ; --- Tests --- (deftest dms-test (is (approx= 40.33611111 (dms 40 20 10)))) (deftest latitude-value-test (is (approx= 39.86078056 (latitude-value "N39513881"))) (is (approx= -78.86078056 (latitude-value "S78513881")))) (deftest longitude-value-test (is (approx= -90.359255555 (longitude-value "W090213332"))) (is (approx= -120.35925555 (longitude-value "E120213332"))) (is (approx= -104.75220555 (longitude-value "W104450794")))) (deftest station-declination-value-test (is (= [:east-of-true-north 0.0] (station-declination-value "E0000"))) (is (= [:west-of-true-north 1.0] (station-declination-value "W0010"))) (is (= [:oriented-to-grid-north 101.0] (station-declination-value "G1010"))))
null
https://raw.githubusercontent.com/eburlingame/arinc-parser/1bef86924aef21888c27301bf51af90262ec4c52/test/arinc424/fields/latlong_test.clj
clojure
--- Tests ---
(ns arinc424.fields.latlong-test (:require [arinc424.fields.latlong :refer :all] [arinc424.helpers :refer :all] [clojure.test :refer :all])) (deftest dms-test (is (approx= 40.33611111 (dms 40 20 10)))) (deftest latitude-value-test (is (approx= 39.86078056 (latitude-value "N39513881"))) (is (approx= -78.86078056 (latitude-value "S78513881")))) (deftest longitude-value-test (is (approx= -90.359255555 (longitude-value "W090213332"))) (is (approx= -120.35925555 (longitude-value "E120213332"))) (is (approx= -104.75220555 (longitude-value "W104450794")))) (deftest station-declination-value-test (is (= [:east-of-true-north 0.0] (station-declination-value "E0000"))) (is (= [:west-of-true-north 1.0] (station-declination-value "W0010"))) (is (= [:oriented-to-grid-north 101.0] (station-declination-value "G1010"))))