_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
6640688e9848c99dbf9790ec7814371e9e742f372c7b26a7f61bab3809b90103
mattdw/caponia
index.clj
(ns caponia.index (:use [stemmers.core :only [stems]]) (:require [clojure.java.io :as io] [clojure.edn :as edn] [stemmers.porter])) (defrecord Index [data stemmer]) (defn make-index "Create a new (empty) index. Takes an optional stemmer function" ([] (make-index stemmers.porter/stem)) ([stemmer-func] (agent (Index. {} stemmer-func)))) # # Functions that take stems (defn add-entry "Insert an entry into the index, associating {key weight} with stem" [index stem key weight] (send index assoc-in [:data stem key] weight)) (defn remove-entries "dissociate key from stems" [index key stems] (doseq [stem (set stems)] (send index update-in [:data stem] #(dissoc % key)))) # # Functions that take blocks of text (defn index-text "Indexes a chunk of text. - `key` is an id for your reference. - `data` can be: - single string - a seq of [txt weight] pairs. - `weight` is a multiplier for occurrences. For example: (index doc-id doc-body) ;; defaults to weight=1 (index doc-id doc-body 3) (index doc-id [[doc-body 1] [doc-title 2] [doc-tags 2]]) " ([index key txt weight] (index-text index key [[txt 1]])) ([index key data] (->> (let [data (if (coll? data) data [[data 1]])] (for [[text-block multiplier] data] (into {} (->> (stems text-block (:stemmer @index)) (frequencies) (map (fn [[stem num]] [stem (* num multiplier)])))))) (apply merge-with +) (map (fn [[stem num]] (add-entry index stem key num))) (dorun)))) (defn unindex-text "remove all entries for [key txt]." [index key txt] (remove-entries index key (stems txt (:stemmer @index))) nil) (defn unindex-all "remove *all* entries for key. Traverses the entire index." [index key] (send index update-in [:data] (fn [state] (reduce #(update-in %1 [%2] dissoc key) state (keys state)))) nil) ;; ## Disk persistence (defn save-index "Serialise an index to a file. The index stores the filename with the index, and will save to that on subsequent saves." ([index] ; save to previous filename (if-let [file (:file-storage-name @index)] (binding [*out* (io/writer file)] (prn (:data @index))) (throw (Exception. "No filename specified"))) index) ([index filename-or-file] ; save to specified filename (send index assoc :file-storage-name filename-or-file) (await index) (save-index index))) (defn load-index "Load a serialised index from a file, storing the filename in meta." [index filename-or-file] (send index assoc :data (edn/read-string (slurp filename-or-file))) (send index assoc :file-storage-name filename-or-file))
null
https://raw.githubusercontent.com/mattdw/caponia/5a638973c207a664788a9959aeda7feef1998fe8/src/caponia/index.clj
clojure
defaults to weight=1 ## Disk persistence save to previous filename save to specified filename
(ns caponia.index (:use [stemmers.core :only [stems]]) (:require [clojure.java.io :as io] [clojure.edn :as edn] [stemmers.porter])) (defrecord Index [data stemmer]) (defn make-index "Create a new (empty) index. Takes an optional stemmer function" ([] (make-index stemmers.porter/stem)) ([stemmer-func] (agent (Index. {} stemmer-func)))) # # Functions that take stems (defn add-entry "Insert an entry into the index, associating {key weight} with stem" [index stem key weight] (send index assoc-in [:data stem key] weight)) (defn remove-entries "dissociate key from stems" [index key stems] (doseq [stem (set stems)] (send index update-in [:data stem] #(dissoc % key)))) # # Functions that take blocks of text (defn index-text "Indexes a chunk of text. - `key` is an id for your reference. - `data` can be: - single string - a seq of [txt weight] pairs. - `weight` is a multiplier for occurrences. For example: (index doc-id doc-body 3) (index doc-id [[doc-body 1] [doc-title 2] [doc-tags 2]]) " ([index key txt weight] (index-text index key [[txt 1]])) ([index key data] (->> (let [data (if (coll? data) data [[data 1]])] (for [[text-block multiplier] data] (into {} (->> (stems text-block (:stemmer @index)) (frequencies) (map (fn [[stem num]] [stem (* num multiplier)])))))) (apply merge-with +) (map (fn [[stem num]] (add-entry index stem key num))) (dorun)))) (defn unindex-text "remove all entries for [key txt]." [index key txt] (remove-entries index key (stems txt (:stemmer @index))) nil) (defn unindex-all "remove *all* entries for key. Traverses the entire index." [index key] (send index update-in [:data] (fn [state] (reduce #(update-in %1 [%2] dissoc key) state (keys state)))) nil) (defn save-index "Serialise an index to a file. The index stores the filename with the index, and will save to that on subsequent saves." (if-let [file (:file-storage-name @index)] (binding [*out* (io/writer file)] (prn (:data @index))) (throw (Exception. "No filename specified"))) index) (send index assoc :file-storage-name filename-or-file) (await index) (save-index index))) (defn load-index "Load a serialised index from a file, storing the filename in meta." [index filename-or-file] (send index assoc :data (edn/read-string (slurp filename-or-file))) (send index assoc :file-storage-name filename-or-file))
7bd06519d23e75453d0008c26e1f8404d16a3cbe5cd0fa6ce5c60fea18ea2918
RunOrg/RunOrg
sqlConnection.ml
(* © 2014 RunOrg *) open Std (* A 't' connection keeps a queue of operations to be performed, and runs them against a 'pgsql' connection which is created on-the-fly. Pooling is applied to 'pgsql' connections. All the work is done in the [process] function below, which forwards appropriate calls to members of type [operation]. Exceptions raised in [process] are treated as fatal errors and will shut down the process. *) (* Connection pooling ================== *) type config = { host : string ; port : int ; database : string ; user : string ; password : string ; pool_size : int ; } (* Forcibly disconnects from a postgreSQL database. Obviously not returning it to the pool. *) let disconnect pgsql = pgsql # finish exception ConnectionFailed of string Connect to the database . Does not use the pool . let connect config = try let sql = new Postgresql.connection ~host:config.host ~port:(string_of_int config.port) ~dbname:config.database ~user:config.user ~password:config.password () in sql # set_nonblocking true ; sql with | Postgresql.Error (Postgresql.Connection_failure message) -> raise (ConnectionFailed message) | Postgresql.Error reason -> raise (ConnectionFailed (Postgresql.string_of_error reason)) A pool of connections . There is one such pool for every configuration object . configuration object. *) type pool = { mutable pool : Postgresql.connection list ; mutable size : int ; max_size : int ; } (* Connection pools, keyed by (host,port,db) *) let pools = Hashtbl.create 10 Returns the pool for the provided configuration , and whether this is the first time this pool is requested . this is the first time this pool is requested. *) let get_pool config = let key = (config.host, config.port, config.database) in try false, Hashtbl.find pools key with Not_found -> let pool = { pool = [] ; size = 0 ; max_size = config.pool_size } in Hashtbl.add pools key pool ; true, pool Connect to the database . Picks a connection out of the pool , if there is one . if there is one. *) let connect_from_pool config = let _, pool = get_pool config in match pool.pool with | [] -> connect config | h :: t -> pool.pool <- t ; pool.size <- pool.size - 1 ; h (* Returns a connection to the pool. If the pool is full, kills the connection. *) let return_to_pool config = function | None -> () | Some pgsql -> let _, pool = get_pool config in if pool.size = pool.max_size then disconnect pgsql else ( pool.size <- pool.size + 1 ; pool.pool <- pgsql :: pool.pool ) (* Data types ========== *) type query = string type param = [ `Binary of string | `String of string | `Id of Id.t | `Int of int ] type result = string array array (* An operation that needs to be performed by this query. *) type operation = { (* Run this function to start the operation. *) start : Postgresql.connection -> unit ; (* Run this function to determine if the operation is finished. If [`Failed], may call [start] on another connection. *) poll : Postgresql.connection -> [ `Finished | `Waiting | `Failed of exn ] ; This function loops until a result is available , calling its first parameter on each iteration then yielding if no result was found . first parameter on each iteration then yielding if no result was found. *) wait : 'ctx. (unit -> unit) -> ('ctx, result) Run.t ; (* Transaction-related meta-information. Helps mark the connection as 'in transaction' when applicable. *) special : [ `BeginTransaction | `EndTransaction ] option ; (* The query that generated this operation. For debugging and logging purporses. *) query : query ; } (* A raw database connection. *) type t = { The database connection , if any . A brand new database connection will be created the first time it is required . be created the first time it is required. *) mutable pgsql : Postgresql.connection option ; (* The operation being executed by the database right now. *) mutable current : operation option ; (* Operations that will start once the current operation finishes. *) pending : operation Queue.t ; (* The configuration used to connect to the database. *) config : config ; Is this the first time a database connection was requested for this configuration ? configuration ? *) first : bool ; (* Is this connection running a transaction ? If a query fails during a transaction, there are no retries. *) mutable transaction : bool ; (* Has this connection been marked for relase ? This would make executing anything a fatal error. *) mutable released : bool ; } (* Operations ========== *) exception OperationFailed of exn let operation ?special (query:string) params = (* The number of times this operation has failed. *) let fail_count = ref 0 in (* Result is stored in this reference. *) let result : (result, exn) Std.result option ref = ref None in (* Starts the query on a new database. *) let start (pgsql:Postgresql.connection) = result := None ; let binary_params = Array.of_list (List.map (function | `Binary _ -> true | `String _ | `Id _ | `Int _ -> false ) params) in let params = Array.of_list (List.map (function | `Binary s | `String s -> s | `Id i -> Id.to_string i | `Int i -> string_of_int i ) params) in try pgsql # send_query ~params ~binary_params query ; pgsql # flush with exn -> result := Some (Bad exn) in (* Polls a database for a query result. *) let poll pgsql = if !result = None then begin try pgsql # consume_input ; match pgsql # get_result with None -> () | Some r -> if not (pgsql # is_busy) then result := Some (Ok (r # get_all)) with exn -> result := Some (Bad exn) end ; match !result with | None -> `Waiting | Some (Ok _) -> `Finished | Some (Bad exn) -> incr fail_count ; result := None ; if !fail_count > 1 then begin raise (OperationFailed exn) end else `Failed exn in (* Stay busy waiting for a result. *) let rec wait process = process () ; match !result with | Some (Ok r) -> return r | Some (Bad _) (* <-- let 'poll' handle this *) | None -> Run.yield (Run.of_call wait process) in { start ; poll ; wait ; special ; query } (* Running queries =============== *) exception FailedDuringTransaction of exn exception ConnectionReleased of string (* Does a step of processing on the SQL database. Call this function on before checking for any results. *) let rec process t = (* Select the next operation 'op' to be performed. *) match t.current with | None when Queue.is_empty t.pending -> () (* Nothing to do... *) | None -> let op = Queue.take t.pending in ( match t.pgsql with Some pgsql -> op.start pgsql | None -> () ) ; t.current <- Some op ; process t | Some op -> if t.released then raise (ConnectionReleased op.query) ; if op.special = Some `BeginTransaction then t.transaction <- true ; if op.special = Some `EndTransaction then t.transaction <- false ; (* Select the database 'pgsql' on which the next operation *HAS* already been started. *) match t.pgsql with | None -> let pgsql = connect_from_pool t.config in op.start pgsql ; t.pgsql <- Some pgsql ; process t | Some pgsql -> (* Poll and process the result. *) match op.poll pgsql with | `Waiting -> () | `Finished -> t.current <- None ; process t | `Failed exn -> if t.transaction then raise (FailedDuringTransaction exn) else begin disconnect pgsql ; t.pgsql <- None ; process t end (* Wrapper around [process] above. Catches any exceptions and treats them as critical failures. *) let process t = try process t with | FailedDuringTransaction (OperationFailed exn) | FailedDuringTransaction exn -> Log.error "[FATAL] SQL error during transaction: %s" (Printexc.to_string exn) ; exit (-1) | ConnectionFailed reason -> Log.error "[FATAL] SQL connection failed: %s" reason ; exit (-1) | OperationFailed exn -> Log.error "[FATAL] SQL error not solved by re-connection: %s" (Printexc.to_string exn) ; exit (-1) | ConnectionReleased query -> Log.error "[FATAL] SQL connection released while executing:\n%s" query ; exit (-1) ; | exn -> Log.error "[FATAL] Unknown SQL error: %s" (Printexc.to_string exn) ; exit (-1) (* Start executing a query *) let run t ?special query params = let operation = operation ?special query params in Queue.push operation t.pending ; operation.wait (fun () -> process t) (* Public functions ================ *) Connect to the database . let connect config = { pgsql = None ; current = None ; config ; first = fst (get_pool config) ; pending = Queue.create () ; transaction = false ; released = false ; } Is this the first connection to this database by this process ? let is_first_connection t = t.first (* Public function for executing a query. *) let execute t query params = run t query params (* Start a transaction. *) let transaction t = let! _ = run t ~special:`BeginTransaction "BEGIN TRANSACTION" [] in return () (* End a transaction.*) let commit t = let! _ = run t ~special:`EndTransaction "COMMIT" [] in return () (* Release a transaction. *) let release t = let do_release () = return_to_pool t.config t.pgsql ; t.released <- true ; return () in if t.current = None && Queue.is_empty t.pending then do_release () else let! () = Run.sleep 30000.0 in do_release ()
null
https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/sqlConnection.ml
ocaml
© 2014 RunOrg A 't' connection keeps a queue of operations to be performed, and runs them against a 'pgsql' connection which is created on-the-fly. Pooling is applied to 'pgsql' connections. All the work is done in the [process] function below, which forwards appropriate calls to members of type [operation]. Exceptions raised in [process] are treated as fatal errors and will shut down the process. Connection pooling ================== Forcibly disconnects from a postgreSQL database. Obviously not returning it to the pool. Connection pools, keyed by (host,port,db) Returns a connection to the pool. If the pool is full, kills the connection. Data types ========== An operation that needs to be performed by this query. Run this function to start the operation. Run this function to determine if the operation is finished. If [`Failed], may call [start] on another connection. Transaction-related meta-information. Helps mark the connection as 'in transaction' when applicable. The query that generated this operation. For debugging and logging purporses. A raw database connection. The operation being executed by the database right now. Operations that will start once the current operation finishes. The configuration used to connect to the database. Is this connection running a transaction ? If a query fails during a transaction, there are no retries. Has this connection been marked for relase ? This would make executing anything a fatal error. Operations ========== The number of times this operation has failed. Result is stored in this reference. Starts the query on a new database. Polls a database for a query result. Stay busy waiting for a result. <-- let 'poll' handle this Running queries =============== Does a step of processing on the SQL database. Call this function on before checking for any results. Select the next operation 'op' to be performed. Nothing to do... Select the database 'pgsql' on which the next operation *HAS* already been started. Poll and process the result. Wrapper around [process] above. Catches any exceptions and treats them as critical failures. Start executing a query Public functions ================ Public function for executing a query. Start a transaction. End a transaction. Release a transaction.
open Std type config = { host : string ; port : int ; database : string ; user : string ; password : string ; pool_size : int ; } let disconnect pgsql = pgsql # finish exception ConnectionFailed of string Connect to the database . Does not use the pool . let connect config = try let sql = new Postgresql.connection ~host:config.host ~port:(string_of_int config.port) ~dbname:config.database ~user:config.user ~password:config.password () in sql # set_nonblocking true ; sql with | Postgresql.Error (Postgresql.Connection_failure message) -> raise (ConnectionFailed message) | Postgresql.Error reason -> raise (ConnectionFailed (Postgresql.string_of_error reason)) A pool of connections . There is one such pool for every configuration object . configuration object. *) type pool = { mutable pool : Postgresql.connection list ; mutable size : int ; max_size : int ; } let pools = Hashtbl.create 10 Returns the pool for the provided configuration , and whether this is the first time this pool is requested . this is the first time this pool is requested. *) let get_pool config = let key = (config.host, config.port, config.database) in try false, Hashtbl.find pools key with Not_found -> let pool = { pool = [] ; size = 0 ; max_size = config.pool_size } in Hashtbl.add pools key pool ; true, pool Connect to the database . Picks a connection out of the pool , if there is one . if there is one. *) let connect_from_pool config = let _, pool = get_pool config in match pool.pool with | [] -> connect config | h :: t -> pool.pool <- t ; pool.size <- pool.size - 1 ; h let return_to_pool config = function | None -> () | Some pgsql -> let _, pool = get_pool config in if pool.size = pool.max_size then disconnect pgsql else ( pool.size <- pool.size + 1 ; pool.pool <- pgsql :: pool.pool ) type query = string type param = [ `Binary of string | `String of string | `Id of Id.t | `Int of int ] type result = string array array type operation = { start : Postgresql.connection -> unit ; poll : Postgresql.connection -> [ `Finished | `Waiting | `Failed of exn ] ; This function loops until a result is available , calling its first parameter on each iteration then yielding if no result was found . first parameter on each iteration then yielding if no result was found. *) wait : 'ctx. (unit -> unit) -> ('ctx, result) Run.t ; special : [ `BeginTransaction | `EndTransaction ] option ; query : query ; } type t = { The database connection , if any . A brand new database connection will be created the first time it is required . be created the first time it is required. *) mutable pgsql : Postgresql.connection option ; mutable current : operation option ; pending : operation Queue.t ; config : config ; Is this the first time a database connection was requested for this configuration ? configuration ? *) first : bool ; mutable transaction : bool ; mutable released : bool ; } exception OperationFailed of exn let operation ?special (query:string) params = let fail_count = ref 0 in let result : (result, exn) Std.result option ref = ref None in let start (pgsql:Postgresql.connection) = result := None ; let binary_params = Array.of_list (List.map (function | `Binary _ -> true | `String _ | `Id _ | `Int _ -> false ) params) in let params = Array.of_list (List.map (function | `Binary s | `String s -> s | `Id i -> Id.to_string i | `Int i -> string_of_int i ) params) in try pgsql # send_query ~params ~binary_params query ; pgsql # flush with exn -> result := Some (Bad exn) in let poll pgsql = if !result = None then begin try pgsql # consume_input ; match pgsql # get_result with None -> () | Some r -> if not (pgsql # is_busy) then result := Some (Ok (r # get_all)) with exn -> result := Some (Bad exn) end ; match !result with | None -> `Waiting | Some (Ok _) -> `Finished | Some (Bad exn) -> incr fail_count ; result := None ; if !fail_count > 1 then begin raise (OperationFailed exn) end else `Failed exn in let rec wait process = process () ; match !result with | Some (Ok r) -> return r | None -> Run.yield (Run.of_call wait process) in { start ; poll ; wait ; special ; query } exception FailedDuringTransaction of exn exception ConnectionReleased of string let rec process t = match t.current with | None -> let op = Queue.take t.pending in ( match t.pgsql with Some pgsql -> op.start pgsql | None -> () ) ; t.current <- Some op ; process t | Some op -> if t.released then raise (ConnectionReleased op.query) ; if op.special = Some `BeginTransaction then t.transaction <- true ; if op.special = Some `EndTransaction then t.transaction <- false ; match t.pgsql with | None -> let pgsql = connect_from_pool t.config in op.start pgsql ; t.pgsql <- Some pgsql ; process t | Some pgsql -> match op.poll pgsql with | `Waiting -> () | `Finished -> t.current <- None ; process t | `Failed exn -> if t.transaction then raise (FailedDuringTransaction exn) else begin disconnect pgsql ; t.pgsql <- None ; process t end let process t = try process t with | FailedDuringTransaction (OperationFailed exn) | FailedDuringTransaction exn -> Log.error "[FATAL] SQL error during transaction: %s" (Printexc.to_string exn) ; exit (-1) | ConnectionFailed reason -> Log.error "[FATAL] SQL connection failed: %s" reason ; exit (-1) | OperationFailed exn -> Log.error "[FATAL] SQL error not solved by re-connection: %s" (Printexc.to_string exn) ; exit (-1) | ConnectionReleased query -> Log.error "[FATAL] SQL connection released while executing:\n%s" query ; exit (-1) ; | exn -> Log.error "[FATAL] Unknown SQL error: %s" (Printexc.to_string exn) ; exit (-1) let run t ?special query params = let operation = operation ?special query params in Queue.push operation t.pending ; operation.wait (fun () -> process t) Connect to the database . let connect config = { pgsql = None ; current = None ; config ; first = fst (get_pool config) ; pending = Queue.create () ; transaction = false ; released = false ; } Is this the first connection to this database by this process ? let is_first_connection t = t.first let execute t query params = run t query params let transaction t = let! _ = run t ~special:`BeginTransaction "BEGIN TRANSACTION" [] in return () let commit t = let! _ = run t ~special:`EndTransaction "COMMIT" [] in return () let release t = let do_release () = return_to_pool t.config t.pgsql ; t.released <- true ; return () in if t.current = None && Queue.is_empty t.pending then do_release () else let! () = Run.sleep 30000.0 in do_release ()
be04b5075667420a0ebac17cf9794c98e0a4656b387b1e73da58960c317b169f
plumatic/hiphip
type_impl_test.clj
;;; Benchmark code shared between array types. ;; Assumes the appropriate hiphip array type ns has been aliased as 'hiphip', and the appropriate Java baseline class has been imported as ' Baseline ' (use 'clojure.test 'hiphip.test-utils) (require '[hiphip.impl.core :as impl]) (def +type+ hiphip/+type+) (set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests for selection and partitioning (defn partitioned? [s pivot] (let [[smaller more] ((juxt take-while drop-while) #(< % pivot) s) [eq more] ((juxt take-while drop-while) #(= % pivot) more)] (every? #(> % pivot) more))) (defn selected? [s k] (let [[small big] (split-at k s)] (is (<= (apply max small) (apply min big))))) (defn ascending? [s] (= (seq s) (sort s))) (defn max-sorted? [s k] (let [[front back] (split-at (- (count s) k) s)] (and (every? #(<= % (first back)) front) (ascending? back)))) (defn min-sorted? [s k] (let [[front back] (split-at k s)] (and (every? #(>= % (last front)) back) (ascending? front)))) (defn de-index [arr indices] (is (= (count arr) (count indices))) (let [v (vec arr)] (map #(nth v %) indices))) (defn into-arr [s] (let [v (vec s)] (hiphip/amake [i (count v)] (nth v i)))) (defn direct-partition-ops-tests [s k] (let [a (into-arr s) pivot (nth a k)] (is (= a (hiphip/apartition! a pivot))) (is (partitioned? a pivot))) (let [a (into-arr s)] (is (= a (hiphip/aselect! a k))) (is (selected? a k))) (let [a (into-arr s)] (is (= a (hiphip/asort! a))) (is (ascending? a))) (let [a (into-arr s)] (is (= a (hiphip/asort-max! a k))) (is (max-sorted? a k))) (let [a (into-arr s)] (is (= a (hiphip/asort-min! a k))) (is (min-sorted? a k)))) (defn index-partition-ops-tests [s k] (let [a (into-arr s) pivot (nth a k)] (is (= (map long a) s)) (let [indices (hiphip.IndexArrays/make 0 (count s))] (is (partitioned? (de-index a (hiphip/apartition-indices! indices a pivot)) pivot))) (let [indices (hiphip.IndexArrays/make 0 (count s))] (is (selected? (de-index a (hiphip/aselect-indices! indices a k)) k))) (is (ascending? (de-index a (hiphip/asort-indices! a)))) (is (max-sorted? (de-index a (hiphip/amax-indices a k)) k)) (is (min-sorted? (de-index a (hiphip/amin-indices a k)) k)))) (deftest big-partition-and-sort-ops-test (let [n 1000 r (java.util.Random. 1)] (doseq [[test-name t] {"direct" direct-partition-ops-tests "indirect" index-partition-ops-tests} [seq-name s] {"zeros" (repeat n 0) "asc" (range n) "desc" (reverse (range n)) "rand" (repeatedly n #(.nextInt r 10000)) "rand-repeated" (repeatedly n #(.nextInt r 100))} k [1 10 50 100 500 900 950 990 999]] (testing (format "%s opts on %s with k=%s" test-name n k) (t s k))))) (deftest simple-partition-and-sort-opts-test (is (= [1 1 2 2 2 3] (map long (hiphip/apartition! (into-arr [2 1 2 1 2 3]) 2)))) (is (= [1 1 2 2] (map long (hiphip/aselect! (into-arr [1 2 2 1]) 2)))) (is (= [1 2 3 4] (map long (hiphip/asort! (into-arr [4 2 3 1]))))) (is (= [3 3 4] (take-last 3 (map long (hiphip/asort-max! (into-arr [-2 3 4 2 3 1 -1]) 3))))) (is (= [-2 -1 1] (take 3 (map long (hiphip/asort-min! (into-arr [-2 3 4 2 3 1 -1]) 3))))) (is (= [1 2 0] (seq (hiphip/apartition-indices! (hiphip.IndexArrays/make 0 3) (into-arr [3 1 2]) 2)))) (is (= [1 0] (seq (hiphip/aselect-indices! (hiphip.IndexArrays/make 0 2) (into-arr [2 1]) 1)))) (is (= [3 1 2 0] (seq (hiphip/asort-indices! (into-arr [4 2 3 1]))))) (is (= [4 2 1] (take-last 3 (hiphip/amax-indices (into-arr [-2 5 4 2 3 1 -1]) 3)))) (is (= [0 6 5] (take 3 (hiphip/amin-indices (into-arr [-2 3 4 2 3 1 -1]) 3))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Simple tests for typehinted hiphip.array fns , including : let and : range (deftest simple-binding-macro-test (is (= [1 2 3] (map long (hiphip/amake [i 3] (inc i))))) (is (= 10 (hiphip/areduce [x (into-arr [1 2 3 4])] r 0 (+ r (long x))))) (is (= 26 (hiphip/areduce [:range [1 3] x (into-arr [1 2 3 4]) :let [y (* x 2)]] r 0 (+ r (long (* x y)))))) (let [res (atom [])] (hiphip/doarr [:range [1 3] [i x] (into-arr [1 2 3 4]) :let [y (+ i x)]] (swap! res conj [i (long x) (long y)])) (is (= [[1 2 3] [2 3 5]] @res))) (is (= [3 5] (map long (hiphip/amap [:range [1 3] [i x] (into-arr [1 2 3 4]) :let [y (+ i x)]] y)))) (let [a (into-arr [1 2 3 4])] (is (= a (hiphip/afill! [:range [1 3] x a x a :let [y (* x x)]] (+ y 2)))) (is (= [1 6 11 4] (map long a))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Benchmark/equality tests (defn- select-slowness "If slowness is given as a type map, pull out the correct value" [slowness-and-exprs] (->> (partition 2 slowness-and-exprs) (mapcat (fn [[slowness expr]] [(if (map? slowness) (get slowness (keyword (name +type+))) slowness) expr])))) (defmacro defbenchmarktype "Wrapper around defbenchmark for fns that take two arrays of the primitive type being tested, and allows expressing type-dependent slowness like: {:double slowness :float slowness :int slowness :long slowness}" [name expr & slowness-and-exprs] (assert (even? (count slowness-and-exprs))) `(defbenchmark ~name [~(impl/array-cast +type+ 'xs) ~(impl/array-cast +type+ 'ys)] ~expr ~@(select-slowness slowness-and-exprs))) (defbenchmarktype aclone (Baseline/aclone xs) 1.1 (hiphip/aclone xs)) (defbenchmarktype alength (Baseline/alength xs) 1.1 (hiphip/alength xs) ;; failure cases for testing the tests ;; 1.2 (inc (hiphip/alength xs)) 1.2 ( do ( hiphip / aset xs 0 100 ) ( hiphip / alength xs ) ) ;; 0.3 (do (hiphip/aset ys 0 101) (hiphip/alength xs)) ) (defbenchmarktype aget (Baseline/aget xs 0) 1.1 (hiphip/aget xs 0)) (defbenchmarktype aset (Baseline/aset xs 0 42) 1.1 (hiphip/aset xs 0 42)) (set! *unchecked-math* true) (defbenchmarktype ainc (Baseline/ainc xs 0 1) 1.1 (hiphip/ainc xs 0 1)) (defbenchmarktype amake (Baseline/acopy_inc (hiphip/alength xs) xs) {:double 1.1 :float 1.7 :long 1.9 :int 1.3} (hiphip/amake [i (hiphip/alength xs)] (inc (hiphip/aget xs i)))) Arrays should be correctly cast even if the RHS is somewhat complex . (defbenchmarktype array-cast (let [m {:xs {:data [xs]}}] (let [xs-new (-> m (get-in [:xs :data]) first)] (hiphip/afill! [x xs-new] (+ x 2)))) 1.1 (let [m {:xs {:data [xs]}}] (hiphip/afill! [x (-> m (get-in [:xs :data]) first)] (+ x 2)))) ;; helpers for areduce-and-dot-product (defmacro hinted-hiphip-areduce [bind ret-sym init final] `(hiphip/areduce ~bind ~ret-sym ~(impl/value-cast +type+ init) ~final)) (defmacro hinted-clojure-areduce [arr-sym idx-sym ret-sym init final] `(areduce ~arr-sym ~idx-sym ~ret-sym ~(impl/value-cast +type+ init) ~final)) (set! *unchecked-math* false) (defbenchmarktype areduce-and-dot-product-no-unchecked (Baseline/dot_product xs ys) {:double 1.1 :float 1.7 :long 30.0 :int 30.0} (hinted-hiphip-areduce [x xs y ys] ret 0 (+ ret (* x y))) {:double 1.1 :float 1.7 :long 30.0 :int 30.0} (hiphip/dot-product xs ys) nil (hinted-clojure-areduce xs i ret 0 (+ ret (* (aget xs i) (aget ys i)))) nil (reduce + (map * xs ys))) (set! *unchecked-math* true) (defbenchmarktype areduce-and-dot-product (Baseline/dot_product xs ys) {:double 1.4 :float 1.8 :long 2.6 :int 2.9} (hinted-hiphip-areduce [x xs y ys] ret 0 (+ ret (* x y))) {:double 1.4 :float 1.8 :long 2.6 :int 2.9} (hiphip/dot-product xs ys) nil (hinted-clojure-areduce xs i ret 0 (+ ret (* (aget xs i) (aget ys i)))) nil (reduce + (map * xs ys))) (defbenchmarktype doarr-and-afill! (Baseline/multiply_in_place_pointwise xs ys) {:double 1.4 :float 3.3 :long 1.6 :int 2.4} (do (hiphip/doarr [[i x] xs y ys] (hiphip/aset xs i (* x y))) xs) {:double 1.4 :float 3.3 :long 1.6 :int 2.4} (hiphip/afill! [x xs y ys] (* x y))) (defbenchmarktype doarr-and-afill-range! (Baseline/multiply_end_in_place_pointwise xs ys) {:double 1.5 :float 3.3 :long 1.6 :int 2.4} (do (hiphip/doarr [:range [(quot (alength xs) 2) (alength xs)] [i x] xs y ys] (hiphip/aset xs i (* x y))) xs) {:double 1.5 :float 3.3 :long 1.6 :int 2.4} (hiphip/afill! [:range [(quot (alength xs) 2) (alength xs)] x xs y ys] (* x y))) ;; slightly faster for double with unchecked off (defbenchmarktype afill-with-index! (Baseline/multiply_in_place_by_idx xs) 2.8 (hiphip/afill! [[i x] xs] (* x i))) (defbenchmarktype amap (Baseline/amap_inc xs) {:double 1.1 :float 1.7 :long 1.1 :int 1.4} (hiphip/amap [x xs] (inc x)) nil (amap xs i ret (aset ret i (inc (aget xs i))))) (defbenchmarktype amap-range (Baseline/amap_end_inc xs) {:double 1.5 :float 2.2 :long 1.3 :int 1.6} (hiphip/amap [:range [(quot (alength xs) 2) (alength xs)] x xs] (inc x))) (defbenchmarktype amap-with-index (Baseline/amap_plus_idx xs) {:double 1.1 :float 1.5 :long 1.1 :int 1.3} (hiphip/amap [[i x] xs] (+ i x))) (defbenchmarktype asum (Baseline/asum xs) {:double 1.1 :float 1.1 :long 3.3 :int 2.4} (hiphip/asum xs) nil (hinted-clojure-areduce xs i ret 0 (+ ret (aget xs i))) nil (reduce + xs)) (defbenchmarktype asum-range (Baseline/asum_end xs) {:double 1.1 :float 1.1 :long 7.0 :int 2.6} (hiphip/asum [:range [(quot (alength xs) 2) (alength xs)] x xs] x)) (set! *unchecked-math* false) (defbenchmarktype asum-op-no-unchecked (Baseline/asum_square xs) {:double 1.1 :float 1.6 :long 25.0 :int 20.0} (hiphip/asum [x xs] (* x x))) (set! *unchecked-math* true) (defbenchmarktype asum-op (Baseline/asum_square xs) {:double 1.1 :float 2.2 :long 2.3 :int 1.7} (hiphip/asum [x xs] (* x x))) (defbenchmarktype aproduct (Baseline/aproduct xs) 1.1 (hiphip/aproduct xs)) (defbenchmarktype amean (Baseline/amean xs) {:double 1.1 :float 1.1 :long 3.3 :int 3.3} (hiphip/amean xs)) (defmacro amax-clj "Maximum over an array." [xs] (let [rsym (gensym "r") xsym (gensym "x")] `(let [xs# ~xs] (hiphip/areduce [~xsym xs#] ~rsym (aget xs# 0) ~(impl/value-cast +type+ `(if (> ~rsym ~xsym) ~rsym ~xsym)))))) ;; these implicitly test max/min-index (defbenchmarktype amax (Baseline/amax xs) 1.1 (hiphip/amax xs) nil (amax-clj xs)) (defbenchmarktype amin (Baseline/amin xs) 1.1 (hiphip/amin xs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Top-level benchmark/equality test runners (defn gen-array [size phase] (hiphip/amake [i size] (nth [-2 3 0 -1 0 1 -1 2 3] (mod (+ i phase) 9)))) (let [me *ns*] (defn all-tests [size] (doseq [[n t] (ns-interns me) :when (.startsWith ^String (name n) "test-")] (t (gen-array size 0) (gen-array size 1)))) (defn all-benches [size] (doseq [[n t] (ns-interns me) :when (.startsWith ^String (name n) "bench-")] (t (gen-array size 0) (gen-array size 1))))) (deftest hiphip-type-test (all-tests 10000)) (deftest ^:bench hiphip-type-bench (all-benches 10000)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Test sorting ops, with no equality and differnet data (set! *unchecked-math* false) (defmacro deftestfasttype "Wrapper around deftestfast -- like defbenchmarktype, but does not declare a test." [name expr & slowness-and-exprs] (assert (even? (count slowness-and-exprs))) `(deftestfast ~name [~(impl/array-cast +type+ 'xs) ~(impl/array-cast +type+ 'ys)] ~expr ~@(select-slowness slowness-and-exprs))) (deftestfasttype sort-ops (java.util.Arrays/sort xs) 0.1 (hiphip/aselect! xs (quot (alength xs) 2)) 0.2 (hiphip/aselect! xs (quot (alength xs) 10)) 0.2 (hiphip/aselect! xs 1) 0.03 (hiphip/amax xs) 0.3 (hiphip/asort-max! xs (quot (alength xs) 10)) 6.0 (hiphip/asort-indices! xs) 1.0 (hiphip/amax-indices xs (quot (alength xs) 10)) 0.6 (hiphip/amax-indices xs 5)) (deftest ^:bench sort-ops-bench (let [r (java.util.Random. 1) xs (hiphip/amake [_ 10000] (.nextInt r 1000000))] (sort-ops xs xs))) (set! *warn-on-reflection* false)
null
https://raw.githubusercontent.com/plumatic/hiphip/d839359cc1e4c453cd6ffe0b5857de550b3d7489/test/hiphip/type_impl_test.clj
clojure
Benchmark code shared between array types. Assumes the appropriate hiphip array type ns has been aliased as 'hiphip', Tests for selection and partitioning Benchmark/equality tests failure cases for testing the tests 1.2 (inc (hiphip/alength xs)) 0.3 (do (hiphip/aset ys 0 101) (hiphip/alength xs)) helpers for areduce-and-dot-product slightly faster for double with unchecked off these implicitly test max/min-index Top-level benchmark/equality test runners Test sorting ops, with no equality and differnet data
and the appropriate Java baseline class has been imported as ' Baseline ' (use 'clojure.test 'hiphip.test-utils) (require '[hiphip.impl.core :as impl]) (def +type+ hiphip/+type+) (set! *warn-on-reflection* true) (defn partitioned? [s pivot] (let [[smaller more] ((juxt take-while drop-while) #(< % pivot) s) [eq more] ((juxt take-while drop-while) #(= % pivot) more)] (every? #(> % pivot) more))) (defn selected? [s k] (let [[small big] (split-at k s)] (is (<= (apply max small) (apply min big))))) (defn ascending? [s] (= (seq s) (sort s))) (defn max-sorted? [s k] (let [[front back] (split-at (- (count s) k) s)] (and (every? #(<= % (first back)) front) (ascending? back)))) (defn min-sorted? [s k] (let [[front back] (split-at k s)] (and (every? #(>= % (last front)) back) (ascending? front)))) (defn de-index [arr indices] (is (= (count arr) (count indices))) (let [v (vec arr)] (map #(nth v %) indices))) (defn into-arr [s] (let [v (vec s)] (hiphip/amake [i (count v)] (nth v i)))) (defn direct-partition-ops-tests [s k] (let [a (into-arr s) pivot (nth a k)] (is (= a (hiphip/apartition! a pivot))) (is (partitioned? a pivot))) (let [a (into-arr s)] (is (= a (hiphip/aselect! a k))) (is (selected? a k))) (let [a (into-arr s)] (is (= a (hiphip/asort! a))) (is (ascending? a))) (let [a (into-arr s)] (is (= a (hiphip/asort-max! a k))) (is (max-sorted? a k))) (let [a (into-arr s)] (is (= a (hiphip/asort-min! a k))) (is (min-sorted? a k)))) (defn index-partition-ops-tests [s k] (let [a (into-arr s) pivot (nth a k)] (is (= (map long a) s)) (let [indices (hiphip.IndexArrays/make 0 (count s))] (is (partitioned? (de-index a (hiphip/apartition-indices! indices a pivot)) pivot))) (let [indices (hiphip.IndexArrays/make 0 (count s))] (is (selected? (de-index a (hiphip/aselect-indices! indices a k)) k))) (is (ascending? (de-index a (hiphip/asort-indices! a)))) (is (max-sorted? (de-index a (hiphip/amax-indices a k)) k)) (is (min-sorted? (de-index a (hiphip/amin-indices a k)) k)))) (deftest big-partition-and-sort-ops-test (let [n 1000 r (java.util.Random. 1)] (doseq [[test-name t] {"direct" direct-partition-ops-tests "indirect" index-partition-ops-tests} [seq-name s] {"zeros" (repeat n 0) "asc" (range n) "desc" (reverse (range n)) "rand" (repeatedly n #(.nextInt r 10000)) "rand-repeated" (repeatedly n #(.nextInt r 100))} k [1 10 50 100 500 900 950 990 999]] (testing (format "%s opts on %s with k=%s" test-name n k) (t s k))))) (deftest simple-partition-and-sort-opts-test (is (= [1 1 2 2 2 3] (map long (hiphip/apartition! (into-arr [2 1 2 1 2 3]) 2)))) (is (= [1 1 2 2] (map long (hiphip/aselect! (into-arr [1 2 2 1]) 2)))) (is (= [1 2 3 4] (map long (hiphip/asort! (into-arr [4 2 3 1]))))) (is (= [3 3 4] (take-last 3 (map long (hiphip/asort-max! (into-arr [-2 3 4 2 3 1 -1]) 3))))) (is (= [-2 -1 1] (take 3 (map long (hiphip/asort-min! (into-arr [-2 3 4 2 3 1 -1]) 3))))) (is (= [1 2 0] (seq (hiphip/apartition-indices! (hiphip.IndexArrays/make 0 3) (into-arr [3 1 2]) 2)))) (is (= [1 0] (seq (hiphip/aselect-indices! (hiphip.IndexArrays/make 0 2) (into-arr [2 1]) 1)))) (is (= [3 1 2 0] (seq (hiphip/asort-indices! (into-arr [4 2 3 1]))))) (is (= [4 2 1] (take-last 3 (hiphip/amax-indices (into-arr [-2 5 4 2 3 1 -1]) 3)))) (is (= [0 6 5] (take 3 (hiphip/amin-indices (into-arr [-2 3 4 2 3 1 -1]) 3))))) Simple tests for typehinted hiphip.array fns , including : let and : range (deftest simple-binding-macro-test (is (= [1 2 3] (map long (hiphip/amake [i 3] (inc i))))) (is (= 10 (hiphip/areduce [x (into-arr [1 2 3 4])] r 0 (+ r (long x))))) (is (= 26 (hiphip/areduce [:range [1 3] x (into-arr [1 2 3 4]) :let [y (* x 2)]] r 0 (+ r (long (* x y)))))) (let [res (atom [])] (hiphip/doarr [:range [1 3] [i x] (into-arr [1 2 3 4]) :let [y (+ i x)]] (swap! res conj [i (long x) (long y)])) (is (= [[1 2 3] [2 3 5]] @res))) (is (= [3 5] (map long (hiphip/amap [:range [1 3] [i x] (into-arr [1 2 3 4]) :let [y (+ i x)]] y)))) (let [a (into-arr [1 2 3 4])] (is (= a (hiphip/afill! [:range [1 3] x a x a :let [y (* x x)]] (+ y 2)))) (is (= [1 6 11 4] (map long a))))) (defn- select-slowness "If slowness is given as a type map, pull out the correct value" [slowness-and-exprs] (->> (partition 2 slowness-and-exprs) (mapcat (fn [[slowness expr]] [(if (map? slowness) (get slowness (keyword (name +type+))) slowness) expr])))) (defmacro defbenchmarktype "Wrapper around defbenchmark for fns that take two arrays of the primitive type being tested, and allows expressing type-dependent slowness like: {:double slowness :float slowness :int slowness :long slowness}" [name expr & slowness-and-exprs] (assert (even? (count slowness-and-exprs))) `(defbenchmark ~name [~(impl/array-cast +type+ 'xs) ~(impl/array-cast +type+ 'ys)] ~expr ~@(select-slowness slowness-and-exprs))) (defbenchmarktype aclone (Baseline/aclone xs) 1.1 (hiphip/aclone xs)) (defbenchmarktype alength (Baseline/alength xs) 1.1 (hiphip/alength xs) 1.2 ( do ( hiphip / aset xs 0 100 ) ( hiphip / alength xs ) ) ) (defbenchmarktype aget (Baseline/aget xs 0) 1.1 (hiphip/aget xs 0)) (defbenchmarktype aset (Baseline/aset xs 0 42) 1.1 (hiphip/aset xs 0 42)) (set! *unchecked-math* true) (defbenchmarktype ainc (Baseline/ainc xs 0 1) 1.1 (hiphip/ainc xs 0 1)) (defbenchmarktype amake (Baseline/acopy_inc (hiphip/alength xs) xs) {:double 1.1 :float 1.7 :long 1.9 :int 1.3} (hiphip/amake [i (hiphip/alength xs)] (inc (hiphip/aget xs i)))) Arrays should be correctly cast even if the RHS is somewhat complex . (defbenchmarktype array-cast (let [m {:xs {:data [xs]}}] (let [xs-new (-> m (get-in [:xs :data]) first)] (hiphip/afill! [x xs-new] (+ x 2)))) 1.1 (let [m {:xs {:data [xs]}}] (hiphip/afill! [x (-> m (get-in [:xs :data]) first)] (+ x 2)))) (defmacro hinted-hiphip-areduce [bind ret-sym init final] `(hiphip/areduce ~bind ~ret-sym ~(impl/value-cast +type+ init) ~final)) (defmacro hinted-clojure-areduce [arr-sym idx-sym ret-sym init final] `(areduce ~arr-sym ~idx-sym ~ret-sym ~(impl/value-cast +type+ init) ~final)) (set! *unchecked-math* false) (defbenchmarktype areduce-and-dot-product-no-unchecked (Baseline/dot_product xs ys) {:double 1.1 :float 1.7 :long 30.0 :int 30.0} (hinted-hiphip-areduce [x xs y ys] ret 0 (+ ret (* x y))) {:double 1.1 :float 1.7 :long 30.0 :int 30.0} (hiphip/dot-product xs ys) nil (hinted-clojure-areduce xs i ret 0 (+ ret (* (aget xs i) (aget ys i)))) nil (reduce + (map * xs ys))) (set! *unchecked-math* true) (defbenchmarktype areduce-and-dot-product (Baseline/dot_product xs ys) {:double 1.4 :float 1.8 :long 2.6 :int 2.9} (hinted-hiphip-areduce [x xs y ys] ret 0 (+ ret (* x y))) {:double 1.4 :float 1.8 :long 2.6 :int 2.9} (hiphip/dot-product xs ys) nil (hinted-clojure-areduce xs i ret 0 (+ ret (* (aget xs i) (aget ys i)))) nil (reduce + (map * xs ys))) (defbenchmarktype doarr-and-afill! (Baseline/multiply_in_place_pointwise xs ys) {:double 1.4 :float 3.3 :long 1.6 :int 2.4} (do (hiphip/doarr [[i x] xs y ys] (hiphip/aset xs i (* x y))) xs) {:double 1.4 :float 3.3 :long 1.6 :int 2.4} (hiphip/afill! [x xs y ys] (* x y))) (defbenchmarktype doarr-and-afill-range! (Baseline/multiply_end_in_place_pointwise xs ys) {:double 1.5 :float 3.3 :long 1.6 :int 2.4} (do (hiphip/doarr [:range [(quot (alength xs) 2) (alength xs)] [i x] xs y ys] (hiphip/aset xs i (* x y))) xs) {:double 1.5 :float 3.3 :long 1.6 :int 2.4} (hiphip/afill! [:range [(quot (alength xs) 2) (alength xs)] x xs y ys] (* x y))) (defbenchmarktype afill-with-index! (Baseline/multiply_in_place_by_idx xs) 2.8 (hiphip/afill! [[i x] xs] (* x i))) (defbenchmarktype amap (Baseline/amap_inc xs) {:double 1.1 :float 1.7 :long 1.1 :int 1.4} (hiphip/amap [x xs] (inc x)) nil (amap xs i ret (aset ret i (inc (aget xs i))))) (defbenchmarktype amap-range (Baseline/amap_end_inc xs) {:double 1.5 :float 2.2 :long 1.3 :int 1.6} (hiphip/amap [:range [(quot (alength xs) 2) (alength xs)] x xs] (inc x))) (defbenchmarktype amap-with-index (Baseline/amap_plus_idx xs) {:double 1.1 :float 1.5 :long 1.1 :int 1.3} (hiphip/amap [[i x] xs] (+ i x))) (defbenchmarktype asum (Baseline/asum xs) {:double 1.1 :float 1.1 :long 3.3 :int 2.4} (hiphip/asum xs) nil (hinted-clojure-areduce xs i ret 0 (+ ret (aget xs i))) nil (reduce + xs)) (defbenchmarktype asum-range (Baseline/asum_end xs) {:double 1.1 :float 1.1 :long 7.0 :int 2.6} (hiphip/asum [:range [(quot (alength xs) 2) (alength xs)] x xs] x)) (set! *unchecked-math* false) (defbenchmarktype asum-op-no-unchecked (Baseline/asum_square xs) {:double 1.1 :float 1.6 :long 25.0 :int 20.0} (hiphip/asum [x xs] (* x x))) (set! *unchecked-math* true) (defbenchmarktype asum-op (Baseline/asum_square xs) {:double 1.1 :float 2.2 :long 2.3 :int 1.7} (hiphip/asum [x xs] (* x x))) (defbenchmarktype aproduct (Baseline/aproduct xs) 1.1 (hiphip/aproduct xs)) (defbenchmarktype amean (Baseline/amean xs) {:double 1.1 :float 1.1 :long 3.3 :int 3.3} (hiphip/amean xs)) (defmacro amax-clj "Maximum over an array." [xs] (let [rsym (gensym "r") xsym (gensym "x")] `(let [xs# ~xs] (hiphip/areduce [~xsym xs#] ~rsym (aget xs# 0) ~(impl/value-cast +type+ `(if (> ~rsym ~xsym) ~rsym ~xsym)))))) (defbenchmarktype amax (Baseline/amax xs) 1.1 (hiphip/amax xs) nil (amax-clj xs)) (defbenchmarktype amin (Baseline/amin xs) 1.1 (hiphip/amin xs)) (defn gen-array [size phase] (hiphip/amake [i size] (nth [-2 3 0 -1 0 1 -1 2 3] (mod (+ i phase) 9)))) (let [me *ns*] (defn all-tests [size] (doseq [[n t] (ns-interns me) :when (.startsWith ^String (name n) "test-")] (t (gen-array size 0) (gen-array size 1)))) (defn all-benches [size] (doseq [[n t] (ns-interns me) :when (.startsWith ^String (name n) "bench-")] (t (gen-array size 0) (gen-array size 1))))) (deftest hiphip-type-test (all-tests 10000)) (deftest ^:bench hiphip-type-bench (all-benches 10000)) (set! *unchecked-math* false) (defmacro deftestfasttype "Wrapper around deftestfast -- like defbenchmarktype, but does not declare a test." [name expr & slowness-and-exprs] (assert (even? (count slowness-and-exprs))) `(deftestfast ~name [~(impl/array-cast +type+ 'xs) ~(impl/array-cast +type+ 'ys)] ~expr ~@(select-slowness slowness-and-exprs))) (deftestfasttype sort-ops (java.util.Arrays/sort xs) 0.1 (hiphip/aselect! xs (quot (alength xs) 2)) 0.2 (hiphip/aselect! xs (quot (alength xs) 10)) 0.2 (hiphip/aselect! xs 1) 0.03 (hiphip/amax xs) 0.3 (hiphip/asort-max! xs (quot (alength xs) 10)) 6.0 (hiphip/asort-indices! xs) 1.0 (hiphip/amax-indices xs (quot (alength xs) 10)) 0.6 (hiphip/amax-indices xs 5)) (deftest ^:bench sort-ops-bench (let [r (java.util.Random. 1) xs (hiphip/amake [_ 10000] (.nextInt r 1000000))] (sort-ops xs xs))) (set! *warn-on-reflection* false)
774fc87535f56e41b3f3ea975f8e6025479380cb94626558d3e8cf9d551e73e5
cj1128/sicp-review
3.20.scm
Exercise 3.20 ;; Draw environment diagrams to illustrate ;; the evaluation of the sequence of expressions ;; Just ignore
null
https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-3/3.3/3.20.scm
scheme
Draw environment diagrams to illustrate the evaluation of the sequence of expressions Just ignore
Exercise 3.20
9085dcaaee206e9da1c1d973ba69ac81e74787aad57bd712e73a1ffee1d47cd0
ssor/erlangDemos
gen_web_server.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2010 , %%% @doc The main interface for the gen_web_server application %%% @end Created : 10 Feb 2010 by < > %%%------------------------------------------------------------------- -module(gen_web_server). %% API -export([start_link/4, start_link/3, http_reply/1, http_reply/3]). -export([behaviour_info/1]). -include("eunit.hrl"). behaviour_info(callbacks) -> [{init,1}, {head, 3}, {get, 3}, {delete, 3}, {options, 4}, {post, 4}, {put, 4}, {trace, 4}, {other_methods, 4}]; behaviour_info(_Other) -> undefined. %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- @doc Start a new gen_web_server behaviour container . @spec ( Callback , IP , Port , UserArgs ) - > { ok , Pid } %% @end %%-------------------------------------------------------------------- start_link(Callback, IP, Port, UserArgs) -> gws_connection_sup:start_link(Callback, IP, Port, UserArgs). @spec start_link(Callback , Port , UserArgs ) - > { ok , Pid } | ignore | { error , Error } @equiv start_link(Callback , DefaultIP , Port , UserArgs ) start_link(Callback, Port, UserArgs) -> start_link(Callback, default_ip, Port, UserArgs). %%-------------------------------------------------------------------- %% @doc helper function for creating a very minimally specified %% http message %% @spec (Code, Headers, Body) -> ok %% @end %%-------------------------------------------------------------------- http_reply(Code, Headers, Body) when is_list(Body) -> http_reply(Code, Headers, list_to_binary(Body)); http_reply(Code, Headers, Body) -> list_to_binary(["HTTP/1.1 ", code_to_code_and_string(Code), "\r\n", format_headers(Headers), "Content-Length: ", integer_to_list(size(Body)), "\r\n\r\n", Body]). %% @spec (Code) -> ok @equiv http_reply(Code , [ { " Content - Type " , " text / html " } ] , " " ) http_reply(Code) -> http_reply(Code, [{"Content-Type", "text/html"}], <<>>). format_headers([{Header, Value}|T]) -> [tos(Header), ": ", Value, "\r\n"|format_headers(T)]; format_headers([]) -> []. tos(Val) when is_atom(Val) -> atom_to_list(Val); tos(Val) -> Val. %%%=================================================================== Internal functions %%%=================================================================== @private %% @doc Given a number of a standard HTTP response code, return %% a binary (string) of the number and name. %% %% Example: ` ` ` code_to_code_and_string(404 ) = > " 404 Not Found " %% ''' %% %% The supported status codes are taken from: %% [""] %% %% @spec (integer()) -> binary() code_to_code_and_string(100) -> "100 Continue"; code_to_code_and_string(101) -> "101 Switching Protocols"; code_to_code_and_string(102) -> "102 Processing"; code_to_code_and_string(200) -> "200 OK"; code_to_code_and_string(201) -> "201 Created"; code_to_code_and_string(202) -> "202 Accepted"; code_to_code_and_string(203) -> "203 Non-Authoritative Information"; code_to_code_and_string(204) -> "204 No Content"; code_to_code_and_string(205) -> "205 Reset Content"; code_to_code_and_string(206) -> "206 Partial Content"; code_to_code_and_string(207) -> "207 Multi-Status"; code_to_code_and_string(300) -> "300 Multiple Choices"; code_to_code_and_string(301) -> "301 Moved Permanently"; code_to_code_and_string(302) -> "302 Found"; code_to_code_and_string(303) -> "303 See Other"; code_to_code_and_string(304) -> "304 Not Modified"; code_to_code_and_string(305) -> "305 Use Proxy"; code_to_code_and_string(307) -> "307 Temporary Redirect"; code_to_code_and_string(400) -> "400 Bad Request"; code_to_code_and_string(401) -> "401 Unauthorized"; code_to_code_and_string(402) -> "402 Payment Required"; code_to_code_and_string(403) -> "403 Forbidden"; code_to_code_and_string(404) -> "404 Not Found"; code_to_code_and_string(405) -> "405 Method Not Allowed"; code_to_code_and_string(406) -> "406 Not Acceptable"; code_to_code_and_string(407) -> "407 Proxy Authentication Required"; code_to_code_and_string(408) -> "408 Request Time-out"; code_to_code_and_string(409) -> "409 Conflict"; code_to_code_and_string(410) -> "410 Gone"; code_to_code_and_string(411) -> "411 Length Required"; code_to_code_and_string(412) -> "412 Precondition Failed"; code_to_code_and_string(413) -> "413 Request Entity Too Large"; code_to_code_and_string(414) -> "414 Request-URI Too Large"; code_to_code_and_string(415) -> "415 Unsupported Media Type"; code_to_code_and_string(416) -> "416 Requested range not satisfiable"; code_to_code_and_string(417) -> "417 Expectation Failed"; code_to_code_and_string(421) -> "421 There are too many connections from your internet address"; code_to_code_and_string(422) -> "422 Unprocessable Entity"; code_to_code_and_string(423) -> "423 Locked"; code_to_code_and_string(424) -> "424 Failed Dependency"; code_to_code_and_string(425) -> "425 Unordered Collection"; code_to_code_and_string(426) -> "426 Upgrade Required"; code_to_code_and_string(449) -> "449 Retry With"; code_to_code_and_string(500) -> "500 Internal Server Error"; code_to_code_and_string(501) -> "501 Not Implemented"; code_to_code_and_string(502) -> "502 Bad Gateway"; code_to_code_and_string(503) -> "503 Service Unavailable"; code_to_code_and_string(504) -> "504 Gateway Time-out"; code_to_code_and_string(505) -> "505 HTTP Version not supported"; code_to_code_and_string(506) -> "506 Variant Also Negotiates"; code_to_code_and_string(507) -> "507 Insufficient Storage"; code_to_code_and_string(509) -> "509 Bandwidth Limit Exceeded"; code_to_code_and_string(510) -> "510 Not Extended"; code_to_code_and_string(Code) -> Code. http_reply_test() -> Reply = <<"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 0\r\n\r\n">>, ?assertMatch(Reply, http_reply(200)), Reply2 = <<"HTTP/1.1 200 OK\r\nheader: value\r\nContent-Length: 8\r\n\r\nall good">>, ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], "all good")), ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], <<"all good">>)), ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], ["all"," good"])).
null
https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/erlware-Erlang-and-OTP-in-Action-Source/chapter_11/old/gen_web_server/src/gen_web_server.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API =================================================================== API =================================================================== -------------------------------------------------------------------- @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc helper function for creating a very minimally specified http message @spec (Code, Headers, Body) -> ok @end -------------------------------------------------------------------- @spec (Code) -> ok =================================================================== =================================================================== @doc Given a number of a standard HTTP response code, return a binary (string) of the number and name. Example: ''' The supported status codes are taken from: [""] @spec (integer()) -> binary()
@author < > ( C ) 2010 , The main interface for the gen_web_server application Created : 10 Feb 2010 by < > -module(gen_web_server). -export([start_link/4, start_link/3, http_reply/1, http_reply/3]). -export([behaviour_info/1]). -include("eunit.hrl"). behaviour_info(callbacks) -> [{init,1}, {head, 3}, {get, 3}, {delete, 3}, {options, 4}, {post, 4}, {put, 4}, {trace, 4}, {other_methods, 4}]; behaviour_info(_Other) -> undefined. @doc Start a new gen_web_server behaviour container . @spec ( Callback , IP , Port , UserArgs ) - > { ok , Pid } start_link(Callback, IP, Port, UserArgs) -> gws_connection_sup:start_link(Callback, IP, Port, UserArgs). @spec start_link(Callback , Port , UserArgs ) - > { ok , Pid } | ignore | { error , Error } @equiv start_link(Callback , DefaultIP , Port , UserArgs ) start_link(Callback, Port, UserArgs) -> start_link(Callback, default_ip, Port, UserArgs). http_reply(Code, Headers, Body) when is_list(Body) -> http_reply(Code, Headers, list_to_binary(Body)); http_reply(Code, Headers, Body) -> list_to_binary(["HTTP/1.1 ", code_to_code_and_string(Code), "\r\n", format_headers(Headers), "Content-Length: ", integer_to_list(size(Body)), "\r\n\r\n", Body]). @equiv http_reply(Code , [ { " Content - Type " , " text / html " } ] , " " ) http_reply(Code) -> http_reply(Code, [{"Content-Type", "text/html"}], <<>>). format_headers([{Header, Value}|T]) -> [tos(Header), ": ", Value, "\r\n"|format_headers(T)]; format_headers([]) -> []. tos(Val) when is_atom(Val) -> atom_to_list(Val); tos(Val) -> Val. Internal functions @private ` ` ` code_to_code_and_string(404 ) = > " 404 Not Found " code_to_code_and_string(100) -> "100 Continue"; code_to_code_and_string(101) -> "101 Switching Protocols"; code_to_code_and_string(102) -> "102 Processing"; code_to_code_and_string(200) -> "200 OK"; code_to_code_and_string(201) -> "201 Created"; code_to_code_and_string(202) -> "202 Accepted"; code_to_code_and_string(203) -> "203 Non-Authoritative Information"; code_to_code_and_string(204) -> "204 No Content"; code_to_code_and_string(205) -> "205 Reset Content"; code_to_code_and_string(206) -> "206 Partial Content"; code_to_code_and_string(207) -> "207 Multi-Status"; code_to_code_and_string(300) -> "300 Multiple Choices"; code_to_code_and_string(301) -> "301 Moved Permanently"; code_to_code_and_string(302) -> "302 Found"; code_to_code_and_string(303) -> "303 See Other"; code_to_code_and_string(304) -> "304 Not Modified"; code_to_code_and_string(305) -> "305 Use Proxy"; code_to_code_and_string(307) -> "307 Temporary Redirect"; code_to_code_and_string(400) -> "400 Bad Request"; code_to_code_and_string(401) -> "401 Unauthorized"; code_to_code_and_string(402) -> "402 Payment Required"; code_to_code_and_string(403) -> "403 Forbidden"; code_to_code_and_string(404) -> "404 Not Found"; code_to_code_and_string(405) -> "405 Method Not Allowed"; code_to_code_and_string(406) -> "406 Not Acceptable"; code_to_code_and_string(407) -> "407 Proxy Authentication Required"; code_to_code_and_string(408) -> "408 Request Time-out"; code_to_code_and_string(409) -> "409 Conflict"; code_to_code_and_string(410) -> "410 Gone"; code_to_code_and_string(411) -> "411 Length Required"; code_to_code_and_string(412) -> "412 Precondition Failed"; code_to_code_and_string(413) -> "413 Request Entity Too Large"; code_to_code_and_string(414) -> "414 Request-URI Too Large"; code_to_code_and_string(415) -> "415 Unsupported Media Type"; code_to_code_and_string(416) -> "416 Requested range not satisfiable"; code_to_code_and_string(417) -> "417 Expectation Failed"; code_to_code_and_string(421) -> "421 There are too many connections from your internet address"; code_to_code_and_string(422) -> "422 Unprocessable Entity"; code_to_code_and_string(423) -> "423 Locked"; code_to_code_and_string(424) -> "424 Failed Dependency"; code_to_code_and_string(425) -> "425 Unordered Collection"; code_to_code_and_string(426) -> "426 Upgrade Required"; code_to_code_and_string(449) -> "449 Retry With"; code_to_code_and_string(500) -> "500 Internal Server Error"; code_to_code_and_string(501) -> "501 Not Implemented"; code_to_code_and_string(502) -> "502 Bad Gateway"; code_to_code_and_string(503) -> "503 Service Unavailable"; code_to_code_and_string(504) -> "504 Gateway Time-out"; code_to_code_and_string(505) -> "505 HTTP Version not supported"; code_to_code_and_string(506) -> "506 Variant Also Negotiates"; code_to_code_and_string(507) -> "507 Insufficient Storage"; code_to_code_and_string(509) -> "509 Bandwidth Limit Exceeded"; code_to_code_and_string(510) -> "510 Not Extended"; code_to_code_and_string(Code) -> Code. http_reply_test() -> Reply = <<"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 0\r\n\r\n">>, ?assertMatch(Reply, http_reply(200)), Reply2 = <<"HTTP/1.1 200 OK\r\nheader: value\r\nContent-Length: 8\r\n\r\nall good">>, ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], "all good")), ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], <<"all good">>)), ?assertMatch(Reply2, http_reply(200, [{"header", "value"}], ["all"," good"])).
41665ff24671c613b2206f6f65ff6c24365199c13e31b19308f850e1994217fb
eeng/mercurius
in_memory_trade_repository.clj
(ns mercurius.trading.adapters.repositories.in-memory-trade-repository (:require [mercurius.trading.domain.repositories.trade-repository :refer [TradeRepository add-trade get-trades]] [mercurius.trading.domain.entities.ticker :refer [available-tickers]])) (defrecord InMemoryTradeRepository [db] TradeRepository (add-trade [_ {:keys [ticker] :as trade}] (swap! db update ticker conj (dissoc trade :bid :ask))) (get-trades [_ ticker] (get @db ticker []))) (defn new-in-memory-trade-repo [] (InMemoryTradeRepository. (atom (zipmap available-tickers (repeat (count available-tickers) '()))))) (comment (def repo (new-in-memory-trade-repo)) (add-trade repo {:ticker "BTCUSD" :amount 10 :price 200}) (add-trade repo {:ticker "BTCUSD" :amount 11 :price 200}) (get-trades repo "BTCUSD"))
null
https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/src/mercurius/trading/adapters/repositories/in_memory_trade_repository.clj
clojure
(ns mercurius.trading.adapters.repositories.in-memory-trade-repository (:require [mercurius.trading.domain.repositories.trade-repository :refer [TradeRepository add-trade get-trades]] [mercurius.trading.domain.entities.ticker :refer [available-tickers]])) (defrecord InMemoryTradeRepository [db] TradeRepository (add-trade [_ {:keys [ticker] :as trade}] (swap! db update ticker conj (dissoc trade :bid :ask))) (get-trades [_ ticker] (get @db ticker []))) (defn new-in-memory-trade-repo [] (InMemoryTradeRepository. (atom (zipmap available-tickers (repeat (count available-tickers) '()))))) (comment (def repo (new-in-memory-trade-repo)) (add-trade repo {:ticker "BTCUSD" :amount 10 :price 200}) (add-trade repo {:ticker "BTCUSD" :amount 11 :price 200}) (get-trades repo "BTCUSD"))
f9c9b3bddf906f86f1d028c6bf100fc350f0ece0e41863a17a48d340d173c691
Plutonomicon/plutarch-core
Haskell.hs
module Plutarch.Backends.Haskell (compile) where import Data.Text (Text) class PHaskell newtype Impl compile' :: forall a m. (Applicative m, IsEType (Impl m) a) => Term (Impl m) a -> m Text compile' (Term t) = (,) <$> runImpl t SN <*> pure (typeInfo (Proxy @m) (Proxy @a) SN) compile :: Compile EDSL (SFTerm, SFType) compile t = let _unused = callStack in compile' t
null
https://raw.githubusercontent.com/Plutonomicon/plutarch-core/c3bebe9621b5ca68fc316756c66f6eb72f677372/Plutarch/Backends/Haskell.hs
haskell
module Plutarch.Backends.Haskell (compile) where import Data.Text (Text) class PHaskell newtype Impl compile' :: forall a m. (Applicative m, IsEType (Impl m) a) => Term (Impl m) a -> m Text compile' (Term t) = (,) <$> runImpl t SN <*> pure (typeInfo (Proxy @m) (Proxy @a) SN) compile :: Compile EDSL (SFTerm, SFType) compile t = let _unused = callStack in compile' t
542d7939a990f05b6691a2ca895734ab6f733592524d19a0f2e23095a6b8650c
pbv/codex
Types.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} Needed to derive Generic # LANGUAGE GeneralizedNewtypeDeriving # {- Types for various entities -} module Codex.Types ( -- * types UserLogin(..), Password(..), SubmitId(..), Language(..), Code(..), Page, -- re-exports Text ) where import Data.Typeable import Data.Hashable import Data.String (IsString(..)) import Data.Text (Text) import qualified Data.Text as T import Data.Int(Int64) import Data.ByteString.UTF8 (ByteString) import Database.SQLite.Simple.ToField import Database.SQLite.Simple.FromField import Database.SQLite.Simple.FromRow import Data.Configurator.Types import Data.Configurator () import Web.Routes.PathInfo import Text.Pandoc.Definition -- hiding (Code) -- | a user login; should uniquely identify the user newtype UserLogin = UserLogin {fromLogin :: Text} deriving (Eq, Ord, Hashable) newtype Password = Password {fromPassword :: ByteString} deriving (Eq,Ord) -- | submission identifier newtype SubmitId = SubmitId {fromSubmitId :: Int64} deriving (Eq, Ord) -- | conversion to strings instance Show UserLogin where showsPrec prec (UserLogin uid) = showsPrec prec uid instance Show SubmitId where showsPrec prec (SubmitId sid) = showsPrec prec sid instance Read SubmitId where readsPrec p s = [(SubmitId n, s' ) | (n,s')<-readsPrec p s] instance PathInfo SubmitId where toPathSegments (SubmitId sid) = toPathSegments sid fromPathSegments = SubmitId <$> fromPathSegments -- | language identifier newtype Language = Language {fromLanguage :: Text} deriving (Eq, Ord, Hashable, Typeable) -- | program code tagged with language identifier data Code = Code { codeLang :: !Language , codeText :: !Text } deriving (Eq, Typeable) --, Read, Show) instance Show Language where showsPrec prec (Language l) = showsPrec prec l instance Configured Language where convert v = (Language . T.toLower) <$> convert v -- | conversion from strings instance IsString UserLogin where fromString = UserLogin . T.pack instance IsString Language where fromString = Language . T.pack -- | convertion to/from SQL fields instance ToField UserLogin where toField = toField . fromLogin instance FromField UserLogin where fromField f = UserLogin <$> fromField f instance ToField SubmitId where toField = toField . fromSubmitId instance FromField SubmitId where fromField f = SubmitId <$> fromField f instance FromRow UserLogin where fromRow = field instance ToField Language where toField = toField . fromLanguage instance FromField Language where fromField f = Language <$> fromField f instance FromRow Text where fromRow = field -- a Page is a synonym for a Pandoc document -- either an active exercise or a passive document (e.g. an index) -- type Page = Pandoc
null
https://raw.githubusercontent.com/pbv/codex/1a5a81965b12f834b436e2165c07120360aded99/src/Codex/Types.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE DeriveDataTypeable # Types for various entities * types re-exports hiding (Code) | a user login; should uniquely identify the user | submission identifier | conversion to strings | language identifier | program code tagged with language identifier , Read, Show) | conversion from strings | convertion to/from SQL fields either an active exercise or a passive document (e.g. an index)
Needed to derive Generic # LANGUAGE GeneralizedNewtypeDeriving # module Codex.Types UserLogin(..), Password(..), SubmitId(..), Language(..), Code(..), Page, Text ) where import Data.Typeable import Data.Hashable import Data.String (IsString(..)) import Data.Text (Text) import qualified Data.Text as T import Data.Int(Int64) import Data.ByteString.UTF8 (ByteString) import Database.SQLite.Simple.ToField import Database.SQLite.Simple.FromField import Database.SQLite.Simple.FromRow import Data.Configurator.Types import Data.Configurator () import Web.Routes.PathInfo newtype UserLogin = UserLogin {fromLogin :: Text} deriving (Eq, Ord, Hashable) newtype Password = Password {fromPassword :: ByteString} deriving (Eq,Ord) newtype SubmitId = SubmitId {fromSubmitId :: Int64} deriving (Eq, Ord) instance Show UserLogin where showsPrec prec (UserLogin uid) = showsPrec prec uid instance Show SubmitId where showsPrec prec (SubmitId sid) = showsPrec prec sid instance Read SubmitId where readsPrec p s = [(SubmitId n, s' ) | (n,s')<-readsPrec p s] instance PathInfo SubmitId where toPathSegments (SubmitId sid) = toPathSegments sid fromPathSegments = SubmitId <$> fromPathSegments newtype Language = Language {fromLanguage :: Text} deriving (Eq, Ord, Hashable, Typeable) data Code = Code { codeLang :: !Language , codeText :: !Text instance Show Language where showsPrec prec (Language l) = showsPrec prec l instance Configured Language where convert v = (Language . T.toLower) <$> convert v instance IsString UserLogin where fromString = UserLogin . T.pack instance IsString Language where fromString = Language . T.pack instance ToField UserLogin where toField = toField . fromLogin instance FromField UserLogin where fromField f = UserLogin <$> fromField f instance ToField SubmitId where toField = toField . fromSubmitId instance FromField SubmitId where fromField f = SubmitId <$> fromField f instance FromRow UserLogin where fromRow = field instance ToField Language where toField = toField . fromLanguage instance FromField Language where fromField f = Language <$> fromField f instance FromRow Text where fromRow = field a Page is a synonym for a Pandoc document type Page = Pandoc
69fe8ae587f2c07de4c2f217841be62ec3a26d1bf7c48a900b7c0ff3582ea54d
artyom-poptsov/guile-png
bKGD.scm
;;; bKGD.scm -- bKGD chunk. Copyright ( C ) 2022 < > ;; ;; 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. ;; ;; The 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 the program. If not, see </>. ;;; Commentary: ;; The bKGD chunk specifies a default background color to present ;; the image against. Note that viewers are not bound to honor ;; this chunk; a viewer can choose to use a different background. ;; ;; -editor.org/rfc/rfc2083#page-19 ;;; Code: (define-module (png core chunk bKGD) #:use-module (srfi srfi-43) #:use-module (oop goops) #:use-module (rnrs bytevectors) #:use-module (png core common) #:use-module (png core chunk) #:use-module (png core chunk IHDR) #:export (<png-chunk:bKGD> png-chunk:bKGD-color-type png-chunk:bKGD-grayscale png-chunk:bKGD-red png-chunk:bKGD-green png-chunk:bKGD-blue png-chunk:bKGD-palette-index png-chunk-decode-bKGD)) (define-class <png-chunk:bKGD> (<png-chunk>) ;; <number> (color-type #:init-keyword #:color-type #:init-value 0 #:getter png-chunk:bKGD-color-type) ;; <number> (grayscale #:init-keyword #:greyscale #:init-value 0 #:getter png-chunk:bKGD-grayscale) ;; <number> (red #:init-keyword #:red #:init-value 0 #:getter png-chunk:bKGD-red) ;; <number> (green #:init-keyword #:green #:init-value 0 #:getter png-chunk:bKGD-green) ;; <number> (blue #:init-keyword #:blue #:init-value 0 #:getter png-chunk:bKGD-blue) Palette index of the color to be used as background . ;; ;; <number> (palette-index #:init-keyword #:palette-index #:init-value 0 #:getter png-chunk:bKGD-palette-index)) (define-method (initialize (chunk <png-chunk:bKGD>) initargs) (next-method) (slot-set! chunk 'type 'bKGD)) (define-method (%display (chunk <png-chunk:bKGD>) (port <port>)) (let ((type (png-chunk-type-info chunk))) (format port "#<png-chunk:bKGD color type: ~a ~a>" (png-chunk:bKGD-color-type chunk) (object-address/hex-string chunk)))) (define-method (display (chunk <png-chunk:bKGD>) (port <port>)) (%display chunk port)) (define-method (write (chunk <png-chunk:bKGD>) (port <port>)) (%display chunk port)) (define-method (png-chunk-decode-bKGD (chunk <png-chunk>) (ihdr <png-chunk>)) "Convert a PNG chunk data to a bKGD chunk instance." (let ((length (png-chunk-length chunk)) (type (png-chunk-type chunk)) (data (png-chunk-data chunk)) (crc (png-chunk-crc chunk)) (color-type (png-chunk:IHDR-color-type ihdr))) (case color-type ((0 4) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:greyscale (vector->int16 data))) ((2 6) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:red (vector->int16 (bytevector-copy/part data 0 2)) #:green (vector->int16 (bytevector-copy/part data 2 2)) #:blue (vector->int16 (bytevector-copy/part data 4 2)))) ((3) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:palette-index (vector-ref data 0)))))) (define-method (png-chunk-encode (chunk <png-chunk:bKGD>)) (let ((color-type (png-chunk:bKGD-color-type chunk))) (case color-type ((0 4) (let* ((grayscale-value (png-chunk:bKGD-grayscale chunk)) (data (int16->bytevector grayscale-value)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) ((2 6) (let* ((r (png-chunk:bKGD-red chunk)) (g (png-chunk:bKGD-green chunk)) (b (png-chunk:bKGD-blue chunk)) (data (make-bytevector 6 0)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (bytevector-copy! (int16->bytevector r) 0 data 0 2) (bytevector-copy! (int16->bytevector g) 0 data 2 2) (bytevector-copy! (int16->bytevector b) 0 data 4 2) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) ((3) (let* ((palette-index (png-chunk:bKGD-palette-index chunk)) (data (make-bytevector 1 0)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (bytevector-u8-set! data 0 palette-index) (png-chunk-crc-update! encoded-chunk) encoded-chunk))))) (define-method (png-chunk-clone (chunk <png-chunk:bKGD>)) (make <png-chunk:bKGD> #:length (png-chunk-length chunk) #:data (png-chunk-data chunk) #:crc (png-chunk-crc chunk) #:color-type (png-chunk:bKGD-color-type chunk) #:greyscale (png-chunk:bKGD-grayscale chunk) #:red (png-chunk:bKGD-red chunk) #:green (png-chunk:bKGD-green chunk) #:blue (png-chunk:bKGD-blue chunk) #:palette-index (png-chunk:bKGD-palette-index chunk))) ;;; bKGD.scm ends here.
null
https://raw.githubusercontent.com/artyom-poptsov/guile-png/3b570ee73507a3785cb122c77a5c9556478edd66/modules/png/core/chunk/bKGD.scm
scheme
bKGD.scm -- bKGD chunk. This program is free software: you can redistribute it and/or modify (at your option) any later version. The 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 the program. If not, see </>. Commentary: The bKGD chunk specifies a default background color to present the image against. Note that viewers are not bound to honor this chunk; a viewer can choose to use a different background. -editor.org/rfc/rfc2083#page-19 Code: <number> <number> <number> <number> <number> <number> bKGD.scm ends here.
Copyright ( C ) 2022 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (define-module (png core chunk bKGD) #:use-module (srfi srfi-43) #:use-module (oop goops) #:use-module (rnrs bytevectors) #:use-module (png core common) #:use-module (png core chunk) #:use-module (png core chunk IHDR) #:export (<png-chunk:bKGD> png-chunk:bKGD-color-type png-chunk:bKGD-grayscale png-chunk:bKGD-red png-chunk:bKGD-green png-chunk:bKGD-blue png-chunk:bKGD-palette-index png-chunk-decode-bKGD)) (define-class <png-chunk:bKGD> (<png-chunk>) (color-type #:init-keyword #:color-type #:init-value 0 #:getter png-chunk:bKGD-color-type) (grayscale #:init-keyword #:greyscale #:init-value 0 #:getter png-chunk:bKGD-grayscale) (red #:init-keyword #:red #:init-value 0 #:getter png-chunk:bKGD-red) (green #:init-keyword #:green #:init-value 0 #:getter png-chunk:bKGD-green) (blue #:init-keyword #:blue #:init-value 0 #:getter png-chunk:bKGD-blue) Palette index of the color to be used as background . (palette-index #:init-keyword #:palette-index #:init-value 0 #:getter png-chunk:bKGD-palette-index)) (define-method (initialize (chunk <png-chunk:bKGD>) initargs) (next-method) (slot-set! chunk 'type 'bKGD)) (define-method (%display (chunk <png-chunk:bKGD>) (port <port>)) (let ((type (png-chunk-type-info chunk))) (format port "#<png-chunk:bKGD color type: ~a ~a>" (png-chunk:bKGD-color-type chunk) (object-address/hex-string chunk)))) (define-method (display (chunk <png-chunk:bKGD>) (port <port>)) (%display chunk port)) (define-method (write (chunk <png-chunk:bKGD>) (port <port>)) (%display chunk port)) (define-method (png-chunk-decode-bKGD (chunk <png-chunk>) (ihdr <png-chunk>)) "Convert a PNG chunk data to a bKGD chunk instance." (let ((length (png-chunk-length chunk)) (type (png-chunk-type chunk)) (data (png-chunk-data chunk)) (crc (png-chunk-crc chunk)) (color-type (png-chunk:IHDR-color-type ihdr))) (case color-type ((0 4) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:greyscale (vector->int16 data))) ((2 6) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:red (vector->int16 (bytevector-copy/part data 0 2)) #:green (vector->int16 (bytevector-copy/part data 2 2)) #:blue (vector->int16 (bytevector-copy/part data 4 2)))) ((3) (make <png-chunk:bKGD> #:length length #:type type #:data data #:crc crc #:color-type color-type #:palette-index (vector-ref data 0)))))) (define-method (png-chunk-encode (chunk <png-chunk:bKGD>)) (let ((color-type (png-chunk:bKGD-color-type chunk))) (case color-type ((0 4) (let* ((grayscale-value (png-chunk:bKGD-grayscale chunk)) (data (int16->bytevector grayscale-value)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) ((2 6) (let* ((r (png-chunk:bKGD-red chunk)) (g (png-chunk:bKGD-green chunk)) (b (png-chunk:bKGD-blue chunk)) (data (make-bytevector 6 0)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (bytevector-copy! (int16->bytevector r) 0 data 0 2) (bytevector-copy! (int16->bytevector g) 0 data 2 2) (bytevector-copy! (int16->bytevector b) 0 data 4 2) (png-chunk-crc-update! encoded-chunk) encoded-chunk)) ((3) (let* ((palette-index (png-chunk:bKGD-palette-index chunk)) (data (make-bytevector 1 0)) (encoded-chunk (make <png-chunk> #:type 'bKGD #:data data #:length (bytevector-length data)))) (bytevector-u8-set! data 0 palette-index) (png-chunk-crc-update! encoded-chunk) encoded-chunk))))) (define-method (png-chunk-clone (chunk <png-chunk:bKGD>)) (make <png-chunk:bKGD> #:length (png-chunk-length chunk) #:data (png-chunk-data chunk) #:crc (png-chunk-crc chunk) #:color-type (png-chunk:bKGD-color-type chunk) #:greyscale (png-chunk:bKGD-grayscale chunk) #:red (png-chunk:bKGD-red chunk) #:green (png-chunk:bKGD-green chunk) #:blue (png-chunk:bKGD-blue chunk) #:palette-index (png-chunk:bKGD-palette-index chunk)))
9bdaa522c72e0b3e620431d337c0329c221d79e6110248e242de8e13e18957db
rpav/ninja-sphere
build.lisp
build-it.lisp --- script for making SBCL binaries for Linux and ;;; MS Windows using only Free Software (GNU/Linux and ;;; Wine) ( C ) Copyright 2011 - 2016 by < > ( C ) Copyright 2011 - 2016 by < > ;; ;; 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. ;;; Note, I modified this of course to build spell-and-dagger. (defpackage :build (:use #:cl) (:export *name* *system* *binary* *startup*)) (in-package :build) #-quicklisp (load #P"~/quicklisp/setup.lisp") (require 'sb-posix) (setf sb-impl::*default-external-format* :utf-8) (defun argument (name) (let* ((args sb-ext:*posix-argv*) (index (position name args :test 'equal)) (value (when (and (numberp index) (< index (length args))) (nth (1+ index) args)))) value)) (defparameter *name* (argument "--name")) (defparameter *binary* (or (argument "--binary") #+win32 (concatenate 'string *name* ".exe") #+linux (concatenate 'string *name* ".bin"))) (defparameter *system* (or (argument "--system") (intern *name* :keyword))) (ql:quickload *system*) (defparameter *startup* (or (argument "--startup") (concatenate 'string (string-upcase *name*) "::" (string-upcase *name*)))) (sb-ext:save-lisp-and-die *binary* :toplevel (lambda () (sdl2:make-this-thread-main (lambda () (sb-ext:disable-debugger) (gk:gk-init) (funcall (read-from-string *startup*)) 0))) :executable t)
null
https://raw.githubusercontent.com/rpav/ninja-sphere/f6708d9ab209a831c7e7df3f12d32ecc4afe0426/build.lisp
lisp
MS Windows using only Free Software (GNU/Linux and Wine) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Note, I modified this of course to build spell-and-dagger.
build-it.lisp --- script for making SBCL binaries for Linux and ( C ) Copyright 2011 - 2016 by < > ( C ) Copyright 2011 - 2016 by < > " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION (defpackage :build (:use #:cl) (:export *name* *system* *binary* *startup*)) (in-package :build) #-quicklisp (load #P"~/quicklisp/setup.lisp") (require 'sb-posix) (setf sb-impl::*default-external-format* :utf-8) (defun argument (name) (let* ((args sb-ext:*posix-argv*) (index (position name args :test 'equal)) (value (when (and (numberp index) (< index (length args))) (nth (1+ index) args)))) value)) (defparameter *name* (argument "--name")) (defparameter *binary* (or (argument "--binary") #+win32 (concatenate 'string *name* ".exe") #+linux (concatenate 'string *name* ".bin"))) (defparameter *system* (or (argument "--system") (intern *name* :keyword))) (ql:quickload *system*) (defparameter *startup* (or (argument "--startup") (concatenate 'string (string-upcase *name*) "::" (string-upcase *name*)))) (sb-ext:save-lisp-and-die *binary* :toplevel (lambda () (sdl2:make-this-thread-main (lambda () (sb-ext:disable-debugger) (gk:gk-init) (funcall (read-from-string *startup*)) 0))) :executable t)
2ad8720a90c70ee17f461ba28114a3f4d60e2c97b0511a2c9129bc5e46748afd
Mercerenies/eulers-melting-pot
smgen.lisp
;; Snowman source generator / "compiler" ;; This "magic" string at the start of the program activates abdf ;; ;; "(@(" (defparameter *letter-operators* '((decr "NdE" 1 1) (incr "NiN" 1 1) (print "sP" 1 0) (to-string "tS" 1 1) (nth "aA" 2 1) (range "nR" 2 1) (equal? "eQ" 2 1) (dup "dU" 1 2) (div "nD" 2 1) (mod "NmO" 2 1) (floor "nF" 1 1) (ceil "nC" 1 1) (not "nO" 1 1) (wrap "wR" 1 1) (pow "nP" 2 1) (mul "nM" 2 1) (add "nA" 2 1) (less-than "nL" 2 1))) (defparameter *vars* '()) (defconstant +reserved-vars+ 2) (defparameter *next-available-var* +reserved-vars+) (defun index-to-var (n) (concatenate 'string (make-string (floor n 2) :initial-element #\=) (if (zerop (mod n 2)) "+" "!"))) (defun translate-var (name) (check-type name symbol) (or (cdr (assoc name *vars*)) (let ((new-var (index-to-var *next-available-var*))) (incf *next-available-var*) (push (cons name new-var) *vars*) new-var))) ;; Duplicates v1 into v2 (leaves v2 as active variable) (defun duplicate-var (v1 v2) (when (numberp v1) (setq v1 (index-to-var v1))) (when (numberp v2) (setq v2 (index-to-var v2))) `("~" ,v1 "#" "dU" "*" ,v2 "*" "~")) (defun translate-input (input) (etypecase input (string `(,@(duplicate-var input 0) "#")) (number (list input)) (list input))) (defun compile-call (name inputs outputs) (let ((fn (or (assoc name *letter-operators*) (error "Unknown function ~S" name)))) (unless (= (length inputs) (third fn)) (error "Expecting ~S inputs to ~S, got ~S" (third fn) (first fn) (length inputs))) (unless (= (length outputs) (fourth fn)) (error "Expecting ~S outputs to ~S, got ~S" (fourth fn) (first fn) (length outputs))) (append (loop for input in inputs append (translate-input input)) (list (second fn)) (loop for output in outputs append `(,output "*"))))) (defun list-to-text (list) (format nil "~{~A~^ ~}" (loop with last-was-number = nil for elem in list if (and (numberp elem) last-was-number) collect "vN" collect elem do (setq last-was-number (numberp elem))))) (defun translate (line) (flet ((translate-arg (value) (translate-literal value :can-be-var t))) (case (first line) ;; (store literal variable) (store (destructuring-bind (literal var) (rest line) (let ((literal (translate-literal literal)) (var (translate-var var))) `(,var ,literal "*")))) ;; (move src dest) (move (destructuring-bind (src dest) (rest line) (let ((src (translate-var src)) (dest (translate-var dest))) `(,src "#" ,dest "*")))) ;; (map var array out-var block) (map (destructuring-bind (var array out-var block) (rest line) (let ((var (translate-var var))) (let ((block (translate-block block :prefix `(,var "*") :suffix `(,var "#"))) (array (translate-literal array :can-be-var t)) (out-var (translate-var out-var))) (append (translate-input array) block `("aM" ,out-var "*")))))) ;; (each var array block) (each (destructuring-bind (var array block) (rest line) (let ((var (translate-var var))) (let ((block (translate-block block :prefix `(,var "*"))) (array (translate-literal array :can-be-var t))) (append (translate-input array) block '("aE")))))) ;; (if cond true-block false-block) (if (destructuring-bind (cond true-block false-block) (rest line) (let ((cond (translate-literal cond :can-be-var t)) (true-block (translate-block true-block)) (false-block (translate-block false-block))) (append true-block false-block (translate-input cond) '("bI"))))) ;; (while cond var body) (while (destructuring-bind (cond var body) (rest line) (let ((var (translate-var var))) (let ((cond (translate-block cond :suffix `(,var "#"))) (body (translate-block body))) (append body cond '("bW")))))) (t (destructuring-bind (name inputs outputs) line (let ((inputs (mapcar #'translate-arg inputs)) (outputs (mapcar #'translate-var outputs))) (compile-call name inputs outputs))))))) (defun translate-literal (literal &key can-be-var) (etypecase literal (number literal) (list (translate-block literal)) (symbol (assert can-be-var) (translate-var literal)))) (defun translate-block (lines &key prefix suffix) (append '(":") prefix (loop for line in lines append (translate line)) suffix '(";"))) (defun translate-lines (lines) (loop for line in lines append (translate line))) (defun full-translate (lines) (list-to-text (append '("(" "@" "(") (translate-lines lines)))) ;; (format t "~A~%" ;; (full-translate ' ( ( store 1 total ) ;; (while ((incr (total) (total)) ( dup ( total ) ( total ) ) ( equal ? ( 10 ) ( c ) ) ;; (not (c) (c))) ;; c ;; ((dup (total) (total total2)) ;; (to-string (total2) (total2)) ;; (print (total2) ())))))) ;; (format t "~A~%" ;; (full-translate ;; '((store 0 total) ( range ( 4 12001 ) ( iter ) ) ;; (each d iter ;; ((dup (d) (d d1)) ;; (dup (d1) (d1 d2)) ( div ( d1 3 ) ( n0 ) ) ;; (div (d2 2) (n1)) ( floor ( n0 ) ( n0 ) ) ;; (ceil (n1) (n1)) ( incr ( n0 ) ( n0 ) ) ( range ( n0 n1 ) ( iter1 ) ) ;; (dup (d) (d aaa)) ( mod ( aaa 100 ) ( bbb ) ) ( equal ? ( bbb 0 ) ( bbb ) ) ( if ;; ((dup (d) (d aaa)) ( to - string ( aaa ) ( ) ) ;; (print (aaa) ()) ( wrap ( 13 ) ( aaa ) ) ;; (print (aaa) ()) ( wrap ( 10 ) ( aaa ) ) ;; (print (aaa) ())) ;; ()) ;; (each n iter1 ;; ;; gcd calculation ;; ((while ((dup (d) (d dzero)) ;; (equal? (dzero 0) (cond)) ;; (not (cond) (cond))) ;; cond ;; ((dup (d) (t0 t1)) ;; (mod (n t0) (d)) ;; (move t1 n))) ;; (equal? (n 1) (eq)) ;; (if eq ;; ((incr (total) (total))) ;; ()))))) ;; (to-string (total) (total)) ;; (print (total) ())))) ;; (format t "~A~%" ;; (full-translate ' ( ( range ( 0 1000001 ) ( phi ) ) ( range ( 2 1000001 ) ( iter ) ) ;; (each index iter ( ( nth ( phi index ) ( phi[index ] ) ) ;; (equal? (phi[index] index) (cond)) ;; (if cond ( ( dup ( index ) ( index jndex ) ) ) ;; ()))) ( to - string ( 963 ) ( ) ) ;; (print (aaa) ())))) (format t "~A~%" (full-translate '((store 1 a) (store 1 b) (pow (10 12) (min)) (mul (2 min) (min)) (while ((dup (a) (a aa)) (dup (min) (min tmp)) (less-than (aa tmp) (cond))) cond ((dup (a) (a ta)) (dup (b) (b tb)) (mul (3 a) (tmp1)) (mul (4 b) (tmp2)) (add (tmp1 tmp2) (a)) (mul (2 ta) (tmp1)) (mul (3 tb) (tmp2)) (add (tmp1 tmp2) (b)))) (add (b 1) (b)) (div (b 2) (b)) (to-string (b) (b)) (print (b) ())
null
https://raw.githubusercontent.com/Mercerenies/eulers-melting-pot/68bcb9b1d46278c0bab4ab6200bcba09be8e4930/etc/smgen.lisp
lisp
Snowman source generator / "compiler" This "magic" string at the start of the program activates abdf "(@(" Duplicates v1 into v2 (leaves v2 as active variable) (store literal variable) (move src dest) (map var array out-var block) (each var array block) (if cond true-block false-block) (while cond var body) (format t "~A~%" (full-translate (while ((incr (total) (total)) (not (c) (c))) c ((dup (total) (total total2)) (to-string (total2) (total2)) (print (total2) ())))))) (format t "~A~%" (full-translate '((store 0 total) (each d iter ((dup (d) (d d1)) (dup (d1) (d1 d2)) (div (d2 2) (n1)) (ceil (n1) (n1)) (dup (d) (d aaa)) ((dup (d) (d aaa)) (print (aaa) ()) (print (aaa) ()) (print (aaa) ())) ()) (each n iter1 ;; gcd calculation ((while ((dup (d) (d dzero)) (equal? (dzero 0) (cond)) (not (cond) (cond))) cond ((dup (d) (t0 t1)) (mod (n t0) (d)) (move t1 n))) (equal? (n 1) (eq)) (if eq ((incr (total) (total))) ()))))) (to-string (total) (total)) (print (total) ())))) (format t "~A~%" (full-translate (each index iter (equal? (phi[index] index) (cond)) (if cond ()))) (print (aaa) ()))))
(defparameter *letter-operators* '((decr "NdE" 1 1) (incr "NiN" 1 1) (print "sP" 1 0) (to-string "tS" 1 1) (nth "aA" 2 1) (range "nR" 2 1) (equal? "eQ" 2 1) (dup "dU" 1 2) (div "nD" 2 1) (mod "NmO" 2 1) (floor "nF" 1 1) (ceil "nC" 1 1) (not "nO" 1 1) (wrap "wR" 1 1) (pow "nP" 2 1) (mul "nM" 2 1) (add "nA" 2 1) (less-than "nL" 2 1))) (defparameter *vars* '()) (defconstant +reserved-vars+ 2) (defparameter *next-available-var* +reserved-vars+) (defun index-to-var (n) (concatenate 'string (make-string (floor n 2) :initial-element #\=) (if (zerop (mod n 2)) "+" "!"))) (defun translate-var (name) (check-type name symbol) (or (cdr (assoc name *vars*)) (let ((new-var (index-to-var *next-available-var*))) (incf *next-available-var*) (push (cons name new-var) *vars*) new-var))) (defun duplicate-var (v1 v2) (when (numberp v1) (setq v1 (index-to-var v1))) (when (numberp v2) (setq v2 (index-to-var v2))) `("~" ,v1 "#" "dU" "*" ,v2 "*" "~")) (defun translate-input (input) (etypecase input (string `(,@(duplicate-var input 0) "#")) (number (list input)) (list input))) (defun compile-call (name inputs outputs) (let ((fn (or (assoc name *letter-operators*) (error "Unknown function ~S" name)))) (unless (= (length inputs) (third fn)) (error "Expecting ~S inputs to ~S, got ~S" (third fn) (first fn) (length inputs))) (unless (= (length outputs) (fourth fn)) (error "Expecting ~S outputs to ~S, got ~S" (fourth fn) (first fn) (length outputs))) (append (loop for input in inputs append (translate-input input)) (list (second fn)) (loop for output in outputs append `(,output "*"))))) (defun list-to-text (list) (format nil "~{~A~^ ~}" (loop with last-was-number = nil for elem in list if (and (numberp elem) last-was-number) collect "vN" collect elem do (setq last-was-number (numberp elem))))) (defun translate (line) (flet ((translate-arg (value) (translate-literal value :can-be-var t))) (case (first line) (store (destructuring-bind (literal var) (rest line) (let ((literal (translate-literal literal)) (var (translate-var var))) `(,var ,literal "*")))) (move (destructuring-bind (src dest) (rest line) (let ((src (translate-var src)) (dest (translate-var dest))) `(,src "#" ,dest "*")))) (map (destructuring-bind (var array out-var block) (rest line) (let ((var (translate-var var))) (let ((block (translate-block block :prefix `(,var "*") :suffix `(,var "#"))) (array (translate-literal array :can-be-var t)) (out-var (translate-var out-var))) (append (translate-input array) block `("aM" ,out-var "*")))))) (each (destructuring-bind (var array block) (rest line) (let ((var (translate-var var))) (let ((block (translate-block block :prefix `(,var "*"))) (array (translate-literal array :can-be-var t))) (append (translate-input array) block '("aE")))))) (if (destructuring-bind (cond true-block false-block) (rest line) (let ((cond (translate-literal cond :can-be-var t)) (true-block (translate-block true-block)) (false-block (translate-block false-block))) (append true-block false-block (translate-input cond) '("bI"))))) (while (destructuring-bind (cond var body) (rest line) (let ((var (translate-var var))) (let ((cond (translate-block cond :suffix `(,var "#"))) (body (translate-block body))) (append body cond '("bW")))))) (t (destructuring-bind (name inputs outputs) line (let ((inputs (mapcar #'translate-arg inputs)) (outputs (mapcar #'translate-var outputs))) (compile-call name inputs outputs))))))) (defun translate-literal (literal &key can-be-var) (etypecase literal (number literal) (list (translate-block literal)) (symbol (assert can-be-var) (translate-var literal)))) (defun translate-block (lines &key prefix suffix) (append '(":") prefix (loop for line in lines append (translate line)) suffix '(";"))) (defun translate-lines (lines) (loop for line in lines append (translate line))) (defun full-translate (lines) (list-to-text (append '("(" "@" "(") (translate-lines lines)))) ' ( ( store 1 total ) ( dup ( total ) ( total ) ) ( equal ? ( 10 ) ( c ) ) ( range ( 4 12001 ) ( iter ) ) ( div ( d1 3 ) ( n0 ) ) ( floor ( n0 ) ( n0 ) ) ( incr ( n0 ) ( n0 ) ) ( range ( n0 n1 ) ( iter1 ) ) ( mod ( aaa 100 ) ( bbb ) ) ( equal ? ( bbb 0 ) ( bbb ) ) ( if ( to - string ( aaa ) ( ) ) ( wrap ( 13 ) ( aaa ) ) ( wrap ( 10 ) ( aaa ) ) ' ( ( range ( 0 1000001 ) ( phi ) ) ( range ( 2 1000001 ) ( iter ) ) ( ( nth ( phi index ) ( phi[index ] ) ) ( ( dup ( index ) ( index jndex ) ) ) ( to - string ( 963 ) ( ) ) (format t "~A~%" (full-translate '((store 1 a) (store 1 b) (pow (10 12) (min)) (mul (2 min) (min)) (while ((dup (a) (a aa)) (dup (min) (min tmp)) (less-than (aa tmp) (cond))) cond ((dup (a) (a ta)) (dup (b) (b tb)) (mul (3 a) (tmp1)) (mul (4 b) (tmp2)) (add (tmp1 tmp2) (a)) (mul (2 ta) (tmp1)) (mul (3 tb) (tmp2)) (add (tmp1 tmp2) (b)))) (add (b 1) (b)) (div (b 2) (b)) (to-string (b) (b)) (print (b) ())
20bd92f7c9f194c0505ddea101255e5a89ccb75d42b1322ef00459904bd2a6d0
airbus-seclab/bincat
stubs.ml
This file is part of BinCAT . Copyright 2014 - 2021 - Airbus BinCAT is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . BinCAT is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with BinCAT . If not , see < / > . This file is part of BinCAT. Copyright 2014-2021 - Airbus BinCAT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BinCAT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with BinCAT. If not, see </>. *) module L = Log.Make(struct let name = "stubs" end) module type T = sig type domain_t val process : Data.Address.t -> Data.Address.t option -> domain_t -> string -> Asm.calling_convention_t -> domain_t * Taint.Set.t * Asm.stmt list val skip: domain_t -> Config.fun_t -> Asm.calling_convention_t -> domain_t * Taint.Set.t * Asm.stmt list val init: unit -> unit val default_handler: int -> Asm.stmt list val stubs : (string, (Data.Address.t -> Data.Address.t option -> domain_t -> Asm.lval -> (int -> Asm.lval) -> domain_t * Taint.Set.t) * int) Hashtbl.t end module Make(D: Domain.T) = struct type domain_t = D.t let shift argfun n = fun x -> (argfun (n+x)) let heap_allocator (ip: Data.Address.t) (calling_ip: Data.Address.t option) (d: domain_t) ret args: domain_t * Taint.Set.t = try let sz = D.value_of_exp d (Asm.Lval (args 0)) in let region, id = Data.Address.new_heap_region (Z.mul (Z.of_int 8) sz) in Hashtbl.add Dump.heap_id_tbl id ip; let d' = D.allocate_on_heap d id in let zero = Data.Word.zero !Config.address_sz in let addr = region, zero in let success_msg = "successfull heap allocation " in let failure_msg = "heap allocation failed " in let postfix = match calling_ip with | Some ip -> let ip_str = Data.Address.to_string ip in "at " ^ ip_str | None -> "" in let success_msg = success_msg ^ postfix in let failure_msg = failure_msg ^ postfix in D.set_lval_to_addr ret [ (addr, success_msg) ; (Data.Address.of_null (), failure_msg) ] d' with Z.Overflow -> raise (Exceptions.Too_many_concrete_elements "heap allocation: imprecise size to allocate") let check_free (ip: Data.Address.t) (a: Data.Address.t): Data.Address.heap_id_t = match a with | Data.Address.Heap (id, _), o -> if Data.Word.compare o (Data.Word.zero !Config.address_sz) <> 0 then raise (Exceptions.Undefined_free (Printf.sprintf "at instruction %s: base address to free is not zero (%s)" (Data.Address.to_string ip) (Data.Address.to_string a))) else id | _ -> raise (Exceptions.Undefined_free (Printf.sprintf "at instruction %s: base address (%s) to free not in the heap or NULL" (Data.Address.to_string ip) (Data.Address.to_string a))) let heap_deallocator (ip: Data.Address.t) _ (d: domain_t) _ret args: domain_t * Taint.Set.t = let mem = Asm.Lval (args 0) in try let addrs, taint = D.mem_to_addresses d mem in let addrs' = Data.Address.Set.elements addrs in match addrs' with | [a] -> let id = check_free ip a in L.debug2 (fun p -> p "check_free"); D.deallocate d id, taint | _::_ -> let ids = List.fold_left (fun ids a -> (check_free ip a)::ids) [] addrs' in D.weak_deallocate d ids, taint | [] -> let msg = Printf.sprintf "Illegal dereference of %s (null)" (Asm.string_of_lval (args 0) true) in raise (Exceptions.Null_deref msg) with Exceptions.Too_many_concrete_elements _ -> raise (Exceptions.Too_many_concrete_elements "Stubs: too many addresses to deallocate") let strlen (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let zero = Asm.Const (Data.Word.zero 8) in let len = D.get_offset_from (Asm.Lval (args 0)) Asm.EQ zero 10000 8 d in if len > !Config.unroll then begin L.info (fun p -> p "updates automatic loop unrolling with the computed string length = %d" len); Config.unroll := len end; D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d let memcpy (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = L.info (fun p -> p "memcpy stub"); let dst = Asm.Lval (args 0) in let src = Asm.Lval (args 1) in let sz = Asm.Lval (args 2) in try let n = Z.to_int (D.value_of_exp d sz) in let d' = D.copy d dst (Asm.Lval (Asm.M (src, (8*n)))) (8*n) in D.set ret dst d' with _ -> L.abort (fun p -> p "too large copy size in memcpy stub") let memcmp (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = L.info (fun p -> p "memcmp stub"); let sz = Asm.Lval (args 2) in try let n = Z.to_int (D.value_of_exp d sz) in let lv1 = Asm.M (Asm.Lval (args 0), 8*n) in let lv2 = Asm.M (Asm.Lval (args 1), 8*n) in let taint = try Taint.join (D.get_taint lv1 d) (D.get_taint lv2 d) with _ -> Taint.TOP in let v1 = D.value_of_exp d (Asm.Lval lv1) in let v2 = D.value_of_exp d (Asm.Lval lv2) in let res = Asm.Const (Data.Word.of_int (Z.sub v1 v2) !Config.operand_sz) in let d' = fst (D.set ret res d) in D.taint_lval ret taint d' with _ -> D.forget_lval ret d, Taint.Set.singleton Taint.TOP let memset (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let arg0 = args 0 in let dst = Asm.Lval arg0 in let src = args 1 in let nb = Asm.Lval (args 2) in try let nb' = D.value_of_exp d nb in let byte = match src with | Asm.V (Asm.T r) -> Asm.V (Asm.P (r, 0, 7)) | Asm.V (Asm.P (r, l, u)) when u-l>=7-> Asm.V (Asm.P (r, l, l+7)) (* little endian only ? *) | Asm.M (e, n) when Z.compare (Z.of_int n) nb' >= 0 -> Asm.M(e, 8) (* little endian only ? *) | _ -> raise (Exceptions.Error "inconsistent argument for memset") in let sz = Asm.lval_length arg0 in let byte_exp = Asm.Lval byte in L.info (fun p -> p "memset(%s, %s, %s) stub" (Z.to_string (D.value_of_exp d dst)) (Z.to_string (D.value_of_exp d byte_exp)) (Z.to_string nb')); let one_set d i = if Z.compare i nb' < 0 then let addr = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int i sz)) in fst (D.set (Asm.M(addr, 8)) byte_exp d) (* we ignore taint as the source is a constant *) else d in let rec set_loop d i = if Z.sign i < 0 then d else let d'=one_set d i in set_loop d' (Z.pred i) in let d' = set_loop d nb' in (* result is tainted if the destination to copy the byte is tainted *) D.set ret dst d' with _ -> L.abort (fun p -> p "too large number of bytes to copy in memset stub") let print (d: domain_t) ret format_addr va_args (to_buffer: Asm.exp option): domain_t * Taint.Set.t = ret has to contain the number of bytes stored in dst ; format_addr is the address of the format string ; va_args the list of values needed to fill the format string format_addr is the address of the format string ; va_args the list of values needed to fill the format string *) try let zero = Asm.Const (Data.Word.of_int Z.zero 8) in let str_len, format_string = D.get_bytes format_addr Asm.EQ zero 1000 8 d in L.info (fun p -> p "(s)printf stub, format string: \"%s\"" (String.escaped (Bytes.to_string format_string))); let format_num d dst_off c fmt_pos arg pad_char pad_left: int * int * domain_t = let rec compute digit_nb fmt_pos = let c = Bytes.get format_string fmt_pos in match c with | c when '0' <= c && c <= '9' -> let n = ((Char.code c) - (Char.code '0')) in compute (digit_nb*10+n) (fmt_pos+1) | 'l' -> begin let c = Bytes.get format_string (fmt_pos+1) in match c with | 'x' | 'X' -> let sz = Config.size_of_long () in L.info (fun p -> p "hypothesis used in format string: size of long = %d bits" sz); let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_hex d dst' | _ -> D.print_hex d in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) (Some (pad_char, pad_left)) sz in fmt_pos+2, dst_off', d' | c -> L.abort (fun p -> p "(s)printf: Unknown format char in format string: %c" c) end | 'x' | 'X' | 'd' -> let format_copy, format_print = match c with |'x' | 'X' -> D.copy_hex, D.print_hex | _ -> D.copy_int, D.print_int in let copy = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in format_copy d dst' | _ -> format_print d in let d', dst_off' = copy arg digit_nb (Char.compare c 'X' = 0) (Some (pad_char, pad_left)) !Config.operand_sz in fmt_pos+1, dst_off', d' | 's' -> let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_chars d dst' | _ -> (fun arg1 arg2 arg3 -> fst (D.print_chars d arg1 arg2 arg3)) in fmt_pos+1, digit_nb, dump arg digit_nb (Some (pad_char, pad_left)) (* value is in memory *) | c -> L.abort (fun p -> p "(s)printf: Unknown format char in format string: %c" c) in let n = ((Char.code c) - (Char.code '0')) in compute n fmt_pos in let format_arg d fmt_pos dst_off arg: int * int * domain_t = let c = Bytes.get format_string fmt_pos in match c with | 's' -> (* %s *) let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_until d dst' | None -> D.print_until d in let sz, d' = dump arg (Asm.Const (Data.Word.of_int Z.zero 8)) 8 10000 true None in fmt_pos+1, sz, d' | 'x' | 'X' -> (* %x | %X *) let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_hex d dst' | None -> D.print_hex d in let digit_nb = !Config.operand_sz/8 in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) None !Config.operand_sz in fmt_pos+1, dst_off', d' | 'd' -> (* %d *) let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_int d dst' | None -> D.print_int d in let digit_nb = !Config.operand_sz/8 in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) None !Config.operand_sz in fmt_pos+1, dst_off', d' | c when '1' <= c && c <= '9' -> format_num d dst_off c (fmt_pos+1) arg '0' true | '0' -> format_num d dst_off '0' (fmt_pos+1) arg '0' true | ' ' -> format_num d dst_off '0' (fmt_pos+1) arg ' ' true | '-' -> format_num d dst_off '0' (fmt_pos+1) arg ' ' false | _ -> L.abort (fun p -> p "Unknown format or modifier in format string: %c" c) in let rec copy_char d c (fmt_pos: int) dst_off arg_nb: int * domain_t = let src = (Asm.Const (Data.Word.of_int (Z.of_int (Char.code c)) 8)) in let dump = match to_buffer with | Some dst -> D.copy d (Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.address_sz))) | _ -> D.print d in let d' = dump src 8 in fill_buffer d' (fmt_pos+1) 0 (dst_off+1) arg_nb (* state machine for format string parsing *) and fill_buffer (d: domain_t) (fmt_pos: int) (state_id: int) (dst_off: int) arg_nb: int * domain_t = if fmt_pos < str_len then match state_id with | 0 -> (* look for % *) begin match Bytes.get format_string fmt_pos with | '%' -> fill_buffer d (fmt_pos+1) 1 dst_off arg_nb | c -> copy_char d c fmt_pos dst_off arg_nb end | 1 -> (* % found, do we have %% ? *) let c = Bytes.get format_string fmt_pos in begin match c with | '%' -> copy_char d c fmt_pos dst_off arg_nb | _ -> fill_buffer d fmt_pos 2 dst_off arg_nb end = 2 ie previous char is % let arg = Asm.Lval (va_args arg_nb) in let fmt_pos', buf_len, d' = format_arg d fmt_pos dst_off arg in fill_buffer d' fmt_pos' 0 (dst_off+buf_len) (arg_nb+1) else add a zero to the end of the buffer match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in dst_off, D.copy d dst' (Asm.Const (Data.Word.of_int Z.zero 8)) 8 | None -> dst_off, d in let len', d' = fill_buffer d 0 0 0 0 in (* set the number of bytes (excluding the string terminator) read into the given register *) D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len') !Config.operand_sz)) d' with | Exceptions.Too_many_concrete_elements _ as e -> L.exc_and_abort e (fun p -> p "(s)printf: Unknown address of the format string or imprecise value of the format string") | Not_found as e -> L.exc_and_abort e (fun p -> p "address of the null terminator in the format string in (s)printf not found") let sprintf (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let dst = Asm.Lval (args 0) in let format_addr = Asm.Lval (args 1) in let va_args = shift args 2 in print d ret format_addr va_args (Some dst) let sprintf_chk (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let dst = Asm.Lval (args 0) in let format_addr = Asm.Lval (args 3) in let va_args = shift args 4 in print d ret format_addr va_args (Some dst) let printf (_ip: Data.Address.t) _ d ret args = (* TODO: not optimal as buffer destination is built as for sprintf *) let format_addr = Asm.Lval (args 0) in let va_args = shift args 1 in (* creating a very large temporary buffer to store the output of printf *) let d', is_tainted = print d ret format_addr va_args None in d', is_tainted let printf_chk (ip: Data.Address.t) calling_ip d ret args = printf ip calling_ip d ret (shift args 1) let puts (_ip: Data.Address.t) _ d ret args = let str = Asm.Lval (args 0) in let len, d' = D.print_until d str (Asm.Const (Data.Word.of_int Z.zero 8)) 8 10000 true None in let d', taint = D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d' in Log.Stdout.stdout (fun p -> p "\n"); d', taint let write _ip _ d ret args = let fd = try Z.to_int (D.value_of_exp d (Asm.Lval (args 0))) with _ -> L.abort (fun p -> p "imprecise file descriptor as argument of write") in if fd = 1 then let buf = Asm.Lval (args 1) in try let char_nb = Z.to_int (D.value_of_exp d (Asm.Lval (args 2))) in let d', len = D.print_chars d buf char_nb None in let d', taint = D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d' in d', taint with Exceptions.Too_many_concrete_elements _ -> L.abort (fun p -> p "imprecise number of char to write") else L.abort (fun p -> p "write output implemented only for stdout") let stubs = Hashtbl.create 5 let signal_process d call_conv: domain_t * Taint.Set.t * Asm.stmt list = let args = call_conv.Asm.arguments in let d, taint, stmts = try let int_nb = Z.to_int (D.value_of_exp d (Asm.Lval (args 0))) in let addrs, taint = D.mem_to_addresses d (Asm.Lval (args 1)) in (* int_nb and addr has to be concrete values *) match Data.Address.Set.elements addrs with | [a] -> d, taint, [Asm.Directive (Asm.Handler (int_nb, a))] | _ -> raise (Exceptions.Too_many_concrete_elements "several possible handler addresses") with Exceptions.Too_many_concrete_elements _ -> L.warn (fun p -> p "uncomputable argument of signal call (signal number or handler address). Skipped"); d, Taint.Set.singleton Taint.U, [] in let cleanup_stmts = (call_conv.Asm.callee_cleanup 2) in d, taint, stmts@cleanup_stmts let putchar (_ip) _ d ret args = let str = Asm.Lval (args 0) in let d' = D.print d str !Config.operand_sz in D.set ret (Asm.Const (Data.Word.of_int Z.one !Config.operand_sz)) d' (* TODO: merge all tainting src to have the same id *) let getc _ _ d ret _ = let d' = D.forget_lval ret d in if !Config.taint_input then let taint_mask = Taint.S (Taint.SrcSet.singleton (Taint.Src.Tainted (Taint.Src.new_src()))) in D.taint_lval ret taint_mask d' else d', Taint.Set.singleton Taint.U let getchar = getc let bin_exit (_ip) _ _d _ret _args = raise (Exceptions.Stop "on exit call") let process ip calling_ip d fun_name call_conv: domain_t * Taint.Set.t * Asm.stmt list = if String.compare fun_name "signal" = 0 then signal_process d call_conv else let apply_f, arg_nb = try Hashtbl.find stubs fun_name with Not_found -> L.abort (fun p -> p "No stub available for function [%s]" fun_name) in let d', taint = try apply_f ip calling_ip d call_conv.Asm.return call_conv.Asm.arguments with | Exit -> d, Taint.Set.singleton Taint.U | Exceptions.Use_after_free _ as e -> raise e | Exceptions.Double_free -> raise Exceptions.Double_free | Exceptions.Null_deref _ as e -> raise e | Exceptions.Stop _ as e -> raise e | Exceptions.Error _ as e -> raise e | e -> L.exc e (fun p -> p "error while processing stub [%s]" fun_name); L.warn (fun p -> p "uncomputable stub for [%s]. Skipped." fun_name); d, Taint.Set.singleton Taint.U in let cleanup_stmts = (call_conv.Asm.callee_cleanup arg_nb) in d', taint, cleanup_stmts let skip d f call_conv: domain_t * Taint.Set.t * Asm.stmt list = let arg_nb, ret_val = Hashtbl.find Config.funSkipTbl f in let d, taint = match ret_val with | None -> D.forget_lval call_conv.Asm.return d, Taint.Set.singleton Taint.TOP | Some ret_val' -> let sz = Config.size_of_config ret_val' in match call_conv.Asm.return with | Asm.V (Asm.T r) when Register.size r = sz -> D.set_register_from_config r ret_val' d | Asm.M (e, n) when sz = n -> let addrs, _ = D.mem_to_addresses d e in let d', taint' = match Data.Address.Set.elements addrs with | [a] -> D.set_memory_from_config a ret_val' 1 d | _ -> D.forget d, Taint.Set.singleton Taint.TOP (* TODO: be more precise *) in d', taint' | _ -> D.forget d, Taint.Set.singleton Taint.TOP (* TODO: be more precise *) in let cleanup_stmts = call_conv.Asm.callee_cleanup (Z.to_int arg_nb) in d,taint, cleanup_stmts let default_handler sig_nb = see man 7 signal . Implementation of POSIX.1 - 2001 let ignore_sig sig_text = L.analysis (fun p -> p "Handling signal %s: ignored" sig_text); [] in let abort sig_text = L.analysis (fun p -> p "Handling signal %s: analysis stops" sig_text); L.abort (fun p -> p "see above") in match sig_nb with | 1 (* SIGHUP *) -> abort "SIGHUP" | 2 (* SIGINT *) -> abort "SIGINT" SIGQUIT SIGIL SIGTRAP | 6 (* SIGABRT *) -> abort "SIGABRT" | 7 | 10 (* SIGBUS *) -> abort "SIGBUS" | 8 (* SIGFPE *) -> abort "SIGFPE" SIGKILL | 11 (* SIGSEGV *) -> abort "SIGSEGV" | 12 | 31 (* SIGSYS *) -> abort "SIGSYS" SIGALRM SIGTERM | 16 (* SIGUSR1 *) -> ignore_sig "SIGUSR1" SIGCHLD | 19 | 25 (* SIGCONT *) -> ignore_sig "SIGCONT" SIGTSTP SIGTTIN SIGTTOU | _ -> L.analysis (fun p -> p "received Illegal signal %d. Ignored" sig_nb); [] let init () = Hashtbl.replace stubs "memcpy" (memcpy, 3); Hashtbl.replace stubs "memcmp" (memcmp, 3); Hashtbl.replace stubs "memset" (memset, 3); Hashtbl.replace stubs "sprintf" (sprintf, 0); Hashtbl.replace stubs "printf" (printf, 0); Hashtbl.replace stubs "write" (write, 3); Hashtbl.replace stubs "__sprintf_chk" (sprintf_chk, 0); Hashtbl.replace stubs "__printf_chk" (printf_chk, 0); Hashtbl.replace stubs "puts" (puts, 1); Hashtbl.replace stubs "strlen" (strlen, 1); Hashtbl.replace stubs "signal" ((fun _ _ _ _ _ -> raise (Exceptions.Stop "on signal that stops execution of the program")), 0); (* special treatment for signal see signal_process *) Hashtbl.replace stubs "putchar" (putchar, 1); Hashtbl.replace stubs "getchar" (getchar, 0); Hashtbl.replace stubs "getc" (getc, 1); Hashtbl.replace stubs "exit" (bin_exit, 1); Hashtbl.replace stubs "malloc" (heap_allocator, 1); Hashtbl.replace stubs "free" (heap_deallocator, 1);; end
null
https://raw.githubusercontent.com/airbus-seclab/bincat/7d4a0b90cf950c0f43e252602a348cf9e2f858ba/ocaml/src/fixpoint/stubs.ml
ocaml
little endian only ? little endian only ? we ignore taint as the source is a constant result is tainted if the destination to copy the byte is tainted value is in memory %s %x | %X %d state machine for format string parsing look for % % found, do we have %% ? set the number of bytes (excluding the string terminator) read into the given register TODO: not optimal as buffer destination is built as for sprintf creating a very large temporary buffer to store the output of printf int_nb and addr has to be concrete values TODO: merge all tainting src to have the same id TODO: be more precise TODO: be more precise SIGHUP SIGINT SIGABRT SIGBUS SIGFPE SIGSEGV SIGSYS SIGUSR1 SIGCONT special treatment for signal see signal_process
This file is part of BinCAT . Copyright 2014 - 2021 - Airbus BinCAT is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . BinCAT is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with BinCAT . If not , see < / > . This file is part of BinCAT. Copyright 2014-2021 - Airbus BinCAT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BinCAT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with BinCAT. If not, see </>. *) module L = Log.Make(struct let name = "stubs" end) module type T = sig type domain_t val process : Data.Address.t -> Data.Address.t option -> domain_t -> string -> Asm.calling_convention_t -> domain_t * Taint.Set.t * Asm.stmt list val skip: domain_t -> Config.fun_t -> Asm.calling_convention_t -> domain_t * Taint.Set.t * Asm.stmt list val init: unit -> unit val default_handler: int -> Asm.stmt list val stubs : (string, (Data.Address.t -> Data.Address.t option -> domain_t -> Asm.lval -> (int -> Asm.lval) -> domain_t * Taint.Set.t) * int) Hashtbl.t end module Make(D: Domain.T) = struct type domain_t = D.t let shift argfun n = fun x -> (argfun (n+x)) let heap_allocator (ip: Data.Address.t) (calling_ip: Data.Address.t option) (d: domain_t) ret args: domain_t * Taint.Set.t = try let sz = D.value_of_exp d (Asm.Lval (args 0)) in let region, id = Data.Address.new_heap_region (Z.mul (Z.of_int 8) sz) in Hashtbl.add Dump.heap_id_tbl id ip; let d' = D.allocate_on_heap d id in let zero = Data.Word.zero !Config.address_sz in let addr = region, zero in let success_msg = "successfull heap allocation " in let failure_msg = "heap allocation failed " in let postfix = match calling_ip with | Some ip -> let ip_str = Data.Address.to_string ip in "at " ^ ip_str | None -> "" in let success_msg = success_msg ^ postfix in let failure_msg = failure_msg ^ postfix in D.set_lval_to_addr ret [ (addr, success_msg) ; (Data.Address.of_null (), failure_msg) ] d' with Z.Overflow -> raise (Exceptions.Too_many_concrete_elements "heap allocation: imprecise size to allocate") let check_free (ip: Data.Address.t) (a: Data.Address.t): Data.Address.heap_id_t = match a with | Data.Address.Heap (id, _), o -> if Data.Word.compare o (Data.Word.zero !Config.address_sz) <> 0 then raise (Exceptions.Undefined_free (Printf.sprintf "at instruction %s: base address to free is not zero (%s)" (Data.Address.to_string ip) (Data.Address.to_string a))) else id | _ -> raise (Exceptions.Undefined_free (Printf.sprintf "at instruction %s: base address (%s) to free not in the heap or NULL" (Data.Address.to_string ip) (Data.Address.to_string a))) let heap_deallocator (ip: Data.Address.t) _ (d: domain_t) _ret args: domain_t * Taint.Set.t = let mem = Asm.Lval (args 0) in try let addrs, taint = D.mem_to_addresses d mem in let addrs' = Data.Address.Set.elements addrs in match addrs' with | [a] -> let id = check_free ip a in L.debug2 (fun p -> p "check_free"); D.deallocate d id, taint | _::_ -> let ids = List.fold_left (fun ids a -> (check_free ip a)::ids) [] addrs' in D.weak_deallocate d ids, taint | [] -> let msg = Printf.sprintf "Illegal dereference of %s (null)" (Asm.string_of_lval (args 0) true) in raise (Exceptions.Null_deref msg) with Exceptions.Too_many_concrete_elements _ -> raise (Exceptions.Too_many_concrete_elements "Stubs: too many addresses to deallocate") let strlen (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let zero = Asm.Const (Data.Word.zero 8) in let len = D.get_offset_from (Asm.Lval (args 0)) Asm.EQ zero 10000 8 d in if len > !Config.unroll then begin L.info (fun p -> p "updates automatic loop unrolling with the computed string length = %d" len); Config.unroll := len end; D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d let memcpy (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = L.info (fun p -> p "memcpy stub"); let dst = Asm.Lval (args 0) in let src = Asm.Lval (args 1) in let sz = Asm.Lval (args 2) in try let n = Z.to_int (D.value_of_exp d sz) in let d' = D.copy d dst (Asm.Lval (Asm.M (src, (8*n)))) (8*n) in D.set ret dst d' with _ -> L.abort (fun p -> p "too large copy size in memcpy stub") let memcmp (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = L.info (fun p -> p "memcmp stub"); let sz = Asm.Lval (args 2) in try let n = Z.to_int (D.value_of_exp d sz) in let lv1 = Asm.M (Asm.Lval (args 0), 8*n) in let lv2 = Asm.M (Asm.Lval (args 1), 8*n) in let taint = try Taint.join (D.get_taint lv1 d) (D.get_taint lv2 d) with _ -> Taint.TOP in let v1 = D.value_of_exp d (Asm.Lval lv1) in let v2 = D.value_of_exp d (Asm.Lval lv2) in let res = Asm.Const (Data.Word.of_int (Z.sub v1 v2) !Config.operand_sz) in let d' = fst (D.set ret res d) in D.taint_lval ret taint d' with _ -> D.forget_lval ret d, Taint.Set.singleton Taint.TOP let memset (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let arg0 = args 0 in let dst = Asm.Lval arg0 in let src = args 1 in let nb = Asm.Lval (args 2) in try let nb' = D.value_of_exp d nb in let byte = match src with | Asm.V (Asm.T r) -> Asm.V (Asm.P (r, 0, 7)) | _ -> raise (Exceptions.Error "inconsistent argument for memset") in let sz = Asm.lval_length arg0 in let byte_exp = Asm.Lval byte in L.info (fun p -> p "memset(%s, %s, %s) stub" (Z.to_string (D.value_of_exp d dst)) (Z.to_string (D.value_of_exp d byte_exp)) (Z.to_string nb')); let one_set d i = if Z.compare i nb' < 0 then let addr = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int i sz)) in else d in let rec set_loop d i = if Z.sign i < 0 then d else let d'=one_set d i in set_loop d' (Z.pred i) in let d' = set_loop d nb' in D.set ret dst d' with _ -> L.abort (fun p -> p "too large number of bytes to copy in memset stub") let print (d: domain_t) ret format_addr va_args (to_buffer: Asm.exp option): domain_t * Taint.Set.t = ret has to contain the number of bytes stored in dst ; format_addr is the address of the format string ; va_args the list of values needed to fill the format string format_addr is the address of the format string ; va_args the list of values needed to fill the format string *) try let zero = Asm.Const (Data.Word.of_int Z.zero 8) in let str_len, format_string = D.get_bytes format_addr Asm.EQ zero 1000 8 d in L.info (fun p -> p "(s)printf stub, format string: \"%s\"" (String.escaped (Bytes.to_string format_string))); let format_num d dst_off c fmt_pos arg pad_char pad_left: int * int * domain_t = let rec compute digit_nb fmt_pos = let c = Bytes.get format_string fmt_pos in match c with | c when '0' <= c && c <= '9' -> let n = ((Char.code c) - (Char.code '0')) in compute (digit_nb*10+n) (fmt_pos+1) | 'l' -> begin let c = Bytes.get format_string (fmt_pos+1) in match c with | 'x' | 'X' -> let sz = Config.size_of_long () in L.info (fun p -> p "hypothesis used in format string: size of long = %d bits" sz); let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_hex d dst' | _ -> D.print_hex d in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) (Some (pad_char, pad_left)) sz in fmt_pos+2, dst_off', d' | c -> L.abort (fun p -> p "(s)printf: Unknown format char in format string: %c" c) end | 'x' | 'X' | 'd' -> let format_copy, format_print = match c with |'x' | 'X' -> D.copy_hex, D.print_hex | _ -> D.copy_int, D.print_int in let copy = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in format_copy d dst' | _ -> format_print d in let d', dst_off' = copy arg digit_nb (Char.compare c 'X' = 0) (Some (pad_char, pad_left)) !Config.operand_sz in fmt_pos+1, dst_off', d' | 's' -> let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_chars d dst' | _ -> (fun arg1 arg2 arg3 -> fst (D.print_chars d arg1 arg2 arg3)) in fmt_pos+1, digit_nb, dump arg digit_nb (Some (pad_char, pad_left)) | c -> L.abort (fun p -> p "(s)printf: Unknown format char in format string: %c" c) in let n = ((Char.code c) - (Char.code '0')) in compute n fmt_pos in let format_arg d fmt_pos dst_off arg: int * int * domain_t = let c = Bytes.get format_string fmt_pos in match c with let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_until d dst' | None -> D.print_until d in let sz, d' = dump arg (Asm.Const (Data.Word.of_int Z.zero 8)) 8 10000 true None in fmt_pos+1, sz, d' let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_hex d dst' | None -> D.print_hex d in let digit_nb = !Config.operand_sz/8 in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) None !Config.operand_sz in fmt_pos+1, dst_off', d' let dump = match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in D.copy_int d dst' | None -> D.print_int d in let digit_nb = !Config.operand_sz/8 in let d', dst_off' = dump arg digit_nb (Char.compare c 'X' = 0) None !Config.operand_sz in fmt_pos+1, dst_off', d' | c when '1' <= c && c <= '9' -> format_num d dst_off c (fmt_pos+1) arg '0' true | '0' -> format_num d dst_off '0' (fmt_pos+1) arg '0' true | ' ' -> format_num d dst_off '0' (fmt_pos+1) arg ' ' true | '-' -> format_num d dst_off '0' (fmt_pos+1) arg ' ' false | _ -> L.abort (fun p -> p "Unknown format or modifier in format string: %c" c) in let rec copy_char d c (fmt_pos: int) dst_off arg_nb: int * domain_t = let src = (Asm.Const (Data.Word.of_int (Z.of_int (Char.code c)) 8)) in let dump = match to_buffer with | Some dst -> D.copy d (Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.address_sz))) | _ -> D.print d in let d' = dump src 8 in fill_buffer d' (fmt_pos+1) 0 (dst_off+1) arg_nb and fill_buffer (d: domain_t) (fmt_pos: int) (state_id: int) (dst_off: int) arg_nb: int * domain_t = if fmt_pos < str_len then match state_id with begin match Bytes.get format_string fmt_pos with | '%' -> fill_buffer d (fmt_pos+1) 1 dst_off arg_nb | c -> copy_char d c fmt_pos dst_off arg_nb end let c = Bytes.get format_string fmt_pos in begin match c with | '%' -> copy_char d c fmt_pos dst_off arg_nb | _ -> fill_buffer d fmt_pos 2 dst_off arg_nb end = 2 ie previous char is % let arg = Asm.Lval (va_args arg_nb) in let fmt_pos', buf_len, d' = format_arg d fmt_pos dst_off arg in fill_buffer d' fmt_pos' 0 (dst_off+buf_len) (arg_nb+1) else add a zero to the end of the buffer match to_buffer with | Some dst -> let dst' = Asm.BinOp (Asm.Add, dst, Asm.Const (Data.Word.of_int (Z.of_int dst_off) !Config.stack_width)) in dst_off, D.copy d dst' (Asm.Const (Data.Word.of_int Z.zero 8)) 8 | None -> dst_off, d in let len', d' = fill_buffer d 0 0 0 0 in D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len') !Config.operand_sz)) d' with | Exceptions.Too_many_concrete_elements _ as e -> L.exc_and_abort e (fun p -> p "(s)printf: Unknown address of the format string or imprecise value of the format string") | Not_found as e -> L.exc_and_abort e (fun p -> p "address of the null terminator in the format string in (s)printf not found") let sprintf (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let dst = Asm.Lval (args 0) in let format_addr = Asm.Lval (args 1) in let va_args = shift args 2 in print d ret format_addr va_args (Some dst) let sprintf_chk (_ip: Data.Address.t) _ (d: domain_t) ret args: domain_t * Taint.Set.t = let dst = Asm.Lval (args 0) in let format_addr = Asm.Lval (args 3) in let va_args = shift args 4 in print d ret format_addr va_args (Some dst) let printf (_ip: Data.Address.t) _ d ret args = let format_addr = Asm.Lval (args 0) in let va_args = shift args 1 in let d', is_tainted = print d ret format_addr va_args None in d', is_tainted let printf_chk (ip: Data.Address.t) calling_ip d ret args = printf ip calling_ip d ret (shift args 1) let puts (_ip: Data.Address.t) _ d ret args = let str = Asm.Lval (args 0) in let len, d' = D.print_until d str (Asm.Const (Data.Word.of_int Z.zero 8)) 8 10000 true None in let d', taint = D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d' in Log.Stdout.stdout (fun p -> p "\n"); d', taint let write _ip _ d ret args = let fd = try Z.to_int (D.value_of_exp d (Asm.Lval (args 0))) with _ -> L.abort (fun p -> p "imprecise file descriptor as argument of write") in if fd = 1 then let buf = Asm.Lval (args 1) in try let char_nb = Z.to_int (D.value_of_exp d (Asm.Lval (args 2))) in let d', len = D.print_chars d buf char_nb None in let d', taint = D.set ret (Asm.Const (Data.Word.of_int (Z.of_int len) !Config.operand_sz)) d' in d', taint with Exceptions.Too_many_concrete_elements _ -> L.abort (fun p -> p "imprecise number of char to write") else L.abort (fun p -> p "write output implemented only for stdout") let stubs = Hashtbl.create 5 let signal_process d call_conv: domain_t * Taint.Set.t * Asm.stmt list = let args = call_conv.Asm.arguments in let d, taint, stmts = try let int_nb = Z.to_int (D.value_of_exp d (Asm.Lval (args 0))) in let addrs, taint = D.mem_to_addresses d (Asm.Lval (args 1)) in match Data.Address.Set.elements addrs with | [a] -> d, taint, [Asm.Directive (Asm.Handler (int_nb, a))] | _ -> raise (Exceptions.Too_many_concrete_elements "several possible handler addresses") with Exceptions.Too_many_concrete_elements _ -> L.warn (fun p -> p "uncomputable argument of signal call (signal number or handler address). Skipped"); d, Taint.Set.singleton Taint.U, [] in let cleanup_stmts = (call_conv.Asm.callee_cleanup 2) in d, taint, stmts@cleanup_stmts let putchar (_ip) _ d ret args = let str = Asm.Lval (args 0) in let d' = D.print d str !Config.operand_sz in D.set ret (Asm.Const (Data.Word.of_int Z.one !Config.operand_sz)) d' let getc _ _ d ret _ = let d' = D.forget_lval ret d in if !Config.taint_input then let taint_mask = Taint.S (Taint.SrcSet.singleton (Taint.Src.Tainted (Taint.Src.new_src()))) in D.taint_lval ret taint_mask d' else d', Taint.Set.singleton Taint.U let getchar = getc let bin_exit (_ip) _ _d _ret _args = raise (Exceptions.Stop "on exit call") let process ip calling_ip d fun_name call_conv: domain_t * Taint.Set.t * Asm.stmt list = if String.compare fun_name "signal" = 0 then signal_process d call_conv else let apply_f, arg_nb = try Hashtbl.find stubs fun_name with Not_found -> L.abort (fun p -> p "No stub available for function [%s]" fun_name) in let d', taint = try apply_f ip calling_ip d call_conv.Asm.return call_conv.Asm.arguments with | Exit -> d, Taint.Set.singleton Taint.U | Exceptions.Use_after_free _ as e -> raise e | Exceptions.Double_free -> raise Exceptions.Double_free | Exceptions.Null_deref _ as e -> raise e | Exceptions.Stop _ as e -> raise e | Exceptions.Error _ as e -> raise e | e -> L.exc e (fun p -> p "error while processing stub [%s]" fun_name); L.warn (fun p -> p "uncomputable stub for [%s]. Skipped." fun_name); d, Taint.Set.singleton Taint.U in let cleanup_stmts = (call_conv.Asm.callee_cleanup arg_nb) in d', taint, cleanup_stmts let skip d f call_conv: domain_t * Taint.Set.t * Asm.stmt list = let arg_nb, ret_val = Hashtbl.find Config.funSkipTbl f in let d, taint = match ret_val with | None -> D.forget_lval call_conv.Asm.return d, Taint.Set.singleton Taint.TOP | Some ret_val' -> let sz = Config.size_of_config ret_val' in match call_conv.Asm.return with | Asm.V (Asm.T r) when Register.size r = sz -> D.set_register_from_config r ret_val' d | Asm.M (e, n) when sz = n -> let addrs, _ = D.mem_to_addresses d e in let d', taint' = match Data.Address.Set.elements addrs with | [a] -> D.set_memory_from_config a ret_val' 1 d in d', taint' in let cleanup_stmts = call_conv.Asm.callee_cleanup (Z.to_int arg_nb) in d,taint, cleanup_stmts let default_handler sig_nb = see man 7 signal . Implementation of POSIX.1 - 2001 let ignore_sig sig_text = L.analysis (fun p -> p "Handling signal %s: ignored" sig_text); [] in let abort sig_text = L.analysis (fun p -> p "Handling signal %s: analysis stops" sig_text); L.abort (fun p -> p "see above") in match sig_nb with SIGQUIT SIGIL SIGTRAP SIGKILL SIGALRM SIGTERM SIGCHLD SIGTSTP SIGTTIN SIGTTOU | _ -> L.analysis (fun p -> p "received Illegal signal %d. Ignored" sig_nb); [] let init () = Hashtbl.replace stubs "memcpy" (memcpy, 3); Hashtbl.replace stubs "memcmp" (memcmp, 3); Hashtbl.replace stubs "memset" (memset, 3); Hashtbl.replace stubs "sprintf" (sprintf, 0); Hashtbl.replace stubs "printf" (printf, 0); Hashtbl.replace stubs "write" (write, 3); Hashtbl.replace stubs "__sprintf_chk" (sprintf_chk, 0); Hashtbl.replace stubs "__printf_chk" (printf_chk, 0); Hashtbl.replace stubs "puts" (puts, 1); Hashtbl.replace stubs "strlen" (strlen, 1); Hashtbl.replace stubs "putchar" (putchar, 1); Hashtbl.replace stubs "getchar" (getchar, 0); Hashtbl.replace stubs "getc" (getc, 1); Hashtbl.replace stubs "exit" (bin_exit, 1); Hashtbl.replace stubs "malloc" (heap_allocator, 1); Hashtbl.replace stubs "free" (heap_deallocator, 1);; end
84611d7cd0d4bea06b75334db39789d31419bc5663efc284a01b630390441585
ZHaskell/stdio
Aeson.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Data.Aeson import Control.Monad import Data.Attoparsec.ByteString (IResult(..), parseWith) import Data.Time.Clock import System.Environment (getArgs) import System.IO import qualified Data.ByteString as B main :: IO () main = do (bs:cnt:args) <- getArgs let count = read cnt :: Int blkSize = read bs forM_ args $ \arg -> withFile arg ReadMode $ \h -> do putStrLn $ arg ++ ":" start <- getCurrentTime let loop !good !bad | good+bad >= count = return (good, bad) | otherwise = do hSeek h AbsoluteSeek 0 let refill = B.hGet h blkSize result <- parseWith refill json' =<< refill case result of Done _ _ -> loop (good+1) bad _ -> loop good (bad+1) (good, _) <- loop 0 0 delta <- flip diffUTCTime start `fmap` getCurrentTime putStrLn $ " " ++ show good ++ " good, " ++ show delta let rate = fromIntegral count / realToFrac delta :: Double putStrLn $ " " ++ show (round rate :: Int) ++ " per second"
null
https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/bench/json/Aeson.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings #
module Main (main) where import Data.Aeson import Control.Monad import Data.Attoparsec.ByteString (IResult(..), parseWith) import Data.Time.Clock import System.Environment (getArgs) import System.IO import qualified Data.ByteString as B main :: IO () main = do (bs:cnt:args) <- getArgs let count = read cnt :: Int blkSize = read bs forM_ args $ \arg -> withFile arg ReadMode $ \h -> do putStrLn $ arg ++ ":" start <- getCurrentTime let loop !good !bad | good+bad >= count = return (good, bad) | otherwise = do hSeek h AbsoluteSeek 0 let refill = B.hGet h blkSize result <- parseWith refill json' =<< refill case result of Done _ _ -> loop (good+1) bad _ -> loop good (bad+1) (good, _) <- loop 0 0 delta <- flip diffUTCTime start `fmap` getCurrentTime putStrLn $ " " ++ show good ++ " good, " ++ show delta let rate = fromIntegral count / realToFrac delta :: Double putStrLn $ " " ++ show (round rate :: Int) ++ " per second"
4a2398ab30ce218872c803efcc16792fbfb037b927bff9bc216eb6eaccc2adb0
wanishing/sap
yaml.clj
(ns sap.commands.yaml (:require [clj-yaml.core :as yaml] [sap.client :refer [fetch-yaml fetch-fresh-yaml]])) (defn yaml [{:keys [id]} {:keys [fresh]}] (let [yml (if (some? fresh) (fetch-fresh-yaml id) (fetch-yaml id))] (println (yaml/generate-string yml))))
null
https://raw.githubusercontent.com/wanishing/sap/1d4c9f8c8a648eec9e09cf87b900b854ba483e42/src/sap/commands/yaml.clj
clojure
(ns sap.commands.yaml (:require [clj-yaml.core :as yaml] [sap.client :refer [fetch-yaml fetch-fresh-yaml]])) (defn yaml [{:keys [id]} {:keys [fresh]}] (let [yml (if (some? fresh) (fetch-fresh-yaml id) (fetch-yaml id))] (println (yaml/generate-string yml))))
e7d8955774afd680863dcba798e6295ccb3a523a8a9a8ca33b426442528a47ed
bramford/2d-exploration-game
entity_lib.mli
module type Entity = sig type t val symbol : string val name : string val fg : t -> Notty.A.color val to_string : t -> string val random : int -> t val draw : t -> Notty.image end
null
https://raw.githubusercontent.com/bramford/2d-exploration-game/0660ced6ec4aa39d4548b0ecc1f20f8269bf4c6b/src/entity_lib.mli
ocaml
module type Entity = sig type t val symbol : string val name : string val fg : t -> Notty.A.color val to_string : t -> string val random : int -> t val draw : t -> Notty.image end
63e2d2374b376fe02c8a584dc35120afec006e08e3511486e1cb5b14dbb9aeb6
racket/rhombus-prototype
define-arity.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse/pre) "expression.rkt" "static-info.rkt" "function-arity-key.rkt") (provide define/arity) (define-syntax (define/arity stx) (syntax-parse stx [(_ #:name name (id . args) (~optional (~seq #:static-infos (si ...)) #:defaults ([(si 1) '()])) . body) #'(begin (define id (let ([name (lambda args . body)]) name)) (define-static-info-syntax id (#%function-arity #,(extract-arity #'args)) si ...))] [(_ (id . args) (~optional (~seq #:static-infos (si ...)) #:defaults ([(si 1) '()])) . body) #'(begin (define (id . args) . body) (define-static-info-syntax id (#%function-arity #,(extract-arity #'args)) si ...))])) (define-for-syntax (extract-arity args) (let loop ([args args] [mask 1]) (syntax-parse args [() mask] [(_:identifier . args) (loop #'args (arithmetic-shift mask 1))] [([_:identifier _] . args) (bitwise-ior mask (loop #'args (arithmetic-shift mask 1)))] [_:identifier (bitwise-not (sub1 (arithmetic-shift mask 1)))])))
null
https://raw.githubusercontent.com/racket/rhombus-prototype/60070a3edd2b850bf429298b84b66eee3ea79194/rhombus/private/define-arity.rkt
racket
#lang racket/base (require (for-syntax racket/base syntax/parse/pre) "expression.rkt" "static-info.rkt" "function-arity-key.rkt") (provide define/arity) (define-syntax (define/arity stx) (syntax-parse stx [(_ #:name name (id . args) (~optional (~seq #:static-infos (si ...)) #:defaults ([(si 1) '()])) . body) #'(begin (define id (let ([name (lambda args . body)]) name)) (define-static-info-syntax id (#%function-arity #,(extract-arity #'args)) si ...))] [(_ (id . args) (~optional (~seq #:static-infos (si ...)) #:defaults ([(si 1) '()])) . body) #'(begin (define (id . args) . body) (define-static-info-syntax id (#%function-arity #,(extract-arity #'args)) si ...))])) (define-for-syntax (extract-arity args) (let loop ([args args] [mask 1]) (syntax-parse args [() mask] [(_:identifier . args) (loop #'args (arithmetic-shift mask 1))] [([_:identifier _] . args) (bitwise-ior mask (loop #'args (arithmetic-shift mask 1)))] [_:identifier (bitwise-not (sub1 (arithmetic-shift mask 1)))])))
f0f465f66d4956e000bf3b61e70b0708a71de96c36b98e24453ccc0757e50875
locusmath/locus
cone.clj
(ns locus.set.copresheaf.topoi.copresheaf.cone (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.limit.product :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.order.lattice.core.object :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.copresheaf.quiver.unital.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.natural.transformation :refer :all] [locus.set.copresheaf.topoi.copresheaf.object :refer :all] [locus.set.copresheaf.topoi.copresheaf.morphism :refer :all]) (:import (locus.algebra.category.core.morphism Functor))) A morphism of copresheaves from a constant copresheaf to another copresheaf A set cone is also a special type of morphism of copresheaves . (deftype SetCone [source-object target-functor func] AbstractMorphism (source-object [this] (constant-copresheaf (index target-functor) source-object)) (target-object [this] target-functor) clojure.lang.IFn (invoke [this arg] (func arg)) (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) ; Get the index category of a cone in the topos of sets (defmethod index SetCone [^SetCone cone] (category-product t2 (index (target-object cone)))) Convert a set cone into a morphism of copresheaves (defmethod to-morphism-of-copresheaves SetCone [^SetCone cone] (->MorphismOfCopresheaves (source-object cone) (target-object cone) (.-func cone))) (defmethod to-copresheaf SetCone [^SetCone cone] (to-copresheaf (to-morphism-of-copresheaves cone))) ; Create a set product cone (defn set-product-cone [& sets] (let [origin (apply product sets)] (->SetCone origin (nset-copresheaf sets) (fn [i] (->SetFunction origin (nth sets i) (fn [coll] (nth coll i))))))) ; Ontology of set cones (defn set-cone? [obj] (= (type obj) SetCone))
null
https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/set/copresheaf/topoi/copresheaf/cone.clj
clojure
Get the index category of a cone in the topos of sets Create a set product cone Ontology of set cones
(ns locus.set.copresheaf.topoi.copresheaf.cone (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.limit.product :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.order.lattice.core.object :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.copresheaf.quiver.unital.object :refer :all] [locus.algebra.category.core.morphism :refer :all] [locus.algebra.category.core.object :refer :all] [locus.algebra.category.natural.transformation :refer :all] [locus.set.copresheaf.topoi.copresheaf.object :refer :all] [locus.set.copresheaf.topoi.copresheaf.morphism :refer :all]) (:import (locus.algebra.category.core.morphism Functor))) A morphism of copresheaves from a constant copresheaf to another copresheaf A set cone is also a special type of morphism of copresheaves . (deftype SetCone [source-object target-functor func] AbstractMorphism (source-object [this] (constant-copresheaf (index target-functor) source-object)) (target-object [this] target-functor) clojure.lang.IFn (invoke [this arg] (func arg)) (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) (defmethod index SetCone [^SetCone cone] (category-product t2 (index (target-object cone)))) Convert a set cone into a morphism of copresheaves (defmethod to-morphism-of-copresheaves SetCone [^SetCone cone] (->MorphismOfCopresheaves (source-object cone) (target-object cone) (.-func cone))) (defmethod to-copresheaf SetCone [^SetCone cone] (to-copresheaf (to-morphism-of-copresheaves cone))) (defn set-product-cone [& sets] (let [origin (apply product sets)] (->SetCone origin (nset-copresheaf sets) (fn [i] (->SetFunction origin (nth sets i) (fn [coll] (nth coll i))))))) (defn set-cone? [obj] (= (type obj) SetCone))
9283fa353d650b3567192341c23fcc5ab418c56d6c2918779cb44b4811c73cc1
vehicle-lang/vehicle
NoThunks.hs
# LANGUAGE CPP # module Vehicle.Syntax.AST.Instances.NoThunks where #if nothunks import Vehicle.Syntax.AST.Arg import Vehicle.Syntax.AST.Binder import Vehicle.Syntax.AST.Builtin import Vehicle.Syntax.AST.Builtin.Core import Vehicle.Syntax.AST.Builtin.TypeClass import Vehicle.Syntax.AST.Decl import Vehicle.Syntax.AST.Expr import Vehicle.Syntax.AST.Meta import Vehicle.Syntax.AST.Name import Vehicle.Syntax.AST.Prog import Vehicle.Syntax.AST.Provenance import Vehicle.Syntax.AST.Relevance import Vehicle.Syntax.AST.Visibility import NoThunks.Class (NoThunks) Vehicle . Syntax . AST.Builtin . Core instance NoThunks FunctionPosition instance NoThunks EqualityOp instance NoThunks EqualityDomain instance NoThunks OrderOp instance NoThunks OrderDomain instance NoThunks Quantifier -- Now Vehicle.Compile.Type.Subsystem.Linearity.Core instance instance NoThunks Linearity instance LinearityTypeClass -- Now Vehicle.Compile.Type.Subsystem.Polarity.Core instance instance NoThunks Polarity instance PolarityTypeClass Vehicle . Syntax . AST.Builtin . TypeClass instance NoThunks TypeClass instance NoThunks TypeClassOp -- Vehicle.Syntax.AST.Arg instance NoThunks expr => NoThunks (GenericArg expr) -- Vehicle.Syntax.AST.Binder instance NoThunks BinderNamingForm instance NoThunks BinderDisplayForm instance (NoThunks binder, NoThunks expr) => NoThunks (GenericBinder binder expr) Vehicle . Syntax . AST.Builtin instance NoThunks BuiltinConstructor instance NoThunks BuiltinFunction instance NoThunks BuiltinType instance NoThunks NegDomain instance NoThunks AddDomain instance NoThunks SubDomain instance NoThunks MulDomain instance NoThunks DivDomain instance NoThunks FromNatDomain instance NoThunks FromRatDomain instance NoThunks FoldDomain instance NoThunks QuantifierDomain instance NoThunks Builtin instance NoThunks Resource -- Vehicle.Syntax.AST.Decl instance NoThunks expr => NoThunks (GenericDecl expr) -- Vehicle.Syntax.AST.Expr instance NoThunks UniverseLevel instance (NoThunks binder, NoThunks var, NoThunks builtin) => NoThunks (Expr binder var builtin) Vehicle . Syntax . AST.Meta instance NoThunks MetaID -- Vehicle.Syntax.AST.Name instance NoThunks Module instance NoThunks Identifier -- Vehicle.Syntax.AST.Prog instance NoThunks expr => NoThunks (GenericProg expr) -- Vehicle.Syntax.AST.Provenance instance NoThunks Position instance NoThunks Range instance NoThunks Origin instance NoThunks Provenance Vehicle . Syntax . AST.Relevance instance NoThunks Relevance -- Vehicle.Syntax.AST.Visibility instance NoThunks Visibility #endif
null
https://raw.githubusercontent.com/vehicle-lang/vehicle/3a3548f9b48c3969212ccb51e954d4d4556ea815/vehicle-syntax/src/Vehicle/Syntax/AST/Instances/NoThunks.hs
haskell
Now Vehicle.Compile.Type.Subsystem.Linearity.Core Now Vehicle.Compile.Type.Subsystem.Polarity.Core Vehicle.Syntax.AST.Arg Vehicle.Syntax.AST.Binder Vehicle.Syntax.AST.Decl Vehicle.Syntax.AST.Expr Vehicle.Syntax.AST.Name Vehicle.Syntax.AST.Prog Vehicle.Syntax.AST.Provenance Vehicle.Syntax.AST.Visibility
# LANGUAGE CPP # module Vehicle.Syntax.AST.Instances.NoThunks where #if nothunks import Vehicle.Syntax.AST.Arg import Vehicle.Syntax.AST.Binder import Vehicle.Syntax.AST.Builtin import Vehicle.Syntax.AST.Builtin.Core import Vehicle.Syntax.AST.Builtin.TypeClass import Vehicle.Syntax.AST.Decl import Vehicle.Syntax.AST.Expr import Vehicle.Syntax.AST.Meta import Vehicle.Syntax.AST.Name import Vehicle.Syntax.AST.Prog import Vehicle.Syntax.AST.Provenance import Vehicle.Syntax.AST.Relevance import Vehicle.Syntax.AST.Visibility import NoThunks.Class (NoThunks) Vehicle . Syntax . AST.Builtin . Core instance NoThunks FunctionPosition instance NoThunks EqualityOp instance NoThunks EqualityDomain instance NoThunks OrderOp instance NoThunks OrderDomain instance NoThunks Quantifier instance instance NoThunks Linearity instance LinearityTypeClass instance instance NoThunks Polarity instance PolarityTypeClass Vehicle . Syntax . AST.Builtin . TypeClass instance NoThunks TypeClass instance NoThunks TypeClassOp instance NoThunks expr => NoThunks (GenericArg expr) instance NoThunks BinderNamingForm instance NoThunks BinderDisplayForm instance (NoThunks binder, NoThunks expr) => NoThunks (GenericBinder binder expr) Vehicle . Syntax . AST.Builtin instance NoThunks BuiltinConstructor instance NoThunks BuiltinFunction instance NoThunks BuiltinType instance NoThunks NegDomain instance NoThunks AddDomain instance NoThunks SubDomain instance NoThunks MulDomain instance NoThunks DivDomain instance NoThunks FromNatDomain instance NoThunks FromRatDomain instance NoThunks FoldDomain instance NoThunks QuantifierDomain instance NoThunks Builtin instance NoThunks Resource instance NoThunks expr => NoThunks (GenericDecl expr) instance NoThunks UniverseLevel instance (NoThunks binder, NoThunks var, NoThunks builtin) => NoThunks (Expr binder var builtin) Vehicle . Syntax . AST.Meta instance NoThunks MetaID instance NoThunks Module instance NoThunks Identifier instance NoThunks expr => NoThunks (GenericProg expr) instance NoThunks Position instance NoThunks Range instance NoThunks Origin instance NoThunks Provenance Vehicle . Syntax . AST.Relevance instance NoThunks Relevance instance NoThunks Visibility #endif
ba8beec4393f872e8309889437d50c0c65dfd52d1b610acdc4dec74deb60eb98
ocaml-gospel/gospel
char1.mli
val f : char -> unit (*@ f c requires c = '\' *) { gospel_expected| [ 125 ] File " char1.mli " , line 3 , characters 17 - 18 : 3 | requires c = ' \ ' [125] File "char1.mli", line 3, characters 17-18: 3 | requires c = '\' *) ^ Error: Illegal character `''. |gospel_expected} *)
null
https://raw.githubusercontent.com/ocaml-gospel/gospel/79841c510baeb396d9a695ae33b290899188380b/test/negative/char1.mli
ocaml
@ f c requires c = '\'
val f : char -> unit { gospel_expected| [ 125 ] File " char1.mli " , line 3 , characters 17 - 18 : 3 | requires c = ' \ ' [125] File "char1.mli", line 3, characters 17-18: 3 | requires c = '\' *) ^ Error: Illegal character `''. |gospel_expected} *)
0c8d70e96cfe418b9052b7900e6b816a9f2d01a233e3294ea674e47f83359e4b
PacktWorkshops/The-Clojure-Workshop
core.clj
(ns hello-leiningen.core (:require [java-time :as time]) (:gen-class)) (defn -main "Display current local time" [& args] (println (time/local-time)))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter08/tests/Exercise8.12/hello-leiningen/src/hello_leiningen/core.clj
clojure
(ns hello-leiningen.core (:require [java-time :as time]) (:gen-class)) (defn -main "Display current local time" [& args] (println (time/local-time)))
67f83f5e94a4de321d0a21bb00f93b5c56b13bd8d28c69f8af0a325575d6b458
TheLortex/mirage-monorepo
mirage_net.ml
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * Copyright ( c ) 2018 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * Copyright (c) 2018 Hannes Mehnert <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Net = struct exception Invalid_length of int end type stats = { mutable rx_bytes : int64; mutable rx_pkts : int32; mutable tx_bytes : int64; mutable tx_pkts : int32; } module Stats = struct let create () = { rx_pkts = 0l; rx_bytes = 0L; tx_pkts = 0l; tx_bytes = 0L } let rx t size = t.rx_pkts <- Int32.succ t.rx_pkts; t.rx_bytes <- Int64.add t.rx_bytes size let tx t size = t.tx_pkts <- Int32.succ t.tx_pkts; t.tx_bytes <- Int64.add t.tx_bytes size let reset t = t.rx_bytes <- 0L; t.rx_pkts <- 0l; t.tx_bytes <- 0L; t.tx_pkts <- 0l end module type S = sig type t val disconnect : t -> unit val writev : t -> Cstruct.t list -> unit val listen : t -> header_size:int -> (Cstruct.t -> unit) -> unit val mac : t -> Macaddr.t val mtu : t -> int val get_stats_counters : t -> stats val reset_stats_counters : t -> unit end
null
https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/mirage-net/src/mirage_net.ml
ocaml
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * Copyright ( c ) 2018 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * Copyright (c) 2018 Hannes Mehnert <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Net = struct exception Invalid_length of int end type stats = { mutable rx_bytes : int64; mutable rx_pkts : int32; mutable tx_bytes : int64; mutable tx_pkts : int32; } module Stats = struct let create () = { rx_pkts = 0l; rx_bytes = 0L; tx_pkts = 0l; tx_bytes = 0L } let rx t size = t.rx_pkts <- Int32.succ t.rx_pkts; t.rx_bytes <- Int64.add t.rx_bytes size let tx t size = t.tx_pkts <- Int32.succ t.tx_pkts; t.tx_bytes <- Int64.add t.tx_bytes size let reset t = t.rx_bytes <- 0L; t.rx_pkts <- 0l; t.tx_bytes <- 0L; t.tx_pkts <- 0l end module type S = sig type t val disconnect : t -> unit val writev : t -> Cstruct.t list -> unit val listen : t -> header_size:int -> (Cstruct.t -> unit) -> unit val mac : t -> Macaddr.t val mtu : t -> int val get_stats_counters : t -> stats val reset_stats_counters : t -> unit end
05c05b1e84a20b459ddf713b3058755e700db801a0bc9eb91efee212d3b1b481
deadpendency/deadpendency
QueuePayload.hs
module Common.Effect.QueueEventPublish.Model.QueuePayload ( QueuePayload (..), ) where import Data.Aeson data QueuePayload where QueuePayload :: (ToJSON a) => a -> QueuePayload RawQueuePayload :: ByteString -> QueuePayload
null
https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/Effect/QueueEventPublish/Model/QueuePayload.hs
haskell
module Common.Effect.QueueEventPublish.Model.QueuePayload ( QueuePayload (..), ) where import Data.Aeson data QueuePayload where QueuePayload :: (ToJSON a) => a -> QueuePayload RawQueuePayload :: ByteString -> QueuePayload
ebafc084a291045f54eff0e249e132d3418e51bd25c64108e6730335cd0c512e
samply/blaze
spec.clj
(ns blaze.handler.fhir.util.spec (:require [clojure.spec.alpha :as s])) (s/def :ring.request.query-params/key string?) (s/def :ring.request.query-params/value (s/or :string string? :strings (s/coll-of string? :min-count 2))) (s/def :ring.request/query-params (s/map-of :ring.request.query-params/key :ring.request.query-params/value))
null
https://raw.githubusercontent.com/samply/blaze/948eee38021467fa343c522a644a7fd4b24b6467/modules/rest-util/src/blaze/handler/fhir/util/spec.clj
clojure
(ns blaze.handler.fhir.util.spec (:require [clojure.spec.alpha :as s])) (s/def :ring.request.query-params/key string?) (s/def :ring.request.query-params/value (s/or :string string? :strings (s/coll-of string? :min-count 2))) (s/def :ring.request/query-params (s/map-of :ring.request.query-params/key :ring.request.query-params/value))
9a1f544a1e1a5d8052b4bdad7e94c8dc825f34fe35e51525c924e502831693fe
hyperfiddle/electric
data.cljc
(ns contrib.data (:require clojure.math [clojure.datafy :refer [datafy]] ; todo remove [hyperfiddle.rcf :refer [tests]]) #?(:cljs (:require-macros [contrib.data :refer [auto-props]]))) (defn qualify "Qualify a keyword with a namespace. If already qualified, leave kw untouched. Nil-safe. (qualify :db :isComponent) -> :db/isComponent" [ns ?kw] {:pre [(some? ns) #_(not (namespace ns)) (keyword? ?kw)]} (when ?kw (if (qualified-keyword? ?kw) ?kw (keyword (name ns) (name ?kw))))) (tests ;(keyword (name (namespace ::ns)) (name :limit)) (qualify (namespace ::x) :limit) := ::limit ( qualify ( namespace : :x ) " limit " ) thrown ? AssertionError "leave qualified kws untouched" (qualify (namespace ::x) :user/foo) := :user/foo) (defn unqualify "Strip namespace from keyword, discarding it and return unqualified keyword. Nil-safe. (unqualify :db.type/ref) -> :ref" [?qualified-kw] (assert (or (nil? ?qualified-kw) (qualified-keyword? ?qualified-kw)) (str " can't unqualify: " ?qualified-kw)) (if ?qualified-kw (keyword (name ?qualified-kw)))) (tests (unqualify ::x) := :x (unqualify :db.type/ref) := :ref (unqualify nil) := nil (unqualify "") :throws #?(:clj AssertionError :cljs js/Error)) (defn -omit-keys-ns [ns ?m] {:pre [(some? ns)]} (when ?m (reduce-kv (fn [m k v] (if (= (name ns) (namespace k)) m (assoc m k v))) {} ?m))) (defmacro omit-keys-ns ([?m] `(-omit-keys-ns ~(str *ns*) ~?m)) ([ns- ?m] `(-omit-keys-ns ~ns- ~?m))) (tests (omit-keys-ns :c {::a 1 :b 2 :c/c 3}) := {::a 1 :b 2} (omit-keys-ns :c {::a 1 :b 2 :c/c 3}) := {::a 1 :b 2} (omit-keys-ns :c nil) := nil (omit-keys-ns nil {::a 1 :b 2 :c/c 3}) :throws #?(:clj AssertionError :cljs js/Error) (omit-keys-ns nil nil) :throws #?(:clj AssertionError :cljs js/Error) nil) (defn has-ns? "State if a `named` value (keyword or symbol) has such namespace `ns`. `ns` can be be a string, or a non-namespaced keyword or symbol." [ns named] {:pre [(or (string? ns) (simple-ident? ns))]} (= (name ns) (namespace named))) (defn select-ns "Like `select-keys` but select all namespaced keys by ns." [ns map] (into (empty map) (filter (fn [[k _v]] (has-ns? ns k))) map)) (defn -auto-props "qualify any unqualified keys to the current ns and then add qualified defaults" [ns props defaults-qualified] {:pre [(some? ns) (or (string? ns) (symbol? ns))]} (merge defaults-qualified (update-keys props (partial qualify ns)))) (defmacro auto-props ([ns props defaults-qualified] `(-auto-props ~ns ~props ~defaults-qualified)) ([props defaults-qualified] `(-auto-props ~(str *ns*) ~props ~defaults-qualified)) ([props] `(-auto-props ~(str *ns*) ~props {}))) (tests (auto-props "user" {:a 1} {:dom/class "a"}) := {:user/a 1 :dom/class "a"} (auto-props 'user {:a 1} {:dom/class "a"}) := {:user/a 1 :dom/class "a"} (auto-props *ns* {:a 1} {:dom/class "a"}) :throws #?(:clj AssertionError :cljs js/Error) (auto-props {:a 1} {:dom/class "a"}) := {:contrib.data/a 1 :dom/class "a"} (auto-props {:a 1}) := {:contrib.data/a 1}) (defn xorxs "an argument parser that accepts both scalars and collections, lifting scalars into a collection" [xorxs & [zero]] (cond (vector? xorxs) xorxs (set? xorxs) xorxs (seq? xorxs) xorxs (nil? xorxs) zero :else-single-value-or-map (conj (or zero []) xorxs))) (tests (xorxs :a) := [:a] (xorxs [:a]) := [:a] (xorxs #{:a}) := #{:a} (xorxs :a #{}) := #{:a} (xorxs :a []) := [:a] (xorxs nil #{}) := #{} (xorxs nil) := nil) (defn index-by [kf xs] {:pre [kf]} (into {} (map-indexed (fn [i x] [(kf x i) ; fallback to index when key is not present #_(if-not kf (kf x i) i) ; alternative design is to define nil kf as fallback x])) xs)) (tests (def xs [{:db/ident :foo :a 1} {:db/ident :bar :b 2}]) (index-by :db/ident xs) := {:foo {:db/ident :foo, :a 1}, :bar {:db/ident :bar, :b 2}} (index-by ::missing xs) ; should this throw? := {0 {:db/ident :foo, :a 1}, 1 {:db/ident :bar, :b 2}} ;"nil kf uses default value (which is likely unintended, should it throw?)" ;(index-by nil xs) : = { 0 { : db / ident : foo , : a 1 } , 1 { : db / ident : bar , : b 2 } } (index-by :a nil) := {} ;(index-by nil nil) := {} ; kf never used -- alternative design (index-by nil nil) :throws #?(:clj AssertionError :cljs js/Error) (index-by :a [{}]) := {0 {}} (index-by :a [{:a 1}]) := {1 {:a 1}} (index-by :b [{:a 1}]) := {0 {:a 1}} ; missing key, fallback to index "indexing map entries (which is weird, should this throw?)" (index-by :a {:a 1}) := {0 [:a 1]} ; index the map entry, not the map, :a is missing so fallback (index-by :b {:a 1}) := {0 [:a 1]} "collisions are possible" (index-by :db/id [{:db/id 1} {:db/id 2} {:db/id 1}]) ; should this detect collision and throw? := {1 #:db{:id 1}, 2 #:db{:id 2}} "kf fallback arity" (index-by (fn [x i] (str i)) xs) := {"0" {:db/ident :foo, :a 1}, "1" {:db/ident :bar, :b 2}} "index by first element" ( index - by first [ [: a 1 ] [: b 2 ] ] ) -- ArityException : kf must accept fallback . Is this a mistake ? (index-by (fn [a b] (first a)) [[:a 1] [:b 2]]) := {:a [:a 1], :b [:b 2]} (index-by #(do %2 (first %1)) [[:a 1] [:b 2]]) := {:a [:a 1], :b [:b 2]}) (defn index "index a sequential collection into an associative collection with explicit keys. this may not be useful, as vectors are already associative" [xs] (assert (sequential? xs)) ; maps are not indexable (index-by (fn [x i] i) xs)) (tests (def xs [{:db/ident :foo :a 1} {:db/ident :bar :b 2}]) (index xs) := {0 {:db/ident :foo, :a 1}, 1 {:db/ident :bar, :b 2}}) (defn group-by-pred [f? xs] ; todo rename (let [{a true b false} (group-by f? xs)] [a b])) (tests (group-by-pred map? [:user/email {:user/gender [:db/ident]} {:user/shirt-size [:db/ident]} :db/id]) := [[#:user{:gender [:db/ident]} #:user{:shirt-size [:db/ident]}] [:user/email :db/id]]) (defn update-existing [m k f & args] (if (get m k) (apply update m k f args) m)) (tests (update-existing {:a 1} :a + 10) := {:a 11} (update-existing {:a 1} :b + 10) := {:a 1}) ( defn positional " Transform an array - like map { 0 : foo , 1 : bar , ... } with contiguous array keys ( 0 , 1 , ... ) into ; list [:foo :bar]" [ amap ] ( - > > ( range ( inc ( count amap ) ) ) ( reduce ( fn [ acc idx ] ( if ( contains ? amap idx ) ( conj acc ( get amap idx ) ) ( reduced acc ) ) ) ; []) ; (seq))) ; ( tests ( positional { 0 : foo 1 : bar } ) : = [ : foo : bar ] ) (defn round-floor [n base] (* base (clojure.math/floor (/ n base)))) (comment "base 10" (round-floor 89 10) := 80.0 (round-floor 90 10) := 90.0 (round-floor 91 10) := 90.0 (round-floor 99 10) := 90.0 (round-floor 100 10) := 100.0 "base 8" (round-floor 7 8) := 0.0 (round-floor 8 8) := 8.0 (round-floor 9 8) := 8.0 (round-floor 15 8) := 8.0 (round-floor 16 8) := 16.0 (round-floor 1234567 1000) := 1234000.0) (defn pad ([zero coll] (concat coll (repeat zero))) ([n zero coll] (take n (pad zero coll)))) (defn padl [n zero coll] (concat (repeat (- n (count coll)) zero) coll)) (tests (pad 8 0 (range 3)) := [0 1 2 0 0 0 0 0] (padl 8 0 (range 3)) := [0 0 0 0 0 0 1 2] "strings leak platform internals, use padl-str" (pad 8 "0" "xx") := #?(:clj [\x \x "0" "0" "0" "0" "0" "0"] :cljs ["x" "x" "0" "0" "0" "0" "0" "0"]) (padl 8 "0" "xx") := #?(:clj ["0" "0" "0" "0" "0" "0" \x \x] :cljs ["0" "0" "0" "0" "0" "0" "x" "x"])) (defn assoc-vec [xs k v] (if (>= k (count xs)) (assoc (vec (pad k nil xs)) k v) (assoc xs k v))) (tests (assoc-vec [] 0 :a) := [:a] (assoc-vec [] 1 :b) := [nil :b] (assoc-vec [] 4 :e) := [nil nil nil nil :e] (assoc-vec nil 4 :e) := [nil nil nil nil :e] (assoc-vec [:a :b :c] 1 :B) := [:a :B :c] (assoc-vec [:a :b :c] 4 :E) := [:a :b :c nil :E]) (defn padl-str [n zero s] (apply str (padl n zero s))) (tests (padl-str 8 "0" "xx") := "000000xx" (padl-str 4 "0" (str 11)) := "0011") (defn with-pad [reducer zero] (fn [f & cols] (let [n (apply max (map count cols)) cols (map #(pad n zero %) cols)] (apply reducer f cols)))) (def map-pad (partial with-pad map)) (tests (map + [1 1 1] [1 1 1 1]) := '(2 2 2) ((map-pad 0) + [1 1 1] [1 1 1 1]) := '(2 2 2 1)) (defn str-last-n [n s] #?(:clj (.substring s (max 0 (- (.length s) n))) :cljs (apply str (reverse (take n (reverse s)))))) (tests (str-last-n 4 "0123456789") := "6789") ; org.apache.commons.lang3.StringUtils.containsIgnoreCase() ( - contains - ignore - case [ ] ) ( defn clamp [ n min max ] ( Math / min ( Math / max n min ) ) ) ; ;(tests ( clamp 51 10 50 ) : = 50 ( clamp 50 10 50 ) : = 50 ( clamp 49 10 50 ) : = 49 ( clamp 11 10 50 ) : = 11 ( clamp 10 10 50 ) : = 10 ( clamp 9 10 50 ) : = 10 ) #?(:clj (defmacro orp "`clojure.core/or` evaluates arguments one by one, returning the first truthy one and so leaving the remaining ones unevaluated. `orp` does the same but with a custom predicate." ([pred] nil) ([pred x] `(let [or# ~x] (when (~pred or#) or#))) ([pred x & next] `(let [or# ~x] (if (~pred or#) or# (orp ~pred ~@next)))))) (tests (orp some? nil false 1) := false (orp even? 1 3 5 6 7) := 6) (defn nil-or-empty? [x] (if (seqable? x) (empty? x) (nil? x))) (defn- -tree-list [depth xs children-fn keep? input] (eduction (mapcat (fn [x] (let [x (datafy x)] (if-let [children (children-fn x)] (when-let [rows (seq (-tree-list (inc depth) children children-fn keep? input))] (into [[depth x]] rows)) (cond-> [] (keep? x input) (conj [depth x])))))) (datafy xs))) (defn treelister ([xs] (treelister xs (fn [_]) (fn [_ _] true))) ([xs children-fn keep?] (fn [input] (-tree-list 0 xs children-fn keep? input)))) (tests (vec ((treelister [1 2 [3 4] [5 [6 [7]]]] #(when (vector? %) %) (fn [v _] (odd? v))) nil)) := [[0 1] [0 [3 4]] [1 3] [0 [5 [6 [7]]]] [1 5] [1 [6 [7]]] [2 [7]] [3 7]] ((treelister [{:dir "x" :children [{:file "a"} {:file "b"}]}] :children (fn [v needle] (-> v :file #{needle})) ) "a") (count (vec *1)) := 2 "directory is omitted if there are no children matching keep?" ((treelister [{:dir "x" :children [{:file "a"} {:file "b"}]}] :children (fn [v needle] (-> v :file #{needle}))) "nope") (count (vec *1)) := 0)
null
https://raw.githubusercontent.com/hyperfiddle/electric/4cb7008615a43e38b60af9dad804892479907b8a/src/contrib/data.cljc
clojure
todo remove (keyword (name (namespace ::ns)) (name :limit)) fallback to index when key is not present alternative design is to define nil kf as fallback should this throw? "nil kf uses default value (which is likely unintended, should it throw?)" (index-by nil xs) (index-by nil nil) := {} ; kf never used -- alternative design missing key, fallback to index index the map entry, not the map, :a is missing so fallback should this detect collision and throw? maps are not indexable todo rename list [:foo :bar]" []) (seq))) org.apache.commons.lang3.StringUtils.containsIgnoreCase() (tests
(ns contrib.data (:require clojure.math [hyperfiddle.rcf :refer [tests]]) #?(:cljs (:require-macros [contrib.data :refer [auto-props]]))) (defn qualify "Qualify a keyword with a namespace. If already qualified, leave kw untouched. Nil-safe. (qualify :db :isComponent) -> :db/isComponent" [ns ?kw] {:pre [(some? ns) #_(not (namespace ns)) (keyword? ?kw)]} (when ?kw (if (qualified-keyword? ?kw) ?kw (keyword (name ns) (name ?kw))))) (tests (qualify (namespace ::x) :limit) := ::limit ( qualify ( namespace : :x ) " limit " ) thrown ? AssertionError "leave qualified kws untouched" (qualify (namespace ::x) :user/foo) := :user/foo) (defn unqualify "Strip namespace from keyword, discarding it and return unqualified keyword. Nil-safe. (unqualify :db.type/ref) -> :ref" [?qualified-kw] (assert (or (nil? ?qualified-kw) (qualified-keyword? ?qualified-kw)) (str " can't unqualify: " ?qualified-kw)) (if ?qualified-kw (keyword (name ?qualified-kw)))) (tests (unqualify ::x) := :x (unqualify :db.type/ref) := :ref (unqualify nil) := nil (unqualify "") :throws #?(:clj AssertionError :cljs js/Error)) (defn -omit-keys-ns [ns ?m] {:pre [(some? ns)]} (when ?m (reduce-kv (fn [m k v] (if (= (name ns) (namespace k)) m (assoc m k v))) {} ?m))) (defmacro omit-keys-ns ([?m] `(-omit-keys-ns ~(str *ns*) ~?m)) ([ns- ?m] `(-omit-keys-ns ~ns- ~?m))) (tests (omit-keys-ns :c {::a 1 :b 2 :c/c 3}) := {::a 1 :b 2} (omit-keys-ns :c {::a 1 :b 2 :c/c 3}) := {::a 1 :b 2} (omit-keys-ns :c nil) := nil (omit-keys-ns nil {::a 1 :b 2 :c/c 3}) :throws #?(:clj AssertionError :cljs js/Error) (omit-keys-ns nil nil) :throws #?(:clj AssertionError :cljs js/Error) nil) (defn has-ns? "State if a `named` value (keyword or symbol) has such namespace `ns`. `ns` can be be a string, or a non-namespaced keyword or symbol." [ns named] {:pre [(or (string? ns) (simple-ident? ns))]} (= (name ns) (namespace named))) (defn select-ns "Like `select-keys` but select all namespaced keys by ns." [ns map] (into (empty map) (filter (fn [[k _v]] (has-ns? ns k))) map)) (defn -auto-props "qualify any unqualified keys to the current ns and then add qualified defaults" [ns props defaults-qualified] {:pre [(some? ns) (or (string? ns) (symbol? ns))]} (merge defaults-qualified (update-keys props (partial qualify ns)))) (defmacro auto-props ([ns props defaults-qualified] `(-auto-props ~ns ~props ~defaults-qualified)) ([props defaults-qualified] `(-auto-props ~(str *ns*) ~props ~defaults-qualified)) ([props] `(-auto-props ~(str *ns*) ~props {}))) (tests (auto-props "user" {:a 1} {:dom/class "a"}) := {:user/a 1 :dom/class "a"} (auto-props 'user {:a 1} {:dom/class "a"}) := {:user/a 1 :dom/class "a"} (auto-props *ns* {:a 1} {:dom/class "a"}) :throws #?(:clj AssertionError :cljs js/Error) (auto-props {:a 1} {:dom/class "a"}) := {:contrib.data/a 1 :dom/class "a"} (auto-props {:a 1}) := {:contrib.data/a 1}) (defn xorxs "an argument parser that accepts both scalars and collections, lifting scalars into a collection" [xorxs & [zero]] (cond (vector? xorxs) xorxs (set? xorxs) xorxs (seq? xorxs) xorxs (nil? xorxs) zero :else-single-value-or-map (conj (or zero []) xorxs))) (tests (xorxs :a) := [:a] (xorxs [:a]) := [:a] (xorxs #{:a}) := #{:a} (xorxs :a #{}) := #{:a} (xorxs :a []) := [:a] (xorxs nil #{}) := #{} (xorxs nil) := nil) (defn index-by [kf xs] {:pre [kf]} (into {} (map-indexed (fn [i x] x])) xs)) (tests (def xs [{:db/ident :foo :a 1} {:db/ident :bar :b 2}]) (index-by :db/ident xs) := {:foo {:db/ident :foo, :a 1}, :bar {:db/ident :bar, :b 2}} := {0 {:db/ident :foo, :a 1}, 1 {:db/ident :bar, :b 2}} : = { 0 { : db / ident : foo , : a 1 } , 1 { : db / ident : bar , : b 2 } } (index-by :a nil) := {} (index-by nil nil) :throws #?(:clj AssertionError :cljs js/Error) (index-by :a [{}]) := {0 {}} (index-by :a [{:a 1}]) := {1 {:a 1}} "indexing map entries (which is weird, should this throw?)" (index-by :b {:a 1}) := {0 [:a 1]} "collisions are possible" := {1 #:db{:id 1}, 2 #:db{:id 2}} "kf fallback arity" (index-by (fn [x i] (str i)) xs) := {"0" {:db/ident :foo, :a 1}, "1" {:db/ident :bar, :b 2}} "index by first element" ( index - by first [ [: a 1 ] [: b 2 ] ] ) -- ArityException : kf must accept fallback . Is this a mistake ? (index-by (fn [a b] (first a)) [[:a 1] [:b 2]]) := {:a [:a 1], :b [:b 2]} (index-by #(do %2 (first %1)) [[:a 1] [:b 2]]) := {:a [:a 1], :b [:b 2]}) (defn index "index a sequential collection into an associative collection with explicit keys. this may not be useful, as vectors are already associative" [xs] (index-by (fn [x i] i) xs)) (tests (def xs [{:db/ident :foo :a 1} {:db/ident :bar :b 2}]) (index xs) := {0 {:db/ident :foo, :a 1}, 1 {:db/ident :bar, :b 2}}) (let [{a true b false} (group-by f? xs)] [a b])) (tests (group-by-pred map? [:user/email {:user/gender [:db/ident]} {:user/shirt-size [:db/ident]} :db/id]) := [[#:user{:gender [:db/ident]} #:user{:shirt-size [:db/ident]}] [:user/email :db/id]]) (defn update-existing [m k f & args] (if (get m k) (apply update m k f args) m)) (tests (update-existing {:a 1} :a + 10) := {:a 11} (update-existing {:a 1} :b + 10) := {:a 1}) ( defn positional " Transform an array - like map { 0 : foo , 1 : bar , ... } with contiguous array keys ( 0 , 1 , ... ) into [ amap ] ( - > > ( range ( inc ( count amap ) ) ) ( reduce ( fn [ acc idx ] ( if ( contains ? amap idx ) ( conj acc ( get amap idx ) ) ( reduced acc ) ) ) ( tests ( positional { 0 : foo 1 : bar } ) : = [ : foo : bar ] ) (defn round-floor [n base] (* base (clojure.math/floor (/ n base)))) (comment "base 10" (round-floor 89 10) := 80.0 (round-floor 90 10) := 90.0 (round-floor 91 10) := 90.0 (round-floor 99 10) := 90.0 (round-floor 100 10) := 100.0 "base 8" (round-floor 7 8) := 0.0 (round-floor 8 8) := 8.0 (round-floor 9 8) := 8.0 (round-floor 15 8) := 8.0 (round-floor 16 8) := 16.0 (round-floor 1234567 1000) := 1234000.0) (defn pad ([zero coll] (concat coll (repeat zero))) ([n zero coll] (take n (pad zero coll)))) (defn padl [n zero coll] (concat (repeat (- n (count coll)) zero) coll)) (tests (pad 8 0 (range 3)) := [0 1 2 0 0 0 0 0] (padl 8 0 (range 3)) := [0 0 0 0 0 0 1 2] "strings leak platform internals, use padl-str" (pad 8 "0" "xx") := #?(:clj [\x \x "0" "0" "0" "0" "0" "0"] :cljs ["x" "x" "0" "0" "0" "0" "0" "0"]) (padl 8 "0" "xx") := #?(:clj ["0" "0" "0" "0" "0" "0" \x \x] :cljs ["0" "0" "0" "0" "0" "0" "x" "x"])) (defn assoc-vec [xs k v] (if (>= k (count xs)) (assoc (vec (pad k nil xs)) k v) (assoc xs k v))) (tests (assoc-vec [] 0 :a) := [:a] (assoc-vec [] 1 :b) := [nil :b] (assoc-vec [] 4 :e) := [nil nil nil nil :e] (assoc-vec nil 4 :e) := [nil nil nil nil :e] (assoc-vec [:a :b :c] 1 :B) := [:a :B :c] (assoc-vec [:a :b :c] 4 :E) := [:a :b :c nil :E]) (defn padl-str [n zero s] (apply str (padl n zero s))) (tests (padl-str 8 "0" "xx") := "000000xx" (padl-str 4 "0" (str 11)) := "0011") (defn with-pad [reducer zero] (fn [f & cols] (let [n (apply max (map count cols)) cols (map #(pad n zero %) cols)] (apply reducer f cols)))) (def map-pad (partial with-pad map)) (tests (map + [1 1 1] [1 1 1 1]) := '(2 2 2) ((map-pad 0) + [1 1 1] [1 1 1 1]) := '(2 2 2 1)) (defn str-last-n [n s] #?(:clj (.substring s (max 0 (- (.length s) n))) :cljs (apply str (reverse (take n (reverse s)))))) (tests (str-last-n 4 "0123456789") := "6789") ( - contains - ignore - case [ ] ) ( defn clamp [ n min max ] ( Math / min ( Math / max n min ) ) ) ( clamp 51 10 50 ) : = 50 ( clamp 50 10 50 ) : = 50 ( clamp 49 10 50 ) : = 49 ( clamp 11 10 50 ) : = 11 ( clamp 10 10 50 ) : = 10 ( clamp 9 10 50 ) : = 10 ) #?(:clj (defmacro orp "`clojure.core/or` evaluates arguments one by one, returning the first truthy one and so leaving the remaining ones unevaluated. `orp` does the same but with a custom predicate." ([pred] nil) ([pred x] `(let [or# ~x] (when (~pred or#) or#))) ([pred x & next] `(let [or# ~x] (if (~pred or#) or# (orp ~pred ~@next)))))) (tests (orp some? nil false 1) := false (orp even? 1 3 5 6 7) := 6) (defn nil-or-empty? [x] (if (seqable? x) (empty? x) (nil? x))) (defn- -tree-list [depth xs children-fn keep? input] (eduction (mapcat (fn [x] (let [x (datafy x)] (if-let [children (children-fn x)] (when-let [rows (seq (-tree-list (inc depth) children children-fn keep? input))] (into [[depth x]] rows)) (cond-> [] (keep? x input) (conj [depth x])))))) (datafy xs))) (defn treelister ([xs] (treelister xs (fn [_]) (fn [_ _] true))) ([xs children-fn keep?] (fn [input] (-tree-list 0 xs children-fn keep? input)))) (tests (vec ((treelister [1 2 [3 4] [5 [6 [7]]]] #(when (vector? %) %) (fn [v _] (odd? v))) nil)) := [[0 1] [0 [3 4]] [1 3] [0 [5 [6 [7]]]] [1 5] [1 [6 [7]]] [2 [7]] [3 7]] ((treelister [{:dir "x" :children [{:file "a"} {:file "b"}]}] :children (fn [v needle] (-> v :file #{needle})) ) "a") (count (vec *1)) := 2 "directory is omitted if there are no children matching keep?" ((treelister [{:dir "x" :children [{:file "a"} {:file "b"}]}] :children (fn [v needle] (-> v :file #{needle}))) "nope") (count (vec *1)) := 0)
ec8836c775ed83dc3c7c0610e4c9067f68e5c34da332bd26538fb2e2c52a6972
cartazio/tlaps
e_constness.ml
* expr / constness.ml --- detect constant operators * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * expr/constness.ml --- detect constant operators * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) Revision.f "$Rev: 34599 $";; open Ext open Property open E_t module Visit = E_visit;; let isconst : bool pfuncs = Property.make ~uuid:"595aaaad-07ca-498b-8ebc-a473db6b0b27" "Expr.Constness.isconst" let has_const x = Property.has x isconst (*let is_const x = Property.get x isconst*) let is_const x = try Property.get x isconst with | Not_found -> false class virtual const_visitor = object (self : 'self) inherit [unit] Visit.map as super method expr scx e = match e.core with | Lambda (vss, le) -> let hs = List.map begin fun (v, shp) -> assign (Fresh (v, shp, Constant, Unbounded) @@ v) isconst true end vss in let scx = Visit.adjs scx hs in let le = self#expr scx le in let e = Lambda (vss, le) @@ e in (* Util.eprintf e *) (* "const (%a) <-- %b@." *) ( Fmt.pp_print_expr ( snd scx , ) ) e ( Property.has le isconst ) ; assign e isconst (is_const le) | Sequent sq -> let (_, sq) = super#sequent scx sq in let e = Sequent sq @@ e in let rec sq_const cx = match Deque.front cx with | None -> is_const sq.active | Some (h, cx) -> begin let hgood = match h.core with | Fresh (_, _, Constant, _) -> true | ( Defn ({core = Operator (_, e)}, _, _, _) | Fact (e, _, _) ) -> is_const e | _ -> false in hgood && sq_const cx end in assign e isconst (sq_const sq.context) | _ -> let e = super#expr scx e in let cx = snd scx in let const = match e.core with | Ix n -> begin match Deque.nth ~backwards:true cx (n - 1) with | Some h -> begin match h.core with | Defn ({core = Operator (_, op)}, _, _, _) -> is_const op | Fresh (_, _, Constant, _) -> true | _ -> false end | _ -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Ix" end | Opaque _ -> true | ( Tquant _ | Sub _ | Tsub _ | Fair _ ) -> false | Internal b -> begin match b with | Builtin.Prime | Builtin.StrongPrime | Builtin.Leadsto | Builtin.ENABLED | Builtin.UNCHANGED | Builtin.Cdot | Builtin.Actplus | Builtin.Box _ | Builtin.Diamond -> false | _ -> true end | Lambda (vss, e) -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Lambda" | Sequent sq -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Sequent" | Bang (e,_) -> (* TL: we ignore the selection for now *) is_const e | Apply (op, args) -> is_const op && List.for_all is_const args | Let (ds, e) -> begin let rec c_defns cx = function | [] -> is_const e | d :: ds -> begin let dgood = match d.core with | Operator (_, e) -> is_const e | _ -> false in dgood && let h = Defn (d, User, Visible, Local) @@ d in let h = assign h isconst true in c_defns (Deque.snoc cx h) ds end in c_defns cx ds end | ( String _ | Num _ | At _ ) -> true | ( With (e, _) | Dot (e, _) | Parens (e, _) ) -> is_const e | ( Quant (_, bs, qe) | Fcn (bs, qe) | SetOf (qe, bs) ) -> begin let rec c_bounds cx = function | [] -> is_const qe | (v, k, bd) :: bs -> begin let bdgood = match bd with | Domain d -> is_const d | _ -> true in bdgood && let h = Fresh (v, Shape_expr, Constant, Unbounded) @@ v in let h = assign h isconst true in c_bounds (Deque.snoc cx h) bs end in c_bounds cx bs end | Choose (v, None, e) -> is_const e | ( Choose (v, Some d, e) | SetSt (v, d, e) ) -> is_const d && is_const e | If (e, f, g) -> is_const e && is_const f && is_const g | ( List (_, es) | Tuple es | Product es | SetEnum es ) -> List.for_all is_const es | FcnApp (f, es) -> is_const f && List.for_all is_const es | ( Rect fs | Record fs ) -> List.for_all (fun (_, e) -> is_const e) fs | Arrow (e, f) -> is_const e && is_const f | Except (e, xs) -> let c_exspec (tr, re) = List.for_all begin function | Except_dot _ -> true | Except_apply e -> is_const e end tr && is_const re in is_const e && List.for_all c_exspec xs | Case (arms, oth) -> List.for_all begin fun (p, e) -> is_const p && is_const e end arms && begin match oth with | None -> true | Some e -> is_const e end in assign e isconst const method hyp scx h = if (has_const h) then (scx,h) else super#hyp scx h method pform scx p = if (has_const p) then p else super#pform scx p method defn scx p = if (has_const p) then p else super#defn scx p end
null
https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/expr/e_constness.ml
ocaml
let is_const x = Property.get x isconst Util.eprintf e "const (%a) <-- %b@." TL: we ignore the selection for now
* expr / constness.ml --- detect constant operators * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * expr/constness.ml --- detect constant operators * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) Revision.f "$Rev: 34599 $";; open Ext open Property open E_t module Visit = E_visit;; let isconst : bool pfuncs = Property.make ~uuid:"595aaaad-07ca-498b-8ebc-a473db6b0b27" "Expr.Constness.isconst" let has_const x = Property.has x isconst let is_const x = try Property.get x isconst with | Not_found -> false class virtual const_visitor = object (self : 'self) inherit [unit] Visit.map as super method expr scx e = match e.core with | Lambda (vss, le) -> let hs = List.map begin fun (v, shp) -> assign (Fresh (v, shp, Constant, Unbounded) @@ v) isconst true end vss in let scx = Visit.adjs scx hs in let le = self#expr scx le in let e = Lambda (vss, le) @@ e in ( Fmt.pp_print_expr ( snd scx , ) ) e ( Property.has le isconst ) ; assign e isconst (is_const le) | Sequent sq -> let (_, sq) = super#sequent scx sq in let e = Sequent sq @@ e in let rec sq_const cx = match Deque.front cx with | None -> is_const sq.active | Some (h, cx) -> begin let hgood = match h.core with | Fresh (_, _, Constant, _) -> true | ( Defn ({core = Operator (_, e)}, _, _, _) | Fact (e, _, _) ) -> is_const e | _ -> false in hgood && sq_const cx end in assign e isconst (sq_const sq.context) | _ -> let e = super#expr scx e in let cx = snd scx in let const = match e.core with | Ix n -> begin match Deque.nth ~backwards:true cx (n - 1) with | Some h -> begin match h.core with | Defn ({core = Operator (_, op)}, _, _, _) -> is_const op | Fresh (_, _, Constant, _) -> true | _ -> false end | _ -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Ix" end | Opaque _ -> true | ( Tquant _ | Sub _ | Tsub _ | Fair _ ) -> false | Internal b -> begin match b with | Builtin.Prime | Builtin.StrongPrime | Builtin.Leadsto | Builtin.ENABLED | Builtin.UNCHANGED | Builtin.Cdot | Builtin.Actplus | Builtin.Box _ | Builtin.Diamond -> false | _ -> true end | Lambda (vss, e) -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Lambda" | Sequent sq -> Errors.bug ~at:e "Expr.Constness.propagate#expr: Sequent" is_const e | Apply (op, args) -> is_const op && List.for_all is_const args | Let (ds, e) -> begin let rec c_defns cx = function | [] -> is_const e | d :: ds -> begin let dgood = match d.core with | Operator (_, e) -> is_const e | _ -> false in dgood && let h = Defn (d, User, Visible, Local) @@ d in let h = assign h isconst true in c_defns (Deque.snoc cx h) ds end in c_defns cx ds end | ( String _ | Num _ | At _ ) -> true | ( With (e, _) | Dot (e, _) | Parens (e, _) ) -> is_const e | ( Quant (_, bs, qe) | Fcn (bs, qe) | SetOf (qe, bs) ) -> begin let rec c_bounds cx = function | [] -> is_const qe | (v, k, bd) :: bs -> begin let bdgood = match bd with | Domain d -> is_const d | _ -> true in bdgood && let h = Fresh (v, Shape_expr, Constant, Unbounded) @@ v in let h = assign h isconst true in c_bounds (Deque.snoc cx h) bs end in c_bounds cx bs end | Choose (v, None, e) -> is_const e | ( Choose (v, Some d, e) | SetSt (v, d, e) ) -> is_const d && is_const e | If (e, f, g) -> is_const e && is_const f && is_const g | ( List (_, es) | Tuple es | Product es | SetEnum es ) -> List.for_all is_const es | FcnApp (f, es) -> is_const f && List.for_all is_const es | ( Rect fs | Record fs ) -> List.for_all (fun (_, e) -> is_const e) fs | Arrow (e, f) -> is_const e && is_const f | Except (e, xs) -> let c_exspec (tr, re) = List.for_all begin function | Except_dot _ -> true | Except_apply e -> is_const e end tr && is_const re in is_const e && List.for_all c_exspec xs | Case (arms, oth) -> List.for_all begin fun (p, e) -> is_const p && is_const e end arms && begin match oth with | None -> true | Some e -> is_const e end in assign e isconst const method hyp scx h = if (has_const h) then (scx,h) else super#hyp scx h method pform scx p = if (has_const p) then p else super#pform scx p method defn scx p = if (has_const p) then p else super#defn scx p end
cf532ad622e441191e8d7b681f462cf97cd4b26100cefa0e95ee800dee61da63
fare/lisp-interface-library
sequence.lisp
;;;;; Read-only interfaces common to pure and stateful collections (uiop:define-package :lil/interface/sequence (:use :closer-common-lisp :lil/core :lil/interface/base :lil/interface/collection) (:use-reexport :lil/interface/empty :lil/interface/size :lil/interface/fold :lil/interface/iterator) (:export #:<sequence> ;; to be shadowed by pure and stateful packages. #:sequence-list #:list-sequence)) (in-package :lil/interface/sequence) ;; TODO: create this interface... (define-interface <sequence> (<finite-collection>) () (:abstract))
null
https://raw.githubusercontent.com/fare/lisp-interface-library/ac2e0063dc65feb805f0c57715d52fda28d4dcd8/interface/sequence.lisp
lisp
Read-only interfaces common to pure and stateful collections to be shadowed by pure and stateful packages. TODO: create this interface...
(uiop:define-package :lil/interface/sequence (:use :closer-common-lisp :lil/core :lil/interface/base :lil/interface/collection) (:use-reexport :lil/interface/empty :lil/interface/size :lil/interface/fold :lil/interface/iterator) (:export #:sequence-list #:list-sequence)) (in-package :lil/interface/sequence) (define-interface <sequence> (<finite-collection>) () (:abstract))
ecc2fafaf353c4775d1b9d65bb09ffea70345a65c4efd311c2a32fe4ed8170f7
GNOME/aisleriot
agnes.scm
; AisleRiot - agnes.scm Copyright ( C ) 2001 , 2003 < > ; ; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; You should have received a copy of the GNU General Public License ; along with this program. If not, see </>. (use-modules (aisleriot interface) (aisleriot api) (ice-9 format)) (define BASE-VAL 0) (define stock 0) (define foundation '(1 2 3 4)) (define tableau '(5 6 7 8 9 10 11)) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK 'stock) (add-blank-slot) (add-blank-slot) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-carriage-return-slot) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (deal-cards 0 '(5 6 7 8 9 10 11 6 7 8 9 10 11 7 8 9 10 11 8 9 10 11 9 10 11 10 11 11)) (map flip-top-card '(5 6 7 8 9 10 11)) (deal-cards-face-up 0 '(1)) (add-to-score! 1) (set! BASE-VAL (get-value (get-top-card 1))) (give-status-message) (dealable-set-sensitive (dealable?)) (list 7 4)) (define (give-status-message) (set-statusbar-message (string-append (get-stock-no-string) " " (get-base-string)))) (define (get-base-string) (cond ((and (> BASE-VAL 1) (< BASE-VAL 11)) (format #f (G_"Base Card: ~a") (number->string BASE-VAL))) ((= BASE-VAL 1) (G_"Base Card: Ace")) ((= BASE-VAL 11) (G_"Base Card: Jack")) ((= BASE-VAL 12) (G_"Base Card: Queen")) ((= BASE-VAL 13) (G_"Base Card: King")) (#t ""))) (define (get-stock-no-string) (if (> (length (get-cards 0)) 1) (string-append (G_"Stock left:") " " (number->string (length (get-cards 0)))) (string-append (G_"Stock left: 0")))) (define (check-straight-descending-list-base-low card-list) (or (< (length card-list) 2) (and (= (get-value (car card-list)) king) (= (get-value (cadr card-list)) ace) (not (= BASE-VAL ace)) (check-straight-descending-list-base-low (cdr card-list))) (and (= (get-value (car card-list)) (- (get-value (cadr card-list)) 1)) (not (= BASE-VAL (get-value (cadr card-list)))) (check-straight-descending-list-base-low (cdr card-list))))) (define (button-pressed slot-id card-list) (and (not (empty-slot? slot-id)) (is-visible? (car (reverse card-list))) (check-same-color-list card-list) (check-straight-descending-list-base-low card-list))) (define (droppable? start-slot card-list end-slot) (cond ((= start-slot end-slot) #f) ((and (> end-slot 0) (< end-slot 5)) (and (= (length card-list) 1) (or (and (empty-slot? end-slot) (= (get-value (car card-list)) BASE-VAL)) (and (not (empty-slot? end-slot)) (= (get-suit (car card-list)) (get-suit (get-top-card end-slot))) (or (= (get-value (car card-list)) (+ 1 (get-value (get-top-card end-slot)))) (and (= (get-value (car card-list)) ace) (= (get-value (get-top-card end-slot)) king))))))) ((> end-slot 4) (and (not (empty-slot? end-slot)) (eq? (is-red? (car card-list)) (is-red? (get-top-card end-slot))) (or (= (get-value (car (reverse card-list))) (- (get-value (get-top-card end-slot)) 1)) (and (= (get-value (car (reverse card-list))) king) (= (get-value (get-top-card end-slot)) ace))))) (#t #f))) (define (button-released start-slot card-list end-slot) (and (droppable? start-slot card-list end-slot) (move-n-cards! start-slot end-slot card-list) (or (> start-slot 4) (add-to-score! -1)) (or (> end-slot 4) (add-to-score! 1)) (or (empty-slot? start-slot) (make-visible-top-card start-slot)))) (define (check-slot-and-deal slot) (if (and (not (empty-slot? 0)) (< slot 12)) (and (deal-cards-face-up 0 (list slot)) (check-slot-and-deal (+ 1 slot))))) (define (do-deal-next-cards) (and (dealable?) (check-slot-and-deal 5))) (define (button-clicked slot-id) (and (= slot-id 0) (do-deal-next-cards))) (define (dealable?) (not (empty-slot? 0))) (define (check-dc slot f-slot just-checking?) (cond ((= f-slot 5) #f) ((and (not (empty-slot? f-slot)) (= (get-suit (get-top-card slot)) (get-suit (get-top-card f-slot))) (or (= (get-value (get-top-card slot)) (+ 1 (get-value (get-top-card f-slot)))) (and (= (get-value (get-top-card slot)) ace) (= (get-value (get-top-card f-slot)) king))) (or (and just-checking? f-slot) (and (deal-cards slot (list f-slot)) (add-to-score! 1) (or (empty-slot? slot) (make-visible-top-card slot)))))) (#t (check-dc slot (+ 1 f-slot) just-checking?)))) (define (autoplay-foundations) (define (autoplay-foundations-tail) (if (or-map button-double-clicked '(5 6 7 8 9 10 11)) (delayed-call autoplay-foundations-tail) #t)) (if (or-map button-double-clicked '(5 6 7 8 9 10 11)) (autoplay-foundations-tail) #f)) (define (button-double-clicked slot-id) (cond ((or (and (empty-slot? slot-id) (> slot-id 4)) (= slot-id 0)) #f) ((< slot-id 5) (autoplay-foundations)) ((= (get-value (get-top-card slot-id)) BASE-VAL) (and (or (and (empty-slot? 1) (deal-cards slot-id '(1))) (and (empty-slot? 2) (deal-cards slot-id '(2))) (and (empty-slot? 3) (deal-cards slot-id '(3))) (deal-cards slot-id '(4))) (add-to-score! 1) (or (empty-slot? slot-id) (make-visible-top-card slot-id)))) (#t (check-dc slot-id 1 #f)))) (define (game-continuable) (give-status-message) (dealable-set-sensitive (dealable?)) (not (game-won))) (define (game-won) (and (= 13 (length (get-cards 1))) (= 13 (length (get-cards 2))) (= 13 (length (get-cards 3))) (= 13 (length (get-cards 4))))) (define (check-to-foundation? slot) (cond ((= slot 12) #f) ((and (not (empty-slot? slot)) (= (get-value (get-top-card slot)) BASE-VAL)) (hint-move slot 1 (find-empty-slot foundation))) ((and (not (empty-slot? slot)) (check-dc slot 1 #t)) (hint-move slot 1 (check-dc slot 1 #t))) (#t (check-to-foundation? (+ 1 slot))))) (define (check-a-tableau card slot) (and (not (empty-slot? slot)) (eq? (is-red? card) (is-red? (get-top-card slot))) (not (= (get-value (get-top-card slot)) BASE-VAL)) (or (and (= (get-value card) king) (= (get-value (get-top-card slot)) ace)) (= (+ (get-value card) 1) (get-value (get-top-card slot)))))) (define (strip card-list) (cond ((< (length card-list) 2) (car card-list)) ((or (not (is-visible? (car (reverse card-list)))) ; (eq? (is-red? (car (reverse card-list))) ; (is-black? (car card-list))) (not (check-same-color-list card-list)) (not (check-straight-descending-list-base-low card-list))) (strip (reverse (cdr (reverse card-list))))) (#t (car (reverse card-list))))) (define (check-to-tableau? slot1 slot2) (cond ((= slot1 12) #f) ((or (= slot2 12) (empty-slot? slot1)) (check-to-tableau? (+ 1 slot1) 5)) ((and (not (= slot1 slot2)) (check-a-tableau (strip (get-cards slot1)) slot2)) (hint-move slot1 (find-card slot1 (strip (get-cards slot1))) slot2)) (#t (check-to-tableau? slot1 (+ 1 slot2))))) (define (check-deal?) (and (dealable?) (list 0 (G_"Deal more cards")))) (define (get-hint) (or (check-to-foundation? 5) (check-to-tableau? 5 6) (check-deal?) (list 0 (G_"Try rearranging the cards")))) (define (get-options) #f) (define (apply-options options) #f) (define (timeout) #f) (set-features droppable-feature dealable-feature) (set-lambda new-game button-pressed button-released button-clicked button-double-clicked game-continuable game-won get-hint get-options apply-options timeout droppable? dealable?)
null
https://raw.githubusercontent.com/GNOME/aisleriot/5b04e58ba5f8df8223a3830d2c61325527d52237/games/agnes.scm
scheme
AisleRiot - agnes.scm This program is free software: you can redistribute it and/or modify (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, see </>. (eq? (is-red? (car (reverse card-list))) (is-black? (car card-list)))
Copyright ( C ) 2001 , 2003 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (use-modules (aisleriot interface) (aisleriot api) (ice-9 format)) (define BASE-VAL 0) (define stock 0) (define foundation '(1 2 3 4)) (define tableau '(5 6 7 8 9 10 11)) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK 'stock) (add-blank-slot) (add-blank-slot) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-carriage-return-slot) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (add-extended-slot '() down 'tableau) (deal-cards 0 '(5 6 7 8 9 10 11 6 7 8 9 10 11 7 8 9 10 11 8 9 10 11 9 10 11 10 11 11)) (map flip-top-card '(5 6 7 8 9 10 11)) (deal-cards-face-up 0 '(1)) (add-to-score! 1) (set! BASE-VAL (get-value (get-top-card 1))) (give-status-message) (dealable-set-sensitive (dealable?)) (list 7 4)) (define (give-status-message) (set-statusbar-message (string-append (get-stock-no-string) " " (get-base-string)))) (define (get-base-string) (cond ((and (> BASE-VAL 1) (< BASE-VAL 11)) (format #f (G_"Base Card: ~a") (number->string BASE-VAL))) ((= BASE-VAL 1) (G_"Base Card: Ace")) ((= BASE-VAL 11) (G_"Base Card: Jack")) ((= BASE-VAL 12) (G_"Base Card: Queen")) ((= BASE-VAL 13) (G_"Base Card: King")) (#t ""))) (define (get-stock-no-string) (if (> (length (get-cards 0)) 1) (string-append (G_"Stock left:") " " (number->string (length (get-cards 0)))) (string-append (G_"Stock left: 0")))) (define (check-straight-descending-list-base-low card-list) (or (< (length card-list) 2) (and (= (get-value (car card-list)) king) (= (get-value (cadr card-list)) ace) (not (= BASE-VAL ace)) (check-straight-descending-list-base-low (cdr card-list))) (and (= (get-value (car card-list)) (- (get-value (cadr card-list)) 1)) (not (= BASE-VAL (get-value (cadr card-list)))) (check-straight-descending-list-base-low (cdr card-list))))) (define (button-pressed slot-id card-list) (and (not (empty-slot? slot-id)) (is-visible? (car (reverse card-list))) (check-same-color-list card-list) (check-straight-descending-list-base-low card-list))) (define (droppable? start-slot card-list end-slot) (cond ((= start-slot end-slot) #f) ((and (> end-slot 0) (< end-slot 5)) (and (= (length card-list) 1) (or (and (empty-slot? end-slot) (= (get-value (car card-list)) BASE-VAL)) (and (not (empty-slot? end-slot)) (= (get-suit (car card-list)) (get-suit (get-top-card end-slot))) (or (= (get-value (car card-list)) (+ 1 (get-value (get-top-card end-slot)))) (and (= (get-value (car card-list)) ace) (= (get-value (get-top-card end-slot)) king))))))) ((> end-slot 4) (and (not (empty-slot? end-slot)) (eq? (is-red? (car card-list)) (is-red? (get-top-card end-slot))) (or (= (get-value (car (reverse card-list))) (- (get-value (get-top-card end-slot)) 1)) (and (= (get-value (car (reverse card-list))) king) (= (get-value (get-top-card end-slot)) ace))))) (#t #f))) (define (button-released start-slot card-list end-slot) (and (droppable? start-slot card-list end-slot) (move-n-cards! start-slot end-slot card-list) (or (> start-slot 4) (add-to-score! -1)) (or (> end-slot 4) (add-to-score! 1)) (or (empty-slot? start-slot) (make-visible-top-card start-slot)))) (define (check-slot-and-deal slot) (if (and (not (empty-slot? 0)) (< slot 12)) (and (deal-cards-face-up 0 (list slot)) (check-slot-and-deal (+ 1 slot))))) (define (do-deal-next-cards) (and (dealable?) (check-slot-and-deal 5))) (define (button-clicked slot-id) (and (= slot-id 0) (do-deal-next-cards))) (define (dealable?) (not (empty-slot? 0))) (define (check-dc slot f-slot just-checking?) (cond ((= f-slot 5) #f) ((and (not (empty-slot? f-slot)) (= (get-suit (get-top-card slot)) (get-suit (get-top-card f-slot))) (or (= (get-value (get-top-card slot)) (+ 1 (get-value (get-top-card f-slot)))) (and (= (get-value (get-top-card slot)) ace) (= (get-value (get-top-card f-slot)) king))) (or (and just-checking? f-slot) (and (deal-cards slot (list f-slot)) (add-to-score! 1) (or (empty-slot? slot) (make-visible-top-card slot)))))) (#t (check-dc slot (+ 1 f-slot) just-checking?)))) (define (autoplay-foundations) (define (autoplay-foundations-tail) (if (or-map button-double-clicked '(5 6 7 8 9 10 11)) (delayed-call autoplay-foundations-tail) #t)) (if (or-map button-double-clicked '(5 6 7 8 9 10 11)) (autoplay-foundations-tail) #f)) (define (button-double-clicked slot-id) (cond ((or (and (empty-slot? slot-id) (> slot-id 4)) (= slot-id 0)) #f) ((< slot-id 5) (autoplay-foundations)) ((= (get-value (get-top-card slot-id)) BASE-VAL) (and (or (and (empty-slot? 1) (deal-cards slot-id '(1))) (and (empty-slot? 2) (deal-cards slot-id '(2))) (and (empty-slot? 3) (deal-cards slot-id '(3))) (deal-cards slot-id '(4))) (add-to-score! 1) (or (empty-slot? slot-id) (make-visible-top-card slot-id)))) (#t (check-dc slot-id 1 #f)))) (define (game-continuable) (give-status-message) (dealable-set-sensitive (dealable?)) (not (game-won))) (define (game-won) (and (= 13 (length (get-cards 1))) (= 13 (length (get-cards 2))) (= 13 (length (get-cards 3))) (= 13 (length (get-cards 4))))) (define (check-to-foundation? slot) (cond ((= slot 12) #f) ((and (not (empty-slot? slot)) (= (get-value (get-top-card slot)) BASE-VAL)) (hint-move slot 1 (find-empty-slot foundation))) ((and (not (empty-slot? slot)) (check-dc slot 1 #t)) (hint-move slot 1 (check-dc slot 1 #t))) (#t (check-to-foundation? (+ 1 slot))))) (define (check-a-tableau card slot) (and (not (empty-slot? slot)) (eq? (is-red? card) (is-red? (get-top-card slot))) (not (= (get-value (get-top-card slot)) BASE-VAL)) (or (and (= (get-value card) king) (= (get-value (get-top-card slot)) ace)) (= (+ (get-value card) 1) (get-value (get-top-card slot)))))) (define (strip card-list) (cond ((< (length card-list) 2) (car card-list)) ((or (not (is-visible? (car (reverse card-list)))) (not (check-same-color-list card-list)) (not (check-straight-descending-list-base-low card-list))) (strip (reverse (cdr (reverse card-list))))) (#t (car (reverse card-list))))) (define (check-to-tableau? slot1 slot2) (cond ((= slot1 12) #f) ((or (= slot2 12) (empty-slot? slot1)) (check-to-tableau? (+ 1 slot1) 5)) ((and (not (= slot1 slot2)) (check-a-tableau (strip (get-cards slot1)) slot2)) (hint-move slot1 (find-card slot1 (strip (get-cards slot1))) slot2)) (#t (check-to-tableau? slot1 (+ 1 slot2))))) (define (check-deal?) (and (dealable?) (list 0 (G_"Deal more cards")))) (define (get-hint) (or (check-to-foundation? 5) (check-to-tableau? 5 6) (check-deal?) (list 0 (G_"Try rearranging the cards")))) (define (get-options) #f) (define (apply-options options) #f) (define (timeout) #f) (set-features droppable-feature dealable-feature) (set-lambda new-game button-pressed button-released button-clicked button-double-clicked game-continuable game-won get-hint get-options apply-options timeout droppable? dealable?)
59549938e3d489ddead711ec436b1eff582dd4cc57e3c5e5235007fcd6071c66
JPMoresmau/dbIDE
as-browser-integration.hs
module Main where import Language.Haskell.ASBrowser.Integration.CabalTest import Test.Tasty main :: IO() main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [cabalTests]
null
https://raw.githubusercontent.com/JPMoresmau/dbIDE/dae37edf67fbe55660e7e22c9c5356d0ada47c61/as-browser/integration/as-browser-integration.hs
haskell
module Main where import Language.Haskell.ASBrowser.Integration.CabalTest import Test.Tasty main :: IO() main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [cabalTests]
a5d0f6bfbdc30c74f87512e5ab0fc4f5cd2c166805aa1d5574e225cbd04e412c
malcolmreynolds/GSLL
monte-carlo-structs.lisp
CFFI - Grovel definitions for unix systems . 2009 - 06 - 06 09:32:30EDT monte-carlo-structs.lisp Time - stamp : < 2009 - 08 - 23 10:19:40EDT monte-carlo-structs.lisp > (in-package :gsl) #+linux (define "_GNU_SOURCE") When installed through Mac Ports , GSL .h files will be found ;;; in /opt/local/include. #+darwin (cc-flags "-I/opt/local/include/") (include "gsl/gsl_monte_plain.h") (cstruct plain-state "gsl_monte_plain_state" (dim "dim" :type sizet) (x "x" :type :pointer)) (include "gsl/gsl_monte_miser.h") (cstruct miser-state "gsl_monte_miser_state" (min-calls "min_calls" :type sizet) (min-calls-per-bisection "min_calls_per_bisection" :type sizet) (dither "dither" :type :double) (estimate-frac "estimate_frac" :type :double) (alpha "alpha" :type :double) (dim "dim" :type sizet) (estimate-style "estimate_style" :type :int) (depth "depth" :type :int) (verbose "verbose" :type :int) (x "x" :type :pointer) (xmid "xmid" :type :pointer) (sigma-l "sigma_l" :type :pointer) (sigma-r "sigma_r" :type :pointer) (fmax-l "fmax_l" :type :pointer) (fmax-r "fmax_r" :type :pointer) (fmin-l "fmin_l" :type :pointer) (fmin-r "fmin_r" :type :pointer) (fsum-l "fsum_l" :type :pointer) (fsum-r "fsum_r" :type :pointer) (fsum2-l "fsum2_l" :type :pointer) (fsum2-r "fsum2_r" :type :pointer) (hits-l "hits_l" :type :pointer) (hits-r "hits_r" :type :pointer)) (include "gsl/gsl_monte_vegas.h") (cstruct vegas-state "gsl_monte_vegas_state" ;; grid (dim "dim" :type sizet) (bins-max "bins_max" :type sizet) (bins "bins" :type :uint) ; uint (boxes "boxes" :type :uint) ; these are both counted along the axes (xi "xi" :type :pointer) (xin "xin" :type :pointer) (delx "delx" :type :pointer) (weight "weight" :type :pointer) (vol "vol" :type :double) (x "x" :type :pointer) (bin "bin" :type :pointer) (box "box" :type :pointer) (d "d" :type :pointer) ; distribution ;; control variables (alpha "alpha" :type :double) (mode "mode" :type :int) (verbose "verbose" :type :int) (iterations "iterations" :type :uint) (stage "stage" :type :int))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/calculus/monte-carlo-structs.lisp
lisp
in /opt/local/include. grid uint these are both counted along the axes distribution control variables
CFFI - Grovel definitions for unix systems . 2009 - 06 - 06 09:32:30EDT monte-carlo-structs.lisp Time - stamp : < 2009 - 08 - 23 10:19:40EDT monte-carlo-structs.lisp > (in-package :gsl) #+linux (define "_GNU_SOURCE") When installed through Mac Ports , GSL .h files will be found #+darwin (cc-flags "-I/opt/local/include/") (include "gsl/gsl_monte_plain.h") (cstruct plain-state "gsl_monte_plain_state" (dim "dim" :type sizet) (x "x" :type :pointer)) (include "gsl/gsl_monte_miser.h") (cstruct miser-state "gsl_monte_miser_state" (min-calls "min_calls" :type sizet) (min-calls-per-bisection "min_calls_per_bisection" :type sizet) (dither "dither" :type :double) (estimate-frac "estimate_frac" :type :double) (alpha "alpha" :type :double) (dim "dim" :type sizet) (estimate-style "estimate_style" :type :int) (depth "depth" :type :int) (verbose "verbose" :type :int) (x "x" :type :pointer) (xmid "xmid" :type :pointer) (sigma-l "sigma_l" :type :pointer) (sigma-r "sigma_r" :type :pointer) (fmax-l "fmax_l" :type :pointer) (fmax-r "fmax_r" :type :pointer) (fmin-l "fmin_l" :type :pointer) (fmin-r "fmin_r" :type :pointer) (fsum-l "fsum_l" :type :pointer) (fsum-r "fsum_r" :type :pointer) (fsum2-l "fsum2_l" :type :pointer) (fsum2-r "fsum2_r" :type :pointer) (hits-l "hits_l" :type :pointer) (hits-r "hits_r" :type :pointer)) (include "gsl/gsl_monte_vegas.h") (cstruct vegas-state "gsl_monte_vegas_state" (dim "dim" :type sizet) (bins-max "bins_max" :type sizet) (xi "xi" :type :pointer) (xin "xin" :type :pointer) (delx "delx" :type :pointer) (weight "weight" :type :pointer) (vol "vol" :type :double) (x "x" :type :pointer) (bin "bin" :type :pointer) (box "box" :type :pointer) (alpha "alpha" :type :double) (mode "mode" :type :int) (verbose "verbose" :type :int) (iterations "iterations" :type :uint) (stage "stage" :type :int))
6fb889956dcff521c4839ab4d26c151d49a7aab0337ceff46d7cf08cfbb35fd7
hammerlab/biokepi
pyensembl.ml
open Biokepi_run_environment open Common let pyensembl_env_key = "PYENSEMBL_CACHE_DIR" let get_cache_dir ~(run_with: Machine.t) = let open KEDSL in let cache_dir = Machine.(get_pyensembl_cache_dir run_with) in match cache_dir with | Some path -> path | None -> failwith "Tool depends on PyEnsembl, but the cache directory \ has not been set!" let set_cache_dir_command ~(run_with: Machine.t) = let open KEDSL in let cache_dir_value = get_cache_dir ~run_with in Program.(shf "export %s='%s'" pyensembl_env_key cache_dir_value) let cache_genome ~(run_with: Machine.t) ~reference_build = let open KEDSL in let pyensembl = Machine.get_tool run_with Machine.Tool.Default.pyensembl in let genome = Machine.(get_reference_genome run_with reference_build) in let ensembl_release = genome |> Reference_genome.ensembl in let species = genome |> Reference_genome.species in let witness_file_path = sprintf "%s/%s.cached" (get_cache_dir ~run_with) reference_build in let name = sprintf "pyensembl_cache-%d-%s" ensembl_release species in workflow_node (single_file witness_file_path ~host:(Machine.as_host run_with)) ~name ~edges:[ depends_on Machine.Tool.(ensure pyensembl); ] ~make:( Machine.run_download_program run_with ~requirements:[`Internet_access;] ~name Program.( Machine.Tool.(init pyensembl) && (set_cache_dir_command ~run_with) && shf "pyensembl install --release %d --species \"%s\"" ensembl_release species && exec ["touch"; witness_file_path] ) )
null
https://raw.githubusercontent.com/hammerlab/biokepi/d64eb2c891b41bda3444445cd2adf4e3251725d4/src/bfx_tools/pyensembl.ml
ocaml
open Biokepi_run_environment open Common let pyensembl_env_key = "PYENSEMBL_CACHE_DIR" let get_cache_dir ~(run_with: Machine.t) = let open KEDSL in let cache_dir = Machine.(get_pyensembl_cache_dir run_with) in match cache_dir with | Some path -> path | None -> failwith "Tool depends on PyEnsembl, but the cache directory \ has not been set!" let set_cache_dir_command ~(run_with: Machine.t) = let open KEDSL in let cache_dir_value = get_cache_dir ~run_with in Program.(shf "export %s='%s'" pyensembl_env_key cache_dir_value) let cache_genome ~(run_with: Machine.t) ~reference_build = let open KEDSL in let pyensembl = Machine.get_tool run_with Machine.Tool.Default.pyensembl in let genome = Machine.(get_reference_genome run_with reference_build) in let ensembl_release = genome |> Reference_genome.ensembl in let species = genome |> Reference_genome.species in let witness_file_path = sprintf "%s/%s.cached" (get_cache_dir ~run_with) reference_build in let name = sprintf "pyensembl_cache-%d-%s" ensembl_release species in workflow_node (single_file witness_file_path ~host:(Machine.as_host run_with)) ~name ~edges:[ depends_on Machine.Tool.(ensure pyensembl); ] ~make:( Machine.run_download_program run_with ~requirements:[`Internet_access;] ~name Program.( Machine.Tool.(init pyensembl) && (set_cache_dir_command ~run_with) && shf "pyensembl install --release %d --species \"%s\"" ensembl_release species && exec ["touch"; witness_file_path] ) )
88971486e81040e1ca903b936ee71d9f89c06282c2a60f00010a69650a6b65bf
webyrd/mediKanren
CHAMP1_RNA_seq.rkt
#lang racket (require "../../../medikanren/pieces-parts/query.rkt" "../pieces-parts/Thi-useful-functions.rkt") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*********GENERAL SEARCH********;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; *** Data Sources: - Processed CHAMP1 RNAseq data from outside of mediKanren ;; - RNA was obtained from patients or control ;; cultured fibroblasts derived from skin biopsies ;; ;; *** Objective: Repurpose drugs for CHAMP1 genetic disorder using RNAseq data from patients - derived skin fibroblasts ;; ;; *** Please find the case presentation at First , I 'm doing exploratory searches for the disease information related to CHAMP1 genes : Find disease conditions that are related to CHAMP1 genes (curie-synonyms/names "HGNC:20311") (define CHAMP1 "HGNC:20311") Check the diseases and conditions associted with the CHAMP1 gene (define q-disease-CHAMP1 (time (query/graph ((S disease) (O CHAMP1)) ((S->O #f)) (S S->O O)))) (define disease-CHAMP1-edges (edges/query q-disease-CHAMP1 'S->O)) The results show that CHAMP1 gene ( chromosome alignment - maintaining phosphoprotein , is a protein - coding gene , a member of the zinc fingers C2H2 - types protein , located on chromosome 13q34 ) ;; is associated with certain disease conditions such as ;; mental retardation (autosomal dominant), rare (non-syndromic) intellectual disability, monogenic genetic ;; central nervous system disorder, mental disorder, and psychiatric disorder. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*******STRATEGY NUMBER 1*******;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; In this strategy, we want to find drugs that target the genes that belong to enriched functional categories such as cell cycle and cell senescence , retinol metabolism ( which are results from gene set enrichemnet analysis ( GSEA ) performed ;; outside of medikanren). GSEA has identified a number of genes that are upregulated in CHAMP1 fibroblasts compared to control fibroblasts . First , find HGNC CURIEs ( " HGNC : " ) of each gene from the gene name ( either by using genecards database " / " or using mediKanren 's find - concepts ;; ,then check if they are synonymized. If the CURIE is synonymized , we use it to define the gene / protein in query / graph ;; eg: (find-concepts #f (list "VIM")) (curie-synonyms/names "HGNC:1583") ;; genes that are altered in the cell cycle pathway: (define CCND2 "HGNC:1583") ;; cell cycle up-regulated (define TUBA1A "HGNC:20766") ;; cell cycle down-regulated ;; cell senescence pathway: ;(define CCND2 "HGNC:1583") ;; up-regulated (define RASSF5 "HGNC:17609") ;; up-regulated ;; DNA replication| apoptosis (define PSMA5 "HGNC:9534");; up-regulated meiosis | progesterone - mediated oocyte maturation| calcium signaling (define ADCY4 "HGNC:235");; up-regulate ;; retinol metabolism: (define ALDH1A1 "HGNC:402");; up-regulated ABC transporter : (define ABCA13 "HGNC:14638");; up-regulated ;; HIV infection| calcium (define PTK2B "HGNC:9612");; up-regulated (define AP1G2 "HGNC:556");; up-regulated ;; amyotropic lateral sclerosis | apoptosis (define TNFRSF1B "HGNC:11917");; down-regulated ;; regulation of actin cytoskeleton: (define FGF10 "HGNC:3666");; up-regulated (define CHRM2 "HGNC:1951");; down-regulated ;; Gonadotropin hormone-releasing (define KCNN4 "HGNC:6293");; down-regulated ;; ECM receptor interaction: (define CD36 "HGNC:1663");; up-regulated Neuroactive ligand - receptor interaction | calcium (define EDNRB "HGNC:3180") ;; up-regulated (define LHB "HGNC:6584");; down-regulated ;; mRNA surveillance: (define MSI2 "HGNC:18585") ;; down-regulated ;; calcium ;(define ADCY4 "HGNC:235");; up-regulated ( define PTK2B " HGNC:9612 " ) ; ; up - regulated (define ERBB4 "HGNC:3432");; up-regulated ( define " HGNC:1951 " ) ; ; down - regulated ;(define EDNRB "HGNC:3180") ;; up-regulated ;; apoptosis: (define VIM "HGNC:12692");; down-regulated ;; All selected upregulated genes in enriched functional categories are: (define functional-cat-up (list CCND2 RASSF5 PSMA5 ADCY4 ALDH1A1 ABCA13 PTK2B AP1G2 FGF10 CD36 EDNRB EDNRB ERBB4)) (define functional-cat-down (list TUBA1A TNFRSF1B CHRM2 KCNN4 LHB MSI2 VIM)) (define results-CHAMP1-functional-cat-down (find-drugs-for-genes functional-cat-up positively-regulates)) (define results-CHAMP1-functional-cat-up (find-drugs-for-genes functional-cat-up negatively-regulates)) ;;extract drug=>gene hash-table: (define drug=>gene-CHAMP1-functional-cat-down (car results-CHAMP1-functional-cat-down)) (define drug=>gene-CHAMP1-functional-cat-up (car results-CHAMP1-functional-cat-up)) extract gene=>drug hash - table : (define gene=>drug-CHAMP1-functional-cat-down (cadr results-CHAMP1-functional-cat-down)) (define gene=>drug-CHAMP1-functional-cat-up (car results-CHAMP1-functional-cat-up)) (define drug=>gene-strategy1 (merge-assoc-lists (list drug=>gene-CHAMP1-functional-cat-down drug=>gene-CHAMP1-functional-cat-up))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; * * * * * * * STRATEGY NUMBER 2 * * * * * * * ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; Based on literature research , we identifed 5 different disease conditions that are associated with CHAMP1 genetic disorder : (define hypotonia-concepts (find-concepts #f (list "hypotonia"))) (define cerebral-palsy-concepts (find-concepts #f (list "cerebral palsy"))) (define autism-concepts (find-concepts #f (list "autism"))) (define dev-delay-concepts (find-concepts #f (list "developmental delay"))) (define epilepsy-concepts (find-concepts #f (list "epilepsy"))) In this 2nd strategy , we first search for all the genes that are associated with the five CHAMP1 ;; disease associated conditions using run/graph (match-define (list name=>concepts name=>edges) (run/graph ((S #f) (O (set-union hypotonia-concepts cerebral-palsy-concepts autism-concepts dev-delay-concepts epilepsy-concepts))) ((S->O gene-to-disease-preds)) (S S->O O))) ;; filter the subjects to retain only genes or proteins and get their names: (map (lambda (y) (cons (concept->curie y) (concept->name y))) (filter (lambda (x) (gene/protein-concept? (concept->curie x))) (hash-ref name=>concepts 'S))) This filter results in 1397 genes / proteins that are related to CHAMP1 patients ' phenotypes . ;; I then cleaned the data, converted it to .csv and mapped different gene/protein identifers to HGNC symbols then I removed duplicates and NA . This resulted in 934 genes . ;; Using these genes, I plot a volcano plot that show differences in expression levels between CHAMP1 patients fibroblasts vs control fibroblasts . ;; This visualisation shows genes that are statistically significantly altered between these two conditions . These genes become our drug targets . Now we want to find drugs that reverse the directions of DEG genes ( which are genes found to be associated with CHAMP1 patients ' phenotypes- the results from the run / graph above . Directionality is provided by gene expression values ( determined by experiments on CHAMP1 patients ' fibroblasts ) . ;; For genes that are significantly upregulated, we want to find drugs that decrease their expression, and vice versa. ;; Abstract genes that are upregulated: (define CACNB4 "HGNC:1404") (define PRICKLE1 "HGNC:17019") (define DMD "HGNC:2928") (define SHANK2 "HGNC:14295") (define MAP2 "HGNC:6839") (define H19 "HGNC:4713") (define BCHE "HGNC:983") (define EFNA5 "HGNC:3225") (define CNTNAP2 "HGNC:13830") (define ANKH "HGNC:15492") (define SLC12A6 "HGNC:10914") (define CHAMP1-phenotype-RNA-up (list CACNB4 PRICKLE1 DMD SHANK2 MAP2 H19 BCHE EFNA5 CNTNAP2 ANKH SLC12A6)) ;; Alternatively, for genes that are significantly downregulatated, we want to find drugs that increase their expression: (define GABRA5 "HGNC:4079") ;(define TNFRSF1B "HGNC:11917") (define STX1B "HGNC:18539") (define RBFA "HGNC:26120") (define CHAMP1-phenotype-RNA-down (list GABRA5 TNFRSF1B STX1B RBFA)) ;; Now we use the function find-drugs-for-genes in Thi's-useful-functions: (define results-CHAMP1-phenotype-RNA-up (find-drugs-for-genes CHAMP1-phenotype-RNA-up negatively-regulates)) (define drug=>gene-CHAMP1-phenotype-RNA-up (car results-CHAMP1-phenotype-RNA-up)) (define gene=>drug-CHAMP1-phenotype-RNA-up (cadr results-CHAMP1-phenotype-RNA-up)) (define results-CHAMP1-phenotype-RNA-down (find-drugs-for-genes CHAMP1-phenotype-RNA-down positively-regulates)) (define drug=>gene-CHAMP1-phenotype-RNA-down (car results-CHAMP1-phenotype-RNA-down)) (define gene=>drug-CHAMP1-phenotype-RNA-down (cadr results-CHAMP1-phenotype-RNA-down)) ;; use the get-num-values function in Thi's-useful-functions: (define drug=>gene-CHAMP1-phenotype-RNA-up-with-stats (get-num-values drug=>gene-CHAMP1-phenotype-RNA-up)) (define gene=>drug-CHAMP1-phenotype-RNA-up-with-stats (get-num-values gene=>drug-CHAMP1-phenotype-RNA-up)) (define drug=>gene-CHAMP1-phenotype-RNA-down-with-stats (get-num-values drug=>gene-CHAMP1-phenotype-RNA-down)) (define gene=>drug-CHAMP1-phenotype-RNA-down-with-stats (get-num-values gene=>drug-CHAMP1-phenotype-RNA-down)) (define merged_strategy2 (merge-2-assoc-list drug=>gene-CHAMP1-phenotype-RNA-up drug=>gene-CHAMP1-phenotype-RNA-down)) (define merged_trategy2_count (get-num-values (car merged_strategy2))) (define merged_strategy2_genes (merge-2-assoc-list gene=>drug-CHAMP1-phenotype-RNA-up gene=>drug-CHAMP1-phenotype-RNA-down)) (define merged_trategy2_genes_count (get-num-values (car merged_strategy2_genes))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;*******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; * * * * * * * STRATEGY NUMBER 3 * * * * * * * ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; 2 - edge queries to find drugs that treat the CHAMP1 disease conditions and reverse the gene expression directions : ;; These are all significantly altered genes in differential expression analyses performed outside of mediKanren (define CHAMP1-DE-RNA-up (list "ENSEMBL:ENSG00000228630" "ENSEMBL:ENSG00000261340" "ENSEMBL:ENSG00000083937" "ENSEMBL:ENSG00000143106" "ENSEMBL:ENSG00000140199" "ENSEMBL:ENSG00000065357" "ENSEMBL:ENSG00000129480" "ENSEMBL:ENSG00000162688" "ENSEMBL:ENSG00000180818" "ENSEMBL:ENSG00000136478" "ENSEMBL:ENSG00000065413" "ENSEMBL:ENSG00000167394" "ENSEMBL:ENSG00000163249" "ENSEMBL:ENSG00000118762" "ENSEMBL:ENSG00000185070" "ENSEMBL:ENSG00000089060" "ENSEMBL:ENSG00000173221" "ENSEMBL:ENSG00000175040" "ENSEMBL:ENSG00000112964" "ENSEMBL:ENSG00000111670" "ENSEMBL:ENSG00000119986" "ENSEMBL:ENSG00000106415" "ENSEMBL:ENSG00000038427" "ENSEMBL:ENSG00000154122" "ENSEMBL:ENSG00000176531" "ENSEMBL:ENSG00000121413" "ENSEMBL:ENSG00000176809" "ENSEMBL:ENSG00000165804" "ENSEMBL:ENSG00000198948" "ENSEMBL:ENSG00000012171" "ENSEMBL:ENSG00000267454" "ENSEMBL:ENSG00000182379" "ENSEMBL:ENSG00000213983" "ENSEMBL:ENSG00000169313" "ENSEMBL:ENSG00000137573" "ENSEMBL:ENSG00000174469" "ENSEMBL:ENSG00000189129" "ENSEMBL:ENSG00000112378" "ENSEMBL:ENSG00000136048" "ENSEMBL:ENSG00000101134" "ENSEMBL:ENSG00000176928" "ENSEMBL:ENSG00000184916" "ENSEMBL:ENSG00000162643" "ENSEMBL:ENSG00000266094" "ENSEMBL:ENSG00000150540" "ENSEMBL:ENSG00000176771" "ENSEMBL:ENSG00000138772" "ENSEMBL:ENSG00000115271" "ENSEMBL:ENSG00000250133" "ENSEMBL:ENSG00000179104" "ENSEMBL:ENSG00000145390" "ENSEMBL:ENSG00000184349" "ENSEMBL:ENSG00000101605" "ENSEMBL:ENSG00000205002" "ENSEMBL:ENSG00000198133" "ENSEMBL:ENSG00000205835" "ENSEMBL:ENSG00000165113" "ENSEMBL:ENSG00000172403" "ENSEMBL:ENSG00000120899" "ENSEMBL:ENSG00000174600" "ENSEMBL:ENSG00000099260" "ENSEMBL:ENSG00000137727" "ENSEMBL:ENSG00000136160" "ENSEMBL:ENSG00000182901" "ENSEMBL:ENSG00000112981" "ENSEMBL:ENSG00000242600" "ENSEMBL:ENSG00000115604" "ENSEMBL:ENSG00000144229" "ENSEMBL:ENSG00000151623" "ENSEMBL:ENSG00000165023" "ENSEMBL:ENSG00000152804" "ENSEMBL:ENSG00000112379" "ENSEMBL:ENSG00000082497" "ENSEMBL:ENSG00000144645" "ENSEMBL:ENSG00000196208" "ENSEMBL:ENSG00000228495" "ENSEMBL:ENSG00000135919" "ENSEMBL:ENSG00000211448" "ENSEMBL:ENSG00000141449" "ENSEMBL:ENSG00000203727" "ENSEMBL:ENSG00000013588" "ENSEMBL:ENSG00000130600" "ENSEMBL:ENSG00000126861" "ENSEMBL:ENSG00000165084" "ENSEMBL:ENSG00000179869" "ENSEMBL:ENSG00000114200" "ENSEMBL:ENSG00000143028" "ENSEMBL:ENSG00000164106" "ENSEMBL:ENSG00000138449" "ENSEMBL:ENSG00000110723" "ENSEMBL:ENSG00000162687" "ENSEMBL:ENSG00000183775" "ENSEMBL:ENSG00000106538" "ENSEMBL:ENSG00000064225" "ENSEMBL:ENSG00000086289" "ENSEMBL:ENSG00000070193" "ENSEMBL:ENSG00000116183" "ENSEMBL:ENSG00000102109" "ENSEMBL:ENSG00000078018" "ENSEMBL:ENSG00000099864" "ENSEMBL:ENSG00000173391" "ENSEMBL:ENSG00000198947" "ENSEMBL:ENSG00000139174" "ENSEMBL:ENSG00000165092" "ENSEMBL:ENSG00000162105" "ENSEMBL:ENSG00000137672" "ENSEMBL:ENSG00000178568" "ENSEMBL:ENSG00000064042" "ENSEMBL:ENSG00000135218" "ENSEMBL:ENSG00000126785" "ENSEMBL:ENSG00000240694" "ENSEMBL:ENSG00000248874" "ENSEMBL:ENSG00000118971" "ENSEMBL:ENSG00000182389" "ENSEMBL:ENSG00000129467" "ENSEMBL:ENSG00000106483" "ENSEMBL:ENSG00000123572")) (define CHAMP1-DE-RNA-down (list "EMSEMBL:ENSG00000204792" "EMSEMBL:ENSG00000166796" "EMSEMBL:ENSG00000186297" "EMSEMBL:ENSG00000005379" "EMSEMBL:ENSG00000234465" "EMSEMBL:ENSG00000165887" "EMSEMBL:ENSG00000115648" "EMSEMBL:ENSG00000102575" "EMSEMBL:ENSG00000175084" "EMSEMBL:ENSG00000145824" "EMSEMBL:ENSG00000213030" "EMSEMBL:ENSG00000132639" "EMSEMBL:ENSG00000006606" "EMSEMBL:ENSG00000101017" "EMSEMBL:ENSG00000154451" "EMSEMBL:ENSG00000169429" "EMSEMBL:ENSG00000104826" "EMSEMBL:ENSG00000163618" "EMSEMBL:ENSG00000147573" "EMSEMBL:ENSG00000171517" "EMSEMBL:ENSG00000130720" "EMSEMBL:ENSG00000157557" "EMSEMBL:ENSG00000178882" "EMSEMBL:ENSG00000156453" "EMSEMBL:ENSG00000148803" "EMSEMBL:ENSG00000107611" "EMSEMBL:ENSG00000175294" "EMSEMBL:ENSG00000181072" "EMSEMBL:ENSG00000104783" "EMSEMBL:ENSG00000128285" "EMSEMBL:ENSG00000080823" "EMSEMBL:ENSG00000167889" "EMSEMBL:ENSG00000124191" "EMSEMBL:ENSG00000163701" "EMSEMBL:ENSG00000076706" "EMSEMBL:ENSG00000144354" "EMSEMBL:ENSG00000103034" "EMSEMBL:ENSG00000164929" "EMSEMBL:ENSG00000204103" "EMSEMBL:ENSG00000242265" "EMSEMBL:ENSG00000196460" "EMSEMBL:ENSG00000138395" "EMSEMBL:ENSG00000225968" "EMSEMBL:ENSG00000028137" "EMSEMBL:ENSG00000091622" "EMSEMBL:ENSG00000125968" "EMSEMBL:ENSG00000173848" "EMSEMBL:ENSG00000239332" "EMSEMBL:ENSG00000139278" "EMSEMBL:ENSG00000137563" "EMSEMBL:ENSG00000163814" "EMSEMBL:ENSG00000121904" "EMSEMBL:ENSG00000186847" "EMSEMBL:ENSG00000099365" "EMSEMBL:ENSG00000136490" "EMSEMBL:ENSG00000100181" "EMSEMBL:ENSG00000079462" "EMSEMBL:ENSG00000026025" "EMSEMBL:ENSG00000105255" "EMSEMBL:ENSG00000188064" "EMSEMBL:ENSG00000103449" "EMSEMBL:ENSG00000235162" "EMSEMBL:ENSG00000074410" "EMSEMBL:ENSG00000170961" "EMSEMBL:ENSG00000140280" "EMSEMBL:ENSG00000187583" "EMSEMBL:ENSG00000205683" "EMSEMBL:ENSG00000109062" "EMSEMBL:ENSG00000159231" "EMSEMBL:ENSG00000183077" "EMSEMBL:ENSG00000173588" "EMSEMBL:ENSG00000167552" "EMSEMBL:ENSG00000243156" "EMSEMBL:ENSG00000166886" "EMSEMBL:ENSG00000153944" "EMSEMBL:ENSG00000196912" "EMSEMBL:ENSG00000183506" "EMSEMBL:ENSG00000156535" "EMSEMBL:ENSG00000087266" "EMSEMBL:ENSG00000170921" "EMSEMBL:ENSG00000185052" "EMSEMBL:ENSG00000089486" "EMSEMBL:ENSG00000196155" "EMSEMBL:ENSG00000101546" "EMSEMBL:ENSG00000038382" "EMSEMBL:ENSG00000167460" "EMSEMBL:ENSG00000186281" "EMSEMBL:ENSG00000130309" "EMSEMBL:ENSG00000054523" "EMSEMBL:ENSG00000100097" "EMSEMBL:ENSG00000142892" "EMSEMBL:ENSG00000231419" "EMSEMBL:ENSG00000163687")) define CHAMP1 disease related conditions : (define dev-delay "HP:0001263") (define hypotonia "HP:0001252") (define cerebral-palsy "HP:0100021") (define autism "MONDO:0005260") (define epilepsy "MONDO:0005027") The function find - drug - for - condition takes a disease condition , a gene list ( derived from RNA - seq DEG results ) ;; a list of drug-to-gene predicates that we want the drug to modulate. This function will run a query / graph that does a 2 - edge query which find drugs that modify the disease condition ;; while also modulate the gene in the gene list this function will return a list which contains 2 hash - tables which are sorted based on the number ;; of genes or drugs available: ; Use the find-drug-for-condition from Thi-useful-functions.rkt: (define dev-delay-drug-results-RNA-up (find-drug-for-condition dev-delay CHAMP1-DE-RNA-up negatively-regulates)) (define dev-delay-drug-results-RNA-down (find-drug-for-condition dev-delay CHAMP1-DE-RNA-down positively-regulates)) (define hypotonia-drug-results-RNA-up (find-drug-for-condition hypotonia CHAMP1-DE-RNA-up negatively-regulates)) (define hypotonia-drug-results-RNA-down (find-drug-for-condition hypotonia CHAMP1-DE-RNA-up negatively-regulates)) (define cerebral-palsy-drug-results-RNA-up (find-drug-for-condition cerebral-palsy CHAMP1-DE-RNA-up negatively-regulates)) (define cerebral-palsy-drug-results-RNA-down (find-drug-for-condition cerebral-palsy CHAMP1-DE-RNA-down positively-regulates)) (define autism-drug-results-RNA-up (find-drug-for-condition autism CHAMP1-DE-RNA-up negatively-regulates)) (define autism-drug-results-RNA-down (find-drug-for-condition autism CHAMP1-DE-RNA-down positively-regulates)) (define epilepsy-drug-results-RNA-up (find-drug-for-condition epilepsy CHAMP1-DE-RNA-up negatively-regulates)) (define epilepsy-drug-results-RNA-down (find-drug-for-condition epilepsy CHAMP1-DE-RNA-down positively-regulates)) ;; Extract gene=>drug and drug=>gene tables: (define drug=>gene-dev-delay-drug-results-RNA-up (car dev-delay-drug-results-RNA-up)) (define gene=>drug-dev-delay-drug-results-RNA-up (cadr dev-delay-drug-results-RNA-up)) (define drug=>gene-dev-delay-drug-results-RNA-down (car dev-delay-drug-results-RNA-down)) (define gene=>drug-dev-delay-drug-results-RNA-down (cadr dev-delay-drug-results-RNA-down)) (define drug=>gene-hypotonia-drug-results-RNA-up (car hypotonia-drug-results-RNA-up)) (define gene=>drug-hypotonia-drug-results-RNA-up (cadr hypotonia-drug-results-RNA-up)) (define drug=>gene-hypotonia-drug-results-RNA-down (car hypotonia-drug-results-RNA-down)) (define gene=>drug-hypotonia-drug-results-RNA-down (cadr hypotonia-drug-results-RNA-down)) (define drug=>gene-cerebral-palsy-drug-results-RNA-up (car cerebral-palsy-drug-results-RNA-up)) (define gene=>drug-cerebral-palsy-drug-results-RNA-up (cadr cerebral-palsy-drug-results-RNA-up)) (define drug=>gene-cerebral-palsy-drug-results-RNA-down (car cerebral-palsy-drug-results-RNA-down)) (define gene=>drug-cerebral-palsy-drug-results-RNA-down (cadr cerebral-palsy-drug-results-RNA-down)) (define drug=>gene-autism-drug-results-RNA-up (car autism-drug-results-RNA-up)) (define gene=>drug-autism-drug-results-RNA-up (cadr autism-drug-results-RNA-up)) (define drug=>gene-autism-drug-results-RNA-down (car autism-drug-results-RNA-down)) (define gene=>drug-autism-drug-results-RNA-down (cadr autism-drug-results-RNA-down)) (define drug=>gene-epilepsy-drug-results-RNA-up (car epilepsy-drug-results-RNA-up)) (define gene=>drug-epilepsy-drug-results-RNA-up (cadr epilepsy-drug-results-RNA-up)) (define drug=>gene-epilepsy-drug-results-RNA-down (car epilepsy-drug-results-RNA-down)) (define gene=>drug-epilepsy-drug-results-RNA-down (cadr epilepsy-drug-results-RNA-down)) combine 10 association lists : (define strategy3_results (merge-assoc-lists (list drug=>gene-dev-delay-drug-results-RNA-up drug=>gene-dev-delay-drug-results-RNA-down drug=>gene-hypotonia-drug-results-RNA-up drug=>gene-hypotonia-drug-results-RNA-down drug=>gene-cerebral-palsy-drug-results-RNA-up drug=>gene-cerebral-palsy-drug-results-RNA-down drug=>gene-autism-drug-results-RNA-up drug=>gene-autism-drug-results-RNA-down drug=>gene-epilepsy-drug-results-RNA-up drug=>gene-epilepsy-drug-results-RNA-down))) (define strategy3_genes_results (merge-assoc-lists (list gene=>drug-dev-delay-drug-results-RNA-up gene=>drug-dev-delay-drug-results-RNA-down gene=>drug-hypotonia-drug-results-RNA-up gene=>drug-hypotonia-drug-results-RNA-down gene=>drug-cerebral-palsy-drug-results-RNA-up gene=>drug-cerebral-palsy-drug-results-RNA-down gene=>drug-autism-drug-results-RNA-up gene=>drug-autism-drug-results-RNA-down gene=>drug-epilepsy-drug-results-RNA-up gene=>drug-epilepsy-drug-results-RNA-down))) ; sort them by the values: (define strategy3_results-count (get-num-values (car strategy3_results))) (define strategy3_results-genes-count (get-num-values (car strategy3_genes_results)))
null
https://raw.githubusercontent.com/webyrd/mediKanren/a2b80ea94f66bcdd4305b9369ad4184c2afe9829/contrib/medikanren/use-cases/CHAMP1_RNA_seq.rkt
racket
*******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *********GENERAL SEARCH********;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *** Data Sources: - RNA was obtained from patients or control cultured fibroblasts derived from skin biopsies *** Objective: *** Please find the case presentation at is associated with certain disease conditions such as mental retardation (autosomal dominant), rare (non-syndromic) intellectual disability, monogenic genetic central nervous system disorder, mental disorder, and psychiatric disorder. *******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; *******STRATEGY NUMBER 1*******;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; In this strategy, we want to find drugs that target the genes that belong to enriched functional categories outside of medikanren). ,then check if they are synonymized. eg: genes that are altered in the cell cycle pathway: cell cycle up-regulated cell cycle down-regulated cell senescence pathway: (define CCND2 "HGNC:1583") ;; up-regulated up-regulated DNA replication| apoptosis up-regulated up-regulate retinol metabolism: up-regulated up-regulated HIV infection| calcium up-regulated up-regulated amyotropic lateral sclerosis | apoptosis down-regulated regulation of actin cytoskeleton: up-regulated down-regulated Gonadotropin hormone-releasing down-regulated ECM receptor interaction: up-regulated up-regulated down-regulated mRNA surveillance: down-regulated calcium (define ADCY4 "HGNC:235");; up-regulated ; up - regulated up-regulated ; down - regulated (define EDNRB "HGNC:3180") ;; up-regulated apoptosis: down-regulated All selected upregulated genes in enriched functional categories are: extract drug=>gene hash-table: *******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; disease associated conditions using run/graph filter the subjects to retain only genes or proteins and get their names: I then cleaned the data, converted it to .csv and mapped different gene/protein identifers to HGNC symbols Using these genes, I plot a volcano plot that show differences in expression levels between This visualisation shows genes that are statistically significantly altered between these For genes that are significantly upregulated, we want to find drugs that decrease their expression, and vice versa. Abstract genes that are upregulated: Alternatively, for genes that are significantly downregulatated, we want to find drugs that increase their expression: (define TNFRSF1B "HGNC:11917") Now we use the function find-drugs-for-genes in Thi's-useful-functions: use the get-num-values function in Thi's-useful-functions: *******************************;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; These are all significantly altered genes in differential expression analyses performed outside of mediKanren a list of drug-to-gene predicates that we want the drug to modulate. while also modulate the gene in the gene list of genes or drugs available: Use the find-drug-for-condition from Thi-useful-functions.rkt: Extract gene=>drug and drug=>gene tables: sort them by the values:
#lang racket (require "../../../medikanren/pieces-parts/query.rkt" "../pieces-parts/Thi-useful-functions.rkt") - Processed CHAMP1 RNAseq data from outside of mediKanren Repurpose drugs for CHAMP1 genetic disorder using RNAseq data from patients - derived skin fibroblasts First , I 'm doing exploratory searches for the disease information related to CHAMP1 genes : Find disease conditions that are related to CHAMP1 genes (curie-synonyms/names "HGNC:20311") (define CHAMP1 "HGNC:20311") Check the diseases and conditions associted with the CHAMP1 gene (define q-disease-CHAMP1 (time (query/graph ((S disease) (O CHAMP1)) ((S->O #f)) (S S->O O)))) (define disease-CHAMP1-edges (edges/query q-disease-CHAMP1 'S->O)) The results show that CHAMP1 gene ( chromosome alignment - maintaining phosphoprotein , is a protein - coding gene , a member of the zinc fingers C2H2 - types protein , located on chromosome 13q34 ) such as cell cycle and cell senescence , retinol metabolism ( which are results from gene set enrichemnet analysis ( GSEA ) performed GSEA has identified a number of genes that are upregulated in CHAMP1 fibroblasts compared to control fibroblasts . First , find HGNC CURIEs ( " HGNC : " ) of each gene from the gene name ( either by using genecards database " / " or using mediKanren 's find - concepts If the CURIE is synonymized , we use it to define the gene / protein in query / graph (find-concepts #f (list "VIM")) (curie-synonyms/names "HGNC:1583") meiosis | progesterone - mediated oocyte maturation| calcium signaling ABC transporter : Neuroactive ligand - receptor interaction | calcium (define functional-cat-up (list CCND2 RASSF5 PSMA5 ADCY4 ALDH1A1 ABCA13 PTK2B AP1G2 FGF10 CD36 EDNRB EDNRB ERBB4)) (define functional-cat-down (list TUBA1A TNFRSF1B CHRM2 KCNN4 LHB MSI2 VIM)) (define results-CHAMP1-functional-cat-down (find-drugs-for-genes functional-cat-up positively-regulates)) (define results-CHAMP1-functional-cat-up (find-drugs-for-genes functional-cat-up negatively-regulates)) (define drug=>gene-CHAMP1-functional-cat-down (car results-CHAMP1-functional-cat-down)) (define drug=>gene-CHAMP1-functional-cat-up (car results-CHAMP1-functional-cat-up)) extract gene=>drug hash - table : (define gene=>drug-CHAMP1-functional-cat-down (cadr results-CHAMP1-functional-cat-down)) (define gene=>drug-CHAMP1-functional-cat-up (car results-CHAMP1-functional-cat-up)) (define drug=>gene-strategy1 (merge-assoc-lists (list drug=>gene-CHAMP1-functional-cat-down drug=>gene-CHAMP1-functional-cat-up))) Based on literature research , we identifed 5 different disease conditions that are associated with CHAMP1 genetic disorder : (define hypotonia-concepts (find-concepts #f (list "hypotonia"))) (define cerebral-palsy-concepts (find-concepts #f (list "cerebral palsy"))) (define autism-concepts (find-concepts #f (list "autism"))) (define dev-delay-concepts (find-concepts #f (list "developmental delay"))) (define epilepsy-concepts (find-concepts #f (list "epilepsy"))) In this 2nd strategy , we first search for all the genes that are associated with the five CHAMP1 (match-define (list name=>concepts name=>edges) (run/graph ((S #f) (O (set-union hypotonia-concepts cerebral-palsy-concepts autism-concepts dev-delay-concepts epilepsy-concepts))) ((S->O gene-to-disease-preds)) (S S->O O))) (map (lambda (y) (cons (concept->curie y) (concept->name y))) (filter (lambda (x) (gene/protein-concept? (concept->curie x))) (hash-ref name=>concepts 'S))) This filter results in 1397 genes / proteins that are related to CHAMP1 patients ' phenotypes . then I removed duplicates and NA . This resulted in 934 genes . CHAMP1 patients fibroblasts vs control fibroblasts . two conditions . These genes become our drug targets . Now we want to find drugs that reverse the directions of DEG genes ( which are genes found to be associated with CHAMP1 patients ' phenotypes- the results from the run / graph above . Directionality is provided by gene expression values ( determined by experiments on CHAMP1 patients ' fibroblasts ) . (define CACNB4 "HGNC:1404") (define PRICKLE1 "HGNC:17019") (define DMD "HGNC:2928") (define SHANK2 "HGNC:14295") (define MAP2 "HGNC:6839") (define H19 "HGNC:4713") (define BCHE "HGNC:983") (define EFNA5 "HGNC:3225") (define CNTNAP2 "HGNC:13830") (define ANKH "HGNC:15492") (define SLC12A6 "HGNC:10914") (define CHAMP1-phenotype-RNA-up (list CACNB4 PRICKLE1 DMD SHANK2 MAP2 H19 BCHE EFNA5 CNTNAP2 ANKH SLC12A6)) (define GABRA5 "HGNC:4079") (define STX1B "HGNC:18539") (define RBFA "HGNC:26120") (define CHAMP1-phenotype-RNA-down (list GABRA5 TNFRSF1B STX1B RBFA)) (define results-CHAMP1-phenotype-RNA-up (find-drugs-for-genes CHAMP1-phenotype-RNA-up negatively-regulates)) (define drug=>gene-CHAMP1-phenotype-RNA-up (car results-CHAMP1-phenotype-RNA-up)) (define gene=>drug-CHAMP1-phenotype-RNA-up (cadr results-CHAMP1-phenotype-RNA-up)) (define results-CHAMP1-phenotype-RNA-down (find-drugs-for-genes CHAMP1-phenotype-RNA-down positively-regulates)) (define drug=>gene-CHAMP1-phenotype-RNA-down (car results-CHAMP1-phenotype-RNA-down)) (define gene=>drug-CHAMP1-phenotype-RNA-down (cadr results-CHAMP1-phenotype-RNA-down)) (define drug=>gene-CHAMP1-phenotype-RNA-up-with-stats (get-num-values drug=>gene-CHAMP1-phenotype-RNA-up)) (define gene=>drug-CHAMP1-phenotype-RNA-up-with-stats (get-num-values gene=>drug-CHAMP1-phenotype-RNA-up)) (define drug=>gene-CHAMP1-phenotype-RNA-down-with-stats (get-num-values drug=>gene-CHAMP1-phenotype-RNA-down)) (define gene=>drug-CHAMP1-phenotype-RNA-down-with-stats (get-num-values gene=>drug-CHAMP1-phenotype-RNA-down)) (define merged_strategy2 (merge-2-assoc-list drug=>gene-CHAMP1-phenotype-RNA-up drug=>gene-CHAMP1-phenotype-RNA-down)) (define merged_trategy2_count (get-num-values (car merged_strategy2))) (define merged_strategy2_genes (merge-2-assoc-list gene=>drug-CHAMP1-phenotype-RNA-up gene=>drug-CHAMP1-phenotype-RNA-down)) (define merged_trategy2_genes_count (get-num-values (car merged_strategy2_genes))) 2 - edge queries to find drugs that treat the CHAMP1 disease conditions and reverse the gene expression directions : (define CHAMP1-DE-RNA-up (list "ENSEMBL:ENSG00000228630" "ENSEMBL:ENSG00000261340" "ENSEMBL:ENSG00000083937" "ENSEMBL:ENSG00000143106" "ENSEMBL:ENSG00000140199" "ENSEMBL:ENSG00000065357" "ENSEMBL:ENSG00000129480" "ENSEMBL:ENSG00000162688" "ENSEMBL:ENSG00000180818" "ENSEMBL:ENSG00000136478" "ENSEMBL:ENSG00000065413" "ENSEMBL:ENSG00000167394" "ENSEMBL:ENSG00000163249" "ENSEMBL:ENSG00000118762" "ENSEMBL:ENSG00000185070" "ENSEMBL:ENSG00000089060" "ENSEMBL:ENSG00000173221" "ENSEMBL:ENSG00000175040" "ENSEMBL:ENSG00000112964" "ENSEMBL:ENSG00000111670" "ENSEMBL:ENSG00000119986" "ENSEMBL:ENSG00000106415" "ENSEMBL:ENSG00000038427" "ENSEMBL:ENSG00000154122" "ENSEMBL:ENSG00000176531" "ENSEMBL:ENSG00000121413" "ENSEMBL:ENSG00000176809" "ENSEMBL:ENSG00000165804" "ENSEMBL:ENSG00000198948" "ENSEMBL:ENSG00000012171" "ENSEMBL:ENSG00000267454" "ENSEMBL:ENSG00000182379" "ENSEMBL:ENSG00000213983" "ENSEMBL:ENSG00000169313" "ENSEMBL:ENSG00000137573" "ENSEMBL:ENSG00000174469" "ENSEMBL:ENSG00000189129" "ENSEMBL:ENSG00000112378" "ENSEMBL:ENSG00000136048" "ENSEMBL:ENSG00000101134" "ENSEMBL:ENSG00000176928" "ENSEMBL:ENSG00000184916" "ENSEMBL:ENSG00000162643" "ENSEMBL:ENSG00000266094" "ENSEMBL:ENSG00000150540" "ENSEMBL:ENSG00000176771" "ENSEMBL:ENSG00000138772" "ENSEMBL:ENSG00000115271" "ENSEMBL:ENSG00000250133" "ENSEMBL:ENSG00000179104" "ENSEMBL:ENSG00000145390" "ENSEMBL:ENSG00000184349" "ENSEMBL:ENSG00000101605" "ENSEMBL:ENSG00000205002" "ENSEMBL:ENSG00000198133" "ENSEMBL:ENSG00000205835" "ENSEMBL:ENSG00000165113" "ENSEMBL:ENSG00000172403" "ENSEMBL:ENSG00000120899" "ENSEMBL:ENSG00000174600" "ENSEMBL:ENSG00000099260" "ENSEMBL:ENSG00000137727" "ENSEMBL:ENSG00000136160" "ENSEMBL:ENSG00000182901" "ENSEMBL:ENSG00000112981" "ENSEMBL:ENSG00000242600" "ENSEMBL:ENSG00000115604" "ENSEMBL:ENSG00000144229" "ENSEMBL:ENSG00000151623" "ENSEMBL:ENSG00000165023" "ENSEMBL:ENSG00000152804" "ENSEMBL:ENSG00000112379" "ENSEMBL:ENSG00000082497" "ENSEMBL:ENSG00000144645" "ENSEMBL:ENSG00000196208" "ENSEMBL:ENSG00000228495" "ENSEMBL:ENSG00000135919" "ENSEMBL:ENSG00000211448" "ENSEMBL:ENSG00000141449" "ENSEMBL:ENSG00000203727" "ENSEMBL:ENSG00000013588" "ENSEMBL:ENSG00000130600" "ENSEMBL:ENSG00000126861" "ENSEMBL:ENSG00000165084" "ENSEMBL:ENSG00000179869" "ENSEMBL:ENSG00000114200" "ENSEMBL:ENSG00000143028" "ENSEMBL:ENSG00000164106" "ENSEMBL:ENSG00000138449" "ENSEMBL:ENSG00000110723" "ENSEMBL:ENSG00000162687" "ENSEMBL:ENSG00000183775" "ENSEMBL:ENSG00000106538" "ENSEMBL:ENSG00000064225" "ENSEMBL:ENSG00000086289" "ENSEMBL:ENSG00000070193" "ENSEMBL:ENSG00000116183" "ENSEMBL:ENSG00000102109" "ENSEMBL:ENSG00000078018" "ENSEMBL:ENSG00000099864" "ENSEMBL:ENSG00000173391" "ENSEMBL:ENSG00000198947" "ENSEMBL:ENSG00000139174" "ENSEMBL:ENSG00000165092" "ENSEMBL:ENSG00000162105" "ENSEMBL:ENSG00000137672" "ENSEMBL:ENSG00000178568" "ENSEMBL:ENSG00000064042" "ENSEMBL:ENSG00000135218" "ENSEMBL:ENSG00000126785" "ENSEMBL:ENSG00000240694" "ENSEMBL:ENSG00000248874" "ENSEMBL:ENSG00000118971" "ENSEMBL:ENSG00000182389" "ENSEMBL:ENSG00000129467" "ENSEMBL:ENSG00000106483" "ENSEMBL:ENSG00000123572")) (define CHAMP1-DE-RNA-down (list "EMSEMBL:ENSG00000204792" "EMSEMBL:ENSG00000166796" "EMSEMBL:ENSG00000186297" "EMSEMBL:ENSG00000005379" "EMSEMBL:ENSG00000234465" "EMSEMBL:ENSG00000165887" "EMSEMBL:ENSG00000115648" "EMSEMBL:ENSG00000102575" "EMSEMBL:ENSG00000175084" "EMSEMBL:ENSG00000145824" "EMSEMBL:ENSG00000213030" "EMSEMBL:ENSG00000132639" "EMSEMBL:ENSG00000006606" "EMSEMBL:ENSG00000101017" "EMSEMBL:ENSG00000154451" "EMSEMBL:ENSG00000169429" "EMSEMBL:ENSG00000104826" "EMSEMBL:ENSG00000163618" "EMSEMBL:ENSG00000147573" "EMSEMBL:ENSG00000171517" "EMSEMBL:ENSG00000130720" "EMSEMBL:ENSG00000157557" "EMSEMBL:ENSG00000178882" "EMSEMBL:ENSG00000156453" "EMSEMBL:ENSG00000148803" "EMSEMBL:ENSG00000107611" "EMSEMBL:ENSG00000175294" "EMSEMBL:ENSG00000181072" "EMSEMBL:ENSG00000104783" "EMSEMBL:ENSG00000128285" "EMSEMBL:ENSG00000080823" "EMSEMBL:ENSG00000167889" "EMSEMBL:ENSG00000124191" "EMSEMBL:ENSG00000163701" "EMSEMBL:ENSG00000076706" "EMSEMBL:ENSG00000144354" "EMSEMBL:ENSG00000103034" "EMSEMBL:ENSG00000164929" "EMSEMBL:ENSG00000204103" "EMSEMBL:ENSG00000242265" "EMSEMBL:ENSG00000196460" "EMSEMBL:ENSG00000138395" "EMSEMBL:ENSG00000225968" "EMSEMBL:ENSG00000028137" "EMSEMBL:ENSG00000091622" "EMSEMBL:ENSG00000125968" "EMSEMBL:ENSG00000173848" "EMSEMBL:ENSG00000239332" "EMSEMBL:ENSG00000139278" "EMSEMBL:ENSG00000137563" "EMSEMBL:ENSG00000163814" "EMSEMBL:ENSG00000121904" "EMSEMBL:ENSG00000186847" "EMSEMBL:ENSG00000099365" "EMSEMBL:ENSG00000136490" "EMSEMBL:ENSG00000100181" "EMSEMBL:ENSG00000079462" "EMSEMBL:ENSG00000026025" "EMSEMBL:ENSG00000105255" "EMSEMBL:ENSG00000188064" "EMSEMBL:ENSG00000103449" "EMSEMBL:ENSG00000235162" "EMSEMBL:ENSG00000074410" "EMSEMBL:ENSG00000170961" "EMSEMBL:ENSG00000140280" "EMSEMBL:ENSG00000187583" "EMSEMBL:ENSG00000205683" "EMSEMBL:ENSG00000109062" "EMSEMBL:ENSG00000159231" "EMSEMBL:ENSG00000183077" "EMSEMBL:ENSG00000173588" "EMSEMBL:ENSG00000167552" "EMSEMBL:ENSG00000243156" "EMSEMBL:ENSG00000166886" "EMSEMBL:ENSG00000153944" "EMSEMBL:ENSG00000196912" "EMSEMBL:ENSG00000183506" "EMSEMBL:ENSG00000156535" "EMSEMBL:ENSG00000087266" "EMSEMBL:ENSG00000170921" "EMSEMBL:ENSG00000185052" "EMSEMBL:ENSG00000089486" "EMSEMBL:ENSG00000196155" "EMSEMBL:ENSG00000101546" "EMSEMBL:ENSG00000038382" "EMSEMBL:ENSG00000167460" "EMSEMBL:ENSG00000186281" "EMSEMBL:ENSG00000130309" "EMSEMBL:ENSG00000054523" "EMSEMBL:ENSG00000100097" "EMSEMBL:ENSG00000142892" "EMSEMBL:ENSG00000231419" "EMSEMBL:ENSG00000163687")) define CHAMP1 disease related conditions : (define dev-delay "HP:0001263") (define hypotonia "HP:0001252") (define cerebral-palsy "HP:0100021") (define autism "MONDO:0005260") (define epilepsy "MONDO:0005027") The function find - drug - for - condition takes a disease condition , a gene list ( derived from RNA - seq DEG results ) This function will run a query / graph that does a 2 - edge query which find drugs that modify the disease condition this function will return a list which contains 2 hash - tables which are sorted based on the number (define dev-delay-drug-results-RNA-up (find-drug-for-condition dev-delay CHAMP1-DE-RNA-up negatively-regulates)) (define dev-delay-drug-results-RNA-down (find-drug-for-condition dev-delay CHAMP1-DE-RNA-down positively-regulates)) (define hypotonia-drug-results-RNA-up (find-drug-for-condition hypotonia CHAMP1-DE-RNA-up negatively-regulates)) (define hypotonia-drug-results-RNA-down (find-drug-for-condition hypotonia CHAMP1-DE-RNA-up negatively-regulates)) (define cerebral-palsy-drug-results-RNA-up (find-drug-for-condition cerebral-palsy CHAMP1-DE-RNA-up negatively-regulates)) (define cerebral-palsy-drug-results-RNA-down (find-drug-for-condition cerebral-palsy CHAMP1-DE-RNA-down positively-regulates)) (define autism-drug-results-RNA-up (find-drug-for-condition autism CHAMP1-DE-RNA-up negatively-regulates)) (define autism-drug-results-RNA-down (find-drug-for-condition autism CHAMP1-DE-RNA-down positively-regulates)) (define epilepsy-drug-results-RNA-up (find-drug-for-condition epilepsy CHAMP1-DE-RNA-up negatively-regulates)) (define epilepsy-drug-results-RNA-down (find-drug-for-condition epilepsy CHAMP1-DE-RNA-down positively-regulates)) (define drug=>gene-dev-delay-drug-results-RNA-up (car dev-delay-drug-results-RNA-up)) (define gene=>drug-dev-delay-drug-results-RNA-up (cadr dev-delay-drug-results-RNA-up)) (define drug=>gene-dev-delay-drug-results-RNA-down (car dev-delay-drug-results-RNA-down)) (define gene=>drug-dev-delay-drug-results-RNA-down (cadr dev-delay-drug-results-RNA-down)) (define drug=>gene-hypotonia-drug-results-RNA-up (car hypotonia-drug-results-RNA-up)) (define gene=>drug-hypotonia-drug-results-RNA-up (cadr hypotonia-drug-results-RNA-up)) (define drug=>gene-hypotonia-drug-results-RNA-down (car hypotonia-drug-results-RNA-down)) (define gene=>drug-hypotonia-drug-results-RNA-down (cadr hypotonia-drug-results-RNA-down)) (define drug=>gene-cerebral-palsy-drug-results-RNA-up (car cerebral-palsy-drug-results-RNA-up)) (define gene=>drug-cerebral-palsy-drug-results-RNA-up (cadr cerebral-palsy-drug-results-RNA-up)) (define drug=>gene-cerebral-palsy-drug-results-RNA-down (car cerebral-palsy-drug-results-RNA-down)) (define gene=>drug-cerebral-palsy-drug-results-RNA-down (cadr cerebral-palsy-drug-results-RNA-down)) (define drug=>gene-autism-drug-results-RNA-up (car autism-drug-results-RNA-up)) (define gene=>drug-autism-drug-results-RNA-up (cadr autism-drug-results-RNA-up)) (define drug=>gene-autism-drug-results-RNA-down (car autism-drug-results-RNA-down)) (define gene=>drug-autism-drug-results-RNA-down (cadr autism-drug-results-RNA-down)) (define drug=>gene-epilepsy-drug-results-RNA-up (car epilepsy-drug-results-RNA-up)) (define gene=>drug-epilepsy-drug-results-RNA-up (cadr epilepsy-drug-results-RNA-up)) (define drug=>gene-epilepsy-drug-results-RNA-down (car epilepsy-drug-results-RNA-down)) (define gene=>drug-epilepsy-drug-results-RNA-down (cadr epilepsy-drug-results-RNA-down)) combine 10 association lists : (define strategy3_results (merge-assoc-lists (list drug=>gene-dev-delay-drug-results-RNA-up drug=>gene-dev-delay-drug-results-RNA-down drug=>gene-hypotonia-drug-results-RNA-up drug=>gene-hypotonia-drug-results-RNA-down drug=>gene-cerebral-palsy-drug-results-RNA-up drug=>gene-cerebral-palsy-drug-results-RNA-down drug=>gene-autism-drug-results-RNA-up drug=>gene-autism-drug-results-RNA-down drug=>gene-epilepsy-drug-results-RNA-up drug=>gene-epilepsy-drug-results-RNA-down))) (define strategy3_genes_results (merge-assoc-lists (list gene=>drug-dev-delay-drug-results-RNA-up gene=>drug-dev-delay-drug-results-RNA-down gene=>drug-hypotonia-drug-results-RNA-up gene=>drug-hypotonia-drug-results-RNA-down gene=>drug-cerebral-palsy-drug-results-RNA-up gene=>drug-cerebral-palsy-drug-results-RNA-down gene=>drug-autism-drug-results-RNA-up gene=>drug-autism-drug-results-RNA-down gene=>drug-epilepsy-drug-results-RNA-up gene=>drug-epilepsy-drug-results-RNA-down))) (define strategy3_results-count (get-num-values (car strategy3_results))) (define strategy3_results-genes-count (get-num-values (car strategy3_genes_results)))
ca800c1a1173c1eb180760730ec0ab5fe68140fba6a405bd093b1c00135352b1
ku-fpg/hermit
Main.hs
# LANGUAGE CPP # # LANGUAGE ViewPatterns # module Main (main) where import Constants (hiVersion) import Control.Monad import Data.Char (isSpace) import Data.List import Data.Maybe (listToMaybe) import GHC.Paths (ghc) import HERMIT.Driver import System.Directory import System.FilePath as F #if defined(darwin_HOST_OS) import System.Info (arch) #else import System.Info (arch, os) #endif import System.IO import System.IO.Temp (withSystemTempFile) import System.Process import Test.Tasty (TestTree, TestName, defaultMain, testGroup) import Test.Tasty.Golden (goldenVsFileDiff) type HermitTestArgs = (FilePath, FilePath, FilePath, [String]) main :: IO () main = defaultMain hermitTests hermitTests :: TestTree hermitTests = testGroup "HERMIT tests" $ map mkHermitTest testArgs -- subdirectory names golden, dump, rootDir, examples :: FilePath golden = "golden" </> "golden-ghc-" ++ show hiVersion dump = "dump" rootDir = "tests" examples = "examples" testArgs :: [HermitTestArgs] testArgs = [ ("concatVanishes", "Flatten.hs", "Flatten.hss", ["-safety=unsafe"]) , ("concatVanishes", "QSort.hs" , "QSort.hss" , ["-safety=unsafe"]) , ("concatVanishes", "Rev.hs" , "Rev.hss" , ["-safety=unsafe"]) , ("evaluation" , "Eval.hs" , "Eval.hss" , []) #if __GLASGOW_HASKELL__ < 710 broken on GHC 7.10 due to not satisfying the let / app invariant . I should probably fix this . , ("factorial" , "Fac.hs" , "Fac.hss" , []) #endif broken due to : , ( " fib - stream " , " Fib.hs " , " Fib.hss " ) , ("fib-tuple" , "Fib.hs" , "Fib.hss" , []) , ("flatten" , "Flatten.hs", "Flatten.hec", ["-safety=unsafe"]) for some reason loops in testsuite but not normally : , ( " hanoi " , " " , " Hanoi.hss " ) , ("last" , "Last.hs" , "Last.hss" , ["-safety=unsafe"]) , ("last" , "Last.hs" , "NewLast.hss", ["-safety=strict"]) broken due to : , ( " map " , " Map.hs " , " Map.hss " ) , ("mean" , "Mean.hs" , "Mean.hss" , []) -- TODO: re-enable once fixed , ("nub" , "Nub.hs" , "Nub.hss" , []) , ("qsort" , "QSort.hs" , "QSort.hss" , []) , ("reverse" , "Reverse.hs", "Reverse.hss", ["-safety=unsafe"]) , ("new_reverse" , "Reverse.hs", "Reverse.hec", []) ] fixName :: FilePath -> FilePath fixName = map (\c -> if c == '.' then '_' else c) mkTestScript :: Handle -> FilePath -> IO () mkTestScript h hss = do hPutStrLn h $ unlines [ "set-auto-corelint True" , "set-pp-type Show" , "set-fail-hard True" , "load-and-run \"" ++ hss ++ "\"" , "top ; prog" , "display" -- all the bindings , "show-lemmas" , "resume" ] hClose h -- | Get the path to the sandbox database if any Taken from hoogle - index ( by , under BSD3 ) getSandboxDb :: IO (Maybe FilePath) getSandboxDb = do dir <- getCurrentDirectory let f = dir </> "cabal.sandbox.config" ex <- doesFileExist f if ex then (listToMaybe . map ((</> archOSCompilerConf) . dropFileName . dropWhile isSpace . tail . dropWhile (/= ':')) . filter (isPrefixOf "package-db") . lines) <$> readFile f else return Nothing where archOSCompilerConf :: String archOSCompilerConf = intercalate "-" [arch, theOS, takeFileName ghc, "packages.conf.d"] theOS :: String #if defined(darwin_HOST_OS) System.Info.os gives " " , which is n't what is actually -- used, for some silly reason #else theOS = os #endif mkHermitTest :: HermitTestArgs -> TestTree mkHermitTest (dir, hs, hss, extraFlags) = goldenVsFileDiff testName diff gfile dfile hermitOutput where testName :: TestName testName = dir </> hs fixed, gfile, dfile, pathp :: FilePath fixed = fixName (concat [dir, "_", hs, "_", hss]) gfile = rootDir </> golden </> fixed <.> "ref" dfile = rootDir </> dump </> fixed <.> "dump" pathp = examples </> dir diff :: FilePath -> FilePath -> [String] diff ref new = ["diff", "-b", "-U 5", ref, new] For some incredibly bizarre reason , 's output can be have different -- line orderings depending on if it's been run once before. As far as I can -- tell, this is due to the presence of object (.o) and interface (.hi) files. -- Wat. -- Luckily , removing any object or interface before running seems to provide a guarantee that HERMIT 's output will be the same on subsequent runs . cleanObjectFiles :: IO () cleanObjectFiles = do files <- getDirectoryContents pathp forM_ files $ \file -> when (takeExtension file `elem` [".o", ".hi"]) $ removeFile $ pathp </> file hermitOutput :: IO () hermitOutput = do cleanObjectFiles mbDb <- getSandboxDb createDirectoryIfMissing True (dropFileName gfile) let dbFlags :: String dbFlags | Just db <- mbDb = unwords ["-no-user-package-db", "-package-db", db] | otherwise = "" withSystemTempFile "Test.hss" $ \ fp h -> do mkTestScript h hss let cmd :: String cmd = unwords $ [ "(" , "cd" , pathp , ";" , ghc , dbFlags , hs , "-w" -- Disable all warnings ] ++ ghcFlags ++ [ "-fplugin=HERMIT" made by mkTestScript , "-v0" ] ++ [ "-fplugin-opt=HERMIT:Main:" ++ f | f <- extraFlags] ++ [ ")" ] Adding a & > dfile redirect in cmd causes the call to GHC to not block until the compiler is finished ( on Linux , not OSX ) . So we do the -- equivalent here by opening our own file. fh <- openFile dfile WriteMode -- putStrLn cmd (_,_,_,rHermit) <- createProcess $ (shell cmd) { std_out = UseHandle fh, std_err = UseHandle fh } _ <- waitForProcess rHermit -- Ensure that the golden file exists prior to calling diff goldenExists <- doesFileExist gfile unless goldenExists $ copyFile dfile gfile
null
https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/tests/Main.hs
haskell
subdirectory names TODO: re-enable once fixed , ("nub" , "Nub.hs" , "Nub.hss" , []) all the bindings | Get the path to the sandbox database if any used, for some silly reason line orderings depending on if it's been run once before. As far as I can tell, this is due to the presence of object (.o) and interface (.hi) files. Wat. Disable all warnings equivalent here by opening our own file. putStrLn cmd Ensure that the golden file exists prior to calling diff
# LANGUAGE CPP # # LANGUAGE ViewPatterns # module Main (main) where import Constants (hiVersion) import Control.Monad import Data.Char (isSpace) import Data.List import Data.Maybe (listToMaybe) import GHC.Paths (ghc) import HERMIT.Driver import System.Directory import System.FilePath as F #if defined(darwin_HOST_OS) import System.Info (arch) #else import System.Info (arch, os) #endif import System.IO import System.IO.Temp (withSystemTempFile) import System.Process import Test.Tasty (TestTree, TestName, defaultMain, testGroup) import Test.Tasty.Golden (goldenVsFileDiff) type HermitTestArgs = (FilePath, FilePath, FilePath, [String]) main :: IO () main = defaultMain hermitTests hermitTests :: TestTree hermitTests = testGroup "HERMIT tests" $ map mkHermitTest testArgs golden, dump, rootDir, examples :: FilePath golden = "golden" </> "golden-ghc-" ++ show hiVersion dump = "dump" rootDir = "tests" examples = "examples" testArgs :: [HermitTestArgs] testArgs = [ ("concatVanishes", "Flatten.hs", "Flatten.hss", ["-safety=unsafe"]) , ("concatVanishes", "QSort.hs" , "QSort.hss" , ["-safety=unsafe"]) , ("concatVanishes", "Rev.hs" , "Rev.hss" , ["-safety=unsafe"]) , ("evaluation" , "Eval.hs" , "Eval.hss" , []) #if __GLASGOW_HASKELL__ < 710 broken on GHC 7.10 due to not satisfying the let / app invariant . I should probably fix this . , ("factorial" , "Fac.hs" , "Fac.hss" , []) #endif broken due to : , ( " fib - stream " , " Fib.hs " , " Fib.hss " ) , ("fib-tuple" , "Fib.hs" , "Fib.hss" , []) , ("flatten" , "Flatten.hs", "Flatten.hec", ["-safety=unsafe"]) for some reason loops in testsuite but not normally : , ( " hanoi " , " " , " Hanoi.hss " ) , ("last" , "Last.hs" , "Last.hss" , ["-safety=unsafe"]) , ("last" , "Last.hs" , "NewLast.hss", ["-safety=strict"]) broken due to : , ( " map " , " Map.hs " , " Map.hss " ) , ("mean" , "Mean.hs" , "Mean.hss" , []) , ("qsort" , "QSort.hs" , "QSort.hss" , []) , ("reverse" , "Reverse.hs", "Reverse.hss", ["-safety=unsafe"]) , ("new_reverse" , "Reverse.hs", "Reverse.hec", []) ] fixName :: FilePath -> FilePath fixName = map (\c -> if c == '.' then '_' else c) mkTestScript :: Handle -> FilePath -> IO () mkTestScript h hss = do hPutStrLn h $ unlines [ "set-auto-corelint True" , "set-pp-type Show" , "set-fail-hard True" , "load-and-run \"" ++ hss ++ "\"" , "top ; prog" , "show-lemmas" , "resume" ] hClose h Taken from hoogle - index ( by , under BSD3 ) getSandboxDb :: IO (Maybe FilePath) getSandboxDb = do dir <- getCurrentDirectory let f = dir </> "cabal.sandbox.config" ex <- doesFileExist f if ex then (listToMaybe . map ((</> archOSCompilerConf) . dropFileName . dropWhile isSpace . tail . dropWhile (/= ':')) . filter (isPrefixOf "package-db") . lines) <$> readFile f else return Nothing where archOSCompilerConf :: String archOSCompilerConf = intercalate "-" [arch, theOS, takeFileName ghc, "packages.conf.d"] theOS :: String #if defined(darwin_HOST_OS) System.Info.os gives " " , which is n't what is actually #else theOS = os #endif mkHermitTest :: HermitTestArgs -> TestTree mkHermitTest (dir, hs, hss, extraFlags) = goldenVsFileDiff testName diff gfile dfile hermitOutput where testName :: TestName testName = dir </> hs fixed, gfile, dfile, pathp :: FilePath fixed = fixName (concat [dir, "_", hs, "_", hss]) gfile = rootDir </> golden </> fixed <.> "ref" dfile = rootDir </> dump </> fixed <.> "dump" pathp = examples </> dir diff :: FilePath -> FilePath -> [String] diff ref new = ["diff", "-b", "-U 5", ref, new] For some incredibly bizarre reason , 's output can be have different Luckily , removing any object or interface before running seems to provide a guarantee that HERMIT 's output will be the same on subsequent runs . cleanObjectFiles :: IO () cleanObjectFiles = do files <- getDirectoryContents pathp forM_ files $ \file -> when (takeExtension file `elem` [".o", ".hi"]) $ removeFile $ pathp </> file hermitOutput :: IO () hermitOutput = do cleanObjectFiles mbDb <- getSandboxDb createDirectoryIfMissing True (dropFileName gfile) let dbFlags :: String dbFlags | Just db <- mbDb = unwords ["-no-user-package-db", "-package-db", db] | otherwise = "" withSystemTempFile "Test.hss" $ \ fp h -> do mkTestScript h hss let cmd :: String cmd = unwords $ [ "(" , "cd" , pathp , ";" , ghc , dbFlags , hs ] ++ ghcFlags ++ [ "-fplugin=HERMIT" made by mkTestScript , "-v0" ] ++ [ "-fplugin-opt=HERMIT:Main:" ++ f | f <- extraFlags] ++ [ ")" ] Adding a & > dfile redirect in cmd causes the call to GHC to not block until the compiler is finished ( on Linux , not OSX ) . So we do the fh <- openFile dfile WriteMode (_,_,_,rHermit) <- createProcess $ (shell cmd) { std_out = UseHandle fh, std_err = UseHandle fh } _ <- waitForProcess rHermit goldenExists <- doesFileExist gfile unless goldenExists $ copyFile dfile gfile
120d6f4f097ca29b0bf9c784a6fb6dc99b8fd4fd4c4e052e31c175389aed221b
2600hz-archive/whistle
conference.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 , VoIP , INC %%% @doc %%% Its a party and your invite'd... %%% @end Created : 27 June 2011 by < > %%%------------------------------------------------------------------- -module(conference). -include_lib("whistle/include/wh_types.hrl"). -export([start/0, start_link/0, stop/0]). %%-------------------------------------------------------------------- @public %% @doc %% Starts the app for inclusion in a supervisor tree %% @end %%-------------------------------------------------------------------- -spec start_link/0 :: () -> startlink_ret(). start_link() -> start_deps(), conference_sup:start_link(). %%-------------------------------------------------------------------- @public %% @doc %% Starts the app %% @end %%-------------------------------------------------------------------- -spec start/0 :: () -> ok. start() -> start_deps(), application:start(conference). %%-------------------------------------------------------------------- @public %% @doc %% Stop the app %% @end %%-------------------------------------------------------------------- -spec stop/0 :: () -> ok. stop() -> ok = application:stop(conference). %%-------------------------------------------------------------------- @private %% @doc %% Ensures that all dependencies for this app are already running %% @end %%-------------------------------------------------------------------- -spec start_deps/0 :: () -> ok. start_deps() -> if started by the whistle_controller , this will exist ensure_started(sasl), % logging ensure_started(crypto), % random wrapper ensure_started(whistle_couch). % couch wrapper %%-------------------------------------------------------------------- @private %% @doc %% Verify that an application is running %% @end %%-------------------------------------------------------------------- -spec ensure_started/1 :: (App) -> ok when App :: atom(). ensure_started(App) -> case application:start(App) of ok -> ok; {error, {already_started, App}} -> ok end.
null
https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/whistle_apps/apps/conference/src/conference.erl
erlang
------------------------------------------------------------------- @doc Its a party and your invite'd... @end ------------------------------------------------------------------- -------------------------------------------------------------------- @doc Starts the app for inclusion in a supervisor tree @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Starts the app @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Stop the app @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Ensures that all dependencies for this app are already running @end -------------------------------------------------------------------- logging random couch wrapper -------------------------------------------------------------------- @doc Verify that an application is running @end --------------------------------------------------------------------
@author < > ( C ) 2011 , VoIP , INC Created : 27 June 2011 by < > -module(conference). -include_lib("whistle/include/wh_types.hrl"). -export([start/0, start_link/0, stop/0]). @public -spec start_link/0 :: () -> startlink_ret(). start_link() -> start_deps(), conference_sup:start_link(). @public -spec start/0 :: () -> ok. start() -> start_deps(), application:start(conference). @public -spec stop/0 :: () -> ok. stop() -> ok = application:stop(conference). @private -spec start_deps/0 :: () -> ok. start_deps() -> if started by the whistle_controller , this will exist wrapper @private -spec ensure_started/1 :: (App) -> ok when App :: atom(). ensure_started(App) -> case application:start(App) of ok -> ok; {error, {already_started, App}} -> ok end.
fc9213f77281be2db87f002b7a9a1a8c764e34e167e7f6e9aba1c4f390b5c332
ninenines/gun
gun_tcp_proxy.erl
Copyright ( c ) 2020 - 2023 , < > %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -module(gun_tcp_proxy). -export([name/0]). -export([messages/0]). -export([connect/3]). -export([connect/4]). -export([send/2]). -export([setopts/2]). -export([sockname/1]). -export([close/1]). -type socket() :: #{ %% The pid of the Gun connection. gun_pid := pid(), %% The pid of the process that gets replies for this tunnel. reply_to := pid(), %% The full stream reference for this tunnel. stream_ref := gun:stream_ref() }. name() -> tcp_proxy. messages() -> {tcp_proxy, tcp_proxy_closed, tcp_proxy_error}. -spec connect(_, _, _) -> no_return(). connect(_, _, _) -> error(not_implemented). -spec connect(_, _, _, _) -> no_return(). connect(_, _, _, _) -> error(not_implemented). -spec send(socket(), iodata()) -> ok. send(#{gun_pid := GunPid, reply_to := ReplyTo, stream_ref := StreamRef, handle_continue_stream_ref := ContinueStreamRef}, Data) -> GunPid ! {handle_continue, ContinueStreamRef, {data, ReplyTo, StreamRef, nofin, Data}}, ok; send(#{reply_to := ReplyTo, stream_ref := StreamRef}, Data) -> gen_statem:cast(self(), {data, ReplyTo, StreamRef, nofin, Data}). -spec setopts(_, _) -> no_return(). setopts(#{handle_continue_stream_ref := _}, _) -> %% We send messages automatically regardless of active mode. ok; setopts(_, _) -> error(not_implemented). -spec sockname(_) -> no_return(). sockname(_) -> error(not_implemented). -spec close(socket()) -> ok. close(_) -> ok.
null
https://raw.githubusercontent.com/ninenines/gun/33223e751267c5f249f3db1277c13904a1801b92/src/gun_tcp_proxy.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. The pid of the Gun connection. The pid of the process that gets replies for this tunnel. The full stream reference for this tunnel. We send messages automatically regardless of active mode.
Copyright ( c ) 2020 - 2023 , < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(gun_tcp_proxy). -export([name/0]). -export([messages/0]). -export([connect/3]). -export([connect/4]). -export([send/2]). -export([setopts/2]). -export([sockname/1]). -export([close/1]). -type socket() :: #{ gun_pid := pid(), reply_to := pid(), stream_ref := gun:stream_ref() }. name() -> tcp_proxy. messages() -> {tcp_proxy, tcp_proxy_closed, tcp_proxy_error}. -spec connect(_, _, _) -> no_return(). connect(_, _, _) -> error(not_implemented). -spec connect(_, _, _, _) -> no_return(). connect(_, _, _, _) -> error(not_implemented). -spec send(socket(), iodata()) -> ok. send(#{gun_pid := GunPid, reply_to := ReplyTo, stream_ref := StreamRef, handle_continue_stream_ref := ContinueStreamRef}, Data) -> GunPid ! {handle_continue, ContinueStreamRef, {data, ReplyTo, StreamRef, nofin, Data}}, ok; send(#{reply_to := ReplyTo, stream_ref := StreamRef}, Data) -> gen_statem:cast(self(), {data, ReplyTo, StreamRef, nofin, Data}). -spec setopts(_, _) -> no_return(). setopts(#{handle_continue_stream_ref := _}, _) -> ok; setopts(_, _) -> error(not_implemented). -spec sockname(_) -> no_return(). sockname(_) -> error(not_implemented). -spec close(socket()) -> ok. close(_) -> ok.
86ebcbe6c648157c9196ddf12f2e31dc5fb262da3fb96c2f8b6f03462eaf08c6
DataHaskell/dh-core
WeighBench.hs
module Main where import qualified Statistics.Matrix as M import qualified Statistics.Matrix.Fast as F import qualified Statistics.Matrix.Fast.Algorithms as FA import Statistics.Matrix (Matrix (..)) import qualified Statistics.Matrix.Algorithms as A import qualified Data.Vector.Unboxed as U import Data.Vector.Unboxed (Vector) import qualified System.Random.MWC as Mwc import qualified Weigh as W n :: Int n = 100 testVector :: IO (Vector Double) testVector = do gen <- Mwc.create Mwc.uniformVector gen (n*n) testMatrix :: IO Matrix testMatrix = do vec <- testVector return $ Matrix n n vec weight :: Vector Double -> Matrix -> Matrix -> IO () weight v a b = do let v2 = U.take n v W.mainWith (do W.func "norm" M.norm v2 W.func "Fast.norm" F.norm v2 W.func "multiplyV" (M.multiplyV a) (v2) W.func "Fast.multiplyV" (F.multiplyV a) (v2) W.func "transpose" M.transpose a W.func "Fast.transpose" F.transpose a W.func "ident" M.ident n W.func "diag" M.diag v2 W.func "multiply" (M.multiply a) b W.func "Fast.multiply" (F.multiply a) b W.func "qr" A.qr a W.func "Fast.qr" FA.qr a ) main :: IO () main = do v <- testVector a <- testMatrix b <- testMatrix putStrLn "---Benchmarking memory consumption---" weight v a b
null
https://raw.githubusercontent.com/DataHaskell/dh-core/2beb8740f27fa9683db70eb8d8424ee6c75d3e91/dense-linear-algebra/bench/WeighBench.hs
haskell
module Main where import qualified Statistics.Matrix as M import qualified Statistics.Matrix.Fast as F import qualified Statistics.Matrix.Fast.Algorithms as FA import Statistics.Matrix (Matrix (..)) import qualified Statistics.Matrix.Algorithms as A import qualified Data.Vector.Unboxed as U import Data.Vector.Unboxed (Vector) import qualified System.Random.MWC as Mwc import qualified Weigh as W n :: Int n = 100 testVector :: IO (Vector Double) testVector = do gen <- Mwc.create Mwc.uniformVector gen (n*n) testMatrix :: IO Matrix testMatrix = do vec <- testVector return $ Matrix n n vec weight :: Vector Double -> Matrix -> Matrix -> IO () weight v a b = do let v2 = U.take n v W.mainWith (do W.func "norm" M.norm v2 W.func "Fast.norm" F.norm v2 W.func "multiplyV" (M.multiplyV a) (v2) W.func "Fast.multiplyV" (F.multiplyV a) (v2) W.func "transpose" M.transpose a W.func "Fast.transpose" F.transpose a W.func "ident" M.ident n W.func "diag" M.diag v2 W.func "multiply" (M.multiply a) b W.func "Fast.multiply" (F.multiply a) b W.func "qr" A.qr a W.func "Fast.qr" FA.qr a ) main :: IO () main = do v <- testVector a <- testMatrix b <- testMatrix putStrLn "---Benchmarking memory consumption---" weight v a b
ad4b236c94d38f009009b655cddb3dd17476fdd7d2a5c36d3a72fe7aeec00df1
roman/Haskell-Reactive-Extensions
Maybe.hs
# LANGUAGE NoImplicitPrelude # module Rx.Observable.Maybe where import Prelude.Compat import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar) import Control.Monad (void) import Rx.Disposable (dispose) import Rx.Scheduler (Async) import Rx.Observable.First (first) import Rx.Observable.Types toMaybe :: Observable Async a -> IO (Maybe a) toMaybe source = do completedVar <- newEmptyMVar subDisposable <- subscribe (first source) (void . tryPutMVar completedVar . Just) (\_ -> void $ tryPutMVar completedVar Nothing) (void $ tryPutMVar completedVar Nothing) result <- takeMVar completedVar dispose subDisposable return result
null
https://raw.githubusercontent.com/roman/Haskell-Reactive-Extensions/0faddbb671be7f169eeadbe6163e8d0b2be229fb/rx-core/src/Rx/Observable/Maybe.hs
haskell
# LANGUAGE NoImplicitPrelude # module Rx.Observable.Maybe where import Prelude.Compat import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar) import Control.Monad (void) import Rx.Disposable (dispose) import Rx.Scheduler (Async) import Rx.Observable.First (first) import Rx.Observable.Types toMaybe :: Observable Async a -> IO (Maybe a) toMaybe source = do completedVar <- newEmptyMVar subDisposable <- subscribe (first source) (void . tryPutMVar completedVar . Just) (\_ -> void $ tryPutMVar completedVar Nothing) (void $ tryPutMVar completedVar Nothing) result <- takeMVar completedVar dispose subDisposable return result
c3b33050f1fd5905808bbb800d4b1d86092bfe8e3fea1df8b64861638ff6fd67
unisonweb/unison
Var.hs
module U.Core.ABT.Var where import Data.Set (Set) -- | A class for avoiding accidental variable capture -- -- * `Set.notMember (freshIn vs v) vs`: -- `freshIn` returns a variable not used in the `Set` class (Ord v) => Var v where freshIn :: Set v -> v -> v
null
https://raw.githubusercontent.com/unisonweb/unison/cf278f9fb66ccb9436bf8a2eb4ab03fc7a92021d/codebase2/core/U/Core/ABT/Var.hs
haskell
| A class for avoiding accidental variable capture * `Set.notMember (freshIn vs v) vs`: `freshIn` returns a variable not used in the `Set`
module U.Core.ABT.Var where import Data.Set (Set) class (Ord v) => Var v where freshIn :: Set v -> v -> v
52ec94eb90603c8743c983a89cb8a8592b44a726ca5658dbbbe418c089462f0a
turtlesoupy/haskakafka
TestMain.hs
# LANGUAGE ScopedTypeVariables # module Main (main) where import Haskakafka import Haskakafka.InternalSetup import Control.Exception import Control.Monad import System.Environment import Test.Hspec import Text.Regex.Posix import qualified Data.Map as Map import qualified Data.ByteString.Char8 as C8 brokerAddress :: IO String brokerAddress = (getEnv "HASKAKAFKA_TEST_BROKER") `catch` \(_ :: SomeException) -> (return "localhost:9092") brokerTopic :: IO String brokerTopic = (getEnv "HASKAKAFKA_TEST_TOPIC") `catch` \(_ :: SomeException) -> (return "haskakafka_tests") kafkaDelay :: Int -- Little delay for operation kafkaDelay = 5 * 1000 getAddressTopic :: (String -> String -> IO ()) -> IO () getAddressTopic cb = do b <- brokerAddress t <- brokerTopic cb b t sampleProduceMessages :: [KafkaProduceMessage] sampleProduceMessages = [ (KafkaProduceMessage $ C8.pack "hello") , (KafkaProduceKeyedMessage (C8.pack "key") (C8.pack "value")) , (KafkaProduceMessage $ C8.pack "goodbye") ] shouldBeProduceConsume :: KafkaProduceMessage -> KafkaMessage -> IO () shouldBeProduceConsume (KafkaProduceMessage ppayload) m = do (messagePayload m) `shouldBe` ppayload (messageKey m) `shouldBe` Nothing shouldBeProduceConsume (KafkaProduceKeyedMessage pkey ppayload) m = do ppayload `shouldBe` (messagePayload m) (Just pkey) `shouldBe` (messageKey m) primeEOF :: KafkaTopic -> IO () primeEOF kt = consumeMessage kt 0 kafkaDelay >> return () testmain :: IO () testmain = hspec $ do describe "RdKafka versioning" $ do it "should be a valid version number" $ do rdKafkaVersionStr `shouldSatisfy` (=~"[0-9]+(.[0-9]+)+") describe "Kafka Configuration" $ do it "should allow dumping" $ do kConf <- newKafkaConf kvs <- dumpKafkaConf kConf (Map.size kvs) `shouldSatisfy` (>0) it "should change when set is called" $ do kConf <- newKafkaConf setKafkaConfValue kConf "socket.timeout.ms" "50000" kvs <- dumpKafkaConf kConf (kvs Map.! "socket.timeout.ms") `shouldBe` "50000" it "should throw an exception on unknown property" $ do kConf <- newKafkaConf (setKafkaConfValue kConf "blippity.blop.cosby" "120") `shouldThrow` (\(KafkaUnknownConfigurationKey str) -> (length str) > 0) it "should throw an exception on an invalid value" $ do kConf <- newKafkaConf (setKafkaConfValue kConf "socket.timeout.ms" "monorail") `shouldThrow` (\(KafkaInvalidConfigurationValue str) -> (length str) > 0) describe "Kafka topic configuration" $ do it "should allow dumping" $ do kTopicConf <- newKafkaTopicConf kvs <- dumpKafkaTopicConf kTopicConf (Map.size kvs) `shouldSatisfy` (>0) it "should change when set is called" $ do kTopicConf <- newKafkaTopicConf setKafkaTopicConfValue kTopicConf "request.timeout.ms" "20000" kvs <- dumpKafkaTopicConf kTopicConf (kvs Map.! "request.timeout.ms") `shouldBe` "20000" it "should throw an exception on unknown property" $ do kTopicConf <- newKafkaTopicConf (setKafkaTopicConfValue kTopicConf "blippity.blop.cosby" "120") `shouldThrow` (\(KafkaUnknownConfigurationKey str) -> (length str) > 0) it "should throw an exception on an invalid value" $ do kTopicConf <- newKafkaTopicConf (setKafkaTopicConfValue kTopicConf "request.timeout.ms" "mono...doh!") `shouldThrow` (\(KafkaInvalidConfigurationValue str) -> (length str) > 0) describe "Logging" $ do it "should allow setting of log level" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \kafka _ -> do setLogLevel kafka KafkaLogDebug describe "Consume and produce cycle" $ do it "should produce a single message" $ getAddressTopic $ \a t -> do let message = KafkaProduceMessage (C8.pack "Hey, first test message!") perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessage producerTopic (KafkaSpecifiedPartition 0) message perr `shouldBe`Nothing it "should be able to produce and consume a unkeyed message off of the broker" $ getAddressTopic $ \a t -> do let message = KafkaProduceMessage (C8.pack "hey hey we're the monkeys") withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessage producerTopic (KafkaSpecifiedPartition 0) message perr `shouldBe` Nothing et <- consumeMessage topic 0 kafkaDelay case et of Left err -> error $ show err Right m -> message `shouldBeProduceConsume` m it "should be able to produce a keyed message" $ getAddressTopic $ \a t -> do let message = KafkaProduceKeyedMessage (C8.pack "key") (C8.pack "monkey around") perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceKeyedMessage producerTopic message perr `shouldBe` Nothing it "should be able to batch produce messages" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic errs <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessageBatch producerTopic (KafkaSpecifiedPartition 0 ) sampleProduceMessages errs `shouldBe` [] ets <- mapM (\_ -> consumeMessage topic 0 kafkaDelay) ([1..3] :: [Integer]) forM_ (zip sampleProduceMessages ets) $ \(pm, et) -> case (pm, et) of (_, Left err) -> error $ show err (pmessage, Right cm) -> pmessage `shouldBeProduceConsume` cm it "should be able to batch consume messages" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic errs <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessageBatch producerTopic (KafkaSpecifiedPartition 0 ) sampleProduceMessages errs `shouldBe` [] et <- consumeMessageBatch topic 0 kafkaDelay 3 case et of (Left err) -> error $ show err (Right oms) -> do (length oms) `shouldBe` 3 forM_ (zip sampleProduceMessages oms) $ \(pm, om) -> pm `shouldBeProduceConsume` om test for it "should not fail on batch consume when no messages are available #12" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic et <- consumeMessageBatch topic 0 kafkaDelay 3 case et of (Left err) -> error $ show err (Right oms) -> do (length oms) `shouldBe` 0 it "should return EOF on batch consume if necessary" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do et <- consumeMessageBatch topic 0 kafkaDelay 10 case et of (Left err) -> print err (Right _oms) -> error "should return EOF" Test setup ( error on no ) checkForKafka :: IO (Bool) checkForKafka = do a <- brokerAddress me <- fetchBrokerMetadata [] a 1000 return $ case me of (Left _) -> False (Right _) -> True main :: IO () main = do a <- brokerAddress hasKafka <- checkForKafka if hasKafka then testmain else error $ "\n\n\ \*******************************************************************************\n\ \Haskakafka's tests require an operable Kafka broker running on " ++ a ++ "\n\ \please follow the guide in Readme.md to set this up \n\ \*******************************************************************************\n"
null
https://raw.githubusercontent.com/turtlesoupy/haskakafka/cae3348be1a3934629cf58d433c224d87ff59608/tests/TestMain.hs
haskell
Little delay for operation
# LANGUAGE ScopedTypeVariables # module Main (main) where import Haskakafka import Haskakafka.InternalSetup import Control.Exception import Control.Monad import System.Environment import Test.Hspec import Text.Regex.Posix import qualified Data.Map as Map import qualified Data.ByteString.Char8 as C8 brokerAddress :: IO String brokerAddress = (getEnv "HASKAKAFKA_TEST_BROKER") `catch` \(_ :: SomeException) -> (return "localhost:9092") brokerTopic :: IO String brokerTopic = (getEnv "HASKAKAFKA_TEST_TOPIC") `catch` \(_ :: SomeException) -> (return "haskakafka_tests") kafkaDelay = 5 * 1000 getAddressTopic :: (String -> String -> IO ()) -> IO () getAddressTopic cb = do b <- brokerAddress t <- brokerTopic cb b t sampleProduceMessages :: [KafkaProduceMessage] sampleProduceMessages = [ (KafkaProduceMessage $ C8.pack "hello") , (KafkaProduceKeyedMessage (C8.pack "key") (C8.pack "value")) , (KafkaProduceMessage $ C8.pack "goodbye") ] shouldBeProduceConsume :: KafkaProduceMessage -> KafkaMessage -> IO () shouldBeProduceConsume (KafkaProduceMessage ppayload) m = do (messagePayload m) `shouldBe` ppayload (messageKey m) `shouldBe` Nothing shouldBeProduceConsume (KafkaProduceKeyedMessage pkey ppayload) m = do ppayload `shouldBe` (messagePayload m) (Just pkey) `shouldBe` (messageKey m) primeEOF :: KafkaTopic -> IO () primeEOF kt = consumeMessage kt 0 kafkaDelay >> return () testmain :: IO () testmain = hspec $ do describe "RdKafka versioning" $ do it "should be a valid version number" $ do rdKafkaVersionStr `shouldSatisfy` (=~"[0-9]+(.[0-9]+)+") describe "Kafka Configuration" $ do it "should allow dumping" $ do kConf <- newKafkaConf kvs <- dumpKafkaConf kConf (Map.size kvs) `shouldSatisfy` (>0) it "should change when set is called" $ do kConf <- newKafkaConf setKafkaConfValue kConf "socket.timeout.ms" "50000" kvs <- dumpKafkaConf kConf (kvs Map.! "socket.timeout.ms") `shouldBe` "50000" it "should throw an exception on unknown property" $ do kConf <- newKafkaConf (setKafkaConfValue kConf "blippity.blop.cosby" "120") `shouldThrow` (\(KafkaUnknownConfigurationKey str) -> (length str) > 0) it "should throw an exception on an invalid value" $ do kConf <- newKafkaConf (setKafkaConfValue kConf "socket.timeout.ms" "monorail") `shouldThrow` (\(KafkaInvalidConfigurationValue str) -> (length str) > 0) describe "Kafka topic configuration" $ do it "should allow dumping" $ do kTopicConf <- newKafkaTopicConf kvs <- dumpKafkaTopicConf kTopicConf (Map.size kvs) `shouldSatisfy` (>0) it "should change when set is called" $ do kTopicConf <- newKafkaTopicConf setKafkaTopicConfValue kTopicConf "request.timeout.ms" "20000" kvs <- dumpKafkaTopicConf kTopicConf (kvs Map.! "request.timeout.ms") `shouldBe` "20000" it "should throw an exception on unknown property" $ do kTopicConf <- newKafkaTopicConf (setKafkaTopicConfValue kTopicConf "blippity.blop.cosby" "120") `shouldThrow` (\(KafkaUnknownConfigurationKey str) -> (length str) > 0) it "should throw an exception on an invalid value" $ do kTopicConf <- newKafkaTopicConf (setKafkaTopicConfValue kTopicConf "request.timeout.ms" "mono...doh!") `shouldThrow` (\(KafkaInvalidConfigurationValue str) -> (length str) > 0) describe "Logging" $ do it "should allow setting of log level" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \kafka _ -> do setLogLevel kafka KafkaLogDebug describe "Consume and produce cycle" $ do it "should produce a single message" $ getAddressTopic $ \a t -> do let message = KafkaProduceMessage (C8.pack "Hey, first test message!") perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessage producerTopic (KafkaSpecifiedPartition 0) message perr `shouldBe`Nothing it "should be able to produce and consume a unkeyed message off of the broker" $ getAddressTopic $ \a t -> do let message = KafkaProduceMessage (C8.pack "hey hey we're the monkeys") withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessage producerTopic (KafkaSpecifiedPartition 0) message perr `shouldBe` Nothing et <- consumeMessage topic 0 kafkaDelay case et of Left err -> error $ show err Right m -> message `shouldBeProduceConsume` m it "should be able to produce a keyed message" $ getAddressTopic $ \a t -> do let message = KafkaProduceKeyedMessage (C8.pack "key") (C8.pack "monkey around") perr <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceKeyedMessage producerTopic message perr `shouldBe` Nothing it "should be able to batch produce messages" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic errs <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessageBatch producerTopic (KafkaSpecifiedPartition 0 ) sampleProduceMessages errs `shouldBe` [] ets <- mapM (\_ -> consumeMessage topic 0 kafkaDelay) ([1..3] :: [Integer]) forM_ (zip sampleProduceMessages ets) $ \(pm, et) -> case (pm, et) of (_, Left err) -> error $ show err (pmessage, Right cm) -> pmessage `shouldBeProduceConsume` cm it "should be able to batch consume messages" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic errs <- withKafkaProducer [] [] a t $ \_ producerTopic -> do produceMessageBatch producerTopic (KafkaSpecifiedPartition 0 ) sampleProduceMessages errs `shouldBe` [] et <- consumeMessageBatch topic 0 kafkaDelay 3 case et of (Left err) -> error $ show err (Right oms) -> do (length oms) `shouldBe` 3 forM_ (zip sampleProduceMessages oms) $ \(pm, om) -> pm `shouldBeProduceConsume` om test for it "should not fail on batch consume when no messages are available #12" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do primeEOF topic et <- consumeMessageBatch topic 0 kafkaDelay 3 case et of (Left err) -> error $ show err (Right oms) -> do (length oms) `shouldBe` 0 it "should return EOF on batch consume if necessary" $ getAddressTopic $ \a t -> do withKafkaConsumer [] [] a t 0 KafkaOffsetEnd $ \_ topic -> do et <- consumeMessageBatch topic 0 kafkaDelay 10 case et of (Left err) -> print err (Right _oms) -> error "should return EOF" Test setup ( error on no ) checkForKafka :: IO (Bool) checkForKafka = do a <- brokerAddress me <- fetchBrokerMetadata [] a 1000 return $ case me of (Left _) -> False (Right _) -> True main :: IO () main = do a <- brokerAddress hasKafka <- checkForKafka if hasKafka then testmain else error $ "\n\n\ \*******************************************************************************\n\ \Haskakafka's tests require an operable Kafka broker running on " ++ a ++ "\n\ \please follow the guide in Readme.md to set this up \n\ \*******************************************************************************\n"
05af41f587ae0397e291d528d853371351748e3c9b95e969e2cfed982f0ef06c
cpsc411/cpsc411-book
a3-skeleton.rkt
#lang racket (require racket/set "a3-graph-lib.rkt" "a3-compiler-lib.rkt") (provide current-assignable-registers compiler-a2 compiler-a3 check-values-lang interp-values-lang uniquify select-instructions check-loc-lang uncover-locals assign-homes assign-registers conflict-analysis undead-analysis assign-homes-opt replace-locations patch-instructions check-paren-x64 interp-paren-x64 generate-x64) (module+ test (require rackunit)) ;; ------------------------------------------------------------------------ ;; New starter code. (TODO "Merge your solution from a2.rkt into this section. You should move this starter code to just after the definition of assign-homes in your current implementation.") Exercise 1 (define current-assignable-registers (TODO "Design and implement the parameter current-assignable-registers for Exercise 1")) Exercise 2 (define (assign-registers p) (TODO "Design and implement assign-registers for Exercise 2.")) Exercise 3 (define (conflict-analysis p) (TODO "Design and implement conflict-analysis for Exercise 3.")) Exercise 4 (define (undead-analysis p) (TODO "Design and implement undead-analysis for Exercise 4.")) (module+ test (define (get-undead-info p) (match p [`(begin ,info . ,any) (car (dict-ref info 'undead))])) (define-check (check-undead-sets-equal? actuals expecteds) (unless (equal? (length actuals) (length expecteds)) (fail-check (format "Expected ~a elements in the undead set, but found only ~a elements\n expecteds~a:\n actuals:~a" (length expecteds) (length actuals) expecteds actuals))) (for ([s1 actuals] [s2 expecteds] [i (in-naturals)]) (unless (set=? s1 s2) (fail-check (format "Expected undead set ~a for instruction ~a, but got ~a" s2 i s1))))) (check-undead-sets-equal? (get-undead-info (undead-analysis '(begin ((locals (v.1 w.2 x.3 y.4 z.5 t.6 t.7 t.8 t.9))) (set! v.1 1) (set! w.2 46) (set! x.3 v.1) (set! t.7 7) (set! x.3 (+ x.3 t.7)) (set! y.4 x.3) (set! t.8 4) (set! y.4 (+ y.4 t.8)) (set! z.5 x.3) (set! z.5 (+ z.5 w.2)) (set! t.6 y.4) (set! t.9 -1) (set! t.6 (* t.6 t.9)) (set! z.5 (+ z.5 t.6)) (halt z.5)))) '((v.1) (v.1 w.2) (w.2 x.3) (t.7 w.2 x.3) (w.2 x.3) (y.4 w.2 x.3) (t.8 y.4 w.2 x.3) (y.4 w.2 x.3) (z.5 y.4 w.2) (z.5 y.4) (t.6 z.5) (t.6 z.5 t.9) (t.6 z.5) (z.5) ()))) Exercise 5 (define (assign-homes-opt p) (TODO "Design and implement assign-homes-opt for Exercise 5.")) ;; ------------------------------------------------------------------------ (TODO "Add this section to your solution to A2 after the definition of generate-x64") Exercise 6 (define (compiler-a2 p) (TODO "Implement compiler-a2 for Exercise 6")) (define (compiler-a3 p) (TODO "Implement compiler-a3 for Exercise 6")) #| Fill me in ... |# (TODO "Write a brief paragraph in the above comment block comparing the compiler-a2 and compiler-a3 for Exercise 6.") ;; ------------------------------------------------------------------------
null
https://raw.githubusercontent.com/cpsc411/cpsc411-book/f2199857fe0b894ac5216775c5e6036f5fb0a8f2/build/share/a3-skeleton.rkt
racket
------------------------------------------------------------------------ New starter code. ------------------------------------------------------------------------ Fill me in ... ------------------------------------------------------------------------
#lang racket (require racket/set "a3-graph-lib.rkt" "a3-compiler-lib.rkt") (provide current-assignable-registers compiler-a2 compiler-a3 check-values-lang interp-values-lang uniquify select-instructions check-loc-lang uncover-locals assign-homes assign-registers conflict-analysis undead-analysis assign-homes-opt replace-locations patch-instructions check-paren-x64 interp-paren-x64 generate-x64) (module+ test (require rackunit)) (TODO "Merge your solution from a2.rkt into this section. You should move this starter code to just after the definition of assign-homes in your current implementation.") Exercise 1 (define current-assignable-registers (TODO "Design and implement the parameter current-assignable-registers for Exercise 1")) Exercise 2 (define (assign-registers p) (TODO "Design and implement assign-registers for Exercise 2.")) Exercise 3 (define (conflict-analysis p) (TODO "Design and implement conflict-analysis for Exercise 3.")) Exercise 4 (define (undead-analysis p) (TODO "Design and implement undead-analysis for Exercise 4.")) (module+ test (define (get-undead-info p) (match p [`(begin ,info . ,any) (car (dict-ref info 'undead))])) (define-check (check-undead-sets-equal? actuals expecteds) (unless (equal? (length actuals) (length expecteds)) (fail-check (format "Expected ~a elements in the undead set, but found only ~a elements\n expecteds~a:\n actuals:~a" (length expecteds) (length actuals) expecteds actuals))) (for ([s1 actuals] [s2 expecteds] [i (in-naturals)]) (unless (set=? s1 s2) (fail-check (format "Expected undead set ~a for instruction ~a, but got ~a" s2 i s1))))) (check-undead-sets-equal? (get-undead-info (undead-analysis '(begin ((locals (v.1 w.2 x.3 y.4 z.5 t.6 t.7 t.8 t.9))) (set! v.1 1) (set! w.2 46) (set! x.3 v.1) (set! t.7 7) (set! x.3 (+ x.3 t.7)) (set! y.4 x.3) (set! t.8 4) (set! y.4 (+ y.4 t.8)) (set! z.5 x.3) (set! z.5 (+ z.5 w.2)) (set! t.6 y.4) (set! t.9 -1) (set! t.6 (* t.6 t.9)) (set! z.5 (+ z.5 t.6)) (halt z.5)))) '((v.1) (v.1 w.2) (w.2 x.3) (t.7 w.2 x.3) (w.2 x.3) (y.4 w.2 x.3) (t.8 y.4 w.2 x.3) (y.4 w.2 x.3) (z.5 y.4 w.2) (z.5 y.4) (t.6 z.5) (t.6 z.5 t.9) (t.6 z.5) (z.5) ()))) Exercise 5 (define (assign-homes-opt p) (TODO "Design and implement assign-homes-opt for Exercise 5.")) (TODO "Add this section to your solution to A2 after the definition of generate-x64") Exercise 6 (define (compiler-a2 p) (TODO "Implement compiler-a2 for Exercise 6")) (define (compiler-a3 p) (TODO "Implement compiler-a3 for Exercise 6")) (TODO "Write a brief paragraph in the above comment block comparing the compiler-a2 and compiler-a3 for Exercise 6.")
2996aafd6f9e7dfda4c4989c75fddb17c95a81371a012d02c943996347414063
replikativ/hitchhiker-tree
redis_test.clj
(ns hitchhiker.redis-test (:require [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [hitchhiker.tree.bootstrap.redis :as redis] [hitchhiker.tree :as core] [hitchhiker.tree.utils.async :as ha] hitchhiker.tree.core-test [hitchhiker.tree.messaging :as msg] [taoensso.carmine :as car :refer [wcar]])) (defn insert [t k] (msg/insert t k k)) (defn lookup-fwd-iter [t v] (seq (map first (msg/lookup-fwd-iter t v)))) (defn mixed-op-seq "This is like the basic mixed-op-seq tests, but it also mixes in flushes to redis and automatically deletes the old tree" [add-freq del-freq flush-freq universe-size num-ops] (prop/for-all [ops (gen/vector (gen/frequency [[add-freq (gen/tuple (gen/return :add) (gen/no-shrink gen/int))] [flush-freq (gen/return [:flush])] [del-freq (gen/tuple (gen/return :del) (gen/no-shrink gen/int))]]) num-ops)] (assert (let [ks (wcar {} (car/keys "*"))] (or (empty? ks) (= ["refcount:expiry"] ks) (= #{"refcount:expiry" nil} (into #{} ks)))) "Start with no keys") (let [[b-tree root set] (reduce (fn [[t root set] [op x]] (let [x-reduced (when x (mod x universe-size))] (case op :flush (let [t (:tree (ha/<?? (core/flush-tree t (redis/->RedisBackend))))] (when root (wcar {} (redis/drop-ref root))) #_(println "flush") [t (ha/<?? (:storage-addr t)) set]) :add (do #_(println "add") [(ha/<?? (insert t x-reduced)) root (conj set x-reduced)]) :del (do #_(println "del") [(ha/<?? (msg/delete t x-reduced)) root (disj set x-reduced)])))) [(ha/<?? (core/b-tree (core/->Config 3 3 2))) nil #{}] ops)] #_(println "Make it to the end of a test, tree has" (count (lookup-fwd-iter b-tree -1)) "keys left") (let [b-tree-order (lookup-fwd-iter b-tree -1) res (= b-tree-order (seq (sort set)))] (wcar {} (redis/drop-ref root)) (assert (let [ks (wcar {} (car/keys "*"))] (or (empty? ks) (= ["refcount:expiry"] ks) (= #{"refcount:expiry" nil} (into #{} ks)))) "End with no keys") (assert res (str "These are unequal: " (pr-str b-tree-order) " " (pr-str (seq (sort set))))) res)))) (comment (defspec test-many-keys-bigger-trees 100 (mixed-op-seq 800 200 10 1000 1000)) (test-many-keys-bigger-trees) (count (remove (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (condp = :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} (drop-last 2 opseq)) (lookup-fwd-iter (msg/delete test-tree -33) 0))) (:op-buf test-tree) (count (sort (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} opseq))) (let [ops (->> (read-string (slurp "broken-data.edn")) (map (fn [[op x]] [op (mod x 100000)])) (drop-last 125))] (let [[b-tree s] (reduce (fn [[t s] [op x]] (let [x-reduced (mod x 100000)] (case op :add [(insert t x-reduced) (conj s x-reduced)] :del [(msg/delete t x-reduced) (disj s x-reduced)]))) [(core/b-tree (core/->Config 3 3 2)) #{}] ops)] (println ops) (println (->> (read-string (slurp "broken-data.edn")) (map (fn [[op x]] [op (mod x 100000)])) (take-last 125) first)) (println (lookup-fwd-iter b-tree -1)) (println (sort s)))) (defn trial [] (let [opseq (read-string (slurp "broken-data.edn")) [b-tree root] (reduce (fn [[t root] [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush (let [_ (println "About to flush...") t (:tree (core/flush-tree t (redis/->RedisBackend)))] (when root (wcar {} (redis/drop-ref root))) (println "flushed") [t @(:storage-addr t)]) :add (do (println "about to add" x-reduced "...") (let [x [(insert t x-reduced) root]] (println "added") x)) :del (do (println "about to del" x-reduced "...") (let [x [(msg/delete t x-reduced) root]] (println "deled") x))))) [(core/b-tree (core/->Config 3 3 2))] opseq)] (def test-tree b-tree) (println "Got diff" (count (remove (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} opseq) (lookup-fwd-iter test-tree 0)))) (println "balanced?" (hitchhiker.tree.core-test/check-node-is-balanced test-tree)) (def my-root root))) (map #(and (second %) (mod (second %) 1000)) opseq) (def opseq (read-string (io/resource "test/resources/redis_test_data.clj"))))
null
https://raw.githubusercontent.com/replikativ/hitchhiker-tree/9279fb75a581717e7b52a9d3f4c5e2e537458372/test/hitchhiker/redis_test.clj
clojure
(ns hitchhiker.redis-test (:require [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [hitchhiker.tree.bootstrap.redis :as redis] [hitchhiker.tree :as core] [hitchhiker.tree.utils.async :as ha] hitchhiker.tree.core-test [hitchhiker.tree.messaging :as msg] [taoensso.carmine :as car :refer [wcar]])) (defn insert [t k] (msg/insert t k k)) (defn lookup-fwd-iter [t v] (seq (map first (msg/lookup-fwd-iter t v)))) (defn mixed-op-seq "This is like the basic mixed-op-seq tests, but it also mixes in flushes to redis and automatically deletes the old tree" [add-freq del-freq flush-freq universe-size num-ops] (prop/for-all [ops (gen/vector (gen/frequency [[add-freq (gen/tuple (gen/return :add) (gen/no-shrink gen/int))] [flush-freq (gen/return [:flush])] [del-freq (gen/tuple (gen/return :del) (gen/no-shrink gen/int))]]) num-ops)] (assert (let [ks (wcar {} (car/keys "*"))] (or (empty? ks) (= ["refcount:expiry"] ks) (= #{"refcount:expiry" nil} (into #{} ks)))) "Start with no keys") (let [[b-tree root set] (reduce (fn [[t root set] [op x]] (let [x-reduced (when x (mod x universe-size))] (case op :flush (let [t (:tree (ha/<?? (core/flush-tree t (redis/->RedisBackend))))] (when root (wcar {} (redis/drop-ref root))) #_(println "flush") [t (ha/<?? (:storage-addr t)) set]) :add (do #_(println "add") [(ha/<?? (insert t x-reduced)) root (conj set x-reduced)]) :del (do #_(println "del") [(ha/<?? (msg/delete t x-reduced)) root (disj set x-reduced)])))) [(ha/<?? (core/b-tree (core/->Config 3 3 2))) nil #{}] ops)] #_(println "Make it to the end of a test, tree has" (count (lookup-fwd-iter b-tree -1)) "keys left") (let [b-tree-order (lookup-fwd-iter b-tree -1) res (= b-tree-order (seq (sort set)))] (wcar {} (redis/drop-ref root)) (assert (let [ks (wcar {} (car/keys "*"))] (or (empty? ks) (= ["refcount:expiry"] ks) (= #{"refcount:expiry" nil} (into #{} ks)))) "End with no keys") (assert res (str "These are unequal: " (pr-str b-tree-order) " " (pr-str (seq (sort set))))) res)))) (comment (defspec test-many-keys-bigger-trees 100 (mixed-op-seq 800 200 10 1000 1000)) (test-many-keys-bigger-trees) (count (remove (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (condp = :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} (drop-last 2 opseq)) (lookup-fwd-iter (msg/delete test-tree -33) 0))) (:op-buf test-tree) (count (sort (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} opseq))) (let [ops (->> (read-string (slurp "broken-data.edn")) (map (fn [[op x]] [op (mod x 100000)])) (drop-last 125))] (let [[b-tree s] (reduce (fn [[t s] [op x]] (let [x-reduced (mod x 100000)] (case op :add [(insert t x-reduced) (conj s x-reduced)] :del [(msg/delete t x-reduced) (disj s x-reduced)]))) [(core/b-tree (core/->Config 3 3 2)) #{}] ops)] (println ops) (println (->> (read-string (slurp "broken-data.edn")) (map (fn [[op x]] [op (mod x 100000)])) (take-last 125) first)) (println (lookup-fwd-iter b-tree -1)) (println (sort s)))) (defn trial [] (let [opseq (read-string (slurp "broken-data.edn")) [b-tree root] (reduce (fn [[t root] [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush (let [_ (println "About to flush...") t (:tree (core/flush-tree t (redis/->RedisBackend)))] (when root (wcar {} (redis/drop-ref root))) (println "flushed") [t @(:storage-addr t)]) :add (do (println "about to add" x-reduced "...") (let [x [(insert t x-reduced) root]] (println "added") x)) :del (do (println "about to del" x-reduced "...") (let [x [(msg/delete t x-reduced) root]] (println "deled") x))))) [(core/b-tree (core/->Config 3 3 2))] opseq)] (def test-tree b-tree) (println "Got diff" (count (remove (reduce (fn [t [op x]] (let [x-reduced (when x (mod x 1000))] (case op :flush t :add (conj t x-reduced) :del (disj t x-reduced)))) #{} opseq) (lookup-fwd-iter test-tree 0)))) (println "balanced?" (hitchhiker.tree.core-test/check-node-is-balanced test-tree)) (def my-root root))) (map #(and (second %) (mod (second %) 1000)) opseq) (def opseq (read-string (io/resource "test/resources/redis_test_data.clj"))))
7b100c30ec8907610fcd88748a3bc1b0548c300531e6c27033c8959e115f52c5
monadbobo/ocaml-core
extended_result.ml
open Core.Std module Ok = Result module Error = struct module T = struct type ('a,'b) t = ('b,'a) Result.t end include T include Monad.Make2 (struct include T let bind x f = match x with | Error x -> f x | Ok _ as x -> x let return x = Error x end) end module Exn = struct module T = struct type 'a t = ('a, exn) Result.t with sexp_of end include T include (Monad.Make (struct include T let return x = Ok x let bind (t : 'a t) f = match t with | Ok x -> f x | Error e -> Error e ;; end):Monad.S with type 'a t := 'a t) let ok = function | Ok a -> a | Error exn -> raise exn ;; end
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/extended_result.ml
ocaml
open Core.Std module Ok = Result module Error = struct module T = struct type ('a,'b) t = ('b,'a) Result.t end include T include Monad.Make2 (struct include T let bind x f = match x with | Error x -> f x | Ok _ as x -> x let return x = Error x end) end module Exn = struct module T = struct type 'a t = ('a, exn) Result.t with sexp_of end include T include (Monad.Make (struct include T let return x = Ok x let bind (t : 'a t) f = match t with | Ok x -> f x | Error e -> Error e ;; end):Monad.S with type 'a t := 'a t) let ok = function | Ok a -> a | Error exn -> raise exn ;; end
e1baa411630cc23adcb8343372c340634e56a15094e971b5e79744e0f9fca0ad
input-output-hk/ouroboros-network
Praos.hs
# LANGUAGE BangPatterns # {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UndecidableSuperClasses #-} -- | Proof of concept implementation of Praos module Ouroboros.Consensus.Mock.Protocol.Praos ( HotKey (..) , HotKeyEvolutionError (..) , Praos , PraosChainDepState (..) , PraosEvolvingStake (..) , PraosExtraFields (..) , PraosFields (..) , PraosParams (..) , emptyPraosEvolvingStake , evolveKey , forgePraosFields -- * Tags , PraosCrypto (..) , PraosMockCrypto , PraosStandardCrypto , PraosValidateView (..) , PraosValidationError (..) , praosValidateView -- * Type instances , BlockInfo (..) , ConsensusConfig (..) , Ticked (..) ) where import Cardano.Binary (FromCBOR (..), ToCBOR (..), serialize') import Codec.CBOR.Decoding (decodeListLenOf) import Codec.CBOR.Encoding (encodeListLen) import Codec.Serialise (Serialise (..)) import Control.Monad (unless) import Control.Monad.Except (throwError) import Data.Kind (Type) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Typeable import Data.Word (Word64) import GHC.Generics (Generic) import GHC.Stack (HasCallStack) import NoThunks.Class (NoThunks (..)) import Numeric.Natural import Cardano.Crypto.DSIGN.Ed448 (Ed448DSIGN) import Cardano.Crypto.Hash.Class (HashAlgorithm (..), hashToBytes, hashWithSerialiser, sizeHash) import Cardano.Crypto.Hash.SHA256 (SHA256) import Cardano.Crypto.KES.Class import Cardano.Crypto.KES.Mock import Cardano.Crypto.KES.Simple import Cardano.Crypto.Util import Cardano.Crypto.VRF.Class import Cardano.Crypto.VRF.Mock (MockVRF) import Cardano.Crypto.VRF.Simple (SimpleVRF) import Cardano.Slotting.EpochInfo import Data.Maybe (fromMaybe) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Mock.Ledger.Stake import Ouroboros.Consensus.NodeId (CoreNodeId (..)) import Ouroboros.Consensus.Protocol.Abstract import Ouroboros.Consensus.Protocol.Signed import Ouroboros.Consensus.Util.Condense The Praos paper can be located at -- A block as defined in Praos ( section 3 , definition 2 , then extended in Fig 9 ) -- consist of a tuple: -- > B = ( slⱼ , st , d , B_πj , ρ , σⱼ ) -- -- where -- - slⱼ: the slot at which the block was generated. -- Named 'simpleSlotNo' in the 'SimpleStdHeader' block header. -- As far as consensus is concerned this will be accessed through ' biSlot ' in each block in the ' ChainDepState ' . -- -- - st: state, a string ∈ {0,1}^λ, which holds the hash of the previous block. -- Named 'simplePrev' in the 'SimpleStdHeader' block header. -- -- - d: data (transaction data in most cases). -- Named 'simpleBody' inside 'SimpleBlock'. -- -- - B_πj: block proof consisting of (Uᵢ, y, π). -- Named 'praosY' inside 'PraosExtraFields'. - y : a VRF output used to confirm that Uᵢ was the slot leader . - π : the VRF proof of the above value . -- > ( y , π ) ≜ VRF_evalProve(η , slⱼ , TEST ) see 9 -- -- - ρ: the block nonce consisting of (ρ_y, ρ_π), to capture entropy from the -- block forging process. -- Named 'praosRho' inside 'PraosExtraFields'. -- - ρ_y: a VRF output used to confirm this block captured all the previous -- entropy. - ρ_π : the VRF proof of the above value . -- > ( ρ_y , ρ_π ) ≜ VRF_evalProve(η , slⱼ , ) see 9 -- - σⱼ : a signature on ( st , d , slⱼ , B_πj , ρ ) with the signing key -- for the slot slⱼ for the stakeholder Uᵢ. Named ' praosSignature ' in ' PraosFields ' . -- Protocol parameters : -- - k: maximum number of blocks we can rollback. -- Named 'praosSecurityParam' in 'PraosParams'. -- - R: number of slots per epoch. -- Named 'praosSlotsPerEpoch' in 'PraosParams'. -- - f: the active slots coefficient, specifies roughly the proportion of -- occupied slots per epoch. -- Named 'praosLeaderF' in 'PraosParams'. -- -- Some values you will encounter: - η : The epoch 's nonce . Captures entropy from the block chain . See Fig 8 in praos paper for where it is used and 10 for how it is defined . -- Defined as the hash of the η from the previous epoch, this epoch number and the ρ of the first 2/3 of the blocks in the previous epoch . -- Commonly named through the code as 'eta'. -- > η_e ≜ HASH(η_{e-1 } || e || ρ_{e-1,0 } ... , 2R/3 } ) -- -- - Tᵢ: the leader threshold for a specific stakeholder considering its relative stake ( therefore depending on the slot ) . Defined in the Praos paper in Figure 4 using the definition for ϕ_f(αᵢ ) from section 3.3 . -- Named 't' in the code but essentially computed by 'leaderThreshold' in -- 'rhoYT'. -- -- > Tᵢ ≜ 2^(l_VRF) * pᵢ -- > pᵢ = ϕ_f(αᵢ) ≜ 1 - (1 - f)^(αᵢ) ------------------------------------------------------------------------------ Fields required by Praos in the header ------------------------------------------------------------------------------ Fields required by Praos in the header -------------------------------------------------------------------------------} | The fields that Praos required in the header data PraosFields crypto typeBeingSigned = PraosFields { praosSignature :: SignedKES (PraosKES crypto) typeBeingSigned , praosExtraFields :: PraosExtraFields crypto } deriving (Generic) instance (PraosCrypto c, Typeable toSign) => NoThunks (PraosFields c toSign) deriving instance PraosCrypto c => Show (PraosFields c toSign) deriving instance PraosCrypto c => Eq (PraosFields c toSign) -- | Fields that should be included in the signature data PraosExtraFields c = PraosExtraFields { praosCreator :: CoreNodeId , praosRho :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosY :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) } deriving (Generic) instance PraosCrypto c => NoThunks (PraosExtraFields c) deriving instance PraosCrypto c => Show (PraosExtraFields c) deriving instance PraosCrypto c => Eq (PraosExtraFields c) -- | A validate view is an association from the (@signed@) value to the -- @PraosFields@ that contains the signature that sign it. -- -- In this mock implementation, this could have been simplified to use -- @SignedSimplePraos@ but from the consensus point of view, it is not relevant -- which actual value is being signed, that's why we use the existential. data PraosValidateView c = forall signed. Cardano.Crypto.KES.Class.Signable (PraosKES c) signed => PraosValidateView (PraosFields c signed) signed -- | Convenience constructor for 'PraosValidateView' praosValidateView :: ( SignedHeader hdr , Cardano.Crypto.KES.Class.Signable (PraosKES c) (Signed hdr) ) => (hdr -> PraosFields c (Signed hdr)) -> (hdr -> PraosValidateView c) praosValidateView getFields hdr = PraosValidateView (getFields hdr) (headerSigned hdr) {------------------------------------------------------------------------------- Forging -------------------------------------------------------------------------------} -- | The key used for the given period or a stub Poisoned value. -- A key will be poisoned if it failed to evolve by , and will remain -- poisoned forever after that. data HotKey c = HotKey !Period -- ^ Absolute period of the KES key !(SignKeyKES (PraosKES c)) | HotKeyPoisoned deriving (Generic) instance PraosCrypto c => NoThunks (HotKey c) deriving instance PraosCrypto c => Show (HotKey c) -- | The 'HotKey' could not be evolved to the given 'Period'. newtype HotKeyEvolutionError = HotKeyEvolutionError Period deriving (Show) -- | To be used in conjunction with, e.g., 'updateMVar'. -- -- NOTE: when the key's period is after the target period, we shouldn't use -- it, but we currently do. In real TPraos we check this in -- 'tpraosCheckCanForge'. evolveKey :: PraosCrypto c => SlotNo -> HotKey c -> (HotKey c, UpdateInfo (HotKey c) HotKeyEvolutionError) evolveKey slotNo hotKey = case hotKey of HotKey keyPeriod oldKey | keyPeriod >= targetPeriod -> (hotKey, Updated hotKey) | otherwise -> case updateKES () oldKey keyPeriod of Nothing -> (HotKeyPoisoned, UpdateFailed $ HotKeyEvolutionError targetPeriod) Just newKey -> evolveKey slotNo (HotKey (keyPeriod + 1) newKey) HotKeyPoisoned -> (HotKeyPoisoned, UpdateFailed $ HotKeyEvolutionError targetPeriod) where targetPeriod :: Period targetPeriod = fromIntegral $ unSlotNo slotNo | Create a PraosFields using a proof , a key and the data to be signed . -- It is done by signing whatever is extracted from the extra fields by -- and storing the signature and the extra fields on a @PraosFields@. forgePraosFields :: ( PraosCrypto c , Cardano.Crypto.KES.Class.Signable (PraosKES c) toSign , HasCallStack ) => PraosProof c -> HotKey c -> (PraosExtraFields c -> toSign) -> PraosFields c toSign forgePraosFields PraosProof{..} hotKey mkToSign = case hotKey of HotKey kesPeriod key -> PraosFields { praosSignature = signedKES () kesPeriod (mkToSign fieldsToSign) key , praosExtraFields = fieldsToSign } HotKeyPoisoned -> error "trying to sign with a poisoned key" where fieldsToSign = PraosExtraFields { praosCreator = praosLeader , praosRho = praosProofRho , praosY = praosProofY } {------------------------------------------------------------------------------- Mock stake distribution -------------------------------------------------------------------------------} -- | An association from epoch to stake distributions. -- -- Should be used when checking if someone is the leader of a particular slot. -- This is sufficiently good for a mock protocol as far as consensus is -- concerned. It is not strictly necessary that the stake distribution is -- computed from previous epochs, as we just need to consider that: -- -- 1) an attacker cannot influence it. 2 ) all the nodes agree on the same value for each Slot . -- Each pair stores the stake distribution established by the end of the epoch in the first item of the pair . See ' latestEvolvedStakeDistAsOfEpoch ' for the -- intended interface. -- -- If no value is returned, that means we are checking the stake before any -- changes have happened so we should consult instead the 'praosInitialStake'. newtype PraosEvolvingStake = PraosEvolvingStake (Map EpochNo StakeDist) deriving stock Show deriving newtype NoThunks emptyPraosEvolvingStake :: PraosEvolvingStake emptyPraosEvolvingStake = PraosEvolvingStake Map.empty latestEvolvedStakeDistAsOfEpoch :: PraosEvolvingStake -> EpochNo -> Maybe StakeDist latestEvolvedStakeDistAsOfEpoch (PraosEvolvingStake x) e = fmap snd . Map.lookupMax . fst $ Map.split e x ------------------------------------------------------------------------------ Praos specific types ------------------------------------------------------------------------------ Praos specific types -------------------------------------------------------------------------------} |The two VRF invocation modes , ( rho ) and TEST ( y ) . See the comment at -- the top of the module for an explanation of these. data VRFType = NONCE | TEST deriving (Show, Eq, Ord, Generic, NoThunks) instance Serialise VRFType instance ToCBOR VRFType where This is a cheat , and at some point we probably want to decide on Serialise / ToCBOR toCBOR = encode -- |Proofs certifying ρ and y for a given slot and eta. data PraosProof c = PraosProof { praosProofRho :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosProofY :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosLeader :: CoreNodeId } -- | An error that can arise during validation data PraosValidationError c = PraosInvalidSlot SlotNo SlotNo | PraosUnknownCoreId CoreNodeId | PraosInvalidSig String (VerKeyKES (PraosKES c)) Natural (SigKES (PraosKES c)) | PraosInvalidCert (VerKeyVRF (PraosVRF c)) (Natural, SlotNo, VRFType) Natural (CertVRF (PraosVRF c)) | PraosInsufficientStake Double Natural deriving (Generic) We override ' showTypeOf ' to make sure to show @c@ instance PraosCrypto c => NoThunks (PraosValidationError c) where showTypeOf _ = show $ typeRep (Proxy @(PraosValidationError c)) deriving instance PraosCrypto c => Show (PraosValidationError c) deriving instance PraosCrypto c => Eq (PraosValidationError c) data BlockInfo c = BlockInfo { biSlot :: !SlotNo , biRho :: !(CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType)) } deriving (Generic) deriving instance PraosCrypto c => Show (BlockInfo c) deriving instance PraosCrypto c => Eq (BlockInfo c) deriving instance PraosCrypto c => NoThunks (BlockInfo c) ------------------------------------------------------------------------------ Protocol proper ------------------------------------------------------------------------------ Protocol proper -------------------------------------------------------------------------------} | An uninhabited type representing the Praos protocol . data Praos c -- | Praos parameters that are node independent data PraosParams = PraosParams { praosLeaderF :: !Double ^ f , the active slots coefficient , defined in 3.3 in the Praos paper . , praosSecurityParam :: !SecurityParam -- ^ k, maximum number of blocks we can rollback , praosSlotsPerEpoch :: !Word64 ^ R , slots in each epoch , defined in section 3 in the Praos paper . } deriving (Generic, NoThunks) -- | The configuration that will be provided to every node when running the MockPraos protocol . data instance ConsensusConfig (Praos c) = PraosConfig { praosParams :: !PraosParams , praosInitialEta :: !Natural , praosInitialStake :: !StakeDist , praosEvolvingStake :: !PraosEvolvingStake , praosSignKeyVRF :: !(SignKeyVRF (PraosVRF c)) , praosVerKeys :: !(Map CoreNodeId (VerKeyKES (PraosKES c), VerKeyVRF (PraosVRF c))) } deriving (Generic) instance PraosCrypto c => NoThunks (ConsensusConfig (Praos c)) slotEpoch :: ConsensusConfig (Praos c) -> SlotNo -> EpochNo slotEpoch PraosConfig{..} s = fixedEpochInfoEpoch (EpochSize praosSlotsPerEpoch) s where PraosParams{..} = praosParams epochFirst :: ConsensusConfig (Praos c) -> EpochNo -> SlotNo epochFirst PraosConfig{..} e = fixedEpochInfoFirst (EpochSize praosSlotsPerEpoch) e where PraosParams{..} = praosParams -- |The chain dependent state, in this case as it is a mock, we just will store a list of BlockInfos that allow us to look into the past . newtype PraosChainDepState c = PraosChainDepState { praosHistory :: [BlockInfo c] } deriving stock (Eq, Show) deriving newtype (NoThunks, Serialise) infosSlice :: SlotNo -> SlotNo -> [BlockInfo c] -> [BlockInfo c] infosSlice from to xs = takeWhile (\b -> biSlot b >= from) $ dropWhile (\b -> biSlot b > to) xs infosEta :: forall c. (PraosCrypto c) => ConsensusConfig (Praos c) -> [BlockInfo c] -> EpochNo -> Natural infosEta l _ 0 = praosInitialEta l infosEta l@PraosConfig{praosParams = PraosParams{..}} xs e = let e' = e - 1 -- the η from the previous epoch eta' = infosEta l xs e' the first slot in previous epoch from = epochFirst l e' 2/3 of the slots per epoch n = div (2 * praosSlotsPerEpoch) 3 the last of the 2/3 of slots in this epoch to = SlotNo $ unSlotNo from + n the list of rhos from the first block in this epoch until the one at 2/3 of the slots . Note it is reversed , i.e. start at the oldest . rhos = reverse [biRho b | b <- infosSlice from to xs] in bytesToNatural . hashToBytes $ hashWithSerialiser @(PraosHash c) toCBOR (eta', e, rhos) | Ticking the Praos chain dep state has no effect -- For the real Praos implementation , ticking is crucial , as it determines the -- point where the "nonce under construction" is swapped out for the "active" -- nonce. However, for the mock implementation, we keep the full history, and -- choose the right nonce from that; this means that ticking has no effect. -- -- We do however need access to the ticked stake distribution. data instance Ticked (PraosChainDepState c) = TickedPraosChainDepState { tickedPraosLedgerView :: Ticked (LedgerView (Praos c)) -- ^ The ticked ledger view. , untickedPraosChainDepState :: PraosChainDepState c -- ^ The unticked chain dependent state, containing the full history. } instance PraosCrypto c => ConsensusProtocol (Praos c) where protocolSecurityParam = praosSecurityParam . praosParams type LedgerView (Praos c) = () type IsLeader (Praos c) = PraosProof c type ValidationErr (Praos c) = PraosValidationError c type ValidateView (Praos c) = PraosValidateView c type ChainDepState (Praos c) = PraosChainDepState c type CanBeLeader (Praos c) = CoreNodeId checkIsLeader cfg@PraosConfig{..} nid slot (TickedPraosChainDepState _u cds) = See Figure 4 of the Praos paper . -- In order to be leader, y must be < Tᵢ if fromIntegral (getOutputVRFNatural (certifiedOutput y)) < t then Just PraosProof { praosProofRho = rho , praosProofY = y , praosLeader = nid } else Nothing where (rho', y', t) = rhoYT cfg (praosHistory cds) slot nid rho = evalCertified () rho' praosSignKeyVRF y = evalCertified () y' praosSignKeyVRF tickChainDepState _ lv _ = TickedPraosChainDepState lv updateChainDepState cfg@PraosConfig{..} (PraosValidateView PraosFields{..} toSign) slot (TickedPraosChainDepState TickedTrivial cds) = do let PraosExtraFields {..} = praosExtraFields nid = praosCreator -- check that the new block advances time case praosHistory cds of (c : _) | biSlot c >= slot -> throwError $ PraosInvalidSlot slot (biSlot c) _ -> return () -- check that block creator is a known core node (vkKES, vkVRF) <- case Map.lookup nid praosVerKeys of Nothing -> throwError $ PraosUnknownCoreId nid Just vks -> return vks -- verify block signature case verifySignedKES () vkKES (fromIntegral $ unSlotNo slot) toSign praosSignature of Right () -> return () Left err -> throwError $ PraosInvalidSig err vkKES (fromIntegral $ unSlotNo slot) (getSig praosSignature) let (rho', y', t) = rhoYT cfg (praosHistory cds) slot nid -- verify rho proof unless (verifyCertified () vkVRF rho' praosRho) $ throwError $ PraosInvalidCert vkVRF rho' (getOutputVRFNatural (certifiedOutput praosRho)) (certifiedProof praosRho) -- verify y proof unless (verifyCertified () vkVRF y' praosY) $ throwError $ PraosInvalidCert vkVRF y' (getOutputVRFNatural (certifiedOutput praosY)) (certifiedProof praosY) -- verify stake unless (fromIntegral (getOutputVRFNatural (certifiedOutput praosY)) < t) $ throwError $ PraosInsufficientStake t $ getOutputVRFNatural (certifiedOutput praosY) -- "store" a block by adding it to the chain dependent state let !bi = BlockInfo { biSlot = slot , biRho = praosRho } return $ PraosChainDepState $ bi : praosHistory cds reupdateChainDepState _ (PraosValidateView PraosFields{..} _) slot (TickedPraosChainDepState TickedTrivial cds) = let PraosExtraFields{..} = praosExtraFields !bi = BlockInfo { biSlot = slot , biRho = praosRho } in PraosChainDepState $ bi : praosHistory cds -- (Standard) Praos uses the standard chain selection rule, so no need to -- override (though see note regarding clock skew). -- | Probability for stakeholder Uᵢ to be elected in slot slⱼ considering its relative stake αᵢ. phi :: ConsensusConfig (Praos c) -> Rational -> Double phi PraosConfig{..} alpha = 1 - (1 - praosLeaderF) ** fromRational alpha where PraosParams{..} = praosParams | Compute Tᵢ for a given stakeholder @n@ at a @SlotNo@. Will be computed from -- 'praosEvolvingStake' (or taken from 'praosInitialStake' if checking epoch 0). leaderThreshold :: forall c. PraosCrypto c => ConsensusConfig (Praos c) -> [BlockInfo c] -> SlotNo -> CoreNodeId -> Double leaderThreshold config _blockInfos s n = let alpha = stakeWithDefault 0 n $ fromMaybe (praosInitialStake config) $ latestEvolvedStakeDistAsOfEpoch (praosEvolvingStake config) (slotEpoch config s) in 2^(l_VRF * 8) * ϕ_f(αᵢ ) the 8 factor converts from bytes to bits . 2 ^ (sizeHash (Proxy :: Proxy (PraosHash c)) * 8) * phi config alpha |Compute the rho , y and parameters for a given slot . rhoYT :: PraosCrypto c => ConsensusConfig (Praos c) -> [BlockInfo c] -> SlotNo -> CoreNodeId -> ( (Natural, SlotNo, VRFType) , (Natural, SlotNo, VRFType) , Double ) rhoYT st xs s nid = let e = slotEpoch st s eta = infosEta st xs e rho = (eta, s, NONCE) y = (eta, s, TEST) t = leaderThreshold st xs s nid in (rho, y, t) {------------------------------------------------------------------------------- Crypto models -------------------------------------------------------------------------------} class ( KESAlgorithm (PraosKES c) , VRFAlgorithm (PraosVRF c) , HashAlgorithm (PraosHash c) , Typeable c , Typeable (PraosVRF c) , Condense (SigKES (PraosKES c)) , Cardano.Crypto.VRF.Class.Signable (PraosVRF c) (Natural, SlotNo, VRFType) , ContextKES (PraosKES c) ~ () , ContextVRF (PraosVRF c) ~ () ) => PraosCrypto (c :: Type) where type family PraosKES c :: Type type family PraosVRF c :: Type type family PraosHash c :: Type data PraosStandardCrypto data PraosMockCrypto instance PraosCrypto PraosStandardCrypto where type PraosKES PraosStandardCrypto = SimpleKES Ed448DSIGN 1000 type PraosVRF PraosStandardCrypto = SimpleVRF type PraosHash PraosStandardCrypto = SHA256 instance PraosCrypto PraosMockCrypto where type PraosKES PraosMockCrypto = MockKES 10000 type PraosVRF PraosMockCrypto = MockVRF type PraosHash PraosMockCrypto = SHA256 ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Condense -------------------------------------------------------------------------------} instance PraosCrypto c => Condense (PraosFields c toSign) where condense PraosFields{..} = condense praosSignature ------------------------------------------------------------------------------ Serialisation ------------------------------------------------------------------------------ Serialisation -------------------------------------------------------------------------------} instance PraosCrypto c => Serialise (BlockInfo c) where encode BlockInfo {..} = mconcat [ encodeListLen 2 , encode biSlot , toCBOR biRho ] decode = do decodeListLenOf 2 biSlot <- decode biRho <- fromCBOR return BlockInfo {..} instance SignableRepresentation (Natural, SlotNo, VRFType) where getSignableRepresentation = serialize' . toCBOR
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/17889be3e1b6d9b5ee86022b91729837051e6fbb/ouroboros-consensus-mock/src/Ouroboros/Consensus/Mock/Protocol/Praos.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE UndecidableInstances # # LANGUAGE UndecidableSuperClasses # | Proof of concept implementation of Praos * Tags * Type instances consist of a tuple: where - slⱼ: the slot at which the block was generated. Named 'simpleSlotNo' in the 'SimpleStdHeader' block header. As far as consensus is concerned this will be accessed through - st: state, a string ∈ {0,1}^λ, which holds the hash of the previous block. Named 'simplePrev' in the 'SimpleStdHeader' block header. - d: data (transaction data in most cases). Named 'simpleBody' inside 'SimpleBlock'. - B_πj: block proof consisting of (Uᵢ, y, π). Named 'praosY' inside 'PraosExtraFields'. - ρ: the block nonce consisting of (ρ_y, ρ_π), to capture entropy from the block forging process. Named 'praosRho' inside 'PraosExtraFields'. - ρ_y: a VRF output used to confirm this block captured all the previous entropy. for the slot slⱼ for the stakeholder Uᵢ. - k: maximum number of blocks we can rollback. Named 'praosSecurityParam' in 'PraosParams'. - R: number of slots per epoch. Named 'praosSlotsPerEpoch' in 'PraosParams'. - f: the active slots coefficient, specifies roughly the proportion of occupied slots per epoch. Named 'praosLeaderF' in 'PraosParams'. Some values you will encounter: Defined as the hash of the η from the previous epoch, this epoch number Commonly named through the code as 'eta'. - Tᵢ: the leader threshold for a specific stakeholder considering its Named 't' in the code but essentially computed by 'leaderThreshold' in 'rhoYT'. > Tᵢ ≜ 2^(l_VRF) * pᵢ > pᵢ = ϕ_f(αᵢ) ≜ 1 - (1 - f)^(αᵢ) ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} | Fields that should be included in the signature | A validate view is an association from the (@signed@) value to the @PraosFields@ that contains the signature that sign it. In this mock implementation, this could have been simplified to use @SignedSimplePraos@ but from the consensus point of view, it is not relevant which actual value is being signed, that's why we use the existential. | Convenience constructor for 'PraosValidateView' ------------------------------------------------------------------------------ Forging ------------------------------------------------------------------------------ | The key used for the given period or a stub Poisoned value. poisoned forever after that. ^ Absolute period of the KES key | The 'HotKey' could not be evolved to the given 'Period'. | To be used in conjunction with, e.g., 'updateMVar'. NOTE: when the key's period is after the target period, we shouldn't use it, but we currently do. In real TPraos we check this in 'tpraosCheckCanForge'. and storing the signature and the extra fields on a @PraosFields@. ------------------------------------------------------------------------------ Mock stake distribution ------------------------------------------------------------------------------ | An association from epoch to stake distributions. Should be used when checking if someone is the leader of a particular slot. This is sufficiently good for a mock protocol as far as consensus is concerned. It is not strictly necessary that the stake distribution is computed from previous epochs, as we just need to consider that: 1) an attacker cannot influence it. intended interface. If no value is returned, that means we are checking the stake before any changes have happened so we should consult instead the 'praosInitialStake'. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} the top of the module for an explanation of these. |Proofs certifying ρ and y for a given slot and eta. | An error that can arise during validation ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} | Praos parameters that are node independent ^ k, maximum number of blocks we can rollback | The configuration that will be provided to every node when running the |The chain dependent state, in this case as it is a mock, we just will store the η from the previous epoch point where the "nonce under construction" is swapped out for the "active" nonce. However, for the mock implementation, we keep the full history, and choose the right nonce from that; this means that ticking has no effect. We do however need access to the ticked stake distribution. ^ The ticked ledger view. ^ The unticked chain dependent state, containing the full history. In order to be leader, y must be < Tᵢ check that the new block advances time check that block creator is a known core node verify block signature verify rho proof verify y proof verify stake "store" a block by adding it to the chain dependent state (Standard) Praos uses the standard chain selection rule, so no need to override (though see note regarding clock skew). | Probability for stakeholder Uᵢ to be elected in slot 'praosEvolvingStake' (or taken from 'praosInitialStake' if checking epoch 0). ------------------------------------------------------------------------------ Crypto models ------------------------------------------------------------------------------ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------}
# LANGUAGE BangPatterns # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Ouroboros.Consensus.Mock.Protocol.Praos ( HotKey (..) , HotKeyEvolutionError (..) , Praos , PraosChainDepState (..) , PraosEvolvingStake (..) , PraosExtraFields (..) , PraosFields (..) , PraosParams (..) , emptyPraosEvolvingStake , evolveKey , forgePraosFields , PraosCrypto (..) , PraosMockCrypto , PraosStandardCrypto , PraosValidateView (..) , PraosValidationError (..) , praosValidateView , BlockInfo (..) , ConsensusConfig (..) , Ticked (..) ) where import Cardano.Binary (FromCBOR (..), ToCBOR (..), serialize') import Codec.CBOR.Decoding (decodeListLenOf) import Codec.CBOR.Encoding (encodeListLen) import Codec.Serialise (Serialise (..)) import Control.Monad (unless) import Control.Monad.Except (throwError) import Data.Kind (Type) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Typeable import Data.Word (Word64) import GHC.Generics (Generic) import GHC.Stack (HasCallStack) import NoThunks.Class (NoThunks (..)) import Numeric.Natural import Cardano.Crypto.DSIGN.Ed448 (Ed448DSIGN) import Cardano.Crypto.Hash.Class (HashAlgorithm (..), hashToBytes, hashWithSerialiser, sizeHash) import Cardano.Crypto.Hash.SHA256 (SHA256) import Cardano.Crypto.KES.Class import Cardano.Crypto.KES.Mock import Cardano.Crypto.KES.Simple import Cardano.Crypto.Util import Cardano.Crypto.VRF.Class import Cardano.Crypto.VRF.Mock (MockVRF) import Cardano.Crypto.VRF.Simple (SimpleVRF) import Cardano.Slotting.EpochInfo import Data.Maybe (fromMaybe) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Mock.Ledger.Stake import Ouroboros.Consensus.NodeId (CoreNodeId (..)) import Ouroboros.Consensus.Protocol.Abstract import Ouroboros.Consensus.Protocol.Signed import Ouroboros.Consensus.Util.Condense The Praos paper can be located at A block as defined in Praos ( section 3 , definition 2 , then extended in Fig 9 ) > B = ( slⱼ , st , d , B_πj , ρ , σⱼ ) ' biSlot ' in each block in the ' ChainDepState ' . - y : a VRF output used to confirm that Uᵢ was the slot leader . - π : the VRF proof of the above value . > ( y , π ) ≜ VRF_evalProve(η , slⱼ , TEST ) see 9 - ρ_π : the VRF proof of the above value . > ( ρ_y , ρ_π ) ≜ VRF_evalProve(η , slⱼ , ) see 9 - σⱼ : a signature on ( st , d , slⱼ , B_πj , ρ ) with the signing key Named ' praosSignature ' in ' PraosFields ' . Protocol parameters : - η : The epoch 's nonce . Captures entropy from the block chain . See Fig 8 in praos paper for where it is used and 10 for how it is defined . and the ρ of the first 2/3 of the blocks in the previous epoch . > η_e ≜ HASH(η_{e-1 } || e || ρ_{e-1,0 } ... , 2R/3 } ) relative stake ( therefore depending on the slot ) . Defined in the Praos paper in Figure 4 using the definition for ϕ_f(αᵢ ) from section 3.3 . Fields required by Praos in the header Fields required by Praos in the header | The fields that Praos required in the header data PraosFields crypto typeBeingSigned = PraosFields { praosSignature :: SignedKES (PraosKES crypto) typeBeingSigned , praosExtraFields :: PraosExtraFields crypto } deriving (Generic) instance (PraosCrypto c, Typeable toSign) => NoThunks (PraosFields c toSign) deriving instance PraosCrypto c => Show (PraosFields c toSign) deriving instance PraosCrypto c => Eq (PraosFields c toSign) data PraosExtraFields c = PraosExtraFields { praosCreator :: CoreNodeId , praosRho :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosY :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) } deriving (Generic) instance PraosCrypto c => NoThunks (PraosExtraFields c) deriving instance PraosCrypto c => Show (PraosExtraFields c) deriving instance PraosCrypto c => Eq (PraosExtraFields c) data PraosValidateView c = forall signed. Cardano.Crypto.KES.Class.Signable (PraosKES c) signed => PraosValidateView (PraosFields c signed) signed praosValidateView :: ( SignedHeader hdr , Cardano.Crypto.KES.Class.Signable (PraosKES c) (Signed hdr) ) => (hdr -> PraosFields c (Signed hdr)) -> (hdr -> PraosValidateView c) praosValidateView getFields hdr = PraosValidateView (getFields hdr) (headerSigned hdr) A key will be poisoned if it failed to evolve by , and will remain data HotKey c = HotKey !(SignKeyKES (PraosKES c)) | HotKeyPoisoned deriving (Generic) instance PraosCrypto c => NoThunks (HotKey c) deriving instance PraosCrypto c => Show (HotKey c) newtype HotKeyEvolutionError = HotKeyEvolutionError Period deriving (Show) evolveKey :: PraosCrypto c => SlotNo -> HotKey c -> (HotKey c, UpdateInfo (HotKey c) HotKeyEvolutionError) evolveKey slotNo hotKey = case hotKey of HotKey keyPeriod oldKey | keyPeriod >= targetPeriod -> (hotKey, Updated hotKey) | otherwise -> case updateKES () oldKey keyPeriod of Nothing -> (HotKeyPoisoned, UpdateFailed $ HotKeyEvolutionError targetPeriod) Just newKey -> evolveKey slotNo (HotKey (keyPeriod + 1) newKey) HotKeyPoisoned -> (HotKeyPoisoned, UpdateFailed $ HotKeyEvolutionError targetPeriod) where targetPeriod :: Period targetPeriod = fromIntegral $ unSlotNo slotNo | Create a PraosFields using a proof , a key and the data to be signed . It is done by signing whatever is extracted from the extra fields by forgePraosFields :: ( PraosCrypto c , Cardano.Crypto.KES.Class.Signable (PraosKES c) toSign , HasCallStack ) => PraosProof c -> HotKey c -> (PraosExtraFields c -> toSign) -> PraosFields c toSign forgePraosFields PraosProof{..} hotKey mkToSign = case hotKey of HotKey kesPeriod key -> PraosFields { praosSignature = signedKES () kesPeriod (mkToSign fieldsToSign) key , praosExtraFields = fieldsToSign } HotKeyPoisoned -> error "trying to sign with a poisoned key" where fieldsToSign = PraosExtraFields { praosCreator = praosLeader , praosRho = praosProofRho , praosY = praosProofY } 2 ) all the nodes agree on the same value for each Slot . Each pair stores the stake distribution established by the end of the epoch in the first item of the pair . See ' latestEvolvedStakeDistAsOfEpoch ' for the newtype PraosEvolvingStake = PraosEvolvingStake (Map EpochNo StakeDist) deriving stock Show deriving newtype NoThunks emptyPraosEvolvingStake :: PraosEvolvingStake emptyPraosEvolvingStake = PraosEvolvingStake Map.empty latestEvolvedStakeDistAsOfEpoch :: PraosEvolvingStake -> EpochNo -> Maybe StakeDist latestEvolvedStakeDistAsOfEpoch (PraosEvolvingStake x) e = fmap snd . Map.lookupMax . fst $ Map.split e x Praos specific types Praos specific types |The two VRF invocation modes , ( rho ) and TEST ( y ) . See the comment at data VRFType = NONCE | TEST deriving (Show, Eq, Ord, Generic, NoThunks) instance Serialise VRFType instance ToCBOR VRFType where This is a cheat , and at some point we probably want to decide on Serialise / ToCBOR toCBOR = encode data PraosProof c = PraosProof { praosProofRho :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosProofY :: CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType) , praosLeader :: CoreNodeId } data PraosValidationError c = PraosInvalidSlot SlotNo SlotNo | PraosUnknownCoreId CoreNodeId | PraosInvalidSig String (VerKeyKES (PraosKES c)) Natural (SigKES (PraosKES c)) | PraosInvalidCert (VerKeyVRF (PraosVRF c)) (Natural, SlotNo, VRFType) Natural (CertVRF (PraosVRF c)) | PraosInsufficientStake Double Natural deriving (Generic) We override ' showTypeOf ' to make sure to show @c@ instance PraosCrypto c => NoThunks (PraosValidationError c) where showTypeOf _ = show $ typeRep (Proxy @(PraosValidationError c)) deriving instance PraosCrypto c => Show (PraosValidationError c) deriving instance PraosCrypto c => Eq (PraosValidationError c) data BlockInfo c = BlockInfo { biSlot :: !SlotNo , biRho :: !(CertifiedVRF (PraosVRF c) (Natural, SlotNo, VRFType)) } deriving (Generic) deriving instance PraosCrypto c => Show (BlockInfo c) deriving instance PraosCrypto c => Eq (BlockInfo c) deriving instance PraosCrypto c => NoThunks (BlockInfo c) Protocol proper Protocol proper | An uninhabited type representing the Praos protocol . data Praos c data PraosParams = PraosParams { praosLeaderF :: !Double ^ f , the active slots coefficient , defined in 3.3 in the Praos paper . , praosSecurityParam :: !SecurityParam , praosSlotsPerEpoch :: !Word64 ^ R , slots in each epoch , defined in section 3 in the Praos paper . } deriving (Generic, NoThunks) MockPraos protocol . data instance ConsensusConfig (Praos c) = PraosConfig { praosParams :: !PraosParams , praosInitialEta :: !Natural , praosInitialStake :: !StakeDist , praosEvolvingStake :: !PraosEvolvingStake , praosSignKeyVRF :: !(SignKeyVRF (PraosVRF c)) , praosVerKeys :: !(Map CoreNodeId (VerKeyKES (PraosKES c), VerKeyVRF (PraosVRF c))) } deriving (Generic) instance PraosCrypto c => NoThunks (ConsensusConfig (Praos c)) slotEpoch :: ConsensusConfig (Praos c) -> SlotNo -> EpochNo slotEpoch PraosConfig{..} s = fixedEpochInfoEpoch (EpochSize praosSlotsPerEpoch) s where PraosParams{..} = praosParams epochFirst :: ConsensusConfig (Praos c) -> EpochNo -> SlotNo epochFirst PraosConfig{..} e = fixedEpochInfoFirst (EpochSize praosSlotsPerEpoch) e where PraosParams{..} = praosParams a list of BlockInfos that allow us to look into the past . newtype PraosChainDepState c = PraosChainDepState { praosHistory :: [BlockInfo c] } deriving stock (Eq, Show) deriving newtype (NoThunks, Serialise) infosSlice :: SlotNo -> SlotNo -> [BlockInfo c] -> [BlockInfo c] infosSlice from to xs = takeWhile (\b -> biSlot b >= from) $ dropWhile (\b -> biSlot b > to) xs infosEta :: forall c. (PraosCrypto c) => ConsensusConfig (Praos c) -> [BlockInfo c] -> EpochNo -> Natural infosEta l _ 0 = praosInitialEta l infosEta l@PraosConfig{praosParams = PraosParams{..}} xs e = let e' = e - 1 eta' = infosEta l xs e' the first slot in previous epoch from = epochFirst l e' 2/3 of the slots per epoch n = div (2 * praosSlotsPerEpoch) 3 the last of the 2/3 of slots in this epoch to = SlotNo $ unSlotNo from + n the list of rhos from the first block in this epoch until the one at 2/3 of the slots . Note it is reversed , i.e. start at the oldest . rhos = reverse [biRho b | b <- infosSlice from to xs] in bytesToNatural . hashToBytes $ hashWithSerialiser @(PraosHash c) toCBOR (eta', e, rhos) | Ticking the Praos chain dep state has no effect For the real Praos implementation , ticking is crucial , as it determines the data instance Ticked (PraosChainDepState c) = TickedPraosChainDepState { tickedPraosLedgerView :: Ticked (LedgerView (Praos c)) , untickedPraosChainDepState :: PraosChainDepState c } instance PraosCrypto c => ConsensusProtocol (Praos c) where protocolSecurityParam = praosSecurityParam . praosParams type LedgerView (Praos c) = () type IsLeader (Praos c) = PraosProof c type ValidationErr (Praos c) = PraosValidationError c type ValidateView (Praos c) = PraosValidateView c type ChainDepState (Praos c) = PraosChainDepState c type CanBeLeader (Praos c) = CoreNodeId checkIsLeader cfg@PraosConfig{..} nid slot (TickedPraosChainDepState _u cds) = See Figure 4 of the Praos paper . if fromIntegral (getOutputVRFNatural (certifiedOutput y)) < t then Just PraosProof { praosProofRho = rho , praosProofY = y , praosLeader = nid } else Nothing where (rho', y', t) = rhoYT cfg (praosHistory cds) slot nid rho = evalCertified () rho' praosSignKeyVRF y = evalCertified () y' praosSignKeyVRF tickChainDepState _ lv _ = TickedPraosChainDepState lv updateChainDepState cfg@PraosConfig{..} (PraosValidateView PraosFields{..} toSign) slot (TickedPraosChainDepState TickedTrivial cds) = do let PraosExtraFields {..} = praosExtraFields nid = praosCreator case praosHistory cds of (c : _) | biSlot c >= slot -> throwError $ PraosInvalidSlot slot (biSlot c) _ -> return () (vkKES, vkVRF) <- case Map.lookup nid praosVerKeys of Nothing -> throwError $ PraosUnknownCoreId nid Just vks -> return vks case verifySignedKES () vkKES (fromIntegral $ unSlotNo slot) toSign praosSignature of Right () -> return () Left err -> throwError $ PraosInvalidSig err vkKES (fromIntegral $ unSlotNo slot) (getSig praosSignature) let (rho', y', t) = rhoYT cfg (praosHistory cds) slot nid unless (verifyCertified () vkVRF rho' praosRho) $ throwError $ PraosInvalidCert vkVRF rho' (getOutputVRFNatural (certifiedOutput praosRho)) (certifiedProof praosRho) unless (verifyCertified () vkVRF y' praosY) $ throwError $ PraosInvalidCert vkVRF y' (getOutputVRFNatural (certifiedOutput praosY)) (certifiedProof praosY) unless (fromIntegral (getOutputVRFNatural (certifiedOutput praosY)) < t) $ throwError $ PraosInsufficientStake t $ getOutputVRFNatural (certifiedOutput praosY) let !bi = BlockInfo { biSlot = slot , biRho = praosRho } return $ PraosChainDepState $ bi : praosHistory cds reupdateChainDepState _ (PraosValidateView PraosFields{..} _) slot (TickedPraosChainDepState TickedTrivial cds) = let PraosExtraFields{..} = praosExtraFields !bi = BlockInfo { biSlot = slot , biRho = praosRho } in PraosChainDepState $ bi : praosHistory cds slⱼ considering its relative stake αᵢ. phi :: ConsensusConfig (Praos c) -> Rational -> Double phi PraosConfig{..} alpha = 1 - (1 - praosLeaderF) ** fromRational alpha where PraosParams{..} = praosParams | Compute Tᵢ for a given stakeholder @n@ at a @SlotNo@. Will be computed from leaderThreshold :: forall c. PraosCrypto c => ConsensusConfig (Praos c) -> [BlockInfo c] -> SlotNo -> CoreNodeId -> Double leaderThreshold config _blockInfos s n = let alpha = stakeWithDefault 0 n $ fromMaybe (praosInitialStake config) $ latestEvolvedStakeDistAsOfEpoch (praosEvolvingStake config) (slotEpoch config s) in 2^(l_VRF * 8) * ϕ_f(αᵢ ) the 8 factor converts from bytes to bits . 2 ^ (sizeHash (Proxy :: Proxy (PraosHash c)) * 8) * phi config alpha |Compute the rho , y and parameters for a given slot . rhoYT :: PraosCrypto c => ConsensusConfig (Praos c) -> [BlockInfo c] -> SlotNo -> CoreNodeId -> ( (Natural, SlotNo, VRFType) , (Natural, SlotNo, VRFType) , Double ) rhoYT st xs s nid = let e = slotEpoch st s eta = infosEta st xs e rho = (eta, s, NONCE) y = (eta, s, TEST) t = leaderThreshold st xs s nid in (rho, y, t) class ( KESAlgorithm (PraosKES c) , VRFAlgorithm (PraosVRF c) , HashAlgorithm (PraosHash c) , Typeable c , Typeable (PraosVRF c) , Condense (SigKES (PraosKES c)) , Cardano.Crypto.VRF.Class.Signable (PraosVRF c) (Natural, SlotNo, VRFType) , ContextKES (PraosKES c) ~ () , ContextVRF (PraosVRF c) ~ () ) => PraosCrypto (c :: Type) where type family PraosKES c :: Type type family PraosVRF c :: Type type family PraosHash c :: Type data PraosStandardCrypto data PraosMockCrypto instance PraosCrypto PraosStandardCrypto where type PraosKES PraosStandardCrypto = SimpleKES Ed448DSIGN 1000 type PraosVRF PraosStandardCrypto = SimpleVRF type PraosHash PraosStandardCrypto = SHA256 instance PraosCrypto PraosMockCrypto where type PraosKES PraosMockCrypto = MockKES 10000 type PraosVRF PraosMockCrypto = MockVRF type PraosHash PraosMockCrypto = SHA256 Condense instance PraosCrypto c => Condense (PraosFields c toSign) where condense PraosFields{..} = condense praosSignature Serialisation Serialisation instance PraosCrypto c => Serialise (BlockInfo c) where encode BlockInfo {..} = mconcat [ encodeListLen 2 , encode biSlot , toCBOR biRho ] decode = do decodeListLenOf 2 biSlot <- decode biRho <- fromCBOR return BlockInfo {..} instance SignableRepresentation (Natural, SlotNo, VRFType) where getSignableRepresentation = serialize' . toCBOR
b67bb3b301067e0ca8abdeba146a8d662c8c9ebc896c317d9fd5b03aa04e400a
camllight/camllight
bubble.ml
#open "animation";; let sort gc = let ordered = ref true in let rec sweep i = if i+1 >= vect_length gc.array then if !ordered then Finished else begin ordered := false; sweep 0 end else Pause(fun () -> if gc.array.(i+1) < gc.array.(i) then begin exchange gc i (i+1); ordered := false end; sweep(i+1)) in sweep 0 ;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/examples/showsort/bubble.ml
ocaml
#open "animation";; let sort gc = let ordered = ref true in let rec sweep i = if i+1 >= vect_length gc.array then if !ordered then Finished else begin ordered := false; sweep 0 end else Pause(fun () -> if gc.array.(i+1) < gc.array.(i) then begin exchange gc i (i+1); ordered := false end; sweep(i+1)) in sweep 0 ;;
31a8bef20aed5a7dc48b68a9fe4969b872ee40d1130c1932e6ca996828bb9291
wilkerlucio/pathom
project.clj
(defproject com.wsscode/pathom "2.4.0" :description "A Clojure library designed to provide a collection of helper functions to support Clojure(script) graph parsers using\nom.next graph syntax." :url "" :license {:name "MIT" :url ""} :source-paths ["src"] :dependencies [[camel-snake-kebab "0.4.0"] [com.wsscode/async "2021.01.14"] [com.wsscode/spec-inspec "1.0.0-alpha2"] [edn-query-language/eql "1.0.0"] [org.clojure/data.json "0.2.6"] [com.cognitect/transit-clj "1.0.324" :scope "test"] [com.cognitect/transit-cljs "0.8.256" :scope "test"] [com.fulcrologic/guardrails "0.0.12"] ; provided [org.clojure/test.check "1.0.0" :scope "provided"] [cheshire/cheshire "5.8.1" :scope "provided"] [clj-http "3.8.0" :scope "provided"] [fulcrologic/fulcro "2.6.0" :scope "provided"] [org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/clojurescript "1.9.946" :scope "provided"]] :plugins [[lein-cljsbuild "1.1.7"]] :cljsbuild {:builds [{:id "sanity" :source-paths ["src"] :compiler {:optimizations :whitespace :verbose true :main com.wsscode.pathom.connect}}]} :jar-exclusions [#"src-docs/.*" #"docs/.+" #"node-modules/.+"] :deploy-repositories [["clojars" {:url "/" :creds :gpg :checksum :ignore}] ["releases" :clojars] ["snapshots" :clojars]] :aliases {"pre-release" [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "v"]] "post-release" [["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]]} :profiles {:dev {:source-paths ["src" "src-docs" "workspaces/src"] :dependencies [[criterium "0.4.4"] [nubank/workspaces "1.0.0-preview7"] [com.cognitect/transit-clj "0.8.313"] [com.cognitect/transit-cljs "0.8.256"]]}})
null
https://raw.githubusercontent.com/wilkerlucio/pathom/4ec25055d3d156241e9174d68ec438c93c971b9b/project.clj
clojure
provided
(defproject com.wsscode/pathom "2.4.0" :description "A Clojure library designed to provide a collection of helper functions to support Clojure(script) graph parsers using\nom.next graph syntax." :url "" :license {:name "MIT" :url ""} :source-paths ["src"] :dependencies [[camel-snake-kebab "0.4.0"] [com.wsscode/async "2021.01.14"] [com.wsscode/spec-inspec "1.0.0-alpha2"] [edn-query-language/eql "1.0.0"] [org.clojure/data.json "0.2.6"] [com.cognitect/transit-clj "1.0.324" :scope "test"] [com.cognitect/transit-cljs "0.8.256" :scope "test"] [com.fulcrologic/guardrails "0.0.12"] [org.clojure/test.check "1.0.0" :scope "provided"] [cheshire/cheshire "5.8.1" :scope "provided"] [clj-http "3.8.0" :scope "provided"] [fulcrologic/fulcro "2.6.0" :scope "provided"] [org.clojure/clojure "1.10.0" :scope "provided"] [org.clojure/clojurescript "1.9.946" :scope "provided"]] :plugins [[lein-cljsbuild "1.1.7"]] :cljsbuild {:builds [{:id "sanity" :source-paths ["src"] :compiler {:optimizations :whitespace :verbose true :main com.wsscode.pathom.connect}}]} :jar-exclusions [#"src-docs/.*" #"docs/.+" #"node-modules/.+"] :deploy-repositories [["clojars" {:url "/" :creds :gpg :checksum :ignore}] ["releases" :clojars] ["snapshots" :clojars]] :aliases {"pre-release" [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "v"]] "post-release" [["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]]} :profiles {:dev {:source-paths ["src" "src-docs" "workspaces/src"] :dependencies [[criterium "0.4.4"] [nubank/workspaces "1.0.0-preview7"] [com.cognitect/transit-clj "0.8.313"] [com.cognitect/transit-cljs "0.8.256"]]}})
489b1a19c8535339dd43c03246ea1020b57e0e70bf7e37121085429dbb62359f
ocsigen/ojwidgets
ojw_mobile_tools.mli
(** Various tools for mobiles. *) (** {3 Enable or disable mobile features} *) val disable_zoom : unit -> Dom_html.event_listener_id val hide_navigation_bar : unit -> unit
null
https://raw.githubusercontent.com/ocsigen/ojwidgets/4be2233980bdd1cae187c749bd27ddbfff389880/src/ojw_mobile_tools.mli
ocaml
* Various tools for mobiles. * {3 Enable or disable mobile features}
val disable_zoom : unit -> Dom_html.event_listener_id val hide_navigation_bar : unit -> unit
43b6d0eb563722d4a8fdb118b8100258c66524ec6c4d17185289984d58f5a0fa
jafingerhut/clojure-benchmarks
fasta.clj-8.clj
The Computer Language Benchmarks Game ;; / contributed by (ns fasta (:gen-class)) (set! *warn-on-reflection* true) ;; Handle slight difference in function name between Clojure 1.2.0 and ;; 1.3.0-alpha*. (defmacro my-unchecked-inc-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-inc ~@args) `(unchecked-inc-int ~@args))) (defmacro my-unchecked-add-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-add ~@args) `(unchecked-add-int ~@args))) (defmacro my-unchecked-multiply-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-multiply ~@args) `(unchecked-multiply-int ~@args))) (defmacro my-unchecked-remainder-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-remainder ~@args) `(unchecked-remainder-int ~@args))) (defn make-repeat-fasta [#^java.io.BufferedOutputStream ostream line-length id desc s n] (let [descstr (str ">" id " " desc "\n")] (.write ostream (.getBytes descstr) 0 (count descstr))) (let [s-len (int (count s)) line-length (int line-length) line-length+1 (int (inc line-length)) min-buf-len (int (+ s-len line-length)) repeat-count (int (inc (quot min-buf-len s-len))) buf (apply str (repeat repeat-count s)) Precompute all byte arrays that we might want to write , one ;; at each possible offset in the string s to be repeated. line-strings (vec (map (fn [i] (.getBytes (str (subs buf i (+ i line-length)) "\n"))) (range 0 s-len))) num-full-lines (int (quot n line-length))] (loop [j (int 0) s-offset (int 0)] (if (== j num-full-lines) ;; Write out the left over part of length n, if any. (let [remaining (int (rem n line-length))] (when (not= 0 remaining) (.write ostream (.getBytes (str (subs buf s-offset (+ s-offset remaining)) "\n")) 0 (inc remaining)))) (do (.write ostream #^bytes (line-strings s-offset) 0 line-length+1) (recur (inc j) (int (my-unchecked-remainder-int (my-unchecked-add-int s-offset line-length) s-len)))))))) (definterface IPRNG (gen_random_BANG_ [^double max-val])) (deftype PRNG [^{:unsynchronized-mutable true :tag int} rand-state] IPRNG (gen-random! [this max-val] (let [IM (int 139968) IM-double (double 139968.0) IA (int 3877) IC (int 29573) max (double max-val) last-state (int rand-state) next-state (int (my-unchecked-remainder-int (my-unchecked-add-int (my-unchecked-multiply-int last-state IA) IC) IM)) next-state-double (double next-state)] (set! rand-state next-state) (/ (* max next-state-double) IM-double)))) (defmacro fill-random! [#^bytes gene-bytes #^doubles gene-cdf n #^bytes buf my-prng] `(let [double-one# (double 1.0)] (dotimes [i# ~n] (let [x# (double (.gen-random! ~my-prng double-one#)) ;; In my performance testing, I found linear search to ;; be a little faster than binary search. The arrays ;; being searched are small. b# (byte (loop [j# (int 0)] (if (< x# (aget ~gene-cdf j#)) (aget ~gene-bytes j#) (recur (my-unchecked-inc-int j#)))))] (aset ~buf i# b#))))) (defn make-random-fasta [#^java.io.BufferedOutputStream ostream line-length id desc n #^bytes gene-bytes #^doubles gene-cdf #^PRNG my-prng] (let [descstr (str ">" id " " desc "\n")] (.write ostream (.getBytes descstr))) (let [line-length (int line-length) len-with-newline (int (inc line-length)) num-full-lines (int (quot n line-length)) line-buf (byte-array len-with-newline)] (aset line-buf line-length (byte (int \newline))) (dotimes [i num-full-lines] (fill-random! gene-bytes gene-cdf line-length line-buf my-prng) (.write ostream line-buf (int 0) len-with-newline)) (let [remaining-len (int (rem n line-length))] (when (not= 0 remaining-len) (fill-random! gene-bytes gene-cdf remaining-len line-buf my-prng) (.write ostream line-buf 0 remaining-len) (.write ostream (int \newline))))) my-prng) (def alu (str "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA")) (def iub [[\a 0.27] [\c 0.12] [\g 0.12] [\t 0.27] [\B 0.02] [\D 0.02] [\H 0.02] [\K 0.02] [\M 0.02] [\N 0.02] [\R 0.02] [\S 0.02] [\V 0.02] [\W 0.02] [\Y 0.02]]) (def homosapiens [[\a 0.3029549426680] [\c 0.1979883004921] [\g 0.1975473066391] [\t 0.3015094502008]]) (defn prefix-sums-helper [x coll] (lazy-seq (when-let [s (seq coll)] (let [sum (+ x (first s))] (cons sum (prefix-sums-helper sum (rest s))))))) (defn prefix-sums [coll] (prefix-sums-helper 0 coll)) (defn make-genelist [pdf-map] (let [n (count pdf-map) bytes (byte-array n (map (fn [pair] (byte (int (first pair)))) pdf-map)) cdf (double-array n (prefix-sums (map #(nth % 1) pdf-map)))] [bytes cdf])) (defn -main [& args] (let [n (if (and (>= (count args) 1) (re-matches #"^\d+$" (nth args 0))) (. Integer valueOf (nth args 0) 10)) line-length 60 ostream (java.io.BufferedOutputStream. System/out) [iub-bytes iub-cdf] (make-genelist iub) [homosapiens-bytes homosapiens-cdf] (make-genelist homosapiens) my-prng (PRNG. (int 42))] (make-repeat-fasta ostream line-length "ONE" "Homo sapiens alu" alu (* 2 n)) (let [my-prng2 (make-random-fasta ostream line-length "TWO" "IUB ambiguity codes" (* 3 n) iub-bytes iub-cdf my-prng)] (make-random-fasta ostream line-length "THREE" "Homo sapiens frequency" (* 5 n) homosapiens-bytes homosapiens-cdf my-prng2)) (.flush ostream)))
null
https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/fasta/fasta.clj-8.clj
clojure
/ Handle slight difference in function name between Clojure 1.2.0 and 1.3.0-alpha*. at each possible offset in the string s to be repeated. Write out the left over part of length n, if any. In my performance testing, I found linear search to be a little faster than binary search. The arrays being searched are small.
The Computer Language Benchmarks Game contributed by (ns fasta (:gen-class)) (set! *warn-on-reflection* true) (defmacro my-unchecked-inc-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-inc ~@args) `(unchecked-inc-int ~@args))) (defmacro my-unchecked-add-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-add ~@args) `(unchecked-add-int ~@args))) (defmacro my-unchecked-multiply-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-multiply ~@args) `(unchecked-multiply-int ~@args))) (defmacro my-unchecked-remainder-int [& args] (if (and (== (*clojure-version* :major) 1) (== (*clojure-version* :minor) 2)) `(unchecked-remainder ~@args) `(unchecked-remainder-int ~@args))) (defn make-repeat-fasta [#^java.io.BufferedOutputStream ostream line-length id desc s n] (let [descstr (str ">" id " " desc "\n")] (.write ostream (.getBytes descstr) 0 (count descstr))) (let [s-len (int (count s)) line-length (int line-length) line-length+1 (int (inc line-length)) min-buf-len (int (+ s-len line-length)) repeat-count (int (inc (quot min-buf-len s-len))) buf (apply str (repeat repeat-count s)) Precompute all byte arrays that we might want to write , one line-strings (vec (map (fn [i] (.getBytes (str (subs buf i (+ i line-length)) "\n"))) (range 0 s-len))) num-full-lines (int (quot n line-length))] (loop [j (int 0) s-offset (int 0)] (if (== j num-full-lines) (let [remaining (int (rem n line-length))] (when (not= 0 remaining) (.write ostream (.getBytes (str (subs buf s-offset (+ s-offset remaining)) "\n")) 0 (inc remaining)))) (do (.write ostream #^bytes (line-strings s-offset) 0 line-length+1) (recur (inc j) (int (my-unchecked-remainder-int (my-unchecked-add-int s-offset line-length) s-len)))))))) (definterface IPRNG (gen_random_BANG_ [^double max-val])) (deftype PRNG [^{:unsynchronized-mutable true :tag int} rand-state] IPRNG (gen-random! [this max-val] (let [IM (int 139968) IM-double (double 139968.0) IA (int 3877) IC (int 29573) max (double max-val) last-state (int rand-state) next-state (int (my-unchecked-remainder-int (my-unchecked-add-int (my-unchecked-multiply-int last-state IA) IC) IM)) next-state-double (double next-state)] (set! rand-state next-state) (/ (* max next-state-double) IM-double)))) (defmacro fill-random! [#^bytes gene-bytes #^doubles gene-cdf n #^bytes buf my-prng] `(let [double-one# (double 1.0)] (dotimes [i# ~n] (let [x# (double (.gen-random! ~my-prng double-one#)) b# (byte (loop [j# (int 0)] (if (< x# (aget ~gene-cdf j#)) (aget ~gene-bytes j#) (recur (my-unchecked-inc-int j#)))))] (aset ~buf i# b#))))) (defn make-random-fasta [#^java.io.BufferedOutputStream ostream line-length id desc n #^bytes gene-bytes #^doubles gene-cdf #^PRNG my-prng] (let [descstr (str ">" id " " desc "\n")] (.write ostream (.getBytes descstr))) (let [line-length (int line-length) len-with-newline (int (inc line-length)) num-full-lines (int (quot n line-length)) line-buf (byte-array len-with-newline)] (aset line-buf line-length (byte (int \newline))) (dotimes [i num-full-lines] (fill-random! gene-bytes gene-cdf line-length line-buf my-prng) (.write ostream line-buf (int 0) len-with-newline)) (let [remaining-len (int (rem n line-length))] (when (not= 0 remaining-len) (fill-random! gene-bytes gene-cdf remaining-len line-buf my-prng) (.write ostream line-buf 0 remaining-len) (.write ostream (int \newline))))) my-prng) (def alu (str "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA")) (def iub [[\a 0.27] [\c 0.12] [\g 0.12] [\t 0.27] [\B 0.02] [\D 0.02] [\H 0.02] [\K 0.02] [\M 0.02] [\N 0.02] [\R 0.02] [\S 0.02] [\V 0.02] [\W 0.02] [\Y 0.02]]) (def homosapiens [[\a 0.3029549426680] [\c 0.1979883004921] [\g 0.1975473066391] [\t 0.3015094502008]]) (defn prefix-sums-helper [x coll] (lazy-seq (when-let [s (seq coll)] (let [sum (+ x (first s))] (cons sum (prefix-sums-helper sum (rest s))))))) (defn prefix-sums [coll] (prefix-sums-helper 0 coll)) (defn make-genelist [pdf-map] (let [n (count pdf-map) bytes (byte-array n (map (fn [pair] (byte (int (first pair)))) pdf-map)) cdf (double-array n (prefix-sums (map #(nth % 1) pdf-map)))] [bytes cdf])) (defn -main [& args] (let [n (if (and (>= (count args) 1) (re-matches #"^\d+$" (nth args 0))) (. Integer valueOf (nth args 0) 10)) line-length 60 ostream (java.io.BufferedOutputStream. System/out) [iub-bytes iub-cdf] (make-genelist iub) [homosapiens-bytes homosapiens-cdf] (make-genelist homosapiens) my-prng (PRNG. (int 42))] (make-repeat-fasta ostream line-length "ONE" "Homo sapiens alu" alu (* 2 n)) (let [my-prng2 (make-random-fasta ostream line-length "TWO" "IUB ambiguity codes" (* 3 n) iub-bytes iub-cdf my-prng)] (make-random-fasta ostream line-length "THREE" "Homo sapiens frequency" (* 5 n) homosapiens-bytes homosapiens-cdf my-prng2)) (.flush ostream)))
fc020b664bb0e3c33a6dbd10bd46481e220e6b5c8e30ecbc7f8d436520392060
abakst/Brisk
spawn00.hs
# LANGUAGE ScopedTypeVariables # {-# OPTIONS_GHC -fplugin Brisk.Plugin #-} # OPTIONS_GHC -fplugin - opt Brisk . Plugin : main # module Scratch where import Control.Distributed.Process main :: Process ProcessId main = do p <- spawnLocal $ do p <- expect send p (0 :: Int) send p () expect :: Process ProcessId main
null
https://raw.githubusercontent.com/abakst/Brisk/3e4ce790a742d3e3b786dba45d36f715ea0e61ef/examples/spawn00.hs
haskell
# OPTIONS_GHC -fplugin Brisk.Plugin #
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fplugin - opt Brisk . Plugin : main # module Scratch where import Control.Distributed.Process main :: Process ProcessId main = do p <- spawnLocal $ do p <- expect send p (0 :: Int) send p () expect :: Process ProcessId main
f5bbb338e6af7b31d5daad203dd9234c90f199990d118ecdef3a1f460a5505f4
derekmcloughlin/pearls
chap13b.hs
import Data.List import System.Environment (getArgs) transform :: Ord a => [a] -> ([a], Int) transform xs = (map last xss, position xs xss) where xss = sort (rots xs) position :: Eq a => a -> [a] -> Int position xs xss = length (takeWhile (/= xs) xss) rots :: [a] -> [[a]] rots xs = take (length xs) (iterate lrot xs) where lrot :: [a] -> [a] lrot [] = [] lrot (y:ys) = ys ++ [y] takeCols :: Int -> [[a]] -> [[a]] takeCols j = map (take j) recreate :: Ord a => Int -> [a] -> [[a]] recreate 0 = map (const []) recreate j = hdsort . consCol . fork (id, recreate (j - 1)) hdsort :: Ord a => [[a]] -> [[a]] hdsort = sortBy cmp where cmp (x:xs) (y:ys) = compare x y consCol :: ([a], [[a]]) -> [[a]] consCol (xs, xss) = zipWith (:) xs xss fork :: (a -> b, a -> c) -> a -> (b, c) fork (f, g) x = (f x, g x) Note : in the book , it does n't mention that the first argument to the first -- call of `recreate` needs to be the length of the transformed string. untransform :: Ord a => ([a], Int) -> [a] untransform (ys, k) = (recreate (length ys) ys) !! k main :: IO () main = do args <- getArgs hContents <- readFile (head args) let result = untransform $ transform hContents putStrLn $ if result == hContents then "matched" else "NOT MATCHED"
null
https://raw.githubusercontent.com/derekmcloughlin/pearls/42bc6ea0fecc105386a8b75789f563d44e05b772/chap13/chap13b.hs
haskell
call of `recreate` needs to be the length of the transformed string.
import Data.List import System.Environment (getArgs) transform :: Ord a => [a] -> ([a], Int) transform xs = (map last xss, position xs xss) where xss = sort (rots xs) position :: Eq a => a -> [a] -> Int position xs xss = length (takeWhile (/= xs) xss) rots :: [a] -> [[a]] rots xs = take (length xs) (iterate lrot xs) where lrot :: [a] -> [a] lrot [] = [] lrot (y:ys) = ys ++ [y] takeCols :: Int -> [[a]] -> [[a]] takeCols j = map (take j) recreate :: Ord a => Int -> [a] -> [[a]] recreate 0 = map (const []) recreate j = hdsort . consCol . fork (id, recreate (j - 1)) hdsort :: Ord a => [[a]] -> [[a]] hdsort = sortBy cmp where cmp (x:xs) (y:ys) = compare x y consCol :: ([a], [[a]]) -> [[a]] consCol (xs, xss) = zipWith (:) xs xss fork :: (a -> b, a -> c) -> a -> (b, c) fork (f, g) x = (f x, g x) Note : in the book , it does n't mention that the first argument to the first untransform :: Ord a => ([a], Int) -> [a] untransform (ys, k) = (recreate (length ys) ys) !! k main :: IO () main = do args <- getArgs hContents <- readFile (head args) let result = untransform $ transform hContents putStrLn $ if result == hContents then "matched" else "NOT MATCHED"
b672290aeddbb25d3a45989a85775600f3c104359260f23183051c121831154d
patrikja/AFPcourse
Shallow.hs
module DSL.Shallow where | : : Double| | = , Point -- | = Vec| | : : , rot -- | :: Angle -> Point -> Point| ) empty :: Shape disc :: Shape -- disc with radius |1| around the origin square :: Shape -- square between |(0,0)| and |(1,1)| translate :: Vec -> Shape -> Shape -- shift the shape along a vector scale :: Vec -> Shape -> Shape -- magnify the shape by a vector rotate :: Angle -> Shape -> Shape -- rotate the shape by an angle (around the origin) union :: Shape -> Shape -> Shape intersect :: Shape -> Shape -> Shape difference :: Shape -> Shape -> Shape inside :: Point -> Shape -> Bool -- run function: is the point inside the shape? -- Shallow = close to the semantics, far from the syntax = almost the type of the run function newtype Shape = Shape {runShape :: Point -> Bool} inside = flip runShape empty = Shape (\p -> False) disc = Shape (\p -> norm p <= 1) square = Shape (\p -> ordered [0, vecX p, 1] && ordered [0, vecY p, 1]) translate v s = Shape (\p -> inside (sub p v) s) scale v s = Shape (\p -> inside (divide p v) s) rotate a s = Shape (\p -> inside (rot (-a) p) s) union x y = Shape (\p -> inside p x || inside p y) intersect x y = Shape (\p -> inside p x && inside p y) difference x y = Shape (\p -> inside p x && not (inside p y)) -- Helper functions: norm :: Vec -> Double norm p = sqrt ((vecX p)^2 + (vecY p)^2) ordered :: Ord a => [a] -> Bool ordered (x:y:ys) = x <= y && ordered (y:ys) ordered _ = True
null
https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/exam/2012-08/DSL/Shallow.hs
haskell
| = Vec| | :: Angle -> Point -> Point| disc with radius |1| around the origin square between |(0,0)| and |(1,1)| shift the shape along a vector magnify the shape by a vector rotate the shape by an angle (around the origin) run function: is the point inside the shape? Shallow = close to the semantics, far from the syntax = almost the type of the run function Helper functions:
module DSL.Shallow where | : : Double| | = | : : ) empty :: Shape union :: Shape -> Shape -> Shape intersect :: Shape -> Shape -> Shape difference :: Shape -> Shape -> Shape newtype Shape = Shape {runShape :: Point -> Bool} inside = flip runShape empty = Shape (\p -> False) disc = Shape (\p -> norm p <= 1) square = Shape (\p -> ordered [0, vecX p, 1] && ordered [0, vecY p, 1]) translate v s = Shape (\p -> inside (sub p v) s) scale v s = Shape (\p -> inside (divide p v) s) rotate a s = Shape (\p -> inside (rot (-a) p) s) union x y = Shape (\p -> inside p x || inside p y) intersect x y = Shape (\p -> inside p x && inside p y) difference x y = Shape (\p -> inside p x && not (inside p y)) norm :: Vec -> Double norm p = sqrt ((vecX p)^2 + (vecY p)^2) ordered :: Ord a => [a] -> Bool ordered (x:y:ys) = x <= y && ordered (y:ys) ordered _ = True
3da60462403788c4614b363e9041b4bbf0f8927042248dc5194fbc911b511f6c
Zulu-Inuoe/winutil
moving-a-window.lisp
(defpackage #:com.inuoe.winutil.examples.moving-a-window (:use #:cl) (:import-from #:win32) (:import-from #:winutil) (:export #:main)) (in-package #:com.inuoe.winutil.examples.moving-a-window) (defclass moving-a-window (winutil:window) ((x-label :type winutil:hwnd-wrapper :accessor x-label) (y-label :type winutil:hwnd-wrapper :accessor y-label)) (:default-initargs :class-name "Moving" :name "Moving" :style (logior win32:+ws-overlappedwindow+ win32:+ws-visible+) :background (win32:get-sys-color-brush win32:+color-3dface+) :x 150 :y 150 :width 250 :height 180)) (defun create-labels (window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "x: " :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 1 :x 10 :y 10 :width 25 :height 25) (setf (x-label window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "150" :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 2 :x 40 :y 10 :width 55 :height 25)) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "y: " :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 3 :x 10 :y 30 :width 25 :height 25) (setf (y-label window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "150" :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 4 :x 40 :y 30 :width 55 :height 25))) (defmethod winutil:call-wndproc ((window moving-a-window) msg wparam lparam) (case msg (#.win32:+wm-create+ (create-labels window)) (#.win32:+wm-move+ (multiple-value-bind (x y) (winutil:hwnd-pos window) (setf (winutil:hwnd-text (x-label window)) (format nil "~D" x) (winutil:hwnd-text (y-label window)) (format nil "~D" y)))) (#.win32:+wm-destroy+ (win32:post-quit-message 0))) (call-next-method)) (defun main (&optional argv) (declare (ignore argv)) (let ((window (make-instance 'moving-a-window))) (when (find-package '#:slynk) (win32:show-window (winutil:hwnd window) win32:+sw-show+)) (winutil:message-pump)))
null
https://raw.githubusercontent.com/Zulu-Inuoe/winutil/85f9b8df95d772a94a07addf5b0f81f7da3df4d5/examples/zetcode/moving-a-window.lisp
lisp
(defpackage #:com.inuoe.winutil.examples.moving-a-window (:use #:cl) (:import-from #:win32) (:import-from #:winutil) (:export #:main)) (in-package #:com.inuoe.winutil.examples.moving-a-window) (defclass moving-a-window (winutil:window) ((x-label :type winutil:hwnd-wrapper :accessor x-label) (y-label :type winutil:hwnd-wrapper :accessor y-label)) (:default-initargs :class-name "Moving" :name "Moving" :style (logior win32:+ws-overlappedwindow+ win32:+ws-visible+) :background (win32:get-sys-color-brush win32:+color-3dface+) :x 150 :y 150 :width 250 :height 180)) (defun create-labels (window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "x: " :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 1 :x 10 :y 10 :width 25 :height 25) (setf (x-label window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "150" :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 2 :x 40 :y 10 :width 55 :height 25)) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "y: " :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 3 :x 10 :y 30 :width 25 :height 25) (setf (y-label window) (make-instance 'winutil:hwnd-wrapper :wndclass "static" :name "150" :style (logior win32:+ws-child+ win32:+ws-visible+) :parent window :menu 4 :x 40 :y 30 :width 55 :height 25))) (defmethod winutil:call-wndproc ((window moving-a-window) msg wparam lparam) (case msg (#.win32:+wm-create+ (create-labels window)) (#.win32:+wm-move+ (multiple-value-bind (x y) (winutil:hwnd-pos window) (setf (winutil:hwnd-text (x-label window)) (format nil "~D" x) (winutil:hwnd-text (y-label window)) (format nil "~D" y)))) (#.win32:+wm-destroy+ (win32:post-quit-message 0))) (call-next-method)) (defun main (&optional argv) (declare (ignore argv)) (let ((window (make-instance 'moving-a-window))) (when (find-package '#:slynk) (win32:show-window (winutil:hwnd window) win32:+sw-show+)) (winutil:message-pump)))
2488816a77f42d9781b2d5e3bb5aa3b60b1b661c45ecb8a47993b276bbb9700b
juspay/atlas
Fulfillment.hs
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Core . OnStatus . Fulfillment Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Core.OnStatus.Fulfillment Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Core.OnStatus.Fulfillment (module Reexport) where import Core.OnConfirm.Fulfillment as Reexport
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/parking-bap/src/Core/OnStatus/Fulfillment.hs
haskell
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Core . OnStatus . Fulfillment Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Core.OnStatus.Fulfillment Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Core.OnStatus.Fulfillment (module Reexport) where import Core.OnConfirm.Fulfillment as Reexport
7cb924a1240273ebf6d2f74373b925b7d437521f08271dbb973be3278f84bab7
joelburget/lvca
Repl.ml
open Base open Brr open Brr_note open Lvca_syntax open Lvca_util open Note let buf = "input" module Evaluation = struct module Lang = [%lvca.abstract_syntax_module {| string : * nominal : * evaluation := Evaluation(string; nominal); |} , { string = "Primitive.String"; nominal = "Nominal.Term" }] include Lang.Evaluation (* TODO: generate this *) let equivalent ~info_eq (Evaluation (i1, s1, n1)) (Evaluation (i2, s2, n2)) = info_eq i1 i2 && Primitive.String.equivalent ~info_eq s1 s2 && Nominal.Term.equivalent ~info_eq n1 n2 ;; let ( = ) = equivalent ~info_eq:Provenance.( = ) end module Model = struct type t = { evaluations : Evaluation.t list ; error_msg : string option } let initial_model = { evaluations = []; error_msg = None } let ( = ) x y = List.equal Evaluation.( = ) x.evaluations y.evaluations && Option.equal String.( = ) x.error_msg y.error_msg ;; end module Action = struct type t = | Evaluate of string | DeleteRow of int end module Controller = struct let update (action : Action.t) Model.{ evaluations; error_msg } = match action with | Evaluate str -> (match Common.parse_term str with | Ok tm -> let info = Provenance.of_here [%here] in Model. { evaluations = Evaluation (info, (info, str), tm) :: evaluations ; error_msg = None } | Error msg -> { evaluations; error_msg = Some msg }) | DeleteRow i -> { evaluations = List.remove_nth evaluations i; error_msg } ;; end module View = struct open El open Prelude let row cells = El.tr ~at:[ class' "border-b" ] cells let view model_s = let input, input_event = Single_line_input.mk (S.const ~eq:String.( = ) "lam(x. x)") in let thead = row [ th ~at:(classes "w-1/2 text-left") [ txt' "input" ] ; th ~at:(classes "w-1/3 text-left") [ txt' "output" ] ; th ~at:(classes "w-1/6") [] ] in let row' row_num input_str tm = let delete_button = button ~at:(classes "inline-block p-1 border-2 border-indigo-900 rounded") [ txt' "remove" ] in let evts = Evr.on_el Ev.click (fun _evt -> Action.DeleteRow row_num) delete_button in let tree_view, _tree_selection_e = Tree_view.view_tm ~source_column:false ~range_column:false tm in let elem = row [ td ~at:(classes "py-4 pr-1") [ pre ~at:(classes "whitespace-pre-wrap break-word") [ txt' input_str ] ] ; td [ tree_view ] ; td [ delete_button ] ] in elem, evts in let tbody, tbody_evts = let never_eq _ _ = false in let eq = Tuple2.equal Common.htmls_eq never_eq in let s = model_s |> S.map ~eq (fun model -> model.Model.evaluations |> List.mapi ~f:(fun row_num (Evaluation.Evaluation (_, (_, input), parsed)) -> row' row_num input parsed) |> List.unzip) in S.Pair.fst ~eq:Common.htmls_eq s, S.Pair.snd ~eq:never_eq s in let error_msg = model_s |> S.map ~eq:Common.htmls_eq (fun model -> match model.Model.error_msg with | None -> [] | Some msg -> [ span [ txt' msg ] ]) |> mk_reactive div in let elem = div [ div ~at:[ class' "my-2" ] [ input ] ; div ~at:(classes "error my-2") [ error_msg ] ; Components.table ~classes:[ "w-full"; "mb-6" ] thead tbody ] in let actions = E.select [ input_event |> E.filter_map (function | Common.Evaluate_input str -> Some (Action.Evaluate str) | _ -> None) ; tbody_evts Select one event from a list of events |> E.swap (* Extract current signal's event *) ] in actions, elem ;; end module Stateless_view = Stateless_view.Mk (Action) (Model) (View) (Controller)
null
https://raw.githubusercontent.com/joelburget/lvca/dc1a9b2fbaed013c5d57d7fe63dd4a05062c93d5/pages/Repl.ml
ocaml
TODO: generate this Extract current signal's event
open Base open Brr open Brr_note open Lvca_syntax open Lvca_util open Note let buf = "input" module Evaluation = struct module Lang = [%lvca.abstract_syntax_module {| string : * nominal : * evaluation := Evaluation(string; nominal); |} , { string = "Primitive.String"; nominal = "Nominal.Term" }] include Lang.Evaluation let equivalent ~info_eq (Evaluation (i1, s1, n1)) (Evaluation (i2, s2, n2)) = info_eq i1 i2 && Primitive.String.equivalent ~info_eq s1 s2 && Nominal.Term.equivalent ~info_eq n1 n2 ;; let ( = ) = equivalent ~info_eq:Provenance.( = ) end module Model = struct type t = { evaluations : Evaluation.t list ; error_msg : string option } let initial_model = { evaluations = []; error_msg = None } let ( = ) x y = List.equal Evaluation.( = ) x.evaluations y.evaluations && Option.equal String.( = ) x.error_msg y.error_msg ;; end module Action = struct type t = | Evaluate of string | DeleteRow of int end module Controller = struct let update (action : Action.t) Model.{ evaluations; error_msg } = match action with | Evaluate str -> (match Common.parse_term str with | Ok tm -> let info = Provenance.of_here [%here] in Model. { evaluations = Evaluation (info, (info, str), tm) :: evaluations ; error_msg = None } | Error msg -> { evaluations; error_msg = Some msg }) | DeleteRow i -> { evaluations = List.remove_nth evaluations i; error_msg } ;; end module View = struct open El open Prelude let row cells = El.tr ~at:[ class' "border-b" ] cells let view model_s = let input, input_event = Single_line_input.mk (S.const ~eq:String.( = ) "lam(x. x)") in let thead = row [ th ~at:(classes "w-1/2 text-left") [ txt' "input" ] ; th ~at:(classes "w-1/3 text-left") [ txt' "output" ] ; th ~at:(classes "w-1/6") [] ] in let row' row_num input_str tm = let delete_button = button ~at:(classes "inline-block p-1 border-2 border-indigo-900 rounded") [ txt' "remove" ] in let evts = Evr.on_el Ev.click (fun _evt -> Action.DeleteRow row_num) delete_button in let tree_view, _tree_selection_e = Tree_view.view_tm ~source_column:false ~range_column:false tm in let elem = row [ td ~at:(classes "py-4 pr-1") [ pre ~at:(classes "whitespace-pre-wrap break-word") [ txt' input_str ] ] ; td [ tree_view ] ; td [ delete_button ] ] in elem, evts in let tbody, tbody_evts = let never_eq _ _ = false in let eq = Tuple2.equal Common.htmls_eq never_eq in let s = model_s |> S.map ~eq (fun model -> model.Model.evaluations |> List.mapi ~f:(fun row_num (Evaluation.Evaluation (_, (_, input), parsed)) -> row' row_num input parsed) |> List.unzip) in S.Pair.fst ~eq:Common.htmls_eq s, S.Pair.snd ~eq:never_eq s in let error_msg = model_s |> S.map ~eq:Common.htmls_eq (fun model -> match model.Model.error_msg with | None -> [] | Some msg -> [ span [ txt' msg ] ]) |> mk_reactive div in let elem = div [ div ~at:[ class' "my-2" ] [ input ] ; div ~at:(classes "error my-2") [ error_msg ] ; Components.table ~classes:[ "w-full"; "mb-6" ] thead tbody ] in let actions = E.select [ input_event |> E.filter_map (function | Common.Evaluate_input str -> Some (Action.Evaluate str) | _ -> None) ; tbody_evts Select one event from a list of events |> E.swap ] in actions, elem ;; end module Stateless_view = Stateless_view.Mk (Action) (Model) (View) (Controller)
36bbe0ecd985bd866b770a4bb1aeb1fa1bed40ea3295c8cadef9127c7e74460f
openweb-nl/open-bank-mark
project.clj
(defproject nl.openweb/synchronizer "0.1.0-SNAPSHOT" :plugins [[lein-modules "0.3.11"]] :dependencies [[clj-http "3.10.0" :exclusions [commons-logging]] [nl.openweb/topology :version] [org.clojure/clojure :version] [org.clojure/data.json :version] [org.slf4j/jcl-over-slf4j "1.7.26"]] :main nl.openweb.synchronizer.core :profiles {:uberjar {:omit-source true :aot :all :uberjar-name "syn-docker.jar"}})
null
https://raw.githubusercontent.com/openweb-nl/open-bank-mark/786c940dafb39c36fdbcae736fe893af9c00ef17/synchronizer/project.clj
clojure
(defproject nl.openweb/synchronizer "0.1.0-SNAPSHOT" :plugins [[lein-modules "0.3.11"]] :dependencies [[clj-http "3.10.0" :exclusions [commons-logging]] [nl.openweb/topology :version] [org.clojure/clojure :version] [org.clojure/data.json :version] [org.slf4j/jcl-over-slf4j "1.7.26"]] :main nl.openweb.synchronizer.core :profiles {:uberjar {:omit-source true :aot :all :uberjar-name "syn-docker.jar"}})
44aa30b4d974d1366207f61e35fd4cc768bbfd56a22e217c026cf6568cdbfee5
Bogdanp/racket-gui-extra
status-bar.rkt
#lang racket/base (require (only-in mred/private/wx/common/event control-event%) (prefix-in base: racket/base) racket/class racket/list "common.rkt" "ffi.rkt" (prefix-in mred: "mred.rkt")) (provide status-bar-menu%) (import-class NSMenu NSMenuItem NSStatusBar) (define status-bar-menu% (class* mred:mred% (mred:internal-menu<%> mred:wx<%>) (init-field image) (super-make-object this) (define-values (_cocoa cocoa-menu) (with-atomic (define status-bar (tell NSStatusBar systemStatusBar)) (define-values (width _height) (send image get-size)) (define cocoa (as-objc-allocation-with-retain (tell status-bar statusItemWithLength: #:type _CGFloat width))) (tell (tell cocoa button) setImage: (send image get-cocoa)) (define cocoa-menu (as-objc-allocation (tell (tell NSMenu alloc) initWithTitle: #:type _NSString "menu"))) (tellv cocoa-menu setAutoenablesItems: #:type _BOOL #f) (tellv cocoa setMenu: cocoa-menu) (values cocoa cocoa-menu))) ;; mred ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define/public (get-mred) this) (define/public (get-proxy) this) (define/public (get-container) this) ;; container ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define items null) (define (push! item-wx) (set! items (base:append items (list item-wx)))) (define (index-of-item item-wx) (for/first ([it (in-list items)] [idx (in-naturals)] #:when (and it (eq? it item-wx))) idx)) (define (update item-wx proc) (define idx (index-of-item item-wx)) (when idx (proc idx (tell cocoa-menu itemAtIndex: #:type _NSInteger idx)))) (define/public (append-item _item _item-wx) (void)) (define/public (append-separator) (set! items (base:append items (list #f))) (tellv cocoa-menu addItem: (tell NSMenuItem separatorItem))) (define/public (append item-wx label maybe-submenu checkable?) (send item-wx set-label label) (when (is-a? maybe-submenu mred:wx-menu%) (send item-wx set-submenu maybe-submenu) (send maybe-submenu set-parent this)) (push! item-wx) (send item-wx set-parent this) (send item-wx install cocoa-menu checkable?)) (define/public (delete item-wx _item) (update item-wx (λ (idx _cocoa-item) (tellv cocoa-menu removeItemAtIndex: #:type _NSInteger idx) (set! items (base:append (take items idx) (drop items (add1 idx))))))) (define/public (enable item-wx _item on?) (update item-wx (λ (_idx cocoa-item) (tellv cocoa-item setEnabled: #:type _BOOL on?) (send item-wx set-enabled-flag (and on? #t))))) (define/public (check item-wx on?) (update item-wx (λ (_idx cocoa-item) (tellv cocoa-item setState: #:type _NSInteger (if on? 1 0)) (send item-wx set-checked (and on? #t))))) (define/public (set-label item-wx label) (update item-wx (λ (_idx cocoa-item) (define clean-label (regexp-replace #rx"&(.)" label "\\1")) (tellv cocoa-item setTitle: #:type _NSString clean-label) (send item-wx set-label clean-label)))) ;; FIXME: Need keymap support. Called before `set-label`. (define/public (swap-item-keymap _item-wx _label) (void)) ;; HACK: Act as if we are the top-level window in order to support ;; submenus. (define/public (get-top-window) this) (define/public (get-eventspace) (mred:current-eventspace)) (define/public (on-menu-command item-wx) (item-command item-wx)) ;; callbacks ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define/public (item-selected item-wx) (mred:queue-callback (λ () (item-command item-wx)))) (define/private (item-command item-wx) (define item (mred:wx->mred item-wx)) (send item command (make-object control-event% 'menu)))))
null
https://raw.githubusercontent.com/Bogdanp/racket-gui-extra/6e1d2d154427707424dcc8bbfe2115009e38d3d4/gui-extra-lib/gui/extra/private/cocoa/status-bar.rkt
racket
mred ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; container ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; FIXME: Need keymap support. Called before `set-label`. HACK: Act as if we are the top-level window in order to support submenus. callbacks ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket/base (require (only-in mred/private/wx/common/event control-event%) (prefix-in base: racket/base) racket/class racket/list "common.rkt" "ffi.rkt" (prefix-in mred: "mred.rkt")) (provide status-bar-menu%) (import-class NSMenu NSMenuItem NSStatusBar) (define status-bar-menu% (class* mred:mred% (mred:internal-menu<%> mred:wx<%>) (init-field image) (super-make-object this) (define-values (_cocoa cocoa-menu) (with-atomic (define status-bar (tell NSStatusBar systemStatusBar)) (define-values (width _height) (send image get-size)) (define cocoa (as-objc-allocation-with-retain (tell status-bar statusItemWithLength: #:type _CGFloat width))) (tell (tell cocoa button) setImage: (send image get-cocoa)) (define cocoa-menu (as-objc-allocation (tell (tell NSMenu alloc) initWithTitle: #:type _NSString "menu"))) (tellv cocoa-menu setAutoenablesItems: #:type _BOOL #f) (tellv cocoa setMenu: cocoa-menu) (values cocoa cocoa-menu))) (define/public (get-mred) this) (define/public (get-proxy) this) (define/public (get-container) this) (define items null) (define (push! item-wx) (set! items (base:append items (list item-wx)))) (define (index-of-item item-wx) (for/first ([it (in-list items)] [idx (in-naturals)] #:when (and it (eq? it item-wx))) idx)) (define (update item-wx proc) (define idx (index-of-item item-wx)) (when idx (proc idx (tell cocoa-menu itemAtIndex: #:type _NSInteger idx)))) (define/public (append-item _item _item-wx) (void)) (define/public (append-separator) (set! items (base:append items (list #f))) (tellv cocoa-menu addItem: (tell NSMenuItem separatorItem))) (define/public (append item-wx label maybe-submenu checkable?) (send item-wx set-label label) (when (is-a? maybe-submenu mred:wx-menu%) (send item-wx set-submenu maybe-submenu) (send maybe-submenu set-parent this)) (push! item-wx) (send item-wx set-parent this) (send item-wx install cocoa-menu checkable?)) (define/public (delete item-wx _item) (update item-wx (λ (idx _cocoa-item) (tellv cocoa-menu removeItemAtIndex: #:type _NSInteger idx) (set! items (base:append (take items idx) (drop items (add1 idx))))))) (define/public (enable item-wx _item on?) (update item-wx (λ (_idx cocoa-item) (tellv cocoa-item setEnabled: #:type _BOOL on?) (send item-wx set-enabled-flag (and on? #t))))) (define/public (check item-wx on?) (update item-wx (λ (_idx cocoa-item) (tellv cocoa-item setState: #:type _NSInteger (if on? 1 0)) (send item-wx set-checked (and on? #t))))) (define/public (set-label item-wx label) (update item-wx (λ (_idx cocoa-item) (define clean-label (regexp-replace #rx"&(.)" label "\\1")) (tellv cocoa-item setTitle: #:type _NSString clean-label) (send item-wx set-label clean-label)))) (define/public (swap-item-keymap _item-wx _label) (void)) (define/public (get-top-window) this) (define/public (get-eventspace) (mred:current-eventspace)) (define/public (on-menu-command item-wx) (item-command item-wx)) (define/public (item-selected item-wx) (mred:queue-callback (λ () (item-command item-wx)))) (define/private (item-command item-wx) (define item (mred:wx->mred item-wx)) (send item command (make-object control-event% 'menu)))))
19ceae36d78db636a52678b80268edcfd2670431e8555f079cf24f542037bd9b
mfoemmel/erlang-otp
dets.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(dets). %% Disk based linear hashing lookup dictionary. %% Public. -export([all/0, bchunk/2, close/1, delete/2, delete_all_objects/1, delete_object/2, first/1, foldl/3, foldr/3, from_ets/2, info/1, info/2, init_table/2, init_table/3, insert/2, insert_new/2, is_compatible_bchunk_format/2, is_dets_file/1, lookup/2, match/1, match/2, match/3, match_delete/2, match_object/1, match_object/2, match_object/3, member/2, next/2, open_file/1, open_file/2, pid2name/1, repair_continuation/2, safe_fixtable/2, select/1, select/2, select/3, select_delete/2, slot/2, sync/1, table/1, table/2, to_ets/2, traverse/2, update_counter/3]). %% Server export. -export([start/0, stop/0]). %% Internal exports. -export([istart_link/1, init/2, internal_open/3, add_user/3, internal_close/1, remove_user/2, system_continue/3, system_terminate/4, system_code_change/4]). %% Debug. -export([file_info/1, fsck/1, fsck/2, get_head_field/2, view/1, where/2, verbose/0, verbose/1 ]). %% Not documented, or not ready for publication. -export([lookup_keys/2]). -compile({inline, [{einval,2},{badarg,2},{undefined,1}, {badarg_exit,2},{lookup_reply,2}]}). -include_lib("kernel/include/file.hrl"). -include("dets.hrl"). -type object() :: tuple(). -type pattern() :: atom() | tuple(). -type tab_name() :: atom() | reference(). %%% This is the implementation of the mnesia file storage. Each (non ram - copy ) table is maintained in a corresponding .DAT file . The %%% dat file is organized as a segmented linear hashlist. The head of %%% the file with the split indicator, size etc is held in ram by the %%% server at all times. %%% The parts specific for formats up to and including 8(c ) are implemented in dets_v8.erl , parts specific for format 9 are implemented in dets_v9.erl . %% The method of hashing is the so called linear hashing algorithm %% with segments. %% %% Linear hashing: %% - n indicates next bucket to split ( initially zero ) ; %% - m is the size of the hash table - initially next = m and n = 0 %% %% - to insert: %% - hash = key mod m - if hash < n then hash = key mod 2 m %% - when the number of objects exceeds the initial size %% of the hash table, each insertion of an object %% causes bucket n to be split: %% - add a new bucket to the end of the table %% - redistribute the contents of bucket n using hash = key mod 2 m %% - increment n - if n = m then m = 2 m , n = 0 %% - to search: %% hash = key mod m if hash < n then hash = key mod 2 m %% do linear scan of the bucket %% If a file error occurs on a working dets file , update_mode is set %%% to the error tuple. When in 'error' mode, the free lists are not %%% written, and a repair is forced next time the file is opened. -record(dets_cont, { object | bindings | select | bchunk requested number of objects : default | integer ( ) > 0 bin, % small chunk not consumed, or 'eof' at end-of-file alloc, % the part of the file not yet scanned, mostly a binary tab, match_program % true | compiled_match_spec() | undefined }). -record(open_args, { file, type, keypos, repair, min_no_slots, max_no_slots, ram_file, delayed_write, auto_save, access, version, debug }). -define(PATTERN_TO_OBJECT_MATCH_SPEC(Pat), [{Pat,[],['$_']}]). -define(PATTERN_TO_BINDINGS_MATCH_SPEC(Pat), [{Pat,[],['$$']}]). -define(PATTERN_TO_TRUE_MATCH_SPEC(Pat), [{Pat,[],[true]}]). %%-define(DEBUGM(X, Y), io:format(X, Y)). -define(DEBUGM(X, Y), true). %%-define(DEBUGF(X,Y), io:format(X, Y)). -define(DEBUGF(X,Y), void). %%-define(PROFILE(C), C). -define(PROFILE(C), void). Some further debug code was added in R12B-1 ( stdlib-1.15.1 ): %%% - there is a new open_file() option 'debug'; %%% - there is a new OS environment variable 'DETS_DEBUG'; %%% - verbose(true) implies that info messages are written onto %%% the error log whenever an unsafe traversal is started. %%% The 'debug' mode (set by the open_file() option 'debug' or by os : " , " true " ) ) implies that the results of calling pwrite ( ) and pread ( ) are tested to some extent . It also %%% means a considerable overhead when it comes to RAM usage. The %%% operation of Dets is also slowed down a bit. Note that in debug %%% mode terms will be output on the error logger. %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- add_user(Pid, Tab, Args) -> req(Pid, {add_user, Tab, Args}). -spec all() -> [tab_name()]. all() -> dets_server:all(). -type cont() :: #dets_cont{}. -spec bchunk(tab_name(), 'start' | cont()) -> {cont(), binary() | tuple()} | '$end_of_table' | {'error', term()}. bchunk(Tab, start) -> badarg(treq(Tab, {bchunk_init, Tab}), [Tab, start]); bchunk(Tab, #dets_cont{bin = eof, tab = Tab}) -> '$end_of_table'; bchunk(Tab, #dets_cont{what = bchunk, tab = Tab} = State) -> badarg(treq(Tab, {bchunk, State}), [Tab, State]); bchunk(Tab, Term) -> erlang:error(badarg, [Tab, Term]). -spec close(tab_name()) -> 'ok' | {'error', term()}. close(Tab) -> case dets_server:close(Tab) of badarg -> % Should not happen. {error, not_owner}; % Backwards compatibility... Reply -> Reply end. -spec delete(tab_name(), term()) -> 'ok' | {'error', term()}. delete(Tab, Key) -> badarg(treq(Tab, {delete_key, [Key]}), [Tab, Key]). -spec delete_all_objects(tab_name()) -> 'ok' | {'error', term()}. delete_all_objects(Tab) -> case treq(Tab, delete_all_objects) of badarg -> erlang:error(badarg, [Tab]); fixed -> match_delete(Tab, '_'); Reply -> Reply end. -spec delete_object(tab_name(), object()) -> 'ok' | {'error', term()}. delete_object(Tab, O) -> badarg(treq(Tab, {delete_object, [O]}), [Tab, O]). %% Given a filename, fsck it. Debug. fsck(Fname) -> fsck(Fname, default). fsck(Fname, Version) -> catch begin {ok, Fd, FH} = read_file_header(Fname, read, false), ?DEBUGF("FileHeader: ~p~n", [FH]), case (FH#fileheader.mod):check_file_header(FH, Fd) of {error, not_closed} -> fsck(Fd, make_ref(), Fname, FH, default, default, Version); {ok, _Head, _Extra} -> fsck(Fd, make_ref(), Fname, FH, default, default, Version); Error -> Error end end. -spec first(tab_name()) -> term() | '$end_of_table'. first(Tab) -> badarg_exit(treq(Tab, first), [Tab]). -spec foldr(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}. foldr(Fun, Acc, Tab) -> foldl(Fun, Acc, Tab). -spec foldl(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}. foldl(Fun, Acc, Tab) -> Ref = make_ref(), do_traverse(Fun, Acc, Tab, Ref). -spec from_ets(tab_name(), ets:tab()) -> 'ok' | {'error', term()}. from_ets(DTab, ETab) -> ets:safe_fixtable(ETab, true), Spec = ?PATTERN_TO_OBJECT_MATCH_SPEC('_'), LC = ets:select(ETab, Spec, 100), InitFun = from_ets_fun(LC, ETab), Reply = treq(DTab, {initialize, InitFun, term, default}), ets:safe_fixtable(ETab, false), case Reply of {thrown, Thrown} -> throw(Thrown); Else -> badarg(Else, [DTab, ETab]) end. from_ets_fun(LC, ETab) -> fun(close) -> ok; (read) when LC =:= '$end_of_table' -> end_of_input; (read) -> {L, C} = LC, {L, from_ets_fun(ets:select(C), ETab)} end. info(Tab) -> case catch dets_server:get_pid(Tab) of {'EXIT', _Reason} -> undefined; Pid -> undefined(req(Pid, info)) end. info(Tab, owner) -> case catch dets_server:get_pid(Tab) of Pid when is_pid(Pid) -> Pid; _ -> undefined end; info(Tab, users) -> % undocumented case dets_server:users(Tab) of [] -> undefined; Users -> Users end; info(Tab, Tag) -> case catch dets_server:get_pid(Tab) of {'EXIT', _Reason} -> undefined; Pid -> undefined(req(Pid, {info, Tag})) end. init_table(Tab, InitFun) -> init_table(Tab, InitFun, []). init_table(Tab, InitFun, Options) when is_function(InitFun) -> case options(Options, [format, min_no_slots]) of {badarg,_} -> erlang:error(badarg, [Tab, InitFun, Options]); [Format, MinNoSlots] -> case treq(Tab, {initialize, InitFun, Format, MinNoSlots}) of {thrown, Thrown} -> throw(Thrown); Else -> badarg(Else, [Tab, InitFun, Options]) end end; init_table(Tab, InitFun, Options) -> erlang:error(badarg, [Tab, InitFun, Options]). insert(Tab, Objs) when is_list(Objs) -> badarg(treq(Tab, {insert, Objs}), [Tab, Objs]); insert(Tab, Obj) -> badarg(treq(Tab, {insert, [Obj]}), [Tab, Obj]). insert_new(Tab, Objs) when is_list(Objs) -> badarg(treq(Tab, {insert_new, Objs}), [Tab, Objs]); insert_new(Tab, Obj) -> badarg(treq(Tab, {insert_new, [Obj]}), [Tab, Obj]). internal_close(Pid) -> req(Pid, close). internal_open(Pid, Ref, Args) -> req(Pid, {internal_open, Ref, Args}). is_compatible_bchunk_format(Tab, Term) -> badarg(treq(Tab, {is_compatible_bchunk_format, Term}), [Tab, Term]). is_dets_file(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> file:close(Fd), FH#fileheader.cookie =:= ?MAGIC; {error, {tooshort, _}} -> false; {error, {not_a_dets_file, _}} -> false; Other -> Other end. lookup(Tab, Key) -> badarg(treq(Tab, {lookup_keys, [Key]}), [Tab, Key]). %% Not public. lookup_keys(Tab, Keys) -> case catch lists:usort(Keys) of UKeys when is_list(UKeys), UKeys =/= [] -> badarg(treq(Tab, {lookup_keys, UKeys}), [Tab, Keys]); _Else -> erlang:error(badarg, [Tab, Keys]) end. match(Tab, Pat) -> badarg(safe_match(Tab, Pat, bindings), [Tab, Pat]). match(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, bindings, N), [Tab, Pat, N]). match(State) when State#dets_cont.what =:= bindings -> badarg(chunk_match(State), [State]); match(Term) -> erlang:error(badarg, [Term]). -spec match_delete(tab_name(), pattern()) -> non_neg_integer() | 'ok' | {'error', term()}. match_delete(Tab, Pat) -> badarg(match_delete(Tab, Pat, delete), [Tab, Pat]). match_delete(Tab, Pat, What) -> safe_fixtable(Tab, true), case compile_match_spec(What, Pat) of {Spec, MP} -> Proc = dets_server:get_pid(Tab), R = req(Proc, {match_delete_init, MP, Spec}), do_match_delete(Tab, Proc, R, What, 0); badarg -> badarg end. do_match_delete(Tab, _Proc, {done, N1}, select, N) -> safe_fixtable(Tab, false), N + N1; do_match_delete(Tab, _Proc, {done, _N1}, _What, _N) -> safe_fixtable(Tab, false), ok; do_match_delete(Tab, Proc, {cont, State, N1}, What, N) -> do_match_delete(Tab, Proc, req(Proc, {match_delete, State}), What, N+N1); do_match_delete(Tab, _Proc, Error, _What, _N) -> safe_fixtable(Tab, false), Error. match_object(Tab, Pat) -> badarg(safe_match(Tab, Pat, object), [Tab, Pat]). match_object(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, object, N), [Tab, Pat, N]). match_object(State) when State#dets_cont.what =:= object -> badarg(chunk_match(State), [State]); match_object(Term) -> erlang:error(badarg, [Term]). member(Tab, Key) -> badarg(treq(Tab, {member, Key}), [Tab, Key]). next(Tab, Key) -> badarg_exit(treq(Tab, {next, Key}), [Tab, Key]). %% Assuming that a file already exists, open it with the %% parameters as already specified in the file itself. %% Return a ref leading to the file. open_file(File) -> case dets_server:open_file(to_list(File)) of badarg -> % Should not happen. erlang:error(dets_process_died, [File]); Reply -> einval(Reply, [File]) end. open_file(Tab, Args) when is_list(Args) -> case catch defaults(Tab, Args) of OpenArgs when is_record(OpenArgs, open_args) -> case dets_server:open_file(Tab, OpenArgs) of badarg -> % Should not happen. erlang:error(dets_process_died, [Tab, Args]); Reply -> einval(Reply, [Tab, Args]) end; _ -> erlang:error(badarg, [Tab, Args]) end; open_file(Tab, Arg) -> open_file(Tab, [Arg]). pid2name(Pid) -> dets_server:pid2name(Pid). remove_user(Pid, From) -> req(Pid, {close, From}). repair_continuation(#dets_cont{match_program = B}=Cont, MS) when is_binary(B) -> case ets:is_compiled_ms(B) of true -> Cont; false -> Cont#dets_cont{match_program = ets:match_spec_compile(MS)} end; repair_continuation(#dets_cont{}=Cont, _MS) -> Cont; repair_continuation(T, MS) -> erlang:error(badarg, [T, MS]). safe_fixtable(Tab, Bool) when Bool; not Bool -> badarg(treq(Tab, {safe_fixtable, Bool}), [Tab, Bool]); safe_fixtable(Tab, Term) -> erlang:error(badarg, [Tab, Term]). select(Tab, Pat) -> badarg(safe_match(Tab, Pat, select), [Tab, Pat]). select(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, select, N), [Tab, Pat, N]). select(State) when State#dets_cont.what =:= select -> badarg(chunk_match(State), [State]); select(Term) -> erlang:error(badarg, [Term]). select_delete(Tab, Pat) -> badarg(match_delete(Tab, Pat, select), [Tab, Pat]). slot(Tab, Slot) when is_integer(Slot), Slot >= 0 -> badarg(treq(Tab, {slot, Slot}), [Tab, Slot]); slot(Tab, Term) -> erlang:error(badarg, [Tab, Term]). start() -> dets_server:start(). stop() -> dets_server:stop(). istart_link(Server) -> {ok, proc_lib:spawn_link(dets, init, [self(), Server])}. sync(Tab) -> badarg(treq(Tab, sync), [Tab]). table(Tab) -> table(Tab, []). table(Tab, Opts) -> case options(Opts, [traverse, n_objects]) of {badarg,_} -> erlang:error(badarg, [Tab, Opts]); [Traverse, NObjs] -> TF = case Traverse of first_next -> fun() -> qlc_next(Tab, first(Tab)) end; select -> fun(MS) -> qlc_select(select(Tab, MS, NObjs)) end; {select, MS} -> fun() -> qlc_select(select(Tab, MS, NObjs)) end end, PreFun = fun(_) -> safe_fixtable(Tab, true) end, PostFun = fun() -> safe_fixtable(Tab, false) end, InfoFun = fun(Tag) -> table_info(Tab, Tag) end, %% lookup_keys is not public, but convenient LookupFun = case Traverse of {select, _MS} -> undefined; _ -> fun(_KeyPos, [K]) -> lookup(Tab, K); (_KeyPos, Ks) -> lookup_keys(Tab, Ks) end end, FormatFun = fun({all, _NElements, _ElementFun}) -> As = [Tab | [Opts || _ <- [[]], Opts =/= []]], {?MODULE, table, As}; ({match_spec, MS}) -> {?MODULE, table, [Tab, [{traverse, {select, MS}} | listify(Opts)]]}; ({lookup, _KeyPos, [Value], _NElements, ElementFun}) -> io_lib:format("~w:lookup(~w, ~w)", [?MODULE, Tab, ElementFun(Value)]); ({lookup, _KeyPos, Values, _NElements, ElementFun}) -> Vals = [ElementFun(V) || V <- Values], io_lib:format("lists:flatmap(fun(V) -> " "~w:lookup(~w, V) end, ~w)", [?MODULE, Tab, Vals]) end, qlc:table(TF, [{pre_fun, PreFun}, {post_fun, PostFun}, {info_fun, InfoFun}, {format_fun, FormatFun}, {key_equality, '=:='}, {lookup_fun, LookupFun}]) end. qlc_next(_Tab, '$end_of_table') -> []; qlc_next(Tab, Key) -> case lookup(Tab, Key) of Objects when is_list(Objects) -> Objects ++ fun() -> qlc_next(Tab, next(Tab, Key)) end; Error -> Do what first and next do . exit(Error) end. qlc_select('$end_of_table') -> []; qlc_select({Objects, Cont}) when is_list(Objects) -> Objects ++ fun() -> qlc_select(select(Cont)) end; qlc_select(Error) -> Error. table_info(Tab, num_of_objects) -> info(Tab, size); table_info(Tab, keypos) -> info(Tab, keypos); table_info(Tab, is_unique_objects) -> info(Tab, type) =/= duplicate_bag; table_info(_Tab, _) -> undefined. %% End of table/2. to_ets(DTab, ETab) -> case ets:info(ETab, protection) of undefined -> erlang:error(badarg, [DTab, ETab]); _ -> Fun = fun(X, T) -> true = ets:insert(T, X), T end, foldl(Fun, ETab, DTab) end. traverse(Tab, Fun) -> Ref = make_ref(), TFun = fun(O, Acc) -> case Fun(O) of continue -> Acc; {continue, Val} -> [Val | Acc]; {done, Value} -> throw({Ref, [Value | Acc]}); Other -> throw({Ref, Other}) end end, do_traverse(TFun, [], Tab, Ref). update_counter(Tab, Key, C) -> badarg(treq(Tab, {update_counter, Key, C}), [Tab, Key, C]). verbose() -> verbose(true). verbose(What) -> ok = dets_server:verbose(What), All = dets_server:all(), Fun = fun(Tab) -> treq(Tab, {set_verbose, What}) end, lists:foreach(Fun, All), All. %% Where in the (open) table is Object located? The address of the first matching object is returned . Format 9 returns the address of the object collection . %% -> {ok, Address} | false where(Tab, Object) -> badarg(treq(Tab, {where, Object}), [Tab, Object]). do_traverse(Fun, Acc, Tab, Ref) -> safe_fixtable(Tab, true), Proc = dets_server:get_pid(Tab), try do_trav(Proc, Acc, Fun) catch {Ref, Result} -> Result after safe_fixtable(Tab, false) end. do_trav(Proc, Acc, Fun) -> {Spec, MP} = compile_match_spec(object, '_'), %% MP not used case req(Proc, {match, MP, Spec, default}) of {cont, State} -> do_trav(State, Proc, Acc, Fun); Error -> Error end. do_trav(#dets_cont{bin = eof}, _Proc, Acc, _Fun) -> Acc; do_trav(State, Proc, Acc, Fun) -> case req(Proc, {match_init, State}) of {cont, {Bins, NewState}} -> do_trav_bins(NewState, Proc, Acc, Fun, lists:reverse(Bins)); Error -> Error end. do_trav_bins(State, Proc, Acc, Fun, []) -> do_trav(State, Proc, Acc, Fun); do_trav_bins(State, Proc, Acc, Fun, [Bin | Bins]) -> Unpack one binary at a time , using the client 's heap . case catch binary_to_term(Bin) of {'EXIT', _} -> req(Proc, {corrupt, dets_utils:bad_object(do_trav_bins, Bin)}); Term -> NewAcc = Fun(Term, Acc), do_trav_bins(State, Proc, NewAcc, Fun, Bins) end. safe_match(Tab, Pat, What) -> safe_fixtable(Tab, true), R = do_safe_match(init_chunk_match(Tab, Pat, What, default), []), safe_fixtable(Tab, false), R. do_safe_match({error, Error}, _L) -> {error, Error}; do_safe_match({L, C}, LL) -> do_safe_match(chunk_match(C), L++LL); do_safe_match('$end_of_table', L) -> L; do_safe_match(badarg, _L) -> badarg. %% What = object | bindings | select init_chunk_match(Tab, Pat, What, N) when is_integer(N), N >= 0; N =:= default -> case compile_match_spec(What, Pat) of {Spec, MP} -> case req(dets_server:get_pid(Tab), {match, MP, Spec, N}) of {done, L} -> {L, #dets_cont{tab = Tab, what = What, bin = eof}}; {cont, State} -> chunk_match(State#dets_cont{what = What, tab = Tab}); Error -> Error end; badarg -> badarg end; init_chunk_match(_Tab, _Pat, _What, _) -> badarg. chunk_match(State) -> case catch dets_server:get_pid(State#dets_cont.tab) of {'EXIT', _Reason} -> badarg; _Proc when State#dets_cont.bin =:= eof -> '$end_of_table'; Proc -> case req(Proc, {match_init, State}) of {cont, {Bins, NewState}} -> MP = NewState#dets_cont.match_program, case catch do_foldl_bins(Bins, MP) of {'EXIT', _} -> case ets:is_compiled_ms(MP) of true -> Bad = dets_utils:bad_object(chunk_match, Bins), req(Proc, {corrupt, Bad}); false -> badarg end; [] -> chunk_match(NewState); Terms -> {Terms, NewState} end; Error -> Error end end. do_foldl_bins(Bins, true) -> foldl_bins(Bins, []); do_foldl_bins(Bins, MP) -> foldl_bins(Bins, MP, []). foldl_bins([], Terms) -> Preserve time order ( version 9 ) . Terms; foldl_bins([Bin | Bins], Terms) -> foldl_bins(Bins, [binary_to_term(Bin) | Terms]). foldl_bins([], _MP, Terms) -> Preserve time order ( version 9 ) . Terms; foldl_bins([Bin | Bins], MP, Terms) -> Term = binary_to_term(Bin), case ets:match_spec_run([Term], MP) of [] -> foldl_bins(Bins, MP, Terms); [Result] -> foldl_bins(Bins, MP, [Result | Terms]) end. %% -> {Spec, binary()} | badarg compile_match_spec(select, ?PATTERN_TO_OBJECT_MATCH_SPEC('_') = Spec) -> {Spec, true}; compile_match_spec(select, Spec) -> case catch ets:match_spec_compile(Spec) of X when is_binary(X) -> {Spec, X}; _ -> badarg end; compile_match_spec(object, Pat) -> compile_match_spec(select, ?PATTERN_TO_OBJECT_MATCH_SPEC(Pat)); compile_match_spec(bindings, Pat) -> compile_match_spec(select, ?PATTERN_TO_BINDINGS_MATCH_SPEC(Pat)); compile_match_spec(delete, Pat) -> compile_match_spec(select, ?PATTERN_TO_TRUE_MATCH_SPEC(Pat)). %% Process the args list as provided to open_file/2. defaults(Tab, Args) -> Defaults0 = #open_args{file = to_list(Tab), type = set, keypos = 1, repair = true, min_no_slots = default, max_no_slots = default, ram_file = false, delayed_write = ?DEFAULT_CACHE, auto_save = timer:minutes(?DEFAULT_AUTOSAVE), access = read_write, version = default, debug = false}, Fun = fun repl/2, Defaults = lists:foldl(Fun, Defaults0, Args), case Defaults#open_args.version of 8 -> Defaults#open_args{max_no_slots = default}; _ -> is_comp_min_max(Defaults) end. to_list(T) when is_atom(T) -> atom_to_list(T); to_list(T) -> T. repl({access, A}, Defs) -> mem(A, [read, read_write]), Defs#open_args{access = A}; repl({auto_save, Int}, Defs) when is_integer(Int), Int >= 0 -> Defs#open_args{auto_save = Int}; repl({auto_save, infinity}, Defs) -> Defs#open_args{auto_save =infinity}; repl({cache_size, Int}, Defs) when is_integer(Int), Int >= 0 -> %% Recognized, but ignored. Defs; repl({cache_size, infinity}, Defs) -> Defs; repl({delayed_write, default}, Defs) -> Defs#open_args{delayed_write = ?DEFAULT_CACHE}; repl({delayed_write, {Delay,Size} = C}, Defs) when is_integer(Delay), Delay >= 0, is_integer(Size), Size >= 0 -> Defs#open_args{delayed_write = C}; repl({estimated_no_objects, I}, Defs) -> repl({min_no_slots, I}, Defs); repl({file, File}, Defs) -> Defs#open_args{file = to_list(File)}; repl({keypos, P}, Defs) when is_integer(P), P > 0 -> Defs#open_args{keypos =P}; repl({max_no_slots, I}, Defs) -> Version 9 only . MaxSlots = is_max_no_slots(I), Defs#open_args{max_no_slots = MaxSlots}; repl({min_no_slots, I}, Defs) -> MinSlots = is_min_no_slots(I), Defs#open_args{min_no_slots = MinSlots}; repl({ram_file, Bool}, Defs) -> mem(Bool, [true, false]), Defs#open_args{ram_file = Bool}; repl({repair, T}, Defs) -> mem(T, [true, false, force]), Defs#open_args{repair = T}; repl({type, T}, Defs) -> mem(T, [set, bag, duplicate_bag]), Defs#open_args{type =T}; repl({version, Version}, Defs) -> V = is_version(Version), Defs#open_args{version = V}; repl({debug, Bool}, Defs) -> %% Not documented. mem(Bool, [true, false]), Defs#open_args{debug = Bool}; repl({_, _}, _) -> exit(badarg). is_min_no_slots(default) -> default; is_min_no_slots(I) when is_integer(I), I >= ?DEFAULT_MIN_NO_SLOTS -> I; is_min_no_slots(I) when is_integer(I), I >= 0 -> ?DEFAULT_MIN_NO_SLOTS. is_max_no_slots(default) -> default; is_max_no_slots(I) when is_integer(I), I > 0, I < 1 bsl 31 -> I. is_comp_min_max(Defs) -> #open_args{max_no_slots = Max, min_no_slots = Min, version = V} = Defs, case V of _ when Min =:= default -> Defs; _ when Max =:= default -> Defs; _ -> true = Min =< Max, Defs end. is_version(default) -> default; is_version(8) -> 8; is_version(9) -> 9. mem(X, L) -> case lists:member(X, L) of true -> true; false -> exit(badarg) end. options(Options, Keys) when is_list(Options) -> options(Options, Keys, []); options(Option, Keys) -> options([Option], Keys, []). options(Options, [Key | Keys], L) when is_list(Options) -> V = case lists:keysearch(Key, 1, Options) of {value, {format, Format}} when Format =:= term; Format =:= bchunk -> {ok, Format}; {value, {min_no_slots, I}} -> case catch is_min_no_slots(I) of {'EXIT', _} -> badarg; MinNoSlots -> {ok, MinNoSlots} end; {value, {n_objects, default}} -> {ok, default_option(Key)}; {value, {n_objects, NObjs}} when is_integer(NObjs), NObjs >= 1 -> {ok, NObjs}; {value, {traverse, select}} -> {ok, select}; {value, {traverse, {select, MS}}} -> {ok, {select, MS}}; {value, {traverse, first_next}} -> {ok, first_next}; {value, {Key, _}} -> badarg; false -> Default = default_option(Key), {ok, Default} end, case V of badarg -> {badarg, Key}; {ok, Value} -> NewOptions = lists:keydelete(Key, 1, Options), options(NewOptions, Keys, [Value | L]) end; options([], [], L) -> lists:reverse(L); options(Options, _, _L) -> {badarg,Options}. default_option(format) -> term; default_option(min_no_slots) -> default; default_option(traverse) -> select; default_option(n_objects) -> default. listify(L) when is_list(L) -> L; listify(T) -> [T]. treq(Tab, R) -> case catch dets_server:get_pid(Tab) of Pid when is_pid(Pid) -> req(Pid, R); _ -> badarg end. req(Proc, R) -> Ref = erlang:monitor(process, Proc), Proc ! ?DETS_CALL(self(), R), receive {'DOWN', Ref, process, Proc, _Info} -> badarg; {Proc, Reply} -> erlang:demonitor(Ref), receive {'DOWN', Ref, process, Proc, _Reason} -> Reply after 0 -> Reply end end. Inlined . einval({error, {file_error, _, einval}}, A) -> erlang:error(badarg, A); einval({error, {file_error, _, badarg}}, A) -> erlang:error(badarg, A); einval(Reply, _A) -> Reply. Inlined . badarg(badarg, A) -> erlang:error(badarg, A); badarg(Reply, _A) -> Reply. Inlined . undefined(badarg) -> undefined; undefined(Reply) -> Reply. Inlined . badarg_exit(badarg, A) -> erlang:error(badarg, A); badarg_exit({ok, Reply}, _A) -> Reply; badarg_exit(Reply, _A) -> exit(Reply). %%%----------------------------------------------------------------- %%% Server functions %%%----------------------------------------------------------------- init(Parent, Server) -> process_flag(trap_exit, true), open_file_loop(#head{parent = Parent, server = Server}). open_file_loop(Head) -> open_file_loop(Head, 0). open_file_loop(Head, N) when element(1, Head#head.update_mode) =:= error -> open_file_loop2(Head, N); open_file_loop(Head, N) -> receive When the table is fixed it can be assumed that at least one traversal is in progress . To speed the traversal up three %% things have been done: - prioritize match_init , bchunk , next , and ; %% - do not peek the message queue for updates; %% - wait 1 ms after each update. %% next is normally followed by lookup, but since lookup is also %% used when not traversing the table, it is not prioritized. ?DETS_CALL(From, {match_init, _State} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {bchunk, _State} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {next, _Key} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {match_delete_init, _MP, _Spec} = Op) -> do_apply_op(Op, From, Head, N); {'EXIT', Pid, Reason} when Pid =:= Head#head.parent -> %% Parent orders shutdown. _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, Reason} when Pid =:= Head#head.server -> %% The server is gone. _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, _Reason} -> %% A process fixing the table exits. H2 = remove_fix(Head, Pid, close), open_file_loop(H2, N); {system, From, Req} -> sys:handle_system_msg(Req, From, Head#head.parent, ?MODULE, [], Head) after 0 -> open_file_loop2(Head, N) end. open_file_loop2(Head, N) -> receive ?DETS_CALL(From, Op) -> do_apply_op(Op, From, Head, N); {'EXIT', Pid, Reason} when Pid =:= Head#head.parent -> %% Parent orders shutdown. _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, Reason} when Pid =:= Head#head.server -> %% The server is gone. _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, _Reason} -> %% A process fixing the table exits. H2 = remove_fix(Head, Pid, close), open_file_loop(H2, N); {system, From, Req} -> sys:handle_system_msg(Req, From, Head#head.parent, ?MODULE, [], Head); Message -> error_logger:format("** dets: unexpected message" "(ignored): ~w~n", [Message]), open_file_loop(Head, N) end. do_apply_op(Op, From, Head, N) -> try apply_op(Op, From, Head, N) of ok -> open_file_loop(Head, N); {N2, H2} when is_record(H2, head), is_integer(N2) -> open_file_loop(H2, N2); H2 when is_record(H2, head) -> open_file_loop(H2, N) catch exit:normal -> exit(normal); _:Bad -> Name = Head#head.name, case dets_utils:debug_mode() of true -> If stream_op/5 found more requests , this is not %% the last operation. error_logger:format ("** dets: Bug was found when accessing table ~w,~n" "** dets: operation was ~p and reply was ~w.~n" "** dets: Stacktrace: ~w~n", [Name, Op, Bad, erlang:get_stacktrace()]); false -> error_logger:format ("** dets: Bug was found when accessing table ~w~n", [Name]) end, if From =/= self() -> From ! {self(), {error, {dets_bug, Name, Op, Bad}}}; auto_save | may_grow | , _ } ok end, open_file_loop(Head, N) end. apply_op(Op, From, Head, N) -> case Op of {add_user, Tab, OpenArgs}-> #open_args{file = Fname, type = Type, keypos = Keypos, ram_file = Ram, access = Access, version = Version} = OpenArgs, VersionOK = (Version =:= default) or (Head#head.version =:= Version), %% min_no_slots and max_no_slots are not tested Res = if Tab =:= Head#head.name, Head#head.keypos =:= Keypos, Head#head.type =:= Type, Head#head.ram_file =:= Ram, Head#head.access =:= Access, VersionOK, Fname =:= Head#head.filename -> ok; true -> err({error, incompatible_arguments}) end, From ! {self(), Res}, ok; auto_save -> case Head#head.update_mode of saved -> Head; {error, _Reason} -> Head; _Dirty when N =:= 0 -> % dirty or new_dirty %% The updates seems to have declined dets_utils:vformat("** dets: Auto save of ~p\n", [Head#head.name]), {NewHead, _Res} = perform_save(Head, true), erlang:garbage_collect(), {0, NewHead}; dirty -> %% Reset counter and try later start_auto_save_timer(Head), {0, Head} end; close -> From ! {self(), fclose(Head)}, _NewHead = unlink_fixing_procs(Head), ?PROFILE(ep:done()), exit(normal); {close, Pid} -> Used from dets_server when Pid has closed the table , %% but the table is still opened by some process. NewHead = remove_fix(Head, Pid, close), From ! {self(), status(NewHead)}, NewHead; {corrupt, Reason} -> {H2, Error} = dets_utils:corrupt_reason(Head, Reason), From ! {self(), Error}, H2; {delayed_write, WrTime} -> delayed_write(Head, WrTime); info -> {H2, Res} = finfo(Head), From ! {self(), Res}, H2; {info, Tag} -> {H2, Res} = finfo(Head, Tag), From ! {self(), Res}, H2; {is_compatible_bchunk_format, Term} -> Res = test_bchunk_format(Head, Term), From ! {self(), Res}, ok; {internal_open, Ref, Args} -> ?PROFILE(ep:do()), case do_open_file(Args, Head#head.parent, Head#head.server,Ref) of {ok, H2} -> From ! {self(), ok}, H2; Error -> From ! {self(), Error}, exit(normal) end; may_grow when Head#head.update_mode =/= saved -> if Head#head.update_mode =:= dirty -> %% Won't grow more if the table is full. {H2, _Res} = (Head#head.mod):may_grow(Head, 0, many_times), {N + 1, H2}; true -> ok end; {set_verbose, What} -> set_verbose(What), From ! {self(), ok}, ok; {where, Object} -> {H2, Res} = where_is_object(Head, Object), From ! {self(), Res}, H2; _Message when element(1, Head#head.update_mode) =:= error -> From ! {self(), status(Head)}, ok; %% The following messages assume that the status of the table is OK. {bchunk_init, Tab} -> {H2, Res} = do_bchunk_init(Head, Tab), From ! {self(), Res}, H2; {bchunk, State} -> {H2, Res} = do_bchunk(Head, State), From ! {self(), Res}, H2; delete_all_objects -> {H2, Res} = fdelete_all_objects(Head), From ! {self(), Res}, erlang:garbage_collect(), {0, H2}; {delete_key, Keys} when Head#head.update_mode =:= dirty -> if Head#head.version =:= 8 -> {H2, Res} = fdelete_key(Head, Keys), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N) end; {delete_object, Objs} when Head#head.update_mode =:= dirty -> case check_objects(Objs, Head#head.keypos) of true when Head#head.version =:= 8 -> {H2, Res} = fdelete_object(Head, Objs), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N); false -> From ! {self(), badarg}, ok end; first -> {H2, Res} = ffirst(Head), From ! {self(), Res}, H2; {initialize, InitFun, Format, MinNoSlots} -> {H2, Res} = finit(Head, InitFun, Format, MinNoSlots), From ! {self(), Res}, erlang:garbage_collect(), H2; {insert, Objs} when Head#head.update_mode =:= dirty -> case check_objects(Objs, Head#head.keypos) of true when Head#head.version =:= 8 -> {H2, Res} = finsert(Head, Objs), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N); false -> From ! {self(), badarg}, ok end; {insert_new, Objs} when Head#head.update_mode =:= dirty -> {H2, Res} = finsert_new(Head, Objs), From ! {self(), Res}, {N + 1, H2}; {lookup_keys, Keys} when Head#head.version =:= 8 -> {H2, Res} = flookup_keys(Head, Keys), From ! {self(), Res}, H2; {lookup_keys, _Keys} -> stream_op(Op, From, [], Head, N); {match_init, State} -> {H2, Res} = fmatch_init(Head, State), From ! {self(), Res}, H2; {match, MP, Spec, NObjs} -> {H2, Res} = fmatch(Head, MP, Spec, NObjs), From ! {self(), Res}, H2; {member, Key} when Head#head.version =:= 8 -> {H2, Res} = fmember(Head, Key), From ! {self(), Res}, H2; {member, _Key} = Op -> stream_op(Op, From, [], Head, N); {next, Key} -> {H2, Res} = fnext(Head, Key), From ! {self(), Res}, H2; {match_delete, State} when Head#head.update_mode =:= dirty -> {H2, Res} = fmatch_delete(Head, State), From ! {self(), Res}, {N + 1, H2}; {match_delete_init, MP, Spec} when Head#head.update_mode =:= dirty -> {H2, Res} = fmatch_delete_init(Head, MP, Spec), From ! {self(), Res}, {N + 1, H2}; {safe_fixtable, Bool} -> NewHead = do_safe_fixtable(Head, From, Bool), From ! {self(), ok}, NewHead; {slot, Slot} -> {H2, Res} = fslot(Head, Slot), From ! {self(), Res}, H2; sync -> {NewHead, Res} = perform_save(Head, true), From ! {self(), Res}, erlang:garbage_collect(), {0, NewHead}; {update_counter, Key, Incr} when Head#head.update_mode =:= dirty -> {NewHead, Res} = do_update_counter(Head, Key, Incr), From ! {self(), Res}, {N + 1, NewHead}; WriteOp when Head#head.update_mode =:= new_dirty -> H2 = Head#head{update_mode = dirty}, apply_op(WriteOp, From, H2, 0); WriteOp when Head#head.access =:= read_write, Head#head.update_mode =:= saved -> case catch (Head#head.mod):mark_dirty(Head) of ok -> start_auto_save_timer(Head), H2 = Head#head{update_mode = dirty}, apply_op(WriteOp, From, H2, 0); {NewHead, Error} when is_record(NewHead, head) -> From ! {self(), Error}, NewHead end; WriteOp when is_tuple(WriteOp), Head#head.access =:= read -> Reason = {access_mode, Head#head.filename}, From ! {self(), err({error, Reason})}, ok end. start_auto_save_timer(Head) when Head#head.auto_save =:= infinity -> ok; start_auto_save_timer(Head) -> Millis = Head#head.auto_save, erlang:send_after(Millis, self(), ?DETS_CALL(self(), auto_save)). Version 9 : the message queue and try to evaluate several lookup requests in parallel . , delete and %% insert as well. stream_op(Op, Pid, Pids, Head, N) -> stream_op(Head, Pids, [], N, Pid, Op, Head#head.fixed). stream_loop(Head, Pids, C, N, false = Fxd) -> receive ?DETS_CALL(From, Message) -> stream_op(Head, Pids, C, N, From, Message, Fxd) after 0 -> stream_end(Head, Pids, C, N, no_more) end; stream_loop(Head, Pids, C, N, _Fxd) -> stream_end(Head, Pids, C, N, no_more). stream_op(Head, Pids, C, N, Pid, {lookup_keys,Keys}, Fxd) -> NC = [{{lookup,Pid},Keys} | C], stream_loop(Head, Pids, NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {insert, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {insert_new, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {delete_key, _Keys} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {delete_object, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {member, Key}, Fxd) -> NC = [{{lookup,[Pid]},[Key]} | C], stream_loop(Head, Pids, NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, Op, _Fxd) -> stream_end(Head, Pids, C, N, {Pid,Op}). stream_end(Head, Pids0, C, N, Next) -> case catch update_cache(Head, lists:reverse(C)) of {Head1, [], PwriteList} -> stream_end1(Pids0, Next, N, C, Head1, PwriteList); {Head1, Found, PwriteList} -> %% Possibly an optimization: reply to lookup requests %% first, then write stuff. This makes it possible for %% clients to continue while the disk is accessed. %% (Replies to lookup requests are sent earlier than %% replies to delete and insert requests even if the %% latter requests were made before the lookup requests, %% which can be confusing.) lookup_replies(Found), stream_end1(Pids0, Next, N, C, Head1, PwriteList); Head1 when is_record(Head1, head) -> stream_end2(Pids0, Pids0, Next, N, C, Head1, ok); {Head1, Error} when is_record(Head1, head) -> %% Dig out the processes that did lookup or member. Fun = fun({{lookup,[Pid]},_Keys}, L) -> [Pid | L]; ({{lookup,Pid},_Keys}, L) -> [Pid | L]; (_, L) -> L end, LPs0 = lists:foldl(Fun, [], C), LPs = lists:usort(lists:flatten(LPs0)), stream_end2(Pids0 ++ LPs, Pids0, Next, N, C, Head1, Error); DetsError -> throw(DetsError) end. stream_end1(Pids, Next, N, C, Head, []) -> stream_end2(Pids, Pids, Next, N, C, Head, ok); stream_end1(Pids, Next, N, C, Head, PwriteList) -> {Head1, PR} = (catch dets_utils:pwrite(Head, PwriteList)), stream_end2(Pids, Pids, Next, N, C, Head1, PR). stream_end2([Pid | Pids], Ps, Next, N, C, Head, Reply) -> Pid ! {self(), Reply}, stream_end2(Pids, Ps, Next, N+1, C, Head, Reply); stream_end2([], Ps, no_more, N, C, Head, _Reply) -> penalty(Head, Ps, C), {N, Head}; stream_end2([], _Ps, {From, Op}, N, _C, Head, _Reply) -> apply_op(Op, From, Head, N). penalty(H, _Ps, _C) when H#head.fixed =:= false -> ok; penalty(_H, _Ps, [{{lookup,_Pids},_Keys}]) -> ok; penalty(#head{fixed = {_,[{Pid,_}]}}, [Pid], _C) -> ok; penalty(_H, _Ps, _C) -> timer:sleep(1). lookup_replies([{P,O}]) -> lookup_reply(P, O); lookup_replies(Q) -> [{P,O} | L] = dets_utils:family(Q), lookup_replies(P, lists:append(O), L). lookup_replies(P, O, []) -> lookup_reply(P, O); lookup_replies(P, O, [{P2,O2} | L]) -> lookup_reply(P, O), lookup_replies(P2, lists:append(O2), L). If a list of Pid then op was { member , Key } . Inlined . lookup_reply([P], O) -> P ! {self(), O =/= []}; lookup_reply(P, O) -> P ! {self(), O}. %%----------------------------------------------------------------- %% Callback functions for system messages handling. %%----------------------------------------------------------------- system_continue(_Parent, _, Head) -> open_file_loop(Head). system_terminate(Reason, _Parent, _, Head) -> _NewHead = do_stop(Head), exit(Reason). %%----------------------------------------------------------------- %% Code for upgrade. %%----------------------------------------------------------------- system_code_change(State, _Module, _OldVsn, _Extra) -> {ok, State}. %%%---------------------------------------------------------------------- Internal functions %%%---------------------------------------------------------------------- constants(FH, FileName) -> Version = FH#fileheader.version, if Version =< 8 -> dets_v8:constants(); Version =:= 9 -> dets_v9:constants(); true -> throw({error, {not_a_dets_file, FileName}}) end. - > { ok , Fd , fileheader ( ) } | throw(Error ) read_file_header(FileName, Access, RamFile) -> BF = if RamFile -> case file:read_file(FileName) of {ok, B} -> B; Err -> dets_utils:file_error(FileName, Err) end; true -> FileName end, {ok, Fd} = dets_utils:open(BF, open_args(Access, RamFile)), {ok, <<Version:32>>} = dets_utils:pread_close(Fd, FileName, ?FILE_FORMAT_VERSION_POS, 4), if Version =< 8 -> dets_v8:read_file_header(Fd, FileName); Version =:= 9 -> dets_v9:read_file_header(Fd, FileName); true -> throw({error, {not_a_dets_file, FileName}}) end. fclose(Head) -> {Head1, Res} = perform_save(Head, false), case Head1#head.ram_file of true -> ignore; false -> dets_utils:stop_disk_map(), file:close(Head1#head.fptr) end, Res. - > { NewHead , Res } perform_save(Head, DoSync) when Head#head.update_mode =:= dirty; Head#head.update_mode =:= new_dirty -> case catch begin {Head1, []} = write_cache(Head), {Head2, ok} = (Head1#head.mod):do_perform_save(Head1), ok = ensure_written(Head2, DoSync), {Head2#head{update_mode = saved}, ok} end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end; perform_save(Head, _DoSync) -> {Head, status(Head)}. ensure_written(Head, DoSync) when Head#head.ram_file -> {ok, EOF} = dets_utils:position(Head, eof), {ok, Bin} = dets_utils:pread(Head, 0, EOF, 0), if DoSync -> dets_utils:write_file(Head, Bin); not DoSync -> case file:write_file(Head#head.filename, Bin) of ok -> ok; Error -> dets_utils:corrupt_file(Head, Error) end end; ensure_written(Head, true) when not Head#head.ram_file -> dets_utils:sync(Head); ensure_written(Head, false) when not Head#head.ram_file -> ok. - > { NewHead , { cont ( ) , [ binary ( ) ] } } | { NewHead , Error } do_bchunk_init(Head, Tab) -> case catch write_cache(Head) of {H2, []} -> case (H2#head.mod):table_parameters(H2) of undefined -> {H2, {error, old_version}}; Parms -> L = dets_utils:all_allocated(H2), C0 = #dets_cont{no_objs = default, bin = <<>>, alloc = L}, BinParms = term_to_binary(Parms), {H2, {C0#dets_cont{tab = Tab, what = bchunk}, [BinParms]}} end; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , { cont ( ) , [ binary ( ) ] } } | { NewHead , Error } do_bchunk(Head, State) -> case dets_v9:read_bchunks(Head, State#dets_cont.alloc) of {error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {finished, Bins} -> {Head, {State#dets_cont{bin = eof}, Bins}}; {Bins, NewL} -> {Head, {State#dets_cont{alloc = NewL}, Bins}} end. - > { NewHead , Result } fdelete_all_objects(Head) when Head#head.fixed =:= false -> case catch do_delete_all_objects(Head) of {ok, NewHead} -> start_auto_save_timer(NewHead), {NewHead, ok}; {error, Reason} -> dets_utils:corrupt_reason(Head, Reason) end; fdelete_all_objects(Head) -> {Head, fixed}. do_delete_all_objects(Head) -> #head{fptr = Fd, name = Tab, filename = Fname, type = Type, keypos = Kp, ram_file = Ram, auto_save = Auto, min_no_slots = MinSlots, max_no_slots = MaxSlots, cache = Cache} = Head, CacheSz = dets_utils:cache_size(Cache), ok = dets_utils:truncate(Fd, Fname, bof), (Head#head.mod):initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, true). - > { NewHead , Reply } , Reply = ok | Error . fdelete_key(Head, Keys) -> do_delete(Head, Keys, delete_key). - > { NewHead , Reply } , Reply = ok | badarg | Error . fdelete_object(Head, Objects) -> do_delete(Head, Objects, delete_object). ffirst(H) -> Ref = make_ref(), case catch {Ref, ffirst1(H)} of {Ref, {NH, R}} -> {NH, {ok, R}}; {NH, R} when is_record(NH, head) -> {NH, {error, R}} end. ffirst1(H) -> check_safe_fixtable(H), {NH, []} = write_cache(H), ffirst(NH, 0). ffirst(H, Slot) -> case (H#head.mod):slot_objs(H, Slot) of '$end_of_table' -> {H, '$end_of_table'}; [] -> ffirst(H, Slot+1); [X|_] -> {H, element(H#head.keypos, X)} end. - > { NewHead , Reply } , Reply = ok | badarg | Error . finsert(Head, Objects) -> case catch update_cache(Head, Objects, insert) of {NewHead, []} -> {NewHead, ok}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , Reply } , Reply = ok | badarg | Error . finsert_new(Head, Objects) -> KeyPos = Head#head.keypos, case catch lists:map(fun(Obj) -> element(KeyPos, Obj) end, Objects) of Keys when is_list(Keys) -> case catch update_cache(Head, Keys, {lookup, nopid}) of {Head1, PidObjs} when is_list(PidObjs) -> case lists:all(fun({_P,OL}) -> OL =:= [] end, PidObjs) of true -> case catch update_cache(Head1, Objects, insert) of {NewHead, []} -> {NewHead, true}; {NewHead, Error} when is_record(NewHead, head) -> {NewHead, Error} end; false=Reply -> {Head1, Reply} end; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; _ -> {Head, badarg} end. do_safe_fixtable(Head, Pid, true) -> case Head#head.fixed of false -> link(Pid), Fixed = {erlang:now(), [{Pid, 1}]}, Ftab = dets_utils:get_freelists(Head), Head#head{fixed = Fixed, freelists = {Ftab, Ftab}}; {TimeStamp, Counters} -> case lists:keysearch(Pid, 1, Counters) of when Counter > 1 NewCounters = lists:keyreplace(Pid, 1, Counters, {Pid, Counter+1}), Head#head{fixed = {TimeStamp, NewCounters}}; false -> link(Pid), Fixed = {TimeStamp, [{Pid, 1} | Counters]}, Head#head{fixed = Fixed} end end; do_safe_fixtable(Head, Pid, false) -> remove_fix(Head, Pid, false). remove_fix(Head, Pid, How) -> case Head#head.fixed of false -> Head; {TimeStamp, Counters} -> case lists:keysearch(Pid, 1, Counters) of How = : = close when Pid closes the table . {value, {Pid, Counter}} when Counter =:= 1; How =:= close -> unlink(Pid), case lists:keydelete(Pid, 1, Counters) of [] -> check_growth(Head), erlang:garbage_collect(), Head#head{fixed = false, freelists = dets_utils:get_freelists(Head)}; NewCounters -> Head#head{fixed = {TimeStamp, NewCounters}} end; {value, {Pid, Counter}} -> NewCounters = lists:keyreplace(Pid, 1, Counters, {Pid, Counter-1}), Head#head{fixed = {TimeStamp, NewCounters}}; false -> Head end end. do_stop(Head) -> unlink_fixing_procs(Head), fclose(Head). unlink_fixing_procs(Head) -> case Head#head.fixed of false -> Head; {_, Counters} -> lists:map(fun({Pid, _Counter}) -> unlink(Pid) end, Counters), Head#head{fixed = false, freelists = dets_utils:get_freelists(Head)} end. check_growth(#head{access = read}) -> ok; check_growth(Head) -> NoThings = no_things(Head), if NoThings > Head#head.next -> erlang:send_after(200, self(), ?DETS_CALL(self(), may_grow)); % Catch up. true -> ok end. finfo(H) -> case catch write_cache(H) of {H2, []} -> Info = (catch [{type, H2#head.type}, {keypos, H2#head.keypos}, {size, H2#head.no_objects}, {file_size, file_size(H2#head.fptr, H2#head.filename)}, {filename, H2#head.filename}]), {H2, Info}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end. finfo(H, access) -> {H, H#head.access}; finfo(H, auto_save) -> {H, H#head.auto_save}; finfo(H, bchunk_format) -> case catch write_cache(H) of {H2, []} -> case (H2#head.mod):table_parameters(H2) of undefined = Undef -> {H2, Undef}; Parms -> {H2, term_to_binary(Parms)} end; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, delayed_write) -> % undocumented {H, dets_utils:cache_size(H#head.cache)}; finfo(H, filename) -> {H, H#head.filename}; finfo(H, file_size) -> case catch write_cache(H) of {H2, []} -> {H2, catch file_size(H#head.fptr, H#head.filename)}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, fixed) -> %% true if fixtable/2 has been called {H, not (H#head.fixed =:= false)}; finfo(H, hash) -> {H, H#head.hash_bif}; finfo(H, keypos) -> {H, H#head.keypos}; finfo(H, memory) -> finfo(H, file_size); finfo(H, no_objects) -> finfo(H, size); finfo(H, no_keys) -> case catch write_cache(H) of {H2, []} -> {H2, H2#head.no_keys}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, no_slots) -> {H, (H#head.mod):no_slots(H)}; finfo(H, pid) -> {H, self()}; finfo(H, ram_file) -> {H, H#head.ram_file}; finfo(H, safe_fixed) -> {H, H#head.fixed}; finfo(H, size) -> case catch write_cache(H) of {H2, []} -> {H2, H2#head.no_objects}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, type) -> {H, H#head.type}; finfo(H, version) -> {H, H#head.version}; finfo(H, _) -> {H, undefined}. file_size(Fd, FileName) -> {ok, Pos} = dets_utils:position(Fd, FileName, eof), Pos. test_bchunk_format(_Head, undefined) -> false; test_bchunk_format(Head, _Term) when Head#head.version =:= 8 -> false; test_bchunk_format(Head, Term) -> dets_v9:try_bchunk_header(Term, Head) =/= not_ok. do_open_file([Fname, Verbose], Parent, Server, Ref) -> case catch fopen2(Fname, Ref) of {error, _Reason} = Error -> err(Error); {ok, Head} -> maybe_put(verbose, Verbose), {ok, Head#head{parent = Parent, server = Server}}; {'EXIT', _Reason} = Error -> Error; Bad -> error_logger:format ("** dets: Bug was found in open_file/1, reply was ~w.~n", [Bad]), {error, {dets_bug, Fname, Bad}} end; do_open_file([Tab, OpenArgs, Verb], Parent, Server, Ref) -> case catch fopen3(Tab, OpenArgs) of {error, {tooshort, _}} -> file:delete(OpenArgs#open_args.file), do_open_file([Tab, OpenArgs, Verb], Parent, Server, Ref); {error, _Reason} = Error -> err(Error); {ok, Head} -> maybe_put(verbose, Verb), {ok, Head#head{parent = Parent, server = Server}}; {'EXIT', _Reason} = Error -> Error; Bad -> error_logger:format ("** dets: Bug was found in open_file/2, arguments were~n" "** dets: ~w and reply was ~w.~n", [OpenArgs, Bad]), {error, {dets_bug, Tab, {open_file, OpenArgs}, Bad}} end. maybe_put(_, undefined) -> ignore; maybe_put(K, V) -> put(K, V). %% -> {Head, Result}, Result = ok | Error | {thrown, Error} | badarg finit(Head, InitFun, _Format, _NoSlots) when Head#head.access =:= read -> _ = (catch InitFun(close)), {Head, {error, {access_mode, Head#head.filename}}}; finit(Head, InitFun, _Format, _NoSlots) when Head#head.fixed =/= false -> _ = (catch InitFun(close)), {Head, {error, {fixed_table, Head#head.name}}}; finit(Head, InitFun, Format, NoSlots) -> case catch do_finit(Head, InitFun, Format, NoSlots) of {ok, NewHead} -> check_growth(NewHead), start_auto_save_timer(NewHead), {NewHead, ok}; badarg -> {Head, badarg}; Error -> dets_utils:corrupt(Head, Error) end. %% -> {ok, NewHead} | throw(badarg) | throw(Error) do_finit(Head, Init, Format, NoSlots) -> #head{fptr = Fd, type = Type, keypos = Kp, auto_save = Auto, cache = Cache, filename = Fname, ram_file = Ram, min_no_slots = MinSlots0, max_no_slots = MaxSlots, name = Tab, update_mode = UpdateMode, mod = HMod} = Head, CacheSz = dets_utils:cache_size(Cache), {How, Head1} = case Format of term when is_integer(NoSlots), NoSlots > MaxSlots -> throw(badarg); term -> MinSlots = choose_no_slots(NoSlots, MinSlots0), if UpdateMode =:= new_dirty, MinSlots =:= MinSlots0 -> {general_init, Head}; true -> ok = dets_utils:truncate(Fd, Fname, bof), {ok, H} = HMod:initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, false), {general_init, H} end; bchunk -> ok = dets_utils:truncate(Fd, Fname, bof), {bchunk_init, Head} end, case How of bchunk_init -> case HMod:bchunk_init(Head1, Init) of {ok, NewHead} -> {ok, NewHead#head{update_mode = dirty}}; Error -> Error end; general_init -> Cntrs = ets:new(dets_init, []), Input = HMod:bulk_input(Head1, Init, Cntrs), SlotNumbers = {Head1#head.min_no_slots, bulk_init, MaxSlots}, {Reply, SizeData} = do_sort(Head1, SlotNumbers, Input, Cntrs, Fname, not_used), Bulk = true, case Reply of {ok, NoDups, H1} -> fsck_copy(SizeData, H1, Bulk, NoDups); Else -> close_files(Bulk, SizeData, Head1), Else end end. - > { NewHead , [ LookedUpObject ] } | { NewHead , Error } flookup_keys(Head, Keys) -> case catch update_cache(Head, Keys, {lookup, nopid}) of {NewHead, [{_NoPid,Objs}]} -> {NewHead, Objs}; {NewHead, L} when is_list(L) -> {NewHead, lists:flatmap(fun({_Pid,OL}) -> OL end, L)}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , Result } fmatch_init(Head, C) -> case scan(Head, C) of {scan_error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {Ts, NC} -> {Head, {cont, {Ts, NC}}} end. - > { NewHead , Result } fmatch(Head, MP, Spec, N) -> KeyPos = Head#head.keypos, case find_all_keys(Spec, KeyPos, []) of [] -> Complete match case catch write_cache(Head) of {NewHead, []} -> C0 = init_scan(NewHead, N), {NewHead, {cont, C0#dets_cont{match_program = MP}}}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; List -> Keys = lists:usort(List), {NewHead, Reply} = flookup_keys(Head, Keys), case Reply of Objs when is_list(Objs) -> MatchingObjs = ets:match_spec_run(Objs, MP), {NewHead, {done, MatchingObjs}}; Error -> {NewHead, Error} end end. find_all_keys([], _, Ks) -> Ks; find_all_keys([{H,_,_} | T], KeyPos, Ks) when is_tuple(H) -> case tuple_size(H) of Enough when Enough >= KeyPos -> Key = element(KeyPos, H), case contains_variable(Key) of true -> []; false -> find_all_keys(T, KeyPos, [Key | Ks]) end; _ -> find_all_keys(T, KeyPos, Ks) end; find_all_keys(_, _, _) -> []. contains_variable('_') -> true; contains_variable(A) when is_atom(A) -> case atom_to_list(A) of [$$ | T] -> case (catch list_to_integer(T)) of {'EXIT', _} -> false; _ -> true end; _ -> false end; contains_variable(T) when is_tuple(T) -> contains_variable(tuple_to_list(T)); contains_variable([]) -> false; contains_variable([H|T]) -> case contains_variable(H) of true -> true; false -> contains_variable(T) end; contains_variable(_) -> false. - > { NewHead , Res } fmatch_delete_init(Head, MP, Spec) -> KeyPos = Head#head.keypos, case catch case find_all_keys(Spec, KeyPos, []) of [] -> do_fmatch_delete_var_keys(Head, MP, Spec); List -> Keys = lists:usort(List), do_fmatch_constant_keys(Head, Keys, MP) end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end. %% A note: If deleted objects reside in a bucket with other objects %% that are not deleted, the bucket is moved. If the address of the %% moved bucket is greater than original bucket address the kept %% objects will be read once again later on. - > { NewHead , Res } fmatch_delete(Head, C) -> case scan(Head, C) of {scan_error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {[], _} -> {Head, {done, 0}}; {RTs, NC} -> MP = C#dets_cont.match_program, case catch filter_binary_terms(RTs, MP, []) of {'EXIT', _} -> Bad = dets_utils:bad_object(fmatch_delete, RTs), dets_utils:corrupt_reason(Head, Bad); Terms -> do_fmatch_delete(Head, Terms, NC) end end. do_fmatch_delete_var_keys(Head, _MP, ?PATTERN_TO_TRUE_MATCH_SPEC('_')) when Head#head.fixed =:= false -> %% Handle the case where the file is emptied efficiently. %% Empty the cache just to get the number of objects right. {Head1, []} = write_cache(Head), N = Head1#head.no_objects, case fdelete_all_objects(Head1) of {NewHead, ok} -> {NewHead, {done, N}}; Reply -> Reply end; do_fmatch_delete_var_keys(Head, MP, _Spec) -> {NewHead, []} = write_cache(Head), C0 = init_scan(NewHead, default), {NewHead, {cont, C0#dets_cont{match_program = MP}, 0}}. do_fmatch_constant_keys(Head, Keys, MP) -> case flookup_keys(Head, Keys) of {NewHead, ReadTerms} when is_list(ReadTerms) -> Terms = filter_terms(ReadTerms, MP, []), do_fmatch_delete(NewHead, Terms, fixed); Reply -> Reply end. filter_binary_terms([Bin | Bins], MP, L) -> Term = binary_to_term(Bin), case ets:match_spec_run([Term], MP) of [true] -> filter_binary_terms(Bins, MP, [Term | L]); _ -> filter_binary_terms(Bins, MP, L) end; filter_binary_terms([], _MP, L) -> L. filter_terms([Term | Terms], MP, L) -> case ets:match_spec_run([Term], MP) of [true] -> filter_terms(Terms, MP, [Term | L]); _ -> filter_terms(Terms, MP, L) end; filter_terms([], _MP, L) -> L. do_fmatch_delete(Head, Terms, What) -> N = length(Terms), case do_delete(Head, Terms, delete_object) of {NewHead, ok} when What =:= fixed -> {NewHead, {done, N}}; {NewHead, ok} -> {NewHead, {cont, What, N}}; Reply -> Reply end. do_delete(Head, Things, What) -> case catch update_cache(Head, Things, What) of {NewHead, []} -> {NewHead, ok}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. fmember(Head, Key) -> case catch begin {Head2, [{_NoPid,Objs}]} = update_cache(Head, [Key], {lookup, nopid}), {Head2, Objs =/= []} end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end. fnext(Head, Key) -> Slot = (Head#head.mod):db_hash(Key, Head), Ref = make_ref(), case catch {Ref, fnext(Head, Key, Slot)} of {Ref, {H, R}} -> {H, {ok, R}}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. fnext(H, Key, Slot) -> {NH, []} = write_cache(H), case (H#head.mod):slot_objs(NH, Slot) of '$end_of_table' -> {NH, '$end_of_table'}; L -> fnext_search(NH, Key, Slot, L) end. fnext_search(H, K, Slot, L) -> Kp = H#head.keypos, case beyond_key(K, Kp, L) of [] -> fnext_slot(H, K, Slot+1); L2 -> {H, element(H#head.keypos, hd(L2))} end. %% We've got to continue to search for the next key in the next slot fnext_slot(H, K, Slot) -> case (H#head.mod):slot_objs(H, Slot) of '$end_of_table' -> {H, '$end_of_table'}; [] -> fnext_slot(H, K, Slot+1); L -> {H, element(H#head.keypos, hd(L))} end. beyond_key(_K, _Kp, []) -> []; beyond_key(K, Kp, [H|T]) -> case dets_utils:cmp(element(Kp, H), K) of 0 -> beyond_key2(K, Kp, T); _ -> beyond_key(K, Kp, T) end. beyond_key2(_K, _Kp, []) -> []; beyond_key2(K, Kp, [H|T]=L) -> case dets_utils:cmp(element(Kp, H), K) of 0 -> beyond_key2(K, Kp, T); _ -> L end. %% Open an already existing file, no arguments %% -> {ok, head()} | throw(Error) fopen2(Fname, Tab) -> case file:read_file_info(Fname) of {ok, _} -> Acc = read_write, Ram = false, %% Fd is not always closed upon error, but exit is soon called. {ok, Fd, FH} = read_file_header(Fname, Acc, Ram), Mod = FH#fileheader.mod, case Mod:check_file_header(FH, Fd) of {error, not_closed} -> io:format(user,"dets: file ~p not properly closed, " "repairing ...~n", [Fname]), Version = default, case fsck(Fd, Tab, Fname, FH, default, default, Version) of ok -> fopen2(Fname, Tab); Error -> throw(Error) end; {ok, Head, ExtraInfo} -> open_final(Head, Fname, Acc, Ram, ?DEFAULT_CACHE, Tab, ExtraInfo, false); {error, Reason} -> throw({error, {Reason, Fname}}) end; Error -> dets_utils:file_error(Fname, Error) end. %% Open and possibly create and initialize a file %% -> {ok, head()} | throw(Error) fopen3(Tab, OpenArgs) -> FileName = OpenArgs#open_args.file, case file:read_file_info(FileName) of {ok, _} -> fopen_existing_file(Tab, OpenArgs); Error when OpenArgs#open_args.access =:= read -> dets_utils:file_error(FileName, Error); _Error -> fopen_init_file(Tab, OpenArgs) end. fopen_existing_file(Tab, OpenArgs) -> #open_args{file = Fname, type = Type, keypos = Kp, repair = Rep, min_no_slots = MinSlots, max_no_slots = MaxSlots, ram_file = Ram, delayed_write = CacheSz, auto_save = Auto, access = Acc, version = Version, debug = Debug} = OpenArgs, %% Fd is not always closed upon error, but exit is soon called. {ok, Fd, FH} = read_file_header(Fname, Acc, Ram), V9 = (Version =:= 9) or (Version =:= default), MinF = (MinSlots =:= default) or (MinSlots =:= FH#fileheader.min_no_slots), MaxF = (MaxSlots =:= default) or (MaxSlots =:= FH#fileheader.max_no_slots), Do = case (FH#fileheader.mod):check_file_header(FH, Fd) of {ok, Head, true} when Rep =:= force, Acc =:= read_write, FH#fileheader.version =:= 9, FH#fileheader.no_colls =/= undefined, MinF, MaxF, V9 -> {compact, Head}; {ok, _Head, _Extra} when Rep =:= force, Acc =:= read -> throw({error, {access_mode, Fname}}); {ok, Head, need_compacting} when Acc =:= read -> Version 8 only . {ok, _Head, need_compacting} when Rep =:= true -> %% The file needs to be compacted due to a very big and fragmented free_list . Version 8 only . M = " is now compacted ...", {repair, M}; {ok, _Head, _Extra} when Rep =:= force -> M = ", repair forced.", {repair, M}; {ok, Head, ExtraInfo} -> {final, Head, ExtraInfo}; {error, not_closed} when Rep =:= force, Acc =:= read_write -> M = ", repair forced.", {repair, M}; {error, not_closed} when Rep =:= true, Acc =:= read_write -> M = " not properly closed, repairing ...", {repair, M}; {error, not_closed} when Rep =:= false -> throw({error, {needs_repair, Fname}}); {error, version_bump} when Rep =:= true, Acc =:= read_write -> Version 8 only M = " old version, upgrading ...", {repair, M}; {error, Reason} -> throw({error, {Reason, Fname}}) end, case Do of _ when FH#fileheader.type =/= Type -> throw({error, {type_mismatch, Fname}}); _ when FH#fileheader.keypos =/= Kp -> throw({error, {keypos_mismatch, Fname}}); {compact, SourceHead} -> io:format(user, "dets: file ~p is now compacted ...~n", [Fname]), {ok, NewSourceHead} = open_final(SourceHead, Fname, read, false, ?DEFAULT_CACHE, Tab, true, Debug), case catch compact(NewSourceHead) of ok -> erlang:garbage_collect(), fopen3(Tab, OpenArgs#open_args{repair = false}); _Err -> _ = file:close(Fd), dets_utils:stop_disk_map(), io:format(user, "dets: compaction of file ~p failed, " "now repairing ...~n", [Fname]), {ok, Fd2, _FH} = read_file_header(Fname, Acc, Ram), do_repair(Fd2, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs) end; {repair, Mess} -> io:format(user, "dets: file ~p~s~n", [Fname, Mess]), do_repair(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs); _ when FH#fileheader.version =/= Version, Version =/= default -> throw({error, {version_mismatch, Fname}}); {final, H, EI} -> H1 = H#head{auto_save = Auto}, open_final(H1, Fname, Acc, Ram, CacheSz, Tab, EI, Debug) end. do_repair(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs) -> case fsck(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version) of ok -> %% No need to update 'version'. erlang:garbage_collect(), fopen3(Tab, OpenArgs#open_args{repair = false}); Error -> throw(Error) end. %% -> {ok, head()} | throw(Error) open_final(Head, Fname, Acc, Ram, CacheSz, Tab, ExtraInfo, Debug) -> Head1 = Head#head{access = Acc, ram_file = Ram, filename = Fname, name = Tab, cache = dets_utils:new_cache(CacheSz)}, init_disk_map(Head1#head.version, Tab, Debug), Mod = Head#head.mod, Mod:cache_segps(Head1#head.fptr, Fname, Head1#head.next), Ftab = Mod:init_freelist(Head1, ExtraInfo), check_growth(Head1), NewHead = Head1#head{freelists = Ftab}, {ok, NewHead}. %% -> {ok, head()} | throw(Error) fopen_init_file(Tab, OpenArgs) -> #open_args{file = Fname, type = Type, keypos = Kp, min_no_slots = MinSlotsArg, max_no_slots = MaxSlotsArg, ram_file = Ram, delayed_write = CacheSz, auto_save = Auto, version = UseVersion, debug = Debug} = OpenArgs, MinSlots = choose_no_slots(MinSlotsArg, ?DEFAULT_MIN_NO_SLOTS), MaxSlots = choose_no_slots(MaxSlotsArg, ?DEFAULT_MAX_NO_SLOTS), FileSpec = if Ram -> []; true -> Fname end, {ok, Fd} = dets_utils:open(FileSpec, open_args(read_write, Ram)), Version = if UseVersion =:= default -> case os:getenv("DETS_USE_FILE_FORMAT") of "8" -> 8; _ -> 9 end; true -> UseVersion end, Mod = version2module(Version), %% No need to truncate an empty file. init_disk_map(Version, Tab, Debug), case catch Mod:initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, true) of {error, Reason} when Ram -> file:close(Fd), throw({error, Reason}); {error, Reason} -> file:close(Fd), file:delete(Fname), throw({error, Reason}); {ok, Head} -> start_auto_save_timer(Head), %% init_table does not need to truncate and write header {ok, Head#head{update_mode = new_dirty}} end. %% Debug. init_disk_map(9, Name, Debug) -> case Debug orelse dets_utils:debug_mode() of true -> dets_utils:init_disk_map(Name); false -> ok end; init_disk_map(_Version, _Name, _Debug) -> ok. open_args(Access, RamFile) -> A1 = case Access of read -> []; read_write -> [write] end, A2 = case RamFile of true -> [ram]; false -> [raw] end, A1 ++ A2 ++ [binary, read]. version2module(V) when V =< 8 -> dets_v8; version2module(9) -> dets_v9. module2version(dets_v8) -> 8; module2version(dets_v9) -> 9; module2version(not_used) -> 9. %% -> ok | throw(Error) For version 9 tables only . compact(SourceHead) -> #head{name = Tab, filename = Fname, fptr = SFd, type = Type, keypos = Kp, ram_file = Ram, auto_save = Auto} = SourceHead, Tmp = tempfile(Fname), TblParms = dets_v9:table_parameters(SourceHead), {ok, Fd} = dets_utils:open(Tmp, open_args(read_write, false)), CacheSz = ?DEFAULT_CACHE, It is normally not possible to have two open tables in the same %% process since the process dictionary is used for caching %% segment pointers, but here is works anyway--when reading a file %% serially the pointers to not need to be used. Head = case catch dets_v9:prep_table_copy(Fd, Tab, Tmp, Type, Kp, Ram, CacheSz, Auto, TblParms) of {ok, H} -> H; Error -> file:close(Fd), file:delete(Tmp), throw(Error) end, case dets_v9:compact_init(SourceHead, Head, TblParms) of {ok, NewHead} -> R = case fclose(NewHead) of ok -> ok = file:close(SFd), Save ( rename ) Fname first ? dets_utils:rename(Tmp, Fname); E -> E end, if R =:= ok -> ok; true -> file:delete(Tmp), throw(R) end; Err -> file:close(Fd), file:delete(Tmp), throw(Err) end. %% -> ok | Error %% Closes Fd. fsck(Fd, Tab, Fname, FH, MinSlotsArg, MaxSlotsArg, Version) -> MinSlots and MaxSlots are the option values . #fileheader{min_no_slots = MinSlotsFile, max_no_slots = MaxSlotsFile} = FH, EstNoSlots0 = file_no_things(FH), MinSlots = choose_no_slots(MinSlotsArg, MinSlotsFile), MaxSlots = choose_no_slots(MaxSlotsArg, MaxSlotsFile), EstNoSlots = erlang:min(MaxSlots, erlang:max(MinSlots, EstNoSlots0)), SlotNumbers = {MinSlots, EstNoSlots, MaxSlots}, When repairing : We first try and sort on slots using MinSlots . %% If the number of objects (keys) turns out to be significantly %% different from NoSlots, we try again with the correct number of %% objects (keys). case fsck_try(Fd, Tab, FH, Fname, SlotNumbers, Version) of {try_again, BetterNoSlots} -> BetterSlotNumbers = {MinSlots, BetterNoSlots, MaxSlots}, case fsck_try(Fd, Tab, FH, Fname, BetterSlotNumbers, Version) of {try_again, _} -> file:close(Fd), {error, {cannot_repair, Fname}}; Else -> Else end; Else -> Else end. choose_no_slots(default, NoSlots) -> NoSlots; choose_no_slots(NoSlots, _) -> NoSlots. %% -> ok | {try_again, integer()} | Error %% Closes Fd unless {try_again, _} is returned. %% Initiating a table using a fun and repairing (or converting) a %% file are completely different things, but nevertheless the same %% method is used in both cases... fsck_try(Fd, Tab, FH, Fname, SlotNumbers, Version) -> Tmp = tempfile(Fname), #fileheader{type = Type, keypos = KeyPos} = FH, {_MinSlots, EstNoSlots, MaxSlots} = SlotNumbers, OpenArgs = #open_args{file = Tmp, type = Type, keypos = KeyPos, repair = false, min_no_slots = EstNoSlots, max_no_slots = MaxSlots, ram_file = false, delayed_write = ?DEFAULT_CACHE, auto_save = infinity, access = read_write, version = Version, debug = false}, case catch fopen3(Tab, OpenArgs) of {ok, Head} -> case fsck_try_est(Head, Fd, Fname, SlotNumbers, FH) of {ok, NewHead} -> R = case fclose(NewHead) of ok -> Save ( rename ) Fname first ? dets_utils:rename(Tmp, Fname); Error -> Error end, if R =:= ok -> ok; true -> file:delete(Tmp), R end; TryAgainOrError -> file:delete(Tmp), TryAgainOrError end; Error -> file:close(Fd), Error end. tempfile(Fname) -> Tmp = lists:concat([Fname, ".TMP"]), case file:delete(Tmp) of {error, eacces} -> % 'dets_process_died' happened anyway... (W-nd-ws) timer:sleep(5000), file:delete(Tmp); _ -> ok end, Tmp. - > { ok , NewHead } | { try_again , integer ( ) } | Error fsck_try_est(Head, Fd, Fname, SlotNumbers, FH) -> %% Mod is the module to use for reading input when repairing. Mod = FH#fileheader.mod, Cntrs = ets:new(dets_repair, []), Input = Mod:fsck_input(Head, Fd, Cntrs, FH), {Reply, SizeData} = do_sort(Head, SlotNumbers, Input, Cntrs, Fname, Mod), Bulk = false, case Reply of {ok, NoDups, H1} -> file:close(Fd), fsck_copy(SizeData, H1, Bulk, NoDups); {try_again, _} = Return -> close_files(Bulk, SizeData, Head), Return; Else -> file:close(Fd), close_files(Bulk, SizeData, Head), Else end. do_sort(Head, SlotNumbers, Input, Cntrs, Fname, Mod) -> OldV = module2version(Mod), output_objs/4 replaces { LogSize , NoObjects } in by { LogSize , Position , Data , NoObjects | NoCollections } . %% Data = {FileName,FileDescriptor} | [object()] For small tables Data may be a list of objects which is more %% efficient since no temporary files are created. Output = (Head#head.mod):output_objs(OldV, Head, SlotNumbers, Cntrs), TmpDir = filename:dirname(Fname), Reply = (catch file_sorter:sort(Input, Output, [{format, binary},{tmpdir, TmpDir}])), L = ets:tab2list(Cntrs), ets:delete(Cntrs), {Reply, lists:reverse(lists:keysort(1, L))}. fsck_copy([{_LogSz, Pos, Bins, _NoObjects} | SizeData], Head, _Bulk, NoDups) when is_list(Bins) -> true = NoDups =:= 0, PWs = [{Pos,Bins} | lists:map(fun({_, P, B, _}) -> {P, B} end, SizeData)], #head{fptr = Fd, filename = FileName} = Head, dets_utils:pwrite(Fd, FileName, PWs), {ok, Head#head{update_mode = dirty}}; fsck_copy(SizeData, Head, Bulk, NoDups) -> catch fsck_copy1(SizeData, Head, Bulk, NoDups). fsck_copy1([SzData | L], Head, Bulk, NoDups) -> Out = Head#head.fptr, {LogSz, Pos, {FileName, Fd}, NoObjects} = SzData, Size = if NoObjects =:= 0 -> 0; true -> ?POW(LogSz-1) end, ExpectedSize = Size * NoObjects, close_tmp(Fd), case file:position(Out, Pos) of {ok, Pos} -> ok; PError -> dets_utils:file_error(FileName, PError) end, {ok, Pos} = file:position(Out, Pos), CR = file:copy({FileName, [raw,binary]}, Out), file:delete(FileName), case CR of {ok, Copied} when Copied =:= ExpectedSize; NoObjects =:= 0 -> % the segments fsck_copy1(L, Head, Bulk, NoDups); {ok, Copied} when Bulk, Head#head.version =:= 8 -> NoZeros = ExpectedSize - Copied, Dups = NoZeros div Size, Addr = Pos+Copied, NewHead = free_n_objects(Head, Addr, Size-1, NoDups), NewNoDups = NoDups - Dups, fsck_copy1(L, NewHead, Bulk, NewNoDups); {ok, _Copied} -> % should never happen close_files(Bulk, L, Head), Reason = if Bulk -> initialization_failed; true -> repair_failed end, {error, {Reason, Head#head.filename}}; FError -> close_files(Bulk, L, Head), dets_utils:file_error(FileName, FError) end; fsck_copy1([], Head, _Bulk, NoDups) when NoDups =/= 0 -> {error, {initialization_failed, Head#head.filename}}; fsck_copy1([], Head, _Bulk, _NoDups) -> {ok, Head#head{update_mode = dirty}}. free_n_objects(Head, _Addr, _Size, 0) -> Head; free_n_objects(Head, Addr, Size, N) -> {NewHead, _} = dets_utils:free(Head, Addr, Size), NewAddr = Addr + Size + 1, free_n_objects(NewHead, NewAddr, Size, N-1). close_files(false, SizeData, Head) -> file:close(Head#head.fptr), close_files(true, SizeData, Head); close_files(true, SizeData, _Head) -> Fun = fun({_Size, _Pos, {FileName, Fd}, _No}) -> close_tmp(Fd), file:delete(FileName); (_) -> ok end, lists:foreach(Fun, SizeData). close_tmp(Fd) -> file:close(Fd). fslot(H, Slot) -> case catch begin {NH, []} = write_cache(H), Objs = (NH#head.mod):slot_objs(NH, Slot), {NH, Objs} end of {NewHead, _Objects} = Reply when is_record(NewHead, head) -> Reply end. do_update_counter(Head, _Key, _Incr) when Head#head.type =/= set -> {Head, badarg}; do_update_counter(Head, Key, Incr) -> case flookup_keys(Head, [Key]) of {H1, [O]} -> Kp = H1#head.keypos, case catch try_update_tuple(O, Kp, Incr) of {'EXIT', _} -> {H1, badarg}; {New, Term} -> case finsert(H1, [Term]) of {H2, ok} -> {H2, New}; Reply -> Reply end end; {H1, []} -> {H1, badarg}; HeadError -> HeadError end. try_update_tuple(O, _Kp, {Pos, Incr}) -> try_update_tuple2(O, Pos, Incr); try_update_tuple(O, Kp, Incr) -> try_update_tuple2(O, Kp+1, Incr). try_update_tuple2(O, Pos, Incr) -> New = element(Pos, O) + Incr, {New, setelement(Pos, O, New)}. set_verbose(true) -> put(verbose, yes); set_verbose(_) -> erase(verbose). where_is_object(Head, Object) -> Keypos = Head#head.keypos, case check_objects([Object], Keypos) of true -> case catch write_cache(Head) of {NewHead, []} -> {NewHead, (Head#head.mod):find_object(NewHead, Object)}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; false -> {Head, badarg} end. check_objects([T | Ts], Kp) when tuple_size(T) >= Kp -> check_objects(Ts, Kp); check_objects(L, _Kp) -> L =:= []. no_things(Head) when Head#head.no_keys =:= undefined -> Head#head.no_objects; no_things(Head) -> Head#head.no_keys. file_no_things(FH) when FH#fileheader.no_keys =:= undefined -> FH#fileheader.no_objects; file_no_things(FH) -> FH#fileheader.no_keys. The write cache is list of { Key , [ Item ] } where is one of { Seq , delete_key } , { Seq , { lookup , Pid } } , { Seq , { delete_object , object ( ) } } , %%% or {Seq, {insert,object()}}. Seq is a number that increases %%% monotonically for each item put in the cache. The purpose is to %%% make sure that items are sorted correctly. Sequences of delete and %%% insert operations are inserted in the cache without doing any file %%% operations. When the cache is considered full, a lookup operation %%% is requested, or after some delay, the contents of the cache are %%% written to the file, and the cache emptied. %%% %%% Data is not allowed to linger more than 'delay' milliseconds in %%% the write cache. A delayed_write message is received when some datum has become too old . If ' ' is equal to ' undefined ' , %%% then the cache is empty and no such delayed_write message has been %%% scheduled. Otherwise there is a delayed_write message scheduled, and the value of ' ' is the time when the cache was last written , or when it was first updated after the cache was last %%% written. update_cache(Head, KeysOrObjects, What) -> {Head1, LU, PwriteList} = update_cache(Head, [{What,KeysOrObjects}]), {NewHead, ok} = dets_utils:pwrite(Head1, PwriteList), {NewHead, LU}. - > { NewHead , [ object ( ) ] , pwrite_list ( ) } | throw({Head , Error } ) update_cache(Head, ToAdd) -> Cache = Head#head.cache, #cache{cache = C, csize = Size0, inserts = Ins} = Cache, NewSize = Size0 + erlang:external_size(ToAdd), %% The size is used as a sequence number here; it increases monotonically. {NewC, NewIns, Lookup, Found} = cache_binary(Head, ToAdd, C, Size0, Ins, false, []), NewCache = Cache#cache{cache = NewC, csize = NewSize, inserts = NewIns}, Head1 = Head#head{cache = NewCache}, if Lookup; NewSize >= Cache#cache.tsize -> %% The cache is considered full, or some lookup. {NewHead, LU, PwriteList} = (Head#head.mod):write_cache(Head1), {NewHead, Found ++ LU, PwriteList}; NewC =:= [] -> {Head1, Found, []}; Cache#cache.wrtime =:= undefined -> %% Empty cache. Schedule a delayed write. Now = now(), Me = self(), Call = ?DETS_CALL(Me, {delayed_write, Now}), erlang:send_after(Cache#cache.delay, Me, Call), {Head1#head{cache = NewCache#cache{wrtime = Now}}, Found, []}; Size0 =:= 0 -> %% Empty cache that has been written after the %% currently scheduled delayed write. {Head1#head{cache = NewCache#cache{wrtime = now()}}, Found, []}; true -> %% Cache is not empty, delayed write has been scheduled. {Head1, Found, []} end. cache_binary(Head, [{Q,Os} | L], C, Seq, Ins, Lu,F) when Q =:= delete_object -> cache_obj_op(Head, L, C, Seq, Ins, Lu, F, Os, Head#head.keypos, Q); cache_binary(Head, [{Q,Os} | L], C, Seq, Ins, Lu, F) when Q =:= insert -> NewIns = Ins + length(Os), cache_obj_op(Head, L, C, Seq, NewIns, Lu, F, Os, Head#head.keypos, Q); cache_binary(Head, [{Q,Ks} | L], C, Seq, Ins, Lu, F) when Q =:= delete_key -> cache_key_op(Head, L, C, Seq, Ins, Lu, F, Ks, Q); cache_binary(Head, [{Q,Ks} | L], C, Seq, Ins, _Lu, F) when C =:= [] -> % lookup cache_key_op(Head, L, C, Seq, Ins, true, F, Ks, Q); cache_binary(Head, [{Q,Ks} | L], C, Seq, Ins, Lu, F) -> % lookup case dets_utils:cache_lookup(Head#head.type, Ks, C, []) of false -> cache_key_op(Head, L, C, Seq, Ins, true, F, Ks, Q); Found -> {lookup,Pid} = Q, cache_binary(Head, L, C, Seq, Ins, Lu, [{Pid,Found} | F]) end; cache_binary(_Head, [], C, _Seq, Ins, Lu, F) -> {C, Ins, Lu, F}. cache_key_op(Head, L, C, Seq, Ins, Lu, F, [K | Ks], Q) -> E = {K, {Seq, Q}}, cache_key_op(Head, L, [E | C], Seq+1, Ins, Lu, F, Ks, Q); cache_key_op(Head, L, C, Seq, Ins, Lu, F, [], _Q) -> cache_binary(Head, L, C, Seq, Ins, Lu, F). cache_obj_op(Head, L, C, Seq, Ins, Lu, F, [O | Os], Kp, Q) -> E = {element(Kp, O), {Seq, {Q, O}}}, cache_obj_op(Head, L, [E | C], Seq+1, Ins, Lu, F, Os, Kp, Q); cache_obj_op(Head, L, C, Seq, Ins, Lu, F, [], _Kp, _Q) -> cache_binary(Head, L, C, Seq, Ins, Lu, F). %% Called after some delay. - > NewHead delayed_write(Head, WrTime) -> Cache = Head#head.cache, LastWrTime = Cache#cache.wrtime, if LastWrTime =:= WrTime -> %% The cache was not emptied during the last delay. case catch write_cache(Head) of {Head2, []} -> NewCache = (Head2#head.cache)#cache{wrtime = undefined}, Head2#head{cache = NewCache}; {NewHead, _Error} -> % Head.update_mode has been updated NewHead end; true -> %% The cache was emptied during the delay. %% Has anything been written since then? if Cache#cache.csize =:= 0 -> %% No, further delayed write not needed. NewCache = Cache#cache{wrtime = undefined}, Head#head{cache = NewCache}; true -> %% Yes, schedule a new delayed write. {MS1,S1,M1} = WrTime, {MS2,S2,M2} = LastWrTime, WrT = M1+1000000*(S1+1000000*MS1), LastWrT = M2+1000000*(S2+1000000*MS2), When = round((LastWrT - WrT)/1000), Me = self(), Call = ?DETS_CALL(Me, {delayed_write, LastWrTime}), erlang:send_after(When, Me, Call), Head end end. - > { NewHead , [ LookedUpObject ] } | throw({NewHead , Error } ) write_cache(Head) -> {Head1, LU, PwriteList} = (Head#head.mod):write_cache(Head), {NewHead, ok} = dets_utils:pwrite(Head1, PwriteList), {NewHead, LU}. status(Head) -> case Head#head.update_mode of saved -> ok; dirty -> ok; new_dirty -> ok; Error -> Error end. %%% Scan the file from start to end by reading chunks. %% -> dets_cont() init_scan(Head, NoObjs) -> check_safe_fixtable(Head), FreeLists = dets_utils:get_freelists(Head), Base = Head#head.base, {From, To} = dets_utils:find_next_allocated(FreeLists, Base, Base), #dets_cont{no_objs = NoObjs, bin = <<>>, alloc = {From, To, <<>>}}. check_safe_fixtable(Head) -> case (Head#head.fixed =:= false) andalso ((get(verbose) =:= yes) orelse dets_utils:debug_mode()) of true -> error_logger:format ("** dets: traversal of ~p needs safe_fixtable~n", [Head#head.name]); false -> ok end. %% -> {[RTerm], dets_cont()} | {scan_error, Reason} RTerm = { Pos , Next , , Status , Term } scan(_Head, #dets_cont{alloc = <<>>}=C) -> {[], C}; when is_record(C , dets_cont ) #dets_cont{no_objs = No, alloc = L0, bin = Bin} = C, {From, To, L} = L0, R = case No of default -> 0; _ when is_integer(No) -> -No-1 end, scan(Bin, Head, From, To, L, [], R, {C, Head#head.type}). scan(Bin, H, From, To, L, Ts, R, {C0, Type} = C) -> case (H#head.mod):scan_objs(H, Bin, From, To, L, Ts, R, Type) of {more, NFrom, NTo, NL, NTs, NR, Sz} -> scan_read(H, NFrom, NTo, Sz, NL, NTs, NR, C); {stop, <<>>=B, NFrom, NTo, <<>>=NL, NTs} -> Ftab = dets_utils:get_freelists(H), case dets_utils:find_next_allocated(Ftab, NFrom, H#head.base) of none -> {NTs, C0#dets_cont{bin = eof, alloc = B}}; _ -> {NTs, C0#dets_cont{bin = B, alloc = {NFrom, NTo, NL}}} end; {stop, B, NFrom, NTo, NL, NTs} -> {NTs, C0#dets_cont{bin = B, alloc = {NFrom, NTo, NL}}}; bad_object -> {scan_error, dets_utils:bad_object(scan, {From, To, Bin})} end. scan_read(_H, From, To, _Min, L0, Ts, R, {C, _Type}) when R >= ?CHUNK_SIZE -> %% We may have read (much) more than CHUNK_SIZE, if there are holes. L = {From, To, L0}, {Ts, C#dets_cont{bin = <<>>, alloc = L}}; scan_read(H, From, _To, Min, _L, Ts, R, C) -> Max = if Min < ?CHUNK_SIZE -> ?CHUNK_SIZE; true -> Min end, FreeLists = dets_utils:get_freelists(H), case dets_utils:find_allocated(FreeLists, From, Max, H#head.base) of <<>>=Bin0 -> {Cont, _} = C, {Ts, Cont#dets_cont{bin = eof, alloc = Bin0}}; <<From1:32,To1:32,L1/binary>> -> case dets_utils:pread_n(H#head.fptr, From1, Max) of eof -> {scan_error, premature_eof}; NewBin -> scan(NewBin, H, From1, To1, L1, Ts, R, C) end end. err(Error) -> case get(verbose) of yes -> error_logger:format("** dets: failed with ~w~n", [Error]), Error; undefined -> Error end. %%%%%%%%%%%%%%%%% DEBUG functions %%%%%%%%%%%%%%%% file_info(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> file:close(Fd), (FH#fileheader.mod):file_info(FH); Other -> Other end. get_head_field(Fd, Field) -> dets_utils:read_4(Fd, Field). %% Dump the contents of a DAT file to the tty %% internal debug function which ignores the closed properly thingie %% and just tries anyway view(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> Mod = FH#fileheader.mod, case Mod:check_file_header(FH, Fd) of {ok, H0, ExtraInfo} -> Ftab = Mod:init_freelist(H0, ExtraInfo), {_Bump, Base} = constants(FH, FileName), H = H0#head{freelists=Ftab, base = Base}, v_free_list(H), Mod:v_segments(H), file:close(Fd); X -> file:close(Fd), X end; X -> X end. v_free_list(Head) -> io:format("FREE LIST ...... \n",[]), io:format("~p~n", [dets_utils:all_free(Head)]), io:format("END OF FREE LIST \n",[]).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/stdlib/src/dets.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Disk based linear hashing lookup dictionary. Public. Server export. Internal exports. Debug. Not documented, or not ready for publication. This is the implementation of the mnesia file storage. Each (non dat file is organized as a segmented linear hashlist. The head of the file with the split indicator, size etc is held in ram by the server at all times. The method of hashing is the so called linear hashing algorithm with segments. Linear hashing: - m is the size of the hash table - to insert: - hash = key mod m - when the number of objects exceeds the initial size of the hash table, each insertion of an object causes bucket n to be split: - add a new bucket to the end of the table - redistribute the contents of bucket n - increment n - to search: hash = key mod m do linear scan of the bucket to the error tuple. When in 'error' mode, the free lists are not written, and a repair is forced next time the file is opened. small chunk not consumed, or 'eof' at end-of-file the part of the file not yet scanned, mostly a binary true | compiled_match_spec() | undefined -define(DEBUGM(X, Y), io:format(X, Y)). -define(DEBUGF(X,Y), io:format(X, Y)). -define(PROFILE(C), C). - there is a new open_file() option 'debug'; - there is a new OS environment variable 'DETS_DEBUG'; - verbose(true) implies that info messages are written onto the error log whenever an unsafe traversal is started. The 'debug' mode (set by the open_file() option 'debug' or means a considerable overhead when it comes to RAM usage. The operation of Dets is also slowed down a bit. Note that in debug mode terms will be output on the error logger. ---------------------------------------------------------------------- API ---------------------------------------------------------------------- Should not happen. Backwards compatibility... Given a filename, fsck it. Debug. undocumented Not public. Assuming that a file already exists, open it with the parameters as already specified in the file itself. Return a ref leading to the file. Should not happen. Should not happen. lookup_keys is not public, but convenient End of table/2. Where in the (open) table is Object located? -> {ok, Address} | false MP not used What = object | bindings | select -> {Spec, binary()} | badarg Process the args list as provided to open_file/2. Recognized, but ignored. Not documented. ----------------------------------------------------------------- Server functions ----------------------------------------------------------------- things have been done: - do not peek the message queue for updates; - wait 1 ms after each update. next is normally followed by lookup, but since lookup is also used when not traversing the table, it is not prioritized. Parent orders shutdown. The server is gone. A process fixing the table exits. Parent orders shutdown. The server is gone. A process fixing the table exits. the last operation. min_no_slots and max_no_slots are not tested dirty or new_dirty The updates seems to have declined Reset counter and try later but the table is still opened by some process. Won't grow more if the table is full. The following messages assume that the status of the table is OK. insert as well. Possibly an optimization: reply to lookup requests first, then write stuff. This makes it possible for clients to continue while the disk is accessed. (Replies to lookup requests are sent earlier than replies to delete and insert requests even if the latter requests were made before the lookup requests, which can be confusing.) Dig out the processes that did lookup or member. ----------------------------------------------------------------- Callback functions for system messages handling. ----------------------------------------------------------------- ----------------------------------------------------------------- Code for upgrade. ----------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- Catch up. undocumented true if fixtable/2 has been called -> {Head, Result}, Result = ok | Error | {thrown, Error} | badarg -> {ok, NewHead} | throw(badarg) | throw(Error) A note: If deleted objects reside in a bucket with other objects that are not deleted, the bucket is moved. If the address of the moved bucket is greater than original bucket address the kept objects will be read once again later on. Handle the case where the file is emptied efficiently. Empty the cache just to get the number of objects right. We've got to continue to search for the next key in the next slot Open an already existing file, no arguments -> {ok, head()} | throw(Error) Fd is not always closed upon error, but exit is soon called. Open and possibly create and initialize a file -> {ok, head()} | throw(Error) Fd is not always closed upon error, but exit is soon called. The file needs to be compacted due to a very big No need to update 'version'. -> {ok, head()} | throw(Error) -> {ok, head()} | throw(Error) No need to truncate an empty file. init_table does not need to truncate and write header Debug. -> ok | throw(Error) process since the process dictionary is used for caching segment pointers, but here is works anyway--when reading a file serially the pointers to not need to be used. -> ok | Error Closes Fd. If the number of objects (keys) turns out to be significantly different from NoSlots, we try again with the correct number of objects (keys). -> ok | {try_again, integer()} | Error Closes Fd unless {try_again, _} is returned. Initiating a table using a fun and repairing (or converting) a file are completely different things, but nevertheless the same method is used in both cases... 'dets_process_died' happened anyway... (W-nd-ws) Mod is the module to use for reading input when repairing. Data = {FileName,FileDescriptor} | [object()] efficient since no temporary files are created. the segments should never happen or {Seq, {insert,object()}}. Seq is a number that increases monotonically for each item put in the cache. The purpose is to make sure that items are sorted correctly. Sequences of delete and insert operations are inserted in the cache without doing any file operations. When the cache is considered full, a lookup operation is requested, or after some delay, the contents of the cache are written to the file, and the cache emptied. Data is not allowed to linger more than 'delay' milliseconds in the write cache. A delayed_write message is received when some then the cache is empty and no such delayed_write message has been scheduled. Otherwise there is a delayed_write message scheduled, written. The size is used as a sequence number here; it increases monotonically. The cache is considered full, or some lookup. Empty cache. Schedule a delayed write. Empty cache that has been written after the currently scheduled delayed write. Cache is not empty, delayed write has been scheduled. lookup lookup Called after some delay. The cache was not emptied during the last delay. Head.update_mode has been updated The cache was emptied during the delay. Has anything been written since then? No, further delayed write not needed. Yes, schedule a new delayed write. Scan the file from start to end by reading chunks. -> dets_cont() -> {[RTerm], dets_cont()} | {scan_error, Reason} We may have read (much) more than CHUNK_SIZE, if there are holes. DEBUG functions %%%%%%%%%%%%%%%% Dump the contents of a DAT file to the tty internal debug function which ignores the closed properly thingie and just tries anyway
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(dets). -export([all/0, bchunk/2, close/1, delete/2, delete_all_objects/1, delete_object/2, first/1, foldl/3, foldr/3, from_ets/2, info/1, info/2, init_table/2, init_table/3, insert/2, insert_new/2, is_compatible_bchunk_format/2, is_dets_file/1, lookup/2, match/1, match/2, match/3, match_delete/2, match_object/1, match_object/2, match_object/3, member/2, next/2, open_file/1, open_file/2, pid2name/1, repair_continuation/2, safe_fixtable/2, select/1, select/2, select/3, select_delete/2, slot/2, sync/1, table/1, table/2, to_ets/2, traverse/2, update_counter/3]). -export([start/0, stop/0]). -export([istart_link/1, init/2, internal_open/3, add_user/3, internal_close/1, remove_user/2, system_continue/3, system_terminate/4, system_code_change/4]). -export([file_info/1, fsck/1, fsck/2, get_head_field/2, view/1, where/2, verbose/0, verbose/1 ]). -export([lookup_keys/2]). -compile({inline, [{einval,2},{badarg,2},{undefined,1}, {badarg_exit,2},{lookup_reply,2}]}). -include_lib("kernel/include/file.hrl"). -include("dets.hrl"). -type object() :: tuple(). -type pattern() :: atom() | tuple(). -type tab_name() :: atom() | reference(). ram - copy ) table is maintained in a corresponding .DAT file . The The parts specific for formats up to and including 8(c ) are implemented in dets_v8.erl , parts specific for format 9 are implemented in dets_v9.erl . - n indicates next bucket to split ( initially zero ) ; - initially next = m and n = 0 - if hash < n then hash = key mod 2 m using hash = key mod 2 m - if n = m then m = 2 m , n = 0 if hash < n then hash = key mod 2 m If a file error occurs on a working dets file , update_mode is set -record(dets_cont, { object | bindings | select | bchunk requested number of objects : default | integer ( ) > 0 tab, }). -record(open_args, { file, type, keypos, repair, min_no_slots, max_no_slots, ram_file, delayed_write, auto_save, access, version, debug }). -define(PATTERN_TO_OBJECT_MATCH_SPEC(Pat), [{Pat,[],['$_']}]). -define(PATTERN_TO_BINDINGS_MATCH_SPEC(Pat), [{Pat,[],['$$']}]). -define(PATTERN_TO_TRUE_MATCH_SPEC(Pat), [{Pat,[],[true]}]). -define(DEBUGM(X, Y), true). -define(DEBUGF(X,Y), void). -define(PROFILE(C), void). Some further debug code was added in R12B-1 ( stdlib-1.15.1 ): by os : " , " true " ) ) implies that the results of calling pwrite ( ) and pread ( ) are tested to some extent . It also add_user(Pid, Tab, Args) -> req(Pid, {add_user, Tab, Args}). -spec all() -> [tab_name()]. all() -> dets_server:all(). -type cont() :: #dets_cont{}. -spec bchunk(tab_name(), 'start' | cont()) -> {cont(), binary() | tuple()} | '$end_of_table' | {'error', term()}. bchunk(Tab, start) -> badarg(treq(Tab, {bchunk_init, Tab}), [Tab, start]); bchunk(Tab, #dets_cont{bin = eof, tab = Tab}) -> '$end_of_table'; bchunk(Tab, #dets_cont{what = bchunk, tab = Tab} = State) -> badarg(treq(Tab, {bchunk, State}), [Tab, State]); bchunk(Tab, Term) -> erlang:error(badarg, [Tab, Term]). -spec close(tab_name()) -> 'ok' | {'error', term()}. close(Tab) -> case dets_server:close(Tab) of Reply -> Reply end. -spec delete(tab_name(), term()) -> 'ok' | {'error', term()}. delete(Tab, Key) -> badarg(treq(Tab, {delete_key, [Key]}), [Tab, Key]). -spec delete_all_objects(tab_name()) -> 'ok' | {'error', term()}. delete_all_objects(Tab) -> case treq(Tab, delete_all_objects) of badarg -> erlang:error(badarg, [Tab]); fixed -> match_delete(Tab, '_'); Reply -> Reply end. -spec delete_object(tab_name(), object()) -> 'ok' | {'error', term()}. delete_object(Tab, O) -> badarg(treq(Tab, {delete_object, [O]}), [Tab, O]). fsck(Fname) -> fsck(Fname, default). fsck(Fname, Version) -> catch begin {ok, Fd, FH} = read_file_header(Fname, read, false), ?DEBUGF("FileHeader: ~p~n", [FH]), case (FH#fileheader.mod):check_file_header(FH, Fd) of {error, not_closed} -> fsck(Fd, make_ref(), Fname, FH, default, default, Version); {ok, _Head, _Extra} -> fsck(Fd, make_ref(), Fname, FH, default, default, Version); Error -> Error end end. -spec first(tab_name()) -> term() | '$end_of_table'. first(Tab) -> badarg_exit(treq(Tab, first), [Tab]). -spec foldr(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}. foldr(Fun, Acc, Tab) -> foldl(Fun, Acc, Tab). -spec foldl(fun((object(), Acc) -> Acc), Acc, tab_name()) -> Acc | {'error', term()}. foldl(Fun, Acc, Tab) -> Ref = make_ref(), do_traverse(Fun, Acc, Tab, Ref). -spec from_ets(tab_name(), ets:tab()) -> 'ok' | {'error', term()}. from_ets(DTab, ETab) -> ets:safe_fixtable(ETab, true), Spec = ?PATTERN_TO_OBJECT_MATCH_SPEC('_'), LC = ets:select(ETab, Spec, 100), InitFun = from_ets_fun(LC, ETab), Reply = treq(DTab, {initialize, InitFun, term, default}), ets:safe_fixtable(ETab, false), case Reply of {thrown, Thrown} -> throw(Thrown); Else -> badarg(Else, [DTab, ETab]) end. from_ets_fun(LC, ETab) -> fun(close) -> ok; (read) when LC =:= '$end_of_table' -> end_of_input; (read) -> {L, C} = LC, {L, from_ets_fun(ets:select(C), ETab)} end. info(Tab) -> case catch dets_server:get_pid(Tab) of {'EXIT', _Reason} -> undefined; Pid -> undefined(req(Pid, info)) end. info(Tab, owner) -> case catch dets_server:get_pid(Tab) of Pid when is_pid(Pid) -> Pid; _ -> undefined end; case dets_server:users(Tab) of [] -> undefined; Users -> Users end; info(Tab, Tag) -> case catch dets_server:get_pid(Tab) of {'EXIT', _Reason} -> undefined; Pid -> undefined(req(Pid, {info, Tag})) end. init_table(Tab, InitFun) -> init_table(Tab, InitFun, []). init_table(Tab, InitFun, Options) when is_function(InitFun) -> case options(Options, [format, min_no_slots]) of {badarg,_} -> erlang:error(badarg, [Tab, InitFun, Options]); [Format, MinNoSlots] -> case treq(Tab, {initialize, InitFun, Format, MinNoSlots}) of {thrown, Thrown} -> throw(Thrown); Else -> badarg(Else, [Tab, InitFun, Options]) end end; init_table(Tab, InitFun, Options) -> erlang:error(badarg, [Tab, InitFun, Options]). insert(Tab, Objs) when is_list(Objs) -> badarg(treq(Tab, {insert, Objs}), [Tab, Objs]); insert(Tab, Obj) -> badarg(treq(Tab, {insert, [Obj]}), [Tab, Obj]). insert_new(Tab, Objs) when is_list(Objs) -> badarg(treq(Tab, {insert_new, Objs}), [Tab, Objs]); insert_new(Tab, Obj) -> badarg(treq(Tab, {insert_new, [Obj]}), [Tab, Obj]). internal_close(Pid) -> req(Pid, close). internal_open(Pid, Ref, Args) -> req(Pid, {internal_open, Ref, Args}). is_compatible_bchunk_format(Tab, Term) -> badarg(treq(Tab, {is_compatible_bchunk_format, Term}), [Tab, Term]). is_dets_file(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> file:close(Fd), FH#fileheader.cookie =:= ?MAGIC; {error, {tooshort, _}} -> false; {error, {not_a_dets_file, _}} -> false; Other -> Other end. lookup(Tab, Key) -> badarg(treq(Tab, {lookup_keys, [Key]}), [Tab, Key]). lookup_keys(Tab, Keys) -> case catch lists:usort(Keys) of UKeys when is_list(UKeys), UKeys =/= [] -> badarg(treq(Tab, {lookup_keys, UKeys}), [Tab, Keys]); _Else -> erlang:error(badarg, [Tab, Keys]) end. match(Tab, Pat) -> badarg(safe_match(Tab, Pat, bindings), [Tab, Pat]). match(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, bindings, N), [Tab, Pat, N]). match(State) when State#dets_cont.what =:= bindings -> badarg(chunk_match(State), [State]); match(Term) -> erlang:error(badarg, [Term]). -spec match_delete(tab_name(), pattern()) -> non_neg_integer() | 'ok' | {'error', term()}. match_delete(Tab, Pat) -> badarg(match_delete(Tab, Pat, delete), [Tab, Pat]). match_delete(Tab, Pat, What) -> safe_fixtable(Tab, true), case compile_match_spec(What, Pat) of {Spec, MP} -> Proc = dets_server:get_pid(Tab), R = req(Proc, {match_delete_init, MP, Spec}), do_match_delete(Tab, Proc, R, What, 0); badarg -> badarg end. do_match_delete(Tab, _Proc, {done, N1}, select, N) -> safe_fixtable(Tab, false), N + N1; do_match_delete(Tab, _Proc, {done, _N1}, _What, _N) -> safe_fixtable(Tab, false), ok; do_match_delete(Tab, Proc, {cont, State, N1}, What, N) -> do_match_delete(Tab, Proc, req(Proc, {match_delete, State}), What, N+N1); do_match_delete(Tab, _Proc, Error, _What, _N) -> safe_fixtable(Tab, false), Error. match_object(Tab, Pat) -> badarg(safe_match(Tab, Pat, object), [Tab, Pat]). match_object(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, object, N), [Tab, Pat, N]). match_object(State) when State#dets_cont.what =:= object -> badarg(chunk_match(State), [State]); match_object(Term) -> erlang:error(badarg, [Term]). member(Tab, Key) -> badarg(treq(Tab, {member, Key}), [Tab, Key]). next(Tab, Key) -> badarg_exit(treq(Tab, {next, Key}), [Tab, Key]). open_file(File) -> case dets_server:open_file(to_list(File)) of erlang:error(dets_process_died, [File]); Reply -> einval(Reply, [File]) end. open_file(Tab, Args) when is_list(Args) -> case catch defaults(Tab, Args) of OpenArgs when is_record(OpenArgs, open_args) -> case dets_server:open_file(Tab, OpenArgs) of erlang:error(dets_process_died, [Tab, Args]); Reply -> einval(Reply, [Tab, Args]) end; _ -> erlang:error(badarg, [Tab, Args]) end; open_file(Tab, Arg) -> open_file(Tab, [Arg]). pid2name(Pid) -> dets_server:pid2name(Pid). remove_user(Pid, From) -> req(Pid, {close, From}). repair_continuation(#dets_cont{match_program = B}=Cont, MS) when is_binary(B) -> case ets:is_compiled_ms(B) of true -> Cont; false -> Cont#dets_cont{match_program = ets:match_spec_compile(MS)} end; repair_continuation(#dets_cont{}=Cont, _MS) -> Cont; repair_continuation(T, MS) -> erlang:error(badarg, [T, MS]). safe_fixtable(Tab, Bool) when Bool; not Bool -> badarg(treq(Tab, {safe_fixtable, Bool}), [Tab, Bool]); safe_fixtable(Tab, Term) -> erlang:error(badarg, [Tab, Term]). select(Tab, Pat) -> badarg(safe_match(Tab, Pat, select), [Tab, Pat]). select(Tab, Pat, N) -> badarg(init_chunk_match(Tab, Pat, select, N), [Tab, Pat, N]). select(State) when State#dets_cont.what =:= select -> badarg(chunk_match(State), [State]); select(Term) -> erlang:error(badarg, [Term]). select_delete(Tab, Pat) -> badarg(match_delete(Tab, Pat, select), [Tab, Pat]). slot(Tab, Slot) when is_integer(Slot), Slot >= 0 -> badarg(treq(Tab, {slot, Slot}), [Tab, Slot]); slot(Tab, Term) -> erlang:error(badarg, [Tab, Term]). start() -> dets_server:start(). stop() -> dets_server:stop(). istart_link(Server) -> {ok, proc_lib:spawn_link(dets, init, [self(), Server])}. sync(Tab) -> badarg(treq(Tab, sync), [Tab]). table(Tab) -> table(Tab, []). table(Tab, Opts) -> case options(Opts, [traverse, n_objects]) of {badarg,_} -> erlang:error(badarg, [Tab, Opts]); [Traverse, NObjs] -> TF = case Traverse of first_next -> fun() -> qlc_next(Tab, first(Tab)) end; select -> fun(MS) -> qlc_select(select(Tab, MS, NObjs)) end; {select, MS} -> fun() -> qlc_select(select(Tab, MS, NObjs)) end end, PreFun = fun(_) -> safe_fixtable(Tab, true) end, PostFun = fun() -> safe_fixtable(Tab, false) end, InfoFun = fun(Tag) -> table_info(Tab, Tag) end, LookupFun = case Traverse of {select, _MS} -> undefined; _ -> fun(_KeyPos, [K]) -> lookup(Tab, K); (_KeyPos, Ks) -> lookup_keys(Tab, Ks) end end, FormatFun = fun({all, _NElements, _ElementFun}) -> As = [Tab | [Opts || _ <- [[]], Opts =/= []]], {?MODULE, table, As}; ({match_spec, MS}) -> {?MODULE, table, [Tab, [{traverse, {select, MS}} | listify(Opts)]]}; ({lookup, _KeyPos, [Value], _NElements, ElementFun}) -> io_lib:format("~w:lookup(~w, ~w)", [?MODULE, Tab, ElementFun(Value)]); ({lookup, _KeyPos, Values, _NElements, ElementFun}) -> Vals = [ElementFun(V) || V <- Values], io_lib:format("lists:flatmap(fun(V) -> " "~w:lookup(~w, V) end, ~w)", [?MODULE, Tab, Vals]) end, qlc:table(TF, [{pre_fun, PreFun}, {post_fun, PostFun}, {info_fun, InfoFun}, {format_fun, FormatFun}, {key_equality, '=:='}, {lookup_fun, LookupFun}]) end. qlc_next(_Tab, '$end_of_table') -> []; qlc_next(Tab, Key) -> case lookup(Tab, Key) of Objects when is_list(Objects) -> Objects ++ fun() -> qlc_next(Tab, next(Tab, Key)) end; Error -> Do what first and next do . exit(Error) end. qlc_select('$end_of_table') -> []; qlc_select({Objects, Cont}) when is_list(Objects) -> Objects ++ fun() -> qlc_select(select(Cont)) end; qlc_select(Error) -> Error. table_info(Tab, num_of_objects) -> info(Tab, size); table_info(Tab, keypos) -> info(Tab, keypos); table_info(Tab, is_unique_objects) -> info(Tab, type) =/= duplicate_bag; table_info(_Tab, _) -> undefined. to_ets(DTab, ETab) -> case ets:info(ETab, protection) of undefined -> erlang:error(badarg, [DTab, ETab]); _ -> Fun = fun(X, T) -> true = ets:insert(T, X), T end, foldl(Fun, ETab, DTab) end. traverse(Tab, Fun) -> Ref = make_ref(), TFun = fun(O, Acc) -> case Fun(O) of continue -> Acc; {continue, Val} -> [Val | Acc]; {done, Value} -> throw({Ref, [Value | Acc]}); Other -> throw({Ref, Other}) end end, do_traverse(TFun, [], Tab, Ref). update_counter(Tab, Key, C) -> badarg(treq(Tab, {update_counter, Key, C}), [Tab, Key, C]). verbose() -> verbose(true). verbose(What) -> ok = dets_server:verbose(What), All = dets_server:all(), Fun = fun(Tab) -> treq(Tab, {set_verbose, What}) end, lists:foreach(Fun, All), All. The address of the first matching object is returned . Format 9 returns the address of the object collection . where(Tab, Object) -> badarg(treq(Tab, {where, Object}), [Tab, Object]). do_traverse(Fun, Acc, Tab, Ref) -> safe_fixtable(Tab, true), Proc = dets_server:get_pid(Tab), try do_trav(Proc, Acc, Fun) catch {Ref, Result} -> Result after safe_fixtable(Tab, false) end. do_trav(Proc, Acc, Fun) -> {Spec, MP} = compile_match_spec(object, '_'), case req(Proc, {match, MP, Spec, default}) of {cont, State} -> do_trav(State, Proc, Acc, Fun); Error -> Error end. do_trav(#dets_cont{bin = eof}, _Proc, Acc, _Fun) -> Acc; do_trav(State, Proc, Acc, Fun) -> case req(Proc, {match_init, State}) of {cont, {Bins, NewState}} -> do_trav_bins(NewState, Proc, Acc, Fun, lists:reverse(Bins)); Error -> Error end. do_trav_bins(State, Proc, Acc, Fun, []) -> do_trav(State, Proc, Acc, Fun); do_trav_bins(State, Proc, Acc, Fun, [Bin | Bins]) -> Unpack one binary at a time , using the client 's heap . case catch binary_to_term(Bin) of {'EXIT', _} -> req(Proc, {corrupt, dets_utils:bad_object(do_trav_bins, Bin)}); Term -> NewAcc = Fun(Term, Acc), do_trav_bins(State, Proc, NewAcc, Fun, Bins) end. safe_match(Tab, Pat, What) -> safe_fixtable(Tab, true), R = do_safe_match(init_chunk_match(Tab, Pat, What, default), []), safe_fixtable(Tab, false), R. do_safe_match({error, Error}, _L) -> {error, Error}; do_safe_match({L, C}, LL) -> do_safe_match(chunk_match(C), L++LL); do_safe_match('$end_of_table', L) -> L; do_safe_match(badarg, _L) -> badarg. init_chunk_match(Tab, Pat, What, N) when is_integer(N), N >= 0; N =:= default -> case compile_match_spec(What, Pat) of {Spec, MP} -> case req(dets_server:get_pid(Tab), {match, MP, Spec, N}) of {done, L} -> {L, #dets_cont{tab = Tab, what = What, bin = eof}}; {cont, State} -> chunk_match(State#dets_cont{what = What, tab = Tab}); Error -> Error end; badarg -> badarg end; init_chunk_match(_Tab, _Pat, _What, _) -> badarg. chunk_match(State) -> case catch dets_server:get_pid(State#dets_cont.tab) of {'EXIT', _Reason} -> badarg; _Proc when State#dets_cont.bin =:= eof -> '$end_of_table'; Proc -> case req(Proc, {match_init, State}) of {cont, {Bins, NewState}} -> MP = NewState#dets_cont.match_program, case catch do_foldl_bins(Bins, MP) of {'EXIT', _} -> case ets:is_compiled_ms(MP) of true -> Bad = dets_utils:bad_object(chunk_match, Bins), req(Proc, {corrupt, Bad}); false -> badarg end; [] -> chunk_match(NewState); Terms -> {Terms, NewState} end; Error -> Error end end. do_foldl_bins(Bins, true) -> foldl_bins(Bins, []); do_foldl_bins(Bins, MP) -> foldl_bins(Bins, MP, []). foldl_bins([], Terms) -> Preserve time order ( version 9 ) . Terms; foldl_bins([Bin | Bins], Terms) -> foldl_bins(Bins, [binary_to_term(Bin) | Terms]). foldl_bins([], _MP, Terms) -> Preserve time order ( version 9 ) . Terms; foldl_bins([Bin | Bins], MP, Terms) -> Term = binary_to_term(Bin), case ets:match_spec_run([Term], MP) of [] -> foldl_bins(Bins, MP, Terms); [Result] -> foldl_bins(Bins, MP, [Result | Terms]) end. compile_match_spec(select, ?PATTERN_TO_OBJECT_MATCH_SPEC('_') = Spec) -> {Spec, true}; compile_match_spec(select, Spec) -> case catch ets:match_spec_compile(Spec) of X when is_binary(X) -> {Spec, X}; _ -> badarg end; compile_match_spec(object, Pat) -> compile_match_spec(select, ?PATTERN_TO_OBJECT_MATCH_SPEC(Pat)); compile_match_spec(bindings, Pat) -> compile_match_spec(select, ?PATTERN_TO_BINDINGS_MATCH_SPEC(Pat)); compile_match_spec(delete, Pat) -> compile_match_spec(select, ?PATTERN_TO_TRUE_MATCH_SPEC(Pat)). defaults(Tab, Args) -> Defaults0 = #open_args{file = to_list(Tab), type = set, keypos = 1, repair = true, min_no_slots = default, max_no_slots = default, ram_file = false, delayed_write = ?DEFAULT_CACHE, auto_save = timer:minutes(?DEFAULT_AUTOSAVE), access = read_write, version = default, debug = false}, Fun = fun repl/2, Defaults = lists:foldl(Fun, Defaults0, Args), case Defaults#open_args.version of 8 -> Defaults#open_args{max_no_slots = default}; _ -> is_comp_min_max(Defaults) end. to_list(T) when is_atom(T) -> atom_to_list(T); to_list(T) -> T. repl({access, A}, Defs) -> mem(A, [read, read_write]), Defs#open_args{access = A}; repl({auto_save, Int}, Defs) when is_integer(Int), Int >= 0 -> Defs#open_args{auto_save = Int}; repl({auto_save, infinity}, Defs) -> Defs#open_args{auto_save =infinity}; repl({cache_size, Int}, Defs) when is_integer(Int), Int >= 0 -> Defs; repl({cache_size, infinity}, Defs) -> Defs; repl({delayed_write, default}, Defs) -> Defs#open_args{delayed_write = ?DEFAULT_CACHE}; repl({delayed_write, {Delay,Size} = C}, Defs) when is_integer(Delay), Delay >= 0, is_integer(Size), Size >= 0 -> Defs#open_args{delayed_write = C}; repl({estimated_no_objects, I}, Defs) -> repl({min_no_slots, I}, Defs); repl({file, File}, Defs) -> Defs#open_args{file = to_list(File)}; repl({keypos, P}, Defs) when is_integer(P), P > 0 -> Defs#open_args{keypos =P}; repl({max_no_slots, I}, Defs) -> Version 9 only . MaxSlots = is_max_no_slots(I), Defs#open_args{max_no_slots = MaxSlots}; repl({min_no_slots, I}, Defs) -> MinSlots = is_min_no_slots(I), Defs#open_args{min_no_slots = MinSlots}; repl({ram_file, Bool}, Defs) -> mem(Bool, [true, false]), Defs#open_args{ram_file = Bool}; repl({repair, T}, Defs) -> mem(T, [true, false, force]), Defs#open_args{repair = T}; repl({type, T}, Defs) -> mem(T, [set, bag, duplicate_bag]), Defs#open_args{type =T}; repl({version, Version}, Defs) -> V = is_version(Version), Defs#open_args{version = V}; repl({debug, Bool}, Defs) -> mem(Bool, [true, false]), Defs#open_args{debug = Bool}; repl({_, _}, _) -> exit(badarg). is_min_no_slots(default) -> default; is_min_no_slots(I) when is_integer(I), I >= ?DEFAULT_MIN_NO_SLOTS -> I; is_min_no_slots(I) when is_integer(I), I >= 0 -> ?DEFAULT_MIN_NO_SLOTS. is_max_no_slots(default) -> default; is_max_no_slots(I) when is_integer(I), I > 0, I < 1 bsl 31 -> I. is_comp_min_max(Defs) -> #open_args{max_no_slots = Max, min_no_slots = Min, version = V} = Defs, case V of _ when Min =:= default -> Defs; _ when Max =:= default -> Defs; _ -> true = Min =< Max, Defs end. is_version(default) -> default; is_version(8) -> 8; is_version(9) -> 9. mem(X, L) -> case lists:member(X, L) of true -> true; false -> exit(badarg) end. options(Options, Keys) when is_list(Options) -> options(Options, Keys, []); options(Option, Keys) -> options([Option], Keys, []). options(Options, [Key | Keys], L) when is_list(Options) -> V = case lists:keysearch(Key, 1, Options) of {value, {format, Format}} when Format =:= term; Format =:= bchunk -> {ok, Format}; {value, {min_no_slots, I}} -> case catch is_min_no_slots(I) of {'EXIT', _} -> badarg; MinNoSlots -> {ok, MinNoSlots} end; {value, {n_objects, default}} -> {ok, default_option(Key)}; {value, {n_objects, NObjs}} when is_integer(NObjs), NObjs >= 1 -> {ok, NObjs}; {value, {traverse, select}} -> {ok, select}; {value, {traverse, {select, MS}}} -> {ok, {select, MS}}; {value, {traverse, first_next}} -> {ok, first_next}; {value, {Key, _}} -> badarg; false -> Default = default_option(Key), {ok, Default} end, case V of badarg -> {badarg, Key}; {ok, Value} -> NewOptions = lists:keydelete(Key, 1, Options), options(NewOptions, Keys, [Value | L]) end; options([], [], L) -> lists:reverse(L); options(Options, _, _L) -> {badarg,Options}. default_option(format) -> term; default_option(min_no_slots) -> default; default_option(traverse) -> select; default_option(n_objects) -> default. listify(L) when is_list(L) -> L; listify(T) -> [T]. treq(Tab, R) -> case catch dets_server:get_pid(Tab) of Pid when is_pid(Pid) -> req(Pid, R); _ -> badarg end. req(Proc, R) -> Ref = erlang:monitor(process, Proc), Proc ! ?DETS_CALL(self(), R), receive {'DOWN', Ref, process, Proc, _Info} -> badarg; {Proc, Reply} -> erlang:demonitor(Ref), receive {'DOWN', Ref, process, Proc, _Reason} -> Reply after 0 -> Reply end end. Inlined . einval({error, {file_error, _, einval}}, A) -> erlang:error(badarg, A); einval({error, {file_error, _, badarg}}, A) -> erlang:error(badarg, A); einval(Reply, _A) -> Reply. Inlined . badarg(badarg, A) -> erlang:error(badarg, A); badarg(Reply, _A) -> Reply. Inlined . undefined(badarg) -> undefined; undefined(Reply) -> Reply. Inlined . badarg_exit(badarg, A) -> erlang:error(badarg, A); badarg_exit({ok, Reply}, _A) -> Reply; badarg_exit(Reply, _A) -> exit(Reply). init(Parent, Server) -> process_flag(trap_exit, true), open_file_loop(#head{parent = Parent, server = Server}). open_file_loop(Head) -> open_file_loop(Head, 0). open_file_loop(Head, N) when element(1, Head#head.update_mode) =:= error -> open_file_loop2(Head, N); open_file_loop(Head, N) -> receive When the table is fixed it can be assumed that at least one traversal is in progress . To speed the traversal up three - prioritize match_init , bchunk , next , and ; ?DETS_CALL(From, {match_init, _State} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {bchunk, _State} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {next, _Key} = Op) -> do_apply_op(Op, From, Head, N); ?DETS_CALL(From, {match_delete_init, _MP, _Spec} = Op) -> do_apply_op(Op, From, Head, N); {'EXIT', Pid, Reason} when Pid =:= Head#head.parent -> _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, Reason} when Pid =:= Head#head.server -> _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, _Reason} -> H2 = remove_fix(Head, Pid, close), open_file_loop(H2, N); {system, From, Req} -> sys:handle_system_msg(Req, From, Head#head.parent, ?MODULE, [], Head) after 0 -> open_file_loop2(Head, N) end. open_file_loop2(Head, N) -> receive ?DETS_CALL(From, Op) -> do_apply_op(Op, From, Head, N); {'EXIT', Pid, Reason} when Pid =:= Head#head.parent -> _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, Reason} when Pid =:= Head#head.server -> _NewHead = do_stop(Head), exit(Reason); {'EXIT', Pid, _Reason} -> H2 = remove_fix(Head, Pid, close), open_file_loop(H2, N); {system, From, Req} -> sys:handle_system_msg(Req, From, Head#head.parent, ?MODULE, [], Head); Message -> error_logger:format("** dets: unexpected message" "(ignored): ~w~n", [Message]), open_file_loop(Head, N) end. do_apply_op(Op, From, Head, N) -> try apply_op(Op, From, Head, N) of ok -> open_file_loop(Head, N); {N2, H2} when is_record(H2, head), is_integer(N2) -> open_file_loop(H2, N2); H2 when is_record(H2, head) -> open_file_loop(H2, N) catch exit:normal -> exit(normal); _:Bad -> Name = Head#head.name, case dets_utils:debug_mode() of true -> If stream_op/5 found more requests , this is not error_logger:format ("** dets: Bug was found when accessing table ~w,~n" "** dets: operation was ~p and reply was ~w.~n" "** dets: Stacktrace: ~w~n", [Name, Op, Bad, erlang:get_stacktrace()]); false -> error_logger:format ("** dets: Bug was found when accessing table ~w~n", [Name]) end, if From =/= self() -> From ! {self(), {error, {dets_bug, Name, Op, Bad}}}; auto_save | may_grow | , _ } ok end, open_file_loop(Head, N) end. apply_op(Op, From, Head, N) -> case Op of {add_user, Tab, OpenArgs}-> #open_args{file = Fname, type = Type, keypos = Keypos, ram_file = Ram, access = Access, version = Version} = OpenArgs, VersionOK = (Version =:= default) or (Head#head.version =:= Version), Res = if Tab =:= Head#head.name, Head#head.keypos =:= Keypos, Head#head.type =:= Type, Head#head.ram_file =:= Ram, Head#head.access =:= Access, VersionOK, Fname =:= Head#head.filename -> ok; true -> err({error, incompatible_arguments}) end, From ! {self(), Res}, ok; auto_save -> case Head#head.update_mode of saved -> Head; {error, _Reason} -> Head; dets_utils:vformat("** dets: Auto save of ~p\n", [Head#head.name]), {NewHead, _Res} = perform_save(Head, true), erlang:garbage_collect(), {0, NewHead}; dirty -> start_auto_save_timer(Head), {0, Head} end; close -> From ! {self(), fclose(Head)}, _NewHead = unlink_fixing_procs(Head), ?PROFILE(ep:done()), exit(normal); {close, Pid} -> Used from dets_server when Pid has closed the table , NewHead = remove_fix(Head, Pid, close), From ! {self(), status(NewHead)}, NewHead; {corrupt, Reason} -> {H2, Error} = dets_utils:corrupt_reason(Head, Reason), From ! {self(), Error}, H2; {delayed_write, WrTime} -> delayed_write(Head, WrTime); info -> {H2, Res} = finfo(Head), From ! {self(), Res}, H2; {info, Tag} -> {H2, Res} = finfo(Head, Tag), From ! {self(), Res}, H2; {is_compatible_bchunk_format, Term} -> Res = test_bchunk_format(Head, Term), From ! {self(), Res}, ok; {internal_open, Ref, Args} -> ?PROFILE(ep:do()), case do_open_file(Args, Head#head.parent, Head#head.server,Ref) of {ok, H2} -> From ! {self(), ok}, H2; Error -> From ! {self(), Error}, exit(normal) end; may_grow when Head#head.update_mode =/= saved -> if Head#head.update_mode =:= dirty -> {H2, _Res} = (Head#head.mod):may_grow(Head, 0, many_times), {N + 1, H2}; true -> ok end; {set_verbose, What} -> set_verbose(What), From ! {self(), ok}, ok; {where, Object} -> {H2, Res} = where_is_object(Head, Object), From ! {self(), Res}, H2; _Message when element(1, Head#head.update_mode) =:= error -> From ! {self(), status(Head)}, ok; {bchunk_init, Tab} -> {H2, Res} = do_bchunk_init(Head, Tab), From ! {self(), Res}, H2; {bchunk, State} -> {H2, Res} = do_bchunk(Head, State), From ! {self(), Res}, H2; delete_all_objects -> {H2, Res} = fdelete_all_objects(Head), From ! {self(), Res}, erlang:garbage_collect(), {0, H2}; {delete_key, Keys} when Head#head.update_mode =:= dirty -> if Head#head.version =:= 8 -> {H2, Res} = fdelete_key(Head, Keys), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N) end; {delete_object, Objs} when Head#head.update_mode =:= dirty -> case check_objects(Objs, Head#head.keypos) of true when Head#head.version =:= 8 -> {H2, Res} = fdelete_object(Head, Objs), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N); false -> From ! {self(), badarg}, ok end; first -> {H2, Res} = ffirst(Head), From ! {self(), Res}, H2; {initialize, InitFun, Format, MinNoSlots} -> {H2, Res} = finit(Head, InitFun, Format, MinNoSlots), From ! {self(), Res}, erlang:garbage_collect(), H2; {insert, Objs} when Head#head.update_mode =:= dirty -> case check_objects(Objs, Head#head.keypos) of true when Head#head.version =:= 8 -> {H2, Res} = finsert(Head, Objs), From ! {self(), Res}, {N + 1, H2}; true -> stream_op(Op, From, [], Head, N); false -> From ! {self(), badarg}, ok end; {insert_new, Objs} when Head#head.update_mode =:= dirty -> {H2, Res} = finsert_new(Head, Objs), From ! {self(), Res}, {N + 1, H2}; {lookup_keys, Keys} when Head#head.version =:= 8 -> {H2, Res} = flookup_keys(Head, Keys), From ! {self(), Res}, H2; {lookup_keys, _Keys} -> stream_op(Op, From, [], Head, N); {match_init, State} -> {H2, Res} = fmatch_init(Head, State), From ! {self(), Res}, H2; {match, MP, Spec, NObjs} -> {H2, Res} = fmatch(Head, MP, Spec, NObjs), From ! {self(), Res}, H2; {member, Key} when Head#head.version =:= 8 -> {H2, Res} = fmember(Head, Key), From ! {self(), Res}, H2; {member, _Key} = Op -> stream_op(Op, From, [], Head, N); {next, Key} -> {H2, Res} = fnext(Head, Key), From ! {self(), Res}, H2; {match_delete, State} when Head#head.update_mode =:= dirty -> {H2, Res} = fmatch_delete(Head, State), From ! {self(), Res}, {N + 1, H2}; {match_delete_init, MP, Spec} when Head#head.update_mode =:= dirty -> {H2, Res} = fmatch_delete_init(Head, MP, Spec), From ! {self(), Res}, {N + 1, H2}; {safe_fixtable, Bool} -> NewHead = do_safe_fixtable(Head, From, Bool), From ! {self(), ok}, NewHead; {slot, Slot} -> {H2, Res} = fslot(Head, Slot), From ! {self(), Res}, H2; sync -> {NewHead, Res} = perform_save(Head, true), From ! {self(), Res}, erlang:garbage_collect(), {0, NewHead}; {update_counter, Key, Incr} when Head#head.update_mode =:= dirty -> {NewHead, Res} = do_update_counter(Head, Key, Incr), From ! {self(), Res}, {N + 1, NewHead}; WriteOp when Head#head.update_mode =:= new_dirty -> H2 = Head#head{update_mode = dirty}, apply_op(WriteOp, From, H2, 0); WriteOp when Head#head.access =:= read_write, Head#head.update_mode =:= saved -> case catch (Head#head.mod):mark_dirty(Head) of ok -> start_auto_save_timer(Head), H2 = Head#head{update_mode = dirty}, apply_op(WriteOp, From, H2, 0); {NewHead, Error} when is_record(NewHead, head) -> From ! {self(), Error}, NewHead end; WriteOp when is_tuple(WriteOp), Head#head.access =:= read -> Reason = {access_mode, Head#head.filename}, From ! {self(), err({error, Reason})}, ok end. start_auto_save_timer(Head) when Head#head.auto_save =:= infinity -> ok; start_auto_save_timer(Head) -> Millis = Head#head.auto_save, erlang:send_after(Millis, self(), ?DETS_CALL(self(), auto_save)). Version 9 : the message queue and try to evaluate several lookup requests in parallel . , delete and stream_op(Op, Pid, Pids, Head, N) -> stream_op(Head, Pids, [], N, Pid, Op, Head#head.fixed). stream_loop(Head, Pids, C, N, false = Fxd) -> receive ?DETS_CALL(From, Message) -> stream_op(Head, Pids, C, N, From, Message, Fxd) after 0 -> stream_end(Head, Pids, C, N, no_more) end; stream_loop(Head, Pids, C, N, _Fxd) -> stream_end(Head, Pids, C, N, no_more). stream_op(Head, Pids, C, N, Pid, {lookup_keys,Keys}, Fxd) -> NC = [{{lookup,Pid},Keys} | C], stream_loop(Head, Pids, NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {insert, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {insert_new, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {delete_key, _Keys} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {delete_object, _Objects} = Op, Fxd) -> NC = [Op | C], stream_loop(Head, [Pid | Pids], NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, {member, Key}, Fxd) -> NC = [{{lookup,[Pid]},[Key]} | C], stream_loop(Head, Pids, NC, N, Fxd); stream_op(Head, Pids, C, N, Pid, Op, _Fxd) -> stream_end(Head, Pids, C, N, {Pid,Op}). stream_end(Head, Pids0, C, N, Next) -> case catch update_cache(Head, lists:reverse(C)) of {Head1, [], PwriteList} -> stream_end1(Pids0, Next, N, C, Head1, PwriteList); {Head1, Found, PwriteList} -> lookup_replies(Found), stream_end1(Pids0, Next, N, C, Head1, PwriteList); Head1 when is_record(Head1, head) -> stream_end2(Pids0, Pids0, Next, N, C, Head1, ok); {Head1, Error} when is_record(Head1, head) -> Fun = fun({{lookup,[Pid]},_Keys}, L) -> [Pid | L]; ({{lookup,Pid},_Keys}, L) -> [Pid | L]; (_, L) -> L end, LPs0 = lists:foldl(Fun, [], C), LPs = lists:usort(lists:flatten(LPs0)), stream_end2(Pids0 ++ LPs, Pids0, Next, N, C, Head1, Error); DetsError -> throw(DetsError) end. stream_end1(Pids, Next, N, C, Head, []) -> stream_end2(Pids, Pids, Next, N, C, Head, ok); stream_end1(Pids, Next, N, C, Head, PwriteList) -> {Head1, PR} = (catch dets_utils:pwrite(Head, PwriteList)), stream_end2(Pids, Pids, Next, N, C, Head1, PR). stream_end2([Pid | Pids], Ps, Next, N, C, Head, Reply) -> Pid ! {self(), Reply}, stream_end2(Pids, Ps, Next, N+1, C, Head, Reply); stream_end2([], Ps, no_more, N, C, Head, _Reply) -> penalty(Head, Ps, C), {N, Head}; stream_end2([], _Ps, {From, Op}, N, _C, Head, _Reply) -> apply_op(Op, From, Head, N). penalty(H, _Ps, _C) when H#head.fixed =:= false -> ok; penalty(_H, _Ps, [{{lookup,_Pids},_Keys}]) -> ok; penalty(#head{fixed = {_,[{Pid,_}]}}, [Pid], _C) -> ok; penalty(_H, _Ps, _C) -> timer:sleep(1). lookup_replies([{P,O}]) -> lookup_reply(P, O); lookup_replies(Q) -> [{P,O} | L] = dets_utils:family(Q), lookup_replies(P, lists:append(O), L). lookup_replies(P, O, []) -> lookup_reply(P, O); lookup_replies(P, O, [{P2,O2} | L]) -> lookup_reply(P, O), lookup_replies(P2, lists:append(O2), L). If a list of Pid then op was { member , Key } . Inlined . lookup_reply([P], O) -> P ! {self(), O =/= []}; lookup_reply(P, O) -> P ! {self(), O}. system_continue(_Parent, _, Head) -> open_file_loop(Head). system_terminate(Reason, _Parent, _, Head) -> _NewHead = do_stop(Head), exit(Reason). system_code_change(State, _Module, _OldVsn, _Extra) -> {ok, State}. Internal functions constants(FH, FileName) -> Version = FH#fileheader.version, if Version =< 8 -> dets_v8:constants(); Version =:= 9 -> dets_v9:constants(); true -> throw({error, {not_a_dets_file, FileName}}) end. - > { ok , Fd , fileheader ( ) } | throw(Error ) read_file_header(FileName, Access, RamFile) -> BF = if RamFile -> case file:read_file(FileName) of {ok, B} -> B; Err -> dets_utils:file_error(FileName, Err) end; true -> FileName end, {ok, Fd} = dets_utils:open(BF, open_args(Access, RamFile)), {ok, <<Version:32>>} = dets_utils:pread_close(Fd, FileName, ?FILE_FORMAT_VERSION_POS, 4), if Version =< 8 -> dets_v8:read_file_header(Fd, FileName); Version =:= 9 -> dets_v9:read_file_header(Fd, FileName); true -> throw({error, {not_a_dets_file, FileName}}) end. fclose(Head) -> {Head1, Res} = perform_save(Head, false), case Head1#head.ram_file of true -> ignore; false -> dets_utils:stop_disk_map(), file:close(Head1#head.fptr) end, Res. - > { NewHead , Res } perform_save(Head, DoSync) when Head#head.update_mode =:= dirty; Head#head.update_mode =:= new_dirty -> case catch begin {Head1, []} = write_cache(Head), {Head2, ok} = (Head1#head.mod):do_perform_save(Head1), ok = ensure_written(Head2, DoSync), {Head2#head{update_mode = saved}, ok} end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end; perform_save(Head, _DoSync) -> {Head, status(Head)}. ensure_written(Head, DoSync) when Head#head.ram_file -> {ok, EOF} = dets_utils:position(Head, eof), {ok, Bin} = dets_utils:pread(Head, 0, EOF, 0), if DoSync -> dets_utils:write_file(Head, Bin); not DoSync -> case file:write_file(Head#head.filename, Bin) of ok -> ok; Error -> dets_utils:corrupt_file(Head, Error) end end; ensure_written(Head, true) when not Head#head.ram_file -> dets_utils:sync(Head); ensure_written(Head, false) when not Head#head.ram_file -> ok. - > { NewHead , { cont ( ) , [ binary ( ) ] } } | { NewHead , Error } do_bchunk_init(Head, Tab) -> case catch write_cache(Head) of {H2, []} -> case (H2#head.mod):table_parameters(H2) of undefined -> {H2, {error, old_version}}; Parms -> L = dets_utils:all_allocated(H2), C0 = #dets_cont{no_objs = default, bin = <<>>, alloc = L}, BinParms = term_to_binary(Parms), {H2, {C0#dets_cont{tab = Tab, what = bchunk}, [BinParms]}} end; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , { cont ( ) , [ binary ( ) ] } } | { NewHead , Error } do_bchunk(Head, State) -> case dets_v9:read_bchunks(Head, State#dets_cont.alloc) of {error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {finished, Bins} -> {Head, {State#dets_cont{bin = eof}, Bins}}; {Bins, NewL} -> {Head, {State#dets_cont{alloc = NewL}, Bins}} end. - > { NewHead , Result } fdelete_all_objects(Head) when Head#head.fixed =:= false -> case catch do_delete_all_objects(Head) of {ok, NewHead} -> start_auto_save_timer(NewHead), {NewHead, ok}; {error, Reason} -> dets_utils:corrupt_reason(Head, Reason) end; fdelete_all_objects(Head) -> {Head, fixed}. do_delete_all_objects(Head) -> #head{fptr = Fd, name = Tab, filename = Fname, type = Type, keypos = Kp, ram_file = Ram, auto_save = Auto, min_no_slots = MinSlots, max_no_slots = MaxSlots, cache = Cache} = Head, CacheSz = dets_utils:cache_size(Cache), ok = dets_utils:truncate(Fd, Fname, bof), (Head#head.mod):initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, true). - > { NewHead , Reply } , Reply = ok | Error . fdelete_key(Head, Keys) -> do_delete(Head, Keys, delete_key). - > { NewHead , Reply } , Reply = ok | badarg | Error . fdelete_object(Head, Objects) -> do_delete(Head, Objects, delete_object). ffirst(H) -> Ref = make_ref(), case catch {Ref, ffirst1(H)} of {Ref, {NH, R}} -> {NH, {ok, R}}; {NH, R} when is_record(NH, head) -> {NH, {error, R}} end. ffirst1(H) -> check_safe_fixtable(H), {NH, []} = write_cache(H), ffirst(NH, 0). ffirst(H, Slot) -> case (H#head.mod):slot_objs(H, Slot) of '$end_of_table' -> {H, '$end_of_table'}; [] -> ffirst(H, Slot+1); [X|_] -> {H, element(H#head.keypos, X)} end. - > { NewHead , Reply } , Reply = ok | badarg | Error . finsert(Head, Objects) -> case catch update_cache(Head, Objects, insert) of {NewHead, []} -> {NewHead, ok}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , Reply } , Reply = ok | badarg | Error . finsert_new(Head, Objects) -> KeyPos = Head#head.keypos, case catch lists:map(fun(Obj) -> element(KeyPos, Obj) end, Objects) of Keys when is_list(Keys) -> case catch update_cache(Head, Keys, {lookup, nopid}) of {Head1, PidObjs} when is_list(PidObjs) -> case lists:all(fun({_P,OL}) -> OL =:= [] end, PidObjs) of true -> case catch update_cache(Head1, Objects, insert) of {NewHead, []} -> {NewHead, true}; {NewHead, Error} when is_record(NewHead, head) -> {NewHead, Error} end; false=Reply -> {Head1, Reply} end; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; _ -> {Head, badarg} end. do_safe_fixtable(Head, Pid, true) -> case Head#head.fixed of false -> link(Pid), Fixed = {erlang:now(), [{Pid, 1}]}, Ftab = dets_utils:get_freelists(Head), Head#head{fixed = Fixed, freelists = {Ftab, Ftab}}; {TimeStamp, Counters} -> case lists:keysearch(Pid, 1, Counters) of when Counter > 1 NewCounters = lists:keyreplace(Pid, 1, Counters, {Pid, Counter+1}), Head#head{fixed = {TimeStamp, NewCounters}}; false -> link(Pid), Fixed = {TimeStamp, [{Pid, 1} | Counters]}, Head#head{fixed = Fixed} end end; do_safe_fixtable(Head, Pid, false) -> remove_fix(Head, Pid, false). remove_fix(Head, Pid, How) -> case Head#head.fixed of false -> Head; {TimeStamp, Counters} -> case lists:keysearch(Pid, 1, Counters) of How = : = close when Pid closes the table . {value, {Pid, Counter}} when Counter =:= 1; How =:= close -> unlink(Pid), case lists:keydelete(Pid, 1, Counters) of [] -> check_growth(Head), erlang:garbage_collect(), Head#head{fixed = false, freelists = dets_utils:get_freelists(Head)}; NewCounters -> Head#head{fixed = {TimeStamp, NewCounters}} end; {value, {Pid, Counter}} -> NewCounters = lists:keyreplace(Pid, 1, Counters, {Pid, Counter-1}), Head#head{fixed = {TimeStamp, NewCounters}}; false -> Head end end. do_stop(Head) -> unlink_fixing_procs(Head), fclose(Head). unlink_fixing_procs(Head) -> case Head#head.fixed of false -> Head; {_, Counters} -> lists:map(fun({Pid, _Counter}) -> unlink(Pid) end, Counters), Head#head{fixed = false, freelists = dets_utils:get_freelists(Head)} end. check_growth(#head{access = read}) -> ok; check_growth(Head) -> NoThings = no_things(Head), if NoThings > Head#head.next -> erlang:send_after(200, self(), true -> ok end. finfo(H) -> case catch write_cache(H) of {H2, []} -> Info = (catch [{type, H2#head.type}, {keypos, H2#head.keypos}, {size, H2#head.no_objects}, {file_size, file_size(H2#head.fptr, H2#head.filename)}, {filename, H2#head.filename}]), {H2, Info}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end. finfo(H, access) -> {H, H#head.access}; finfo(H, auto_save) -> {H, H#head.auto_save}; finfo(H, bchunk_format) -> case catch write_cache(H) of {H2, []} -> case (H2#head.mod):table_parameters(H2) of undefined = Undef -> {H2, Undef}; Parms -> {H2, term_to_binary(Parms)} end; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; {H, dets_utils:cache_size(H#head.cache)}; finfo(H, filename) -> {H, H#head.filename}; finfo(H, file_size) -> case catch write_cache(H) of {H2, []} -> {H2, catch file_size(H#head.fptr, H#head.filename)}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, fixed) -> {H, not (H#head.fixed =:= false)}; finfo(H, hash) -> {H, H#head.hash_bif}; finfo(H, keypos) -> {H, H#head.keypos}; finfo(H, memory) -> finfo(H, file_size); finfo(H, no_objects) -> finfo(H, size); finfo(H, no_keys) -> case catch write_cache(H) of {H2, []} -> {H2, H2#head.no_keys}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, no_slots) -> {H, (H#head.mod):no_slots(H)}; finfo(H, pid) -> {H, self()}; finfo(H, ram_file) -> {H, H#head.ram_file}; finfo(H, safe_fixed) -> {H, H#head.fixed}; finfo(H, size) -> case catch write_cache(H) of {H2, []} -> {H2, H2#head.no_objects}; {H2, _} = HeadError when is_record(H2, head) -> HeadError end; finfo(H, type) -> {H, H#head.type}; finfo(H, version) -> {H, H#head.version}; finfo(H, _) -> {H, undefined}. file_size(Fd, FileName) -> {ok, Pos} = dets_utils:position(Fd, FileName, eof), Pos. test_bchunk_format(_Head, undefined) -> false; test_bchunk_format(Head, _Term) when Head#head.version =:= 8 -> false; test_bchunk_format(Head, Term) -> dets_v9:try_bchunk_header(Term, Head) =/= not_ok. do_open_file([Fname, Verbose], Parent, Server, Ref) -> case catch fopen2(Fname, Ref) of {error, _Reason} = Error -> err(Error); {ok, Head} -> maybe_put(verbose, Verbose), {ok, Head#head{parent = Parent, server = Server}}; {'EXIT', _Reason} = Error -> Error; Bad -> error_logger:format ("** dets: Bug was found in open_file/1, reply was ~w.~n", [Bad]), {error, {dets_bug, Fname, Bad}} end; do_open_file([Tab, OpenArgs, Verb], Parent, Server, Ref) -> case catch fopen3(Tab, OpenArgs) of {error, {tooshort, _}} -> file:delete(OpenArgs#open_args.file), do_open_file([Tab, OpenArgs, Verb], Parent, Server, Ref); {error, _Reason} = Error -> err(Error); {ok, Head} -> maybe_put(verbose, Verb), {ok, Head#head{parent = Parent, server = Server}}; {'EXIT', _Reason} = Error -> Error; Bad -> error_logger:format ("** dets: Bug was found in open_file/2, arguments were~n" "** dets: ~w and reply was ~w.~n", [OpenArgs, Bad]), {error, {dets_bug, Tab, {open_file, OpenArgs}, Bad}} end. maybe_put(_, undefined) -> ignore; maybe_put(K, V) -> put(K, V). finit(Head, InitFun, _Format, _NoSlots) when Head#head.access =:= read -> _ = (catch InitFun(close)), {Head, {error, {access_mode, Head#head.filename}}}; finit(Head, InitFun, _Format, _NoSlots) when Head#head.fixed =/= false -> _ = (catch InitFun(close)), {Head, {error, {fixed_table, Head#head.name}}}; finit(Head, InitFun, Format, NoSlots) -> case catch do_finit(Head, InitFun, Format, NoSlots) of {ok, NewHead} -> check_growth(NewHead), start_auto_save_timer(NewHead), {NewHead, ok}; badarg -> {Head, badarg}; Error -> dets_utils:corrupt(Head, Error) end. do_finit(Head, Init, Format, NoSlots) -> #head{fptr = Fd, type = Type, keypos = Kp, auto_save = Auto, cache = Cache, filename = Fname, ram_file = Ram, min_no_slots = MinSlots0, max_no_slots = MaxSlots, name = Tab, update_mode = UpdateMode, mod = HMod} = Head, CacheSz = dets_utils:cache_size(Cache), {How, Head1} = case Format of term when is_integer(NoSlots), NoSlots > MaxSlots -> throw(badarg); term -> MinSlots = choose_no_slots(NoSlots, MinSlots0), if UpdateMode =:= new_dirty, MinSlots =:= MinSlots0 -> {general_init, Head}; true -> ok = dets_utils:truncate(Fd, Fname, bof), {ok, H} = HMod:initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, false), {general_init, H} end; bchunk -> ok = dets_utils:truncate(Fd, Fname, bof), {bchunk_init, Head} end, case How of bchunk_init -> case HMod:bchunk_init(Head1, Init) of {ok, NewHead} -> {ok, NewHead#head{update_mode = dirty}}; Error -> Error end; general_init -> Cntrs = ets:new(dets_init, []), Input = HMod:bulk_input(Head1, Init, Cntrs), SlotNumbers = {Head1#head.min_no_slots, bulk_init, MaxSlots}, {Reply, SizeData} = do_sort(Head1, SlotNumbers, Input, Cntrs, Fname, not_used), Bulk = true, case Reply of {ok, NoDups, H1} -> fsck_copy(SizeData, H1, Bulk, NoDups); Else -> close_files(Bulk, SizeData, Head1), Else end end. - > { NewHead , [ LookedUpObject ] } | { NewHead , Error } flookup_keys(Head, Keys) -> case catch update_cache(Head, Keys, {lookup, nopid}) of {NewHead, [{_NoPid,Objs}]} -> {NewHead, Objs}; {NewHead, L} when is_list(L) -> {NewHead, lists:flatmap(fun({_Pid,OL}) -> OL end, L)}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. - > { NewHead , Result } fmatch_init(Head, C) -> case scan(Head, C) of {scan_error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {Ts, NC} -> {Head, {cont, {Ts, NC}}} end. - > { NewHead , Result } fmatch(Head, MP, Spec, N) -> KeyPos = Head#head.keypos, case find_all_keys(Spec, KeyPos, []) of [] -> Complete match case catch write_cache(Head) of {NewHead, []} -> C0 = init_scan(NewHead, N), {NewHead, {cont, C0#dets_cont{match_program = MP}}}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; List -> Keys = lists:usort(List), {NewHead, Reply} = flookup_keys(Head, Keys), case Reply of Objs when is_list(Objs) -> MatchingObjs = ets:match_spec_run(Objs, MP), {NewHead, {done, MatchingObjs}}; Error -> {NewHead, Error} end end. find_all_keys([], _, Ks) -> Ks; find_all_keys([{H,_,_} | T], KeyPos, Ks) when is_tuple(H) -> case tuple_size(H) of Enough when Enough >= KeyPos -> Key = element(KeyPos, H), case contains_variable(Key) of true -> []; false -> find_all_keys(T, KeyPos, [Key | Ks]) end; _ -> find_all_keys(T, KeyPos, Ks) end; find_all_keys(_, _, _) -> []. contains_variable('_') -> true; contains_variable(A) when is_atom(A) -> case atom_to_list(A) of [$$ | T] -> case (catch list_to_integer(T)) of {'EXIT', _} -> false; _ -> true end; _ -> false end; contains_variable(T) when is_tuple(T) -> contains_variable(tuple_to_list(T)); contains_variable([]) -> false; contains_variable([H|T]) -> case contains_variable(H) of true -> true; false -> contains_variable(T) end; contains_variable(_) -> false. - > { NewHead , Res } fmatch_delete_init(Head, MP, Spec) -> KeyPos = Head#head.keypos, case catch case find_all_keys(Spec, KeyPos, []) of [] -> do_fmatch_delete_var_keys(Head, MP, Spec); List -> Keys = lists:usort(List), do_fmatch_constant_keys(Head, Keys, MP) end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end. - > { NewHead , Res } fmatch_delete(Head, C) -> case scan(Head, C) of {scan_error, Reason} -> dets_utils:corrupt_reason(Head, Reason); {[], _} -> {Head, {done, 0}}; {RTs, NC} -> MP = C#dets_cont.match_program, case catch filter_binary_terms(RTs, MP, []) of {'EXIT', _} -> Bad = dets_utils:bad_object(fmatch_delete, RTs), dets_utils:corrupt_reason(Head, Bad); Terms -> do_fmatch_delete(Head, Terms, NC) end end. do_fmatch_delete_var_keys(Head, _MP, ?PATTERN_TO_TRUE_MATCH_SPEC('_')) when Head#head.fixed =:= false -> {Head1, []} = write_cache(Head), N = Head1#head.no_objects, case fdelete_all_objects(Head1) of {NewHead, ok} -> {NewHead, {done, N}}; Reply -> Reply end; do_fmatch_delete_var_keys(Head, MP, _Spec) -> {NewHead, []} = write_cache(Head), C0 = init_scan(NewHead, default), {NewHead, {cont, C0#dets_cont{match_program = MP}, 0}}. do_fmatch_constant_keys(Head, Keys, MP) -> case flookup_keys(Head, Keys) of {NewHead, ReadTerms} when is_list(ReadTerms) -> Terms = filter_terms(ReadTerms, MP, []), do_fmatch_delete(NewHead, Terms, fixed); Reply -> Reply end. filter_binary_terms([Bin | Bins], MP, L) -> Term = binary_to_term(Bin), case ets:match_spec_run([Term], MP) of [true] -> filter_binary_terms(Bins, MP, [Term | L]); _ -> filter_binary_terms(Bins, MP, L) end; filter_binary_terms([], _MP, L) -> L. filter_terms([Term | Terms], MP, L) -> case ets:match_spec_run([Term], MP) of [true] -> filter_terms(Terms, MP, [Term | L]); _ -> filter_terms(Terms, MP, L) end; filter_terms([], _MP, L) -> L. do_fmatch_delete(Head, Terms, What) -> N = length(Terms), case do_delete(Head, Terms, delete_object) of {NewHead, ok} when What =:= fixed -> {NewHead, {done, N}}; {NewHead, ok} -> {NewHead, {cont, What, N}}; Reply -> Reply end. do_delete(Head, Things, What) -> case catch update_cache(Head, Things, What) of {NewHead, []} -> {NewHead, ok}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. fmember(Head, Key) -> case catch begin {Head2, [{_NoPid,Objs}]} = update_cache(Head, [Key], {lookup, nopid}), {Head2, Objs =/= []} end of {NewHead, _} = Reply when is_record(NewHead, head) -> Reply end. fnext(Head, Key) -> Slot = (Head#head.mod):db_hash(Key, Head), Ref = make_ref(), case catch {Ref, fnext(Head, Key, Slot)} of {Ref, {H, R}} -> {H, {ok, R}}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end. fnext(H, Key, Slot) -> {NH, []} = write_cache(H), case (H#head.mod):slot_objs(NH, Slot) of '$end_of_table' -> {NH, '$end_of_table'}; L -> fnext_search(NH, Key, Slot, L) end. fnext_search(H, K, Slot, L) -> Kp = H#head.keypos, case beyond_key(K, Kp, L) of [] -> fnext_slot(H, K, Slot+1); L2 -> {H, element(H#head.keypos, hd(L2))} end. fnext_slot(H, K, Slot) -> case (H#head.mod):slot_objs(H, Slot) of '$end_of_table' -> {H, '$end_of_table'}; [] -> fnext_slot(H, K, Slot+1); L -> {H, element(H#head.keypos, hd(L))} end. beyond_key(_K, _Kp, []) -> []; beyond_key(K, Kp, [H|T]) -> case dets_utils:cmp(element(Kp, H), K) of 0 -> beyond_key2(K, Kp, T); _ -> beyond_key(K, Kp, T) end. beyond_key2(_K, _Kp, []) -> []; beyond_key2(K, Kp, [H|T]=L) -> case dets_utils:cmp(element(Kp, H), K) of 0 -> beyond_key2(K, Kp, T); _ -> L end. fopen2(Fname, Tab) -> case file:read_file_info(Fname) of {ok, _} -> Acc = read_write, Ram = false, {ok, Fd, FH} = read_file_header(Fname, Acc, Ram), Mod = FH#fileheader.mod, case Mod:check_file_header(FH, Fd) of {error, not_closed} -> io:format(user,"dets: file ~p not properly closed, " "repairing ...~n", [Fname]), Version = default, case fsck(Fd, Tab, Fname, FH, default, default, Version) of ok -> fopen2(Fname, Tab); Error -> throw(Error) end; {ok, Head, ExtraInfo} -> open_final(Head, Fname, Acc, Ram, ?DEFAULT_CACHE, Tab, ExtraInfo, false); {error, Reason} -> throw({error, {Reason, Fname}}) end; Error -> dets_utils:file_error(Fname, Error) end. fopen3(Tab, OpenArgs) -> FileName = OpenArgs#open_args.file, case file:read_file_info(FileName) of {ok, _} -> fopen_existing_file(Tab, OpenArgs); Error when OpenArgs#open_args.access =:= read -> dets_utils:file_error(FileName, Error); _Error -> fopen_init_file(Tab, OpenArgs) end. fopen_existing_file(Tab, OpenArgs) -> #open_args{file = Fname, type = Type, keypos = Kp, repair = Rep, min_no_slots = MinSlots, max_no_slots = MaxSlots, ram_file = Ram, delayed_write = CacheSz, auto_save = Auto, access = Acc, version = Version, debug = Debug} = OpenArgs, {ok, Fd, FH} = read_file_header(Fname, Acc, Ram), V9 = (Version =:= 9) or (Version =:= default), MinF = (MinSlots =:= default) or (MinSlots =:= FH#fileheader.min_no_slots), MaxF = (MaxSlots =:= default) or (MaxSlots =:= FH#fileheader.max_no_slots), Do = case (FH#fileheader.mod):check_file_header(FH, Fd) of {ok, Head, true} when Rep =:= force, Acc =:= read_write, FH#fileheader.version =:= 9, FH#fileheader.no_colls =/= undefined, MinF, MaxF, V9 -> {compact, Head}; {ok, _Head, _Extra} when Rep =:= force, Acc =:= read -> throw({error, {access_mode, Fname}}); {ok, Head, need_compacting} when Acc =:= read -> Version 8 only . {ok, _Head, need_compacting} when Rep =:= true -> and fragmented free_list . Version 8 only . M = " is now compacted ...", {repair, M}; {ok, _Head, _Extra} when Rep =:= force -> M = ", repair forced.", {repair, M}; {ok, Head, ExtraInfo} -> {final, Head, ExtraInfo}; {error, not_closed} when Rep =:= force, Acc =:= read_write -> M = ", repair forced.", {repair, M}; {error, not_closed} when Rep =:= true, Acc =:= read_write -> M = " not properly closed, repairing ...", {repair, M}; {error, not_closed} when Rep =:= false -> throw({error, {needs_repair, Fname}}); {error, version_bump} when Rep =:= true, Acc =:= read_write -> Version 8 only M = " old version, upgrading ...", {repair, M}; {error, Reason} -> throw({error, {Reason, Fname}}) end, case Do of _ when FH#fileheader.type =/= Type -> throw({error, {type_mismatch, Fname}}); _ when FH#fileheader.keypos =/= Kp -> throw({error, {keypos_mismatch, Fname}}); {compact, SourceHead} -> io:format(user, "dets: file ~p is now compacted ...~n", [Fname]), {ok, NewSourceHead} = open_final(SourceHead, Fname, read, false, ?DEFAULT_CACHE, Tab, true, Debug), case catch compact(NewSourceHead) of ok -> erlang:garbage_collect(), fopen3(Tab, OpenArgs#open_args{repair = false}); _Err -> _ = file:close(Fd), dets_utils:stop_disk_map(), io:format(user, "dets: compaction of file ~p failed, " "now repairing ...~n", [Fname]), {ok, Fd2, _FH} = read_file_header(Fname, Acc, Ram), do_repair(Fd2, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs) end; {repair, Mess} -> io:format(user, "dets: file ~p~s~n", [Fname, Mess]), do_repair(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs); _ when FH#fileheader.version =/= Version, Version =/= default -> throw({error, {version_mismatch, Fname}}); {final, H, EI} -> H1 = H#head{auto_save = Auto}, open_final(H1, Fname, Acc, Ram, CacheSz, Tab, EI, Debug) end. do_repair(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version, OpenArgs) -> case fsck(Fd, Tab, Fname, FH, MinSlots, MaxSlots, Version) of ok -> erlang:garbage_collect(), fopen3(Tab, OpenArgs#open_args{repair = false}); Error -> throw(Error) end. open_final(Head, Fname, Acc, Ram, CacheSz, Tab, ExtraInfo, Debug) -> Head1 = Head#head{access = Acc, ram_file = Ram, filename = Fname, name = Tab, cache = dets_utils:new_cache(CacheSz)}, init_disk_map(Head1#head.version, Tab, Debug), Mod = Head#head.mod, Mod:cache_segps(Head1#head.fptr, Fname, Head1#head.next), Ftab = Mod:init_freelist(Head1, ExtraInfo), check_growth(Head1), NewHead = Head1#head{freelists = Ftab}, {ok, NewHead}. fopen_init_file(Tab, OpenArgs) -> #open_args{file = Fname, type = Type, keypos = Kp, min_no_slots = MinSlotsArg, max_no_slots = MaxSlotsArg, ram_file = Ram, delayed_write = CacheSz, auto_save = Auto, version = UseVersion, debug = Debug} = OpenArgs, MinSlots = choose_no_slots(MinSlotsArg, ?DEFAULT_MIN_NO_SLOTS), MaxSlots = choose_no_slots(MaxSlotsArg, ?DEFAULT_MAX_NO_SLOTS), FileSpec = if Ram -> []; true -> Fname end, {ok, Fd} = dets_utils:open(FileSpec, open_args(read_write, Ram)), Version = if UseVersion =:= default -> case os:getenv("DETS_USE_FILE_FORMAT") of "8" -> 8; _ -> 9 end; true -> UseVersion end, Mod = version2module(Version), init_disk_map(Version, Tab, Debug), case catch Mod:initiate_file(Fd, Tab, Fname, Type, Kp, MinSlots, MaxSlots, Ram, CacheSz, Auto, true) of {error, Reason} when Ram -> file:close(Fd), throw({error, Reason}); {error, Reason} -> file:close(Fd), file:delete(Fname), throw({error, Reason}); {ok, Head} -> start_auto_save_timer(Head), {ok, Head#head{update_mode = new_dirty}} end. init_disk_map(9, Name, Debug) -> case Debug orelse dets_utils:debug_mode() of true -> dets_utils:init_disk_map(Name); false -> ok end; init_disk_map(_Version, _Name, _Debug) -> ok. open_args(Access, RamFile) -> A1 = case Access of read -> []; read_write -> [write] end, A2 = case RamFile of true -> [ram]; false -> [raw] end, A1 ++ A2 ++ [binary, read]. version2module(V) when V =< 8 -> dets_v8; version2module(9) -> dets_v9. module2version(dets_v8) -> 8; module2version(dets_v9) -> 9; module2version(not_used) -> 9. For version 9 tables only . compact(SourceHead) -> #head{name = Tab, filename = Fname, fptr = SFd, type = Type, keypos = Kp, ram_file = Ram, auto_save = Auto} = SourceHead, Tmp = tempfile(Fname), TblParms = dets_v9:table_parameters(SourceHead), {ok, Fd} = dets_utils:open(Tmp, open_args(read_write, false)), CacheSz = ?DEFAULT_CACHE, It is normally not possible to have two open tables in the same Head = case catch dets_v9:prep_table_copy(Fd, Tab, Tmp, Type, Kp, Ram, CacheSz, Auto, TblParms) of {ok, H} -> H; Error -> file:close(Fd), file:delete(Tmp), throw(Error) end, case dets_v9:compact_init(SourceHead, Head, TblParms) of {ok, NewHead} -> R = case fclose(NewHead) of ok -> ok = file:close(SFd), Save ( rename ) Fname first ? dets_utils:rename(Tmp, Fname); E -> E end, if R =:= ok -> ok; true -> file:delete(Tmp), throw(R) end; Err -> file:close(Fd), file:delete(Tmp), throw(Err) end. fsck(Fd, Tab, Fname, FH, MinSlotsArg, MaxSlotsArg, Version) -> MinSlots and MaxSlots are the option values . #fileheader{min_no_slots = MinSlotsFile, max_no_slots = MaxSlotsFile} = FH, EstNoSlots0 = file_no_things(FH), MinSlots = choose_no_slots(MinSlotsArg, MinSlotsFile), MaxSlots = choose_no_slots(MaxSlotsArg, MaxSlotsFile), EstNoSlots = erlang:min(MaxSlots, erlang:max(MinSlots, EstNoSlots0)), SlotNumbers = {MinSlots, EstNoSlots, MaxSlots}, When repairing : We first try and sort on slots using MinSlots . case fsck_try(Fd, Tab, FH, Fname, SlotNumbers, Version) of {try_again, BetterNoSlots} -> BetterSlotNumbers = {MinSlots, BetterNoSlots, MaxSlots}, case fsck_try(Fd, Tab, FH, Fname, BetterSlotNumbers, Version) of {try_again, _} -> file:close(Fd), {error, {cannot_repair, Fname}}; Else -> Else end; Else -> Else end. choose_no_slots(default, NoSlots) -> NoSlots; choose_no_slots(NoSlots, _) -> NoSlots. fsck_try(Fd, Tab, FH, Fname, SlotNumbers, Version) -> Tmp = tempfile(Fname), #fileheader{type = Type, keypos = KeyPos} = FH, {_MinSlots, EstNoSlots, MaxSlots} = SlotNumbers, OpenArgs = #open_args{file = Tmp, type = Type, keypos = KeyPos, repair = false, min_no_slots = EstNoSlots, max_no_slots = MaxSlots, ram_file = false, delayed_write = ?DEFAULT_CACHE, auto_save = infinity, access = read_write, version = Version, debug = false}, case catch fopen3(Tab, OpenArgs) of {ok, Head} -> case fsck_try_est(Head, Fd, Fname, SlotNumbers, FH) of {ok, NewHead} -> R = case fclose(NewHead) of ok -> Save ( rename ) Fname first ? dets_utils:rename(Tmp, Fname); Error -> Error end, if R =:= ok -> ok; true -> file:delete(Tmp), R end; TryAgainOrError -> file:delete(Tmp), TryAgainOrError end; Error -> file:close(Fd), Error end. tempfile(Fname) -> Tmp = lists:concat([Fname, ".TMP"]), case file:delete(Tmp) of timer:sleep(5000), file:delete(Tmp); _ -> ok end, Tmp. - > { ok , NewHead } | { try_again , integer ( ) } | Error fsck_try_est(Head, Fd, Fname, SlotNumbers, FH) -> Mod = FH#fileheader.mod, Cntrs = ets:new(dets_repair, []), Input = Mod:fsck_input(Head, Fd, Cntrs, FH), {Reply, SizeData} = do_sort(Head, SlotNumbers, Input, Cntrs, Fname, Mod), Bulk = false, case Reply of {ok, NoDups, H1} -> file:close(Fd), fsck_copy(SizeData, H1, Bulk, NoDups); {try_again, _} = Return -> close_files(Bulk, SizeData, Head), Return; Else -> file:close(Fd), close_files(Bulk, SizeData, Head), Else end. do_sort(Head, SlotNumbers, Input, Cntrs, Fname, Mod) -> OldV = module2version(Mod), output_objs/4 replaces { LogSize , NoObjects } in by { LogSize , Position , Data , NoObjects | NoCollections } . For small tables Data may be a list of objects which is more Output = (Head#head.mod):output_objs(OldV, Head, SlotNumbers, Cntrs), TmpDir = filename:dirname(Fname), Reply = (catch file_sorter:sort(Input, Output, [{format, binary},{tmpdir, TmpDir}])), L = ets:tab2list(Cntrs), ets:delete(Cntrs), {Reply, lists:reverse(lists:keysort(1, L))}. fsck_copy([{_LogSz, Pos, Bins, _NoObjects} | SizeData], Head, _Bulk, NoDups) when is_list(Bins) -> true = NoDups =:= 0, PWs = [{Pos,Bins} | lists:map(fun({_, P, B, _}) -> {P, B} end, SizeData)], #head{fptr = Fd, filename = FileName} = Head, dets_utils:pwrite(Fd, FileName, PWs), {ok, Head#head{update_mode = dirty}}; fsck_copy(SizeData, Head, Bulk, NoDups) -> catch fsck_copy1(SizeData, Head, Bulk, NoDups). fsck_copy1([SzData | L], Head, Bulk, NoDups) -> Out = Head#head.fptr, {LogSz, Pos, {FileName, Fd}, NoObjects} = SzData, Size = if NoObjects =:= 0 -> 0; true -> ?POW(LogSz-1) end, ExpectedSize = Size * NoObjects, close_tmp(Fd), case file:position(Out, Pos) of {ok, Pos} -> ok; PError -> dets_utils:file_error(FileName, PError) end, {ok, Pos} = file:position(Out, Pos), CR = file:copy({FileName, [raw,binary]}, Out), file:delete(FileName), case CR of {ok, Copied} when Copied =:= ExpectedSize; fsck_copy1(L, Head, Bulk, NoDups); {ok, Copied} when Bulk, Head#head.version =:= 8 -> NoZeros = ExpectedSize - Copied, Dups = NoZeros div Size, Addr = Pos+Copied, NewHead = free_n_objects(Head, Addr, Size-1, NoDups), NewNoDups = NoDups - Dups, fsck_copy1(L, NewHead, Bulk, NewNoDups); close_files(Bulk, L, Head), Reason = if Bulk -> initialization_failed; true -> repair_failed end, {error, {Reason, Head#head.filename}}; FError -> close_files(Bulk, L, Head), dets_utils:file_error(FileName, FError) end; fsck_copy1([], Head, _Bulk, NoDups) when NoDups =/= 0 -> {error, {initialization_failed, Head#head.filename}}; fsck_copy1([], Head, _Bulk, _NoDups) -> {ok, Head#head{update_mode = dirty}}. free_n_objects(Head, _Addr, _Size, 0) -> Head; free_n_objects(Head, Addr, Size, N) -> {NewHead, _} = dets_utils:free(Head, Addr, Size), NewAddr = Addr + Size + 1, free_n_objects(NewHead, NewAddr, Size, N-1). close_files(false, SizeData, Head) -> file:close(Head#head.fptr), close_files(true, SizeData, Head); close_files(true, SizeData, _Head) -> Fun = fun({_Size, _Pos, {FileName, Fd}, _No}) -> close_tmp(Fd), file:delete(FileName); (_) -> ok end, lists:foreach(Fun, SizeData). close_tmp(Fd) -> file:close(Fd). fslot(H, Slot) -> case catch begin {NH, []} = write_cache(H), Objs = (NH#head.mod):slot_objs(NH, Slot), {NH, Objs} end of {NewHead, _Objects} = Reply when is_record(NewHead, head) -> Reply end. do_update_counter(Head, _Key, _Incr) when Head#head.type =/= set -> {Head, badarg}; do_update_counter(Head, Key, Incr) -> case flookup_keys(Head, [Key]) of {H1, [O]} -> Kp = H1#head.keypos, case catch try_update_tuple(O, Kp, Incr) of {'EXIT', _} -> {H1, badarg}; {New, Term} -> case finsert(H1, [Term]) of {H2, ok} -> {H2, New}; Reply -> Reply end end; {H1, []} -> {H1, badarg}; HeadError -> HeadError end. try_update_tuple(O, _Kp, {Pos, Incr}) -> try_update_tuple2(O, Pos, Incr); try_update_tuple(O, Kp, Incr) -> try_update_tuple2(O, Kp+1, Incr). try_update_tuple2(O, Pos, Incr) -> New = element(Pos, O) + Incr, {New, setelement(Pos, O, New)}. set_verbose(true) -> put(verbose, yes); set_verbose(_) -> erase(verbose). where_is_object(Head, Object) -> Keypos = Head#head.keypos, case check_objects([Object], Keypos) of true -> case catch write_cache(Head) of {NewHead, []} -> {NewHead, (Head#head.mod):find_object(NewHead, Object)}; {NewHead, _} = HeadError when is_record(NewHead, head) -> HeadError end; false -> {Head, badarg} end. check_objects([T | Ts], Kp) when tuple_size(T) >= Kp -> check_objects(Ts, Kp); check_objects(L, _Kp) -> L =:= []. no_things(Head) when Head#head.no_keys =:= undefined -> Head#head.no_objects; no_things(Head) -> Head#head.no_keys. file_no_things(FH) when FH#fileheader.no_keys =:= undefined -> FH#fileheader.no_objects; file_no_things(FH) -> FH#fileheader.no_keys. The write cache is list of { Key , [ Item ] } where is one of { Seq , delete_key } , { Seq , { lookup , Pid } } , { Seq , { delete_object , object ( ) } } , datum has become too old . If ' ' is equal to ' undefined ' , and the value of ' ' is the time when the cache was last written , or when it was first updated after the cache was last update_cache(Head, KeysOrObjects, What) -> {Head1, LU, PwriteList} = update_cache(Head, [{What,KeysOrObjects}]), {NewHead, ok} = dets_utils:pwrite(Head1, PwriteList), {NewHead, LU}. - > { NewHead , [ object ( ) ] , pwrite_list ( ) } | throw({Head , Error } ) update_cache(Head, ToAdd) -> Cache = Head#head.cache, #cache{cache = C, csize = Size0, inserts = Ins} = Cache, NewSize = Size0 + erlang:external_size(ToAdd), {NewC, NewIns, Lookup, Found} = cache_binary(Head, ToAdd, C, Size0, Ins, false, []), NewCache = Cache#cache{cache = NewC, csize = NewSize, inserts = NewIns}, Head1 = Head#head{cache = NewCache}, if Lookup; NewSize >= Cache#cache.tsize -> {NewHead, LU, PwriteList} = (Head#head.mod):write_cache(Head1), {NewHead, Found ++ LU, PwriteList}; NewC =:= [] -> {Head1, Found, []}; Cache#cache.wrtime =:= undefined -> Now = now(), Me = self(), Call = ?DETS_CALL(Me, {delayed_write, Now}), erlang:send_after(Cache#cache.delay, Me, Call), {Head1#head{cache = NewCache#cache{wrtime = Now}}, Found, []}; Size0 =:= 0 -> {Head1#head{cache = NewCache#cache{wrtime = now()}}, Found, []}; true -> {Head1, Found, []} end. cache_binary(Head, [{Q,Os} | L], C, Seq, Ins, Lu,F) when Q =:= delete_object -> cache_obj_op(Head, L, C, Seq, Ins, Lu, F, Os, Head#head.keypos, Q); cache_binary(Head, [{Q,Os} | L], C, Seq, Ins, Lu, F) when Q =:= insert -> NewIns = Ins + length(Os), cache_obj_op(Head, L, C, Seq, NewIns, Lu, F, Os, Head#head.keypos, Q); cache_binary(Head, [{Q,Ks} | L], C, Seq, Ins, Lu, F) when Q =:= delete_key -> cache_key_op(Head, L, C, Seq, Ins, Lu, F, Ks, Q); cache_key_op(Head, L, C, Seq, Ins, true, F, Ks, Q); case dets_utils:cache_lookup(Head#head.type, Ks, C, []) of false -> cache_key_op(Head, L, C, Seq, Ins, true, F, Ks, Q); Found -> {lookup,Pid} = Q, cache_binary(Head, L, C, Seq, Ins, Lu, [{Pid,Found} | F]) end; cache_binary(_Head, [], C, _Seq, Ins, Lu, F) -> {C, Ins, Lu, F}. cache_key_op(Head, L, C, Seq, Ins, Lu, F, [K | Ks], Q) -> E = {K, {Seq, Q}}, cache_key_op(Head, L, [E | C], Seq+1, Ins, Lu, F, Ks, Q); cache_key_op(Head, L, C, Seq, Ins, Lu, F, [], _Q) -> cache_binary(Head, L, C, Seq, Ins, Lu, F). cache_obj_op(Head, L, C, Seq, Ins, Lu, F, [O | Os], Kp, Q) -> E = {element(Kp, O), {Seq, {Q, O}}}, cache_obj_op(Head, L, [E | C], Seq+1, Ins, Lu, F, Os, Kp, Q); cache_obj_op(Head, L, C, Seq, Ins, Lu, F, [], _Kp, _Q) -> cache_binary(Head, L, C, Seq, Ins, Lu, F). - > NewHead delayed_write(Head, WrTime) -> Cache = Head#head.cache, LastWrTime = Cache#cache.wrtime, if LastWrTime =:= WrTime -> case catch write_cache(Head) of {Head2, []} -> NewCache = (Head2#head.cache)#cache{wrtime = undefined}, Head2#head{cache = NewCache}; NewHead end; true -> if Cache#cache.csize =:= 0 -> NewCache = Cache#cache{wrtime = undefined}, Head#head{cache = NewCache}; true -> {MS1,S1,M1} = WrTime, {MS2,S2,M2} = LastWrTime, WrT = M1+1000000*(S1+1000000*MS1), LastWrT = M2+1000000*(S2+1000000*MS2), When = round((LastWrT - WrT)/1000), Me = self(), Call = ?DETS_CALL(Me, {delayed_write, LastWrTime}), erlang:send_after(When, Me, Call), Head end end. - > { NewHead , [ LookedUpObject ] } | throw({NewHead , Error } ) write_cache(Head) -> {Head1, LU, PwriteList} = (Head#head.mod):write_cache(Head), {NewHead, ok} = dets_utils:pwrite(Head1, PwriteList), {NewHead, LU}. status(Head) -> case Head#head.update_mode of saved -> ok; dirty -> ok; new_dirty -> ok; Error -> Error end. init_scan(Head, NoObjs) -> check_safe_fixtable(Head), FreeLists = dets_utils:get_freelists(Head), Base = Head#head.base, {From, To} = dets_utils:find_next_allocated(FreeLists, Base, Base), #dets_cont{no_objs = NoObjs, bin = <<>>, alloc = {From, To, <<>>}}. check_safe_fixtable(Head) -> case (Head#head.fixed =:= false) andalso ((get(verbose) =:= yes) orelse dets_utils:debug_mode()) of true -> error_logger:format ("** dets: traversal of ~p needs safe_fixtable~n", [Head#head.name]); false -> ok end. RTerm = { Pos , Next , , Status , Term } scan(_Head, #dets_cont{alloc = <<>>}=C) -> {[], C}; when is_record(C , dets_cont ) #dets_cont{no_objs = No, alloc = L0, bin = Bin} = C, {From, To, L} = L0, R = case No of default -> 0; _ when is_integer(No) -> -No-1 end, scan(Bin, Head, From, To, L, [], R, {C, Head#head.type}). scan(Bin, H, From, To, L, Ts, R, {C0, Type} = C) -> case (H#head.mod):scan_objs(H, Bin, From, To, L, Ts, R, Type) of {more, NFrom, NTo, NL, NTs, NR, Sz} -> scan_read(H, NFrom, NTo, Sz, NL, NTs, NR, C); {stop, <<>>=B, NFrom, NTo, <<>>=NL, NTs} -> Ftab = dets_utils:get_freelists(H), case dets_utils:find_next_allocated(Ftab, NFrom, H#head.base) of none -> {NTs, C0#dets_cont{bin = eof, alloc = B}}; _ -> {NTs, C0#dets_cont{bin = B, alloc = {NFrom, NTo, NL}}} end; {stop, B, NFrom, NTo, NL, NTs} -> {NTs, C0#dets_cont{bin = B, alloc = {NFrom, NTo, NL}}}; bad_object -> {scan_error, dets_utils:bad_object(scan, {From, To, Bin})} end. scan_read(_H, From, To, _Min, L0, Ts, R, {C, _Type}) when R >= ?CHUNK_SIZE -> L = {From, To, L0}, {Ts, C#dets_cont{bin = <<>>, alloc = L}}; scan_read(H, From, _To, Min, _L, Ts, R, C) -> Max = if Min < ?CHUNK_SIZE -> ?CHUNK_SIZE; true -> Min end, FreeLists = dets_utils:get_freelists(H), case dets_utils:find_allocated(FreeLists, From, Max, H#head.base) of <<>>=Bin0 -> {Cont, _} = C, {Ts, Cont#dets_cont{bin = eof, alloc = Bin0}}; <<From1:32,To1:32,L1/binary>> -> case dets_utils:pread_n(H#head.fptr, From1, Max) of eof -> {scan_error, premature_eof}; NewBin -> scan(NewBin, H, From1, To1, L1, Ts, R, C) end end. err(Error) -> case get(verbose) of yes -> error_logger:format("** dets: failed with ~w~n", [Error]), Error; undefined -> Error end. file_info(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> file:close(Fd), (FH#fileheader.mod):file_info(FH); Other -> Other end. get_head_field(Fd, Field) -> dets_utils:read_4(Fd, Field). view(FileName) -> case catch read_file_header(FileName, read, false) of {ok, Fd, FH} -> Mod = FH#fileheader.mod, case Mod:check_file_header(FH, Fd) of {ok, H0, ExtraInfo} -> Ftab = Mod:init_freelist(H0, ExtraInfo), {_Bump, Base} = constants(FH, FileName), H = H0#head{freelists=Ftab, base = Base}, v_free_list(H), Mod:v_segments(H), file:close(Fd); X -> file:close(Fd), X end; X -> X end. v_free_list(Head) -> io:format("FREE LIST ...... \n",[]), io:format("~p~n", [dets_utils:all_free(Head)]), io:format("END OF FREE LIST \n",[]).
f2a37c4a254ff8eb780133ca568ae5f4f4dcdee5219982154e6faef749b8327c
byorgey/BlogLiterately
Setup.hs
import Distribution.Simple main = defaultMain
null
https://raw.githubusercontent.com/byorgey/BlogLiterately/fbc8dc238c7e5bc570bef4d0c1dd9cf2f92de72a/Setup.hs
haskell
import Distribution.Simple main = defaultMain
55b5da1d8604b9839e48fd8f0427e79829b9ac0697c3d709d77a39b07c79faa1
david-broman/modelyze
extArray.ml
* ExtList - additional and modified functions for lists . * Copyright ( C ) 2005 ( rich @ annexia.org ) * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * ExtList - additional and modified functions for lists. * Copyright (C) 2005 Richard W.M. Jones (rich @ annexia.org) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) module Array = struct include Array let rev_in_place xs = let n = length xs in let j = ref (n-1) in for i = 0 to n/2-1 do let c = xs.(i) in xs.(i) <- xs.(!j); xs.(!j) <- c; decr j done let rev xs = let ys = Array.copy xs in rev_in_place ys; ys let for_all p xs = let n = length xs in let rec loop i = if i = n then true else if p xs.(i) then loop (succ i) else false in loop 0 let exists p xs = let n = length xs in let rec loop i = if i = n then false else if p xs.(i) then true else loop (succ i) in loop 0 let mem a xs = let n = length xs in let rec loop i = if i = n then false else if a = xs.(i) then true else loop (succ i) in loop 0 let memq a xs = let n = length xs in let rec loop i = if i = n then false else if a == xs.(i) then true else loop (succ i) in loop 0 let findi p xs = let n = length xs in let rec loop i = if i = n then raise Not_found else if p xs.(i) then i else loop (succ i) in loop 0 let find p xs = xs.(findi p xs) Use of BitSet suggested by . let filter p xs = let n = length xs in (* Use a bitset to store which elements will be in the final array. *) let bs = BitSet.create n in for i = 0 to n-1 do if p xs.(i) then BitSet.set bs i done; (* Allocate the final array and copy elements into it. *) let n' = BitSet.count bs in let j = ref 0 in let xs' = init n' (fun _ -> Find the next set bit in the BitSet . while not (BitSet.is_set bs !j) do incr j done; let r = xs.(!j) in incr j; r) in xs' let find_all = filter let partition p xs = let n = length xs in (* Use a bitset to store which elements will be in which final array. *) let bs = BitSet.create n in for i = 0 to n-1 do if p xs.(i) then BitSet.set bs i done; (* Allocate the final arrays and copy elements into them. *) let n1 = BitSet.count bs in let n2 = n - n1 in let j = ref 0 in let xs1 = init n1 (fun _ -> Find the next set bit in the BitSet . while not (BitSet.is_set bs !j) do incr j done; let r = xs.(!j) in incr j; r) in let j = ref 0 in let xs2 = init n2 (fun _ -> Find the next clear bit in the BitSet . while BitSet.is_set bs !j do incr j done; let r = xs.(!j) in incr j; r) in xs1, xs2 let enum xs = let rec make start xs = let n = length xs in Enum.make ~next:(fun () -> if !start < n then ( let r = xs.(!start) in incr start; r ) else raise Enum.No_more_elements) ~count:(fun () -> n - !start) ~clone:(fun () -> let xs' = Array.sub xs !start (n - !start) in make (ref 0) xs') in make (ref 0) xs let of_enum e = let n = Enum.count e in (* This assumes, reasonably, that init traverses the array in order. *) Array.init n (fun i -> match Enum.get e with | Some x -> x | None -> assert false) let iter2 f a1 a2 = if Array.length a1 <> Array.length a2 then raise (Invalid_argument "Array.iter2"); for i = 0 to Array.length a1 - 1 do f a1.(i) a2.(i); done;; end
null
https://raw.githubusercontent.com/david-broman/modelyze/e48c934283e683e268a9dfd0fed49d3c10277298/ext/extlib/extArray.ml
ocaml
Use a bitset to store which elements will be in the final array. Allocate the final array and copy elements into it. Use a bitset to store which elements will be in which final array. Allocate the final arrays and copy elements into them. This assumes, reasonably, that init traverses the array in order.
* ExtList - additional and modified functions for lists . * Copyright ( C ) 2005 ( rich @ annexia.org ) * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * ExtList - additional and modified functions for lists. * Copyright (C) 2005 Richard W.M. Jones (rich @ annexia.org) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) module Array = struct include Array let rev_in_place xs = let n = length xs in let j = ref (n-1) in for i = 0 to n/2-1 do let c = xs.(i) in xs.(i) <- xs.(!j); xs.(!j) <- c; decr j done let rev xs = let ys = Array.copy xs in rev_in_place ys; ys let for_all p xs = let n = length xs in let rec loop i = if i = n then true else if p xs.(i) then loop (succ i) else false in loop 0 let exists p xs = let n = length xs in let rec loop i = if i = n then false else if p xs.(i) then true else loop (succ i) in loop 0 let mem a xs = let n = length xs in let rec loop i = if i = n then false else if a = xs.(i) then true else loop (succ i) in loop 0 let memq a xs = let n = length xs in let rec loop i = if i = n then false else if a == xs.(i) then true else loop (succ i) in loop 0 let findi p xs = let n = length xs in let rec loop i = if i = n then raise Not_found else if p xs.(i) then i else loop (succ i) in loop 0 let find p xs = xs.(findi p xs) Use of BitSet suggested by . let filter p xs = let n = length xs in let bs = BitSet.create n in for i = 0 to n-1 do if p xs.(i) then BitSet.set bs i done; let n' = BitSet.count bs in let j = ref 0 in let xs' = init n' (fun _ -> Find the next set bit in the BitSet . while not (BitSet.is_set bs !j) do incr j done; let r = xs.(!j) in incr j; r) in xs' let find_all = filter let partition p xs = let n = length xs in let bs = BitSet.create n in for i = 0 to n-1 do if p xs.(i) then BitSet.set bs i done; let n1 = BitSet.count bs in let n2 = n - n1 in let j = ref 0 in let xs1 = init n1 (fun _ -> Find the next set bit in the BitSet . while not (BitSet.is_set bs !j) do incr j done; let r = xs.(!j) in incr j; r) in let j = ref 0 in let xs2 = init n2 (fun _ -> Find the next clear bit in the BitSet . while BitSet.is_set bs !j do incr j done; let r = xs.(!j) in incr j; r) in xs1, xs2 let enum xs = let rec make start xs = let n = length xs in Enum.make ~next:(fun () -> if !start < n then ( let r = xs.(!start) in incr start; r ) else raise Enum.No_more_elements) ~count:(fun () -> n - !start) ~clone:(fun () -> let xs' = Array.sub xs !start (n - !start) in make (ref 0) xs') in make (ref 0) xs let of_enum e = let n = Enum.count e in Array.init n (fun i -> match Enum.get e with | Some x -> x | None -> assert false) let iter2 f a1 a2 = if Array.length a1 <> Array.length a2 then raise (Invalid_argument "Array.iter2"); for i = 0 to Array.length a1 - 1 do f a1.(i) a2.(i); done;; end
64fd823b51e9dee2d817f708cde15d0f330906d978263922d99eaa39717452ad
vaclavsvejcar/headroom
PureScriptSpec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # # LANGUAGE NoImplicitPrelude # module Headroom.FileSupport.PureScriptSpec ( spec ) where import Headroom.Config ( makeHeadersConfig , parseAppConfig ) import Headroom.Config.Types (AppConfig (..)) import Headroom.Embedded (defaultConfig) import Headroom.FileSupport ( analyzeSourceCode , fileSupport ) import Headroom.FileSupport.TemplateData (TemplateData (..)) import Headroom.FileSupport.Types ( FileSupport (..) , SyntaxAnalysis (..) ) import Headroom.FileType.Types (FileType (..)) import Headroom.Header (extractHeaderTemplate) import Headroom.IO.FileSystem (loadFile) import Headroom.Template (emptyTemplate) import Headroom.Template.Mustache (Mustache) import Headroom.Variables (mkVariables) import RIO import RIO.FilePath ((</>)) import Test.Hspec spec :: Spec spec = do let codeSamples = "test-data" </> "code-samples" </> "purescript" describe "fsSyntaxAnalysis" $ do it "correctly detects comment starts/ends" $ do let samples = [ ("non comment line", (False, False)) , ("-- single line comment", (True, True)) , ("not -- single line comment", (False, False)) , ("{- block comment start", (True, False)) , ("block comment end -}", (False, True)) , ("{- block comment start/end -}", (True, True)) ] all checkSyntaxAnalysis samples `shouldBe` True describe "fsExtractTemplateData" $ do it "doesn't provide any custom data for PureScript" $ do template <- emptyTemplate @_ @Mustache let syntax = undefined expected = NoTemplateData fsExtractTemplateData fileSupport' template syntax `shouldBe` expected describe "fsExtractVariables" $ do it "extract variables from PureScript source code" $ do template <- emptyTemplate @_ @Mustache defaultConfig' <- parseAppConfig defaultConfig config <- makeHeadersConfig (acLicenseHeaders defaultConfig') raw <- loadFile $ codeSamples </> "full.purs" let ht = extractHeaderTemplate config PureScript template headerPos = Just (1, 13) expected = mkVariables [("_purescript_module_name", "Test")] sample = analyzeSourceCode fileSupport' raw fsExtractVariables fileSupport' ht headerPos sample `shouldBe` expected describe "fsFileType" $ do it "matches correct type for PureScript" $ do fsFileType fileSupport' `shouldBe` PureScript where fileSupport' = fileSupport PureScript checkSyntaxAnalysis (l, (s, e)) = let SyntaxAnalysis{..} = fsSyntaxAnalysis fileSupport' in saIsCommentStart l == s && saIsCommentEnd l == e
null
https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/test/Headroom/FileSupport/PureScriptSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # # LANGUAGE NoImplicitPrelude # module Headroom.FileSupport.PureScriptSpec ( spec ) where import Headroom.Config ( makeHeadersConfig , parseAppConfig ) import Headroom.Config.Types (AppConfig (..)) import Headroom.Embedded (defaultConfig) import Headroom.FileSupport ( analyzeSourceCode , fileSupport ) import Headroom.FileSupport.TemplateData (TemplateData (..)) import Headroom.FileSupport.Types ( FileSupport (..) , SyntaxAnalysis (..) ) import Headroom.FileType.Types (FileType (..)) import Headroom.Header (extractHeaderTemplate) import Headroom.IO.FileSystem (loadFile) import Headroom.Template (emptyTemplate) import Headroom.Template.Mustache (Mustache) import Headroom.Variables (mkVariables) import RIO import RIO.FilePath ((</>)) import Test.Hspec spec :: Spec spec = do let codeSamples = "test-data" </> "code-samples" </> "purescript" describe "fsSyntaxAnalysis" $ do it "correctly detects comment starts/ends" $ do let samples = [ ("non comment line", (False, False)) , ("-- single line comment", (True, True)) , ("not -- single line comment", (False, False)) , ("{- block comment start", (True, False)) , ("block comment end -}", (False, True)) , ("{- block comment start/end -}", (True, True)) ] all checkSyntaxAnalysis samples `shouldBe` True describe "fsExtractTemplateData" $ do it "doesn't provide any custom data for PureScript" $ do template <- emptyTemplate @_ @Mustache let syntax = undefined expected = NoTemplateData fsExtractTemplateData fileSupport' template syntax `shouldBe` expected describe "fsExtractVariables" $ do it "extract variables from PureScript source code" $ do template <- emptyTemplate @_ @Mustache defaultConfig' <- parseAppConfig defaultConfig config <- makeHeadersConfig (acLicenseHeaders defaultConfig') raw <- loadFile $ codeSamples </> "full.purs" let ht = extractHeaderTemplate config PureScript template headerPos = Just (1, 13) expected = mkVariables [("_purescript_module_name", "Test")] sample = analyzeSourceCode fileSupport' raw fsExtractVariables fileSupport' ht headerPos sample `shouldBe` expected describe "fsFileType" $ do it "matches correct type for PureScript" $ do fsFileType fileSupport' `shouldBe` PureScript where fileSupport' = fileSupport PureScript checkSyntaxAnalysis (l, (s, e)) = let SyntaxAnalysis{..} = fsSyntaxAnalysis fileSupport' in saIsCommentStart l == s && saIsCommentEnd l == e
14046e91af006e4c2790872038bd2b5c9d32198d4f5aa118fe5a5df23b348d0e
mattsta/er
er_app.erl
-module(er_app). -behaviour(application). %% Application callbacks -export([start/0, start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start() -> er_sup:start_link(). start(_StartType, _StartArgs) -> start(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/mattsta/er/7ac6dccf4952ddf32d921b6548026980a3db70c7/src/er_app.erl
erlang
Application callbacks =================================================================== Application callbacks ===================================================================
-module(er_app). -behaviour(application). -export([start/0, start/2, stop/1]). start() -> er_sup:start_link(). start(_StartType, _StartArgs) -> start(). stop(_State) -> ok.
015e09cf993f339b1168001ac33209e05529894fc2a48bde6f98fc6e1957ccdb
AlexCharlton/site-generator
test-server.lisp
(in-package :site-generator) # # Test server (export '(run-test-server)) (defvar *quit* nil) (defvar *acceptor*) (defun run-test-server (dir &optional (port 4242)) "Pathname &optional Integer -> nil Start a test server and watch the site for changes." (set-root-dir dir) (check-site) (init-db) (start-server port) (setf *quit* nil) (let ((site-thread (make-thread #'watch-site))) (iter (for line = (read-line *standard-input* nil 'eof)) (until (find line '(eof "quit" "exit") :test #'equalp))) (setf *quit* t) (join-thread site-thread)) (print-message "Test server shutting down.") (hunchentoot:stop *acceptor*)) (defun watch-site () "nil -> nil Watch the site for changes and update it when they occur." (print-message "Watching site for changes...") (iter (until *quit*) (update-db) (when-let ((needs-update (needs-update))) (print-message "Updating changes") (update-site needs-update) (print-message "Finished updating changes")) (sleep 1))) (defclass acceptor (hunchentoot:acceptor) () (:default-initargs :address "0.0.0.0" :access-log-destination nil :message-log-destination nil)) (defmethod hunchentoot:acceptor-dispatch-request ((acceptor acceptor) request) "Serve up a static file, with 'index.html' being served when a directory is being requested." (let* ((uri (subseq (hunchentoot:script-name request) 1)) (file (merge-pathnames uri *site-dir*))) (when (file-exists-p file) (hunchentoot:handle-static-file (if (eq (file-kind file) :directory) (merge-pathnames "index.html" (pathname-as-directory file)) file))))) (defun start-server (port) "Integer -> nil Start a Hunchentoot server." (print-message "Starting test server.") (setf *acceptor* (make-instance 'acceptor :port port)) (hunchentoot:start *acceptor*) (print-message "Test server can be accessed through :~a/" port))
null
https://raw.githubusercontent.com/AlexCharlton/site-generator/a827cfeccc72527de44ec048f1b9dd703eb6fe8f/src/test-server.lisp
lisp
(in-package :site-generator) # # Test server (export '(run-test-server)) (defvar *quit* nil) (defvar *acceptor*) (defun run-test-server (dir &optional (port 4242)) "Pathname &optional Integer -> nil Start a test server and watch the site for changes." (set-root-dir dir) (check-site) (init-db) (start-server port) (setf *quit* nil) (let ((site-thread (make-thread #'watch-site))) (iter (for line = (read-line *standard-input* nil 'eof)) (until (find line '(eof "quit" "exit") :test #'equalp))) (setf *quit* t) (join-thread site-thread)) (print-message "Test server shutting down.") (hunchentoot:stop *acceptor*)) (defun watch-site () "nil -> nil Watch the site for changes and update it when they occur." (print-message "Watching site for changes...") (iter (until *quit*) (update-db) (when-let ((needs-update (needs-update))) (print-message "Updating changes") (update-site needs-update) (print-message "Finished updating changes")) (sleep 1))) (defclass acceptor (hunchentoot:acceptor) () (:default-initargs :address "0.0.0.0" :access-log-destination nil :message-log-destination nil)) (defmethod hunchentoot:acceptor-dispatch-request ((acceptor acceptor) request) "Serve up a static file, with 'index.html' being served when a directory is being requested." (let* ((uri (subseq (hunchentoot:script-name request) 1)) (file (merge-pathnames uri *site-dir*))) (when (file-exists-p file) (hunchentoot:handle-static-file (if (eq (file-kind file) :directory) (merge-pathnames "index.html" (pathname-as-directory file)) file))))) (defun start-server (port) "Integer -> nil Start a Hunchentoot server." (print-message "Starting test server.") (setf *acceptor* (make-instance 'acceptor :port port)) (hunchentoot:start *acceptor*) (print-message "Test server can be accessed through :~a/" port))
ba649121fc16a23d8d253eca5cf504ec887eb50bfc3c41dd9a15ade60fd9f0cf
FlogFr/FlashCard
Template.hs
module Template where import Protolude import Data.HashMap.Strict import Control.Concurrent.STM.TMVar import Control.Exception import Text.Mustache import Text.Blaze.Html import SharedEnv import Data.Settings import HandlerM data LCException = TemplateParseException deriving (Show) instance Exception LCException compileTemplate' :: FilePath -> IO Template compileTemplate' templateName = do let searchSpace = ["src/templates/", "templates/", "emails/"] compiled <- automaticCompile searchSpace templateName case compiled of Left err -> do putStrLn $ ("TemplateParseException: " <> (show err) :: Text) throw TemplateParseException Right template -> return template compileTemplate :: FilePath -> HandlerM Template compileTemplate templateName = do sharedEnv <- ask case production . settings $ sharedEnv of True -> do let tCacheTemplate = cacheTemplate sharedEnv templateCache' <- liftIO $ atomically $ readTMVar tCacheTemplate let mCacheValue = lookup templateName templateCache' case mCacheValue of -- if the key exists in the templateCache', return it Just template -> return template -- if the template doesnt exists, load and compile the -- template with the partials, then save it into the -- cache Nothing -> do -- check the cache template <- liftIO $ compileTemplate' templateName let newCache = insert templateName template templateCache' _ <- liftIO $ atomically $ swapTMVar tCacheTemplate newCache return $ template False -> liftIO $ compileTemplate' templateName -- substituteTemplate template context = substitute template (object ["ctx" ~= context]) substituteTemplate :: ToMustache ctx => Template -> ctx -> Text substituteTemplate template context = substitute template context preEscapedToMarkupSubstituteTemplate :: ToMustache ctx => Template -> ctx -> HandlerM Html preEscapedToMarkupSubstituteTemplate template context = do return $ preEscapedToMarkup $ substitute template context
null
https://raw.githubusercontent.com/FlogFr/FlashCard/17029f9b84f23c43f67702b77bd7418cdf0a9d28/src/Template.hs
haskell
if the key exists in the templateCache', return it if the template doesnt exists, load and compile the template with the partials, then save it into the cache check the cache substituteTemplate template context = substitute template (object ["ctx" ~= context])
module Template where import Protolude import Data.HashMap.Strict import Control.Concurrent.STM.TMVar import Control.Exception import Text.Mustache import Text.Blaze.Html import SharedEnv import Data.Settings import HandlerM data LCException = TemplateParseException deriving (Show) instance Exception LCException compileTemplate' :: FilePath -> IO Template compileTemplate' templateName = do let searchSpace = ["src/templates/", "templates/", "emails/"] compiled <- automaticCompile searchSpace templateName case compiled of Left err -> do putStrLn $ ("TemplateParseException: " <> (show err) :: Text) throw TemplateParseException Right template -> return template compileTemplate :: FilePath -> HandlerM Template compileTemplate templateName = do sharedEnv <- ask case production . settings $ sharedEnv of True -> do let tCacheTemplate = cacheTemplate sharedEnv templateCache' <- liftIO $ atomically $ readTMVar tCacheTemplate let mCacheValue = lookup templateName templateCache' case mCacheValue of Just template -> return template Nothing -> do template <- liftIO $ compileTemplate' templateName let newCache = insert templateName template templateCache' _ <- liftIO $ atomically $ swapTMVar tCacheTemplate newCache return $ template False -> liftIO $ compileTemplate' templateName substituteTemplate :: ToMustache ctx => Template -> ctx -> Text substituteTemplate template context = substitute template context preEscapedToMarkupSubstituteTemplate :: ToMustache ctx => Template -> ctx -> HandlerM Html preEscapedToMarkupSubstituteTemplate template context = do return $ preEscapedToMarkup $ substitute template context
10306c19c0f70cdb635f9640001403788f0273b89ec7c7442bee80dcf246bf9e
clj-commons/rewrite-cljs
keyword.cljs
(ns rewrite-clj.node.keyword (:require [rewrite-clj.node.protocols :as node])) ;; ## Node (defrecord KeywordNode [k namespaced?] node/Node (tag [_] :token) (printable-only? [_] false) (sexpr [_] (if (and namespaced? (not (namespace k))) ;; (keyword ;; (name (ns-name *ns*)) ;; (name k)) (throw (js/Error. "Namespaced keywords not supported !")) k)) (length [this] (let [c (inc (count (name k)))] (if namespaced? (inc c) (if-let [nspace (namespace k)] (+ 1 c (count nspace)) c)))) (string [_] (let [v (pr-str k)] (if namespaced? (str ":" v) v))) Object (toString [this] (node/string this))) TODO ( node / make - printable ! ) # # Constructor (defn keyword-node "Create node representing a keyword. If `namespaced?` is given as `true` a keyword à la `::x` or `::ns/x` (i.e. namespaced/aliased) is generated." [k & [namespaced?]] {:pre [(keyword? k)]} (->KeywordNode k namespaced?))
null
https://raw.githubusercontent.com/clj-commons/rewrite-cljs/5b0fdea43a6748519d0b0ad3d7eaa98aa541de35/src/rewrite_clj/node/keyword.cljs
clojure
## Node (keyword (name (ns-name *ns*)) (name k))
(ns rewrite-clj.node.keyword (:require [rewrite-clj.node.protocols :as node])) (defrecord KeywordNode [k namespaced?] node/Node (tag [_] :token) (printable-only? [_] false) (sexpr [_] (if (and namespaced? (not (namespace k))) (throw (js/Error. "Namespaced keywords not supported !")) k)) (length [this] (let [c (inc (count (name k)))] (if namespaced? (inc c) (if-let [nspace (namespace k)] (+ 1 c (count nspace)) c)))) (string [_] (let [v (pr-str k)] (if namespaced? (str ":" v) v))) Object (toString [this] (node/string this))) TODO ( node / make - printable ! ) # # Constructor (defn keyword-node "Create node representing a keyword. If `namespaced?` is given as `true` a keyword à la `::x` or `::ns/x` (i.e. namespaced/aliased) is generated." [k & [namespaced?]] {:pre [(keyword? k)]} (->KeywordNode k namespaced?))
019f16e92989ce49e402e126d478c967e972674fc352f79743aaa8c293229354
jellelicht/guix
password-utils.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > Copyright © 2015 , 2016 < > Copyright © 2015 Copyright © 2016 < > Copyright © 2016 < > Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages password-utils) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (guix download) #:use-module (guix packages) #:use-module (gnu packages admin) #:use-module (gnu packages base) #:use-module (gnu packages compression) #:use-module (gnu packages gnupg) #:use-module (gnu packages gtk) #:use-module (gnu packages guile) #:use-module (gnu packages linux) #:use-module (gnu packages man) #:use-module (gnu packages ncurses) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages tls) #:use-module (gnu packages qt) #:use-module (gnu packages version-control) #:use-module (gnu packages xdisorg) #:use-module (gnu packages xorg) #:use-module (guix build-system python)) (define-public pwgen (package (name "pwgen") (version "2.07") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0mhmw700kkh238fzivcwnwi94bj9f3h36yfh3k3j2v19b0zmjx7b")))) (build-system gnu-build-system) (arguments `(#:tests? #f)) ; no test suite (home-page "/") (synopsis "Password generator") (description "Pwgen generates passwords which can be easily memorized by a human.") (license license:gpl2))) (define-public keepassx (package (name "keepassx") (version "2.0.2") (source (origin (method url-fetch) (uri (string-append "/" version "/keepassx-" version ".tar.gz")) (sha256 (base32 "1f1nlbd669rmpzr52d9dgfgclg4jcaq2jkrby3b8q1vjkksdqjr0")))) (build-system cmake-build-system) (inputs `(("libgcrypt" ,libgcrypt) ("libxtst" ,libxtst) ("qt" ,qt-4))) (native-inputs `(("zlib" ,zlib))) (home-page "") (synopsis "Password manager") (description "KeePassX is a password manager or safe which helps you to manage your passwords in a secure way. You can put all your passwords in one database, which is locked with one master key or a key-file which can be stored on an external storage device. The databases are encrypted using the algorithms AES or Twofish.") ;; Non functional parts use various licences. (license license:gpl3))) (define-public shroud (package (name "shroud") (version "0.1.1") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1y43yhgy2zbrk5bqj3qyx9rkcz2bma9sinlrg7dip3jqms9gq4lr")))) (build-system gnu-build-system) (inputs `(("guile" ,guile-2.0) ("gnupg" ,gnupg) ("xclip" ,xclip))) (synopsis "GnuPG-based secret manager") (description "Shroud is a simple secret manager with a command line interface. The password database is stored as a Scheme s-expression and encrypted with a GnuPG key. Secrets consist of an arbitrary number of key/value pairs, making Shroud suitable for more than just password storage. For copying and pasting secrets into web browsers and other graphical applications, there is xclip integration." ) (home-page "") (license license:gpl3+))) (define-public yapet (package (name "yapet") (version "1.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.bz2")) (sha256 (base32 "0ydbnqw6icdh07pnv2w6dhvq501bdfvrklv4xmyr8znca9d753if")))) (build-system gnu-build-system) (inputs `(("ncurses" ,ncurses) ("openssl" ,openssl))) (native-inputs `(("pkg-config" ,pkg-config))) (synopsis "Yet Another Password Encryption Tool") (description "YAPET is a text based password manager using the Blowfish encryption algorithm. Because of its small footprint and very few library dependencies, it is suited for installing on desktop and server systems alike. The text based user interface allows you to run YAPET easily in a Secure Shell session. Two companion utilities enable users to convert CSV files to YAPET and vice versa.") (home-page "/") (license license:gpl3+))) (define-public cracklib (package (name "cracklib") (version "2.9.6") (source (origin (method url-fetch) (uri (string-append "/" "releases/download/" name "-" version "/" name "-" version ".tar.gz")) (sha256 (base32 "0hrkb0prf7n92w6rxgq0ilzkk6rkhpys2cfqkrbzswp27na7dkqp")))) (build-system gnu-build-system) (synopsis "Password checking library") (home-page "") (description "CrackLib is a library containing a C function which may be used in a passwd like program. The idea is simple: try to prevent users from choosing passwords that could be guessed by crack by filtering them out, at source.") (license license:lgpl2.1))) (define-public libpwquality (package (name "libpwquality") (version "1.3.0") (source (origin (method url-fetch) (uri (list (string-append "/" name "/" name "-" version ".tar.bz2") (string-append "/" version "/+download/" name "-" version ".tar.bz2"))) (sha256 (base32 "0aidriag6h0syfm33nzdfdsqgrnsgihwjv3a5lgkqch3w68fmlkl")))) (build-system gnu-build-system) (arguments ;; XXX: have RUNPATH issue. '(#:configure-flags '("--disable-python-bindings"))) (inputs `(("cracklib" ,cracklib))) (synopsis "Password quality checker") (home-page "/") (description "Libpwquality is a library for password quality checking and generation of random passwords that pass the checks.") (license license:gpl2+))) (define-public assword (package (name "assword") (version "0.8") (source (origin (method url-fetch) (uri (list (string-append "/" "assword_" version ".orig.tar.gz"))) (sha256 (base32 "0dl4wizbi0r21wxzykm8s445xbvqim5nabi799dmpkdnnh8i546i")))) (arguments `(#:python ,python-2 irritatingly , tests do run but not there are two problems : ;; - "import gtk" fails for unknown reasons here despite it the ;; program working (indeed, I've found I have to do a logout and log ;; back in in after an install order for some mumbo jumbo environment variable mess to work with pygtk and ... what 's up with ;; that?) ;; - even when the tests fail, they don't return a nonzero status, ;; so I'm not sure how to programmatically get that information #:tests? #f #:phases (modify-phases %standard-phases (add-after 'install 'manpage (lambda* (#:key outputs #:allow-other-keys) (and (zero? (system* "make" "assword.1")) (install-file "assword.1" (string-append (assoc-ref outputs "out") "/share/man/man1")))))))) (build-system python-build-system) (native-inputs `(("help2man" ,help2man))) (inputs `(("python-setuptools" ,python2-setuptools) ("python2-xdo" ,python2-xdo) ("python2-pygpgme" ,python2-pygpgme) ("python2-pygtk" ,python2-pygtk))) (propagated-inputs `(("xclip" ,xclip))) (home-page "/") (synopsis "Password manager") (description "assword is a simple password manager using GPG-wrapped JSON files. It has a command line interface as well as a very simple graphical interface, which can even \"type\" your passwords into any X11 window.") (license license:gpl3+))) (define-public password-store (package (name "password-store") (version "1.6.5") (source (origin (method url-fetch) (uri (string-append "-store/snapshot/" name "-" version ".tar.xz")) (sha256 (base32 "05bk3lrp5jwg0v338lvylp7glpliydzz4jf5pjr6k3kagrv3jyik")))) (build-system gnu-build-system) (arguments '(#:phases (modify-phases %standard-phases (delete 'configure) (add-after The script requires ' ' at run - time , and this allows ;; the user to not install the providing package 'util-linux' ;; in their profile. 'unpack 'patch-path (lambda* (#:key inputs outputs #:allow-other-keys) (let ((getopt (string-append (assoc-ref inputs "getopt") "/bin/getopt"))) (substitute* "src/password-store.sh" (("GETOPT=\"getopt\"") (string-append "GETOPT=\"" getopt "\""))) #t)))) #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:test-target "test")) (native-inputs `(("getopt" ,util-linux))) ; getopt for the tests (inputs `(("gnupg" ,gnupg) ("pwgen" ,pwgen) ("xclip" ,xclip) ("git" ,git) ("tree" ,tree) ("which" ,which))) (home-page "/") (synopsis "Encrypted password manager") (description "Password-store is a password manager which uses GnuPG to store and retrieve passwords. The tool stores each password in its own GnuPG-encrypted file, allowing the program to be simple yet secure. Synchronization is possible using the integrated git support, which commits changes to your password database to a git repository that can be managed through the pass command.") (license license:gpl2+)))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/password-utils.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. no test suite Non functional parts use various licences. XXX: have RUNPATH issue. - "import gtk" fails for unknown reasons here despite it the program working (indeed, I've found I have to do a logout and log back in in after an install order for some mumbo jumbo environment that?) - even when the tests fail, they don't return a nonzero status, so I'm not sure how to programmatically get that information the user to not install the providing package 'util-linux' in their profile. getopt for the tests
Copyright © 2015 < > Copyright © 2015 , 2016 < > Copyright © 2015 Copyright © 2016 < > Copyright © 2016 < > Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages password-utils) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (guix download) #:use-module (guix packages) #:use-module (gnu packages admin) #:use-module (gnu packages base) #:use-module (gnu packages compression) #:use-module (gnu packages gnupg) #:use-module (gnu packages gtk) #:use-module (gnu packages guile) #:use-module (gnu packages linux) #:use-module (gnu packages man) #:use-module (gnu packages ncurses) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages tls) #:use-module (gnu packages qt) #:use-module (gnu packages version-control) #:use-module (gnu packages xdisorg) #:use-module (gnu packages xorg) #:use-module (guix build-system python)) (define-public pwgen (package (name "pwgen") (version "2.07") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0mhmw700kkh238fzivcwnwi94bj9f3h36yfh3k3j2v19b0zmjx7b")))) (build-system gnu-build-system) (arguments (home-page "/") (synopsis "Password generator") (description "Pwgen generates passwords which can be easily memorized by a human.") (license license:gpl2))) (define-public keepassx (package (name "keepassx") (version "2.0.2") (source (origin (method url-fetch) (uri (string-append "/" version "/keepassx-" version ".tar.gz")) (sha256 (base32 "1f1nlbd669rmpzr52d9dgfgclg4jcaq2jkrby3b8q1vjkksdqjr0")))) (build-system cmake-build-system) (inputs `(("libgcrypt" ,libgcrypt) ("libxtst" ,libxtst) ("qt" ,qt-4))) (native-inputs `(("zlib" ,zlib))) (home-page "") (synopsis "Password manager") (description "KeePassX is a password manager or safe which helps you to manage your passwords in a secure way. You can put all your passwords in one database, which is locked with one master key or a key-file which can be stored on an external storage device. The databases are encrypted using the algorithms AES or Twofish.") (license license:gpl3))) (define-public shroud (package (name "shroud") (version "0.1.1") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1y43yhgy2zbrk5bqj3qyx9rkcz2bma9sinlrg7dip3jqms9gq4lr")))) (build-system gnu-build-system) (inputs `(("guile" ,guile-2.0) ("gnupg" ,gnupg) ("xclip" ,xclip))) (synopsis "GnuPG-based secret manager") (description "Shroud is a simple secret manager with a command line interface. The password database is stored as a Scheme s-expression and encrypted with a GnuPG key. Secrets consist of an arbitrary number of key/value pairs, making Shroud suitable for more than just password storage. For copying and pasting secrets into web browsers and other graphical applications, there is xclip integration." ) (home-page "") (license license:gpl3+))) (define-public yapet (package (name "yapet") (version "1.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.bz2")) (sha256 (base32 "0ydbnqw6icdh07pnv2w6dhvq501bdfvrklv4xmyr8znca9d753if")))) (build-system gnu-build-system) (inputs `(("ncurses" ,ncurses) ("openssl" ,openssl))) (native-inputs `(("pkg-config" ,pkg-config))) (synopsis "Yet Another Password Encryption Tool") (description "YAPET is a text based password manager using the Blowfish encryption algorithm. Because of its small footprint and very few library dependencies, it is suited for installing on desktop and server systems alike. The text based user interface allows you to run YAPET easily in a Secure Shell session. Two companion utilities enable users to convert CSV files to YAPET and vice versa.") (home-page "/") (license license:gpl3+))) (define-public cracklib (package (name "cracklib") (version "2.9.6") (source (origin (method url-fetch) (uri (string-append "/" "releases/download/" name "-" version "/" name "-" version ".tar.gz")) (sha256 (base32 "0hrkb0prf7n92w6rxgq0ilzkk6rkhpys2cfqkrbzswp27na7dkqp")))) (build-system gnu-build-system) (synopsis "Password checking library") (home-page "") (description "CrackLib is a library containing a C function which may be used in a passwd like program. The idea is simple: try to prevent users from choosing passwords that could be guessed by crack by filtering them out, at source.") (license license:lgpl2.1))) (define-public libpwquality (package (name "libpwquality") (version "1.3.0") (source (origin (method url-fetch) (uri (list (string-append "/" name "/" name "-" version ".tar.bz2") (string-append "/" version "/+download/" name "-" version ".tar.bz2"))) (sha256 (base32 "0aidriag6h0syfm33nzdfdsqgrnsgihwjv3a5lgkqch3w68fmlkl")))) (build-system gnu-build-system) (arguments '(#:configure-flags '("--disable-python-bindings"))) (inputs `(("cracklib" ,cracklib))) (synopsis "Password quality checker") (home-page "/") (description "Libpwquality is a library for password quality checking and generation of random passwords that pass the checks.") (license license:gpl2+))) (define-public assword (package (name "assword") (version "0.8") (source (origin (method url-fetch) (uri (list (string-append "/" "assword_" version ".orig.tar.gz"))) (sha256 (base32 "0dl4wizbi0r21wxzykm8s445xbvqim5nabi799dmpkdnnh8i546i")))) (arguments `(#:python ,python-2 irritatingly , tests do run but not there are two problems : variable mess to work with pygtk and ... what 's up with #:tests? #f #:phases (modify-phases %standard-phases (add-after 'install 'manpage (lambda* (#:key outputs #:allow-other-keys) (and (zero? (system* "make" "assword.1")) (install-file "assword.1" (string-append (assoc-ref outputs "out") "/share/man/man1")))))))) (build-system python-build-system) (native-inputs `(("help2man" ,help2man))) (inputs `(("python-setuptools" ,python2-setuptools) ("python2-xdo" ,python2-xdo) ("python2-pygpgme" ,python2-pygpgme) ("python2-pygtk" ,python2-pygtk))) (propagated-inputs `(("xclip" ,xclip))) (home-page "/") (synopsis "Password manager") (description "assword is a simple password manager using GPG-wrapped JSON files. It has a command line interface as well as a very simple graphical interface, which can even \"type\" your passwords into any X11 window.") (license license:gpl3+))) (define-public password-store (package (name "password-store") (version "1.6.5") (source (origin (method url-fetch) (uri (string-append "-store/snapshot/" name "-" version ".tar.xz")) (sha256 (base32 "05bk3lrp5jwg0v338lvylp7glpliydzz4jf5pjr6k3kagrv3jyik")))) (build-system gnu-build-system) (arguments '(#:phases (modify-phases %standard-phases (delete 'configure) (add-after The script requires ' ' at run - time , and this allows 'unpack 'patch-path (lambda* (#:key inputs outputs #:allow-other-keys) (let ((getopt (string-append (assoc-ref inputs "getopt") "/bin/getopt"))) (substitute* "src/password-store.sh" (("GETOPT=\"getopt\"") (string-append "GETOPT=\"" getopt "\""))) #t)))) #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:test-target "test")) (inputs `(("gnupg" ,gnupg) ("pwgen" ,pwgen) ("xclip" ,xclip) ("git" ,git) ("tree" ,tree) ("which" ,which))) (home-page "/") (synopsis "Encrypted password manager") (description "Password-store is a password manager which uses GnuPG to store and retrieve passwords. The tool stores each password in its own GnuPG-encrypted file, allowing the program to be simple yet secure. Synchronization is possible using the integrated git support, which commits changes to your password database to a git repository that can be managed through the pass command.") (license license:gpl2+)))
1a362e757e20f119f6cbd673fbcaa52ac37e98b22f70fd6b3d38912ccbd652f8
input-output-hk/plutus
PubKeyHashes.hs
{-# LANGUAGE PackageImports #-} # LANGUAGE TemplateHaskell # module Examples.PubKeyHashes where import "cryptonite" Crypto.PubKey.ECC.ECDSA import Crypto.PubKey.ECC.Generate import Crypto.PubKey.ECC.Types import "cryptonite" Crypto.Random import Data.Map (Map) import Data.Map qualified as Map import Data.Set (Set) import Data.Set qualified as Set import Examples.Keys import Ledger import UTxO import Witness Template Haskell splices ca n't use local definitions , but only imported ones ( stage restriction ) ; -- hence, we have got some defintions here that we want to use in 'Examples.PubKey'. -- This is very sad! t1Hash = hashTx $ Tx [] [TxOut val1Hash 1000] 1000 0 where val1Hash = scriptHash $$(lockWithPublicKeyValidator (toPublicKey myKeyPair1)) wit2Hash = validatorHash $$(revealPreimage "2") val1Hash = scriptHash $$(lockWithPublicKeyValidator (toPublicKey myKeyPair1))
null
https://raw.githubusercontent.com/input-output-hk/plutus/1af96af28f45030c94e11138a2f13869e9e63b79/doc/notes/model/UTxO.hsproj/Examples/PubKeyHashes.hs
haskell
# LANGUAGE PackageImports # hence, we have got some defintions here that we want to use in 'Examples.PubKey'. This is very sad!
# LANGUAGE TemplateHaskell # module Examples.PubKeyHashes where import "cryptonite" Crypto.PubKey.ECC.ECDSA import Crypto.PubKey.ECC.Generate import Crypto.PubKey.ECC.Types import "cryptonite" Crypto.Random import Data.Map (Map) import Data.Map qualified as Map import Data.Set (Set) import Data.Set qualified as Set import Examples.Keys import Ledger import UTxO import Witness Template Haskell splices ca n't use local definitions , but only imported ones ( stage restriction ) ; t1Hash = hashTx $ Tx [] [TxOut val1Hash 1000] 1000 0 where val1Hash = scriptHash $$(lockWithPublicKeyValidator (toPublicKey myKeyPair1)) wit2Hash = validatorHash $$(revealPreimage "2") val1Hash = scriptHash $$(lockWithPublicKeyValidator (toPublicKey myKeyPair1))
a1e07fb7d179bc29b115787ab118c71aa7dfd274785a0ef034c849f81afa4206
lehins/primal
MVar.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # module Main where import qualified Control.Concurrent.MVar as Base import Primal.Concurrent.MVar import Primal.Eval import Primal.Monad import Criterion.Main import Data.Coerce import qualified Data.IORef as Base import Primal.Ref import qualified UnliftIO.MVar as Unlift import Data.Atomics (atomicModifyIORefCAS, atomicModifyIORefCAS_) main :: IO () main = do let !i0 = 16 :: Integer !i1 = 17 :: Integer envBRef :: NFData e => e -> (BRef e RW -> Benchmark) -> Benchmark envBRef e g = e `deepseq` env (BNF <$> newBRef e) $ \ref -> g (coerce ref) envIORef :: NFData e => e -> (Base.IORef e -> Benchmark) -> Benchmark envIORef e g = e `deepseq` env (BNF <$> Base.newIORef e) $ \ref -> g (coerce ref) envMVar :: (NFData e) => e -> (MVar e RW -> Benchmark) -> Benchmark envMVar e g = e `deepseq` env (BNF <$> newMVar e) $ \(BNF var) -> g var envBaseMVar :: (NFData e) => e -> (Base.MVar e -> Benchmark) -> Benchmark envBaseMVar e g = e `deepseq` env (BNF <$> Base.newMVar e) $ \(BNF var) -> g var defaultMain [ bgroup "Int" [ bgroup "new" [ bench "newBRef" $ whnfIO $ newBRef i0 , bench "newIORef (base)" $ whnfIO $ Base.newIORef i0 , bench "newEmptyMVar" $ whnfIO newEmptyMVar , bench "newEmptyMVar (base)" $ whnfIO Base.newEmptyMVar , bench "newEmptyMVar (unliftio)" $ whnfIO Unlift.newEmptyMVar , bench "newMVar" $ whnfIO $ newMVar i0 , bench "newMVar (base)" $ whnfIO $ Base.newMVar i0 , bench "newMVar (unliftio)" $ whnfIO $ Unlift.newMVar i0 ] , bgroup "read" [ envBRef i0 $ \ref -> bench "readBRef" $ whnfIO $ readBRef ref , envIORef i0 $ \ref -> bench "readIORef (base)" $ whnfIO $ Base.readIORef ref , envMVar i0 $ \ref -> bench "readMVar" $ whnfIO $ readMVar ref , envBaseMVar i0 $ \ref -> bench "readMVar (base)" $ whnfIO $ Base.readMVar ref , envBaseMVar i0 $ \ref -> bench "readMVar (unliftio)" $ whnfIO $ Unlift.readMVar ref ] , bgroup "write" [ envBRef i0 $ \ref -> bench "writeBRef" $ whnfIO $ writeBRef ref i1 , envIORef i0 $ \ref -> bench "writeIORef" $ whnfIO $ Base.writeIORef ref i1 , envMVar i0 $ \ref -> bench "writeMVar" $ whnfIO $ writeMVar ref i1 ] , bgroup "modify" [ envBRef i0 $ \ref -> bench "modifyBRef_" $ whnfIO $ modifyBRef_ ref (+ i1) , envIORef i0 $ \ref -> bench "modifyIORef' (base)" $ whnfIO $ Base.modifyIORef' ref (+ i1) , envMVar i0 $ \ref -> bench "modifyMVar_" $ whnfIO $ modifyMVar_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVar_ (base)" $ whnfIO $ Base.modifyMVar_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVar_ (unliftio)" $ whnfIO $ Unlift.modifyMVar_ ref (pure . (+ i1)) ] , bgroup "modifyMVarMasked" [ envMVar i0 $ \ref -> bench "modifyMVarMasked_" $ whnfIO $ modifyMVarMasked_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVarMasked_ (base)" $ whnfIO $ Base.modifyMVarMasked_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVarMasked_ (unliftio)" $ whnfIO $ Unlift.modifyMVarMasked_ ref (pure . (+ i1)) ] ] , bgroup "atomicWrite" [ envBRef i0 $ \ref -> bench "atomicWriteBRef" $ whnfIO $ atomicWriteBRef ref i1 , envIORef i0 $ \ref -> bench "atomicWriteIORef" $ whnfIO $ Base.atomicWriteIORef ref i1 ] , bgroup "atomicModify" [ envBRef i0 $ \ref -> bench "atomicModifyBRef" $ whnfIO $ atomicModifyBRef ref $ \x -> (x + i1, x) , envIORef i0 $ \ref -> bench "atomicModifyIORefCAS" $ whnfIO $ atomicModifyIORefCAS ref $ \x -> (x + i1, x) , envIORef i0 $ \ref -> bench "atomicModifyIORef'" $ whnfIO $ Base.atomicModifyIORef' ref $ \x -> (x + i1, x) ] , bgroup "atomicModify_" [ envBRef i0 $ \ref -> bench "atomicModifyBRef_" $ whnfIO $ atomicModifyBRef_ ref (+ i1) , envIORef i0 $ \ref -> bench "atomicModifyIORefCAS_" $ whnfIO $ atomicModifyIORefCAS_ ref (+ i1) , envIORef i0 $ \ref -> bench "atomicModifyIORef'" $ whnfIO $ Base.atomicModifyIORef' ref $ \x -> (x + i1, ()) ] ]
null
https://raw.githubusercontent.com/lehins/primal/c620bfd4f2a6475f1c12183fbe8138cf29ab1dad/primal/bench/MVar.hs
haskell
# LANGUAGE BangPatterns #
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # module Main where import qualified Control.Concurrent.MVar as Base import Primal.Concurrent.MVar import Primal.Eval import Primal.Monad import Criterion.Main import Data.Coerce import qualified Data.IORef as Base import Primal.Ref import qualified UnliftIO.MVar as Unlift import Data.Atomics (atomicModifyIORefCAS, atomicModifyIORefCAS_) main :: IO () main = do let !i0 = 16 :: Integer !i1 = 17 :: Integer envBRef :: NFData e => e -> (BRef e RW -> Benchmark) -> Benchmark envBRef e g = e `deepseq` env (BNF <$> newBRef e) $ \ref -> g (coerce ref) envIORef :: NFData e => e -> (Base.IORef e -> Benchmark) -> Benchmark envIORef e g = e `deepseq` env (BNF <$> Base.newIORef e) $ \ref -> g (coerce ref) envMVar :: (NFData e) => e -> (MVar e RW -> Benchmark) -> Benchmark envMVar e g = e `deepseq` env (BNF <$> newMVar e) $ \(BNF var) -> g var envBaseMVar :: (NFData e) => e -> (Base.MVar e -> Benchmark) -> Benchmark envBaseMVar e g = e `deepseq` env (BNF <$> Base.newMVar e) $ \(BNF var) -> g var defaultMain [ bgroup "Int" [ bgroup "new" [ bench "newBRef" $ whnfIO $ newBRef i0 , bench "newIORef (base)" $ whnfIO $ Base.newIORef i0 , bench "newEmptyMVar" $ whnfIO newEmptyMVar , bench "newEmptyMVar (base)" $ whnfIO Base.newEmptyMVar , bench "newEmptyMVar (unliftio)" $ whnfIO Unlift.newEmptyMVar , bench "newMVar" $ whnfIO $ newMVar i0 , bench "newMVar (base)" $ whnfIO $ Base.newMVar i0 , bench "newMVar (unliftio)" $ whnfIO $ Unlift.newMVar i0 ] , bgroup "read" [ envBRef i0 $ \ref -> bench "readBRef" $ whnfIO $ readBRef ref , envIORef i0 $ \ref -> bench "readIORef (base)" $ whnfIO $ Base.readIORef ref , envMVar i0 $ \ref -> bench "readMVar" $ whnfIO $ readMVar ref , envBaseMVar i0 $ \ref -> bench "readMVar (base)" $ whnfIO $ Base.readMVar ref , envBaseMVar i0 $ \ref -> bench "readMVar (unliftio)" $ whnfIO $ Unlift.readMVar ref ] , bgroup "write" [ envBRef i0 $ \ref -> bench "writeBRef" $ whnfIO $ writeBRef ref i1 , envIORef i0 $ \ref -> bench "writeIORef" $ whnfIO $ Base.writeIORef ref i1 , envMVar i0 $ \ref -> bench "writeMVar" $ whnfIO $ writeMVar ref i1 ] , bgroup "modify" [ envBRef i0 $ \ref -> bench "modifyBRef_" $ whnfIO $ modifyBRef_ ref (+ i1) , envIORef i0 $ \ref -> bench "modifyIORef' (base)" $ whnfIO $ Base.modifyIORef' ref (+ i1) , envMVar i0 $ \ref -> bench "modifyMVar_" $ whnfIO $ modifyMVar_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVar_ (base)" $ whnfIO $ Base.modifyMVar_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVar_ (unliftio)" $ whnfIO $ Unlift.modifyMVar_ ref (pure . (+ i1)) ] , bgroup "modifyMVarMasked" [ envMVar i0 $ \ref -> bench "modifyMVarMasked_" $ whnfIO $ modifyMVarMasked_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVarMasked_ (base)" $ whnfIO $ Base.modifyMVarMasked_ ref (pure . (+ i1)) , envBaseMVar i0 $ \ref -> bench "modifyMVarMasked_ (unliftio)" $ whnfIO $ Unlift.modifyMVarMasked_ ref (pure . (+ i1)) ] ] , bgroup "atomicWrite" [ envBRef i0 $ \ref -> bench "atomicWriteBRef" $ whnfIO $ atomicWriteBRef ref i1 , envIORef i0 $ \ref -> bench "atomicWriteIORef" $ whnfIO $ Base.atomicWriteIORef ref i1 ] , bgroup "atomicModify" [ envBRef i0 $ \ref -> bench "atomicModifyBRef" $ whnfIO $ atomicModifyBRef ref $ \x -> (x + i1, x) , envIORef i0 $ \ref -> bench "atomicModifyIORefCAS" $ whnfIO $ atomicModifyIORefCAS ref $ \x -> (x + i1, x) , envIORef i0 $ \ref -> bench "atomicModifyIORef'" $ whnfIO $ Base.atomicModifyIORef' ref $ \x -> (x + i1, x) ] , bgroup "atomicModify_" [ envBRef i0 $ \ref -> bench "atomicModifyBRef_" $ whnfIO $ atomicModifyBRef_ ref (+ i1) , envIORef i0 $ \ref -> bench "atomicModifyIORefCAS_" $ whnfIO $ atomicModifyIORefCAS_ ref (+ i1) , envIORef i0 $ \ref -> bench "atomicModifyIORef'" $ whnfIO $ Base.atomicModifyIORef' ref $ \x -> (x + i1, ()) ] ]
4848ad4f7ebb474feeba9540bb1a77083bf4c5a8f48e654a60705b7c63100e40
onedata/op-worker
monitoring_state.erl
%%%------------------------------------------------------------------- @author ( C ) 2016 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Persistent state of monitoring worker. %%% @end %%%------------------------------------------------------------------- -module(monitoring_state). -author("Michal Wrona"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). %% API -export([save/1, get/1, exists/1, update/2, delete/1, list/0]). -export([run_in_critical_section/2, encode_id/1]). %% datastore_model callbacks -export([get_ctx/0, get_record_struct/1]). -type key() :: #monitoring_id{} | datastore:key(). -type record() :: #monitoring_state{}. -type doc() :: datastore_doc:doc(record()). -type diff() :: datastore_doc:diff(record()). -define(CTX, #{ model => ?MODULE, fold_enabled => true }). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Saves monitoring state. %% @end %%-------------------------------------------------------------------- -spec save(doc()) -> {ok, key()} | {error, term()}. save(Doc) -> ?extract_key(datastore_model:save(?CTX, Doc)). %%-------------------------------------------------------------------- %% @doc %% Updates monitoring state. %% @end %%-------------------------------------------------------------------- -spec update(key(), diff()) -> {ok, key()} | {error, term()}. update(#monitoring_id{} = MonitoringId, Diff) -> monitoring_state:update(encode_id(MonitoringId), Diff); update(Key, Diff) -> ?extract_key(datastore_model:update(?CTX, Key, Diff)). %%-------------------------------------------------------------------- %% @doc %% Returns monitoring state. %% @end %%-------------------------------------------------------------------- -spec get(key()) -> {ok, doc()} | {error, term()}. get(#monitoring_id{} = MonitoringId) -> monitoring_state:get(encode_id(MonitoringId)); get(Key) -> datastore_model:get(?CTX, Key). %%-------------------------------------------------------------------- %% @doc %% Checks whether monitoring state exists. %% @end %%-------------------------------------------------------------------- -spec exists(key()) -> boolean(). exists(#monitoring_id{} = MonitoringId) -> monitoring_state:exists(encode_id(MonitoringId)); exists(Key) -> {ok, Exists} = datastore_model:exists(?CTX, Key), Exists. %%-------------------------------------------------------------------- %% @doc %% Deletes monitoring state. %% @end %%-------------------------------------------------------------------- -spec delete(key()) -> ok | {error, term()}. delete(#monitoring_id{} = MonitoringId) -> monitoring_state:delete(encode_id(MonitoringId)); delete(Key) -> datastore_model:delete(?CTX, Key). %%-------------------------------------------------------------------- %% @doc %% Returns list of all records. %% @end %%-------------------------------------------------------------------- -spec list() -> {ok, [doc()]} | {error, term()}. list() -> datastore_model:fold(?CTX, fun(Doc, Acc) -> {ok, [Doc | Acc]} end, []). %%-------------------------------------------------------------------- %% @doc Runs given function within locked ResourceId . This function makes sure that 2 funs with same ResourceId wo n't run at the same time . %% @end %%-------------------------------------------------------------------- -spec run_in_critical_section(key(), Fun :: fun(() -> Result :: term())) -> Result :: term(). run_in_critical_section(#monitoring_id{} = MonitoringId, Fun) -> monitoring_state:run_in_critical_section(encode_id(MonitoringId), Fun); run_in_critical_section(ResourceId, Fun) -> critical_section:run([?MODULE, ResourceId], Fun). %%-------------------------------------------------------------------- %% @doc record to datastore i d. %% @end %%-------------------------------------------------------------------- -spec encode_id(#monitoring_id{}) -> datastore:key(). encode_id(MonitoringId) -> http_utils:base64url_encode(crypto:hash(md5, term_to_binary(MonitoringId))). %%%=================================================================== %%% datastore_model callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Returns model's context. %% @end %%-------------------------------------------------------------------- -spec get_ctx() -> datastore:ctx(). get_ctx() -> ?CTX. %%-------------------------------------------------------------------- %% @doc %% Returns model's record structure in provided version. %% @end %%-------------------------------------------------------------------- -spec get_record_struct(datastore_model:record_version()) -> datastore_model:record_struct(). get_record_struct(1) -> {record, [ {monitoring_id, {record, [ {main_subject_type, atom}, {main_subject_id, binary}, {metric_type, atom}, {secondary_subject_type, atom}, {secondary_subject_id, binary}, {provider_id, binary} ]}}, {rrd_path, string}, {state_buffer, #{term => term}}, {last_update_time, integer} ]}.
null
https://raw.githubusercontent.com/onedata/op-worker/b09f05b6928121cec4d6b41ce8037fe056e6b4b3/src/modules/datastore/models/system/monitoring_state.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc Persistent state of monitoring worker. @end ------------------------------------------------------------------- API datastore_model callbacks =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Saves monitoring state. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Updates monitoring state. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Returns monitoring state. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Checks whether monitoring state exists. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Deletes monitoring state. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Returns list of all records. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- =================================================================== datastore_model callbacks =================================================================== -------------------------------------------------------------------- @doc Returns model's context. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Returns model's record structure in provided version. @end --------------------------------------------------------------------
@author ( C ) 2016 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(monitoring_state). -author("Michal Wrona"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). -export([save/1, get/1, exists/1, update/2, delete/1, list/0]). -export([run_in_critical_section/2, encode_id/1]). -export([get_ctx/0, get_record_struct/1]). -type key() :: #monitoring_id{} | datastore:key(). -type record() :: #monitoring_state{}. -type doc() :: datastore_doc:doc(record()). -type diff() :: datastore_doc:diff(record()). -define(CTX, #{ model => ?MODULE, fold_enabled => true }). -spec save(doc()) -> {ok, key()} | {error, term()}. save(Doc) -> ?extract_key(datastore_model:save(?CTX, Doc)). -spec update(key(), diff()) -> {ok, key()} | {error, term()}. update(#monitoring_id{} = MonitoringId, Diff) -> monitoring_state:update(encode_id(MonitoringId), Diff); update(Key, Diff) -> ?extract_key(datastore_model:update(?CTX, Key, Diff)). -spec get(key()) -> {ok, doc()} | {error, term()}. get(#monitoring_id{} = MonitoringId) -> monitoring_state:get(encode_id(MonitoringId)); get(Key) -> datastore_model:get(?CTX, Key). -spec exists(key()) -> boolean(). exists(#monitoring_id{} = MonitoringId) -> monitoring_state:exists(encode_id(MonitoringId)); exists(Key) -> {ok, Exists} = datastore_model:exists(?CTX, Key), Exists. -spec delete(key()) -> ok | {error, term()}. delete(#monitoring_id{} = MonitoringId) -> monitoring_state:delete(encode_id(MonitoringId)); delete(Key) -> datastore_model:delete(?CTX, Key). -spec list() -> {ok, [doc()]} | {error, term()}. list() -> datastore_model:fold(?CTX, fun(Doc, Acc) -> {ok, [Doc | Acc]} end, []). Runs given function within locked ResourceId . This function makes sure that 2 funs with same ResourceId wo n't run at the same time . -spec run_in_critical_section(key(), Fun :: fun(() -> Result :: term())) -> Result :: term(). run_in_critical_section(#monitoring_id{} = MonitoringId, Fun) -> monitoring_state:run_in_critical_section(encode_id(MonitoringId), Fun); run_in_critical_section(ResourceId, Fun) -> critical_section:run([?MODULE, ResourceId], Fun). record to datastore i d. -spec encode_id(#monitoring_id{}) -> datastore:key(). encode_id(MonitoringId) -> http_utils:base64url_encode(crypto:hash(md5, term_to_binary(MonitoringId))). -spec get_ctx() -> datastore:ctx(). get_ctx() -> ?CTX. -spec get_record_struct(datastore_model:record_version()) -> datastore_model:record_struct(). get_record_struct(1) -> {record, [ {monitoring_id, {record, [ {main_subject_type, atom}, {main_subject_id, binary}, {metric_type, atom}, {secondary_subject_type, atom}, {secondary_subject_id, binary}, {provider_id, binary} ]}}, {rrd_path, string}, {state_buffer, #{term => term}}, {last_update_time, integer} ]}.
10b94d29bace1b1aa9dc9d23d10dbd3db73ac9304c16113d6f34cc00d2c51a70
privet-kitty/cl-competitive
gray-code.lisp
(defpackage :cp/test/gray-code (:use :cl :fiveam :cp/gray-code) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/gray-code) (in-suite base-suite) (test gray-code (is (zerop (gray-to-natural 0))) (is (zerop (natural-to-gray 0))) (finishes (dotimes (x 100) (assert (= (natural-to-gray (gray-to-natural x)))) (assert (= (gray-to-natural (natural-to-gray x)))) (assert (= 1 (logcount (logxor (natural-to-gray (+ x 1)) (natural-to-gray x))))))))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/test/gray-code.lisp
lisp
(defpackage :cp/test/gray-code (:use :cl :fiveam :cp/gray-code) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/gray-code) (in-suite base-suite) (test gray-code (is (zerop (gray-to-natural 0))) (is (zerop (natural-to-gray 0))) (finishes (dotimes (x 100) (assert (= (natural-to-gray (gray-to-natural x)))) (assert (= (gray-to-natural (natural-to-gray x)))) (assert (= 1 (logcount (logxor (natural-to-gray (+ x 1)) (natural-to-gray x))))))))
33d8346f4c56a95689f9da2c3e4f0cccec686328eeeca3b082b9ff4be96a7ff7
serioga/webapp-clojure-2020
core.clj
(ns lib.clojure.core (:refer-clojure :exclude [assert, future]) (:require [lib.clojure.assert] [lib.clojure.exception] [lib.clojure.future] [lib.clojure.lang] [lib.clojure.print] [medley.core] [potemkin :refer [import-vars]])) (set! *warn-on-reflection* true) •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• (import-vars [lib.clojure.assert assert, assert-pred, assert-try] [lib.clojure.exception ex-message-all, ex-root-cause] [lib.clojure.future future] [lib.clojure.print pr-str*] [lib.clojure.lang add-method, first-arg, second-arg, invoke, select, unwrap-fn, unwrap-future]) •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• ;; The `declare` is a workaround for name resolution in Cursive. ;; See -ide/cursive/issues/2411. (declare find-first map-entry) (import-vars [medley.core find-first map-entry]) (declare map-kv map-keys map-vals) (import-vars [medley.core map-kv map-keys map-vals]) (declare filter-kv filter-keys filter-vals) (import-vars [medley.core filter-kv filter-keys filter-vals]) (declare remove-kv remove-keys remove-vals) (import-vars [medley.core remove-kv remove-keys remove-vals]) (declare deep-merge) (import-vars [medley.core deep-merge]) ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
null
https://raw.githubusercontent.com/serioga/webapp-clojure-2020/306ea852739eb318b286731c7dbbc6724ee10586/src/lib/clojure/core.clj
clojure
The `declare` is a workaround for name resolution in Cursive. See -ide/cursive/issues/2411.
(ns lib.clojure.core (:refer-clojure :exclude [assert, future]) (:require [lib.clojure.assert] [lib.clojure.exception] [lib.clojure.future] [lib.clojure.lang] [lib.clojure.print] [medley.core] [potemkin :refer [import-vars]])) (set! *warn-on-reflection* true) •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• (import-vars [lib.clojure.assert assert, assert-pred, assert-try] [lib.clojure.exception ex-message-all, ex-root-cause] [lib.clojure.future future] [lib.clojure.print pr-str*] [lib.clojure.lang add-method, first-arg, second-arg, invoke, select, unwrap-fn, unwrap-future]) •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• (declare find-first map-entry) (import-vars [medley.core find-first map-entry]) (declare map-kv map-keys map-vals) (import-vars [medley.core map-kv map-keys map-vals]) (declare filter-kv filter-keys filter-vals) (import-vars [medley.core filter-kv filter-keys filter-vals]) (declare remove-kv remove-keys remove-vals) (import-vars [medley.core remove-kv remove-keys remove-vals]) (declare deep-merge) (import-vars [medley.core deep-merge]) ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
efc921d774ef255980396dcb278b16aaf9c9de9d439aa5214977a82a5b00c2fd
janestreet/merlin-jst
typeclass.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Parsetree open Asttypes open Path open Types open Typecore open Typetexp open Format type 'a class_info = { cls_id : Ident.t; cls_id_loc : string loc; cls_decl : class_declaration; cls_ty_id : Ident.t; cls_ty_decl : class_type_declaration; cls_obj_id : Ident.t; cls_obj_abbr : type_declaration; cls_typesharp_id : Ident.t; cls_abbr : type_declaration; cls_arity : int; cls_pub_methods : string list; cls_info : 'a; } type class_type_info = { clsty_ty_id : Ident.t; clsty_id_loc : string loc; clsty_ty_decl : class_type_declaration; clsty_obj_id : Ident.t; clsty_obj_abbr : type_declaration; clsty_typesharp_id : Ident.t; clsty_abbr : type_declaration; clsty_info : Typedtree.class_type_declaration; } type 'a full_class = { id : Ident.t; id_loc : tag loc; clty: class_declaration; ty_id: Ident.t; cltydef: class_type_declaration; obj_id: Ident.t; obj_abbr: type_declaration; cl_id: Ident.t; cl_abbr: type_declaration; arity: int; pub_meths: string list; coe: Warnings.loc list; req: 'a Typedtree.class_infos; } type kind = | Object | Class | Class_type type final = | Final | Not_final let kind_of_final = function | Final -> Object | Not_final -> Class type error = | Unconsistent_constraint of Errortrace.unification_error | Field_type_mismatch of string * string * Errortrace.unification_error | Unexpected_field of type_expr * string | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Errortrace.unification_error | Virtual_class of kind * string list * string list | Undeclared_methods of kind * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of Errortrace.unification_error | Bad_parameters of Ident.t * type_expr * type_expr | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * (type_expr * bool * string * type_expr) | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * Errortrace.unification_error | Self_clash of Errortrace.unification_error | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of class_signature | Polymorphic_class_parameter exception Error of Location.t * Env.t * error exception Error_forward of Location.error open Typedtree let type_open_descr : (?used_slot:bool ref -> Env.t -> Parsetree.open_description -> open_description * Env.t) ref = ref (fun ?used_slot:_ _ -> assert false) let ctyp desc typ env loc = { ctyp_desc = desc; ctyp_type = typ; ctyp_loc = loc; ctyp_env = env; ctyp_attributes = [] } (* Path associated to the temporary class type of a class being typed (its constructor is not available). *) let unbound_class = Env.unbound_class (************************************) (* Some operations on class types *) (************************************) let extract_constraints cty = let sign = Btype.signature_of_class_type cty in (Btype.instance_vars sign, Btype.methods sign, Btype.concrete_methods sign) (* Record a class type *) let rc node = Cmt_format.add_saved_type (Cmt_format.Partial_class_expr node); node let update_class_signature loc env ~warn_implicit_public virt kind sign = let implicit_public, implicit_declared = Ctype.update_class_signature env sign in if implicit_declared <> [] then begin match virt with Should perhaps emit warning 17 here | Concrete -> raise (Error(loc, env, Undeclared_methods(kind, implicit_declared))) end; if warn_implicit_public && implicit_public <> [] then begin Location.prerr_warning loc (Warnings.Implicit_public_methods implicit_public) end let complete_class_signature loc env virt kind sign = update_class_signature loc env ~warn_implicit_public:false virt kind sign; Ctype.hide_private_methods env sign let complete_class_type loc env virt kind typ = let sign = Btype.signature_of_class_type typ in complete_class_signature loc env virt kind sign let check_virtual loc env virt kind sign = match virt with | Virtual -> () | Concrete -> match Btype.virtual_methods sign, Btype.virtual_instance_vars sign with | [], [] -> () | meths, vars -> raise(Error(loc, env, Virtual_class(kind, meths, vars))) let rec check_virtual_clty loc env virt kind clty = match clty with | Cty_constr(_, _, clty) | Cty_arrow(_, _, clty) -> check_virtual_clty loc env virt kind clty | Cty_signature sign -> check_virtual loc env virt kind sign (* Return the constructor type associated to a class type *) let rec constructor_type constr cty = match cty with Cty_constr (_, _, cty) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow (l, ty, cty) -> let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in let ty = Ctype.newmono ty in Ctype.newty (Tarrow (arrow_desc, ty, constructor_type constr cty, commu_ok)) (***********************************) (* Primitives for typing classes *) (***********************************) let raise_add_method_failure loc env label sign failure = match (failure : Ctype.add_method_failure) with | Ctype.Unexpected_method -> raise(Error(loc, env, Unexpected_field (sign.Types.csig_self, label))) | Ctype.Type_mismatch trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let raise_add_instance_variable_failure loc env label failure = match (failure : Ctype.add_instance_variable_failure) with | Ctype.Mutability_mismatch mut -> raise (Error(loc, env, Mutability_mismatch(label, mut))) | Ctype.Type_mismatch trace -> raise (Error(loc, env, Field_type_mismatch("instance variable", label, trace))) let raise_inherit_class_signature_failure loc env sign = function | Ctype.Self_type_mismatch trace -> raise(Error(loc, env, Self_clash trace)) | Ctype.Method(label, failure) -> raise_add_method_failure loc env label sign failure | Ctype.Instance_variable(label, failure) -> raise_add_instance_variable_failure loc env label failure let add_method loc env label priv virt ty sign = match Ctype.add_method env label priv virt ty sign with | () -> () | exception Ctype.Add_method_failed failure -> raise_add_method_failure loc env label sign failure let add_instance_variable ~strict loc env label mut virt ty sign = match Ctype.add_instance_variable ~strict env label mut virt ty sign with | () -> () | exception Ctype.Add_instance_variable_failed failure -> raise_add_instance_variable_failure loc env label failure let inherit_class_signature ~strict loc env sign1 sign2 = match Ctype.inherit_class_signature ~strict env sign1 sign2 with | () -> () | exception Ctype.Inherit_class_signature_failed failure -> raise_inherit_class_signature_failure loc env sign1 failure let inherit_class_type ~strict loc env sign1 cty2 = let sign2 = match Btype.scrape_class_type cty2 with | Cty_signature sign2 -> sign2 | _ -> raise(Error(loc, env, Structure_expected cty2)) in inherit_class_signature ~strict loc env sign1 sign2 let unify_delayed_method_type loc env label ty expected_ty= match Ctype.unify env ty expected_ty with | () -> () | exception Ctype.Unify trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let type_constraint val_env sty sty' loc = let cty = transl_simple_type val_env false Global sty in let ty = cty.ctyp_type in let cty' = transl_simple_type val_env false Global sty' in let ty' = cty'.ctyp_type in begin try Ctype.unify val_env ty ty' with Ctype.Unify err -> raise(Error(loc, val_env, Unconsistent_constraint err)); end; (cty, cty') let make_method loc cl_num expr = let open Ast_helper in let mkid s = mkloc s loc in Exp.fun_ ~loc:expr.pexp_loc Nolabel None (Pat.alias ~loc (Pat.var ~loc (mkid "self-*")) (mkid ("self-" ^ cl_num))) expr (*******************************) let delayed_meth_specs = ref [] let rec class_type_field env sign self_scope ctf = let loc = ctf.pctf_loc in let mkctf desc = { ctf_desc = desc; ctf_loc = loc; ctf_attributes = ctf.pctf_attributes } in let mkctf_with_attrs f = Builtin_attributes.warning_scope ctf.pctf_attributes (fun () -> mkctf (f ())) in match ctf.pctf_desc with | Pctf_inherit sparent -> mkctf_with_attrs (fun () -> let parent = class_type env Virtual self_scope sparent in complete_class_type parent.cltyp_loc env Virtual Class_type parent.cltyp_type; inherit_class_type ~strict:false loc env sign parent.cltyp_type; Tctf_inherit parent) | Pctf_val ({txt=lab}, mut, virt, sty) -> mkctf_with_attrs (fun () -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in add_instance_variable ~strict:false loc env lab mut virt ty sign; Tctf_val (lab, mut, virt, cty)) | Pctf_method ({txt=lab}, priv, virt, sty) -> mkctf_with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in match sty.ptyp_desc, priv with | Ptyp_poly ([],sty'), Public -> let expected_ty = Ctype.newvar () in add_method loc env lab priv virt expected_ty sign; let returned_cty = ctyp Ttyp_any (Ctype.newty Tnil) env loc in delayed_meth_specs := Warnings.mk_lazy (fun () -> let cty = transl_simple_type_univars env sty' in let ty = cty.ctyp_type in unify_delayed_method_type loc env lab ty expected_ty; returned_cty.ctyp_desc <- Ttyp_poly ([], cty); returned_cty.ctyp_type <- ty; ) :: !delayed_meth_specs; Tctf_method (lab, priv, virt, returned_cty) | _ -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in add_method loc env lab priv virt ty sign; Tctf_method (lab, priv, virt, cty)) | Pctf_constraint (sty, sty') -> mkctf_with_attrs (fun () -> let (cty, cty') = type_constraint env sty sty' ctf.pctf_loc in Tctf_constraint (cty, cty')) | Pctf_attribute x -> Builtin_attributes.warning_attribute x; mkctf (Tctf_attribute x) | Pctf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_signature virt env pcsig self_scope loc = let {pcsig_self=sty; pcsig_fields=psign} = pcsig in let sign = Ctype.new_class_signature () in (* Introduce a dummy method preventing self type from being closed. *) Ctype.add_dummy_method env ~scope:self_scope sign; let self_cty = transl_simple_type env false Global sty in let self_type = self_cty.ctyp_type in begin try Ctype.unify env self_type sign.csig_self with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, env, Pattern_type_clash self_type)) end; (* Class type fields *) let fields = Builtin_attributes.warning_scope [] (fun () -> List.map (class_type_field env sign self_scope) psign) in check_virtual loc env virt Class_type sign; { csig_self = self_cty; csig_fields = fields; csig_type = sign; } and class_type env virt self_scope scty = Builtin_attributes.warning_scope scty.pcty_attributes (fun () -> class_type_aux env virt self_scope scty) and class_type_aux env virt self_scope scty = let cltyp desc typ = { cltyp_desc = desc; cltyp_type = typ; cltyp_loc = scty.pcty_loc; cltyp_env = env; cltyp_attributes = scty.pcty_attributes; } in match scty.pcty_desc with | Pcty_constr (lid, styl) -> let (path, decl) = Env.lookup_cltype ~loc:scty.pcty_loc lid.txt env in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, env, Unbound_class_type_2 lid.txt)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method env ~scope:self_scope (Btype.signature_of_class_type clty); if List.length params <> List.length styl then raise(Error(scty.pcty_loc, env, Parameter_arity_mismatch (lid.txt, List.length params, List.length styl))); let ctys = List.map2 (fun sty ty -> let cty' = transl_simple_type env false Global sty in let ty' = cty'.ctyp_type in begin try Ctype.unify env ty' ty with Ctype.Unify err -> raise(Error(sty.ptyp_loc, env, Parameter_mismatch err)) end; cty' ) styl params in let typ = Cty_constr (path, params, clty) in (* Check for unexpected virtual methods *) check_virtual_clty scty.pcty_loc env virt Class_type typ; cltyp (Tcty_constr ( path, lid , ctys)) typ | Pcty_signature pcsig -> let clsig = class_signature virt env pcsig self_scope scty.pcty_loc in let typ = Cty_signature clsig.csig_type in cltyp (Tcty_signature clsig) typ | Pcty_arrow (l, sty, scty) -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in let ty = if Btype.is_optional l then Ctype.newty (Tconstr(Predef.path_option,[ty], ref Mnil)) else ty in let clty = class_type env virt self_scope scty in let typ = Cty_arrow (l, ty, clty.cltyp_type) in cltyp (Tcty_arrow (l, cty, clty)) typ | Pcty_open (od, e) -> let (od, newenv) = !type_open_descr env od in let clty = class_type newenv virt self_scope e in cltyp (Tcty_open (od, clty)) clty.cltyp_type | Pcty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let class_type env virt self_scope scty = delayed_meth_specs := []; let cty = class_type env virt self_scope scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty (*******************************) let enter_ancestor_val name val_env = Env.enter_unbound_value name Val_unbound_ancestor val_env let enter_self_val name val_env = Env.enter_unbound_value name Val_unbound_self val_env let enter_instance_var_val name val_env = Env.enter_unbound_value name Val_unbound_instance_variable val_env let enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env = let check s = Warnings.Unused_ancestor s in let kind = Val_anc (sign, meths, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.enter_value ~check name desc met_env let add_self_met loc id sign self_var_kind vars cl_num as_var ty attrs met_env = let check = if as_var then (fun s -> Warnings.Unused_var s) else (fun s -> Warnings.Unused_var_strict s) in let kind = Val_self (sign, self_var_kind, vars, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value ~check id desc met_env let add_instance_var_met loc label id sign cl_num attrs met_env = let mut, ty = match Vars.find label sign.csig_vars with | (mut, _, ty) -> mut, ty | exception Not_found -> assert false in let kind = Val_ivar (mut, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value id desc met_env let add_instance_vars_met loc vars sign cl_num met_env = List.fold_left (fun met_env (label, id) -> add_instance_var_met loc label id sign cl_num [] met_env) met_env vars type intermediate_class_field = | Inherit of { override : override_flag; parent : class_expr; super : string option; inherited_vars : (string * Ident.t) list; super_meths : (string * Ident.t) list; loc : Location.t; attributes : attribute list; } | Virtual_val of { label : string loc; mut : mutable_flag; id : Ident.t; cty : core_type; already_declared : bool; loc : Location.t; attributes : attribute list; } | Concrete_val of { label : string loc; mut : mutable_flag; id : Ident.t; override : override_flag; definition : expression; already_declared : bool; loc : Location.t; attributes : attribute list; } | Virtual_method of { label : string loc; priv : private_flag; cty : core_type; loc : Location.t; attributes : attribute list; } | Concrete_method of { label : string loc; priv : private_flag; override : override_flag; sdefinition : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Constraint of { cty1 : core_type; cty2 : core_type; loc : Location.t; attributes : attribute list; } | Initializer of { sexpr : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Attribute of { attribute : attribute; loc : Location.t; attributes : attribute list; } type first_pass_accummulater = { rev_fields : intermediate_class_field list; val_env : Env.t; par_env : Env.t; concrete_meths : MethSet.t; concrete_vals : VarSet.t; local_meths : MethSet.t; local_vals : VarSet.t; vars : Ident.t Vars.t; } let rec class_field_first_pass self_loc cl_num sign self_scope acc cf = let { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } = acc in let loc = cf.pcf_loc in let attributes = cf.pcf_attributes in let with_attrs f = Builtin_attributes.warning_scope attributes f in match cf.pcf_desc with | Pcf_inherit (override, sparent, super) -> with_attrs (fun () -> let parent = class_expr cl_num val_env par_env Virtual self_scope sparent in complete_class_type parent.cl_loc par_env Virtual Class parent.cl_type; inherit_class_type ~strict:true loc val_env sign parent.cl_type; let parent_sign = Btype.signature_of_class_type parent.cl_type in let new_concrete_meths = Btype.concrete_methods parent_sign in let new_concrete_vals = Btype.concrete_instance_vars parent_sign in let over_meths = MethSet.inter new_concrete_meths concrete_meths in let over_vals = VarSet.inter new_concrete_vals concrete_vals in begin match override with | Fresh -> let cname = match parent.cl_type with | Cty_constr (p, _, _) -> Path.name p | _ -> "inherited" in if not (MethSet.is_empty over_meths) then Location.prerr_warning loc (Warnings.Method_override (cname :: MethSet.elements over_meths)); if not (VarSet.is_empty over_vals) then Location.prerr_warning loc (Warnings.Instance_variable_override (cname :: VarSet.elements over_vals)); | Override -> if MethSet.is_empty over_meths && VarSet.is_empty over_vals then raise (Error(loc, val_env, No_overriding ("",""))) end; let concrete_vals = VarSet.union new_concrete_vals concrete_vals in let concrete_meths = MethSet.union new_concrete_meths concrete_meths in let val_env, par_env, inherited_vars, vars = Vars.fold (fun label _ (val_env, par_env, inherited_vars, vars) -> let val_env = enter_instance_var_val label val_env in let par_env = enter_instance_var_val label par_env in let id = Ident.create_local label in let inherited_vars = (label, id) :: inherited_vars in let vars = Vars.add label id vars in (val_env, par_env, inherited_vars, vars)) parent_sign.csig_vars (val_env, par_env, [], vars) in (* Methods available through super *) let super_meths = MethSet.fold (fun label acc -> (label, Ident.create_local label) :: acc) new_concrete_meths [] in Super let (val_env, par_env, super) = match super with | None -> (val_env, par_env, None) | Some {txt=name} -> let val_env = enter_ancestor_val name val_env in let par_env = enter_ancestor_val name par_env in (val_env, par_env, Some name) in let field = Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; concrete_meths; concrete_vals; vars }) | Pcf_val (label, mut, Cfk_virtual styp) -> with_attrs (fun () -> if !Clflags.principal then Ctype.begin_def (); let cty = Typetexp.transl_simple_type val_env false Global styp in let ty = cty.ctyp_type in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure ty end; add_instance_variable ~strict:true loc val_env label.txt mut Virtual ty sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Virtual_val { label; mut; id; cty; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; vars }) | Pcf_val (label, mut, Cfk_concrete (override, sdefinition)) -> with_attrs (fun () -> if VarSet.mem label.txt local_vals then raise(Error(loc, val_env, Duplicate ("instance variable", label.txt))); if VarSet.mem label.txt concrete_vals then begin if override = Fresh then Location.prerr_warning label.loc (Warnings.Instance_variable_override[label.txt]) end else begin if override = Override then raise(Error(loc, val_env, No_overriding ("instance variable", label.txt))) end; if !Clflags.principal then Ctype.begin_def (); let definition = type_exp val_env sdefinition in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure definition.exp_type end; add_instance_variable ~strict:true loc val_env label.txt mut Concrete definition.exp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_vals = VarSet.add label.txt concrete_vals in let local_vals = VarSet.add label.txt local_vals in { acc with rev_fields; val_env; par_env; concrete_vals; local_vals; vars }) | Pcf_method (label, priv, Cfk_virtual sty) -> with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in let cty = transl_simple_type val_env false Global sty in let ty = cty.ctyp_type in add_method loc val_env label.txt priv Virtual ty sign; let field = Virtual_method { label; priv; cty; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_method (label, priv, Cfk_concrete (override, expr)) -> with_attrs (fun () -> if MethSet.mem label.txt local_meths then raise(Error(loc, val_env, Duplicate ("method", label.txt))); if MethSet.mem label.txt concrete_meths then begin if override = Fresh then begin Location.prerr_warning loc (Warnings.Method_override [label.txt]) end end else begin if override = Override then begin raise(Error(loc, val_env, No_overriding("method", label.txt))) end end; let expr = match expr.pexp_desc with | Pexp_poly _ -> expr | _ -> Ast_helper.Exp.poly ~loc:expr.pexp_loc expr None in let sbody, sty = match expr.pexp_desc with | Pexp_poly (sbody, sty) -> sbody, sty | _ -> assert false in let ty = match sty with | None -> Ctype.newvar () | Some sty -> let sty = Ast_helper.Typ.force_poly sty in let cty' = Typetexp.transl_simple_type val_env false Global sty in cty'.ctyp_type in add_method loc val_env label.txt priv Concrete ty sign; begin try match get_desc ty with | Tvar _ -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newmono ty') ty; type_approx val_env sbody ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in type_approx val_env sbody ty1' | _ -> assert false with Ctype.Unify err -> raise(Error(loc, val_env, Field_type_mismatch ("method", label.txt, err))) end; let sdefinition = make_method self_loc cl_num expr in let warning_state = Warnings.backup () in let field = Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_meths = MethSet.add label.txt concrete_meths in let local_meths = MethSet.add label.txt local_meths in { acc with rev_fields; concrete_meths; local_meths }) | Pcf_constraint (sty1, sty2) -> with_attrs (fun () -> let (cty1, cty2) = type_constraint val_env sty1 sty2 loc in let field = Constraint { cty1; cty2; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_initializer sexpr -> with_attrs (fun () -> let sexpr = make_method self_loc cl_num sexpr in let warning_state = Warnings.backup () in let field = Initializer { sexpr; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_attribute attribute -> Builtin_attributes.warning_attribute attribute; let field = Attribute { attribute; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields } | Pcf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_fields_first_pass self_loc cl_num sign self_scope val_env par_env cfs = let rev_fields = [] in let concrete_meths = MethSet.empty in let concrete_vals = VarSet.empty in let local_meths = MethSet.empty in let local_vals = VarSet.empty in let vars = Vars.empty in let init_acc = { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } in let acc = Builtin_attributes.warning_scope [] (fun () -> List.fold_left (class_field_first_pass self_loc cl_num sign self_scope) init_acc cfs) in List.rev acc.rev_fields, acc.vars and class_field_second_pass cl_num sign met_env field = let mkcf desc loc attrs = { cf_desc = desc; cf_loc = loc; cf_attributes = attrs } in match field with | Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } -> let met_env = add_instance_vars_met loc inherited_vars sign cl_num met_env in let met_env = match super with | None -> met_env | Some name -> let meths = List.fold_left (fun acc (label, id) -> Meths.add label id acc) Meths.empty super_meths in let ty = Btype.self_type parent.cl_type in let attrs = [] in let _id, met_env = enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env in met_env in let desc = Tcf_inherit(override, parent, super, inherited_vars, super_meths) in met_env, mkcf desc loc attributes | Virtual_val { label; mut; id; cty; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_virtual cty in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_concrete(override, definition) in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Virtual_method { label; priv; cty; loc; attributes } -> let kind = Tcfk_virtual cty in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes | Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let ty = Btype.method_type label.txt sign in let self_type = sign.Types.csig_self in let arrow_desc = Nolabel, Alloc_mode.global, Alloc_mode.global in let self_param_type = Btype.newgenty (Tpoly(self_type, [])) in let meth_type = mk_expected (Btype.newgenty (Tarrow(arrow_desc, self_param_type, ty, commu_ok))) in Ctype.raise_nongen_level (); let texp = type_expect met_env sdefinition meth_type in Ctype.end_def (); let kind = Tcfk_concrete (override, texp) in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes) | Constraint { cty1; cty2; loc; attributes } -> let desc = Tcf_constraint(cty1, cty2) in met_env, mkcf desc loc attributes | Initializer { sexpr; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> Ctype.raise_nongen_level (); let unit_type = Ctype.instance Predef.type_unit in let self_param_type = Ctype.newmono sign.Types.csig_self in let arrow_desc = Nolabel, Alloc_mode.global, Alloc_mode.global in let meth_type = mk_expected (Ctype.newty (Tarrow (arrow_desc, self_param_type, unit_type, commu_ok))) in let texp = type_expect met_env sexpr meth_type in Ctype.end_def (); let desc = Tcf_initializer texp in met_env, mkcf desc loc attributes) | Attribute { attribute; loc; attributes; } -> let desc = Tcf_attribute attribute in met_env, mkcf desc loc attributes and class_fields_second_pass cl_num sign met_env fields = let _, rev_cfs = List.fold_left (fun (met_env, cfs) field -> let met_env, cf = class_field_second_pass cl_num sign met_env field in met_env, cf :: cfs) (met_env, []) fields in List.rev rev_cfs (* N.B. the self type of a final object type doesn't contain a dummy method in the beginning. We only explicitly add a dummy method to class definitions (and class (type) declarations)), which are later removed (made absent) by [final_decl]. If we ever find a dummy method in a final object self type, it means that somehow we've unified the self type of the object with the self type of a not yet finished class. When this happens, we cannot close the object type and must error. *) and class_structure cl_num virt self_scope final val_env met_env loc { pcstr_self = spat; pcstr_fields = str } = (* Environment for substructures *) let val_env = Env.add_lock Value_mode.global val_env in let met_env = Env.add_lock Value_mode.global met_env in let par_env = met_env in (* Location of self. Used for locations of self arguments *) let self_loc = {spat.ppat_loc with Location.loc_ghost = true} in let sign = Ctype.new_class_signature () in (* Adding a dummy method to the signature prevents it from being closed / escaping. That isn't needed for objects though. *) begin match final with | Not_final -> Ctype.add_dummy_method val_env ~scope:self_scope sign; | Final -> () end; (* Self binder *) let (self_pat, self_pat_vars) = type_self_pattern val_env spat in let val_env, par_env = List.fold_right (fun {pv_id; _} (val_env, par_env) -> let name = Ident.name pv_id in let val_env = enter_self_val name val_env in let par_env = enter_self_val name par_env in val_env, par_env) self_pat_vars (val_env, par_env) in (* Check that the binder has a correct type *) begin try Ctype.unify val_env self_pat.pat_type sign.csig_self with Ctype.Unify _ -> raise(Error(spat.ppat_loc, val_env, Pattern_type_clash self_pat.pat_type)) end; (* Typing of class fields *) let (fields, vars) = class_fields_first_pass self_loc cl_num sign self_scope val_env par_env str in let kind = kind_of_final final in (* Check for unexpected virtual methods *) check_virtual loc val_env virt kind sign; (* Update the class signature *) update_class_signature loc val_env ~warn_implicit_public:false virt kind sign; let meths = Meths.fold (fun label _ meths -> Meths.add label (Ident.create_local label) meths) sign.csig_meths Meths.empty in (* Close the signature if it is final *) begin match final with | Not_final -> () | Final -> if not (Ctype.close_class_signature val_env sign) then raise(Error(loc, val_env, Closing_self_type sign)); end; (* Typing of method bodies *) Ctype.generalize_class_signature_spine val_env sign; let self_var_kind = match virt with | Virtual -> Self_virtual(ref meths) | Concrete -> Self_concrete meths in let met_env = List.fold_right (fun {pv_id; pv_type; pv_loc; pv_as_var; pv_attributes} met_env -> add_self_met pv_loc pv_id sign self_var_kind vars cl_num pv_as_var pv_type pv_attributes met_env) self_pat_vars met_env in let fields = class_fields_second_pass cl_num sign met_env fields in (* Update the class signature and warn about public methods made private *) update_class_signature loc val_env ~warn_implicit_public:true virt kind sign; let meths = match self_var_kind with | Self_virtual meths_ref -> !meths_ref | Self_concrete meths -> meths in { cstr_self = self_pat; cstr_fields = fields; cstr_type = sign; cstr_meths = meths; } and class_expr cl_num val_env met_env virt self_scope scl = Builtin_attributes.warning_scope scl.pcl_attributes (fun () -> class_expr_aux cl_num val_env met_env virt self_scope scl) and class_expr_aux cl_num val_env met_env virt self_scope scl = match scl.pcl_desc with | Pcl_constr (lid, styl) -> let (path, decl) = Env.lookup_class ~loc:scl.pcl_loc lid.txt val_env in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, val_env, Unbound_class_2 lid.txt)); let tyl = List.map (fun sty -> transl_simple_type val_env false Global sty) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = Btype.abbreviate_class_type path params clty in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type clty'); if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, val_env, Parameter_arity_mismatch (lid.txt, List.length params, List.length tyl))); List.iter2 (fun cty' ty -> let ty' = cty'.ctyp_type in try Ctype.unify val_env ty' ty with Ctype.Unify err -> raise(Error(cty'.ctyp_loc, val_env, Parameter_mismatch err))) tyl params; (* Check for unexpected virtual methods *) check_virtual_clty scl.pcl_loc val_env virt Class clty'; let cl = rc {cl_desc = Tcl_ident (path, lid, tyl); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = scl.pcl_attributes; } in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tcl_constraint (cl, None, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = []; (* attributes are kept on the inner cl node *) } | Pcl_structure cl_str -> let desc = class_structure cl_num virt self_scope Not_final val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tcl_structure desc; cl_loc = scl.pcl_loc; cl_type = Cty_signature desc.cstr_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_fun (l, Some default, spat, sbody) -> if has_poly_constraint spat then raise(Error(spat.ppat_loc, val_env, Polymorphic_class_parameter)); let loc = default.pexp_loc in let open Ast_helper in let scases = [ Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "Some")))) (Some ([], Pat.var ~loc (mknoloc "*sth*")))) (Exp.ident ~loc (mknoloc (Longident.Lident "*sth*"))); Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "None")))) None) default; ] in let smatch = Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*"))) scases in let sfun = Cl.fun_ ~loc:scl.pcl_loc l None (Pat.var ~loc (mknoloc "*opt*")) (Cl.let_ ~loc:scl.pcl_loc Nonrecursive [Vb.mk spat smatch] sbody) Note : we do n't put the ' # default ' attribute , as it is not detected for class - level let bindings . See # 5975 . is not detected for class-level let bindings. See #5975.*) in class_expr cl_num val_env met_env virt self_scope sfun | Pcl_fun (l, None, spat, scl') -> if has_poly_constraint spat then raise(Error(spat.ppat_loc, val_env, Polymorphic_class_parameter)); if !Clflags.principal then Ctype.begin_def (); let (pat, pv, val_env', met_env) = Typecore.type_class_arg_pattern cl_num val_env met_env l spat in if !Clflags.principal then begin Ctype.end_def (); let gen {pat_type = ty} = Ctype.generalize_structure ty in iter_pattern gen pat end; let pv = List.map begin fun (id, id', _ty) -> let path = Pident id' in (* do not mark the value as being used *) let vd = Env.find_value path val_env' in (id, {exp_desc = Texp_ident(path, mknoloc (Longident.Lident (Ident.name id)), vd, Id_value); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_mode = Value_mode.global; exp_attributes = []; (* check *) exp_env = val_env'}) end pv in let rec not_nolabel_function = function | Cty_arrow(Nolabel, _, _) -> false | Cty_arrow(_, _, cty) -> not_nolabel_function cty | _ -> true in let partial = let dummy = type_exp val_env (Ast_helper.Exp.unreachable ()) in Typecore.check_partial val_env pat.pat_type pat.pat_loc [{c_lhs = pat; c_guard = None; c_rhs = dummy}] in let val_env' = Env.add_lock Value_mode.global val_env' in Ctype.raise_nongen_level (); let cl = class_expr cl_num val_env' met_env virt self_scope scl' in Ctype.end_def (); if Btype.is_optional l && not_nolabel_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tcl_fun (l, pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Cty_arrow (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_apply (scl', sargs) -> assert (sargs <> []); if !Clflags.principal then Ctype.begin_def (); let cl = class_expr cl_num val_env met_env virt self_scope scl' in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_class_type_structure cl.cl_type; end; let rec nonopt_labels ls ty_fun = match ty_fun with | Cty_arrow (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = Nolabel) sargs && List.exists (fun l -> l <> Nolabel) labels && begin Location.prerr_warning cl.cl_loc (Warnings.Labels_omitted (List.map Printtyp.string_of_label (List.filter ((<>) Nolabel) labels))); true end in let rec type_args args omitted ty_fun ty_fun0 sargs = match ty_fun, ty_fun0 with | Cty_arrow (l, ty, ty_fun), Cty_arrow (_, ty0, ty_fun0) when sargs <> [] -> let name = Btype.label_name l and optional = Btype.is_optional l in let use_arg sarg l' = Arg ( if not optional || Btype.is_optional l' then type_argument val_env sarg ty ty0 else let ty' = extract_option_type val_env ty and ty0' = extract_option_type val_env ty0 in let arg = type_argument val_env sarg ty' ty0' in option_some val_env arg Value_mode.global ) in let eliminate_optional_arg () = Arg (option_none val_env ty0 Value_mode.global Location.none) in let remaining_sargs, arg = if ignore_labels then begin match sargs with | [] -> assert false | (l', sarg) :: remaining_sargs -> if name = Btype.label_name l' || (not optional && l' = Nolabel) then (remaining_sargs, use_arg sarg l') else if optional && not (List.exists (fun (l, _) -> name = Btype.label_name l) remaining_sargs) then (sargs, eliminate_optional_arg ()) else raise(Error(sarg.pexp_loc, val_env, Apply_wrong_label l')) end else match Btype.extract_label name sargs with | Some (l', sarg, _, remaining_sargs) -> if not optional && Btype.is_optional l' then Location.prerr_warning sarg.pexp_loc (Warnings.Nonoptional_label (Printtyp.string_of_label l)); remaining_sargs, use_arg sarg l' | None -> sargs, if Btype.is_optional l && List.mem_assoc Nolabel sargs then eliminate_optional_arg () else begin let mode_closure = Alloc_mode.global in let mode_arg = Alloc_mode.global in let mode_ret = Alloc_mode.global in Omitted { mode_closure; mode_arg; mode_ret } end in let omitted = match arg with | Omitted _ -> (l,ty0) :: omitted | Arg _ -> omitted in type_args ((l,arg)::args) omitted ty_fun ty_fun0 remaining_sargs | _ -> match sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l)) else raise(Error(cl.cl_loc, val_env, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Cty_arrow(l,ty,ty_fun)) ty_fun0 omitted) in let (args, cty) = let (_, ty_fun0) = Ctype.instance_class [] cl.cl_type in type_args [] [] cl.cl_type ty_fun0 sargs in rc {cl_desc = Tcl_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = Typecore.type_let In_class_def val_env rec_flag sdefs in let (vals, met_env) = List.fold_right (fun (id, modes) (vals, met_env) -> List.iter (fun (loc, mode) -> Typecore.escape ~loc ~env:val_env mode) modes; let path = Pident id in (* do not mark the value as used *) let vd = Env.find_value path val_env in Ctype.begin_def (); let expr = {exp_desc = Texp_ident(path, mknoloc(Longident.Lident (Ident.name id)),vd, Id_value); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_mode = Value_mode.global; exp_attributes = []; exp_env = val_env; } in Ctype.end_def (); Ctype.generalize expr.exp_type; let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num); val_attributes = []; Types.val_loc = vd.Types.val_loc; val_uid = vd.val_uid; } in let id' = Ident.create_local (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents_with_modes defs) ([], met_env) in let cl = class_expr cl_num val_env met_env virt self_scope scl' in let () = if rec_flag = Recursive then check_recursive_bindings val_env defs in rc {cl_desc = Tcl_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_constraint (scl', scty) -> Ctype.begin_class_def (); let context = Typetexp.narrow () in let cl = class_expr cl_num val_env met_env virt self_scope scl' in complete_class_type cl.cl_loc val_env virt Class_type cl.cl_type; Typetexp.widen context; let context = Typetexp.narrow () in let clty = class_type val_env virt self_scope scty in complete_class_type clty.cltyp_loc val_env virt Class clty.cltyp_type; Typetexp.widen context; Ctype.end_def (); Ctype.limited_generalize_class_type (Btype.self_type_row cl.cl_type) cl.cl_type; Ctype.limited_generalize_class_type (Btype.self_type_row clty.cltyp_type) clty.cltyp_type; begin match Includeclass.class_types val_env cl.cl_type clty.cltyp_type with [] -> () | error -> raise(Error(cl.cl_loc, val_env, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty.cltyp_type in let ty = snd (Ctype.instance_class [] clty.cltyp_type) in (* Adding a dummy method to the self type prevents it from being closed / escaping. *) Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type ty); rc {cl_desc = Tcl_constraint (cl, Some clty, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = ty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_open (pod, e) -> let used_slot = ref false in let (od, new_val_env) = !type_open_descr ~used_slot val_env pod in let ( _, new_met_env) = !type_open_descr ~used_slot met_env pod in let cl = class_expr cl_num new_val_env new_met_env virt self_scope e in rc {cl_desc = Tcl_open (od, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) (*******************************) (* Approximate the type of the constructor to allow recursive use *) (* of optional parameters *) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in let arg = Ctype.newmono arg in let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in Ctype.newty (Tarrow (arrow_desc, arg, approx_declaration cl, commu_ok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_arrow (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in let arg = Ctype.newmono arg in let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in Ctype.newty (Tarrow (arrow_desc, arg, approx_description ct, commu_ok)) | _ -> Ctype.newvar () (*******************************) let temp_abbrev loc env id arity uid = let params = ref [] in for _i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let env = Env.add_type ~check:true id {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc; or keep attrs from the class decl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = uid; } env in (!params, ty, env) let initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, cl_id, uid) = (* Temporary abbreviations *) let arity = List.length cl.pci_params in let (obj_params, obj_ty, env) = temp_abbrev cl.pci_loc env obj_id arity uid in let (cl_params, cl_ty, env) = temp_abbrev cl.pci_loc env cl_id arity uid in (* Temporary type for the class constructor *) if !Clflags.principal then Ctype.begin_def (); let constr_type = approx cl.pci_expr in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure constr_type; end; let dummy_cty = Cty_signature (Ctype.new_class_signature ()) in let dummy_class = {Types.cty_params = []; (* Dummy value *) cty_variance = []; cty_type = dummy_cty; (* Dummy value *) cty_path = unbound_class; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = Location.none; cty_attributes = []; cty_uid = uid; } in let env = Env.add_cltype ty_id {clty_params = []; (* Dummy value *) clty_variance = []; clty_type = dummy_cty; (* Dummy value *) clty_path = unbound_class; clty_loc = Location.none; clty_attributes = []; clty_uid = uid; } ( if define_class then Env.add_class id dummy_class env else env ) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = reset_type_variables (); Ctype.begin_class_def (); (* Introduce class parameters *) let ci_params = let make_param (sty, v) = try (transl_type_param env sty, v) with Already_bound -> raise(Error(sty.ptyp_loc, env, Repeated_parameter)) in List.map make_param cl.pci_params in let params = List.map (fun (cty, _) -> cty.ctyp_type) ci_params in (* Allow self coercions (only for class declarations) *) let coercion_locs = ref [] in (* Type the class expression *) let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_virt cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in let sign = Btype.signature_of_class_type typ in Ctype.end_def (); the row variable List.iter (Ctype.limited_generalize sign.csig_self_row) params; Ctype.limited_generalize_class_type sign.csig_self_row typ; (* Check the abbreviation for the object type *) let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let row = Btype.self_type_row obj_type in Ctype.unify env row (Ctype.newty Tnil); begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (obj_id, constr, Ctype.newconstr (Path.Pident obj_id) obj_params'))) end; let ty = Btype.self_type obj_type in begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; Ctype.set_object_name obj_id params (Btype.self_type typ); (* Check the other temporary abbreviation (#-type) *) begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Btype.self_type cl_type in begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (cl_id, Ctype.newconstr (Path.Pident cl_id) cl_params, Ctype.newconstr (Path.Pident cl_id) cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let constr = Ctype.newconstr (Path.Pident cl_id) params in raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, cl_ty))) end end; (* Type of the class constructor *) begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Constructor_type_mismatch (cl.pci_name.txt, err))) end; (* Class and class type temporary definitions *) let cty_variance = Variance.unknown_signature ~injective:false ~arity:(List.length params) in let cltydef = {clty_params = params; clty_type = Btype.class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in (* Misc. *) let arity = Btype.class_type_arity typ in let pub_meths = Btype.public_methods sign in (* Final definitions *) let (params', typ') = Ctype.instance_class params typ in let cltydef = {clty_params = params'; clty_type = Btype.class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some (Ctype.instance constr_type) end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in let obj_abbr = let arity = List.length obj_params in { type_params = obj_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some obj_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Btype.self_type typ) in Ctype.set_object_name obj_id cl_params cl_ty; let cl_abbr = let arity = List.length cl_params in { type_params = cl_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some cl_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params, arity, pub_meths, coe, expr) = begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Non_collapsable_conjunction (id, clty, err))) end; List.iter Ctype.generalize clty.cty_params; Ctype.generalize_class_type clty.cty_type; Option.iter Ctype.generalize clty.cty_new; List.iter Ctype.generalize obj_abbr.type_params; Option.iter Ctype.generalize obj_abbr.type_manifest; List.iter Ctype.generalize cl_abbr.type_params; Option.iter Ctype.generalize cl_abbr.type_manifest; if Ctype.nongen_class_declaration clty then raise(Error(cl.pci_loc, env, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Btype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, env, Unbound_type_var(printer, reason))) end; { id; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr; arity; pub_meths; coe; id_loc = cl.pci_name; req = { ci_loc = cl.pci_loc; ci_virt = cl.pci_virt; ci_params = ci_params; (* TODO : check that we have the correct use of identifiers *) ci_id_name = cl.pci_name; ci_id_class = id; ci_id_class_type = ty_id; ci_id_object = obj_id; ci_id_typehash = cl_id; ci_expr = expr; ci_decl = clty; ci_type_decl = cltydef; ci_attributes = cl.pci_attributes; } } (* (cl.pci_variance, cl.pci_loc)) *) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = Builtin_attributes.warning_scope cl.pci_attributes (fun () -> class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) ) let extract_type_decls { clty; cltydef; obj_id; obj_abbr; cl_abbr; req} decls = (obj_id, obj_abbr, cl_abbr, clty, cltydef, req) :: decls let merge_type_decls decl (obj_abbr, cl_abbr, clty, cltydef) = {decl with obj_abbr; cl_abbr; clty; cltydef} let final_env define_class env { id; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr } = (* Add definitions after cleaning them *) Env.add_type ~check:true obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_type ~check:true cl_id (Subst.type_declaration Subst.identity cl_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env))) (* Check that #c is coercible to c if there is a self-coercion *) let check_coercions env { id; id_loc; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr; arity; pub_meths; coe; req } = begin match coe with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype err -> raise(Typecore.Error(loc, env, Typecore.Not_subtype err)) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, env, Cannot_coerce_self obj_ty)) end; {cls_id = id; cls_id_loc = id_loc; cls_decl = clty; cls_ty_id = ty_id; cls_ty_decl = cltydef; cls_obj_id = obj_id; cls_obj_abbr = obj_abbr; cls_typesharp_id = cl_id; cls_abbr = cl_abbr; cls_arity = arity; cls_pub_methods = pub_meths; cls_info=req} (*******************************) let type_classes define_class approx kind env cls = let scope = Ctype.create_scope () in let cls = List.map (function cl -> (cl, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope ("#" ^ cl.pci_name.txt), Uid.mk ~current_unit:(Env.get_unit_name ()) )) cls in Ctype.begin_class_def (); let (res, newenv) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, newenv) = List.fold_right (class_infos define_class kind) res ([], newenv) in Ctype.end_def (); let res = List.rev_map (final_decl newenv define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = try Typedecl_variance.update_class_decls newenv decls with Typedecl_variance.Error(loc, err) -> raise (Typedecl.Error(loc, Typedecl.Variance err)) in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env virt sexpr = incr class_num; let self_scope = Ctype.get_current_level () in let expr = class_expr (Int.to_string !class_num) env env virt self_scope sexpr in complete_class_type expr.cl_loc env virt Class expr.cl_type; (expr, expr.cl_type) let class_description env virt sexpr = let self_scope = Ctype.get_current_level () in let expr = class_type env virt self_scope sexpr in complete_class_type expr.cltyp_loc env virt Class_type expr.cltyp_type; (expr, expr.cltyp_type) let class_declarations env cls = let info, env = type_classes true approx_declaration class_declaration env cls in let ids, exprs = List.split (List.map (fun ci -> ci.cls_id, ci.cls_info.ci_expr) info) in check_recursive_class_bindings env ids exprs; info, env let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decls, env) = type_classes false approx_description class_description env cls in (List.map (fun decl -> {clsty_ty_id = decl.cls_ty_id; clsty_id_loc = decl.cls_id_loc; clsty_ty_decl = decl.cls_ty_decl; clsty_obj_id = decl.cls_obj_id; clsty_obj_abbr = decl.cls_obj_abbr; clsty_typesharp_id = decl.cls_typesharp_id; clsty_abbr = decl.cls_abbr; clsty_info = decl.cls_info}) decls, env) let type_object env loc s = incr class_num; let desc = class_structure (Int.to_string !class_num) Concrete Btype.lowest_level Final env env loc s in complete_class_signature loc env Concrete Object desc.cstr_type; let meths = Btype.public_methods desc.cstr_type in (desc, meths) let () = Typecore.type_object := type_object (*******************************) (* Approximate the class declaration as class ['params] id = object end *) let approx_class sdecl = let open Ast_helper in let self' = Typ.any () in let clty' = Cty.signature ~loc:sdecl.pci_expr.pcty_loc (Csig.mk self' []) in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = fst (class_type_declarations env (List.map approx_class sdecls)) (*******************************) (* Error report *) open Format let non_virtual_string_of_kind = function | Object -> "object" | Class -> "non-virtual class" | Class_type -> "non-virtual class type" let report_error env ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint err -> fprintf ppf "@[<v>The class constraints are not consistent.@ "; Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type"); fprintf ppf "@]" | Field_type_mismatch (k, m, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Unexpected_field (ty, lab) -> fprintf ppf "@[@[<2>This object is expected to have type :@ %a@]\ @ This type does not have a method %s." Printtyp.type_expr ty lab | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply _ -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | Nolabel -> "out label" | l -> sprintf " label %s" (Btype.prefixed_label_name l) in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> (* XXX Trace *) XXX Revoir message | Improve error message fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> (* XXX Afficher une trace ? | Print a trace? *) Printtyp.prepare_for_printing [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" !Oprint.out_type (Printtyp.tree_of_typexp Type abbrev) !Oprint.out_type (Printtyp.tree_of_typexp Type actual) !Oprint.out_type (Printtyp.tree_of_typexp Type expected) | Constructor_type_mismatch (c, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (kind, mets, vals) -> let kind = non_virtual_string_of_kind kind in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This %s has virtual %s.@ \ @[<2>The following %s are virtual : %a@]@]" kind missings missings (pp_print_list ~pp_sep:pp_print_space pp_print_string) (mets @ vals) | Undeclared_methods(kind, mets) -> let kind = non_virtual_string_of_kind kind in fprintf ppf "@[This %s has undeclared virtual methods.@ \ @[<2>The following methods were not declared : %a@]@]" kind (pp_print_list ~pp_sep:pp_print_space pp_print_string) mets | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing [params; cstrs]; fprintf ppf "@[The abbreviation %a@ is used with parameters@ %a@ \ which are incompatible with constraints@ %a@]" Printtyp.ident id !Oprint.out_type (Printtyp.tree_of_typexp Type params) !Oprint.out_type (Printtyp.tree_of_typexp Type cstrs) | Class_match_failure error -> Includeclass.report_error Type ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_reason ppf (ty0, real, lab, ty) = let ty1 = if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.add_type_to_preparation ty; Printtyp.add_type_to_preparation ty1; fprintf ppf "The method %s@ has type@;<1 2>%a@ where@ %a@ is unbound" lab !Oprint.out_type (Printtyp.tree_of_typexp Type ty) !Oprint.out_type (Printtyp.tree_of_typexp Type ty0) in fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurrences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, err) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsible conjunctive types in constraints.@ %t@]" (Printtyp.class_declaration id) clty (fun ppf -> Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") ) | Self_clash err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but actually has type") | Mutability_mismatch (_lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s;@ it cannot be redefined as %s@]" mut1 mut2 | No_overriding (_, "") -> fprintf ppf "@[This inheritance does not override any method@ %s@]" "instance variable" | No_overriding (kind, name) -> fprintf ppf "@[The %s `%s'@ has no previous definition@]" kind name | Duplicate (kind, name) -> fprintf ppf "@[The %s `%s'@ has multiple definitions in this object@]" kind name | Closing_self_type sign -> fprintf ppf "@[Cannot close type of object literal:@ %a@,\ it has been unified with the self type of a class that is not yet@ \ completely defined.@]" Printtyp.type_scheme sign.csig_self | Polymorphic_class_parameter -> fprintf ppf "Class parameters cannot be polymorphic" let report_error env ppf err = Printtyp.wrap_printing_env ~error:true env (fun () -> report_error env ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer ~loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
null
https://raw.githubusercontent.com/janestreet/merlin-jst/00f0a2c961fbf5a968125b33612d60224a573f40/src/ocaml/typing/typeclass.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. ************************************************************************ Path associated to the temporary class type of a class being typed (its constructor is not available). ********************************** Some operations on class types ********************************** Record a class type Return the constructor type associated to a class type ********************************* Primitives for typing classes ********************************* ***************************** Introduce a dummy method preventing self type from being closed. Class type fields Adding a dummy method to the self type prevents it from being closed / escaping. Check for unexpected virtual methods ***************************** Methods available through super N.B. the self type of a final object type doesn't contain a dummy method in the beginning. We only explicitly add a dummy method to class definitions (and class (type) declarations)), which are later removed (made absent) by [final_decl]. If we ever find a dummy method in a final object self type, it means that somehow we've unified the self type of the object with the self type of a not yet finished class. When this happens, we cannot close the object type and must error. Environment for substructures Location of self. Used for locations of self arguments Adding a dummy method to the signature prevents it from being closed / escaping. That isn't needed for objects though. Self binder Check that the binder has a correct type Typing of class fields Check for unexpected virtual methods Update the class signature Close the signature if it is final Typing of method bodies Update the class signature and warn about public methods made private Adding a dummy method to the self type prevents it from being closed / escaping. Check for unexpected virtual methods attributes are kept on the inner cl node do not mark the value as being used check do not mark the value as used Adding a dummy method to the self type prevents it from being closed / escaping. ***************************** Approximate the type of the constructor to allow recursive use of optional parameters ***************************** Temporary abbreviations Temporary type for the class constructor Dummy value Dummy value Dummy value Dummy value Introduce class parameters Allow self coercions (only for class declarations) Type the class expression Check the abbreviation for the object type Check the other temporary abbreviation (#-type) Type of the class constructor Class and class type temporary definitions Misc. Final definitions TODO : check that we have the correct use of identifiers (cl.pci_variance, cl.pci_loc)) Add definitions after cleaning them Check that #c is coercible to c if there is a self-coercion ***************************** ***************************** Approximate the class declaration as class ['params] id = object end ***************************** Error report XXX Trace XXX Afficher une trace ? | Print a trace?
, 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 Parsetree open Asttypes open Path open Types open Typecore open Typetexp open Format type 'a class_info = { cls_id : Ident.t; cls_id_loc : string loc; cls_decl : class_declaration; cls_ty_id : Ident.t; cls_ty_decl : class_type_declaration; cls_obj_id : Ident.t; cls_obj_abbr : type_declaration; cls_typesharp_id : Ident.t; cls_abbr : type_declaration; cls_arity : int; cls_pub_methods : string list; cls_info : 'a; } type class_type_info = { clsty_ty_id : Ident.t; clsty_id_loc : string loc; clsty_ty_decl : class_type_declaration; clsty_obj_id : Ident.t; clsty_obj_abbr : type_declaration; clsty_typesharp_id : Ident.t; clsty_abbr : type_declaration; clsty_info : Typedtree.class_type_declaration; } type 'a full_class = { id : Ident.t; id_loc : tag loc; clty: class_declaration; ty_id: Ident.t; cltydef: class_type_declaration; obj_id: Ident.t; obj_abbr: type_declaration; cl_id: Ident.t; cl_abbr: type_declaration; arity: int; pub_meths: string list; coe: Warnings.loc list; req: 'a Typedtree.class_infos; } type kind = | Object | Class | Class_type type final = | Final | Not_final let kind_of_final = function | Final -> Object | Not_final -> Class type error = | Unconsistent_constraint of Errortrace.unification_error | Field_type_mismatch of string * string * Errortrace.unification_error | Unexpected_field of type_expr * string | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of arg_label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class_2 of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * Errortrace.unification_error | Virtual_class of kind * string list * string list | Undeclared_methods of kind * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of Errortrace.unification_error | Bad_parameters of Ident.t * type_expr * type_expr | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * (type_expr * bool * string * type_expr) | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * Errortrace.unification_error | Self_clash of Errortrace.unification_error | Mutability_mismatch of string * mutable_flag | No_overriding of string * string | Duplicate of string * string | Closing_self_type of class_signature | Polymorphic_class_parameter exception Error of Location.t * Env.t * error exception Error_forward of Location.error open Typedtree let type_open_descr : (?used_slot:bool ref -> Env.t -> Parsetree.open_description -> open_description * Env.t) ref = ref (fun ?used_slot:_ _ -> assert false) let ctyp desc typ env loc = { ctyp_desc = desc; ctyp_type = typ; ctyp_loc = loc; ctyp_env = env; ctyp_attributes = [] } let unbound_class = Env.unbound_class let extract_constraints cty = let sign = Btype.signature_of_class_type cty in (Btype.instance_vars sign, Btype.methods sign, Btype.concrete_methods sign) let rc node = Cmt_format.add_saved_type (Cmt_format.Partial_class_expr node); node let update_class_signature loc env ~warn_implicit_public virt kind sign = let implicit_public, implicit_declared = Ctype.update_class_signature env sign in if implicit_declared <> [] then begin match virt with Should perhaps emit warning 17 here | Concrete -> raise (Error(loc, env, Undeclared_methods(kind, implicit_declared))) end; if warn_implicit_public && implicit_public <> [] then begin Location.prerr_warning loc (Warnings.Implicit_public_methods implicit_public) end let complete_class_signature loc env virt kind sign = update_class_signature loc env ~warn_implicit_public:false virt kind sign; Ctype.hide_private_methods env sign let complete_class_type loc env virt kind typ = let sign = Btype.signature_of_class_type typ in complete_class_signature loc env virt kind sign let check_virtual loc env virt kind sign = match virt with | Virtual -> () | Concrete -> match Btype.virtual_methods sign, Btype.virtual_instance_vars sign with | [], [] -> () | meths, vars -> raise(Error(loc, env, Virtual_class(kind, meths, vars))) let rec check_virtual_clty loc env virt kind clty = match clty with | Cty_constr(_, _, clty) | Cty_arrow(_, _, clty) -> check_virtual_clty loc env virt kind clty | Cty_signature sign -> check_virtual loc env virt kind sign let rec constructor_type constr cty = match cty with Cty_constr (_, _, cty) -> constructor_type constr cty | Cty_signature _ -> constr | Cty_arrow (l, ty, cty) -> let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in let ty = Ctype.newmono ty in Ctype.newty (Tarrow (arrow_desc, ty, constructor_type constr cty, commu_ok)) let raise_add_method_failure loc env label sign failure = match (failure : Ctype.add_method_failure) with | Ctype.Unexpected_method -> raise(Error(loc, env, Unexpected_field (sign.Types.csig_self, label))) | Ctype.Type_mismatch trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let raise_add_instance_variable_failure loc env label failure = match (failure : Ctype.add_instance_variable_failure) with | Ctype.Mutability_mismatch mut -> raise (Error(loc, env, Mutability_mismatch(label, mut))) | Ctype.Type_mismatch trace -> raise (Error(loc, env, Field_type_mismatch("instance variable", label, trace))) let raise_inherit_class_signature_failure loc env sign = function | Ctype.Self_type_mismatch trace -> raise(Error(loc, env, Self_clash trace)) | Ctype.Method(label, failure) -> raise_add_method_failure loc env label sign failure | Ctype.Instance_variable(label, failure) -> raise_add_instance_variable_failure loc env label failure let add_method loc env label priv virt ty sign = match Ctype.add_method env label priv virt ty sign with | () -> () | exception Ctype.Add_method_failed failure -> raise_add_method_failure loc env label sign failure let add_instance_variable ~strict loc env label mut virt ty sign = match Ctype.add_instance_variable ~strict env label mut virt ty sign with | () -> () | exception Ctype.Add_instance_variable_failed failure -> raise_add_instance_variable_failure loc env label failure let inherit_class_signature ~strict loc env sign1 sign2 = match Ctype.inherit_class_signature ~strict env sign1 sign2 with | () -> () | exception Ctype.Inherit_class_signature_failed failure -> raise_inherit_class_signature_failure loc env sign1 failure let inherit_class_type ~strict loc env sign1 cty2 = let sign2 = match Btype.scrape_class_type cty2 with | Cty_signature sign2 -> sign2 | _ -> raise(Error(loc, env, Structure_expected cty2)) in inherit_class_signature ~strict loc env sign1 sign2 let unify_delayed_method_type loc env label ty expected_ty= match Ctype.unify env ty expected_ty with | () -> () | exception Ctype.Unify trace -> raise(Error(loc, env, Field_type_mismatch ("method", label, trace))) let type_constraint val_env sty sty' loc = let cty = transl_simple_type val_env false Global sty in let ty = cty.ctyp_type in let cty' = transl_simple_type val_env false Global sty' in let ty' = cty'.ctyp_type in begin try Ctype.unify val_env ty ty' with Ctype.Unify err -> raise(Error(loc, val_env, Unconsistent_constraint err)); end; (cty, cty') let make_method loc cl_num expr = let open Ast_helper in let mkid s = mkloc s loc in Exp.fun_ ~loc:expr.pexp_loc Nolabel None (Pat.alias ~loc (Pat.var ~loc (mkid "self-*")) (mkid ("self-" ^ cl_num))) expr let delayed_meth_specs = ref [] let rec class_type_field env sign self_scope ctf = let loc = ctf.pctf_loc in let mkctf desc = { ctf_desc = desc; ctf_loc = loc; ctf_attributes = ctf.pctf_attributes } in let mkctf_with_attrs f = Builtin_attributes.warning_scope ctf.pctf_attributes (fun () -> mkctf (f ())) in match ctf.pctf_desc with | Pctf_inherit sparent -> mkctf_with_attrs (fun () -> let parent = class_type env Virtual self_scope sparent in complete_class_type parent.cltyp_loc env Virtual Class_type parent.cltyp_type; inherit_class_type ~strict:false loc env sign parent.cltyp_type; Tctf_inherit parent) | Pctf_val ({txt=lab}, mut, virt, sty) -> mkctf_with_attrs (fun () -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in add_instance_variable ~strict:false loc env lab mut virt ty sign; Tctf_val (lab, mut, virt, cty)) | Pctf_method ({txt=lab}, priv, virt, sty) -> mkctf_with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in match sty.ptyp_desc, priv with | Ptyp_poly ([],sty'), Public -> let expected_ty = Ctype.newvar () in add_method loc env lab priv virt expected_ty sign; let returned_cty = ctyp Ttyp_any (Ctype.newty Tnil) env loc in delayed_meth_specs := Warnings.mk_lazy (fun () -> let cty = transl_simple_type_univars env sty' in let ty = cty.ctyp_type in unify_delayed_method_type loc env lab ty expected_ty; returned_cty.ctyp_desc <- Ttyp_poly ([], cty); returned_cty.ctyp_type <- ty; ) :: !delayed_meth_specs; Tctf_method (lab, priv, virt, returned_cty) | _ -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in add_method loc env lab priv virt ty sign; Tctf_method (lab, priv, virt, cty)) | Pctf_constraint (sty, sty') -> mkctf_with_attrs (fun () -> let (cty, cty') = type_constraint env sty sty' ctf.pctf_loc in Tctf_constraint (cty, cty')) | Pctf_attribute x -> Builtin_attributes.warning_attribute x; mkctf (Tctf_attribute x) | Pctf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_signature virt env pcsig self_scope loc = let {pcsig_self=sty; pcsig_fields=psign} = pcsig in let sign = Ctype.new_class_signature () in Ctype.add_dummy_method env ~scope:self_scope sign; let self_cty = transl_simple_type env false Global sty in let self_type = self_cty.ctyp_type in begin try Ctype.unify env self_type sign.csig_self with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, env, Pattern_type_clash self_type)) end; let fields = Builtin_attributes.warning_scope [] (fun () -> List.map (class_type_field env sign self_scope) psign) in check_virtual loc env virt Class_type sign; { csig_self = self_cty; csig_fields = fields; csig_type = sign; } and class_type env virt self_scope scty = Builtin_attributes.warning_scope scty.pcty_attributes (fun () -> class_type_aux env virt self_scope scty) and class_type_aux env virt self_scope scty = let cltyp desc typ = { cltyp_desc = desc; cltyp_type = typ; cltyp_loc = scty.pcty_loc; cltyp_env = env; cltyp_attributes = scty.pcty_attributes; } in match scty.pcty_desc with | Pcty_constr (lid, styl) -> let (path, decl) = Env.lookup_cltype ~loc:scty.pcty_loc lid.txt env in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, env, Unbound_class_type_2 lid.txt)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in Ctype.add_dummy_method env ~scope:self_scope (Btype.signature_of_class_type clty); if List.length params <> List.length styl then raise(Error(scty.pcty_loc, env, Parameter_arity_mismatch (lid.txt, List.length params, List.length styl))); let ctys = List.map2 (fun sty ty -> let cty' = transl_simple_type env false Global sty in let ty' = cty'.ctyp_type in begin try Ctype.unify env ty' ty with Ctype.Unify err -> raise(Error(sty.ptyp_loc, env, Parameter_mismatch err)) end; cty' ) styl params in let typ = Cty_constr (path, params, clty) in check_virtual_clty scty.pcty_loc env virt Class_type typ; cltyp (Tcty_constr ( path, lid , ctys)) typ | Pcty_signature pcsig -> let clsig = class_signature virt env pcsig self_scope scty.pcty_loc in let typ = Cty_signature clsig.csig_type in cltyp (Tcty_signature clsig) typ | Pcty_arrow (l, sty, scty) -> let cty = transl_simple_type env false Global sty in let ty = cty.ctyp_type in let ty = if Btype.is_optional l then Ctype.newty (Tconstr(Predef.path_option,[ty], ref Mnil)) else ty in let clty = class_type env virt self_scope scty in let typ = Cty_arrow (l, ty, clty.cltyp_type) in cltyp (Tcty_arrow (l, cty, clty)) typ | Pcty_open (od, e) -> let (od, newenv) = !type_open_descr env od in let clty = class_type newenv virt self_scope e in cltyp (Tcty_open (od, clty)) clty.cltyp_type | Pcty_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let class_type env virt self_scope scty = delayed_meth_specs := []; let cty = class_type env virt self_scope scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty let enter_ancestor_val name val_env = Env.enter_unbound_value name Val_unbound_ancestor val_env let enter_self_val name val_env = Env.enter_unbound_value name Val_unbound_self val_env let enter_instance_var_val name val_env = Env.enter_unbound_value name Val_unbound_instance_variable val_env let enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env = let check s = Warnings.Unused_ancestor s in let kind = Val_anc (sign, meths, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.enter_value ~check name desc met_env let add_self_met loc id sign self_var_kind vars cl_num as_var ty attrs met_env = let check = if as_var then (fun s -> Warnings.Unused_var s) else (fun s -> Warnings.Unused_var_strict s) in let kind = Val_self (sign, self_var_kind, vars, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value ~check id desc met_env let add_instance_var_met loc label id sign cl_num attrs met_env = let mut, ty = match Vars.find label sign.csig_vars with | (mut, _, ty) -> mut, ty | exception Not_found -> assert false in let kind = Val_ivar (mut, cl_num) in let desc = { val_type = ty; val_kind = kind; val_attributes = attrs; Types.val_loc = loc; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) } in Env.add_value id desc met_env let add_instance_vars_met loc vars sign cl_num met_env = List.fold_left (fun met_env (label, id) -> add_instance_var_met loc label id sign cl_num [] met_env) met_env vars type intermediate_class_field = | Inherit of { override : override_flag; parent : class_expr; super : string option; inherited_vars : (string * Ident.t) list; super_meths : (string * Ident.t) list; loc : Location.t; attributes : attribute list; } | Virtual_val of { label : string loc; mut : mutable_flag; id : Ident.t; cty : core_type; already_declared : bool; loc : Location.t; attributes : attribute list; } | Concrete_val of { label : string loc; mut : mutable_flag; id : Ident.t; override : override_flag; definition : expression; already_declared : bool; loc : Location.t; attributes : attribute list; } | Virtual_method of { label : string loc; priv : private_flag; cty : core_type; loc : Location.t; attributes : attribute list; } | Concrete_method of { label : string loc; priv : private_flag; override : override_flag; sdefinition : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Constraint of { cty1 : core_type; cty2 : core_type; loc : Location.t; attributes : attribute list; } | Initializer of { sexpr : Parsetree.expression; warning_state : Warnings.state; loc : Location.t; attributes : attribute list; } | Attribute of { attribute : attribute; loc : Location.t; attributes : attribute list; } type first_pass_accummulater = { rev_fields : intermediate_class_field list; val_env : Env.t; par_env : Env.t; concrete_meths : MethSet.t; concrete_vals : VarSet.t; local_meths : MethSet.t; local_vals : VarSet.t; vars : Ident.t Vars.t; } let rec class_field_first_pass self_loc cl_num sign self_scope acc cf = let { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } = acc in let loc = cf.pcf_loc in let attributes = cf.pcf_attributes in let with_attrs f = Builtin_attributes.warning_scope attributes f in match cf.pcf_desc with | Pcf_inherit (override, sparent, super) -> with_attrs (fun () -> let parent = class_expr cl_num val_env par_env Virtual self_scope sparent in complete_class_type parent.cl_loc par_env Virtual Class parent.cl_type; inherit_class_type ~strict:true loc val_env sign parent.cl_type; let parent_sign = Btype.signature_of_class_type parent.cl_type in let new_concrete_meths = Btype.concrete_methods parent_sign in let new_concrete_vals = Btype.concrete_instance_vars parent_sign in let over_meths = MethSet.inter new_concrete_meths concrete_meths in let over_vals = VarSet.inter new_concrete_vals concrete_vals in begin match override with | Fresh -> let cname = match parent.cl_type with | Cty_constr (p, _, _) -> Path.name p | _ -> "inherited" in if not (MethSet.is_empty over_meths) then Location.prerr_warning loc (Warnings.Method_override (cname :: MethSet.elements over_meths)); if not (VarSet.is_empty over_vals) then Location.prerr_warning loc (Warnings.Instance_variable_override (cname :: VarSet.elements over_vals)); | Override -> if MethSet.is_empty over_meths && VarSet.is_empty over_vals then raise (Error(loc, val_env, No_overriding ("",""))) end; let concrete_vals = VarSet.union new_concrete_vals concrete_vals in let concrete_meths = MethSet.union new_concrete_meths concrete_meths in let val_env, par_env, inherited_vars, vars = Vars.fold (fun label _ (val_env, par_env, inherited_vars, vars) -> let val_env = enter_instance_var_val label val_env in let par_env = enter_instance_var_val label par_env in let id = Ident.create_local label in let inherited_vars = (label, id) :: inherited_vars in let vars = Vars.add label id vars in (val_env, par_env, inherited_vars, vars)) parent_sign.csig_vars (val_env, par_env, [], vars) in let super_meths = MethSet.fold (fun label acc -> (label, Ident.create_local label) :: acc) new_concrete_meths [] in Super let (val_env, par_env, super) = match super with | None -> (val_env, par_env, None) | Some {txt=name} -> let val_env = enter_ancestor_val name val_env in let par_env = enter_ancestor_val name par_env in (val_env, par_env, Some name) in let field = Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; concrete_meths; concrete_vals; vars }) | Pcf_val (label, mut, Cfk_virtual styp) -> with_attrs (fun () -> if !Clflags.principal then Ctype.begin_def (); let cty = Typetexp.transl_simple_type val_env false Global styp in let ty = cty.ctyp_type in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure ty end; add_instance_variable ~strict:true loc val_env label.txt mut Virtual ty sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Virtual_val { label; mut; id; cty; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields; val_env; par_env; vars }) | Pcf_val (label, mut, Cfk_concrete (override, sdefinition)) -> with_attrs (fun () -> if VarSet.mem label.txt local_vals then raise(Error(loc, val_env, Duplicate ("instance variable", label.txt))); if VarSet.mem label.txt concrete_vals then begin if override = Fresh then Location.prerr_warning label.loc (Warnings.Instance_variable_override[label.txt]) end else begin if override = Override then raise(Error(loc, val_env, No_overriding ("instance variable", label.txt))) end; if !Clflags.principal then Ctype.begin_def (); let definition = type_exp val_env sdefinition in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure definition.exp_type end; add_instance_variable ~strict:true loc val_env label.txt mut Concrete definition.exp_type sign; let already_declared, val_env, par_env, id, vars = match Vars.find label.txt vars with | id -> true, val_env, par_env, id, vars | exception Not_found -> let name = label.txt in let val_env = enter_instance_var_val name val_env in let par_env = enter_instance_var_val name par_env in let id = Ident.create_local name in let vars = Vars.add label.txt id vars in false, val_env, par_env, id, vars in let field = Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_vals = VarSet.add label.txt concrete_vals in let local_vals = VarSet.add label.txt local_vals in { acc with rev_fields; val_env; par_env; concrete_vals; local_vals; vars }) | Pcf_method (label, priv, Cfk_virtual sty) -> with_attrs (fun () -> let sty = Ast_helper.Typ.force_poly sty in let cty = transl_simple_type val_env false Global sty in let ty = cty.ctyp_type in add_method loc val_env label.txt priv Virtual ty sign; let field = Virtual_method { label; priv; cty; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_method (label, priv, Cfk_concrete (override, expr)) -> with_attrs (fun () -> if MethSet.mem label.txt local_meths then raise(Error(loc, val_env, Duplicate ("method", label.txt))); if MethSet.mem label.txt concrete_meths then begin if override = Fresh then begin Location.prerr_warning loc (Warnings.Method_override [label.txt]) end end else begin if override = Override then begin raise(Error(loc, val_env, No_overriding("method", label.txt))) end end; let expr = match expr.pexp_desc with | Pexp_poly _ -> expr | _ -> Ast_helper.Exp.poly ~loc:expr.pexp_loc expr None in let sbody, sty = match expr.pexp_desc with | Pexp_poly (sbody, sty) -> sbody, sty | _ -> assert false in let ty = match sty with | None -> Ctype.newvar () | Some sty -> let sty = Ast_helper.Typ.force_poly sty in let cty' = Typetexp.transl_simple_type val_env false Global sty in cty'.ctyp_type in add_method loc val_env label.txt priv Concrete ty sign; begin try match get_desc ty with | Tvar _ -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newmono ty') ty; type_approx val_env sbody ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in type_approx val_env sbody ty1' | _ -> assert false with Ctype.Unify err -> raise(Error(loc, val_env, Field_type_mismatch ("method", label.txt, err))) end; let sdefinition = make_method self_loc cl_num expr in let warning_state = Warnings.backup () in let field = Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in let concrete_meths = MethSet.add label.txt concrete_meths in let local_meths = MethSet.add label.txt local_meths in { acc with rev_fields; concrete_meths; local_meths }) | Pcf_constraint (sty1, sty2) -> with_attrs (fun () -> let (cty1, cty2) = type_constraint val_env sty1 sty2 loc in let field = Constraint { cty1; cty2; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_initializer sexpr -> with_attrs (fun () -> let sexpr = make_method self_loc cl_num sexpr in let warning_state = Warnings.backup () in let field = Initializer { sexpr; warning_state; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields }) | Pcf_attribute attribute -> Builtin_attributes.warning_attribute attribute; let field = Attribute { attribute; loc; attributes } in let rev_fields = field :: rev_fields in { acc with rev_fields } | Pcf_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) and class_fields_first_pass self_loc cl_num sign self_scope val_env par_env cfs = let rev_fields = [] in let concrete_meths = MethSet.empty in let concrete_vals = VarSet.empty in let local_meths = MethSet.empty in let local_vals = VarSet.empty in let vars = Vars.empty in let init_acc = { rev_fields; val_env; par_env; concrete_meths; concrete_vals; local_meths; local_vals; vars } in let acc = Builtin_attributes.warning_scope [] (fun () -> List.fold_left (class_field_first_pass self_loc cl_num sign self_scope) init_acc cfs) in List.rev acc.rev_fields, acc.vars and class_field_second_pass cl_num sign met_env field = let mkcf desc loc attrs = { cf_desc = desc; cf_loc = loc; cf_attributes = attrs } in match field with | Inherit { override; parent; super; inherited_vars; super_meths; loc; attributes } -> let met_env = add_instance_vars_met loc inherited_vars sign cl_num met_env in let met_env = match super with | None -> met_env | Some name -> let meths = List.fold_left (fun acc (label, id) -> Meths.add label id acc) Meths.empty super_meths in let ty = Btype.self_type parent.cl_type in let attrs = [] in let _id, met_env = enter_ancestor_met ~loc name ~sign ~meths ~cl_num ~ty ~attrs met_env in met_env in let desc = Tcf_inherit(override, parent, super, inherited_vars, super_meths) in met_env, mkcf desc loc attributes | Virtual_val { label; mut; id; cty; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_virtual cty in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Concrete_val { label; mut; id; override; definition; already_declared; loc; attributes } -> let met_env = if already_declared then met_env else begin add_instance_var_met loc label.txt id sign cl_num attributes met_env end in let kind = Tcfk_concrete(override, definition) in let desc = Tcf_val(label, mut, id, kind, already_declared) in met_env, mkcf desc loc attributes | Virtual_method { label; priv; cty; loc; attributes } -> let kind = Tcfk_virtual cty in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes | Concrete_method { label; priv; override; sdefinition; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> let ty = Btype.method_type label.txt sign in let self_type = sign.Types.csig_self in let arrow_desc = Nolabel, Alloc_mode.global, Alloc_mode.global in let self_param_type = Btype.newgenty (Tpoly(self_type, [])) in let meth_type = mk_expected (Btype.newgenty (Tarrow(arrow_desc, self_param_type, ty, commu_ok))) in Ctype.raise_nongen_level (); let texp = type_expect met_env sdefinition meth_type in Ctype.end_def (); let kind = Tcfk_concrete (override, texp) in let desc = Tcf_method(label, priv, kind) in met_env, mkcf desc loc attributes) | Constraint { cty1; cty2; loc; attributes } -> let desc = Tcf_constraint(cty1, cty2) in met_env, mkcf desc loc attributes | Initializer { sexpr; warning_state; loc; attributes } -> Warnings.with_state warning_state (fun () -> Ctype.raise_nongen_level (); let unit_type = Ctype.instance Predef.type_unit in let self_param_type = Ctype.newmono sign.Types.csig_self in let arrow_desc = Nolabel, Alloc_mode.global, Alloc_mode.global in let meth_type = mk_expected (Ctype.newty (Tarrow (arrow_desc, self_param_type, unit_type, commu_ok))) in let texp = type_expect met_env sexpr meth_type in Ctype.end_def (); let desc = Tcf_initializer texp in met_env, mkcf desc loc attributes) | Attribute { attribute; loc; attributes; } -> let desc = Tcf_attribute attribute in met_env, mkcf desc loc attributes and class_fields_second_pass cl_num sign met_env fields = let _, rev_cfs = List.fold_left (fun (met_env, cfs) field -> let met_env, cf = class_field_second_pass cl_num sign met_env field in met_env, cf :: cfs) (met_env, []) fields in List.rev rev_cfs and class_structure cl_num virt self_scope final val_env met_env loc { pcstr_self = spat; pcstr_fields = str } = let val_env = Env.add_lock Value_mode.global val_env in let met_env = Env.add_lock Value_mode.global met_env in let par_env = met_env in let self_loc = {spat.ppat_loc with Location.loc_ghost = true} in let sign = Ctype.new_class_signature () in begin match final with | Not_final -> Ctype.add_dummy_method val_env ~scope:self_scope sign; | Final -> () end; let (self_pat, self_pat_vars) = type_self_pattern val_env spat in let val_env, par_env = List.fold_right (fun {pv_id; _} (val_env, par_env) -> let name = Ident.name pv_id in let val_env = enter_self_val name val_env in let par_env = enter_self_val name par_env in val_env, par_env) self_pat_vars (val_env, par_env) in begin try Ctype.unify val_env self_pat.pat_type sign.csig_self with Ctype.Unify _ -> raise(Error(spat.ppat_loc, val_env, Pattern_type_clash self_pat.pat_type)) end; let (fields, vars) = class_fields_first_pass self_loc cl_num sign self_scope val_env par_env str in let kind = kind_of_final final in check_virtual loc val_env virt kind sign; update_class_signature loc val_env ~warn_implicit_public:false virt kind sign; let meths = Meths.fold (fun label _ meths -> Meths.add label (Ident.create_local label) meths) sign.csig_meths Meths.empty in begin match final with | Not_final -> () | Final -> if not (Ctype.close_class_signature val_env sign) then raise(Error(loc, val_env, Closing_self_type sign)); end; Ctype.generalize_class_signature_spine val_env sign; let self_var_kind = match virt with | Virtual -> Self_virtual(ref meths) | Concrete -> Self_concrete meths in let met_env = List.fold_right (fun {pv_id; pv_type; pv_loc; pv_as_var; pv_attributes} met_env -> add_self_met pv_loc pv_id sign self_var_kind vars cl_num pv_as_var pv_type pv_attributes met_env) self_pat_vars met_env in let fields = class_fields_second_pass cl_num sign met_env fields in update_class_signature loc val_env ~warn_implicit_public:true virt kind sign; let meths = match self_var_kind with | Self_virtual meths_ref -> !meths_ref | Self_concrete meths -> meths in { cstr_self = self_pat; cstr_fields = fields; cstr_type = sign; cstr_meths = meths; } and class_expr cl_num val_env met_env virt self_scope scl = Builtin_attributes.warning_scope scl.pcl_attributes (fun () -> class_expr_aux cl_num val_env met_env virt self_scope scl) and class_expr_aux cl_num val_env met_env virt self_scope scl = match scl.pcl_desc with | Pcl_constr (lid, styl) -> let (path, decl) = Env.lookup_class ~loc:scl.pcl_loc lid.txt val_env in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, val_env, Unbound_class_2 lid.txt)); let tyl = List.map (fun sty -> transl_simple_type val_env false Global sty) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = Btype.abbreviate_class_type path params clty in Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type clty'); if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, val_env, Parameter_arity_mismatch (lid.txt, List.length params, List.length tyl))); List.iter2 (fun cty' ty -> let ty' = cty'.ctyp_type in try Ctype.unify val_env ty' ty with Ctype.Unify err -> raise(Error(cty'.ctyp_loc, val_env, Parameter_mismatch err))) tyl params; check_virtual_clty scl.pcl_loc val_env virt Class clty'; let cl = rc {cl_desc = Tcl_ident (path, lid, tyl); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; cl_attributes = scl.pcl_attributes; } in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tcl_constraint (cl, None, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env; } | Pcl_structure cl_str -> let desc = class_structure cl_num virt self_scope Not_final val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tcl_structure desc; cl_loc = scl.pcl_loc; cl_type = Cty_signature desc.cstr_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_fun (l, Some default, spat, sbody) -> if has_poly_constraint spat then raise(Error(spat.ppat_loc, val_env, Polymorphic_class_parameter)); let loc = default.pexp_loc in let open Ast_helper in let scases = [ Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "Some")))) (Some ([], Pat.var ~loc (mknoloc "*sth*")))) (Exp.ident ~loc (mknoloc (Longident.Lident "*sth*"))); Exp.case (Pat.construct ~loc (mknoloc (Longident.(Ldot (Lident "*predef*", "None")))) None) default; ] in let smatch = Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*"))) scases in let sfun = Cl.fun_ ~loc:scl.pcl_loc l None (Pat.var ~loc (mknoloc "*opt*")) (Cl.let_ ~loc:scl.pcl_loc Nonrecursive [Vb.mk spat smatch] sbody) Note : we do n't put the ' # default ' attribute , as it is not detected for class - level let bindings . See # 5975 . is not detected for class-level let bindings. See #5975.*) in class_expr cl_num val_env met_env virt self_scope sfun | Pcl_fun (l, None, spat, scl') -> if has_poly_constraint spat then raise(Error(spat.ppat_loc, val_env, Polymorphic_class_parameter)); if !Clflags.principal then Ctype.begin_def (); let (pat, pv, val_env', met_env) = Typecore.type_class_arg_pattern cl_num val_env met_env l spat in if !Clflags.principal then begin Ctype.end_def (); let gen {pat_type = ty} = Ctype.generalize_structure ty in iter_pattern gen pat end; let pv = List.map begin fun (id, id', _ty) -> let path = Pident id' in let vd = Env.find_value path val_env' in (id, {exp_desc = Texp_ident(path, mknoloc (Longident.Lident (Ident.name id)), vd, Id_value); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_mode = Value_mode.global; exp_env = val_env'}) end pv in let rec not_nolabel_function = function | Cty_arrow(Nolabel, _, _) -> false | Cty_arrow(_, _, cty) -> not_nolabel_function cty | _ -> true in let partial = let dummy = type_exp val_env (Ast_helper.Exp.unreachable ()) in Typecore.check_partial val_env pat.pat_type pat.pat_loc [{c_lhs = pat; c_guard = None; c_rhs = dummy}] in let val_env' = Env.add_lock Value_mode.global val_env' in Ctype.raise_nongen_level (); let cl = class_expr cl_num val_env' met_env virt self_scope scl' in Ctype.end_def (); if Btype.is_optional l && not_nolabel_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tcl_fun (l, pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Cty_arrow (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_apply (scl', sargs) -> assert (sargs <> []); if !Clflags.principal then Ctype.begin_def (); let cl = class_expr cl_num val_env met_env virt self_scope scl' in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_class_type_structure cl.cl_type; end; let rec nonopt_labels ls ty_fun = match ty_fun with | Cty_arrow (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = Nolabel) sargs && List.exists (fun l -> l <> Nolabel) labels && begin Location.prerr_warning cl.cl_loc (Warnings.Labels_omitted (List.map Printtyp.string_of_label (List.filter ((<>) Nolabel) labels))); true end in let rec type_args args omitted ty_fun ty_fun0 sargs = match ty_fun, ty_fun0 with | Cty_arrow (l, ty, ty_fun), Cty_arrow (_, ty0, ty_fun0) when sargs <> [] -> let name = Btype.label_name l and optional = Btype.is_optional l in let use_arg sarg l' = Arg ( if not optional || Btype.is_optional l' then type_argument val_env sarg ty ty0 else let ty' = extract_option_type val_env ty and ty0' = extract_option_type val_env ty0 in let arg = type_argument val_env sarg ty' ty0' in option_some val_env arg Value_mode.global ) in let eliminate_optional_arg () = Arg (option_none val_env ty0 Value_mode.global Location.none) in let remaining_sargs, arg = if ignore_labels then begin match sargs with | [] -> assert false | (l', sarg) :: remaining_sargs -> if name = Btype.label_name l' || (not optional && l' = Nolabel) then (remaining_sargs, use_arg sarg l') else if optional && not (List.exists (fun (l, _) -> name = Btype.label_name l) remaining_sargs) then (sargs, eliminate_optional_arg ()) else raise(Error(sarg.pexp_loc, val_env, Apply_wrong_label l')) end else match Btype.extract_label name sargs with | Some (l', sarg, _, remaining_sargs) -> if not optional && Btype.is_optional l' then Location.prerr_warning sarg.pexp_loc (Warnings.Nonoptional_label (Printtyp.string_of_label l)); remaining_sargs, use_arg sarg l' | None -> sargs, if Btype.is_optional l && List.mem_assoc Nolabel sargs then eliminate_optional_arg () else begin let mode_closure = Alloc_mode.global in let mode_arg = Alloc_mode.global in let mode_ret = Alloc_mode.global in Omitted { mode_closure; mode_arg; mode_ret } end in let omitted = match arg with | Omitted _ -> (l,ty0) :: omitted | Arg _ -> omitted in type_args ((l,arg)::args) omitted ty_fun ty_fun0 remaining_sargs | _ -> match sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l)) else raise(Error(cl.cl_loc, val_env, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Cty_arrow(l,ty,ty_fun)) ty_fun0 omitted) in let (args, cty) = let (_, ty_fun0) = Ctype.instance_class [] cl.cl_type in type_args [] [] cl.cl_type ty_fun0 sargs in rc {cl_desc = Tcl_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = Typecore.type_let In_class_def val_env rec_flag sdefs in let (vals, met_env) = List.fold_right (fun (id, modes) (vals, met_env) -> List.iter (fun (loc, mode) -> Typecore.escape ~loc ~env:val_env mode) modes; let path = Pident id in let vd = Env.find_value path val_env in Ctype.begin_def (); let expr = {exp_desc = Texp_ident(path, mknoloc(Longident.Lident (Ident.name id)),vd, Id_value); exp_loc = Location.none; exp_extra = []; exp_type = Ctype.instance vd.val_type; exp_mode = Value_mode.global; exp_attributes = []; exp_env = val_env; } in Ctype.end_def (); Ctype.generalize expr.exp_type; let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num); val_attributes = []; Types.val_loc = vd.Types.val_loc; val_uid = vd.val_uid; } in let id' = Ident.create_local (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents_with_modes defs) ([], met_env) in let cl = class_expr cl_num val_env met_env virt self_scope scl' in let () = if rec_flag = Recursive then check_recursive_bindings val_env defs in rc {cl_desc = Tcl_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_constraint (scl', scty) -> Ctype.begin_class_def (); let context = Typetexp.narrow () in let cl = class_expr cl_num val_env met_env virt self_scope scl' in complete_class_type cl.cl_loc val_env virt Class_type cl.cl_type; Typetexp.widen context; let context = Typetexp.narrow () in let clty = class_type val_env virt self_scope scty in complete_class_type clty.cltyp_loc val_env virt Class clty.cltyp_type; Typetexp.widen context; Ctype.end_def (); Ctype.limited_generalize_class_type (Btype.self_type_row cl.cl_type) cl.cl_type; Ctype.limited_generalize_class_type (Btype.self_type_row clty.cltyp_type) clty.cltyp_type; begin match Includeclass.class_types val_env cl.cl_type clty.cltyp_type with [] -> () | error -> raise(Error(cl.cl_loc, val_env, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty.cltyp_type in let ty = snd (Ctype.instance_class [] clty.cltyp_type) in Ctype.add_dummy_method val_env ~scope:self_scope (Btype.signature_of_class_type ty); rc {cl_desc = Tcl_constraint (cl, Some clty, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = ty; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_open (pod, e) -> let used_slot = ref false in let (od, new_val_env) = !type_open_descr ~used_slot val_env pod in let ( _, new_met_env) = !type_open_descr ~used_slot met_env pod in let cl = class_expr cl_num new_val_env new_met_env virt self_scope e in rc {cl_desc = Tcl_open (od, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env; cl_attributes = scl.pcl_attributes; } | Pcl_extension ext -> raise (Error_forward (Builtin_attributes.error_of_extension ext)) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in let arg = Ctype.newmono arg in let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in Ctype.newty (Tarrow (arrow_desc, arg, approx_declaration cl, commu_ok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_arrow (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in let arg = Ctype.newmono arg in let arrow_desc = l, Alloc_mode.global, Alloc_mode.global in Ctype.newty (Tarrow (arrow_desc, arg, approx_description ct, commu_ok)) | _ -> Ctype.newvar () let temp_abbrev loc env id arity uid = let params = ref [] in for _i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let env = Env.add_type ~check:true id {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc; or keep attrs from the class decl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = uid; } env in (!params, ty, env) let initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, cl_id, uid) = let arity = List.length cl.pci_params in let (obj_params, obj_ty, env) = temp_abbrev cl.pci_loc env obj_id arity uid in let (cl_params, cl_ty, env) = temp_abbrev cl.pci_loc env cl_id arity uid in if !Clflags.principal then Ctype.begin_def (); let constr_type = approx cl.pci_expr in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure constr_type; end; let dummy_cty = Cty_signature (Ctype.new_class_signature ()) in let dummy_class = cty_variance = []; cty_path = unbound_class; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = Location.none; cty_attributes = []; cty_uid = uid; } in let env = Env.add_cltype ty_id clty_variance = []; clty_path = unbound_class; clty_loc = Location.none; clty_attributes = []; clty_uid = uid; } ( if define_class then Env.add_class id dummy_class env else env ) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = reset_type_variables (); Ctype.begin_class_def (); let ci_params = let make_param (sty, v) = try (transl_type_param env sty, v) with Already_bound -> raise(Error(sty.ptyp_loc, env, Repeated_parameter)) in List.map make_param cl.pci_params in let params = List.map (fun (cty, _) -> cty.ctyp_type) ci_params in let coercion_locs = ref [] in let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_virt cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in let sign = Btype.signature_of_class_type typ in Ctype.end_def (); the row variable List.iter (Ctype.limited_generalize sign.csig_self_row) params; Ctype.limited_generalize_class_type sign.csig_self_row typ; let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let row = Btype.self_type_row obj_type in Ctype.unify env row (Ctype.newty Tnil); begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (obj_id, constr, Ctype.newconstr (Path.Pident obj_id) obj_params'))) end; let ty = Btype.self_type obj_type in begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; Ctype.set_object_name obj_id params (Btype.self_type typ); begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Btype.self_type cl_type in begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, env, Bad_parameters (cl_id, Ctype.newconstr (Path.Pident cl_id) cl_params, Ctype.newconstr (Path.Pident cl_id) cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let constr = Ctype.newconstr (Path.Pident cl_id) params in raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, cl_ty))) end end; begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Constructor_type_mismatch (cl.pci_name.txt, err))) end; let cty_variance = Variance.unknown_signature ~injective:false ~arity:(List.length params) in let cltydef = {clty_params = params; clty_type = Btype.class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some constr_type end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in let arity = Btype.class_type_arity typ in let pub_meths = Btype.public_methods sign in let (params', typ') = Ctype.instance_class params typ in let cltydef = {clty_params = params'; clty_type = Btype.class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id; clty_loc = cl.pci_loc; clty_attributes = cl.pci_attributes; clty_uid = dummy_class.cty_uid; } and clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = begin match cl.pci_virt with | Virtual -> None | Concrete -> Some (Ctype.instance constr_type) end; cty_loc = cl.pci_loc; cty_attributes = cl.pci_attributes; cty_uid = dummy_class.cty_uid; } in let obj_abbr = let arity = List.length obj_params in { type_params = obj_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some obj_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Btype.self_type typ) in Ctype.set_object_name obj_id cl_params cl_ty; let cl_abbr = let arity = List.length cl_params in { type_params = cl_params; type_arity = arity; type_kind = Type_abstract; type_private = Public; type_manifest = Some cl_ty; type_variance = Variance.unknown_signature ~injective:false ~arity; type_separability = Types.Separability.default_signature ~arity; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = cl.pci_loc; or keep attrs from cl ? type_immediate = Unknown; type_unboxed_default = false; type_uid = dummy_class.cty_uid; } in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params, arity, pub_meths, coe, expr) = begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify err -> raise(Error(cl.pci_loc, env, Non_collapsable_conjunction (id, clty, err))) end; List.iter Ctype.generalize clty.cty_params; Ctype.generalize_class_type clty.cty_type; Option.iter Ctype.generalize clty.cty_new; List.iter Ctype.generalize obj_abbr.type_params; Option.iter Ctype.generalize obj_abbr.type_manifest; List.iter Ctype.generalize cl_abbr.type_params; Option.iter Ctype.generalize cl_abbr.type_manifest; if Ctype.nongen_class_declaration clty then raise(Error(cl.pci_loc, env, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Btype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, env, Unbound_type_var(printer, reason))) end; { id; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr; arity; pub_meths; coe; id_loc = cl.pci_name; req = { ci_loc = cl.pci_loc; ci_virt = cl.pci_virt; ci_params = ci_params; ci_id_name = cl.pci_name; ci_id_class = id; ci_id_class_type = ty_id; ci_id_object = obj_id; ci_id_typehash = cl_id; ci_expr = expr; ci_decl = clty; ci_type_decl = cltydef; ci_attributes = cl.pci_attributes; } } let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = Builtin_attributes.warning_scope cl.pci_attributes (fun () -> class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) ) let extract_type_decls { clty; cltydef; obj_id; obj_abbr; cl_abbr; req} decls = (obj_id, obj_abbr, cl_abbr, clty, cltydef, req) :: decls let merge_type_decls decl (obj_abbr, cl_abbr, clty, cltydef) = {decl with obj_abbr; cl_abbr; clty; cltydef} let final_env define_class env { id; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr } = Env.add_type ~check:true obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_type ~check:true cl_id (Subst.type_declaration Subst.identity cl_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env))) let check_coercions env { id; id_loc; clty; ty_id; cltydef; obj_id; obj_abbr; cl_id; cl_abbr; arity; pub_meths; coe; req } = begin match coe with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype err -> raise(Typecore.Error(loc, env, Typecore.Not_subtype err)) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, env, Cannot_coerce_self obj_ty)) end; {cls_id = id; cls_id_loc = id_loc; cls_decl = clty; cls_ty_id = ty_id; cls_ty_decl = cltydef; cls_obj_id = obj_id; cls_obj_abbr = obj_abbr; cls_typesharp_id = cl_id; cls_abbr = cl_abbr; cls_arity = arity; cls_pub_methods = pub_meths; cls_info=req} let type_classes define_class approx kind env cls = let scope = Ctype.create_scope () in let cls = List.map (function cl -> (cl, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope cl.pci_name.txt, Ident.create_scoped ~scope ("#" ^ cl.pci_name.txt), Uid.mk ~current_unit:(Env.get_unit_name ()) )) cls in Ctype.begin_class_def (); let (res, newenv) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, newenv) = List.fold_right (class_infos define_class kind) res ([], newenv) in Ctype.end_def (); let res = List.rev_map (final_decl newenv define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = try Typedecl_variance.update_class_decls newenv decls with Typedecl_variance.Error(loc, err) -> raise (Typedecl.Error(loc, Typedecl.Variance err)) in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env virt sexpr = incr class_num; let self_scope = Ctype.get_current_level () in let expr = class_expr (Int.to_string !class_num) env env virt self_scope sexpr in complete_class_type expr.cl_loc env virt Class expr.cl_type; (expr, expr.cl_type) let class_description env virt sexpr = let self_scope = Ctype.get_current_level () in let expr = class_type env virt self_scope sexpr in complete_class_type expr.cltyp_loc env virt Class_type expr.cltyp_type; (expr, expr.cltyp_type) let class_declarations env cls = let info, env = type_classes true approx_declaration class_declaration env cls in let ids, exprs = List.split (List.map (fun ci -> ci.cls_id, ci.cls_info.ci_expr) info) in check_recursive_class_bindings env ids exprs; info, env let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decls, env) = type_classes false approx_description class_description env cls in (List.map (fun decl -> {clsty_ty_id = decl.cls_ty_id; clsty_id_loc = decl.cls_id_loc; clsty_ty_decl = decl.cls_ty_decl; clsty_obj_id = decl.cls_obj_id; clsty_obj_abbr = decl.cls_obj_abbr; clsty_typesharp_id = decl.cls_typesharp_id; clsty_abbr = decl.cls_abbr; clsty_info = decl.cls_info}) decls, env) let type_object env loc s = incr class_num; let desc = class_structure (Int.to_string !class_num) Concrete Btype.lowest_level Final env env loc s in complete_class_signature loc env Concrete Object desc.cstr_type; let meths = Btype.public_methods desc.cstr_type in (desc, meths) let () = Typecore.type_object := type_object let approx_class sdecl = let open Ast_helper in let self' = Typ.any () in let clty' = Cty.signature ~loc:sdecl.pci_expr.pcty_loc (Csig.mk self' []) in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = fst (class_type_declarations env (List.map approx_class sdecls)) open Format let non_virtual_string_of_kind = function | Object -> "object" | Class -> "non-virtual class" | Class_type -> "non-virtual class type" let report_error env ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint err -> fprintf ppf "@[<v>The class constraints are not consistent.@ "; Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type"); fprintf ppf "@]" | Field_type_mismatch (k, m, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Unexpected_field (ty, lab) -> fprintf ppf "@[@[<2>This object is expected to have type :@ %a@]\ @ This type does not have a method %s." Printtyp.type_expr ty lab | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply _ -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | Nolabel -> "out label" | l -> sprintf " label %s" (Btype.prefixed_label_name l) in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> XXX Revoir message | Improve error message fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> Printtyp.prepare_for_printing [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" !Oprint.out_type (Printtyp.tree_of_typexp Type abbrev) !Oprint.out_type (Printtyp.tree_of_typexp Type actual) !Oprint.out_type (Printtyp.tree_of_typexp Type expected) | Constructor_type_mismatch (c, err) -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (kind, mets, vals) -> let kind = non_virtual_string_of_kind kind in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This %s has virtual %s.@ \ @[<2>The following %s are virtual : %a@]@]" kind missings missings (pp_print_list ~pp_sep:pp_print_space pp_print_string) (mets @ vals) | Undeclared_methods(kind, mets) -> let kind = non_virtual_string_of_kind kind in fprintf ppf "@[This %s has undeclared virtual methods.@ \ @[<2>The following methods were not declared : %a@]@]" kind (pp_print_list ~pp_sep:pp_print_space pp_print_string) mets | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.prepare_for_printing [params; cstrs]; fprintf ppf "@[The abbreviation %a@ is used with parameters@ %a@ \ which are incompatible with constraints@ %a@]" Printtyp.ident id !Oprint.out_type (Printtyp.tree_of_typexp Type params) !Oprint.out_type (Printtyp.tree_of_typexp Type cstrs) | Class_match_failure error -> Includeclass.report_error Type ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_reason ppf (ty0, real, lab, ty) = let ty1 = if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.add_type_to_preparation ty; Printtyp.add_type_to_preparation ty1; fprintf ppf "The method %s@ has type@;<1 2>%a@ where@ %a@ is unbound" lab !Oprint.out_type (Printtyp.tree_of_typexp Type ty) !Oprint.out_type (Printtyp.tree_of_typexp Type ty0) in fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurrences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, err) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsible conjunctive types in constraints.@ %t@]" (Printtyp.class_declaration id) clty (fun ppf -> Printtyp.report_unification_error ppf env err (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") ) | Self_clash err -> Printtyp.report_unification_error ppf env err (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but actually has type") | Mutability_mismatch (_lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s;@ it cannot be redefined as %s@]" mut1 mut2 | No_overriding (_, "") -> fprintf ppf "@[This inheritance does not override any method@ %s@]" "instance variable" | No_overriding (kind, name) -> fprintf ppf "@[The %s `%s'@ has no previous definition@]" kind name | Duplicate (kind, name) -> fprintf ppf "@[The %s `%s'@ has multiple definitions in this object@]" kind name | Closing_self_type sign -> fprintf ppf "@[Cannot close type of object literal:@ %a@,\ it has been unified with the self type of a class that is not yet@ \ completely defined.@]" Printtyp.type_scheme sign.csig_self | Polymorphic_class_parameter -> fprintf ppf "Class parameters cannot be polymorphic" let report_error env ppf err = Printtyp.wrap_printing_env ~error:true env (fun () -> report_error env ppf err) let () = Location.register_error_of_exn (function | Error (loc, env, err) -> Some (Location.error_of_printer ~loc (report_error env) err) | Error_forward err -> Some err | _ -> None )
e91bbe55cdaf593ea2763c41c14571beaa764bda9fda3405f04780972192cd75
troy-west/apache-kafka-number-stations-clj
radio.clj
(ns numbers.radio (:require [numbers.image :as image] [numbers.kafka :as kafka]) (:import (org.apache.kafka.clients.producer ProducerRecord KafkaProducer))) (defn listen "Nearly three hours of Numbers Station broadcast from 1557125670763 to 1557135278803" [] (image/obsfuscate image/source)) (defn sample [] (take 20 (listen))) (defn stations [] (map #(format "%03d" %1) (range (image/height image/source)))) (defn produce "Send the radio burst to the radio-logs topic on Kafka" [] ;; implement me! (let [^KafkaProducer producer (kafka/producer)] (doseq [message (listen)] (.send producer (ProducerRecord. "radio-logs" (:name message) message)))))
null
https://raw.githubusercontent.com/troy-west/apache-kafka-number-stations-clj/d38b8ef57c38c056b41e1d24a2b8671479113300/src/numbers/radio.clj
clojure
implement me!
(ns numbers.radio (:require [numbers.image :as image] [numbers.kafka :as kafka]) (:import (org.apache.kafka.clients.producer ProducerRecord KafkaProducer))) (defn listen "Nearly three hours of Numbers Station broadcast from 1557125670763 to 1557135278803" [] (image/obsfuscate image/source)) (defn sample [] (take 20 (listen))) (defn stations [] (map #(format "%03d" %1) (range (image/height image/source)))) (defn produce "Send the radio burst to the radio-logs topic on Kafka" [] (let [^KafkaProducer producer (kafka/producer)] (doseq [message (listen)] (.send producer (ProducerRecord. "radio-logs" (:name message) message)))))
1ec48429cb3794521368b9221d228a3174520970771ddc05867bf20e3fa0b77d
janestreet/base
test_uniform_array.ml
open! Import open Uniform_array let does_raise = Exn.does_raise let zero_obj = Stdlib.Obj.repr (0 : int) (* [create_obj_array] *) let%test_unit _ = let t = create_obj_array ~len:0 in assert (length t = 0) ;; (* [create] *) let%test_unit _ = let str = Stdlib.Obj.repr "foo" in let t = create ~len:2 str in assert (phys_equal (get t 0) str); assert (phys_equal (get t 1) str) ;; let%test_unit _ = let float = Stdlib.Obj.repr 3.5 in let t = create ~len:2 float in assert (Stdlib.Obj.tag (Stdlib.Obj.repr t) = 0); (* not a double array *) assert (phys_equal (get t 0) float); assert (phys_equal (get t 1) float); set t 1 (Stdlib.Obj.repr 4.); assert (Float.( = ) (Stdlib.Obj.obj (get t 1)) 4.) ;; (* [empty] *) let%test _ = length empty = 0 let%test _ = does_raise (fun () -> get empty 0) (* [singleton] *) let%test _ = length (singleton zero_obj) = 1 let%test _ = phys_equal (get (singleton zero_obj) 0) zero_obj let%test _ = does_raise (fun () -> get (singleton zero_obj) 1) let%test_unit _ = let f = 13. in let t = singleton (Stdlib.Obj.repr f) in invariant t; assert (Poly.equal (Stdlib.Obj.repr f) (get t 0)) ;; (* [get], [unsafe_get], [set], [unsafe_set], [unsafe_set_assuming_currently_int], [set_with_caml_modify] *) let%test_unit _ = let t = create_obj_array ~len:1 in assert (length t = 1); assert (phys_equal (get t 0) zero_obj); assert (phys_equal (unsafe_get t 0) zero_obj); let one_obj = Stdlib.Obj.repr (1 : int) in let check_get expect = assert (phys_equal (get t 0) expect); assert (phys_equal (unsafe_get t 0) expect) in set t 0 one_obj; check_get one_obj; unsafe_set t 0 zero_obj; check_get zero_obj; unsafe_set_assuming_currently_int t 0 one_obj; check_get one_obj; set_with_caml_modify t 0 zero_obj; check_get zero_obj ;; let%expect_test "exists" = let test arr f = of_list arr |> exists ~f in let r here = require_equal here (module Bool) in r [%here] false (test [] Fn.id); r [%here] true (test [ true ] Fn.id); r [%here] true (test [ false; false; false; false; true ] Fn.id); r [%here] true (test [ 0; 1; 2; 3; 4 ] (fun i -> i % 2 = 1)); r [%here] false (test [ 0; 2; 4; 6; 8 ] (fun i -> i % 2 = 1)); [%expect {| |}] ;; let%expect_test "for_all" = let test arr f = of_list arr |> for_all ~f in let r here = require_equal here (module Bool) in r [%here] true (test [] Fn.id); r [%here] true (test [ true ] Fn.id); r [%here] false (test [ false; false; false; false; true ] Fn.id); r [%here] false (test [ 0; 1; 2; 3; 4 ] (fun i -> i % 2 = 1)); r [%here] true (test [ 0; 2; 4; 6; 8 ] (fun i -> i % 2 = 0)); [%expect {| |}] ;; let%expect_test "iteri" = let test arr = of_list arr |> iteri ~f:(printf "(%d %c)") in test []; [%expect {| |}]; test [ 'a' ]; [%expect {| (0 a) |}]; test [ 'a'; 'b'; 'c'; 'd' ]; [%expect {| (0 a)(1 b)(2 c)(3 d) |}] ;; module Sequence = struct type nonrec 'a t = 'a t type 'a z = 'a let length = length let get = get let set = set let create_bool ~len = create ~len false end include Base_for_tests.Test_blit.Test1 (Sequence) (Uniform_array) let%expect_test "map2_exn" = let test a1 a2 f = let result = map2_exn ~f (of_list a1) (of_list a2) in print_s [%message (result : int Uniform_array.t)] in test [] [] (fun _ -> failwith "don't call me"); [%expect {| (result ()) |}]; test [ 1; 2; 3 ] [ 100; 200; 300 ] ( + ); [%expect {| (result (101 202 303)) |}]; require_does_raise [%here] (fun () -> test [ 1 ] [] (fun _ _ -> 0)); [%expect {| (Invalid_argument Array.map2_exn) |}] ;; let%expect_test "mapi" = let test arr = let mapped = of_list arr |> mapi ~f:(fun i str -> i, String.capitalize str) in print_s [%sexp (mapped : (int * string) t)] in test []; [%expect {| () |}]; test [ "foo"; "bar" ]; [%expect {| ((0 Foo) (1 Bar)) |}] ;;
null
https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/test/test_uniform_array.ml
ocaml
[create_obj_array] [create] not a double array [empty] [singleton] [get], [unsafe_get], [set], [unsafe_set], [unsafe_set_assuming_currently_int], [set_with_caml_modify]
open! Import open Uniform_array let does_raise = Exn.does_raise let zero_obj = Stdlib.Obj.repr (0 : int) let%test_unit _ = let t = create_obj_array ~len:0 in assert (length t = 0) ;; let%test_unit _ = let str = Stdlib.Obj.repr "foo" in let t = create ~len:2 str in assert (phys_equal (get t 0) str); assert (phys_equal (get t 1) str) ;; let%test_unit _ = let float = Stdlib.Obj.repr 3.5 in let t = create ~len:2 float in assert (Stdlib.Obj.tag (Stdlib.Obj.repr t) = 0); assert (phys_equal (get t 0) float); assert (phys_equal (get t 1) float); set t 1 (Stdlib.Obj.repr 4.); assert (Float.( = ) (Stdlib.Obj.obj (get t 1)) 4.) ;; let%test _ = length empty = 0 let%test _ = does_raise (fun () -> get empty 0) let%test _ = length (singleton zero_obj) = 1 let%test _ = phys_equal (get (singleton zero_obj) 0) zero_obj let%test _ = does_raise (fun () -> get (singleton zero_obj) 1) let%test_unit _ = let f = 13. in let t = singleton (Stdlib.Obj.repr f) in invariant t; assert (Poly.equal (Stdlib.Obj.repr f) (get t 0)) ;; let%test_unit _ = let t = create_obj_array ~len:1 in assert (length t = 1); assert (phys_equal (get t 0) zero_obj); assert (phys_equal (unsafe_get t 0) zero_obj); let one_obj = Stdlib.Obj.repr (1 : int) in let check_get expect = assert (phys_equal (get t 0) expect); assert (phys_equal (unsafe_get t 0) expect) in set t 0 one_obj; check_get one_obj; unsafe_set t 0 zero_obj; check_get zero_obj; unsafe_set_assuming_currently_int t 0 one_obj; check_get one_obj; set_with_caml_modify t 0 zero_obj; check_get zero_obj ;; let%expect_test "exists" = let test arr f = of_list arr |> exists ~f in let r here = require_equal here (module Bool) in r [%here] false (test [] Fn.id); r [%here] true (test [ true ] Fn.id); r [%here] true (test [ false; false; false; false; true ] Fn.id); r [%here] true (test [ 0; 1; 2; 3; 4 ] (fun i -> i % 2 = 1)); r [%here] false (test [ 0; 2; 4; 6; 8 ] (fun i -> i % 2 = 1)); [%expect {| |}] ;; let%expect_test "for_all" = let test arr f = of_list arr |> for_all ~f in let r here = require_equal here (module Bool) in r [%here] true (test [] Fn.id); r [%here] true (test [ true ] Fn.id); r [%here] false (test [ false; false; false; false; true ] Fn.id); r [%here] false (test [ 0; 1; 2; 3; 4 ] (fun i -> i % 2 = 1)); r [%here] true (test [ 0; 2; 4; 6; 8 ] (fun i -> i % 2 = 0)); [%expect {| |}] ;; let%expect_test "iteri" = let test arr = of_list arr |> iteri ~f:(printf "(%d %c)") in test []; [%expect {| |}]; test [ 'a' ]; [%expect {| (0 a) |}]; test [ 'a'; 'b'; 'c'; 'd' ]; [%expect {| (0 a)(1 b)(2 c)(3 d) |}] ;; module Sequence = struct type nonrec 'a t = 'a t type 'a z = 'a let length = length let get = get let set = set let create_bool ~len = create ~len false end include Base_for_tests.Test_blit.Test1 (Sequence) (Uniform_array) let%expect_test "map2_exn" = let test a1 a2 f = let result = map2_exn ~f (of_list a1) (of_list a2) in print_s [%message (result : int Uniform_array.t)] in test [] [] (fun _ -> failwith "don't call me"); [%expect {| (result ()) |}]; test [ 1; 2; 3 ] [ 100; 200; 300 ] ( + ); [%expect {| (result (101 202 303)) |}]; require_does_raise [%here] (fun () -> test [ 1 ] [] (fun _ _ -> 0)); [%expect {| (Invalid_argument Array.map2_exn) |}] ;; let%expect_test "mapi" = let test arr = let mapped = of_list arr |> mapi ~f:(fun i str -> i, String.capitalize str) in print_s [%sexp (mapped : (int * string) t)] in test []; [%expect {| () |}]; test [ "foo"; "bar" ]; [%expect {| ((0 Foo) (1 Bar)) |}] ;;
2f36088b03f6dcf129adbc6fbd02e9a65908ee95e00aa502e8a2a4849f98b0b7
tact-lang/tact-obsolete
codegen_func.ml
open Shared.Disabled module Config = Shared.DisabledConfig let%expect_test "simple function generation" = let source = {| fn test() -> Integer { return 0; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test() impure { return 0; } |}] let%expect_test "passing struct to a function" = let source = {| struct T { val b: Integer val c: struct { val d : Integer } } fn test(t: T) -> Integer { return 1; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int] t) impure { return 1; } |}] let%expect_test "function calls" = let source = {| fn test(value: Integer) -> Integer { return value; } fn test2(value: Integer) -> Integer { return test(value); } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int value) impure { return value; } int test2(int value) impure { return test(value); } |}] let%expect_test "Int[bits] serializer codegen" = let source = {| fn test_int(b: Builder) { let i = Int[32].new(100); i.serialize(b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } _ test_int(builder b) impure { int i = 100; return f1(100, b); } |}] let%expect_test "demo struct serializer" = let source = {| struct T { val a: Int[32] val b: Int[16] } let T_serializer = serializer[T]; fn test() { let b = Builder.new(); T_serializer(T{a: Int[32].new(0), b: Int[16].new(1)}, b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder f3(int self, builder builder_) impure { return f2(builder_, self, 16); } builder T_serializer([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); builder b = f3(get1(func_believe_me(self)), b); return b; } builder f4() impure { return builtin_begin_cell(); } _ test() impure { builder b = f4(); return T_serializer([0, 1], b); } |}] let%expect_test "demo struct serializer 2" = let source = {| struct Foo { val a: Int[32] val b: Int[16] } let serialize_foo = serializer[Foo]; fn test() -> Builder { let b = Builder.new(); return serialize_foo(Foo{a: Int[32].new(0), b: Int[16].new(1)}, b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder f3(int self, builder builder_) impure { return f2(builder_, self, 16); } builder serialize_foo([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); builder b = f3(get1(func_believe_me(self)), b); return b; } builder f4() impure { return builtin_begin_cell(); } builder test() impure { builder b = f4(); return serialize_foo([0, 1], b); } |}] let%expect_test "true and false" = let source = {| fn test(flag: Bool) { if (flag) { return false; } else { return true; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int flag) impure { if (flag) { return 0; } else { return -1; } } |}] let%expect_test "if/then/else" = let source = {| fn test(flag: Bool) { if (flag) { return 1; } else { return 2; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int flag) impure { if (flag) { return 1; } else { return 2; } } |}] let%expect_test "serializer inner struct" = let source = {| struct Pubkey { val x: Int[160] } struct Wallet { val seqno: Int[32] val pubkey: Pubkey } let serialize_wallet = serializer[Wallet]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder serialize_wallet([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); return b; } |}] let%expect_test "unions" = let source = {| struct Empty{} union Uni { case Integer case Empty } fn try(x: Uni) -> Uni { x } fn test_try(x: Integer, y: Empty) { let test1 = try(x); let test2 = try(y); } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } tuple try(tuple x) impure { return x; } tuple f0(int v) impure { return func_believe_me([0, v]); } tuple f1([] v) impure { return func_believe_me([1, v]); } _ test_try(int x, [] y) impure { tuple test1 = try(f0(x)); tuple test2 = try(f1(y)); } |}] let%expect_test "switch statement" = let source = {| union Ints { case Int[32] case Int[64] } fn test(i: Ints) -> Integer { switch (i) { case Int[32] vax => { return 32; } case Int[64] vax => { return 64; } } } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } int test(tuple i) impure { { tuple temp = i; int discr = first(temp); { if (discr == 0) { int vax = second(temp); { return 32; } } else { if (discr == 1) { int vax = second(temp); { return 64; } } else { thrown(90); return func_believe_me([]); } } } } } |}] let%expect_test "tensor2" = let source = {| fn test() { let x = builtin_divmod(10, 2); return x.value1; } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } int test() impure { (int, int) x = builtin_divmod(10, 2); return tensor2_value1(x); } |}] let%expect_test "serialization api" = let source = {| struct Empty { impl Serialize { fn serialize(self: Self, b: Builder) -> Builder { return b; } } } fn test(m: MessageRelaxed[Empty]) { let b = Builder.new(); let b = m.serialize(b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get3(tuple t) asm "3 INDEX"; forall A -> A get2(tuple t) asm "2 INDEX"; forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f1() impure { return builtin_begin_cell(); } builder f4(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f9([] self, builder b) impure { return b; } builder f11(int self, builder builder_) impure { return f4(builder_, self, 9); } builder f10([int, int] self, builder b) impure { builder b = f11(get0(func_believe_me(self)), b); builder b = f4(b, get1(func_believe_me(self)), get0(func_believe_me(self))); return b; } builder f14(int self, builder builder_) impure { return f4(builder_, self, 8); } builder f15(int self, builder builder_) impure { return f4(builder_, self, 256); } builder f13([int, int] self, builder b) impure { builder b = f14(get0(func_believe_me(self)), b); builder b = f15(get1(func_believe_me(self)), b); return b; } builder f12([int, int] self, builder b) impure { builder b = f4(b, 0, 0); return f13(self, b); } builder f18(int self, builder builder_) impure { return f4(builder_, self, 32); } builder f17([int, int, int] self, builder b) impure { builder b = f11(get0(func_believe_me(self)), b); builder b = f18(get1(func_believe_me(self)), b); return b; } builder f16([int, int, int] self, builder b) impure { builder b = f4(b, 0, 0); builder b = f17(self, b); return b; } builder f8(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f16(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f12(varr, b); return b; } } else { if (discr == 1) { [int, int] varr = second(temp); { builder b = store_uint(b, 1, 2); builder b = f10(varr, b); return b; } } else { if (discr == 0) { [] varr = second(temp); { builder b = store_uint(b, 0, 2); builder b = f9(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } } } builder f7(tuple self, builder b) impure { return f8(self, b); } builder f20(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 1) { [int, int] varr = second(temp); { builder b = store_uint(b, 1, 2); builder b = f10(varr, b); return b; } } else { if (discr == 0) { [] varr = second(temp); { builder b = store_uint(b, 0, 2); builder b = f9(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f19(tuple self, builder b) impure { return f20(self, b); } builder f22(builder self, int uint, int bits) impure { return builtin_store_uint(self, uint, bits); } builder f21(int self, builder builder_) impure { return f22(builder_, self, 64); } builder f23(int self, builder builder_) impure { return f22(builder_, self, 32); } builder f6([tuple, tuple, int, int] self, builder b) impure { builder b = f7(get0(func_believe_me(self)), b); builder b = f19(get1(func_believe_me(self)), b); builder b = f21(get2(func_believe_me(self)), b); builder b = f23(get3(func_believe_me(self)), b); return b; } builder f5([tuple, tuple, int, int] self, builder b) impure { return f6(self, b); } builder f28(int self, builder builder_) impure { return f22(builder_, self, 1); } builder f27([int, int, int] self, builder b) impure { builder b = f28(get0(func_believe_me(self)), b); builder b = f28(get1(func_believe_me(self)), b); builder b = f28(get2(func_believe_me(self)), b); return b; } builder f26([int, int, int] self, builder b) impure { return f27(self, b); } builder f32(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f16(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f12(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f31(tuple self, builder b) impure { return f32(self, b); } builder f30([tuple, tuple] self, builder b) impure { builder b = f31(get0(func_believe_me(self)), b); builder b = f31(get1(func_believe_me(self)), b); return b; } builder f29([tuple, tuple] self, builder b) impure { return f30(self, b); } builder f36(builder self, int c) impure { return builtin_store_grams(self, c); } builder f35(int self, builder builder_) impure { return f36(builder_, self); } builder f34([int, int, int, int] self, builder b) impure { builder b = f35(get0(func_believe_me(self)), b); builder b = f28(get1(func_believe_me(self)), b); builder b = f35(get2(func_believe_me(self)), b); builder b = f35(get3(func_believe_me(self)), b); return b; } builder f33([int, int, int, int] self, builder b) impure { return f34(self, b); } builder f38([int, int] self, builder b) impure { builder b = f21(get0(func_believe_me(self)), b); builder b = f23(get1(func_believe_me(self)), b); return b; } builder f37([int, int] self, builder b) impure { return f38(self, b); } builder f25([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { builder b = f26(get0(func_believe_me(self)), b); builder b = f29(get1(func_believe_me(self)), b); builder b = f33(get2(func_believe_me(self)), b); builder b = f37(get3(func_believe_me(self)), b); return b; } builder f24([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { return f25(self, b); } builder f3(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 1) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] info = second(temp); { builder b = f4(b, 0, 1); return f24(info, b); } } else { if (discr == 0) { [tuple, tuple, int, int] info = second(temp); { builder b = f4(b, 3, 2); return f5(info, b); } } else { thrown(90); return func_believe_me([]); } } } } } builder f39([] self, builder b) impure { return b; } builder f2([tuple, []] self, builder b) impure { builder b = f3(get0(func_believe_me(self)), b); builder b = f4(b, 0, 1); builder b = f4(b, 0, 1); builder b = f39(get1(func_believe_me(self)), b); return b; } _ test([tuple, []] m) impure { builder b = f1(); builder b = f2(m, b); } |}] let%expect_test "deserialization api" = let source = {| struct Empty { impl Deserialize { fn deserialize(s: Slice) -> LoadResult[Self] { return LoadResult[Self].new(s, Self{}); } } } fn test(c: Cell) { let s = Slice.parse(c); let msg = Message[Empty].deserialize(s); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } slice f1(cell cell_) impure { return builtin_begin_parse(cell_); } [slice, int] f5(slice self, int bits) impure { (slice, int) output = builtin_load_uint(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f12(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f11(slice s) impure { [slice, int] res = f12(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] f10(slice slice_) impure { [slice slice_, int len] = f11(slice_); [slice slice_, int bits] = f12(slice_, len); return [slice_, [len, bits]]; } [slice, tuple] f13(tuple v, slice s) impure { return [s, v]; } [slice, []] f15([] v, slice s) impure { return [s, v]; } [slice, []] f14(slice s) impure { return f15(s, []); } [slice, tuple] f9(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, []] res = f14(get0(func_believe_me(res_discr))); return f13(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 1)) { [slice, [int, int]] res = f10(get0(func_believe_me(res_discr))); return f13(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f8(slice s) impure { return f9(s); } [slice, int] f19(slice s) impure { [slice, int] res = f12(s, 32); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int, int]] f20([int, int, int] v, slice s) impure { return [s, v]; } int f21(int left, int right) impure { return builtin_eq(left, right); } [slice, [int, int, int]] f18(slice s) impure { [slice slice_, int anycast] = f12(s, 1); if (f21(anycast, 0)) { [slice slice_, int len] = f11(slice_); [slice slice_, int workchain_id] = f19(slice_); [slice slice_, int address] = f12(slice_, len); return f20(slice_, [len, workchain_id, address]); } else { thrown(0); } } [slice, tuple] f22(tuple v, slice s) impure { return [s, v]; } [slice, int] f25(slice s) impure { [slice, int] res = f12(s, 8); [slice slice_, int value] = res; return [slice_, value]; } [slice, int] f26(slice s) impure { [slice, int] res = f12(s, 256); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] f24(slice slice_) impure { [slice slice_, int workchain_id] = f25(slice_); [slice slice_, int address] = f26(slice_); return [slice_, [workchain_id, address]]; } [slice, [int, int]] f23(slice s) impure { [slice, int] res_anycast = f12(s, 1); if (f21(get1(func_believe_me(res_anycast)), 0)) { return f24(s); } else { thrown(0); } } [slice, tuple] f17(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 2)) { [slice, [int, int]] res = f23(get0(func_believe_me(res_discr))); return f22(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 3)) { [slice, [int, int, int]] res = f18(get0(func_believe_me(res_discr))); return f22(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f16(slice s) impure { return f17(s); } [slice, int] f28(slice self) impure { (slice, int) output = builtin_load_grams(self); slice slice_ = tensor2_value1(output); int coins = tensor2_value2(output); return [believe_me(slice_), coins]; } [slice, int] f29(int v, slice s) impure { return [s, v]; } [slice, int] f27(slice s) impure { [slice slice_, int value] = f28(s); return f29(value, slice_); } [slice, [tuple, tuple, int]] f7(slice slice_) impure { [slice slice_, tuple src] = f8(slice_); [slice slice_, tuple dest] = f16(slice_); [slice slice_, int import_fee] = f27(slice_); return [slice_, [src, dest, import_fee]]; } [slice, [tuple, tuple, int]] f6(slice s) impure { return f7(s); } [slice, tuple] f30(tuple v, slice s) impure { return [s, v]; } [slice, int] f35(slice s) impure { [slice, int] res = f5(s, 1); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, [int, int, int]] f34(slice slice_) impure { [slice slice_, int ihr_disabled] = f35(slice_); [slice slice_, int bounce] = f35(slice_); [slice slice_, int bounced] = f35(slice_); return [slice_, [ihr_disabled, bounce, bounced]]; } [slice, [int, int, int]] f33(slice s) impure { return f34(s); } [slice, [tuple, tuple]] f37(slice slice_) impure { [slice slice_, tuple src] = f16(slice_); [slice slice_, tuple dst] = f16(slice_); return [slice_, [src, dst]]; } [slice, [tuple, tuple]] f36(slice s) impure { return f37(s); } [slice, [int, int, int, int]] f39(slice slice_) impure { [slice slice_, int amount] = f27(slice_); [slice slice_, int _extra_currencies] = f35(slice_); [slice slice_, int ihr_fee] = f27(slice_); [slice slice_, int fwd_fee] = f27(slice_); return [slice_, [amount, _extra_currencies, ihr_fee, fwd_fee]]; } [slice, [int, int, int, int]] f38(slice s) impure { return f39(s); } [slice, int] f42(slice s) impure { [slice, int] res = f5(s, 64); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, int] f43(slice s) impure { [slice, int] res = f5(s, 32); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, [int, int]] f41(slice slice_) impure { [slice slice_, int created_lt] = f42(slice_); [slice slice_, int created_at] = f43(slice_); return [slice_, [created_lt, created_at]]; } [slice, [int, int]] f40(slice s) impure { return f41(s); } [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] f32(slice slice_) impure { [slice slice_, [int, int, int] flags] = f33(slice_); [slice slice_, [tuple, tuple] addresses] = f36(slice_); [slice slice_, [int, int, int, int] coins] = f38(slice_); [slice slice_, [int, int] timestamps] = f40(slice_); return [slice_, [flags, addresses, coins, timestamps]]; } [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] f31(slice s) impure { return f32(s); } [slice, tuple] f4(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] res = f31(get0(func_believe_me(res_discr))); return f30(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 2)) { [slice, [tuple, tuple, int]] res = f6(get0(func_believe_me(res_discr))); return f30(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f3(slice s) impure { return f4(s); } [slice, []] f45([] v, slice s) impure { return [s, v]; } [slice, []] f44(slice s) impure { return f45(s, []); } [slice, [tuple, []]] f46([tuple, []] v, slice s) impure { return [s, v]; } [slice, [tuple, []]] f2(slice s) impure { [slice slice_, tuple info] = f3(s); [slice slice_, int init] = f12(slice_, 1); if (f21(init, 0)) { [slice slice_, int discr] = f12(slice_, 1); if (f21(discr, 0)) { [slice slice_, [] body] = f44(slice_); [tuple, _] mes = [info, believe_me(body)]; return f46(mes, slice_); } else { thrown(0); } } else { thrown(0); } } _ test(cell c) impure { slice s = f1(c); [slice, [tuple, []]] msg = f2(s); } |}] let%expect_test "destructuring let" = let source = {| struct T { val x: Integer val y: Integer val z: Integer } fn test(t: T) -> Integer { let {x, y as y2, z} = t; y2 } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int, int] t) impure { [int x, int y2, int z] = t; return y2; } |}] let%expect_test "destructuring let with rest ignored" = let source = {| struct T { val x: Integer val y: Integer val z: Integer } fn test(t: T) -> Integer { let {y as y2, ..} = t; y2 } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int, int] t) impure { [_, int y2, _] = t; return y2; } |}] let%expect_test "deserializer" = let source = {| struct Something { val value1: Int[9] val value2: Int[256] } let test = deserializer[Something]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [slice, int] f2(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f1(slice s) impure { [slice, int] res = f2(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, int] f3(slice s) impure { [slice, int] res = f2(s, 256); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] test(slice slice_) impure { [slice slice_, int value1] = f1(slice_); [slice slice_, int value2] = f3(slice_); return [slice_, [value1, value2]]; } |}] let%expect_test "deserializer unions" = let source = {| union TestUnion { case Int[8] case Int[9] } let deserialize_union = deserializer[TestUnion]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [slice, int] f1(slice self, int bits) impure { (slice, int) output = builtin_load_uint(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f3(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f2(slice s) impure { [slice, int] res = f3(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, tuple] f4(tuple v, slice s) impure { return [s, v]; } [slice, int] f5(slice s) impure { [slice, int] res = f3(s, 8); [slice slice_, int value] = res; return [slice_, value]; } [slice, tuple] deserialize_union(slice slice_) impure { [slice, int] res_discr = f1(slice_, 1); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, int] res = f5(get0(func_believe_me(res_discr))); return f4(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f1(slice_, 1); if (builtin_eq(get1(func_believe_me(res_discr)), 1)) { [slice, int] res = f2(get0(func_believe_me(res_discr))); return f4(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } |}] let%expect_test "assignment" = let source = {| fn test(x: Integer) { let a = 1; a = x; a } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int x) impure { int a = 1; a = x; return a; } |}] let%expect_test "assignment with condition block" = let source = {| fn test(x: Int[257]) { let a = 1; if (true) { a = 10; } else { a = 20; } return a; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int x) impure { int a = 1; if (-1) { a = 10; } else { a = 20; } return a; } |}] let%expect_test "codegen while block" = let source = {| fn test() { let a = 10; while (true) { a = 20; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } _ test() impure { int a = 10; while (-1) { a = 20; } } |}] let%expect_test "request builder" = let source = {| struct EmptyMsg { @derive impl Serialize {} } fn test_req_builder() { let b = RequestBuilder[EmptyMsg].new() .can_be_bounced() .ihr_disabled() .money(Coins.new(1)) .body(EmptyMsg{}) .send_to(AddressStd.new(0, 0)); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get4(tuple t) asm "4 INDEX"; forall A -> A get3(tuple t) asm "3 INDEX"; forall A -> A get2(tuple t) asm "2 INDEX"; forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [[int, int, int], int, [int, int, int, int], int, []] f1() impure { return [[0, 0, 0], 0, [0, 0, 0, 0], 0, believe_me(0)]; } [[int, int, int], int, [int, int, int, int], int, []] f2([[int, int, int], int, [int, int, int, int], int, []] self) impure { return [[get0(func_believe_me(get0(func_believe_me(self)))), 1, 0], get1(func_believe_me(self)), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } [[int, int, int], int, [int, int, int, int], int, []] f3([[int, int, int], int, [int, int, int, int], int, []] self) impure { return [[1, get1(func_believe_me(get0(func_believe_me(self)))), 0], get1(func_believe_me(self)), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } int f6(int left, int right) impure { return builtin_add(left, right); } int f7(int i) impure { return i; } int f5(int self) impure { return f7(f6(self, 64)); } int f8(int self) impure { return f7(f6(self, 128)); } [int, int, int, int] f9(int amount, int ihr_fee, int fwd_fee) impure { return [amount, 0, ihr_fee, fwd_fee]; } [[int, int, int], int, [int, int, int, int], int, []] f4([[int, int, int], int, [int, int, int, int], int, []] self, tuple money) impure { { tuple temp = money; int discr = first(temp); { if (discr == 0) { int coins = second(temp); { return [get0(func_believe_me(self)), get1(func_believe_me(self)), f9(coins, get2(func_believe_me(get2(func_believe_me(self)))), get3(func_believe_me(get2(func_believe_me(self))))), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { if (discr == 1) { [] _ = second(temp); { return [get0(func_believe_me(self)), f8(get1(func_believe_me(self))), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { if (discr == 2) { [] _ = second(temp); { return [get0(func_believe_me(self)), f5(get1(func_believe_me(self))), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { thrown(90); return func_believe_me([]); } } } } } } [[int, int, int], int, [int, int, int, int], int, []] f10([[int, int, int], int, [int, int, int, int], int, []] self, [] body) impure { return [get0(func_believe_me(self)), get1(func_believe_me(self)), get2(func_believe_me(self)), -1, body]; } [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] f12([int, int, int] flags, tuple dst, [int, int, int, int] coins) impure { return [flags, [func_believe_me([2, [0, 0]]), dst], coins, [0, 0]]; } tuple f13([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] v) impure { return func_believe_me([0, v]); } builder f14() impure { return builtin_begin_cell(); } builder f22(builder self, int uint, int bits) impure { return builtin_store_uint(self, uint, bits); } builder f21(int self, builder builder_) impure { return f22(builder_, self, 1); } builder f20([int, int, int] self, builder b) impure { builder b = f21(get0(func_believe_me(self)), b); builder b = f21(get1(func_believe_me(self)), b); builder b = f21(get2(func_believe_me(self)), b); return b; } builder f19([int, int, int] self, builder b) impure { return f20(self, b); } builder f28(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f30(int self, builder builder_) impure { return f28(builder_, self, 8); } builder f31(int self, builder builder_) impure { return f28(builder_, self, 256); } builder f29([int, int] self, builder b) impure { builder b = f30(get0(func_believe_me(self)), b); builder b = f31(get1(func_believe_me(self)), b); return b; } builder f27([int, int] self, builder b) impure { builder b = f28(b, 0, 0); return f29(self, b); } builder f34(int self, builder builder_) impure { return f28(builder_, self, 9); } builder f35(int self, builder builder_) impure { return f28(builder_, self, 32); } builder f33([int, int, int] self, builder b) impure { builder b = f34(get0(func_believe_me(self)), b); builder b = f35(get1(func_believe_me(self)), b); return b; } builder f32([int, int, int] self, builder b) impure { builder b = f28(b, 0, 0); builder b = f33(self, b); return b; } builder f26(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f32(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f27(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f25(tuple self, builder b) impure { return f26(self, b); } builder f24([tuple, tuple] self, builder b) impure { builder b = f25(get0(func_believe_me(self)), b); builder b = f25(get1(func_believe_me(self)), b); return b; } builder f23([tuple, tuple] self, builder b) impure { return f24(self, b); } builder f39(builder self, int c) impure { return builtin_store_grams(self, c); } builder f38(int self, builder builder_) impure { return f39(builder_, self); } builder f37([int, int, int, int] self, builder b) impure { builder b = f38(get0(func_believe_me(self)), b); builder b = f21(get1(func_believe_me(self)), b); builder b = f38(get2(func_believe_me(self)), b); builder b = f38(get3(func_believe_me(self)), b); return b; } builder f36([int, int, int, int] self, builder b) impure { return f37(self, b); } builder f42(int self, builder builder_) impure { return f22(builder_, self, 64); } builder f43(int self, builder builder_) impure { return f22(builder_, self, 32); } builder f41([int, int] self, builder b) impure { builder b = f42(get0(func_believe_me(self)), b); builder b = f43(get1(func_believe_me(self)), b); return b; } builder f40([int, int] self, builder b) impure { return f41(self, b); } builder f18([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { builder b = f19(get0(func_believe_me(self)), b); builder b = f23(get1(func_believe_me(self)), b); builder b = f36(get2(func_believe_me(self)), b); builder b = f40(get3(func_believe_me(self)), b); return b; } builder f17([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { return f18(self, b); } builder f16(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 0) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] varr = second(temp); { builder b = store_uint(b, 0, 1); builder b = f17(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } builder f15(tuple self, builder b) impure { return f16(self, b); } builder f45([] self, builder b) impure { return b; } builder f44([] self, builder b) impure { return f45(self, b); } cell f46(builder self) impure { return builtin_end_cell(self); } _ f11([[int, int, int], int, [int, int, int, int], int, []] self, tuple dst) impure { if (get3(func_believe_me(self))) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] info = f12(get0(func_believe_me(self)), dst, get2(func_believe_me(self))); builder b = f15(f13(info), f14()); builder b = f28(b, 0, 1); builder b = f28(b, 0, 1); builder b = f44(get4(func_believe_me(self)), b); send_raw_msg(f46(b), get1(func_believe_me(self))); } else { thrown(87); } } _ test_req_builder() impure { _ b = f11(f10(f4(f3(f2(f1())), func_believe_me([0, 1])), []), func_believe_me([2, [0, 0]])); } |}] let%expect_test "field assignment" = let source = {| struct Test { val field1: Integer val field2: Integer } fn test() { let a = Test { field1: 0, field2: 1 }; a.field1 = 2; a.field2 = 3; } |} in pp_codegen source ~include_std:false ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall F, T -> T update1(tuple t, F elem) asm "1 SETINDEX"; forall F, T -> T update0(tuple t, F elem) asm "0 SETINDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ test() impure { [int, int] a = [0, 1]; a = update0(func_believe_me(a), 2); a = update1(func_believe_me(a), 3); } |}]
null
https://raw.githubusercontent.com/tact-lang/tact-obsolete/35c56ecdc14ab80a86e03312f7812221376eade2/test/codegen_func.ml
ocaml
open Shared.Disabled module Config = Shared.DisabledConfig let%expect_test "simple function generation" = let source = {| fn test() -> Integer { return 0; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test() impure { return 0; } |}] let%expect_test "passing struct to a function" = let source = {| struct T { val b: Integer val c: struct { val d : Integer } } fn test(t: T) -> Integer { return 1; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int] t) impure { return 1; } |}] let%expect_test "function calls" = let source = {| fn test(value: Integer) -> Integer { return value; } fn test2(value: Integer) -> Integer { return test(value); } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int value) impure { return value; } int test2(int value) impure { return test(value); } |}] let%expect_test "Int[bits] serializer codegen" = let source = {| fn test_int(b: Builder) { let i = Int[32].new(100); i.serialize(b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } _ test_int(builder b) impure { int i = 100; return f1(100, b); } |}] let%expect_test "demo struct serializer" = let source = {| struct T { val a: Int[32] val b: Int[16] } let T_serializer = serializer[T]; fn test() { let b = Builder.new(); T_serializer(T{a: Int[32].new(0), b: Int[16].new(1)}, b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder f3(int self, builder builder_) impure { return f2(builder_, self, 16); } builder T_serializer([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); builder b = f3(get1(func_believe_me(self)), b); return b; } builder f4() impure { return builtin_begin_cell(); } _ test() impure { builder b = f4(); return T_serializer([0, 1], b); } |}] let%expect_test "demo struct serializer 2" = let source = {| struct Foo { val a: Int[32] val b: Int[16] } let serialize_foo = serializer[Foo]; fn test() -> Builder { let b = Builder.new(); return serialize_foo(Foo{a: Int[32].new(0), b: Int[16].new(1)}, b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder f3(int self, builder builder_) impure { return f2(builder_, self, 16); } builder serialize_foo([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); builder b = f3(get1(func_believe_me(self)), b); return b; } builder f4() impure { return builtin_begin_cell(); } builder test() impure { builder b = f4(); return serialize_foo([0, 1], b); } |}] let%expect_test "true and false" = let source = {| fn test(flag: Bool) { if (flag) { return false; } else { return true; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int flag) impure { if (flag) { return 0; } else { return -1; } } |}] let%expect_test "if/then/else" = let source = {| fn test(flag: Bool) { if (flag) { return 1; } else { return 2; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int flag) impure { if (flag) { return 1; } else { return 2; } } |}] let%expect_test "serializer inner struct" = let source = {| struct Pubkey { val x: Int[160] } struct Wallet { val seqno: Int[32] val pubkey: Pubkey } let serialize_wallet = serializer[Wallet]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f2(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f1(int self, builder builder_) impure { return f2(builder_, self, 32); } builder serialize_wallet([int, int] self, builder b) impure { builder b = f1(get0(func_believe_me(self)), b); return b; } |}] let%expect_test "unions" = let source = {| struct Empty{} union Uni { case Integer case Empty } fn try(x: Uni) -> Uni { x } fn test_try(x: Integer, y: Empty) { let test1 = try(x); let test2 = try(y); } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } tuple try(tuple x) impure { return x; } tuple f0(int v) impure { return func_believe_me([0, v]); } tuple f1([] v) impure { return func_believe_me([1, v]); } _ test_try(int x, [] y) impure { tuple test1 = try(f0(x)); tuple test2 = try(f1(y)); } |}] let%expect_test "switch statement" = let source = {| union Ints { case Int[32] case Int[64] } fn test(i: Ints) -> Integer { switch (i) { case Int[32] vax => { return 32; } case Int[64] vax => { return 64; } } } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } int test(tuple i) impure { { tuple temp = i; int discr = first(temp); { if (discr == 0) { int vax = second(temp); { return 32; } } else { if (discr == 1) { int vax = second(temp); { return 64; } } else { thrown(90); return func_believe_me([]); } } } } } |}] let%expect_test "tensor2" = let source = {| fn test() { let x = builtin_divmod(10, 2); return x.value1; } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } int test() impure { (int, int) x = builtin_divmod(10, 2); return tensor2_value1(x); } |}] let%expect_test "serialization api" = let source = {| struct Empty { impl Serialize { fn serialize(self: Self, b: Builder) -> Builder { return b; } } } fn test(m: MessageRelaxed[Empty]) { let b = Builder.new(); let b = m.serialize(b); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get3(tuple t) asm "3 INDEX"; forall A -> A get2(tuple t) asm "2 INDEX"; forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } builder f1() impure { return builtin_begin_cell(); } builder f4(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f9([] self, builder b) impure { return b; } builder f11(int self, builder builder_) impure { return f4(builder_, self, 9); } builder f10([int, int] self, builder b) impure { builder b = f11(get0(func_believe_me(self)), b); builder b = f4(b, get1(func_believe_me(self)), get0(func_believe_me(self))); return b; } builder f14(int self, builder builder_) impure { return f4(builder_, self, 8); } builder f15(int self, builder builder_) impure { return f4(builder_, self, 256); } builder f13([int, int] self, builder b) impure { builder b = f14(get0(func_believe_me(self)), b); builder b = f15(get1(func_believe_me(self)), b); return b; } builder f12([int, int] self, builder b) impure { builder b = f4(b, 0, 0); return f13(self, b); } builder f18(int self, builder builder_) impure { return f4(builder_, self, 32); } builder f17([int, int, int] self, builder b) impure { builder b = f11(get0(func_believe_me(self)), b); builder b = f18(get1(func_believe_me(self)), b); return b; } builder f16([int, int, int] self, builder b) impure { builder b = f4(b, 0, 0); builder b = f17(self, b); return b; } builder f8(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f16(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f12(varr, b); return b; } } else { if (discr == 1) { [int, int] varr = second(temp); { builder b = store_uint(b, 1, 2); builder b = f10(varr, b); return b; } } else { if (discr == 0) { [] varr = second(temp); { builder b = store_uint(b, 0, 2); builder b = f9(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } } } builder f7(tuple self, builder b) impure { return f8(self, b); } builder f20(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 1) { [int, int] varr = second(temp); { builder b = store_uint(b, 1, 2); builder b = f10(varr, b); return b; } } else { if (discr == 0) { [] varr = second(temp); { builder b = store_uint(b, 0, 2); builder b = f9(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f19(tuple self, builder b) impure { return f20(self, b); } builder f22(builder self, int uint, int bits) impure { return builtin_store_uint(self, uint, bits); } builder f21(int self, builder builder_) impure { return f22(builder_, self, 64); } builder f23(int self, builder builder_) impure { return f22(builder_, self, 32); } builder f6([tuple, tuple, int, int] self, builder b) impure { builder b = f7(get0(func_believe_me(self)), b); builder b = f19(get1(func_believe_me(self)), b); builder b = f21(get2(func_believe_me(self)), b); builder b = f23(get3(func_believe_me(self)), b); return b; } builder f5([tuple, tuple, int, int] self, builder b) impure { return f6(self, b); } builder f28(int self, builder builder_) impure { return f22(builder_, self, 1); } builder f27([int, int, int] self, builder b) impure { builder b = f28(get0(func_believe_me(self)), b); builder b = f28(get1(func_believe_me(self)), b); builder b = f28(get2(func_believe_me(self)), b); return b; } builder f26([int, int, int] self, builder b) impure { return f27(self, b); } builder f32(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f16(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f12(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f31(tuple self, builder b) impure { return f32(self, b); } builder f30([tuple, tuple] self, builder b) impure { builder b = f31(get0(func_believe_me(self)), b); builder b = f31(get1(func_believe_me(self)), b); return b; } builder f29([tuple, tuple] self, builder b) impure { return f30(self, b); } builder f36(builder self, int c) impure { return builtin_store_grams(self, c); } builder f35(int self, builder builder_) impure { return f36(builder_, self); } builder f34([int, int, int, int] self, builder b) impure { builder b = f35(get0(func_believe_me(self)), b); builder b = f28(get1(func_believe_me(self)), b); builder b = f35(get2(func_believe_me(self)), b); builder b = f35(get3(func_believe_me(self)), b); return b; } builder f33([int, int, int, int] self, builder b) impure { return f34(self, b); } builder f38([int, int] self, builder b) impure { builder b = f21(get0(func_believe_me(self)), b); builder b = f23(get1(func_believe_me(self)), b); return b; } builder f37([int, int] self, builder b) impure { return f38(self, b); } builder f25([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { builder b = f26(get0(func_believe_me(self)), b); builder b = f29(get1(func_believe_me(self)), b); builder b = f33(get2(func_believe_me(self)), b); builder b = f37(get3(func_believe_me(self)), b); return b; } builder f24([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { return f25(self, b); } builder f3(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 1) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] info = second(temp); { builder b = f4(b, 0, 1); return f24(info, b); } } else { if (discr == 0) { [tuple, tuple, int, int] info = second(temp); { builder b = f4(b, 3, 2); return f5(info, b); } } else { thrown(90); return func_believe_me([]); } } } } } builder f39([] self, builder b) impure { return b; } builder f2([tuple, []] self, builder b) impure { builder b = f3(get0(func_believe_me(self)), b); builder b = f4(b, 0, 1); builder b = f4(b, 0, 1); builder b = f39(get1(func_believe_me(self)), b); return b; } _ test([tuple, []] m) impure { builder b = f1(); builder b = f2(m, b); } |}] let%expect_test "deserialization api" = let source = {| struct Empty { impl Deserialize { fn deserialize(s: Slice) -> LoadResult[Self] { return LoadResult[Self].new(s, Self{}); } } } fn test(c: Cell) { let s = Slice.parse(c); let msg = Message[Empty].deserialize(s); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } slice f1(cell cell_) impure { return builtin_begin_parse(cell_); } [slice, int] f5(slice self, int bits) impure { (slice, int) output = builtin_load_uint(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f12(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f11(slice s) impure { [slice, int] res = f12(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] f10(slice slice_) impure { [slice slice_, int len] = f11(slice_); [slice slice_, int bits] = f12(slice_, len); return [slice_, [len, bits]]; } [slice, tuple] f13(tuple v, slice s) impure { return [s, v]; } [slice, []] f15([] v, slice s) impure { return [s, v]; } [slice, []] f14(slice s) impure { return f15(s, []); } [slice, tuple] f9(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, []] res = f14(get0(func_believe_me(res_discr))); return f13(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 1)) { [slice, [int, int]] res = f10(get0(func_believe_me(res_discr))); return f13(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f8(slice s) impure { return f9(s); } [slice, int] f19(slice s) impure { [slice, int] res = f12(s, 32); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int, int]] f20([int, int, int] v, slice s) impure { return [s, v]; } int f21(int left, int right) impure { return builtin_eq(left, right); } [slice, [int, int, int]] f18(slice s) impure { [slice slice_, int anycast] = f12(s, 1); if (f21(anycast, 0)) { [slice slice_, int len] = f11(slice_); [slice slice_, int workchain_id] = f19(slice_); [slice slice_, int address] = f12(slice_, len); return f20(slice_, [len, workchain_id, address]); } else { thrown(0); } } [slice, tuple] f22(tuple v, slice s) impure { return [s, v]; } [slice, int] f25(slice s) impure { [slice, int] res = f12(s, 8); [slice slice_, int value] = res; return [slice_, value]; } [slice, int] f26(slice s) impure { [slice, int] res = f12(s, 256); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] f24(slice slice_) impure { [slice slice_, int workchain_id] = f25(slice_); [slice slice_, int address] = f26(slice_); return [slice_, [workchain_id, address]]; } [slice, [int, int]] f23(slice s) impure { [slice, int] res_anycast = f12(s, 1); if (f21(get1(func_believe_me(res_anycast)), 0)) { return f24(s); } else { thrown(0); } } [slice, tuple] f17(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 2)) { [slice, [int, int]] res = f23(get0(func_believe_me(res_discr))); return f22(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 3)) { [slice, [int, int, int]] res = f18(get0(func_believe_me(res_discr))); return f22(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f16(slice s) impure { return f17(s); } [slice, int] f28(slice self) impure { (slice, int) output = builtin_load_grams(self); slice slice_ = tensor2_value1(output); int coins = tensor2_value2(output); return [believe_me(slice_), coins]; } [slice, int] f29(int v, slice s) impure { return [s, v]; } [slice, int] f27(slice s) impure { [slice slice_, int value] = f28(s); return f29(value, slice_); } [slice, [tuple, tuple, int]] f7(slice slice_) impure { [slice slice_, tuple src] = f8(slice_); [slice slice_, tuple dest] = f16(slice_); [slice slice_, int import_fee] = f27(slice_); return [slice_, [src, dest, import_fee]]; } [slice, [tuple, tuple, int]] f6(slice s) impure { return f7(s); } [slice, tuple] f30(tuple v, slice s) impure { return [s, v]; } [slice, int] f35(slice s) impure { [slice, int] res = f5(s, 1); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, [int, int, int]] f34(slice slice_) impure { [slice slice_, int ihr_disabled] = f35(slice_); [slice slice_, int bounce] = f35(slice_); [slice slice_, int bounced] = f35(slice_); return [slice_, [ihr_disabled, bounce, bounced]]; } [slice, [int, int, int]] f33(slice s) impure { return f34(s); } [slice, [tuple, tuple]] f37(slice slice_) impure { [slice slice_, tuple src] = f16(slice_); [slice slice_, tuple dst] = f16(slice_); return [slice_, [src, dst]]; } [slice, [tuple, tuple]] f36(slice s) impure { return f37(s); } [slice, [int, int, int, int]] f39(slice slice_) impure { [slice slice_, int amount] = f27(slice_); [slice slice_, int _extra_currencies] = f35(slice_); [slice slice_, int ihr_fee] = f27(slice_); [slice slice_, int fwd_fee] = f27(slice_); return [slice_, [amount, _extra_currencies, ihr_fee, fwd_fee]]; } [slice, [int, int, int, int]] f38(slice s) impure { return f39(s); } [slice, int] f42(slice s) impure { [slice, int] res = f5(s, 64); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, int] f43(slice s) impure { [slice, int] res = f5(s, 32); return [get0(func_believe_me(res)), get1(func_believe_me(res))]; } [slice, [int, int]] f41(slice slice_) impure { [slice slice_, int created_lt] = f42(slice_); [slice slice_, int created_at] = f43(slice_); return [slice_, [created_lt, created_at]]; } [slice, [int, int]] f40(slice s) impure { return f41(s); } [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] f32(slice slice_) impure { [slice slice_, [int, int, int] flags] = f33(slice_); [slice slice_, [tuple, tuple] addresses] = f36(slice_); [slice slice_, [int, int, int, int] coins] = f38(slice_); [slice slice_, [int, int] timestamps] = f40(slice_); return [slice_, [flags, addresses, coins, timestamps]]; } [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] f31(slice s) impure { return f32(s); } [slice, tuple] f4(slice slice_) impure { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]]] res = f31(get0(func_believe_me(res_discr))); return f30(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f5(slice_, 2); if (builtin_eq(get1(func_believe_me(res_discr)), 2)) { [slice, [tuple, tuple, int]] res = f6(get0(func_believe_me(res_discr))); return f30(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } [slice, tuple] f3(slice s) impure { return f4(s); } [slice, []] f45([] v, slice s) impure { return [s, v]; } [slice, []] f44(slice s) impure { return f45(s, []); } [slice, [tuple, []]] f46([tuple, []] v, slice s) impure { return [s, v]; } [slice, [tuple, []]] f2(slice s) impure { [slice slice_, tuple info] = f3(s); [slice slice_, int init] = f12(slice_, 1); if (f21(init, 0)) { [slice slice_, int discr] = f12(slice_, 1); if (f21(discr, 0)) { [slice slice_, [] body] = f44(slice_); [tuple, _] mes = [info, believe_me(body)]; return f46(mes, slice_); } else { thrown(0); } } else { thrown(0); } } _ test(cell c) impure { slice s = f1(c); [slice, [tuple, []]] msg = f2(s); } |}] let%expect_test "destructuring let" = let source = {| struct T { val x: Integer val y: Integer val z: Integer } fn test(t: T) -> Integer { let {x, y as y2, z} = t; y2 } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int, int] t) impure { [int x, int y2, int z] = t; return y2; } |}] let%expect_test "destructuring let with rest ignored" = let source = {| struct T { val x: Integer val y: Integer val z: Integer } fn test(t: T) -> Integer { let {y as y2, ..} = t; y2 } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test([int, int, int] t) impure { [_, int y2, _] = t; return y2; } |}] let%expect_test "deserializer" = let source = {| struct Something { val value1: Int[9] val value2: Int[256] } let test = deserializer[Something]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [slice, int] f2(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f1(slice s) impure { [slice, int] res = f2(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, int] f3(slice s) impure { [slice, int] res = f2(s, 256); [slice slice_, int value] = res; return [slice_, value]; } [slice, [int, int]] test(slice slice_) impure { [slice slice_, int value1] = f1(slice_); [slice slice_, int value2] = f3(slice_); return [slice_, [value1, value2]]; } |}] let%expect_test "deserializer unions" = let source = {| union TestUnion { case Int[8] case Int[9] } let deserialize_union = deserializer[TestUnion]; |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [slice, int] f1(slice self, int bits) impure { (slice, int) output = builtin_load_uint(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f3(slice self, int bits) impure { (slice, int) output = builtin_load_int(self, bits); slice slice_ = tensor2_value1(output); int int_ = tensor2_value2(output); return [believe_me(slice_), int_]; } [slice, int] f2(slice s) impure { [slice, int] res = f3(s, 9); [slice slice_, int value] = res; return [slice_, value]; } [slice, tuple] f4(tuple v, slice s) impure { return [s, v]; } [slice, int] f5(slice s) impure { [slice, int] res = f3(s, 8); [slice slice_, int value] = res; return [slice_, value]; } [slice, tuple] deserialize_union(slice slice_) impure { [slice, int] res_discr = f1(slice_, 1); if (builtin_eq(get1(func_believe_me(res_discr)), 0)) { [slice, int] res = f5(get0(func_believe_me(res_discr))); return f4(get0(func_believe_me(res)), get1(func_believe_me(res))); } else { [slice, int] res_discr = f1(slice_, 1); if (builtin_eq(get1(func_believe_me(res_discr)), 1)) { [slice, int] res = f2(get0(func_believe_me(res_discr))); return f4(get0(func_believe_me(res)), get1(func_believe_me(res))); } else throw(0); } } |}] let%expect_test "assignment" = let source = {| fn test(x: Integer) { let a = 1; a = x; a } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int x) impure { int a = 1; a = x; return a; } |}] let%expect_test "assignment with condition block" = let source = {| fn test(x: Int[257]) { let a = 1; if (true) { a = 10; } else { a = 20; } return a; } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } int test(int x) impure { int a = 1; if (-1) { a = 10; } else { a = 20; } return a; } |}] let%expect_test "codegen while block" = let source = {| fn test() { let a = 10; while (true) { a = 20; } } |} in pp_codegen source ~strip_defaults:true ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } _ test() impure { int a = 10; while (-1) { a = 20; } } |}] let%expect_test "request builder" = let source = {| struct EmptyMsg { @derive impl Serialize {} } fn test_req_builder() { let b = RequestBuilder[EmptyMsg].new() .can_be_bounced() .ihr_disabled() .money(Coins.new(1)) .body(EmptyMsg{}) .send_to(AddressStd.new(0, 0)); } |} in pp_codegen source ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall A -> A get4(tuple t) asm "4 INDEX"; forall A -> A get3(tuple t) asm "3 INDEX"; forall A -> A get2(tuple t) asm "2 INDEX"; forall A -> A get1(tuple t) asm "1 INDEX"; forall A -> A get0(tuple t) asm "0 INDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ thrown(int n) impure { return builtin_throw(n); } _ send_raw_msg(cell msg, int flags) impure { return builtin_send_raw_message(msg, flags); } int f0(int i) impure { return i; } int hash_of_slice(slice s) impure { return f0(builtin_slice_hash(s)); } int is_signature_valid(int hash, slice sign, int pubkey) impure { return builtin_check_signature(hash, sign, pubkey); } [[int, int, int], int, [int, int, int, int], int, []] f1() impure { return [[0, 0, 0], 0, [0, 0, 0, 0], 0, believe_me(0)]; } [[int, int, int], int, [int, int, int, int], int, []] f2([[int, int, int], int, [int, int, int, int], int, []] self) impure { return [[get0(func_believe_me(get0(func_believe_me(self)))), 1, 0], get1(func_believe_me(self)), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } [[int, int, int], int, [int, int, int, int], int, []] f3([[int, int, int], int, [int, int, int, int], int, []] self) impure { return [[1, get1(func_believe_me(get0(func_believe_me(self)))), 0], get1(func_believe_me(self)), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } int f6(int left, int right) impure { return builtin_add(left, right); } int f7(int i) impure { return i; } int f5(int self) impure { return f7(f6(self, 64)); } int f8(int self) impure { return f7(f6(self, 128)); } [int, int, int, int] f9(int amount, int ihr_fee, int fwd_fee) impure { return [amount, 0, ihr_fee, fwd_fee]; } [[int, int, int], int, [int, int, int, int], int, []] f4([[int, int, int], int, [int, int, int, int], int, []] self, tuple money) impure { { tuple temp = money; int discr = first(temp); { if (discr == 0) { int coins = second(temp); { return [get0(func_believe_me(self)), get1(func_believe_me(self)), f9(coins, get2(func_believe_me(get2(func_believe_me(self)))), get3(func_believe_me(get2(func_believe_me(self))))), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { if (discr == 1) { [] _ = second(temp); { return [get0(func_believe_me(self)), f8(get1(func_believe_me(self))), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { if (discr == 2) { [] _ = second(temp); { return [get0(func_believe_me(self)), f5(get1(func_believe_me(self))), get2(func_believe_me(self)), get3(func_believe_me(self)), get4(func_believe_me(self))]; } } else { thrown(90); return func_believe_me([]); } } } } } } [[int, int, int], int, [int, int, int, int], int, []] f10([[int, int, int], int, [int, int, int, int], int, []] self, [] body) impure { return [get0(func_believe_me(self)), get1(func_believe_me(self)), get2(func_believe_me(self)), -1, body]; } [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] f12([int, int, int] flags, tuple dst, [int, int, int, int] coins) impure { return [flags, [func_believe_me([2, [0, 0]]), dst], coins, [0, 0]]; } tuple f13([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] v) impure { return func_believe_me([0, v]); } builder f14() impure { return builtin_begin_cell(); } builder f22(builder self, int uint, int bits) impure { return builtin_store_uint(self, uint, bits); } builder f21(int self, builder builder_) impure { return f22(builder_, self, 1); } builder f20([int, int, int] self, builder b) impure { builder b = f21(get0(func_believe_me(self)), b); builder b = f21(get1(func_believe_me(self)), b); builder b = f21(get2(func_believe_me(self)), b); return b; } builder f19([int, int, int] self, builder b) impure { return f20(self, b); } builder f28(builder self, int int_, int bits) impure { return builtin_store_int(self, int_, bits); } builder f30(int self, builder builder_) impure { return f28(builder_, self, 8); } builder f31(int self, builder builder_) impure { return f28(builder_, self, 256); } builder f29([int, int] self, builder b) impure { builder b = f30(get0(func_believe_me(self)), b); builder b = f31(get1(func_believe_me(self)), b); return b; } builder f27([int, int] self, builder b) impure { builder b = f28(b, 0, 0); return f29(self, b); } builder f34(int self, builder builder_) impure { return f28(builder_, self, 9); } builder f35(int self, builder builder_) impure { return f28(builder_, self, 32); } builder f33([int, int, int] self, builder b) impure { builder b = f34(get0(func_believe_me(self)), b); builder b = f35(get1(func_believe_me(self)), b); return b; } builder f32([int, int, int] self, builder b) impure { builder b = f28(b, 0, 0); builder b = f33(self, b); return b; } builder f26(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 3) { [int, int, int] varr = second(temp); { builder b = store_uint(b, 3, 2); builder b = f32(varr, b); return b; } } else { if (discr == 2) { [int, int] varr = second(temp); { builder b = store_uint(b, 2, 2); builder b = f27(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } } builder f25(tuple self, builder b) impure { return f26(self, b); } builder f24([tuple, tuple] self, builder b) impure { builder b = f25(get0(func_believe_me(self)), b); builder b = f25(get1(func_believe_me(self)), b); return b; } builder f23([tuple, tuple] self, builder b) impure { return f24(self, b); } builder f39(builder self, int c) impure { return builtin_store_grams(self, c); } builder f38(int self, builder builder_) impure { return f39(builder_, self); } builder f37([int, int, int, int] self, builder b) impure { builder b = f38(get0(func_believe_me(self)), b); builder b = f21(get1(func_believe_me(self)), b); builder b = f38(get2(func_believe_me(self)), b); builder b = f38(get3(func_believe_me(self)), b); return b; } builder f36([int, int, int, int] self, builder b) impure { return f37(self, b); } builder f42(int self, builder builder_) impure { return f22(builder_, self, 64); } builder f43(int self, builder builder_) impure { return f22(builder_, self, 32); } builder f41([int, int] self, builder b) impure { builder b = f42(get0(func_believe_me(self)), b); builder b = f43(get1(func_believe_me(self)), b); return b; } builder f40([int, int] self, builder b) impure { return f41(self, b); } builder f18([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { builder b = f19(get0(func_believe_me(self)), b); builder b = f23(get1(func_believe_me(self)), b); builder b = f36(get2(func_believe_me(self)), b); builder b = f40(get3(func_believe_me(self)), b); return b; } builder f17([[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] self, builder b) impure { return f18(self, b); } builder f16(tuple self, builder b) impure { { tuple temp = self; int discr = first(temp); { if (discr == 0) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] varr = second(temp); { builder b = store_uint(b, 0, 1); builder b = f17(varr, b); return b; } } else { thrown(90); return func_believe_me([]); } } } } builder f15(tuple self, builder b) impure { return f16(self, b); } builder f45([] self, builder b) impure { return b; } builder f44([] self, builder b) impure { return f45(self, b); } cell f46(builder self) impure { return builtin_end_cell(self); } _ f11([[int, int, int], int, [int, int, int, int], int, []] self, tuple dst) impure { if (get3(func_believe_me(self))) { [[int, int, int], [tuple, tuple], [int, int, int, int], [int, int]] info = f12(get0(func_believe_me(self)), dst, get2(func_believe_me(self))); builder b = f15(f13(info), f14()); builder b = f28(b, 0, 1); builder b = f28(b, 0, 1); builder b = f44(get4(func_believe_me(self)), b); send_raw_msg(f46(b), get1(func_believe_me(self))); } else { thrown(87); } } _ test_req_builder() impure { _ b = f11(f10(f4(f3(f2(f1())), func_believe_me([0, 1])), []), func_believe_me([2, [0, 0]])); } |}] let%expect_test "field assignment" = let source = {| struct Test { val field1: Integer val field2: Integer } fn test() { let a = Test { field1: 0, field2: 1 }; a.field1 = 2; a.field2 = 3; } |} in pp_codegen source ~include_std:false ; [%expect {| forall Value1, Value2 -> Value1 tensor2_value1((Value1, Value2) tensor) { (Value1 value, _) = tensor; return value; } forall Value1, Value2 -> Value2 tensor2_value2((Value1, Value2) tensor) { (_, Value2 value) = tensor; return value; } forall A, B -> B func_believe_me(A i) asm "NOP"; int func_bit_not(int a) { return ~ a; } forall F, T -> T update1(tuple t, F elem) asm "1 SETINDEX"; forall F, T -> T update0(tuple t, F elem) asm "0 SETINDEX"; int builtin_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_gt(int i1, int i2) impure { return _>_(i1, i2); } int builtin_geq(int i1, int i2) impure { return _>=_(i1, i2); } int builtin_lt(int i1, int i2) impure { return _<_(i1, i2); } int builtin_leq(int i1, int i2) impure { return _<=_(i1, i2); } int builtin_neq(int i1, int i2) impure { return _!=_(i1, i2); } int builtin_eq(int i1, int i2) impure { return _==_(i1, i2); } int builtin_bit_or(int i1, int i2) impure { return _|_(i1, i2); } int builtin_bit_and(int i1, int i2) impure { return _&_(i1, i2); } int builtin_div(int i1, int i2) impure { return _/_(i1, i2); } int builtin_mul(int i1, int i2) impure { return _*_(i1, i2); } int builtin_sub(int i1, int i2) impure { return _-_(i1, i2); } int builtin_add(int i1, int i2) impure { return _+_(i1, i2); } int builtin_not(int c) impure { return func_bit_not(c); } forall A, B -> B believe_me(A i) asm "NOP"; _ builtin_accept_message() impure { return accept_message(); } int builtin_slice_hash(slice s) impure { return slice_hash(s); } int builtin_check_signature(int h, slice s, int k) impure { return check_signature(h, s, k); } int builtin_block_lt() impure { return block_lt(); } int builtin_cur_lt() impure { return cur_lt(); } _ builtin_get_balance() impure { return get_balance(); } slice builtin_my_address() impure { return my_address(); } int builtin_now() impure { return now(); } _ builtin_set_data(cell d) impure { return set_data(d); } cell builtin_get_data() impure { return get_data(); } _ builtin_throw(int e) impure { return throw(e); } _ builtin_send_raw_message(cell c, int f) impure { return send_raw_message(c, f); } (int, int) builtin_divmod(int i1, int i2) impure { return divmod(i1, i2); } _ builtin_end_parse(slice s) impure { return end_parse(s); } int builtin_slice_bits(slice s) impure { return slice_bits(s); } int builtin_slice_refs(slice s) impure { return slice_refs(s); } slice builtin_slice_last(slice s, int l) impure { return slice_last(s, l); } (slice, cell) builtin_load_ref(slice s) impure { return load_ref(s); } (slice, int) builtin_load_grams(slice s) impure { return load_grams(s); } (slice, slice) builtin_load_bits(slice s, int bs) impure { return load_bits(s, bs); } (slice, int) builtin_load_uint(slice s, int bs) impure { return load_uint(s, bs); } (slice, int) builtin_load_int(slice s, int bs) impure { return load_int(s, bs); } slice builtin_begin_parse(cell c) impure { return begin_parse(c); } int builtin_builder_depth(builder b) impure { return builder_depth(b); } int builtin_builder_refs(builder b) impure { return builder_refs(b); } int builtin_builder_bits(builder b) impure { return builder_bits(b); } builder builtin_store_maybe_ref(builder b, cell c) impure { return store_maybe_ref(b, c); } builder builtin_store_slice(builder b, slice s) impure { return store_slice(b, s); } builder builtin_store_ref(builder b, cell c) impure { return store_ref(b, c); } builder builtin_store_grams(builder b, int c) impure { return store_grams(b, c); } builder builtin_store_uint(builder b, int i, int bs) impure { return store_uint(b, i, bs); } builder builtin_store_int(builder b, int i, int bs) impure { return store_int(b, i, bs); } cell builtin_end_cell(builder b) impure { return end_cell(b); } builder builtin_begin_cell() impure { return begin_cell(); } _ test() impure { [int, int] a = [0, 1]; a = update0(func_believe_me(a), 2); a = update1(func_believe_me(a), 3); } |}]
d55b18cdc35648aeeaedbb22767ef349533968b173452dcfcc1c466d6b765a7e
symbiont-io/detsys-testkit
Log.hs
# LANGUAGE DerivingStrategies # # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module StuntDouble.Log where import Control.Monad (forM) import Data.Aeson import qualified Data.Aeson.Text as AesonText import Data.Aeson.Encoding ( encodingToLazyByteString , list , pair , pairs , text , unsafeToEncoding ) import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Binary.Builder (fromLazyByteString) import Data.Char (toLower) import qualified Data.Text.Lazy as Text import Data.Traversable (fmapDefault, foldMapDefault) import Control.Exception import GHC.Generics (Generic) import StuntDouble.Codec import StuntDouble.Message import StuntDouble.Reference import StuntDouble.Time import StuntDouble.LogicalTime ------------------------------------------------------------------------ newtype Log = Log [Timestamped LogEntry] deriving stock (Show, Read) deriving newtype (FromJSON) data Timestamped' lt a = Timestamped { tsContent :: a , tsLogicalTime :: lt , tsTime :: Time } deriving stock (Show, Read, Generic) type Timestamped = Timestamped' LogicalTime instance Functor (Timestamped' lt) where fmap = fmapDefault instance Foldable (Timestamped' lt) where foldMap = foldMapDefault instance Traversable (Timestamped' lt) where traverse f (Timestamped a b c) = (\x -> Timestamped x b c) <$> f a tsAesonOptions = defaultOptions { fieldLabelModifier = \s -> case drop (length ("ts" :: String)) s of (x : xs) -> toLower x : xs [] -> error "impossible, unless the field names of `Timestamped` changed" } instance (FromJSON lt, FromJSON a) => FromJSON (Timestamped' lt a) where parseJSON = genericParseJSON tsAesonOptions data TimestampedLogically a = TimestampedLogically a LogicalTimeInt deriving stock (Show, Read) data LogEntry' msg = LogSend { leLocalRef :: LocalRef , leRemoteRef :: RemoteRef , leMessage :: msg } | LogResumeContinuation { leRemoteRef :: RemoteRef , leLocalRef :: LocalRef , leMessage :: msg } deriving stock (Show, Read, Generic) type LogEntry = LogEntry' Message instance Functor LogEntry' where fmap = fmapDefault instance Foldable LogEntry' where foldMap = foldMapDefault instance Traversable LogEntry' where traverse f (LogSend a b c) = (\x -> LogSend a b x) <$> f c traverse f (LogResumeContinuation a b c) = (\x -> LogResumeContinuation a b x) <$> f c leAesonOptions = defaultOptions { fieldLabelModifier = \s -> case drop (length ("le" :: String)) s of (x : xs) -> toLower x : xs [] -> error "impossible, unless the field names of `LogEntry` changed" , sumEncoding = defaultTaggedObject { tagFieldName = "tag" } } instance FromJSON m => FromJSON (LogEntry' m) where parseJSON = genericParseJSON leAesonOptions = Spawned LocalRef | Turn TurnData | ClientRequestEntry | ClientResponseEntry | ErrorLogEntry SomeException data TurnData = TurnData { tdActor : : LocalRef , tdBeforeState : : String -- XXX : State , tdMessage : : Message , tdActions : : [ ActionLogEntry ] , tdLogs : : [ LogLines ] , tdAfterState : : String -- XXX : State , tdLogicalTime : : , tdSimulatedTime : : Int -- XXX : UTCTime , tdReply : : Message } data ActionLogEntry = XXX data LogLines = YYY = Spawned LocalRef | Turn TurnData | ClientRequestEntry | ClientResponseEntry | ErrorLogEntry SomeException data TurnData = TurnData { tdActor :: LocalRef , tdBeforeState :: String -- XXX: State , tdMessage :: Message , tdActions :: [ActionLogEntry] , tdLogs :: [LogLines] , tdAfterState :: String -- XXX: State , tdLogicalTime :: Int , tdSimulatedTime :: Int -- XXX: UTCTime , tdReply :: Message } data ActionLogEntry = XXX data LogLines = YYY -} emptyLog :: Log emptyLog = Log [] appendLog :: LogEntry -> LogicalTime -> Time -> Log -> Log appendLog e lt t (Log es) = Log (Timestamped e lt t : es) -- XXX: Use more efficient data structure to avoid having to reverse. -- AdminTransport wants the messages to be `String`, otherwise we could probably skip -- some translation here getLog :: Codec -> Log -> String getLog (Codec enc _) (Log es) = LBS.unpack $ encodingToLazyByteString f where f = flip list (reverse es) $ \(Timestamped x (LogicalTime _ lt) t) -> pairs ( (pair "content" $ pairs ((pair "tag" (case x of LogSend {} -> text "LogSend" LogResumeContinuation{} -> text "LogResumeContinuation")) <> "localRef" .= leLocalRef x <> "remoteRef" .= leRemoteRef x <> (pair "message" (unsafeToEncoding (fromLazyByteString (enc (leMessage x))))) )) <> "logicalTime" .= lt <> "time" .= t ) parseLog :: NodeName -> Codec -> ByteString -> Either String Log parseLog nn (Codec _ dec) s = do xs :: [Timestamped' LogicalTimeInt (LogEntry' Value)] <- eitherDecode s xs' <- forM xs $ \t -> forM t $ \le -> forM le $ \m -> dec (encode m) pure . Log $ fmap (\ (Timestamped x lt t) -> Timestamped x (LogicalTime nn lt) t) xs' -- Assumes the logs are already sorted merge :: Log -> Log -> Log merge (Log es) (Log es') = Log (go es es') where lt :: Timestamped a -> LogicalTime lt (Timestamped _ l _) = l go :: [Timestamped a] -> [Timestamped a] -> [Timestamped a] go [] es' = es' go es [] = es go es@(x:xs) es'@(y:ys) | HappenedBeforeOrConcurrently <- relation (lt x) (lt y) = x : go xs es' | otherwise = y : go es ys type EventLog = [ LogEntry ] data LogEntry = LogInvoke RemoteRef LocalRef Message Message EventLoopName | LogSendStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogSendFinish Message EventLoopName | LogRequest RemoteRef RemoteRef Message Message EventLoopName | LogReceive RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestFinish CorrelationId Message EventLoopName | LogComment String EventLoopName | EventLoopName deriving ( Eq , Show ) isComment : : LogEntry - > Bool { } = True isComment _ otherwise = False type EventLog = [LogEntry] data LogEntry = LogInvoke RemoteRef LocalRef Message Message EventLoopName | LogSendStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogSendFinish CorrelationId Message EventLoopName | LogRequest RemoteRef RemoteRef Message Message EventLoopName | LogReceive RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestFinish CorrelationId Message EventLoopName | LogComment String EventLoopName | LogAsyncIOFinish CorrelationId IOResult EventLoopName deriving (Eq, Show) isComment :: LogEntry -> Bool isComment LogComment {} = True isComment _otherwise = False -}
null
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/29a3a0140730420e4c5cc8db23df6fdb03f9302c/src/runtime-prototype/src/StuntDouble/Log.hs
haskell
# LANGUAGE OverloadedStrings # ---------------------------------------------------------------------- XXX : State XXX : State XXX : UTCTime XXX: State XXX: State XXX: UTCTime XXX: Use more efficient data structure to avoid having to reverse. AdminTransport wants the messages to be `String`, otherwise we could probably skip some translation here Assumes the logs are already sorted
# LANGUAGE DerivingStrategies # # LANGUAGE DeriveGeneric # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module StuntDouble.Log where import Control.Monad (forM) import Data.Aeson import qualified Data.Aeson.Text as AesonText import Data.Aeson.Encoding ( encodingToLazyByteString , list , pair , pairs , text , unsafeToEncoding ) import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Binary.Builder (fromLazyByteString) import Data.Char (toLower) import qualified Data.Text.Lazy as Text import Data.Traversable (fmapDefault, foldMapDefault) import Control.Exception import GHC.Generics (Generic) import StuntDouble.Codec import StuntDouble.Message import StuntDouble.Reference import StuntDouble.Time import StuntDouble.LogicalTime newtype Log = Log [Timestamped LogEntry] deriving stock (Show, Read) deriving newtype (FromJSON) data Timestamped' lt a = Timestamped { tsContent :: a , tsLogicalTime :: lt , tsTime :: Time } deriving stock (Show, Read, Generic) type Timestamped = Timestamped' LogicalTime instance Functor (Timestamped' lt) where fmap = fmapDefault instance Foldable (Timestamped' lt) where foldMap = foldMapDefault instance Traversable (Timestamped' lt) where traverse f (Timestamped a b c) = (\x -> Timestamped x b c) <$> f a tsAesonOptions = defaultOptions { fieldLabelModifier = \s -> case drop (length ("ts" :: String)) s of (x : xs) -> toLower x : xs [] -> error "impossible, unless the field names of `Timestamped` changed" } instance (FromJSON lt, FromJSON a) => FromJSON (Timestamped' lt a) where parseJSON = genericParseJSON tsAesonOptions data TimestampedLogically a = TimestampedLogically a LogicalTimeInt deriving stock (Show, Read) data LogEntry' msg = LogSend { leLocalRef :: LocalRef , leRemoteRef :: RemoteRef , leMessage :: msg } | LogResumeContinuation { leRemoteRef :: RemoteRef , leLocalRef :: LocalRef , leMessage :: msg } deriving stock (Show, Read, Generic) type LogEntry = LogEntry' Message instance Functor LogEntry' where fmap = fmapDefault instance Foldable LogEntry' where foldMap = foldMapDefault instance Traversable LogEntry' where traverse f (LogSend a b c) = (\x -> LogSend a b x) <$> f c traverse f (LogResumeContinuation a b c) = (\x -> LogResumeContinuation a b x) <$> f c leAesonOptions = defaultOptions { fieldLabelModifier = \s -> case drop (length ("le" :: String)) s of (x : xs) -> toLower x : xs [] -> error "impossible, unless the field names of `LogEntry` changed" , sumEncoding = defaultTaggedObject { tagFieldName = "tag" } } instance FromJSON m => FromJSON (LogEntry' m) where parseJSON = genericParseJSON leAesonOptions = Spawned LocalRef | Turn TurnData | ClientRequestEntry | ClientResponseEntry | ErrorLogEntry SomeException data TurnData = TurnData { tdActor : : LocalRef , tdMessage : : Message , tdActions : : [ ActionLogEntry ] , tdLogs : : [ LogLines ] , tdReply : : Message } data ActionLogEntry = XXX data LogLines = YYY = Spawned LocalRef | Turn TurnData | ClientRequestEntry | ClientResponseEntry | ErrorLogEntry SomeException data TurnData = TurnData { tdActor :: LocalRef , tdMessage :: Message , tdActions :: [ActionLogEntry] , tdLogs :: [LogLines] , tdLogicalTime :: Int , tdReply :: Message } data ActionLogEntry = XXX data LogLines = YYY -} emptyLog :: Log emptyLog = Log [] appendLog :: LogEntry -> LogicalTime -> Time -> Log -> Log appendLog e lt t (Log es) = Log (Timestamped e lt t : es) getLog :: Codec -> Log -> String getLog (Codec enc _) (Log es) = LBS.unpack $ encodingToLazyByteString f where f = flip list (reverse es) $ \(Timestamped x (LogicalTime _ lt) t) -> pairs ( (pair "content" $ pairs ((pair "tag" (case x of LogSend {} -> text "LogSend" LogResumeContinuation{} -> text "LogResumeContinuation")) <> "localRef" .= leLocalRef x <> "remoteRef" .= leRemoteRef x <> (pair "message" (unsafeToEncoding (fromLazyByteString (enc (leMessage x))))) )) <> "logicalTime" .= lt <> "time" .= t ) parseLog :: NodeName -> Codec -> ByteString -> Either String Log parseLog nn (Codec _ dec) s = do xs :: [Timestamped' LogicalTimeInt (LogEntry' Value)] <- eitherDecode s xs' <- forM xs $ \t -> forM t $ \le -> forM le $ \m -> dec (encode m) pure . Log $ fmap (\ (Timestamped x lt t) -> Timestamped x (LogicalTime nn lt) t) xs' merge :: Log -> Log -> Log merge (Log es) (Log es') = Log (go es es') where lt :: Timestamped a -> LogicalTime lt (Timestamped _ l _) = l go :: [Timestamped a] -> [Timestamped a] -> [Timestamped a] go [] es' = es' go es [] = es go es@(x:xs) es'@(y:ys) | HappenedBeforeOrConcurrently <- relation (lt x) (lt y) = x : go xs es' | otherwise = y : go es ys type EventLog = [ LogEntry ] data LogEntry = LogInvoke RemoteRef LocalRef Message Message EventLoopName | LogSendStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogSendFinish Message EventLoopName | LogRequest RemoteRef RemoteRef Message Message EventLoopName | LogReceive RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestFinish CorrelationId Message EventLoopName | LogComment String EventLoopName | EventLoopName deriving ( Eq , Show ) isComment : : LogEntry - > Bool { } = True isComment _ otherwise = False type EventLog = [LogEntry] data LogEntry = LogInvoke RemoteRef LocalRef Message Message EventLoopName | LogSendStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogSendFinish CorrelationId Message EventLoopName | LogRequest RemoteRef RemoteRef Message Message EventLoopName | LogReceive RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestStart RemoteRef RemoteRef Message CorrelationId EventLoopName | LogRequestFinish CorrelationId Message EventLoopName | LogComment String EventLoopName | LogAsyncIOFinish CorrelationId IOResult EventLoopName deriving (Eq, Show) isComment :: LogEntry -> Bool isComment LogComment {} = True isComment _otherwise = False -}
6edfb353939006e2b69eb3930176054f2ed41d0e875c59b034abb0ff10fb64b8
rm-hull/inkspot
palette.clj
(ns inkspot.palette (:require [inkspot.color :as color]) (:import (java.awt Color Graphics2D GraphicsEnvironment RenderingHints) (java.awt.image BufferedImage) (java.io StringWriter) (org.apache.batik.dom GenericDOMImplementation) (org.apache.batik.svggen SVGGraphics2D))) (defprotocol IGraphics2DTarget (create-context [this width height]) (close [this])) (defn- ^BufferedImage create-image [w h] (if (GraphicsEnvironment/isHeadless) (BufferedImage. w h BufferedImage/TYPE_INT_ARGB) (.createCompatibleImage (.getDefaultConfiguration (.getDefaultScreenDevice (GraphicsEnvironment/getLocalGraphicsEnvironment))) w h))) (defn- ^Graphics2D create-graphics [^BufferedImage img] (let [g2d (.createGraphics img)] (doto g2d (.setRenderingHint RenderingHints/KEY_STROKE_CONTROL RenderingHints/VALUE_STROKE_NORMALIZE) (.setRenderingHint RenderingHints/KEY_ANTIALIASING RenderingHints/VALUE_ANTIALIAS_ON) (.setRenderingHint RenderingHints/KEY_RENDERING RenderingHints/VALUE_RENDER_QUALITY)) g2d)) (defn- draw-cell [^Graphics2D g2d x y w h color] (doto g2d (.setColor color) (.fillRect x y w h)) g2d) (defn draw [color-swatch & {:keys [g2d-target cell-width cell-height cells-per-row border]}] (let [cell-width (or cell-width 10) cell-height (or cell-height cell-width) cells-per-row (or cells-per-row 48) num-cells (count color-swatch) width (* cell-width cells-per-row) height (* cell-height (Math/ceil (/ num-cells cells-per-row))) pos (fn [i] [(* cell-width (mod i cells-per-row)) (* cell-height (quot i cells-per-row))]) generator (->> (iterate inc 0) (map pos) (map cons color-swatch)) target (g2d-target) g2d (create-context target width height)] (doto g2d (.setBackground Color/WHITE) (.clearRect 0 0 width height)) (let [w (- cell-width (or border 1)) h (- cell-height (or border 1))] (doseq [[c x y] generator] (draw-cell g2d x y w h (color/coerce c)))) (close target))) (defn bitmap [] (let [img (atom nil)] (reify IGraphics2DTarget (create-context [this width height] (reset! img (create-image width height)) (create-graphics @img)) (close [this] @img)))) (defn svg [] (let [dom-impl (GenericDOMImplementation/getDOMImplementation) document (.createDocument dom-impl nil "svg" nil) svg-generator (SVGGraphics2D. document)] (reify IGraphics2DTarget (create-context [this width height] svg-generator) (close [this] (with-open [out (StringWriter.)] (.stream svg-generator out true) (.toString out))))))
null
https://raw.githubusercontent.com/rm-hull/inkspot/ccb7a452a0930f451bcc6c960024d6029f616cd2/src/inkspot/palette.clj
clojure
(ns inkspot.palette (:require [inkspot.color :as color]) (:import (java.awt Color Graphics2D GraphicsEnvironment RenderingHints) (java.awt.image BufferedImage) (java.io StringWriter) (org.apache.batik.dom GenericDOMImplementation) (org.apache.batik.svggen SVGGraphics2D))) (defprotocol IGraphics2DTarget (create-context [this width height]) (close [this])) (defn- ^BufferedImage create-image [w h] (if (GraphicsEnvironment/isHeadless) (BufferedImage. w h BufferedImage/TYPE_INT_ARGB) (.createCompatibleImage (.getDefaultConfiguration (.getDefaultScreenDevice (GraphicsEnvironment/getLocalGraphicsEnvironment))) w h))) (defn- ^Graphics2D create-graphics [^BufferedImage img] (let [g2d (.createGraphics img)] (doto g2d (.setRenderingHint RenderingHints/KEY_STROKE_CONTROL RenderingHints/VALUE_STROKE_NORMALIZE) (.setRenderingHint RenderingHints/KEY_ANTIALIASING RenderingHints/VALUE_ANTIALIAS_ON) (.setRenderingHint RenderingHints/KEY_RENDERING RenderingHints/VALUE_RENDER_QUALITY)) g2d)) (defn- draw-cell [^Graphics2D g2d x y w h color] (doto g2d (.setColor color) (.fillRect x y w h)) g2d) (defn draw [color-swatch & {:keys [g2d-target cell-width cell-height cells-per-row border]}] (let [cell-width (or cell-width 10) cell-height (or cell-height cell-width) cells-per-row (or cells-per-row 48) num-cells (count color-swatch) width (* cell-width cells-per-row) height (* cell-height (Math/ceil (/ num-cells cells-per-row))) pos (fn [i] [(* cell-width (mod i cells-per-row)) (* cell-height (quot i cells-per-row))]) generator (->> (iterate inc 0) (map pos) (map cons color-swatch)) target (g2d-target) g2d (create-context target width height)] (doto g2d (.setBackground Color/WHITE) (.clearRect 0 0 width height)) (let [w (- cell-width (or border 1)) h (- cell-height (or border 1))] (doseq [[c x y] generator] (draw-cell g2d x y w h (color/coerce c)))) (close target))) (defn bitmap [] (let [img (atom nil)] (reify IGraphics2DTarget (create-context [this width height] (reset! img (create-image width height)) (create-graphics @img)) (close [this] @img)))) (defn svg [] (let [dom-impl (GenericDOMImplementation/getDOMImplementation) document (.createDocument dom-impl nil "svg" nil) svg-generator (SVGGraphics2D. document)] (reify IGraphics2DTarget (create-context [this width height] svg-generator) (close [this] (with-open [out (StringWriter.)] (.stream svg-generator out true) (.toString out))))))
58a11799595f39122964e1860bd10dcd251f5d8ff42c7cebcdff1b415b219c5b
janestreet/core
immediate_option.ml
include Immediate_option_intf
null
https://raw.githubusercontent.com/janestreet/core/b0be1daa71b662bd38ef2bb406f7b3e70d63d05f/core/src/immediate_option.ml
ocaml
include Immediate_option_intf
4f53df3420f8e37d49fe980398f27ae86e4fb2a6b752b118ee2926ac6d394cb9
lisp/de.setf.resource
utilities.lisp
-*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.resource.implementation ; -*- (in-package :de.setf.resource.implementation) (:documentation "This file defines tests for utilities in the `de.setf.resource` Common Lisp library." (copyright "Copyright 2010 [james anderson](mailto:) All Rights Reserved" "'de.setf.resource' is free software: you can redistribute it and/or modify it under the terms of version 3 of the GNU Affero General Public License as published by the Free Software Foundation. 'de.setf.resource' 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 Affero General Public License for more details. A copy of the GNU Affero General Public License should be included with 'de.setf.resource' as `agpl.txt`. If not, see the GNU [site](/).")) ;;; (test:execute-test :resource.utilities.**) (test:test resource.pathname-type-mime-type "Performs an explicit of known mime types." (mapcar #'location-mime-type (mapcar #'first *pathname-type-mime-type*)) (list mime:application/n3 mime:application/n3 mime:application/n3 mime:application/rdf+xml mime:application/rdf+xml)) (test:test resource.utilities.set (and (typep '(1 2) '(cons number)) (typep '(1 a) '(cons number)) (not (typep "a" '(cons number))))) (test:test resource.utilities.resource-subtypep (and (not (resource-subtypep 'string)) (resource-subtypep 'resource-object) (resource-subtypep '(cons resource-object)) (resource-subtypep '(or resource-object (cons resource-object))))) (test:test resource.utilities.base-type (mapcar #'base-type '(nil string (cons string) (or resource-object (cons resource-object)) (or fixnum (cons float)))) '(nil string string resource-object fixnum)) (test:test resource.utilities.format-url-encoded (list (format nil ">~/format-url-encoded/<" "/") (format nil ">~/format-url-encoded/<" "host.domain")) '(">http%3A%2F%2Fhost.domain%2Fdir%2F<" ">host.domain<")) (test:test resource.utilities.uri-vocabulary-components (uri-vocabulary-components "-rdf-syntax-ns#type") (find-package "-rdf-syntax-ns#") "type") (test:test resource.utilities.uri-match-p (and (uri-match-p "/" "/") (not (uri-match-p "/" "/"))))
null
https://raw.githubusercontent.com/lisp/de.setf.resource/27bf6dfb3b3ca99cfd5a6feaa5839d99bfb4d29e/test/utilities.lisp
lisp
Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.resource.implementation ; -*- without even the (test:execute-test :resource.utilities.**)
(in-package :de.setf.resource.implementation) (:documentation "This file defines tests for utilities in the `de.setf.resource` Common Lisp library." (copyright "Copyright 2010 [james anderson](mailto:) All Rights Reserved" "'de.setf.resource' is free software: you can redistribute it and/or modify it under the terms of version 3 of the GNU Affero General Public License as published by the Free Software Foundation. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Affero General Public License for more details. A copy of the GNU Affero General Public License should be included with 'de.setf.resource' as `agpl.txt`. If not, see the GNU [site](/).")) (test:test resource.pathname-type-mime-type "Performs an explicit of known mime types." (mapcar #'location-mime-type (mapcar #'first *pathname-type-mime-type*)) (list mime:application/n3 mime:application/n3 mime:application/n3 mime:application/rdf+xml mime:application/rdf+xml)) (test:test resource.utilities.set (and (typep '(1 2) '(cons number)) (typep '(1 a) '(cons number)) (not (typep "a" '(cons number))))) (test:test resource.utilities.resource-subtypep (and (not (resource-subtypep 'string)) (resource-subtypep 'resource-object) (resource-subtypep '(cons resource-object)) (resource-subtypep '(or resource-object (cons resource-object))))) (test:test resource.utilities.base-type (mapcar #'base-type '(nil string (cons string) (or resource-object (cons resource-object)) (or fixnum (cons float)))) '(nil string string resource-object fixnum)) (test:test resource.utilities.format-url-encoded (list (format nil ">~/format-url-encoded/<" "/") (format nil ">~/format-url-encoded/<" "host.domain")) '(">http%3A%2F%2Fhost.domain%2Fdir%2F<" ">host.domain<")) (test:test resource.utilities.uri-vocabulary-components (uri-vocabulary-components "-rdf-syntax-ns#type") (find-package "-rdf-syntax-ns#") "type") (test:test resource.utilities.uri-match-p (and (uri-match-p "/" "/") (not (uri-match-p "/" "/"))))
6f2b66d26daefed6e34b9e1ea7c6d44e59ec7c2d3e736256e52fe22326c4f209
ygmpkk/house
GIFops.hs
From InternetLib by , -- /~hallgren/InternetLib/ module GIFops where import GIF import Data.Array.Unboxed(listArray) import Data.Word(Word8) apRasterData f gif = gif { data_blocks=map db (data_blocks gif) } where db = either Left (Right . im) im image = image { raster_data = f (image_descriptor image) (raster_data image) } decompressRasterData decompr = apRasterData rd where rd id = either (Right . decompr (pixelcount id)) Right compressRasterData compr = apRasterData rd where rd id = either Left (Left . compr (pixelcount id)) pixelcount :: ImageDescriptor -> Int pixelcount id = fromIntegral (iwidth id)*fromIntegral (iheight id) pixels2array :: Int -> [Word8] -> PixelArray pixels2array n ps = listArray (0,n-1) ({-map fromIntegral-} ps)
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/kernel/Gadgets/Images/GIFops.hs
haskell
/~hallgren/InternetLib/ map fromIntegral
From InternetLib by , module GIFops where import GIF import Data.Array.Unboxed(listArray) import Data.Word(Word8) apRasterData f gif = gif { data_blocks=map db (data_blocks gif) } where db = either Left (Right . im) im image = image { raster_data = f (image_descriptor image) (raster_data image) } decompressRasterData decompr = apRasterData rd where rd id = either (Right . decompr (pixelcount id)) Right compressRasterData compr = apRasterData rd where rd id = either Left (Left . compr (pixelcount id)) pixelcount :: ImageDescriptor -> Int pixelcount id = fromIntegral (iwidth id)*fromIntegral (iheight id) pixels2array :: Int -> [Word8] -> PixelArray
7123b8fcba6bb75935d4842e42372dfcd885300781457a66906760b63c7503eb
masaeedu/monoidal
Category.hs
module Control.Category.Sub.Category where import Data.Subtypes (Trivial) import GHC.Exts (Constraint) import Control.Category (Category(..)) class Category p => SubCat (p :: k -> k -> *) where type Ob p :: k -> Constraint type Ob p = Trivial instance SubCat (->)
null
https://raw.githubusercontent.com/masaeedu/monoidal/c48fa8745a08bad58e6d37041e59a0e88d10805d/src/Control/Category/Sub/Category.hs
haskell
module Control.Category.Sub.Category where import Data.Subtypes (Trivial) import GHC.Exts (Constraint) import Control.Category (Category(..)) class Category p => SubCat (p :: k -> k -> *) where type Ob p :: k -> Constraint type Ob p = Trivial instance SubCat (->)
a65a21b51180fe0f093c82851e9937172a30639a513a2d00dd181caae2127cb3
e-wrks/edh
Monad.hs
module Language.Edh.Monad where -- import Debug.Trace -- import GHC.Stack import Control.Applicative import Control.Concurrent.STM import Control.Exception import Control.Monad.State.Strict import qualified Data.ByteString as B import Data.Dynamic import Data.Hashable import Data.IORef import Data.Lossless.Decimal (Decimal) import qualified Data.Lossless.Decimal as D import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Unique import Language.Edh.Control import Language.Edh.CoreLang import Language.Edh.Evaluate import Language.Edh.IOPD import Language.Edh.RUID import Language.Edh.RtTypes import Prelude * Monadic Edh Interface TODO implement exception catching , then async exception masking , then ' bracket ' ; for ' EIO ' at least , possibly for ' Edh ' too . -- | Scriptability enabling monad -- -- The @Edh@ monad is friendly to scripted concurrency and transactional semantics , i.e. event perceivers , the keyword for transaction grouping . -- -- Note @Edh@ is rather slow in run speed, as a cost of scriptability. -- CAVEAT : An @ai@ block as by the scripting code will be broken , thus an -- exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is -- issued in execution of that block. newtype Edh a = Edh { -- | This should seldom be used directly unEdh :: ([(ErrMessage, ErrContext)] -> STM ()) -> EdhTxExit a -> EdhTx } | Wrap a CPS procedure as ' Edh ' computation -- CAVEAT : This is call / CC equivalent , be alert that you 've stepped out of the " Structured Programming " zone by using this . mEdh :: forall a. (EdhTxExit a -> EdhTx) -> Edh a mEdh act = Edh $ \_naExit exit -> act exit | Wrap a CPS procedure as ' Edh ' computation -- CAVEAT : This is call / CC equivalent , be alert that you 've stepped out of the " Structured Programming " zone by using this . mEdh' :: forall a. (EdhTxExit ErrMessage -> EdhTxExit a -> EdhTx) -> Edh a mEdh' act = Edh $ \naExit exit -> do let naExit' :: EdhTxExit ErrMessage naExit' !msg !ets = naExit [(msg, getEdhErrCtx 0 ets)] act naExit' exit -- | Signal __Not/Applicable__ with an error message -- -- This will cause an 'Alternative' action to be tried, per ' MonadPlus ' semantics . An exception will be thrown with accumulated @naM@ -- error messages, if none of the alternative actions can settle with a result. naM :: forall a. ErrMessage -> Edh a naM msg = mEdh' $ \naExit _exit -> naExit msg | Run an ' Edh ' action from within an @'STM ' ( ) @ action -- CAVEAT : -- * You would better make sure the calling thread owns the ' EdhThreadState ' , or the 1st transaction will be carried out in -- current thread, and following transactions will be carried out in the ' EdhThreadState ' 's owner thread , which is ridiculous . Even worse -- when that @Edh@ thread has already been terminated, all subsequent ' STM ' transactions will cease to happen , and your continuation never -- executed too. * Do n't follow such a call with subsequent ' STM ' actions , that 's usually wrong . Unless interleaved " scripting threads " sharing the -- thread are really intended. -- Note : This call finishes as soon with the 1st ' STM ' transaction within the specified ' Edh ' action , the continuation can be resumed rather later after many subsequent ' STM ' transactions performed , so -- 'catchSTM' or similar exception handling around such calls is usually -- wrong. runEdh :: EdhThreadState -> Edh a -> EdhTxExit a -> STM () runEdh ets act exit = runEdhTx ets $ unEdh act rptEdhNotApplicable exit -- | Internal utility, you usually don't use this rptEdhNotApplicable :: [(ErrMessage, ErrContext)] -> STM () rptEdhNotApplicable errs = throwSTM $ EdhError EvalError "❌ No Edh action applicable" (toDyn nil) $ T.unlines $ ( \(msg, ctx) -> if T.null ctx then "⛔ " <> msg else ctx <> "\n⛔ " <> msg ) <$> errs instance Functor Edh where fmap f edh = Edh $ \naExit exit -> unEdh edh naExit $ \a -> exit $ f a # INLINE fmap # instance Applicative Edh where pure a = Edh $ \_naExit exit -> exit a # INLINE pure # (<*>) = ap {-# INLINE (<*>) #-} instance Monad Edh where return = pure # INLINE return # m >>= k = Edh $ \naExit c -> unEdh m naExit (\x -> unEdh (k x) naExit c) {-# INLINE (>>=) #-} instance MonadFail Edh where fail reason = naM $ T.pack reason # INLINE fail # instance Alternative Edh where empty = Edh $ \naExit _exit _ets -> naExit [] x <|> y = Edh $ \naExit exit ets -> unEdh x (\errOut -> unEdh y (naExit . (++ errOut)) exit ets) exit ets instance MonadPlus Edh instance MonadIO Edh where liftIO act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContIO $ act >>= atomically . exitEdh ets exit # INLINE liftIO # instance MonadEdh Edh where liftEdh = id edhThreadState = Edh $ \_naExit exit ets -> exit ets ets throwEdhM' tag msg details = Edh $ \_naExit _exit ets -> throwEdhSTM' ets tag msg details CAVEAT : An @ai@ block as by the scripting code will be broken , thus an -- exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is -- issued in execution of that block. liftSTM act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContSTM $ act >>= exitEdh ets exit -- | Yield from a (host) generator procedure -- -- The driving for-loop may issue @break@ or early @return@ to cease subsequent -- iterations, or the do-body result value will be passed to the @next'iter@ -- continuation. yieldM :: EdhValue -> (EdhValue -> Edh EdhValue) -> Edh EdhValue yieldM !val !next'iter = do !ctx <- edh'context <$> edhThreadState case edh'ctx'genr'caller ctx of Nothing -> throwEdhM EvalError "yield from a procedure not called as generator" Just iter'cb -> mEdh $ \ !genr'exit !ets -> runEdhTx ets $ iter'cb val $ \case Left (!etsThrower, !exv) -> -- note we can actually be encountering the exception -- occurred from a descendant thread forked by the thread -- running the enclosing generator, @etsThrower@ has the correct task queue , and @ets@ has the correct contextual -- callstack anyway edhThrow etsThrower {edh'context = edh'context ets} exv Right EdhBreak -> usually ` break ` stmt from the calling for - loop , -- return nil from the generator, so the loop ends with nil exitEdh ets genr'exit nil Right (EdhReturn !rtn) -> usually ` return ` stmt from the calling for - loop , -- propagate the value to return as however the generator returns, -- it can be a sacred double-return, in which case the for-loop will -- evaluate to a `return` value, thus actually early return from the -- outer-loop procedure exitEdh ets genr'exit rtn Right !yieldGot -> -- usually some value evaluated from the body of the calling for-loop, -- proceed to next iteration runEdh ets (next'iter yieldGot) genr'exit todo : define monad ' ESTM ' and ' inlineESTM ' , maybe with a ' MonadEdhMini ' -- class that 'naM', 'edhThreadState', 'throwEdhM' and etc. refactored to live there , then fast ' STM ' sequences can run without multiple -- txs going through the task queue | Perform the specified ' STM ' action within current ' Edh ' transaction inlineSTM :: STM a -> Edh a inlineSTM act = Edh $ \_naExit exit ets -> act >>= (`exit` ets) # INLINE inlineSTM # | Schedule an STM action to happen after current transaction committed afterTxSTM :: STM () -> Edh () afterTxSTM !actSTM = afterTxSTM' (False <$ actSTM) | Schedule an STM action to happen after current transaction committed -- -- Current Edh thread will be terminated if that action returns 'False' afterTxSTM' :: STM Bool -> Edh () afterTxSTM' !actSTM = Edh $ \_naExit !exit !ets -> do writeTBQueue (edh'task'queue ets) $ EdhDoSTM ets actSTM exitEdh ets exit () -- | Schedule an IO action to happen after current transaction committed afterTxIO :: IO () -> Edh () afterTxIO !actIO = afterTxIO' (False <$ actIO) -- | Schedule an IO action to happen after current transaction committed -- -- Current Edh thread will be terminated if that action returns 'False' afterTxIO' :: IO Bool -> Edh () afterTxIO' !actIO = Edh $ \_naExit !exit !ets -> do writeTBQueue (edh'task'queue ets) $ EdhDoIO ets actIO exitEdh ets exit () -- ** Attribute Resolution -- | Get a property from an @Edh@ object, with magics honored getObjPropertyM :: Object -> AttrKey -> Edh EdhValue getObjPropertyM !obj !key = mEdh' $ \naExit !exit -> do let exitNoAttr = edhObjDescTx obj $ \ !objDesc -> naExit $ "no such property `" <> attrKeyStr key <> "` on object - " <> objDesc getObjProperty' obj key exitNoAttr exit -- | Resolve an attribute addressor into an attribute key resolveEdhAttrAddrM :: AttrAddr -> Edh AttrKey resolveEdhAttrAddrM (NamedAttr !attrName) = return (AttrByName attrName) resolveEdhAttrAddrM (QuaintAttr !attrName) = return (AttrByName attrName) resolveEdhAttrAddrM (SymbolicAttr !symName) = do !ets <- edhThreadState let scope = contextScope $ edh'context ets inlineSTM (resolveEdhCtxAttr scope $ AttrByName symName) >>= \case Just (!val, _) -> case val of (EdhSymbol !symVal) -> return (AttrBySym symVal) (EdhString !nameVal) -> return (AttrByName nameVal) _ -> throwEdhM EvalError $ "not a symbol/string as " <> symName <> ", it is a " <> edhTypeNameOf val <> ": " <> T.pack (show val) Nothing -> throwEdhM EvalError $ "no symbol/string named " <> T.pack (show symName) <> " available" resolveEdhAttrAddrM (IntplSymAttr src !x) = mEdh $ \exit -> evalExprSrc x $ \ !symVal -> case edhUltimate symVal of EdhSymbol !sym -> exitEdhTx exit $ AttrBySym sym EdhString !nm -> exitEdhTx exit $ AttrByName nm _ -> edhSimpleDescTx symVal $ \ !badDesc -> throwEdhTx UsageError $ "symbol interpolation given unexpected value: " <> badDesc <> "\n 🔣 evaluated from @( " <> src <> " )" resolveEdhAttrAddrM (LitSymAttr !sym) = return $ AttrBySym sym resolveEdhAttrAddrM MissedAttrName = throwEdhM EvalError "incomplete syntax: missing attribute name" resolveEdhAttrAddrM MissedAttrSymbol = throwEdhM EvalError "incomplete syntax: missing symbolic attribute name" # INLINE resolveEdhAttrAddrM # -- | Coerce an @Edh@ value into an attribute key -- -- Note only strings, symbols, and direct addressing expressions are valid, -- other type of values will cause an exception thrown. edhValueAsAttrKeyM :: EdhValue -> Edh AttrKey edhValueAsAttrKeyM !keyVal = case edhUltimate keyVal of EdhString !attrName -> return $ AttrByName attrName EdhSymbol !sym -> return $ AttrBySym sym EdhExpr (ExprDefi _ (AttrExpr (DirectRef (AttrAddrSrc !addr _))) _) _ -> resolveEdhAttrAddrM addr _ -> do !badDesc <- edhSimpleDescM keyVal throwEdhM EvalError $ "not a valid attribute key: " <> badDesc -- | Prepare the exporting store for an object, you can put artifacts into it -- so as to get them /exported/ from that specified object prepareExpStoreM :: Object -> Edh EntityStore prepareExpStoreM !fromObj = case edh'obj'store fromObj of HashStore !tgtEnt -> fromStore tgtEnt HostStore _ -> naM $ "no way exporting with a host object of class " <> objClassName fromObj ClassStore !cls -> fromStore $ edh'class'arts cls EventStore !cls _ _ -> fromStore $ edh'class'arts cls where fromStore tgtEnt = mEdh $ \exit ets -> (exitEdh ets exit =<<) $ prepareMagicStore (AttrByName edhExportsMagicName) tgtEnt $ edhCreateNsObj ets NoDocCmt phantomHostProc $ AttrByName "export" -- | Import into current scope all artifacts exported from the @Edh@ module -- identified by the import spec -- -- The spec can be absolute or relative to current context module. importAllM :: Text -> Edh () importAllM !importSpec = mEdh $ \ !exit !ets -> do let ctx = edh'context ets scope = contextScope ctx tgtEnt = edh'scope'entity scope reExpObj = edh'scope'this scope runEdhTx ets $ importEdhModule' tgtEnt reExpObj (WildReceiver noSrcRange) importSpec $ const $ exitEdhTx exit () -- | Import the @Edh@ module identified by the import spec -- -- The spec can be absolute or relative to current context module. importModuleM :: Text -> Edh Object importModuleM !importSpec = mEdh $ \ !exit -> importEdhModule importSpec $ exitEdhTx exit -- | Make all artifacts defined during an action to be exported from contextual -- this object in current scope exportM_ :: forall a. Edh a -> Edh () exportM_ = void . exportM -- | Make all artifacts defined during an action to be exported from contextual -- this object in current scope exportM :: forall a. Edh a -> Edh a exportM act = Edh $ \naExit exit ets -> do let exit' result _ets = exit result ets prepareExpStore ets (edh'scope'this $ contextScope $ edh'context ets) $ \ !esExps -> unEdh act naExit exit' ets { edh'context = (edh'context ets) {edh'ctx'exp'target = Just esExps} } -- | Discourage artifact definitions during the run of an action pureM_ :: forall a. Edh a -> Edh () pureM_ = void . pureM -- | Discourage artifact definitions during the run of an action pureM :: forall a. Edh a -> Edh a pureM act = Edh $ \naExit exit ets -> do let exit' result _ets = exit result ets unEdh act naExit exit' ets {edh'context = (edh'context ets) {edh'ctx'pure = True}} -- ** Effect Resolution | Resolve an effectful artifact with @perform@ semantics -- -- An exception is thrown if no such effect available performM :: AttrKey -> Edh EdhValue performM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhPerform ets effKey $ exitEdh ets exit | Resolve an effectful artifact with @perform@ semantics -- -- 'Nothing' is returned if no such effect available performM' :: AttrKey -> Edh (Maybe EdhValue) performM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhPerform' ets effKey $ exitEdh ets exit -- | Resolve an effectful artifact with @behave@ semantics -- -- An exception is thrown when no such effect available behaveM :: AttrKey -> Edh EdhValue behaveM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhBehave ets effKey $ exitEdh ets exit -- | Resolve an effectful artifact with @behave@ semantics -- -- 'Nothing' is returned if no such effect available behaveM' :: AttrKey -> Edh (Maybe EdhValue) behaveM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhBehave' ets effKey $ exitEdh ets exit -- | Resolve an effectful artifact with @fallback@ semantics -- -- An exception is thrown when no such effect available fallbackM :: AttrKey -> Edh EdhValue fallbackM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhFallback ets effKey $ exitEdh ets exit -- | Resolve an effectful artifact with @fallback@ semantics -- -- 'Nothing' is returned if no such effect available fallbackM' :: AttrKey -> Edh (Maybe EdhValue) fallbackM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhFallback' ets effKey $ exitEdh ets exit -- | Prepare the effecting store for the context scope, you can put artifacts -- into it so as to make them /effective/ in current scope prepareEffStoreM :: Edh EntityStore prepareEffStoreM = prepareEffStoreM' $ AttrByName edhEffectsMagicName -- | Prepare the specifically named effecting store for the context scope, you -- can put artifacts into it so as to make them /effective/ in current scope -- -- Note the naming is not stable yet, consider this an implementation details -- for now. prepareEffStoreM' :: AttrKey -> Edh EntityStore prepareEffStoreM' !magicKey = mEdh $ \ !exit !ets -> exitEdh ets exit =<< prepareEffStore' magicKey ets (edh'scope'entity $ contextScope $ edh'context ets) -- | Define an effectful artifact defineEffectM :: AttrKey -> EdhValue -> Edh () defineEffectM !key !val = Edh $ \_naExit !exit !ets -> do iopdInsert key val =<< prepareEffStore ets (edh'scope'entity $ contextScope $ edh'context ets) exitEdh ets exit () | Create an Edh channel newChanM :: Edh BChan newChanM = inlineSTM newBChan | Read an Edh channel readChanM :: BChan -> Edh EdhValue readChanM !chan = mEdh $ \ !exit -> readBChan chan exit | Write an Edh channel writeChanM :: BChan -> EdhValue -> Edh Bool writeChanM !chan !v = mEdh $ \ !exit -> writeBChan chan v exit * * | The ' STM ' action lifted into ' Edh ' monad newTVarEdh :: forall a. a -> Edh (TVar a) newTVarEdh = inlineSTM . newTVar # INLINE newTVarEdh # | The ' STM ' action lifted into ' Edh ' monad readTVarEdh :: forall a. TVar a -> Edh a readTVarEdh = inlineSTM . readTVar # INLINE readTVarEdh # | The ' STM ' action lifted into ' Edh ' monad writeTVarEdh :: forall a. TVar a -> a -> Edh () writeTVarEdh ref v = inlineSTM $ writeTVar ref v {-# INLINE writeTVarEdh #-} | The ' STM ' action lifted into ' Edh ' monad modifyTVarEdh' :: forall a. TVar a -> (a -> a) -> Edh () modifyTVarEdh' ref f = inlineSTM $ modifyTVar' ref f {-# INLINE modifyTVarEdh' #-} | The ' STM ' action lifted into ' Edh ' monad newEmptyTMVarEdh :: forall a. Edh (TMVar a) newEmptyTMVarEdh = inlineSTM newEmptyTMVar # INLINE newEmptyTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad newTMVarEdh :: forall a. a -> Edh (TMVar a) newTMVarEdh = inlineSTM . newTMVar {-# INLINE newTMVarEdh #-} | The ' STM ' action lifted into ' Edh ' monad readTMVarEdh :: forall a. TMVar a -> Edh a readTMVarEdh = inlineSTM . readTMVar # INLINE readTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad takeTMVarEdh :: forall a. TMVar a -> Edh a takeTMVarEdh = inlineSTM . takeTMVar # INLINE takeTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad putTMVarEdh :: forall a. TMVar a -> a -> Edh () putTMVarEdh ref v = inlineSTM $ putTMVar ref v # INLINE putTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad tryReadTMVarEdh :: forall a. TMVar a -> Edh (Maybe a) tryReadTMVarEdh = inlineSTM . tryReadTMVar # INLINE tryReadTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad tryTakeTMVarEdh :: forall a. TMVar a -> Edh (Maybe a) tryTakeTMVarEdh = inlineSTM . tryTakeTMVar {-# INLINE tryTakeTMVarEdh #-} | The ' STM ' action lifted into ' Edh ' monad tryPutTMVarEdh :: forall a. TMVar a -> a -> Edh Bool tryPutTMVarEdh ref v = inlineSTM $ tryPutTMVar ref v {-# INLINE tryPutTMVarEdh #-} | The ' IO ' action lifted into ' Edh ' monad newIORefEdh :: forall a. a -> Edh (IORef a) newIORefEdh = liftIO . newIORef {-# INLINE newIORefEdh #-} | The ' IO ' action lifted into ' Edh ' monad readIORefEdh :: forall a. IORef a -> Edh a readIORefEdh = liftIO . readIORef {-# INLINE readIORefEdh #-} | The ' IO ' action lifted into ' Edh ' monad writeIORefEdh :: forall a. IORef a -> a -> Edh () writeIORefEdh ref v = liftIO $ writeIORef ref v {-# INLINE writeIORefEdh #-} | ' newRUID\'STM ' lifted into ' Edh ' monad newRUID'Edh :: Edh RUID newRUID'Edh = inlineSTM newRUID'STM {-# INLINE newRUID'Edh #-} | The ' IOPD ' action lifted into ' Edh ' monad iopdCloneEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh (IOPD k v) iopdCloneEdh = inlineSTM . iopdClone # INLINE iopdCloneEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdTransformEdh :: forall k v v'. (Eq k, Hashable k, Deletable v, Deletable v') => (v -> v') -> IOPD k v -> Edh (IOPD k v') iopdTransformEdh trans = inlineSTM . iopdTransform trans # INLINE iopdTransformEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdEmptyEdh :: forall k v. (Eq k, Hashable k, Deletable v) => Edh (IOPD k v) iopdEmptyEdh = inlineSTM iopdEmpty {-# INLINE iopdEmptyEdh #-} | The ' IOPD ' action lifted into ' Edh ' monad iopdNullEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh Bool iopdNullEdh = inlineSTM . iopdNull # INLINE iopdNullEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdSizeEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh Int iopdSizeEdh = inlineSTM . iopdSize # INLINE iopdSizeEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdInsertEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> v -> IOPD k v -> Edh () iopdInsertEdh k v = inlineSTM . iopdInsert k v # INLINE iopdInsertEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdReserveEdh :: forall k v. (Eq k, Hashable k, Deletable v) => Int -> IOPD k v -> Edh () iopdReserveEdh moreCap = inlineSTM . iopdReserve moreCap # INLINE iopdReserveEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdUpdateEdh :: forall k v. (Eq k, Hashable k, Deletable v) => [(k, v)] -> IOPD k v -> Edh () iopdUpdateEdh ps = inlineSTM . iopdUpdate ps # INLINE iopdUpdateEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdLookupEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> IOPD k v -> Edh (Maybe v) iopdLookupEdh key = inlineSTM . iopdLookup key # INLINE iopdLookupEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdLookupDefaultEdh :: forall k v. (Eq k, Hashable k, Deletable v) => v -> k -> IOPD k v -> Edh v iopdLookupDefaultEdh v k = inlineSTM . iopdLookupDefault v k # INLINE iopdLookupDefaultEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdDeleteEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> IOPD k v -> Edh () iopdDeleteEdh k = inlineSTM . iopdDelete k # INLINE iopdDeleteEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdKeysEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [k] iopdKeysEdh = inlineSTM . iopdKeys # INLINE iopdKeysEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdValuesEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [v] iopdValuesEdh = inlineSTM . iopdValues # INLINE iopdValuesEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdToListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [(k, v)] iopdToListEdh = inlineSTM . iopdToList {-# INLINE iopdToListEdh #-} | The ' IOPD ' action lifted into ' Edh ' monad iopdToReverseListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [(k, v)] iopdToReverseListEdh = inlineSTM . iopdToReverseList {-# INLINE iopdToReverseListEdh #-} | The ' IOPD ' action lifted into ' Edh ' monad iopdFromListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => [(k, v)] -> Edh (IOPD k v) iopdFromListEdh = inlineSTM . iopdFromList # INLINE iopdFromListEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdSnapshotEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh (OrderedDict k v) iopdSnapshotEdh = inlineSTM . iopdSnapshot # INLINE iopdSnapshotEdh # -- ** Call Making & Context Manipulation -- | Call an @Edh@ value with specified argument senders -- -- An exception will be thrown if the callee is not actually callable callM :: EdhValue -> [ArgSender] -> Edh EdhValue callM callee apkr = Edh $ \_naExit -> edhMakeCall callee apkr -- | Call an @Edh@ value with specified arguments pack -- -- An exception will be thrown if the callee is not actually callable callM' :: EdhValue -> ArgsPack -> Edh EdhValue callM' callee apk = Edh $ \_naExit -> edhMakeCall' callee apk -- | Call a magic method of an @Edh@ object with specified arguments pack -- -- An exception will be thrown if the object does not support such magic callMagicM :: Object -> AttrKey -> ArgsPack -> Edh EdhValue callMagicM obj magicKey apk = Edh $ \_naExit -> callMagicMethod obj magicKey apk | Run the specified ' Edh ' action in a nested new scope runNested :: Edh a -> Edh a runNested !act = do !ets <- edhThreadState let !scope = edh'frame'scope $ edh'ctx'tip $ edh'context ets !scope' <- inlineSTM $ newNestedScope scope runNestedIn scope' act | Run the specified ' Edh ' action in a specified scope runNestedIn :: Scope -> Edh a -> Edh a runNestedIn !scope !act = Edh $ \naExit exit ets -> do let !ctx = edh'context ets !tip = edh'ctx'tip ctx !tipNew <- newCallFrame scope $ edh'exe'src'loc tip let !etsNew = ets {edh'context = ctxNew} !ctxNew = ctx { edh'ctx'tip = tipNew, edh'ctx'stack = tip : edh'ctx'stack ctx, edh'ctx'genr'caller = Nothing, edh'ctx'match = true, edh'ctx'pure = False, edh'ctx'exp'target = Nothing, edh'ctx'eff'target = Nothing } unEdh act naExit (edhSwitchState ets . exit) etsNew | Switch to a custom context to run the specified ' Edh ' action inContext :: Context -> Edh a -> Edh a inContext !ctx !act = Edh $ \naExit exit !ets -> runEdhTx ets {edh'context = ctx} $ unEdh act naExit $ \result _ets -> exitEdh ets exit result -- ** Evaluation & Sandboxing evalSrcM :: Text -> Text -> Edh EdhValue evalSrcM !srcName !srcCode = Edh $ \_naExit -> evalEdh srcName srcCode evalSrcM' :: Text -> Int -> Text -> Edh EdhValue evalSrcM' !srcName !lineNo !srcCode = Edh $ \_naExit -> evalEdh' srcName lineNo srcCode -- | Evaluate an expression definition evalExprDefiM :: ExprDefi -> Edh EdhValue evalExprDefiM !x = Edh $ \_naExit -> evalExprDefi x -- | Evaluate an expression evalExprM :: Expr -> Edh EdhValue evalExprM !x = Edh $ \_naExit -> evalExpr x | Evaluate an infix operator with specified lhs / rhs expression evalInfixM :: OpSymbol -> Expr -> Expr -> Edh EdhValue evalInfixM !opSym !lhExpr !rhExpr = Edh $ \_naExit -> evalInfix opSym lhExpr rhExpr | Evaluate an infix operator with specified lhs / rhs expression evalInfixSrcM :: OpSymSrc -> ExprSrc -> ExprSrc -> Edh EdhValue evalInfixSrcM !opSym !lhExpr !rhExpr = Edh $ \_naExit -> evalInfixSrc opSym lhExpr rhExpr -- | Evaluate an expression definition caseValueOfM :: EdhValue -> ExprDefi -> Edh EdhValue caseValueOfM !matchTgtVal !x = Edh $ \_naExit -> edhCaseValueOf matchTgtVal x newSandboxM :: Edh Scope newSandboxM = Edh $ \_naExit !exit !ets -> newSandbox ets >>= exitEdh ets exit mkSandboxM :: Scope -> Edh Scope mkSandboxM !origScope = Edh $ \_naExit !exit !ets -> do let !world = edh'prog'world $ edh'thread'prog ets !origProc = edh'scope'proc origScope !sbProc = origProc {edh'procedure'lexi = edh'world'sandbox world} exitEdh ets exit origScope {edh'scope'proc = sbProc} mkObjSandboxM :: Object -> Edh Scope mkObjSandboxM !obj = Edh $ \_naExit !exit !ets -> do mkObjSandbox ets obj $ exitEdh ets exit runInSandboxM :: forall r. Scope -> Edh r -> Edh r runInSandboxM !sandbox !act = Edh $ \_naExit !exit !ets -> do !tipFrame <- newCallFrame sandbox (SrcLoc (SrcDoc "<sandbox>") zeroSrcRange) let !ctxPriv = edh'context ets !etsSandbox = ets { edh'context = ctxPriv { edh'ctx'tip = tipFrame, edh'ctx'stack = edh'ctx'tip ctxPriv : edh'ctx'stack ctxPriv } } runEdh etsSandbox act $ \ !result _ets -> exitEdh ets exit result -- ** Value Manipulations edhPrettyQty :: Decimal -> UnitSpec -> Edh Text edhPrettyQty q u = edhQuantity q u >>= \case Left num -> return $ T.pack $ show num Right qty -> edhReduceQtyNumber qty >>= \(Quantity q' u') -> return $ T.pack $ D.showDecimalLimited 2 q' <> show u' edhQuantity :: Decimal -> UnitSpec -> Edh (Either Decimal Quantity) edhQuantity q uomSpec = mEdh $ \exit ets -> resolveQuantity ets q uomSpec $ exitEdh ets exit edhReduceQtyNumber :: Quantity -> Edh Quantity edhReduceQtyNumber qty = edhReduceQtyNumber' qty <|> return qty edhReduceQtyNumber' :: Quantity -> Edh Quantity edhReduceQtyNumber' qty = mEdh' $ \naExit exit -> reduceQtyNumber qty (exitEdhTx exit) (naExit "unable to reduce quantity") -- | Convert an @Edh@ object to string edhObjStrM :: Object -> Edh Text edhObjStrM !o = Edh $ \_naExit !exit !ets -> edhObjStr ets o $ exitEdh ets exit -- | Convert an @Edh@ value to string edhValueStrM :: EdhValue -> Edh Text edhValueStrM !v = Edh $ \_naExit !exit !ets -> edhValueStr ets v $ exitEdh ets exit -- | Convert an @Edh@ object to its representation string edhObjReprM :: Object -> Edh Text edhObjReprM !o = Edh $ \_naExit !exit !ets -> edhObjRepr ets o $ exitEdh ets exit -- | Convert an @Edh@ value to its representation string edhValueReprM :: EdhValue -> Edh Text edhValueReprM !v = Edh $ \_naExit !exit !ets -> edhValueRepr ets v $ exitEdh ets exit -- | Convert an @Edh@ object to its descriptive string edhObjDescM :: Object -> Edh Text edhObjDescM !o = Edh $ \_naExit !exit !ets -> edhObjDesc ets o $ exitEdh ets exit -- | Convert an @Edh@ object to its descriptive string, with auxiliary args edhObjDescM' :: Object -> KwArgs -> Edh Text edhObjDescM' !o !kwargs = Edh $ \_naExit !exit !ets -> edhObjDesc' ets o kwargs $ exitEdh ets exit -- | Convert an @Edh@ value to its descriptive string edhValueDescM :: EdhValue -> Edh Text edhValueDescM !v = Edh $ \_naExit !exit !ets -> edhValueDesc ets v $ exitEdh ets exit -- | Convert an @Edh@ value to its descriptive string, magics avoided edhSimpleDescM :: EdhValue -> Edh Text edhSimpleDescM !v = Edh $ \_naExit !exit !ets -> edhSimpleDesc ets v $ exitEdh ets exit -- | Convert an @Edh@ value to its falsy value edhValueNullM :: EdhValue -> Edh Bool edhValueNullM !v = Edh $ \_naExit !exit !ets -> edhValueNull ets v $ exitEdh ets exit -- | Convert an @Edh@ value to its JSON representation string edhValueJsonM :: EdhValue -> Edh Text edhValueJsonM !v = Edh $ \_naExit !exit !ets -> edhValueJson ets v $ exitEdh ets exit | Convert an @Edh@ value to its BLOB form , alternative is requested if not -- convertible edhValueBlobM :: EdhValue -> Edh B.ByteString edhValueBlobM !v = Edh $ \_naExit !exit !ets -> edhValueBlob ets v $ exitEdh ets exit | Convert an @Edh@ value to its BLOB form , ' Nothing ' is returned if not -- convertible edhValueBlobM' :: EdhValue -> Edh (Maybe B.ByteString) edhValueBlobM' !v = Edh $ \_naExit !exit !ets -> edhValueBlob' ets v (exitEdh ets exit Nothing) $ exitEdh ets exit . Just Clone a composite object with one of its object instance ` mutObj ` mutated -- to bear the new object stroage -- -- Other member instances are either deep-cloned as class based super, or left -- intact as prototype based super mutCloneObjectM :: Object -> Object -> ObjectStore -> Edh Object mutCloneObjectM !endObj !mutObj !newStore = Edh $ \_naExit !exit !ets -> edhMutCloneObj ets endObj mutObj newStore $ exitEdh ets exit Clone a composite object with one of its object instance ` mutObj ` mutated -- to bear the new host storage data -- -- Other member instances are either deep-cloned as class based super, or left -- intact as prototype based super -- -- todo maybe check new storage data type matches the old one? mutCloneHostObjectM :: forall v. (Eq v, Hashable v, Typeable v) => Object -> Object -> v -> Edh Object mutCloneHostObjectM !endObj !mutObj = mutCloneObjectM endObj mutObj . HostStore . wrapHostValue Clone a composite object with one of its object instance ` mutObj ` mutated -- to bear the new host storage data -- -- Other member instances are either deep-cloned as class based super, or left -- intact as prototype based super -- -- todo maybe check new storage data type matches the old one? mutCloneArbiHostObjectM :: forall v. (Typeable v) => Object -> Object -> v -> Edh Object mutCloneArbiHostObjectM !endObj !mutObj !v = mutCloneObjectM endObj mutObj =<< pinAndStoreHostValue v -- | Parse an @Edh@ value as an index in @Edh@ semantics parseEdhIndexM :: EdhValue -> Edh (Either ErrMessage EdhIndex) parseEdhIndexM !val = Edh $ \_naExit !exit !ets -> parseEdhIndex ets val $ exitEdh ets exit | Regulate an interger index against the actual length , similar to Python , -- i.e. negaive value converted as if from end to beginning regulateEdhIndexM :: Int -> Int -> Edh Int regulateEdhIndexM !len !idx = if posIdx < 0 || posIdx >= len then throwEdhM EvalError $ "index out of bounds: " <> T.pack (show idx) <> " vs " <> T.pack (show len) else return posIdx where !posIdx = if idx < 0 -- Python style negative index then idx + len else idx | Regulate an integer slice against the actual length , similar to Python , -- i.e. negaive value converted as if from end to beginning regulateEdhSliceM :: Int -> (Maybe Int, Maybe Int, Maybe Int) -> Edh (Int, Int, Int) regulateEdhSliceM !len !slice = Edh $ \_naExit !exit !ets -> regulateEdhSlice ets len slice $ exitEdh ets exit -- ** Exceptions | Throw a general exception from an ' Edh ' action throwHostM :: Exception e => e -> Edh a throwHostM = inlineSTM . throwSTM # INLINE throwHostM # -- ** Artifacts Making | Pin an arbitrary Haskell value , to have a designated identity pinHostValueM :: forall v. (Typeable v) => v -> Edh HostValue pinHostValueM = inlineSTM . pinHostValue -- | Convert an identifiable host value into an object store storeHostValue :: forall v. (Eq v, Hashable v, Typeable v) => v -> ObjectStore storeHostValue v = HostStore $ wrapHostValue v -- | Pin an arbitrary host value and convert into an object store pinAndStoreHostValue :: forall v. (Typeable v) => v -> Edh ObjectStore pinAndStoreHostValue v = inlineSTM $ HostStore <$> pinHostValue v | Wrap an identifiable value as an @Edh@ object wrapM :: forall v. (Eq v, Hashable v, Typeable v) => v -> Edh Object wrapM t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ edhWrapValue $ wrapHostValue t | Wrap an identifiable value as an @Edh@ object , with custom repr wrapM' :: forall v. (Eq v, Hashable v, Typeable v) => Text -> v -> Edh Object wrapM' !repr t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ edhWrapValue $ wrapHostValue t | Wrap an arbitrary value as an @Edh@ object wrapArbiM :: forall v. (Typeable v) => v -> Edh Object wrapArbiM t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ pinHostValue t >>= edhWrapValue | Wrap an arbitrary value as an @Edh@ object , with custom repr wrapArbiM' :: forall v. (Typeable v) => Text -> v -> Edh Object wrapArbiM' !repr t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ pinHostValue t >>= edhWrapValue | Wrap an arbitrary value as an @Edh@ object wrapHostM :: HostValue -> Edh Object wrapHostM !dd = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ edhWrapValue dd | Wrap an arbitrary value as an @Edh@ object , with custom repr wrapHostM' :: Text -> HostValue -> Edh Object wrapHostM' !repr !dd = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ edhWrapValue dd | Wrap the specified scope as an Edh object wrapScopeM :: Scope -> Edh Object wrapScopeM s = Edh $ \_naExit !exit !ets -> do let !world = edh'prog'world $ edh'thread'prog ets edh'scope'wrapper world s >>= exitEdh ets exit | Create an Edh host object from the specified class and host data -- -- note the caller is responsible to make sure the supplied host data -- is compatible with the class createHostObjectM :: forall v. (Eq v, Hashable v, Typeable v) => Object -> v -> Edh Object createHostObjectM !clsObj !d = createHostObjectM' clsObj (wrapHostValue d) [] | Create an Edh host object from the specified class , host storage data and -- list of super objects. -- -- note the caller is responsible to make sure the supplied host storage data -- is compatible with the class, the super objects are compatible with the -- class' mro. createHostObjectM' :: Object -> HostValue -> [Object] -> Edh Object createHostObjectM' !clsObj !hsd !supers = do !ss <- newTVarEdh supers return $ Object (HostStore hsd) clsObj ss | Create an Edh host object from the specified class and host data -- -- note the caller is responsible to make sure the supplied host data -- is compatible with the class createArbiHostObjectM :: forall v. (Typeable v) => Object -> v -> Edh Object createArbiHostObjectM !clsObj !v = createArbiHostObjectM' clsObj v [] | Create an Edh host object from the specified class and host data -- -- note the caller is responsible to make sure the supplied host data -- is compatible with the class createArbiHostObjectM' :: forall v. (Typeable v) => Object -> v -> [Object] -> Edh Object createArbiHostObjectM' !clsObj !v !supers = do !hv <- pinHostValueM v createHostObjectM' clsObj hv supers -- | Give birth to a symbol value -- -- Note that normal symbols should use an \@ prefix for their born names mkEdhSymbol :: Text -> Edh Symbol mkEdhSymbol !bornName = inlineSTM $ mkSymbol bornName | Wrap an arguments - pack taking @'Edh ' ' EdhValue'@ action as an @Edh@ -- procedure -- -- Note the args receiver is for documentation purpose only, and currently not -- very much used. mkEdhProc :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh EdhValue mkEdhProc !vc !nm (!p, _args) = do !ets <- edhThreadState !u <- newRUID'Edh return $ EdhProcedure ( vc ProcDefi { edh'procedure'ident = u, edh'procedure'name = AttrByName nm, edh'procedure'lexi = contextScope $ edh'context ets, edh'procedure'doc = NoDocCmt, edh'procedure'decl = HostDecl $ \apk -> unEdh (p apk) rptEdhNotApplicable } ) Nothing -- | Use the arguments-pack taking @'Edh' 'ObjectStore'@ action as the object -- allocator, and the @'Edh' ()@ action as class initialization procedure, to -- create an @Edh@ class. mkEdhClass :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh Object mkEdhClass !clsName !allocator !superClasses !clsBody = do !ets <- edhThreadState !classStore <- inlineSTM iopdEmpty !idCls <- newRUID'Edh !ssCls <- newTVarEdh superClasses !mroCls <- newTVarEdh [] let !scope = contextScope $ edh'context ets !metaClassObj = edh'obj'class $ edh'obj'class $ edh'scope'this $ rootScopeOf scope !clsProc = ProcDefi idCls (AttrByName clsName) scope NoDocCmt (HostDecl fakeHostProc) !cls = Class clsProc classStore allocator' mroCls !clsObj = Object (ClassStore cls) metaClassObj ssCls !clsScope = scope { edh'scope'entity = classStore, edh'scope'this = clsObj, edh'scope'that = clsObj, edh'scope'proc = clsProc, edh'effects'stack = [] } runNestedIn clsScope clsBody !mroInvalid <- inlineSTM $ fillClassMRO cls superClasses unless (T.null mroInvalid) $ throwEdhM UsageError mroInvalid return clsObj where fakeHostProc :: ArgsPack -> EdhHostProc fakeHostProc _ !exit = exitEdhTx exit nil allocator' :: ArgsPack -> EdhObjectAllocator allocator' apk ctorExit ets = unEdh (allocator apk) rptEdhNotApplicable (\oStore _ets -> ctorExit oStore) ets -- | Define an @Edh@ artifact into current scope -- -- Note pure and exporting semantics are honored. defEdhArt :: AttrName -> EdhValue -> Edh () defEdhArt nm = defEdhArt' (AttrByName nm) -- | Define an @Edh@ artifact into current scope -- -- Note pure and exporting semantics are honored. defEdhArt' :: AttrKey -> EdhValue -> Edh () defEdhArt' key val = do !ets <- edhThreadState let !ctx = edh'context ets esDefs = edh'scope'entity $ contextScope ctx unless (edh'ctx'pure ctx) $ inlineSTM $ iopdInsert key val esDefs case edh'ctx'exp'target ctx of Nothing -> pure () Just !esExps -> inlineSTM $ iopdInsert key val esExps -- | Define an @Edh@ symbol into current scope -- -- Note that the conventional \@ prefix will be added to the attribute name -- specified here defEdhSymbol :: AttrName -> Edh Symbol defEdhSymbol name = do sym <- mkEdhSymbol ("@" <> name) defEdhArt name $ EdhSymbol sym return sym -- | Define an @Edh@ host procedure into current scope -- -- Note pure and exporting semantics are honored. defEdhProc_ :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh () defEdhProc_ !vc !nm !hp = void $ defEdhProc vc nm hp -- | Define an @Edh@ host procedure into current scope -- -- Note pure and exporting semantics are honored. defEdhProc :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh EdhValue defEdhProc !vc !nm !hp = do !pv <- mkEdhProc vc nm hp defEdhArt nm pv return pv -- | Define an @Edh@ host class into current scope -- -- Note pure and exporting semantics are honored. defEdhClass_ :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh () defEdhClass_ !clsName !allocator !superClasses !clsBody = void $ defEdhClass clsName allocator superClasses clsBody -- | Define an @Edh@ host class into current scope -- -- Note pure and exporting semantics are honored. defEdhClass :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh Object defEdhClass !clsName !allocator !superClasses !clsBody = do clsObj <- mkEdhClass clsName allocator superClasses clsBody defEdhArt clsName (EdhObject clsObj) return clsObj * * Edh Error from STM throwEdhSTM :: EdhThreadState -> EdhErrorTag -> ErrMessage -> STM a throwEdhSTM ets tag msg = throwEdhSTM' ets tag msg [] throwEdhSTM' :: EdhThreadState -> EdhErrorTag -> ErrMessage -> [(AttrKey, EdhValue)] -> STM a throwEdhSTM' ets tag msg details = do let !edhErr = EdhError tag msg errDetails $ getEdhErrCtx 0 ets !edhWrapException = edh'exception'wrapper (edh'prog'world $ edh'thread'prog ets) !errDetails = case details of [] -> toDyn nil _ -> toDyn $ EdhArgsPack $ ArgsPack [] $ odFromList details edhWrapException (Just ets) (toException edhErr) >>= \ !exo -> edhThrow ets $ EdhObject exo * * The type class for Edh scriptability enabled monads class (MonadIO m, Monad m) => MonadEdh m where | Lift an ' Edh ' action -- -- This is some similar to what @unliftio@ library does, yet better all known instances can mutually lift eachother with ' Edh ' liftEdh :: Edh a -> m a | Extract the ' EdhThreadState ' from current @Edh@ thread edhThreadState :: m EdhThreadState -- | Extract the 'EdhProgState' from current @Edh@ thread edhProgramState :: m EdhProgState edhProgramState = edh'thread'prog <$> edhThreadState -- | Throw a tagged exception with specified error message throwEdhM :: EdhErrorTag -> ErrMessage -> m a throwEdhM tag msg = throwEdhM' tag msg [] -- | Throw a tagged exception with specified error message, and details throwEdhM' :: EdhErrorTag -> ErrMessage -> [(AttrKey, EdhValue)] -> m a | Perform the specified ' STM ' action in a new ' atomically ' transaction liftSTM :: STM a -> m a * * The EIO Monad | Edh aware ( or scriptability Enhanced ) IO Monad -- High density of ' liftIO 's from ' Edh ' monad means terrible performance -- machine-wise, so we need this continuation based @EIO@ monad in which the machine performance can be much better - ' liftIO 's from within ' EIO ' are -- fairly cheaper. -- You would want go deep into plain ' IO ' monad , but only back to ' EIO ' , you -- can 'liftEdh' to call scripted parts of the program. -- CAVEAT : During either ' EIO ' or plain ' IO ' , even though lifted from an ' Edh ' -- monad, event perceivers if any armed by the script will be suspended -- thus unable to preempt the trunk execution, which is a desirable behavior with the ' Edh ' monad or ' STM ' monad by ' liftSTM ' . newtype EIO a = EIO | Run an ' EIO ' action from within an @'IO ' ( ) @ action -- CAVEAT : -- * You would better make sure the calling thread owns the ' EdhThreadState ' , or the 1st transaction will be carried out in -- current thread, and following transactions will be carried out in the ' EdhThreadState ' 's owner thread , which is ridiculous . Even worse -- when that @Edh@ thread has already been terminated, all subsequent ' STM ' transactions will cease to happen , and your continuation never -- executed too. -- * Don't follow such a call with subsequent 'IO' actions, that's usually wrong . Unless interleaved " scripting threads " sharing the -- thread are really intended. -- Note : This call finishes as soon with the 1st ' STM ' transaction within the specified ' Edh ' action , the continuation can be resumed rather later after many subsequent ' STM ' transactions performed , so -- 'catch' or similar exception handling around such calls is usually -- wrong. runEIO :: EdhThreadState -> (a -> IO ()) -> IO () } instance MonadEdh EIO where liftEdh act = EIO $ \ets exit -> atomically $ runEdh ets act $ edhContIO . exit edhThreadState = EIO $ \ets exit -> exit ets throwEdhM' tag msg details = EIO $ \ets _exit -> atomically $ throwEdhSTM' ets tag msg details liftSTM = liftIO . atomically | Lift an ' EIO ' action from an ' Edh ' action -- This is some similar to what @unliftio@ library does , yet better here ' Edh ' and ' EIO ' can mutually lift eachother , -- CAVEAT : An @ai@ block as by the scripting code will be broken , thus an -- exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is -- issued in execution of that block. liftEIO :: EIO a -> Edh a liftEIO act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContIO $ runEIO act ets $ atomically . exitEdh ets exit instance Functor EIO where fmap f c = EIO $ \ets exit -> runEIO c ets $ exit . f # INLINE fmap # instance Applicative EIO where pure a = EIO $ \_ets exit -> exit a # INLINE pure # (<*>) = ap {-# INLINE (<*>) #-} instance Monad EIO where return = pure # INLINE return # m >>= k = EIO $ \ets exit -> runEIO m ets $ \a -> runEIO (k a) ets exit {-# INLINE (>>=) #-} instance MonadFail EIO where fail reason = throwEdhM EvalError $ T.pack reason # INLINE fail # instance MonadIO EIO where liftIO act = EIO $ \_ets exit -> act >>= exit # INLINE liftIO # * * EIO Monad Utilities | Extract the ' EdhThreadState ' from current @Edh@ thread eioThreadState :: EIO EdhThreadState eioThreadState = EIO $ \ets exit -> exit ets # INLINE eioThreadState # -- | Extract the 'EdhProgState' from current @Edh@ thread eioProgramState :: EIO EdhProgState eioProgramState = EIO $ \ets exit -> exit (edh'thread'prog ets) # INLINE eioProgramState # | Shorthand for @'liftIO ' . ' atomically'@ atomicallyEIO :: STM a -> EIO a atomicallyEIO = liftIO . atomically # INLINE atomicallyEIO # | The ' IO ' action lifted into ' EIO ' monad newTVarEIO :: forall a. a -> EIO (TVar a) newTVarEIO = liftIO . newTVarIO # INLINE newTVarEIO # | The ' IO ' action lifted into ' EIO ' monad readTVarEIO :: forall a. TVar a -> EIO a readTVarEIO = liftIO . readTVarIO # INLINE readTVarEIO # | The ' STM ' action lifted into ' EIO ' monad writeTVarEIO :: forall a. TVar a -> a -> EIO () writeTVarEIO ref v = atomicallyEIO $ writeTVar ref v # INLINE writeTVarEIO # | The ' STM ' action lifted into ' EIO ' monad modifyTVarEIO' :: forall a. TVar a -> (a -> a) -> EIO () modifyTVarEIO' ref f = atomicallyEIO $ modifyTVar' ref f {-# INLINE modifyTVarEIO' #-} | The ' STM ' action lifted into ' EIO ' monad swapTVarEIO :: forall a. TVar a -> a -> EIO a swapTVarEIO ref a = atomicallyEIO $ swapTVar ref a # INLINE swapTVarEIO # | The ' IO ' action lifted into ' EIO ' monad newEmptyTMVarEIO :: forall a. EIO (TMVar a) newEmptyTMVarEIO = liftIO newEmptyTMVarIO # INLINE newEmptyTMVarEIO # | The ' IO ' action lifted into ' EIO ' monad newTMVarEIO :: forall a. a -> EIO (TMVar a) newTMVarEIO = liftIO . newTMVarIO # INLINE newTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad readTMVarEIO :: forall a. TMVar a -> EIO a readTMVarEIO = atomicallyEIO . readTMVar # INLINE readTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad takeTMVarEIO :: forall a. TMVar a -> EIO a takeTMVarEIO = atomicallyEIO . takeTMVar # INLINE takeTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad putTMVarEIO :: forall a. TMVar a -> a -> EIO () putTMVarEIO ref v = atomicallyEIO $ putTMVar ref v # INLINE putTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryReadTMVarEIO :: forall a. TMVar a -> EIO (Maybe a) tryReadTMVarEIO = atomicallyEIO . tryReadTMVar # INLINE tryReadTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryTakeTMVarEIO :: forall a. TMVar a -> EIO (Maybe a) tryTakeTMVarEIO = atomicallyEIO . tryTakeTMVar # INLINE tryTakeTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryPutTMVarEIO :: forall a. TMVar a -> a -> EIO Bool tryPutTMVarEIO ref v = atomicallyEIO $ tryPutTMVar ref v # INLINE tryPutTMVarEIO # | The ' IO ' action lifted into ' EIO ' monad newIORefEIO :: forall a. a -> EIO (IORef a) newIORefEIO = liftIO . newIORef # INLINE newIORefEIO # | The ' IO ' action lifted into ' EIO ' monad readIORefEIO :: forall a. IORef a -> EIO a readIORefEIO = liftIO . readIORef # INLINE readIORefEIO # | The ' IO ' action lifted into ' EIO ' monad writeIORefEIO :: forall a. IORef a -> a -> EIO () writeIORefEIO ref v = liftIO $ writeIORef ref v # INLINE writeIORefEIO # | The ' IO ' action lifted into ' EIO ' monad newUniqueEIO :: EIO Unique newUniqueEIO = liftIO newUnique # INLINE newUniqueEIO # * * Exceptions with EIO | Throw a general exception from an ' EIO ' action throwHostEIO :: Exception e => e -> EIO a throwHostEIO = liftIO . throwIO {-# INLINE throwHostEIO #-}
null
https://raw.githubusercontent.com/e-wrks/edh/b791397dbe4c669e6e3b6dc07e3cad67cffdaba1/elr/src/Language/Edh/Monad.hs
haskell
import Debug.Trace import GHC.Stack | Scriptability enabling monad The @Edh@ monad is friendly to scripted concurrency and transactional Note @Edh@ is rather slow in run speed, as a cost of scriptability. exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is issued in execution of that block. | This should seldom be used directly | Signal __Not/Applicable__ with an error message This will cause an 'Alternative' action to be tried, per error messages, if none of the alternative actions can settle with a result. current thread, and following transactions will be carried out in when that @Edh@ thread has already been terminated, all subsequent executed too. thread are really intended. 'catchSTM' or similar exception handling around such calls is usually wrong. | Internal utility, you usually don't use this # INLINE (<*>) # # INLINE (>>=) # exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is issued in execution of that block. | Yield from a (host) generator procedure The driving for-loop may issue @break@ or early @return@ to cease subsequent iterations, or the do-body result value will be passed to the @next'iter@ continuation. note we can actually be encountering the exception occurred from a descendant thread forked by the thread running the enclosing generator, @etsThrower@ has the callstack anyway return nil from the generator, so the loop ends with nil propagate the value to return as however the generator returns, it can be a sacred double-return, in which case the for-loop will evaluate to a `return` value, thus actually early return from the outer-loop procedure usually some value evaluated from the body of the calling for-loop, proceed to next iteration class that 'naM', 'edhThreadState', 'throwEdhM' and etc. refactored txs going through the task queue Current Edh thread will be terminated if that action returns 'False' | Schedule an IO action to happen after current transaction committed | Schedule an IO action to happen after current transaction committed Current Edh thread will be terminated if that action returns 'False' ** Attribute Resolution | Get a property from an @Edh@ object, with magics honored | Resolve an attribute addressor into an attribute key | Coerce an @Edh@ value into an attribute key Note only strings, symbols, and direct addressing expressions are valid, other type of values will cause an exception thrown. | Prepare the exporting store for an object, you can put artifacts into it so as to get them /exported/ from that specified object | Import into current scope all artifacts exported from the @Edh@ module identified by the import spec The spec can be absolute or relative to current context module. | Import the @Edh@ module identified by the import spec The spec can be absolute or relative to current context module. | Make all artifacts defined during an action to be exported from contextual this object in current scope | Make all artifacts defined during an action to be exported from contextual this object in current scope | Discourage artifact definitions during the run of an action | Discourage artifact definitions during the run of an action ** Effect Resolution An exception is thrown if no such effect available 'Nothing' is returned if no such effect available | Resolve an effectful artifact with @behave@ semantics An exception is thrown when no such effect available | Resolve an effectful artifact with @behave@ semantics 'Nothing' is returned if no such effect available | Resolve an effectful artifact with @fallback@ semantics An exception is thrown when no such effect available | Resolve an effectful artifact with @fallback@ semantics 'Nothing' is returned if no such effect available | Prepare the effecting store for the context scope, you can put artifacts into it so as to make them /effective/ in current scope | Prepare the specifically named effecting store for the context scope, you can put artifacts into it so as to make them /effective/ in current scope Note the naming is not stable yet, consider this an implementation details for now. | Define an effectful artifact # INLINE writeTVarEdh # # INLINE modifyTVarEdh' # # INLINE newTMVarEdh # # INLINE tryTakeTMVarEdh # # INLINE tryPutTMVarEdh # # INLINE newIORefEdh # # INLINE readIORefEdh # # INLINE writeIORefEdh # # INLINE newRUID'Edh # # INLINE iopdEmptyEdh # # INLINE iopdToListEdh # # INLINE iopdToReverseListEdh # ** Call Making & Context Manipulation | Call an @Edh@ value with specified argument senders An exception will be thrown if the callee is not actually callable | Call an @Edh@ value with specified arguments pack An exception will be thrown if the callee is not actually callable | Call a magic method of an @Edh@ object with specified arguments pack An exception will be thrown if the object does not support such magic ** Evaluation & Sandboxing | Evaluate an expression definition | Evaluate an expression | Evaluate an expression definition ** Value Manipulations | Convert an @Edh@ object to string | Convert an @Edh@ value to string | Convert an @Edh@ object to its representation string | Convert an @Edh@ value to its representation string | Convert an @Edh@ object to its descriptive string | Convert an @Edh@ object to its descriptive string, with auxiliary args | Convert an @Edh@ value to its descriptive string | Convert an @Edh@ value to its descriptive string, magics avoided | Convert an @Edh@ value to its falsy value | Convert an @Edh@ value to its JSON representation string convertible convertible to bear the new object stroage Other member instances are either deep-cloned as class based super, or left intact as prototype based super to bear the new host storage data Other member instances are either deep-cloned as class based super, or left intact as prototype based super todo maybe check new storage data type matches the old one? to bear the new host storage data Other member instances are either deep-cloned as class based super, or left intact as prototype based super todo maybe check new storage data type matches the old one? | Parse an @Edh@ value as an index in @Edh@ semantics i.e. negaive value converted as if from end to beginning Python style negative index i.e. negaive value converted as if from end to beginning ** Exceptions ** Artifacts Making | Convert an identifiable host value into an object store | Pin an arbitrary host value and convert into an object store note the caller is responsible to make sure the supplied host data is compatible with the class list of super objects. note the caller is responsible to make sure the supplied host storage data is compatible with the class, the super objects are compatible with the class' mro. note the caller is responsible to make sure the supplied host data is compatible with the class note the caller is responsible to make sure the supplied host data is compatible with the class | Give birth to a symbol value Note that normal symbols should use an \@ prefix for their born names procedure Note the args receiver is for documentation purpose only, and currently not very much used. | Use the arguments-pack taking @'Edh' 'ObjectStore'@ action as the object allocator, and the @'Edh' ()@ action as class initialization procedure, to create an @Edh@ class. | Define an @Edh@ artifact into current scope Note pure and exporting semantics are honored. | Define an @Edh@ artifact into current scope Note pure and exporting semantics are honored. | Define an @Edh@ symbol into current scope Note that the conventional \@ prefix will be added to the attribute name specified here | Define an @Edh@ host procedure into current scope Note pure and exporting semantics are honored. | Define an @Edh@ host procedure into current scope Note pure and exporting semantics are honored. | Define an @Edh@ host class into current scope Note pure and exporting semantics are honored. | Define an @Edh@ host class into current scope Note pure and exporting semantics are honored. This is some similar to what @unliftio@ library does, yet better all known | Extract the 'EdhProgState' from current @Edh@ thread | Throw a tagged exception with specified error message | Throw a tagged exception with specified error message, and details machine-wise, so we need this continuation based @EIO@ monad in which the fairly cheaper. can 'liftEdh' to call scripted parts of the program. monad, event perceivers if any armed by the script will be suspended thus unable to preempt the trunk execution, which is a desirable current thread, and following transactions will be carried out in when that @Edh@ thread has already been terminated, all subsequent executed too. * Don't follow such a call with subsequent 'IO' actions, that's usually thread are really intended. 'catch' or similar exception handling around such calls is usually wrong. exception thrown, wherever any 'liftSTM' 'liftEIO' or 'liftIO' is issued in execution of that block. # INLINE (<*>) # # INLINE (>>=) # | Extract the 'EdhProgState' from current @Edh@ thread # INLINE modifyTVarEIO' # # INLINE throwHostEIO #
module Language.Edh.Monad where import Control.Applicative import Control.Concurrent.STM import Control.Exception import Control.Monad.State.Strict import qualified Data.ByteString as B import Data.Dynamic import Data.Hashable import Data.IORef import Data.Lossless.Decimal (Decimal) import qualified Data.Lossless.Decimal as D import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Unique import Language.Edh.Control import Language.Edh.CoreLang import Language.Edh.Evaluate import Language.Edh.IOPD import Language.Edh.RUID import Language.Edh.RtTypes import Prelude * Monadic Edh Interface TODO implement exception catching , then async exception masking , then ' bracket ' ; for ' EIO ' at least , possibly for ' Edh ' too . semantics , i.e. event perceivers , the keyword for transaction grouping . CAVEAT : An @ai@ block as by the scripting code will be broken , thus an newtype Edh a = Edh unEdh :: ([(ErrMessage, ErrContext)] -> STM ()) -> EdhTxExit a -> EdhTx } | Wrap a CPS procedure as ' Edh ' computation CAVEAT : This is call / CC equivalent , be alert that you 've stepped out of the " Structured Programming " zone by using this . mEdh :: forall a. (EdhTxExit a -> EdhTx) -> Edh a mEdh act = Edh $ \_naExit exit -> act exit | Wrap a CPS procedure as ' Edh ' computation CAVEAT : This is call / CC equivalent , be alert that you 've stepped out of the " Structured Programming " zone by using this . mEdh' :: forall a. (EdhTxExit ErrMessage -> EdhTxExit a -> EdhTx) -> Edh a mEdh' act = Edh $ \naExit exit -> do let naExit' :: EdhTxExit ErrMessage naExit' !msg !ets = naExit [(msg, getEdhErrCtx 0 ets)] act naExit' exit ' MonadPlus ' semantics . An exception will be thrown with accumulated @naM@ naM :: forall a. ErrMessage -> Edh a naM msg = mEdh' $ \naExit _exit -> naExit msg | Run an ' Edh ' action from within an @'STM ' ( ) @ action CAVEAT : * You would better make sure the calling thread owns the ' EdhThreadState ' , or the 1st transaction will be carried out in the ' EdhThreadState ' 's owner thread , which is ridiculous . Even worse ' STM ' transactions will cease to happen , and your continuation never * Do n't follow such a call with subsequent ' STM ' actions , that 's usually wrong . Unless interleaved " scripting threads " sharing the Note : This call finishes as soon with the 1st ' STM ' transaction within the specified ' Edh ' action , the continuation can be resumed rather later after many subsequent ' STM ' transactions performed , so runEdh :: EdhThreadState -> Edh a -> EdhTxExit a -> STM () runEdh ets act exit = runEdhTx ets $ unEdh act rptEdhNotApplicable exit rptEdhNotApplicable :: [(ErrMessage, ErrContext)] -> STM () rptEdhNotApplicable errs = throwSTM $ EdhError EvalError "❌ No Edh action applicable" (toDyn nil) $ T.unlines $ ( \(msg, ctx) -> if T.null ctx then "⛔ " <> msg else ctx <> "\n⛔ " <> msg ) <$> errs instance Functor Edh where fmap f edh = Edh $ \naExit exit -> unEdh edh naExit $ \a -> exit $ f a # INLINE fmap # instance Applicative Edh where pure a = Edh $ \_naExit exit -> exit a # INLINE pure # (<*>) = ap instance Monad Edh where return = pure # INLINE return # m >>= k = Edh $ \naExit c -> unEdh m naExit (\x -> unEdh (k x) naExit c) instance MonadFail Edh where fail reason = naM $ T.pack reason # INLINE fail # instance Alternative Edh where empty = Edh $ \naExit _exit _ets -> naExit [] x <|> y = Edh $ \naExit exit ets -> unEdh x (\errOut -> unEdh y (naExit . (++ errOut)) exit ets) exit ets instance MonadPlus Edh instance MonadIO Edh where liftIO act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContIO $ act >>= atomically . exitEdh ets exit # INLINE liftIO # instance MonadEdh Edh where liftEdh = id edhThreadState = Edh $ \_naExit exit ets -> exit ets ets throwEdhM' tag msg details = Edh $ \_naExit _exit ets -> throwEdhSTM' ets tag msg details CAVEAT : An @ai@ block as by the scripting code will be broken , thus an liftSTM act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContSTM $ act >>= exitEdh ets exit yieldM :: EdhValue -> (EdhValue -> Edh EdhValue) -> Edh EdhValue yieldM !val !next'iter = do !ctx <- edh'context <$> edhThreadState case edh'ctx'genr'caller ctx of Nothing -> throwEdhM EvalError "yield from a procedure not called as generator" Just iter'cb -> mEdh $ \ !genr'exit !ets -> runEdhTx ets $ iter'cb val $ \case Left (!etsThrower, !exv) -> correct task queue , and @ets@ has the correct contextual edhThrow etsThrower {edh'context = edh'context ets} exv Right EdhBreak -> usually ` break ` stmt from the calling for - loop , exitEdh ets genr'exit nil Right (EdhReturn !rtn) -> usually ` return ` stmt from the calling for - loop , exitEdh ets genr'exit rtn Right !yieldGot -> runEdh ets (next'iter yieldGot) genr'exit todo : define monad ' ESTM ' and ' inlineESTM ' , maybe with a ' MonadEdhMini ' to live there , then fast ' STM ' sequences can run without multiple | Perform the specified ' STM ' action within current ' Edh ' transaction inlineSTM :: STM a -> Edh a inlineSTM act = Edh $ \_naExit exit ets -> act >>= (`exit` ets) # INLINE inlineSTM # | Schedule an STM action to happen after current transaction committed afterTxSTM :: STM () -> Edh () afterTxSTM !actSTM = afterTxSTM' (False <$ actSTM) | Schedule an STM action to happen after current transaction committed afterTxSTM' :: STM Bool -> Edh () afterTxSTM' !actSTM = Edh $ \_naExit !exit !ets -> do writeTBQueue (edh'task'queue ets) $ EdhDoSTM ets actSTM exitEdh ets exit () afterTxIO :: IO () -> Edh () afterTxIO !actIO = afterTxIO' (False <$ actIO) afterTxIO' :: IO Bool -> Edh () afterTxIO' !actIO = Edh $ \_naExit !exit !ets -> do writeTBQueue (edh'task'queue ets) $ EdhDoIO ets actIO exitEdh ets exit () getObjPropertyM :: Object -> AttrKey -> Edh EdhValue getObjPropertyM !obj !key = mEdh' $ \naExit !exit -> do let exitNoAttr = edhObjDescTx obj $ \ !objDesc -> naExit $ "no such property `" <> attrKeyStr key <> "` on object - " <> objDesc getObjProperty' obj key exitNoAttr exit resolveEdhAttrAddrM :: AttrAddr -> Edh AttrKey resolveEdhAttrAddrM (NamedAttr !attrName) = return (AttrByName attrName) resolveEdhAttrAddrM (QuaintAttr !attrName) = return (AttrByName attrName) resolveEdhAttrAddrM (SymbolicAttr !symName) = do !ets <- edhThreadState let scope = contextScope $ edh'context ets inlineSTM (resolveEdhCtxAttr scope $ AttrByName symName) >>= \case Just (!val, _) -> case val of (EdhSymbol !symVal) -> return (AttrBySym symVal) (EdhString !nameVal) -> return (AttrByName nameVal) _ -> throwEdhM EvalError $ "not a symbol/string as " <> symName <> ", it is a " <> edhTypeNameOf val <> ": " <> T.pack (show val) Nothing -> throwEdhM EvalError $ "no symbol/string named " <> T.pack (show symName) <> " available" resolveEdhAttrAddrM (IntplSymAttr src !x) = mEdh $ \exit -> evalExprSrc x $ \ !symVal -> case edhUltimate symVal of EdhSymbol !sym -> exitEdhTx exit $ AttrBySym sym EdhString !nm -> exitEdhTx exit $ AttrByName nm _ -> edhSimpleDescTx symVal $ \ !badDesc -> throwEdhTx UsageError $ "symbol interpolation given unexpected value: " <> badDesc <> "\n 🔣 evaluated from @( " <> src <> " )" resolveEdhAttrAddrM (LitSymAttr !sym) = return $ AttrBySym sym resolveEdhAttrAddrM MissedAttrName = throwEdhM EvalError "incomplete syntax: missing attribute name" resolveEdhAttrAddrM MissedAttrSymbol = throwEdhM EvalError "incomplete syntax: missing symbolic attribute name" # INLINE resolveEdhAttrAddrM # edhValueAsAttrKeyM :: EdhValue -> Edh AttrKey edhValueAsAttrKeyM !keyVal = case edhUltimate keyVal of EdhString !attrName -> return $ AttrByName attrName EdhSymbol !sym -> return $ AttrBySym sym EdhExpr (ExprDefi _ (AttrExpr (DirectRef (AttrAddrSrc !addr _))) _) _ -> resolveEdhAttrAddrM addr _ -> do !badDesc <- edhSimpleDescM keyVal throwEdhM EvalError $ "not a valid attribute key: " <> badDesc prepareExpStoreM :: Object -> Edh EntityStore prepareExpStoreM !fromObj = case edh'obj'store fromObj of HashStore !tgtEnt -> fromStore tgtEnt HostStore _ -> naM $ "no way exporting with a host object of class " <> objClassName fromObj ClassStore !cls -> fromStore $ edh'class'arts cls EventStore !cls _ _ -> fromStore $ edh'class'arts cls where fromStore tgtEnt = mEdh $ \exit ets -> (exitEdh ets exit =<<) $ prepareMagicStore (AttrByName edhExportsMagicName) tgtEnt $ edhCreateNsObj ets NoDocCmt phantomHostProc $ AttrByName "export" importAllM :: Text -> Edh () importAllM !importSpec = mEdh $ \ !exit !ets -> do let ctx = edh'context ets scope = contextScope ctx tgtEnt = edh'scope'entity scope reExpObj = edh'scope'this scope runEdhTx ets $ importEdhModule' tgtEnt reExpObj (WildReceiver noSrcRange) importSpec $ const $ exitEdhTx exit () importModuleM :: Text -> Edh Object importModuleM !importSpec = mEdh $ \ !exit -> importEdhModule importSpec $ exitEdhTx exit exportM_ :: forall a. Edh a -> Edh () exportM_ = void . exportM exportM :: forall a. Edh a -> Edh a exportM act = Edh $ \naExit exit ets -> do let exit' result _ets = exit result ets prepareExpStore ets (edh'scope'this $ contextScope $ edh'context ets) $ \ !esExps -> unEdh act naExit exit' ets { edh'context = (edh'context ets) {edh'ctx'exp'target = Just esExps} } pureM_ :: forall a. Edh a -> Edh () pureM_ = void . pureM pureM :: forall a. Edh a -> Edh a pureM act = Edh $ \naExit exit ets -> do let exit' result _ets = exit result ets unEdh act naExit exit' ets {edh'context = (edh'context ets) {edh'ctx'pure = True}} | Resolve an effectful artifact with @perform@ semantics performM :: AttrKey -> Edh EdhValue performM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhPerform ets effKey $ exitEdh ets exit | Resolve an effectful artifact with @perform@ semantics performM' :: AttrKey -> Edh (Maybe EdhValue) performM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhPerform' ets effKey $ exitEdh ets exit behaveM :: AttrKey -> Edh EdhValue behaveM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhBehave ets effKey $ exitEdh ets exit behaveM' :: AttrKey -> Edh (Maybe EdhValue) behaveM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhBehave' ets effKey $ exitEdh ets exit fallbackM :: AttrKey -> Edh EdhValue fallbackM !effKey = Edh $ \_naExit !exit !ets -> resolveEdhFallback ets effKey $ exitEdh ets exit fallbackM' :: AttrKey -> Edh (Maybe EdhValue) fallbackM' !effKey = Edh $ \_naExit !exit !ets -> resolveEdhFallback' ets effKey $ exitEdh ets exit prepareEffStoreM :: Edh EntityStore prepareEffStoreM = prepareEffStoreM' $ AttrByName edhEffectsMagicName prepareEffStoreM' :: AttrKey -> Edh EntityStore prepareEffStoreM' !magicKey = mEdh $ \ !exit !ets -> exitEdh ets exit =<< prepareEffStore' magicKey ets (edh'scope'entity $ contextScope $ edh'context ets) defineEffectM :: AttrKey -> EdhValue -> Edh () defineEffectM !key !val = Edh $ \_naExit !exit !ets -> do iopdInsert key val =<< prepareEffStore ets (edh'scope'entity $ contextScope $ edh'context ets) exitEdh ets exit () | Create an Edh channel newChanM :: Edh BChan newChanM = inlineSTM newBChan | Read an Edh channel readChanM :: BChan -> Edh EdhValue readChanM !chan = mEdh $ \ !exit -> readBChan chan exit | Write an Edh channel writeChanM :: BChan -> EdhValue -> Edh Bool writeChanM !chan !v = mEdh $ \ !exit -> writeBChan chan v exit * * | The ' STM ' action lifted into ' Edh ' monad newTVarEdh :: forall a. a -> Edh (TVar a) newTVarEdh = inlineSTM . newTVar # INLINE newTVarEdh # | The ' STM ' action lifted into ' Edh ' monad readTVarEdh :: forall a. TVar a -> Edh a readTVarEdh = inlineSTM . readTVar # INLINE readTVarEdh # | The ' STM ' action lifted into ' Edh ' monad writeTVarEdh :: forall a. TVar a -> a -> Edh () writeTVarEdh ref v = inlineSTM $ writeTVar ref v | The ' STM ' action lifted into ' Edh ' monad modifyTVarEdh' :: forall a. TVar a -> (a -> a) -> Edh () modifyTVarEdh' ref f = inlineSTM $ modifyTVar' ref f | The ' STM ' action lifted into ' Edh ' monad newEmptyTMVarEdh :: forall a. Edh (TMVar a) newEmptyTMVarEdh = inlineSTM newEmptyTMVar # INLINE newEmptyTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad newTMVarEdh :: forall a. a -> Edh (TMVar a) newTMVarEdh = inlineSTM . newTMVar | The ' STM ' action lifted into ' Edh ' monad readTMVarEdh :: forall a. TMVar a -> Edh a readTMVarEdh = inlineSTM . readTMVar # INLINE readTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad takeTMVarEdh :: forall a. TMVar a -> Edh a takeTMVarEdh = inlineSTM . takeTMVar # INLINE takeTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad putTMVarEdh :: forall a. TMVar a -> a -> Edh () putTMVarEdh ref v = inlineSTM $ putTMVar ref v # INLINE putTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad tryReadTMVarEdh :: forall a. TMVar a -> Edh (Maybe a) tryReadTMVarEdh = inlineSTM . tryReadTMVar # INLINE tryReadTMVarEdh # | The ' STM ' action lifted into ' Edh ' monad tryTakeTMVarEdh :: forall a. TMVar a -> Edh (Maybe a) tryTakeTMVarEdh = inlineSTM . tryTakeTMVar | The ' STM ' action lifted into ' Edh ' monad tryPutTMVarEdh :: forall a. TMVar a -> a -> Edh Bool tryPutTMVarEdh ref v = inlineSTM $ tryPutTMVar ref v | The ' IO ' action lifted into ' Edh ' monad newIORefEdh :: forall a. a -> Edh (IORef a) newIORefEdh = liftIO . newIORef | The ' IO ' action lifted into ' Edh ' monad readIORefEdh :: forall a. IORef a -> Edh a readIORefEdh = liftIO . readIORef | The ' IO ' action lifted into ' Edh ' monad writeIORefEdh :: forall a. IORef a -> a -> Edh () writeIORefEdh ref v = liftIO $ writeIORef ref v | ' newRUID\'STM ' lifted into ' Edh ' monad newRUID'Edh :: Edh RUID newRUID'Edh = inlineSTM newRUID'STM | The ' IOPD ' action lifted into ' Edh ' monad iopdCloneEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh (IOPD k v) iopdCloneEdh = inlineSTM . iopdClone # INLINE iopdCloneEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdTransformEdh :: forall k v v'. (Eq k, Hashable k, Deletable v, Deletable v') => (v -> v') -> IOPD k v -> Edh (IOPD k v') iopdTransformEdh trans = inlineSTM . iopdTransform trans # INLINE iopdTransformEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdEmptyEdh :: forall k v. (Eq k, Hashable k, Deletable v) => Edh (IOPD k v) iopdEmptyEdh = inlineSTM iopdEmpty | The ' IOPD ' action lifted into ' Edh ' monad iopdNullEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh Bool iopdNullEdh = inlineSTM . iopdNull # INLINE iopdNullEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdSizeEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh Int iopdSizeEdh = inlineSTM . iopdSize # INLINE iopdSizeEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdInsertEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> v -> IOPD k v -> Edh () iopdInsertEdh k v = inlineSTM . iopdInsert k v # INLINE iopdInsertEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdReserveEdh :: forall k v. (Eq k, Hashable k, Deletable v) => Int -> IOPD k v -> Edh () iopdReserveEdh moreCap = inlineSTM . iopdReserve moreCap # INLINE iopdReserveEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdUpdateEdh :: forall k v. (Eq k, Hashable k, Deletable v) => [(k, v)] -> IOPD k v -> Edh () iopdUpdateEdh ps = inlineSTM . iopdUpdate ps # INLINE iopdUpdateEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdLookupEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> IOPD k v -> Edh (Maybe v) iopdLookupEdh key = inlineSTM . iopdLookup key # INLINE iopdLookupEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdLookupDefaultEdh :: forall k v. (Eq k, Hashable k, Deletable v) => v -> k -> IOPD k v -> Edh v iopdLookupDefaultEdh v k = inlineSTM . iopdLookupDefault v k # INLINE iopdLookupDefaultEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdDeleteEdh :: forall k v. (Eq k, Hashable k, Deletable v) => k -> IOPD k v -> Edh () iopdDeleteEdh k = inlineSTM . iopdDelete k # INLINE iopdDeleteEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdKeysEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [k] iopdKeysEdh = inlineSTM . iopdKeys # INLINE iopdKeysEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdValuesEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [v] iopdValuesEdh = inlineSTM . iopdValues # INLINE iopdValuesEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdToListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [(k, v)] iopdToListEdh = inlineSTM . iopdToList | The ' IOPD ' action lifted into ' Edh ' monad iopdToReverseListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh [(k, v)] iopdToReverseListEdh = inlineSTM . iopdToReverseList | The ' IOPD ' action lifted into ' Edh ' monad iopdFromListEdh :: forall k v. (Eq k, Hashable k, Deletable v) => [(k, v)] -> Edh (IOPD k v) iopdFromListEdh = inlineSTM . iopdFromList # INLINE iopdFromListEdh # | The ' IOPD ' action lifted into ' Edh ' monad iopdSnapshotEdh :: forall k v. (Eq k, Hashable k, Deletable v) => IOPD k v -> Edh (OrderedDict k v) iopdSnapshotEdh = inlineSTM . iopdSnapshot # INLINE iopdSnapshotEdh # callM :: EdhValue -> [ArgSender] -> Edh EdhValue callM callee apkr = Edh $ \_naExit -> edhMakeCall callee apkr callM' :: EdhValue -> ArgsPack -> Edh EdhValue callM' callee apk = Edh $ \_naExit -> edhMakeCall' callee apk callMagicM :: Object -> AttrKey -> ArgsPack -> Edh EdhValue callMagicM obj magicKey apk = Edh $ \_naExit -> callMagicMethod obj magicKey apk | Run the specified ' Edh ' action in a nested new scope runNested :: Edh a -> Edh a runNested !act = do !ets <- edhThreadState let !scope = edh'frame'scope $ edh'ctx'tip $ edh'context ets !scope' <- inlineSTM $ newNestedScope scope runNestedIn scope' act | Run the specified ' Edh ' action in a specified scope runNestedIn :: Scope -> Edh a -> Edh a runNestedIn !scope !act = Edh $ \naExit exit ets -> do let !ctx = edh'context ets !tip = edh'ctx'tip ctx !tipNew <- newCallFrame scope $ edh'exe'src'loc tip let !etsNew = ets {edh'context = ctxNew} !ctxNew = ctx { edh'ctx'tip = tipNew, edh'ctx'stack = tip : edh'ctx'stack ctx, edh'ctx'genr'caller = Nothing, edh'ctx'match = true, edh'ctx'pure = False, edh'ctx'exp'target = Nothing, edh'ctx'eff'target = Nothing } unEdh act naExit (edhSwitchState ets . exit) etsNew | Switch to a custom context to run the specified ' Edh ' action inContext :: Context -> Edh a -> Edh a inContext !ctx !act = Edh $ \naExit exit !ets -> runEdhTx ets {edh'context = ctx} $ unEdh act naExit $ \result _ets -> exitEdh ets exit result evalSrcM :: Text -> Text -> Edh EdhValue evalSrcM !srcName !srcCode = Edh $ \_naExit -> evalEdh srcName srcCode evalSrcM' :: Text -> Int -> Text -> Edh EdhValue evalSrcM' !srcName !lineNo !srcCode = Edh $ \_naExit -> evalEdh' srcName lineNo srcCode evalExprDefiM :: ExprDefi -> Edh EdhValue evalExprDefiM !x = Edh $ \_naExit -> evalExprDefi x evalExprM :: Expr -> Edh EdhValue evalExprM !x = Edh $ \_naExit -> evalExpr x | Evaluate an infix operator with specified lhs / rhs expression evalInfixM :: OpSymbol -> Expr -> Expr -> Edh EdhValue evalInfixM !opSym !lhExpr !rhExpr = Edh $ \_naExit -> evalInfix opSym lhExpr rhExpr | Evaluate an infix operator with specified lhs / rhs expression evalInfixSrcM :: OpSymSrc -> ExprSrc -> ExprSrc -> Edh EdhValue evalInfixSrcM !opSym !lhExpr !rhExpr = Edh $ \_naExit -> evalInfixSrc opSym lhExpr rhExpr caseValueOfM :: EdhValue -> ExprDefi -> Edh EdhValue caseValueOfM !matchTgtVal !x = Edh $ \_naExit -> edhCaseValueOf matchTgtVal x newSandboxM :: Edh Scope newSandboxM = Edh $ \_naExit !exit !ets -> newSandbox ets >>= exitEdh ets exit mkSandboxM :: Scope -> Edh Scope mkSandboxM !origScope = Edh $ \_naExit !exit !ets -> do let !world = edh'prog'world $ edh'thread'prog ets !origProc = edh'scope'proc origScope !sbProc = origProc {edh'procedure'lexi = edh'world'sandbox world} exitEdh ets exit origScope {edh'scope'proc = sbProc} mkObjSandboxM :: Object -> Edh Scope mkObjSandboxM !obj = Edh $ \_naExit !exit !ets -> do mkObjSandbox ets obj $ exitEdh ets exit runInSandboxM :: forall r. Scope -> Edh r -> Edh r runInSandboxM !sandbox !act = Edh $ \_naExit !exit !ets -> do !tipFrame <- newCallFrame sandbox (SrcLoc (SrcDoc "<sandbox>") zeroSrcRange) let !ctxPriv = edh'context ets !etsSandbox = ets { edh'context = ctxPriv { edh'ctx'tip = tipFrame, edh'ctx'stack = edh'ctx'tip ctxPriv : edh'ctx'stack ctxPriv } } runEdh etsSandbox act $ \ !result _ets -> exitEdh ets exit result edhPrettyQty :: Decimal -> UnitSpec -> Edh Text edhPrettyQty q u = edhQuantity q u >>= \case Left num -> return $ T.pack $ show num Right qty -> edhReduceQtyNumber qty >>= \(Quantity q' u') -> return $ T.pack $ D.showDecimalLimited 2 q' <> show u' edhQuantity :: Decimal -> UnitSpec -> Edh (Either Decimal Quantity) edhQuantity q uomSpec = mEdh $ \exit ets -> resolveQuantity ets q uomSpec $ exitEdh ets exit edhReduceQtyNumber :: Quantity -> Edh Quantity edhReduceQtyNumber qty = edhReduceQtyNumber' qty <|> return qty edhReduceQtyNumber' :: Quantity -> Edh Quantity edhReduceQtyNumber' qty = mEdh' $ \naExit exit -> reduceQtyNumber qty (exitEdhTx exit) (naExit "unable to reduce quantity") edhObjStrM :: Object -> Edh Text edhObjStrM !o = Edh $ \_naExit !exit !ets -> edhObjStr ets o $ exitEdh ets exit edhValueStrM :: EdhValue -> Edh Text edhValueStrM !v = Edh $ \_naExit !exit !ets -> edhValueStr ets v $ exitEdh ets exit edhObjReprM :: Object -> Edh Text edhObjReprM !o = Edh $ \_naExit !exit !ets -> edhObjRepr ets o $ exitEdh ets exit edhValueReprM :: EdhValue -> Edh Text edhValueReprM !v = Edh $ \_naExit !exit !ets -> edhValueRepr ets v $ exitEdh ets exit edhObjDescM :: Object -> Edh Text edhObjDescM !o = Edh $ \_naExit !exit !ets -> edhObjDesc ets o $ exitEdh ets exit edhObjDescM' :: Object -> KwArgs -> Edh Text edhObjDescM' !o !kwargs = Edh $ \_naExit !exit !ets -> edhObjDesc' ets o kwargs $ exitEdh ets exit edhValueDescM :: EdhValue -> Edh Text edhValueDescM !v = Edh $ \_naExit !exit !ets -> edhValueDesc ets v $ exitEdh ets exit edhSimpleDescM :: EdhValue -> Edh Text edhSimpleDescM !v = Edh $ \_naExit !exit !ets -> edhSimpleDesc ets v $ exitEdh ets exit edhValueNullM :: EdhValue -> Edh Bool edhValueNullM !v = Edh $ \_naExit !exit !ets -> edhValueNull ets v $ exitEdh ets exit edhValueJsonM :: EdhValue -> Edh Text edhValueJsonM !v = Edh $ \_naExit !exit !ets -> edhValueJson ets v $ exitEdh ets exit | Convert an @Edh@ value to its BLOB form , alternative is requested if not edhValueBlobM :: EdhValue -> Edh B.ByteString edhValueBlobM !v = Edh $ \_naExit !exit !ets -> edhValueBlob ets v $ exitEdh ets exit | Convert an @Edh@ value to its BLOB form , ' Nothing ' is returned if not edhValueBlobM' :: EdhValue -> Edh (Maybe B.ByteString) edhValueBlobM' !v = Edh $ \_naExit !exit !ets -> edhValueBlob' ets v (exitEdh ets exit Nothing) $ exitEdh ets exit . Just Clone a composite object with one of its object instance ` mutObj ` mutated mutCloneObjectM :: Object -> Object -> ObjectStore -> Edh Object mutCloneObjectM !endObj !mutObj !newStore = Edh $ \_naExit !exit !ets -> edhMutCloneObj ets endObj mutObj newStore $ exitEdh ets exit Clone a composite object with one of its object instance ` mutObj ` mutated mutCloneHostObjectM :: forall v. (Eq v, Hashable v, Typeable v) => Object -> Object -> v -> Edh Object mutCloneHostObjectM !endObj !mutObj = mutCloneObjectM endObj mutObj . HostStore . wrapHostValue Clone a composite object with one of its object instance ` mutObj ` mutated mutCloneArbiHostObjectM :: forall v. (Typeable v) => Object -> Object -> v -> Edh Object mutCloneArbiHostObjectM !endObj !mutObj !v = mutCloneObjectM endObj mutObj =<< pinAndStoreHostValue v parseEdhIndexM :: EdhValue -> Edh (Either ErrMessage EdhIndex) parseEdhIndexM !val = Edh $ \_naExit !exit !ets -> parseEdhIndex ets val $ exitEdh ets exit | Regulate an interger index against the actual length , similar to Python , regulateEdhIndexM :: Int -> Int -> Edh Int regulateEdhIndexM !len !idx = if posIdx < 0 || posIdx >= len then throwEdhM EvalError $ "index out of bounds: " <> T.pack (show idx) <> " vs " <> T.pack (show len) else return posIdx where !posIdx = then idx + len else idx | Regulate an integer slice against the actual length , similar to Python , regulateEdhSliceM :: Int -> (Maybe Int, Maybe Int, Maybe Int) -> Edh (Int, Int, Int) regulateEdhSliceM !len !slice = Edh $ \_naExit !exit !ets -> regulateEdhSlice ets len slice $ exitEdh ets exit | Throw a general exception from an ' Edh ' action throwHostM :: Exception e => e -> Edh a throwHostM = inlineSTM . throwSTM # INLINE throwHostM # | Pin an arbitrary Haskell value , to have a designated identity pinHostValueM :: forall v. (Typeable v) => v -> Edh HostValue pinHostValueM = inlineSTM . pinHostValue storeHostValue :: forall v. (Eq v, Hashable v, Typeable v) => v -> ObjectStore storeHostValue v = HostStore $ wrapHostValue v pinAndStoreHostValue :: forall v. (Typeable v) => v -> Edh ObjectStore pinAndStoreHostValue v = inlineSTM $ HostStore <$> pinHostValue v | Wrap an identifiable value as an @Edh@ object wrapM :: forall v. (Eq v, Hashable v, Typeable v) => v -> Edh Object wrapM t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ edhWrapValue $ wrapHostValue t | Wrap an identifiable value as an @Edh@ object , with custom repr wrapM' :: forall v. (Eq v, Hashable v, Typeable v) => Text -> v -> Edh Object wrapM' !repr t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ edhWrapValue $ wrapHostValue t | Wrap an arbitrary value as an @Edh@ object wrapArbiM :: forall v. (Typeable v) => v -> Edh Object wrapArbiM t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ pinHostValue t >>= edhWrapValue | Wrap an arbitrary value as an @Edh@ object , with custom repr wrapArbiM' :: forall v. (Typeable v) => Text -> v -> Edh Object wrapArbiM' !repr t = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ pinHostValue t >>= edhWrapValue | Wrap an arbitrary value as an @Edh@ object wrapHostM :: HostValue -> Edh Object wrapHostM !dd = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world Nothing inlineSTM $ edhWrapValue dd | Wrap an arbitrary value as an @Edh@ object , with custom repr wrapHostM' :: Text -> HostValue -> Edh Object wrapHostM' !repr !dd = do !ets <- edhThreadState let world = edh'prog'world $ edh'thread'prog ets edhWrapValue = edh'value'wrapper world (Just repr) inlineSTM $ edhWrapValue dd | Wrap the specified scope as an Edh object wrapScopeM :: Scope -> Edh Object wrapScopeM s = Edh $ \_naExit !exit !ets -> do let !world = edh'prog'world $ edh'thread'prog ets edh'scope'wrapper world s >>= exitEdh ets exit | Create an Edh host object from the specified class and host data createHostObjectM :: forall v. (Eq v, Hashable v, Typeable v) => Object -> v -> Edh Object createHostObjectM !clsObj !d = createHostObjectM' clsObj (wrapHostValue d) [] | Create an Edh host object from the specified class , host storage data and createHostObjectM' :: Object -> HostValue -> [Object] -> Edh Object createHostObjectM' !clsObj !hsd !supers = do !ss <- newTVarEdh supers return $ Object (HostStore hsd) clsObj ss | Create an Edh host object from the specified class and host data createArbiHostObjectM :: forall v. (Typeable v) => Object -> v -> Edh Object createArbiHostObjectM !clsObj !v = createArbiHostObjectM' clsObj v [] | Create an Edh host object from the specified class and host data createArbiHostObjectM' :: forall v. (Typeable v) => Object -> v -> [Object] -> Edh Object createArbiHostObjectM' !clsObj !v !supers = do !hv <- pinHostValueM v createHostObjectM' clsObj hv supers mkEdhSymbol :: Text -> Edh Symbol mkEdhSymbol !bornName = inlineSTM $ mkSymbol bornName | Wrap an arguments - pack taking @'Edh ' ' EdhValue'@ action as an @Edh@ mkEdhProc :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh EdhValue mkEdhProc !vc !nm (!p, _args) = do !ets <- edhThreadState !u <- newRUID'Edh return $ EdhProcedure ( vc ProcDefi { edh'procedure'ident = u, edh'procedure'name = AttrByName nm, edh'procedure'lexi = contextScope $ edh'context ets, edh'procedure'doc = NoDocCmt, edh'procedure'decl = HostDecl $ \apk -> unEdh (p apk) rptEdhNotApplicable } ) Nothing mkEdhClass :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh Object mkEdhClass !clsName !allocator !superClasses !clsBody = do !ets <- edhThreadState !classStore <- inlineSTM iopdEmpty !idCls <- newRUID'Edh !ssCls <- newTVarEdh superClasses !mroCls <- newTVarEdh [] let !scope = contextScope $ edh'context ets !metaClassObj = edh'obj'class $ edh'obj'class $ edh'scope'this $ rootScopeOf scope !clsProc = ProcDefi idCls (AttrByName clsName) scope NoDocCmt (HostDecl fakeHostProc) !cls = Class clsProc classStore allocator' mroCls !clsObj = Object (ClassStore cls) metaClassObj ssCls !clsScope = scope { edh'scope'entity = classStore, edh'scope'this = clsObj, edh'scope'that = clsObj, edh'scope'proc = clsProc, edh'effects'stack = [] } runNestedIn clsScope clsBody !mroInvalid <- inlineSTM $ fillClassMRO cls superClasses unless (T.null mroInvalid) $ throwEdhM UsageError mroInvalid return clsObj where fakeHostProc :: ArgsPack -> EdhHostProc fakeHostProc _ !exit = exitEdhTx exit nil allocator' :: ArgsPack -> EdhObjectAllocator allocator' apk ctorExit ets = unEdh (allocator apk) rptEdhNotApplicable (\oStore _ets -> ctorExit oStore) ets defEdhArt :: AttrName -> EdhValue -> Edh () defEdhArt nm = defEdhArt' (AttrByName nm) defEdhArt' :: AttrKey -> EdhValue -> Edh () defEdhArt' key val = do !ets <- edhThreadState let !ctx = edh'context ets esDefs = edh'scope'entity $ contextScope ctx unless (edh'ctx'pure ctx) $ inlineSTM $ iopdInsert key val esDefs case edh'ctx'exp'target ctx of Nothing -> pure () Just !esExps -> inlineSTM $ iopdInsert key val esExps defEdhSymbol :: AttrName -> Edh Symbol defEdhSymbol name = do sym <- mkEdhSymbol ("@" <> name) defEdhArt name $ EdhSymbol sym return sym defEdhProc_ :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh () defEdhProc_ !vc !nm !hp = void $ defEdhProc vc nm hp defEdhProc :: (ProcDefi -> EdhProcDefi) -> AttrName -> (ArgsPack -> Edh EdhValue, ArgsReceiver) -> Edh EdhValue defEdhProc !vc !nm !hp = do !pv <- mkEdhProc vc nm hp defEdhArt nm pv return pv defEdhClass_ :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh () defEdhClass_ !clsName !allocator !superClasses !clsBody = void $ defEdhClass clsName allocator superClasses clsBody defEdhClass :: AttrName -> (ArgsPack -> Edh ObjectStore) -> [Object] -> Edh () -> Edh Object defEdhClass !clsName !allocator !superClasses !clsBody = do clsObj <- mkEdhClass clsName allocator superClasses clsBody defEdhArt clsName (EdhObject clsObj) return clsObj * * Edh Error from STM throwEdhSTM :: EdhThreadState -> EdhErrorTag -> ErrMessage -> STM a throwEdhSTM ets tag msg = throwEdhSTM' ets tag msg [] throwEdhSTM' :: EdhThreadState -> EdhErrorTag -> ErrMessage -> [(AttrKey, EdhValue)] -> STM a throwEdhSTM' ets tag msg details = do let !edhErr = EdhError tag msg errDetails $ getEdhErrCtx 0 ets !edhWrapException = edh'exception'wrapper (edh'prog'world $ edh'thread'prog ets) !errDetails = case details of [] -> toDyn nil _ -> toDyn $ EdhArgsPack $ ArgsPack [] $ odFromList details edhWrapException (Just ets) (toException edhErr) >>= \ !exo -> edhThrow ets $ EdhObject exo * * The type class for Edh scriptability enabled monads class (MonadIO m, Monad m) => MonadEdh m where | Lift an ' Edh ' action instances can mutually lift eachother with ' Edh ' liftEdh :: Edh a -> m a | Extract the ' EdhThreadState ' from current @Edh@ thread edhThreadState :: m EdhThreadState edhProgramState :: m EdhProgState edhProgramState = edh'thread'prog <$> edhThreadState throwEdhM :: EdhErrorTag -> ErrMessage -> m a throwEdhM tag msg = throwEdhM' tag msg [] throwEdhM' :: EdhErrorTag -> ErrMessage -> [(AttrKey, EdhValue)] -> m a | Perform the specified ' STM ' action in a new ' atomically ' transaction liftSTM :: STM a -> m a * * The EIO Monad | Edh aware ( or scriptability Enhanced ) IO Monad High density of ' liftIO 's from ' Edh ' monad means terrible performance machine performance can be much better - ' liftIO 's from within ' EIO ' are You would want go deep into plain ' IO ' monad , but only back to ' EIO ' , you CAVEAT : During either ' EIO ' or plain ' IO ' , even though lifted from an ' Edh ' behavior with the ' Edh ' monad or ' STM ' monad by ' liftSTM ' . newtype EIO a = EIO | Run an ' EIO ' action from within an @'IO ' ( ) @ action CAVEAT : * You would better make sure the calling thread owns the ' EdhThreadState ' , or the 1st transaction will be carried out in the ' EdhThreadState ' 's owner thread , which is ridiculous . Even worse ' STM ' transactions will cease to happen , and your continuation never wrong . Unless interleaved " scripting threads " sharing the Note : This call finishes as soon with the 1st ' STM ' transaction within the specified ' Edh ' action , the continuation can be resumed rather later after many subsequent ' STM ' transactions performed , so runEIO :: EdhThreadState -> (a -> IO ()) -> IO () } instance MonadEdh EIO where liftEdh act = EIO $ \ets exit -> atomically $ runEdh ets act $ edhContIO . exit edhThreadState = EIO $ \ets exit -> exit ets throwEdhM' tag msg details = EIO $ \ets _exit -> atomically $ throwEdhSTM' ets tag msg details liftSTM = liftIO . atomically | Lift an ' EIO ' action from an ' Edh ' action This is some similar to what @unliftio@ library does , yet better here ' Edh ' and ' EIO ' can mutually lift eachother , CAVEAT : An @ai@ block as by the scripting code will be broken , thus an liftEIO :: EIO a -> Edh a liftEIO act = Edh $ \_naExit exit ets -> runEdhTx ets $ edhContIO $ runEIO act ets $ atomically . exitEdh ets exit instance Functor EIO where fmap f c = EIO $ \ets exit -> runEIO c ets $ exit . f # INLINE fmap # instance Applicative EIO where pure a = EIO $ \_ets exit -> exit a # INLINE pure # (<*>) = ap instance Monad EIO where return = pure # INLINE return # m >>= k = EIO $ \ets exit -> runEIO m ets $ \a -> runEIO (k a) ets exit instance MonadFail EIO where fail reason = throwEdhM EvalError $ T.pack reason # INLINE fail # instance MonadIO EIO where liftIO act = EIO $ \_ets exit -> act >>= exit # INLINE liftIO # * * EIO Monad Utilities | Extract the ' EdhThreadState ' from current @Edh@ thread eioThreadState :: EIO EdhThreadState eioThreadState = EIO $ \ets exit -> exit ets # INLINE eioThreadState # eioProgramState :: EIO EdhProgState eioProgramState = EIO $ \ets exit -> exit (edh'thread'prog ets) # INLINE eioProgramState # | Shorthand for @'liftIO ' . ' atomically'@ atomicallyEIO :: STM a -> EIO a atomicallyEIO = liftIO . atomically # INLINE atomicallyEIO # | The ' IO ' action lifted into ' EIO ' monad newTVarEIO :: forall a. a -> EIO (TVar a) newTVarEIO = liftIO . newTVarIO # INLINE newTVarEIO # | The ' IO ' action lifted into ' EIO ' monad readTVarEIO :: forall a. TVar a -> EIO a readTVarEIO = liftIO . readTVarIO # INLINE readTVarEIO # | The ' STM ' action lifted into ' EIO ' monad writeTVarEIO :: forall a. TVar a -> a -> EIO () writeTVarEIO ref v = atomicallyEIO $ writeTVar ref v # INLINE writeTVarEIO # | The ' STM ' action lifted into ' EIO ' monad modifyTVarEIO' :: forall a. TVar a -> (a -> a) -> EIO () modifyTVarEIO' ref f = atomicallyEIO $ modifyTVar' ref f | The ' STM ' action lifted into ' EIO ' monad swapTVarEIO :: forall a. TVar a -> a -> EIO a swapTVarEIO ref a = atomicallyEIO $ swapTVar ref a # INLINE swapTVarEIO # | The ' IO ' action lifted into ' EIO ' monad newEmptyTMVarEIO :: forall a. EIO (TMVar a) newEmptyTMVarEIO = liftIO newEmptyTMVarIO # INLINE newEmptyTMVarEIO # | The ' IO ' action lifted into ' EIO ' monad newTMVarEIO :: forall a. a -> EIO (TMVar a) newTMVarEIO = liftIO . newTMVarIO # INLINE newTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad readTMVarEIO :: forall a. TMVar a -> EIO a readTMVarEIO = atomicallyEIO . readTMVar # INLINE readTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad takeTMVarEIO :: forall a. TMVar a -> EIO a takeTMVarEIO = atomicallyEIO . takeTMVar # INLINE takeTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad putTMVarEIO :: forall a. TMVar a -> a -> EIO () putTMVarEIO ref v = atomicallyEIO $ putTMVar ref v # INLINE putTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryReadTMVarEIO :: forall a. TMVar a -> EIO (Maybe a) tryReadTMVarEIO = atomicallyEIO . tryReadTMVar # INLINE tryReadTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryTakeTMVarEIO :: forall a. TMVar a -> EIO (Maybe a) tryTakeTMVarEIO = atomicallyEIO . tryTakeTMVar # INLINE tryTakeTMVarEIO # | The ' STM ' action lifted into ' EIO ' monad tryPutTMVarEIO :: forall a. TMVar a -> a -> EIO Bool tryPutTMVarEIO ref v = atomicallyEIO $ tryPutTMVar ref v # INLINE tryPutTMVarEIO # | The ' IO ' action lifted into ' EIO ' monad newIORefEIO :: forall a. a -> EIO (IORef a) newIORefEIO = liftIO . newIORef # INLINE newIORefEIO # | The ' IO ' action lifted into ' EIO ' monad readIORefEIO :: forall a. IORef a -> EIO a readIORefEIO = liftIO . readIORef # INLINE readIORefEIO # | The ' IO ' action lifted into ' EIO ' monad writeIORefEIO :: forall a. IORef a -> a -> EIO () writeIORefEIO ref v = liftIO $ writeIORef ref v # INLINE writeIORefEIO # | The ' IO ' action lifted into ' EIO ' monad newUniqueEIO :: EIO Unique newUniqueEIO = liftIO newUnique # INLINE newUniqueEIO # * * Exceptions with EIO | Throw a general exception from an ' EIO ' action throwHostEIO :: Exception e => e -> EIO a throwHostEIO = liftIO . throwIO
09a9879a5c5cd47bd7e95475197835332b574b1e177b43dbb98b4f96528bd11f
jordanthayer/ocaml-search
histogram_dataset.ml
* Histograms show an approximate distribution given a set of floating point values . @author jtd7 @since 2010 - 05 - 24 floating point values. @author jtd7 @since 2010-05-24 *) open Num_by_num_dataset open Drawing open Geometry let f_compare a b = let v = a -. b in if v < 0. then ~-1 else if v > 0. then 1 else 0 (** The length of the line drawn in the legend. *) let line_legend_length = Length.Cm 0.75 let default_line = { default_line_style with line_width = Length.Pt 1. } * value at the left edge of [ i ] in [ h ] let bin_start ~bin_min ~bin_width index = bin_min +. (bin_width *. (float index)) * Value at the right edge of [ i ] in [ h ] . This is not implemented interms of bin_start because ( even when inlined ) OCaml boxes the return value of bin_start . implemented interms of bin_start because (even when inlined) OCaml boxes the return value of bin_start. *) let bin_end ~bin_min ~bin_width index = bin_min +. (bin_width *. (float (index + 1))) (** the index of the bin that should contain [value]. Note that any value outside the range of representable integers, such as [infinity], may yield a garbage value, such as 0! If you might pass such a value, test before calling! (This routine is intended to be simple and fast.) *) let bucket ~bin_min ~bin_width value = truncate ((value -. bin_min) /. bin_width) (** [get_bin_width bin_width ~min_value ~max_value count] gets the width to use for each bin. *) let get_bin_width bin_width ~min_value ~max_value count = match bin_width with | None -> let nbins = sqrt count in This is a common default bin number ( used by Excel ) . (max_value -. min_value) /. nbins | Some w -> w * [ normalize_bins bins ] normalizes the bins to sum to 1 . let normalize_bins bins = let sum = Array.fold_left (+.) 0. bins in let n = Array.length bins in for i = 0 to n - 1 do bins.(i) <- bins.(i) /. sum; done (** [bins_of_points ?normalize w counts] makes a set of bins given a set of [(value, count)] pairs. *) let bins_of_points ?(normalize=false) bin_width pts = let count = Array.fold_left (fun s p -> s +. p.y) 0. pts in let min_value, max_value = Array.fold_left (fun (min, max) p -> let v = p.x in let min' = if v < min then v else min in let max' = if v > max then v else max in min', max') (infinity, neg_infinity) pts in let range = max_value -. min_value in let bin_width = get_bin_width bin_width ~min_value ~max_value count in let bin_count = max (truncate (ceil (range /. bin_width))) 1 in let ave_per_bin = count /. (float bin_count) in let bin_min = min_value -. (bin_width /. ave_per_bin) in let bin_max = bin_end ~bin_min ~bin_width bin_count in let bins = Array.create (bin_count + 1) 0. in let max_weight = ref 0. in Array.iter (fun p -> let v = p.x and c = p.y in let bi = bucket ~bin_min ~bin_width v in let wt = bins.(bi) +. c in bins.(bi) <- wt; if wt > !max_weight then max_weight := wt) pts; if normalize then normalize_bins bins; !max_weight, bin_min, bin_max, bin_width, bins (** [make_bins ?normalize bin_width values] creates an array of bins. *) let make_bins ?(normalize=false) bin_width values = bins_of_points ~normalize bin_width (Array.map (fun v -> point v 1.) values) class histogram_dataset dashes ?(normalize=false) ?(line_width=Length.Pt 1.) ?(bg_color=gray) ?name max_weight bin_min bin_max bin_width bins = object(self) inherit dataset ?name () val style = { line_color = black; line_dashes = dashes; line_width = line_width; } method dimensions = rectangle ~x_min:bin_min ~x_max:bin_max ~y_min:0. ~y_max:max_weight method mean_y_value _ = let s, n = Array.fold_left (fun (s, n) y -> s +. y, n + 1) (0., 0) bins in s /. (float n), n method residual ctx ~src ~dst = zero_rectangle method draw ctx ~src ~dst = let tr_rect = rectangle_transform ~src ~dst in let tr_pt = point_transform ~src ~dst in Array.iteri (fun index count -> if count > 0. then begin let y_max = count and x_min = bin_start ~bin_min ~bin_width index and x_max = bin_end ~bin_min ~bin_width index in let r = rectangle ~x_min ~x_max ~y_min:0. ~y_max in let outline = [ point x_min 0.; point x_min y_max; point x_max y_max; point x_max 0.; point x_min 0.; ] in begin match clip_rectangle ~box:src ~r with | Some r -> fill_rectangle ctx ~color:bg_color (tr_rect r) | None -> () end; draw_line ctx ~box:src ~tr:tr_pt ~style outline; end) bins method draw_legend ctx ~x ~y = let half_length = (ctx.units line_legend_length) /. 2. and quarter_length = (ctx.units line_legend_length) /. 4. in let x_min = x -. half_length and x_max = x +. half_length and y_min = y -. quarter_length and y_max = y +. quarter_length in let r = rectangle ~x_min ~x_max ~y_min:0. ~y_max in let outline = [ point x_min y_min; point x_min y_max; point x_max y_max; point x_max y_min; point x_min y_min;] in fill_rectangle ctx ~color:bg_color r; draw_line ctx ~style outline method legend_dimensions ctx = (ctx.units line_legend_length), (max ((ctx.units line_legend_length) /. 4.) (ctx.units line_width)) method avg_slope = nan end * [ values_histogram_dataset dashes ? normalize ? line_width ? bg_color ? ? name values ] makes a histogram . ?bin_width ?name values] makes a histogram. *) let values_histogram_dataset dashes ?normalize ?line_width ?bg_color ?bin_width ?name values = let max_weight, bin_min, bin_max, bin_width, bins = make_bins ?normalize bin_width values in new histogram_dataset dashes ?normalize ?line_width ?bg_color ?name max_weight bin_min bin_max bin_width bins let histogram_dataset = values_histogram_dataset * [ points_histogram_dataset dashes ? normalize ? line_width ? bg_color ? ? name points ] makes a histogram given an array of points . ?bin_width ?name points] makes a histogram given an array of points. *) let points_histogram_dataset dashes ?normalize ?line_width ?bg_color ?bin_width ?name points = let max_weight, bin_min, bin_max, bin_width, bins = bins_of_points ?normalize bin_width points in new histogram_dataset dashes ?normalize ?line_width ?bg_color ?name max_weight bin_min bin_max bin_width bins EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/spt/src/num_by_num/histogram_dataset.ml
ocaml
* The length of the line drawn in the legend. * the index of the bin that should contain [value]. Note that any value outside the range of representable integers, such as [infinity], may yield a garbage value, such as 0! If you might pass such a value, test before calling! (This routine is intended to be simple and fast.) * [get_bin_width bin_width ~min_value ~max_value count] gets the width to use for each bin. * [bins_of_points ?normalize w counts] makes a set of bins given a set of [(value, count)] pairs. * [make_bins ?normalize bin_width values] creates an array of bins.
* Histograms show an approximate distribution given a set of floating point values . @author jtd7 @since 2010 - 05 - 24 floating point values. @author jtd7 @since 2010-05-24 *) open Num_by_num_dataset open Drawing open Geometry let f_compare a b = let v = a -. b in if v < 0. then ~-1 else if v > 0. then 1 else 0 let line_legend_length = Length.Cm 0.75 let default_line = { default_line_style with line_width = Length.Pt 1. } * value at the left edge of [ i ] in [ h ] let bin_start ~bin_min ~bin_width index = bin_min +. (bin_width *. (float index)) * Value at the right edge of [ i ] in [ h ] . This is not implemented interms of bin_start because ( even when inlined ) OCaml boxes the return value of bin_start . implemented interms of bin_start because (even when inlined) OCaml boxes the return value of bin_start. *) let bin_end ~bin_min ~bin_width index = bin_min +. (bin_width *. (float (index + 1))) let bucket ~bin_min ~bin_width value = truncate ((value -. bin_min) /. bin_width) let get_bin_width bin_width ~min_value ~max_value count = match bin_width with | None -> let nbins = sqrt count in This is a common default bin number ( used by Excel ) . (max_value -. min_value) /. nbins | Some w -> w * [ normalize_bins bins ] normalizes the bins to sum to 1 . let normalize_bins bins = let sum = Array.fold_left (+.) 0. bins in let n = Array.length bins in for i = 0 to n - 1 do bins.(i) <- bins.(i) /. sum; done let bins_of_points ?(normalize=false) bin_width pts = let count = Array.fold_left (fun s p -> s +. p.y) 0. pts in let min_value, max_value = Array.fold_left (fun (min, max) p -> let v = p.x in let min' = if v < min then v else min in let max' = if v > max then v else max in min', max') (infinity, neg_infinity) pts in let range = max_value -. min_value in let bin_width = get_bin_width bin_width ~min_value ~max_value count in let bin_count = max (truncate (ceil (range /. bin_width))) 1 in let ave_per_bin = count /. (float bin_count) in let bin_min = min_value -. (bin_width /. ave_per_bin) in let bin_max = bin_end ~bin_min ~bin_width bin_count in let bins = Array.create (bin_count + 1) 0. in let max_weight = ref 0. in Array.iter (fun p -> let v = p.x and c = p.y in let bi = bucket ~bin_min ~bin_width v in let wt = bins.(bi) +. c in bins.(bi) <- wt; if wt > !max_weight then max_weight := wt) pts; if normalize then normalize_bins bins; !max_weight, bin_min, bin_max, bin_width, bins let make_bins ?(normalize=false) bin_width values = bins_of_points ~normalize bin_width (Array.map (fun v -> point v 1.) values) class histogram_dataset dashes ?(normalize=false) ?(line_width=Length.Pt 1.) ?(bg_color=gray) ?name max_weight bin_min bin_max bin_width bins = object(self) inherit dataset ?name () val style = { line_color = black; line_dashes = dashes; line_width = line_width; } method dimensions = rectangle ~x_min:bin_min ~x_max:bin_max ~y_min:0. ~y_max:max_weight method mean_y_value _ = let s, n = Array.fold_left (fun (s, n) y -> s +. y, n + 1) (0., 0) bins in s /. (float n), n method residual ctx ~src ~dst = zero_rectangle method draw ctx ~src ~dst = let tr_rect = rectangle_transform ~src ~dst in let tr_pt = point_transform ~src ~dst in Array.iteri (fun index count -> if count > 0. then begin let y_max = count and x_min = bin_start ~bin_min ~bin_width index and x_max = bin_end ~bin_min ~bin_width index in let r = rectangle ~x_min ~x_max ~y_min:0. ~y_max in let outline = [ point x_min 0.; point x_min y_max; point x_max y_max; point x_max 0.; point x_min 0.; ] in begin match clip_rectangle ~box:src ~r with | Some r -> fill_rectangle ctx ~color:bg_color (tr_rect r) | None -> () end; draw_line ctx ~box:src ~tr:tr_pt ~style outline; end) bins method draw_legend ctx ~x ~y = let half_length = (ctx.units line_legend_length) /. 2. and quarter_length = (ctx.units line_legend_length) /. 4. in let x_min = x -. half_length and x_max = x +. half_length and y_min = y -. quarter_length and y_max = y +. quarter_length in let r = rectangle ~x_min ~x_max ~y_min:0. ~y_max in let outline = [ point x_min y_min; point x_min y_max; point x_max y_max; point x_max y_min; point x_min y_min;] in fill_rectangle ctx ~color:bg_color r; draw_line ctx ~style outline method legend_dimensions ctx = (ctx.units line_legend_length), (max ((ctx.units line_legend_length) /. 4.) (ctx.units line_width)) method avg_slope = nan end * [ values_histogram_dataset dashes ? normalize ? line_width ? bg_color ? ? name values ] makes a histogram . ?bin_width ?name values] makes a histogram. *) let values_histogram_dataset dashes ?normalize ?line_width ?bg_color ?bin_width ?name values = let max_weight, bin_min, bin_max, bin_width, bins = make_bins ?normalize bin_width values in new histogram_dataset dashes ?normalize ?line_width ?bg_color ?name max_weight bin_min bin_max bin_width bins let histogram_dataset = values_histogram_dataset * [ points_histogram_dataset dashes ? normalize ? line_width ? bg_color ? ? name points ] makes a histogram given an array of points . ?bin_width ?name points] makes a histogram given an array of points. *) let points_histogram_dataset dashes ?normalize ?line_width ?bg_color ?bin_width ?name points = let max_weight, bin_min, bin_max, bin_width, bins = bins_of_points ?normalize bin_width points in new histogram_dataset dashes ?normalize ?line_width ?bg_color ?name max_weight bin_min bin_max bin_width bins EOF
e35fdd008fdfa947c750d77c48cbb5109e62fba8b836f4dac00ce58a7bf06864
jherrlin/guitar-theory-training
drills.cljs
(ns v2.se.jherrlin.music-theory.webapp.drills)
null
https://raw.githubusercontent.com/jherrlin/guitar-theory-training/8a5df5749c4a051653eb597936d528d35b54694d/src/v2/se/jherrlin/music_theory/webapp/drills.cljs
clojure
(ns v2.se.jherrlin.music-theory.webapp.drills)
8ff94aad0df2c1d8b7ba261889d3886b71974519a5d75b712353338cd2954848
sangkilc/ofuzz
misc.mli
(* ofuzz - ocaml fuzzing platform *) * miscellaneous @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) Copyright ( c ) 2014 , All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the < organization > nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS Copyright (c) 2014, Sang Kil Cha All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *) exception Overflow module AddrSet : Set.S with type elt = nativeint module AddrMap : Map.S with type key = nativeint module StringSet : Set.S with type elt = string module StringMap : Map.S with type key = string module IntMap : Map.S with type key = int module IntSet : Set.S with type elt = int (** Read lines from a file *) val readlines : string -> string list (** Exit with showing an error message *) val error_exit : string -> 'a (** Piping *) val (|>) : 'a -> ('a -> 'b) -> 'b (** Get file size *) val get_filesize : string -> int * Check if a program is accessible from the current cmdline val check_program_availability : string -> bool (** Obtain an absolute path of a binary by resolving PATH environment *) val get_abspath_for_bin : string -> string (** Unix.time() float to string *) val time_string : float -> string * Transform a relative path to an absolute path based on the CWD val to_abs : string -> string * Transform a command line to have an absolute program name ( the first arg ) based on the CWD based on the CWD *) val to_abs_cmds : string list -> string list * a file if it exists val rm_if_exists : string -> unit
null
https://raw.githubusercontent.com/sangkilc/ofuzz/ba53cc90cc06512eb90459a7159772d75ebe954f/src/misc.mli
ocaml
ofuzz - ocaml fuzzing platform * Read lines from a file * Exit with showing an error message * Piping * Get file size * Obtain an absolute path of a binary by resolving PATH environment * Unix.time() float to string
* miscellaneous @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) Copyright ( c ) 2014 , All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the < organization > nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS Copyright (c) 2014, Sang Kil Cha All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *) exception Overflow module AddrSet : Set.S with type elt = nativeint module AddrMap : Map.S with type key = nativeint module StringSet : Set.S with type elt = string module StringMap : Map.S with type key = string module IntMap : Map.S with type key = int module IntSet : Set.S with type elt = int val readlines : string -> string list val error_exit : string -> 'a val (|>) : 'a -> ('a -> 'b) -> 'b val get_filesize : string -> int * Check if a program is accessible from the current cmdline val check_program_availability : string -> bool val get_abspath_for_bin : string -> string val time_string : float -> string * Transform a relative path to an absolute path based on the CWD val to_abs : string -> string * Transform a command line to have an absolute program name ( the first arg ) based on the CWD based on the CWD *) val to_abs_cmds : string list -> string list * a file if it exists val rm_if_exists : string -> unit
b81cd391b509a2bc5589b5cdcfdad9d033a76ccd07854d27a9feb4cc2a9fcaf5
ucsd-progsys/nate
program_loading.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt Objective Caml port by and (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : program_loading.mli , v 1.3 1999/11/17 18:57:27 xleroy Exp $ (*** Debugging. ***) val debug_loading : bool ref (*** Load program ***) (* Function used for launching the program. *) val launching_func : (unit -> unit) ref val load_program : unit -> unit type launching_function = (unit -> unit) val loading_modes : (string * launching_function) list val set_launching_function : launching_function -> unit (** Connection **) val connection : Primitives.io_channel ref val connection_opened : bool ref
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/debugger/program_loading.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* ** Debugging. ** ** Load program ** Function used for launching the program. * Connection *
, projet Cristal , INRIA Rocquencourt Objective Caml port by and Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : program_loading.mli , v 1.3 1999/11/17 18:57:27 xleroy Exp $ val debug_loading : bool ref val launching_func : (unit -> unit) ref val load_program : unit -> unit type launching_function = (unit -> unit) val loading_modes : (string * launching_function) list val set_launching_function : launching_function -> unit val connection : Primitives.io_channel ref val connection_opened : bool ref
7666cc66a6609c056f0b0127f2f4be5a3bfbf4977c3604aa46efccf094bd341c
irfn/clojure-ocr
test.clj
(ns test (:use clojure.test)) (def tests [ 'test.string-ops 'test.ocr ]) (doseq [test tests] (require test)) (apply run-tests tests) (shutdown-agents)
null
https://raw.githubusercontent.com/irfn/clojure-ocr/c89da89031379a9c0367c68884caf4fcb40bb2da/test/test.clj
clojure
(ns test (:use clojure.test)) (def tests [ 'test.string-ops 'test.ocr ]) (doseq [test tests] (require test)) (apply run-tests tests) (shutdown-agents)
a2e774471c91d42572359aeaf5c11786d968b66da020b928bc832851b169f6bd
emqx/esockd
dtls_psk_client.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2019 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(dtls_psk_client). -export([ connect/0 , connect/1 , send/2 , recv/2 , recv/3 , user_lookup/3 ]). connect() -> connect(5000). connect(Port) -> {ok, Client} = ssl:connect({127, 0, 0, 1}, Port, opts()), Client. send(Client, Msg) -> ssl:send(Client, Msg). recv(Client, Len) -> ssl:recv(Client, Len). recv(Client, Len, Timeout) -> ssl:recv(Client, Len, Timeout). user_lookup(psk, ServerHint, _UserState = PSKs) -> ServerPskId = server_suggested_psk_id(ServerHint), ClientPsk = maps:get(ServerPskId, PSKs), io:format("ServerHint:~p, ServerSuggestedPSKID:~p, ClientPickedPSK: ~p~n", [ServerHint, ServerPskId, ClientPsk]), {ok, ClientPsk}. server_suggested_psk_id(ServerHint) -> [_, Psk] = binary:split(ServerHint, <<"plz_use_">>), Psk. opts() -> [{ssl_imp, new}, {active, false}, {verify, verify_none}, {versions, [dtlsv1]}, {protocol, dtls}, {ciphers, [{psk, aes_128_cbc, sha}]}, {psk_identity, "psk_b"}, {user_lookup_fun, {fun user_lookup/3, #{<<"psk_a">> => <<"shared_secret_a">>, <<"psk_b">> => <<"shared_secret_b">>}}}, {cb_info, {gen_udp, udp, udp_close, udp_error}} ].
null
https://raw.githubusercontent.com/emqx/esockd/9b959fc11a1c398a589892f335235be6c5b4a454/examples/dtls_psk/dtls_psk_client.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. --------------------------------------------------------------------
Copyright ( c ) 2019 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(dtls_psk_client). -export([ connect/0 , connect/1 , send/2 , recv/2 , recv/3 , user_lookup/3 ]). connect() -> connect(5000). connect(Port) -> {ok, Client} = ssl:connect({127, 0, 0, 1}, Port, opts()), Client. send(Client, Msg) -> ssl:send(Client, Msg). recv(Client, Len) -> ssl:recv(Client, Len). recv(Client, Len, Timeout) -> ssl:recv(Client, Len, Timeout). user_lookup(psk, ServerHint, _UserState = PSKs) -> ServerPskId = server_suggested_psk_id(ServerHint), ClientPsk = maps:get(ServerPskId, PSKs), io:format("ServerHint:~p, ServerSuggestedPSKID:~p, ClientPickedPSK: ~p~n", [ServerHint, ServerPskId, ClientPsk]), {ok, ClientPsk}. server_suggested_psk_id(ServerHint) -> [_, Psk] = binary:split(ServerHint, <<"plz_use_">>), Psk. opts() -> [{ssl_imp, new}, {active, false}, {verify, verify_none}, {versions, [dtlsv1]}, {protocol, dtls}, {ciphers, [{psk, aes_128_cbc, sha}]}, {psk_identity, "psk_b"}, {user_lookup_fun, {fun user_lookup/3, #{<<"psk_a">> => <<"shared_secret_a">>, <<"psk_b">> => <<"shared_secret_b">>}}}, {cb_info, {gen_udp, udp, udp_close, udp_error}} ].
171b37b09d90c110cb254b1d8e7492006b1c0d55ae8f441de22267dd6a66117b
tamarin-prover/tamarin-prover
SecretChannels.hs
# LANGUAGE PatternGuards # -- | Copyright : ( c ) 2019 < > -- License : GPL v3 (see LICENSE) -- Maintainer : < > Portability : GHC only -- -- Compute annotations for always-secret channels -- -- A channel is defined always-secret iff it correspond to a fresh variable -- only used as a channel identifier. For these channels, we can use a more -- efficient translation, as the adversary can never deduce then, and thus only -- a silent transition is possible. module Sapic.SecretChannels ( annotateSecretChannels ) where import Data.Set as S import Data.List as L import Sapic.Annotation import Sapic.Basetranslation import Theory import Theory.Sapic -- | Get all variables inside a term getTermVariables :: SapicTerm -> S.Set LVar getTermVariables ts = S.fromList $ L.map fst $ varOccurences $ toLNTerm ts -- | Get all variables that were never output getSecretChannels :: LProcess (ProcessAnnotation LVar) -> S.Set LVar -> S.Set LVar getSecretChannels (ProcessAction (New v) _ p) candidates = let c = S.insert (toLVar v) candidates in getSecretChannels p c getSecretChannels (ProcessAction (ChOut _ t2) _ p) candidates = let c = S.difference candidates (getTermVariables t2) in getSecretChannels p c getSecretChannels (ProcessAction (Insert _ t2) _ p) candidates = let c = S.difference candidates (getTermVariables t2) in getSecretChannels p c getSecretChannels (ProcessAction _ _ p) candidates = getSecretChannels p candidates getSecretChannels (ProcessNull _) candidates = candidates getSecretChannels (ProcessComb _ _ pl pr ) candidates = S.intersection c1 c2 where c1 = getSecretChannels pl candidates c2 = getSecretChannels pr candidates -- | For each input or output, if the variable is secret, we annotate the process annotateEachSecretChannels :: LProcess (ProcessAnnotation LVar) -> S.Set LVar -> LProcess (ProcessAnnotation LVar) annotateEachSecretChannels (ProcessNull an) _ = ProcessNull an annotateEachSecretChannels (ProcessComb comb an pl pr ) svars = ProcessComb comb an pl' pr' where pl' = annotateEachSecretChannels pl svars pr' = annotateEachSecretChannels pr svars annotateEachSecretChannels (ProcessAction ac an p) svars | (ChIn (Just t1) _ _) <- ac, Lit (Var v') <- viewTerm t1 , v <- toLVar v' = if S.member v svars then ProcessAction ac (an `mappend` annSecretChannel (AnVar v)) p' else ProcessAction ac an p' | (ChOut (Just t1) _) <- ac, Lit (Var v') <- viewTerm t1 , v <- toLVar v' = if S.member v svars then ProcessAction ac (an `mappend` annSecretChannel (AnVar v)) p' else ProcessAction ac an p' | otherwise = ProcessAction ac an p' where p'= annotateEachSecretChannels p svars annotateSecretChannels :: LProcess (ProcessAnnotation LVar) -> LProcess (ProcessAnnotation LVar) annotateSecretChannels anp = annotateEachSecretChannels anp svars where svars = getSecretChannels anp S.empty
null
https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/b14a9e06f20c36a4811944f9216d8826eaa68eab/lib/sapic/src/Sapic/SecretChannels.hs
haskell
| License : GPL v3 (see LICENSE) Compute annotations for always-secret channels A channel is defined always-secret iff it correspond to a fresh variable only used as a channel identifier. For these channels, we can use a more efficient translation, as the adversary can never deduce then, and thus only a silent transition is possible. | Get all variables inside a term | Get all variables that were never output | For each input or output, if the variable is secret, we annotate the process
# LANGUAGE PatternGuards # Copyright : ( c ) 2019 < > Maintainer : < > Portability : GHC only module Sapic.SecretChannels ( annotateSecretChannels ) where import Data.Set as S import Data.List as L import Sapic.Annotation import Sapic.Basetranslation import Theory import Theory.Sapic getTermVariables :: SapicTerm -> S.Set LVar getTermVariables ts = S.fromList $ L.map fst $ varOccurences $ toLNTerm ts getSecretChannels :: LProcess (ProcessAnnotation LVar) -> S.Set LVar -> S.Set LVar getSecretChannels (ProcessAction (New v) _ p) candidates = let c = S.insert (toLVar v) candidates in getSecretChannels p c getSecretChannels (ProcessAction (ChOut _ t2) _ p) candidates = let c = S.difference candidates (getTermVariables t2) in getSecretChannels p c getSecretChannels (ProcessAction (Insert _ t2) _ p) candidates = let c = S.difference candidates (getTermVariables t2) in getSecretChannels p c getSecretChannels (ProcessAction _ _ p) candidates = getSecretChannels p candidates getSecretChannels (ProcessNull _) candidates = candidates getSecretChannels (ProcessComb _ _ pl pr ) candidates = S.intersection c1 c2 where c1 = getSecretChannels pl candidates c2 = getSecretChannels pr candidates annotateEachSecretChannels :: LProcess (ProcessAnnotation LVar) -> S.Set LVar -> LProcess (ProcessAnnotation LVar) annotateEachSecretChannels (ProcessNull an) _ = ProcessNull an annotateEachSecretChannels (ProcessComb comb an pl pr ) svars = ProcessComb comb an pl' pr' where pl' = annotateEachSecretChannels pl svars pr' = annotateEachSecretChannels pr svars annotateEachSecretChannels (ProcessAction ac an p) svars | (ChIn (Just t1) _ _) <- ac, Lit (Var v') <- viewTerm t1 , v <- toLVar v' = if S.member v svars then ProcessAction ac (an `mappend` annSecretChannel (AnVar v)) p' else ProcessAction ac an p' | (ChOut (Just t1) _) <- ac, Lit (Var v') <- viewTerm t1 , v <- toLVar v' = if S.member v svars then ProcessAction ac (an `mappend` annSecretChannel (AnVar v)) p' else ProcessAction ac an p' | otherwise = ProcessAction ac an p' where p'= annotateEachSecretChannels p svars annotateSecretChannels :: LProcess (ProcessAnnotation LVar) -> LProcess (ProcessAnnotation LVar) annotateSecretChannels anp = annotateEachSecretChannels anp svars where svars = getSecretChannels anp S.empty
593bce0d035732626049b89cc7eb9e82c794fe8c5575fac14697315a31d951cf
samply/blaze
routes_test.clj
(ns blaze.rest-api.routes-test (:require [blaze.db.impl.search-param] [blaze.rest-api.routes :as routes] [blaze.rest-api.routes-spec] [blaze.test-util :as tu] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest testing]] [juxt.iota :refer [given]] [reitit.ring])) (st/instrument) (test/use-fixtures :each tu/fixture) (deftest resource-route-test (testing "read interaction" (given (routes/resource-route {:node ::node} [#:blaze.rest-api.resource-pattern {:type :default :interactions {:read #:blaze.rest-api.interaction {:handler (fn [_] ::read)}}}] {:kind "resource" :name "Patient"}) [0] := "/Patient" [1 :fhir.resource/type] := "Patient" [2] := ["" {:name :Patient/type}] [3] := ["/_history" {:conflicting true}] [4] := ["/_search" {:name :Patient/search :conflicting true}] [5] := ["/__page" {:name :Patient/page :conflicting true}] [6 1 1 :name] := :Patient/instance [6 1 1 :conflicting] := true [6 1 1 :get :middleware 0 0 :name] := :db [6 1 1 :get :middleware 0 1] := ::node [6 1 1 :get :handler #(% {})] := ::read [6 2 0] := "/_history" [6 2 1] := ["" {:name :Patient/history-instance, :conflicting true}])))
null
https://raw.githubusercontent.com/samply/blaze/6441a0a2f988b8784ed555c1d20f634ef2df7e4a/modules/rest-api/test/blaze/rest_api/routes_test.clj
clojure
(ns blaze.rest-api.routes-test (:require [blaze.db.impl.search-param] [blaze.rest-api.routes :as routes] [blaze.rest-api.routes-spec] [blaze.test-util :as tu] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest testing]] [juxt.iota :refer [given]] [reitit.ring])) (st/instrument) (test/use-fixtures :each tu/fixture) (deftest resource-route-test (testing "read interaction" (given (routes/resource-route {:node ::node} [#:blaze.rest-api.resource-pattern {:type :default :interactions {:read #:blaze.rest-api.interaction {:handler (fn [_] ::read)}}}] {:kind "resource" :name "Patient"}) [0] := "/Patient" [1 :fhir.resource/type] := "Patient" [2] := ["" {:name :Patient/type}] [3] := ["/_history" {:conflicting true}] [4] := ["/_search" {:name :Patient/search :conflicting true}] [5] := ["/__page" {:name :Patient/page :conflicting true}] [6 1 1 :name] := :Patient/instance [6 1 1 :conflicting] := true [6 1 1 :get :middleware 0 0 :name] := :db [6 1 1 :get :middleware 0 1] := ::node [6 1 1 :get :handler #(% {})] := ::read [6 2 0] := "/_history" [6 2 1] := ["" {:name :Patient/history-instance, :conflicting true}])))
71c3818acf9bbe8112479f25d2bcf0869af02495c74a7925bfa8ba444f88e99c
acl2/acl2
(XDOC::FULL-ESCAPE-SYMBOL)
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/xdoc/.sys/full-escape-symbol%40useless-runes.lsp
lisp
(XDOC::FULL-ESCAPE-SYMBOL)
9d6566ed05e69cbfe69d87af8a53e108ecdc350bd1b9faa7ee267f30debf4ab9
juspay/atlas
SearchRequestForDriver.hs
# LANGUAGE DerivingVia # # LANGUAGE GeneralizedNewtypeDeriving # # OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Domain . Types . SearchRequestForDriver Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Domain.Types.SearchRequestForDriver Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.Types.SearchRequestForDriver where import Beckn.Prelude import Beckn.Types.Common import Beckn.Types.Id import Beckn.Utils.GenericPretty (PrettyShow) import Domain.Types.Person import Domain.Types.SearchRequest import qualified Domain.Types.Vehicle.Variant as Variant data SearchRequestForDriver = SearchRequestForDriver { id :: Id SearchRequestForDriver, searchRequestId :: Id SearchRequest, searchRequestValidTill :: UTCTime, driverId :: Id Person, distanceToPickup :: Meters, durationToPickup :: Seconds, vehicleVariant :: Variant.Variant, baseFare :: Double, createdAt :: UTCTime } deriving (Generic, Show, PrettyShow) deriving newtype instance PrettyShow Seconds deriving newtype instance PrettyShow Meters data SearchRequestForDriverAPIEntity = SearchRequestForDriverAPIEntity { searchRequestId :: Id SearchRequest, searchRequestValidTill :: UTCTime, distanceToPickup :: Meters, durationToPickup :: Seconds, baseFare :: Double } deriving (Generic, ToJSON, ToSchema) deriving newtype instance ToSchema Seconds deriving newtype instance ToSchema Meters mkSearchRequestForDriverAPIEntity :: SearchRequestForDriver -> SearchRequestForDriverAPIEntity mkSearchRequestForDriverAPIEntity SearchRequestForDriver {..} = SearchRequestForDriverAPIEntity {..}
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/Domain/Types/SearchRequestForDriver.hs
haskell
# LANGUAGE DerivingVia # # LANGUAGE GeneralizedNewtypeDeriving # # OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Domain . Types . SearchRequestForDriver Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Domain.Types.SearchRequestForDriver Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.Types.SearchRequestForDriver where import Beckn.Prelude import Beckn.Types.Common import Beckn.Types.Id import Beckn.Utils.GenericPretty (PrettyShow) import Domain.Types.Person import Domain.Types.SearchRequest import qualified Domain.Types.Vehicle.Variant as Variant data SearchRequestForDriver = SearchRequestForDriver { id :: Id SearchRequestForDriver, searchRequestId :: Id SearchRequest, searchRequestValidTill :: UTCTime, driverId :: Id Person, distanceToPickup :: Meters, durationToPickup :: Seconds, vehicleVariant :: Variant.Variant, baseFare :: Double, createdAt :: UTCTime } deriving (Generic, Show, PrettyShow) deriving newtype instance PrettyShow Seconds deriving newtype instance PrettyShow Meters data SearchRequestForDriverAPIEntity = SearchRequestForDriverAPIEntity { searchRequestId :: Id SearchRequest, searchRequestValidTill :: UTCTime, distanceToPickup :: Meters, durationToPickup :: Seconds, baseFare :: Double } deriving (Generic, ToJSON, ToSchema) deriving newtype instance ToSchema Seconds deriving newtype instance ToSchema Meters mkSearchRequestForDriverAPIEntity :: SearchRequestForDriver -> SearchRequestForDriverAPIEntity mkSearchRequestForDriverAPIEntity SearchRequestForDriver {..} = SearchRequestForDriverAPIEntity {..}
549d254827d35c049c61f7110b3b2f7ef61fb9f213dab3b1e95a078362ac9c2d
coco-team/lustrec
c_backend_main.ml
(********************************************************************) (* *) The LustreC compiler toolset / The LustreC Development Team Copyright 2012 - -- ONERA - CNRS - INPT (* *) (* LustreC is free software, distributed WITHOUT ANY WARRANTY *) (* under the terms of the GNU Lesser General Public License *) version 2.1 . (* *) (********************************************************************) open Lustre_types open Machine_code_types open Corelang open Machine_code_common open Format open C_backend_common open Utils module type MODIFIERS_MAINSRC = sig end module EmptyMod = struct end module Main = functor (Mod: MODIFIERS_MAINSRC) -> struct (********************************************************************************************) (* Main related functions *) (********************************************************************************************) let print_put_outputs fmt m = let po fmt (id, o', o) = let suff = string_of_int id in print_put_var fmt suff o'.var_id o.var_type o.var_id in List.iteri2 (fun idx v' v -> fprintf fmt "@ %a;" po ((idx+1), v', v)) m.mname.node_outputs m.mstep.step_outputs let print_main_inout_declaration basename fmt m = let mname = m.mname.node_id in TODO : find a proper way to shorthen long names . This causes in the binary when trying to fprintf in them let mname = if String.length mname > 50 then string_of_int (Hashtbl.hash mname) else mname in fprintf fmt "/* Declaration of inputs/outputs variables */@ "; List.iteri (fun idx v -> fprintf fmt "%a;@ " (pp_c_type v.var_id) v.var_type; we start from 1 : in1 , in2 , ... fprintf fmt "f_in%i = fopen(\"%s_%s_simu.in%i\", \"w\");@ " (idx+1) basename mname (idx+1); ) m.mstep.step_inputs; List.iteri (fun idx v -> fprintf fmt "%a;@ " (pp_c_type v.var_id) v.var_type; we start from 1 : in1 , in2 , ... fprintf fmt "f_out%i = fopen(\"%s_%s_simu.out%i\", \"w\");@ " (idx+1) basename mname (idx+1); ) m.mstep.step_outputs let print_main_memory_allocation mname main_mem fmt m = if not (fst (get_stateless_status m)) then begin fprintf fmt "@ /* Main memory allocation */@ "; if (!Options.static_mem && !Options.main_node <> "") then (fprintf fmt "%a(static,main_mem);@ " pp_machine_static_alloc_name mname) else (fprintf fmt "%a *main_mem = %a();@ " pp_machine_memtype_name mname pp_machine_alloc_name mname); fprintf fmt "@ /* Initialize the main memory */@ "; fprintf fmt "%a(%s);@ " pp_machine_reset_name mname main_mem; end let print_global_initialize fmt basename = let mNAME = file_to_module_name basename in fprintf fmt "@ /* Initialize global constants */@ %a();@ " pp_global_init_name mNAME let print_global_clear fmt basename = let mNAME = file_to_module_name basename in fprintf fmt "@ /* Clear global constants */@ %a();@ " pp_global_clear_name mNAME let print_main_initialize mname main_mem fmt m = if not (fst (get_stateless_status m)) then fprintf fmt "@ /* Initialize inputs, outputs and memories */@ %a%t%a%t%a(%s);@ " (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_outputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) pp_machine_init_name mname main_mem else fprintf fmt "@ /* Initialize inputs and outputs */@ %a%t%a@ " (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_outputs let print_main_clear mname main_mem fmt m = if not (fst (get_stateless_status m)) then fprintf fmt "@ /* Clear inputs, outputs and memories */@ %a%t%a%t%a(%s);@ " (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_outputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) pp_machine_clear_name mname main_mem else fprintf fmt "@ /* Clear inputs and outputs */@ %a%t%a@ " (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_outputs let print_main_loop mname main_mem fmt m = let input_values = List.map (fun v -> mk_val (LocalVar v) v.var_type) m.mstep.step_inputs in begin fprintf fmt "@ ISATTY = isatty(0);@ "; fprintf fmt "@ /* Infinite loop */@ "; fprintf fmt "@[<v 2>while(1){@ "; fprintf fmt "fflush(stdout);@ "; List.iteri (fun idx _ -> fprintf fmt "fflush(f_in%i);@ " (idx+1)) m.mstep.step_inputs; List.iteri (fun idx _ -> fprintf fmt "fflush(f_out%i);@ " (idx+1)) m.mstep.step_outputs; fprintf fmt "%a@ %t%a" print_get_inputs m (fun fmt -> pp_main_call mname main_mem fmt m input_values m.mstep.step_outputs) print_put_outputs m end let print_main_code fmt basename m = let mname = m.mname.node_id in let main_mem = if (!Options.static_mem && !Options.main_node <> "") then "&main_mem" else "main_mem" in fprintf fmt "@[<v 2>int main (int argc, char *argv[]) {@ "; print_main_inout_declaration basename fmt m; Plugins.c_backend_main_loop_body_prefix basename mname fmt (); print_main_memory_allocation mname main_mem fmt m; if !Options.mpfr then begin print_global_initialize fmt basename; print_main_initialize mname main_mem fmt m; end; print_main_loop mname main_mem fmt m; Plugins.c_backend_main_loop_body_suffix fmt (); fprintf fmt "@]@ }@ @ "; if !Options.mpfr then begin print_main_clear mname main_mem fmt m; print_global_clear fmt basename; end; fprintf fmt "@ return 1;"; fprintf fmt "@]@ }@." let print_main_header fmt = fprintf fmt (if !Options.cpp then "#include <stdio.h>@.#include <unistd.h>@.#include \"%s/io_frontend.hpp\"@." else "#include <stdio.h>@.#include <unistd.h>@.#include \"%s/io_frontend.h\"@.") (Options_management.core_dependency "io_frontend") let print_main_c main_fmt main_machine basename prog machines _ (*dependencies*) = print_main_header main_fmt; fprintf main_fmt "#include <stdlib.h>@.#include <assert.h>@."; print_import_alloc_prototype main_fmt (Dep (true, basename, [], true (* assuming it is stateful*) )); pp_print_newline main_fmt (); Print the svn version number and the supported C standard ( C90 or C99 ) print_version main_fmt; print_main_code main_fmt basename main_machine end (* Local Variables: *) (* compile-command:"make -C ../../.." *) (* End: *)
null
https://raw.githubusercontent.com/coco-team/lustrec/b21f9820df97e661633cd4418fdab68a6c6ca67d/src/backends/C/c_backend_main.ml
ocaml
****************************************************************** LustreC is free software, distributed WITHOUT ANY WARRANTY under the terms of the GNU Lesser General Public License ****************************************************************** ****************************************************************************************** Main related functions ****************************************************************************************** dependencies assuming it is stateful Local Variables: compile-command:"make -C ../../.." End:
The LustreC compiler toolset / The LustreC Development Team Copyright 2012 - -- ONERA - CNRS - INPT version 2.1 . open Lustre_types open Machine_code_types open Corelang open Machine_code_common open Format open C_backend_common open Utils module type MODIFIERS_MAINSRC = sig end module EmptyMod = struct end module Main = functor (Mod: MODIFIERS_MAINSRC) -> struct let print_put_outputs fmt m = let po fmt (id, o', o) = let suff = string_of_int id in print_put_var fmt suff o'.var_id o.var_type o.var_id in List.iteri2 (fun idx v' v -> fprintf fmt "@ %a;" po ((idx+1), v', v)) m.mname.node_outputs m.mstep.step_outputs let print_main_inout_declaration basename fmt m = let mname = m.mname.node_id in TODO : find a proper way to shorthen long names . This causes in the binary when trying to fprintf in them let mname = if String.length mname > 50 then string_of_int (Hashtbl.hash mname) else mname in fprintf fmt "/* Declaration of inputs/outputs variables */@ "; List.iteri (fun idx v -> fprintf fmt "%a;@ " (pp_c_type v.var_id) v.var_type; we start from 1 : in1 , in2 , ... fprintf fmt "f_in%i = fopen(\"%s_%s_simu.in%i\", \"w\");@ " (idx+1) basename mname (idx+1); ) m.mstep.step_inputs; List.iteri (fun idx v -> fprintf fmt "%a;@ " (pp_c_type v.var_id) v.var_type; we start from 1 : in1 , in2 , ... fprintf fmt "f_out%i = fopen(\"%s_%s_simu.out%i\", \"w\");@ " (idx+1) basename mname (idx+1); ) m.mstep.step_outputs let print_main_memory_allocation mname main_mem fmt m = if not (fst (get_stateless_status m)) then begin fprintf fmt "@ /* Main memory allocation */@ "; if (!Options.static_mem && !Options.main_node <> "") then (fprintf fmt "%a(static,main_mem);@ " pp_machine_static_alloc_name mname) else (fprintf fmt "%a *main_mem = %a();@ " pp_machine_memtype_name mname pp_machine_alloc_name mname); fprintf fmt "@ /* Initialize the main memory */@ "; fprintf fmt "%a(%s);@ " pp_machine_reset_name mname main_mem; end let print_global_initialize fmt basename = let mNAME = file_to_module_name basename in fprintf fmt "@ /* Initialize global constants */@ %a();@ " pp_global_init_name mNAME let print_global_clear fmt basename = let mNAME = file_to_module_name basename in fprintf fmt "@ /* Clear global constants */@ %a();@ " pp_global_clear_name mNAME let print_main_initialize mname main_mem fmt m = if not (fst (get_stateless_status m)) then fprintf fmt "@ /* Initialize inputs, outputs and memories */@ %a%t%a%t%a(%s);@ " (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_outputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) pp_machine_init_name mname main_mem else fprintf fmt "@ /* Initialize inputs and outputs */@ %a%t%a@ " (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_initialize m main_mem (pp_c_var_read m))) m.mstep.step_outputs let print_main_clear mname main_mem fmt m = if not (fst (get_stateless_status m)) then fprintf fmt "@ /* Clear inputs, outputs and memories */@ %a%t%a%t%a(%s);@ " (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_outputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) pp_machine_clear_name mname main_mem else fprintf fmt "@ /* Clear inputs and outputs */@ %a%t%a@ " (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_inputs (Utils.pp_newline_if_non_empty m.mstep.step_inputs) (Utils.fprintf_list ~sep:"@ " (pp_clear m main_mem (pp_c_var_read m))) m.mstep.step_outputs let print_main_loop mname main_mem fmt m = let input_values = List.map (fun v -> mk_val (LocalVar v) v.var_type) m.mstep.step_inputs in begin fprintf fmt "@ ISATTY = isatty(0);@ "; fprintf fmt "@ /* Infinite loop */@ "; fprintf fmt "@[<v 2>while(1){@ "; fprintf fmt "fflush(stdout);@ "; List.iteri (fun idx _ -> fprintf fmt "fflush(f_in%i);@ " (idx+1)) m.mstep.step_inputs; List.iteri (fun idx _ -> fprintf fmt "fflush(f_out%i);@ " (idx+1)) m.mstep.step_outputs; fprintf fmt "%a@ %t%a" print_get_inputs m (fun fmt -> pp_main_call mname main_mem fmt m input_values m.mstep.step_outputs) print_put_outputs m end let print_main_code fmt basename m = let mname = m.mname.node_id in let main_mem = if (!Options.static_mem && !Options.main_node <> "") then "&main_mem" else "main_mem" in fprintf fmt "@[<v 2>int main (int argc, char *argv[]) {@ "; print_main_inout_declaration basename fmt m; Plugins.c_backend_main_loop_body_prefix basename mname fmt (); print_main_memory_allocation mname main_mem fmt m; if !Options.mpfr then begin print_global_initialize fmt basename; print_main_initialize mname main_mem fmt m; end; print_main_loop mname main_mem fmt m; Plugins.c_backend_main_loop_body_suffix fmt (); fprintf fmt "@]@ }@ @ "; if !Options.mpfr then begin print_main_clear mname main_mem fmt m; print_global_clear fmt basename; end; fprintf fmt "@ return 1;"; fprintf fmt "@]@ }@." let print_main_header fmt = fprintf fmt (if !Options.cpp then "#include <stdio.h>@.#include <unistd.h>@.#include \"%s/io_frontend.hpp\"@." else "#include <stdio.h>@.#include <unistd.h>@.#include \"%s/io_frontend.h\"@.") (Options_management.core_dependency "io_frontend") print_main_header main_fmt; fprintf main_fmt "#include <stdlib.h>@.#include <assert.h>@."; pp_print_newline main_fmt (); Print the svn version number and the supported C standard ( C90 or C99 ) print_version main_fmt; print_main_code main_fmt basename main_machine end
f2371d001ddabc576c8099cdea27dcae1bb6adc59993c9074d7226814d053628
janestreet/bonsai
start.ml
open! Core open! Async_kernel open! Import open Js_of_ocaml module type Result_spec = sig type t type extra type incoming val view : t -> Vdom.Node.t val extra : t -> extra val incoming : t -> incoming -> unit Vdom.Effect.t end module Arrow_deprecated = struct module Handle = struct module Injector = struct type 'a t = | Before_app_start of 'a Queue.t | Inject of ('a -> unit Vdom.Effect.t) end type ('input, 'extra, 'incoming, 'outgoing) t = { mutable injector : 'incoming Injector.t ; stop : unit Ivar.t ; started : unit Ivar.t ; input_var : 'input Incr.Var.t ; outgoing_pipe : 'outgoing Pipe.Reader.t ; extra : ('extra -> unit) Bus.Read_write.t ; last_extra : 'extra Moption.t } let create ~input_var ~outgoing_pipe = let extra = Bus.create_exn [%here] Arity1 ~on_subscription_after_first_write:Allow_and_send_last_value ~on_callback_raise:(fun error -> eprint_s [%sexp (error : Error.t)]) in let last_extra = Moption.create () in Bus.iter_exn extra [%here] ~f:(fun extra -> Moption.set_some last_extra extra); { injector = Before_app_start (Queue.create ()) ; stop = Ivar.create () ; started = Ivar.create () ; input_var ; outgoing_pipe ; extra ; last_extra } ;; let stop t = Ivar.fill_if_empty t.stop () let started t = Ivar.read t.started let schedule t a = match t.injector with | Inject f -> f a |> Vdom.Effect.Expert.handle_non_dom_event_exn | Before_app_start queue -> Queue.enqueue queue a ;; let set_started t = Ivar.fill_if_empty t.started () let set_inject t inject = let prev = t.injector in t.injector <- Inject inject; match prev with | Inject _ -> () | Before_app_start queue -> Queue.iter queue ~f:(schedule t) ;; let input t = Incr.Var.value t.input_var let set_input t input = Incr.Var.set t.input_var input let update_input t ~f = set_input t (f (input t)) let outgoing { outgoing_pipe; _ } = outgoing_pipe let extra t = Bus.read_only t.extra let last_extra t = Moption.get t.last_extra end module App_input = struct type ('input, 'outgoing) t = { input : 'input ; inject_outgoing : 'outgoing -> unit Vdom.Effect.t } [@@deriving fields] let create = Fields.create end module App_result = struct type ('extra, 'incoming) t = { view : Vdom.Node.t ; extra : 'extra ; inject_incoming : 'incoming -> unit Vdom.Effect.t } [@@deriving fields] let create = Fields.create let of_result_spec (type result extra incoming) (module Result : Result_spec with type t = result and type extra = extra and type incoming = incoming) (r : Result.t) = { view = Result.view r ; extra = Result.extra r ; inject_incoming = Result.incoming r } ;; end let make_instrumented_computation ?host ?port ?worker_name component = let open Option.Let_syntax in match [%map let host = host and port = port and worker_name = worker_name in host, port, worker_name] with | Some (host, port, worker_name) -> Forward_performance_entries.instrument ~host ~port ~worker_name component | None -> print_endline "debugger host and port not be specified"; { Forward_performance_entries.instrumented_computation = component ; shutdown = (fun () -> ()) } ;; type debugging_state = | Not_debugging | Debugging of { host : string option ; port : int option ; worker_name : string option } let start_bonsai_debugger (is_debugging_var : debugging_state Incr.Var.t) (host : Js.js_string Js.t Js.Optdef.t) (port : int Js.Optdef.t) (worker_name : Js.js_string Js.t Js.Optdef.t) = match Incr.Var.value is_debugging_var with | Debugging _ -> print_endline "Already debugging." | Not_debugging -> print_endline "Starting the debugger."; Incr.Var.set is_debugging_var (Debugging { host = Js.Optdef.to_option host |> Option.map ~f:Js.to_string ; port = Js.Optdef.to_option port ; worker_name = Js.Optdef.to_option worker_name |> Option.map ~f:Js.to_string }) ;; let start_generic_poly (type input action_input input_and_inject model dynamic_action static_action result extra incoming outgoing) ~(get_app_result : result -> (extra, incoming) App_result.t) ~(get_app_input : input:input -> inject_outgoing:(outgoing -> unit Vdom.Effect.t) -> input_and_inject) ~(initial_input : input) ~bind_to_element_with_id ~(computation : result Bonsai.Private.Computation.t) ~fresh ({ model ; input = _ ; dynamic_action ; static_action ; apply_static ; apply_dynamic ; run ; reset = _ } as info : ( model , dynamic_action , static_action , action_input , result ) Bonsai.Private.Computation.info) : (input, extra, incoming, outgoing) Handle.t = let outgoing_pipe, pipe_write = Pipe.create () in let module Out_event = Virtual_dom.Vdom.Effect.Define (struct module Action = struct type t = outgoing end let handle = Pipe.write_without_pushback_if_open pipe_write end) in let input_var = Incr.Var.create initial_input in let handle = Handle.create ~input_var ~outgoing_pipe in let input = let%map.Incr input = Incr.Var.watch input_var in get_app_input ~input ~inject_outgoing:Out_event.inject in let prev_lifecycle = ref Bonsai.Private.Lifecycle.Collection.empty in let is_debugging_var = Incr.Var.create Not_debugging in let debugger_shutdown = ref None in let module Incr_dom_app = struct module Model = struct type t = model let cutoff = phys_equal end module State = struct type t = unit end module Action = struct let sexp_of_dynamic_action = Bonsai.Private.Meta.Action.Type_id.to_sexp dynamic_action ;; let sexp_of_static_action = Bonsai.Private.Meta.Action.Type_id.to_sexp static_action ;; type t = | Dynamic of dynamic_action | Static of static_action [@@deriving sexp_of] end let action_requires_stabilization = function | Action.Dynamic _ -> true | Static _ -> false ;; let on_startup ~schedule_action:_ _ = return () let create model ~old_model:_ ~inject (run : ( model , dynamic_action , static_action , action_input , result ) Bonsai.Private.Computation.eval_fun) = let open Incr.Let_syntax in let environment = Bonsai.Private.Environment.(empty |> add_exn ~key:fresh ~data:input) in let inject_dynamic a = inject (Action.Dynamic a) in let inject_static a = inject (Action.Static a) in let snapshot = run ~environment ~path:Bonsai.Private.Path.empty ~clock:Incr.clock ~model ~inject_dynamic ~inject_static in let%map view = let%map { App_result.view; extra; inject_incoming } = snapshot |> Bonsai.Private.Snapshot.result >>| get_app_result in Handle.set_inject handle inject_incoming; Bus.write handle.extra extra; view and apply_action = let%map input = snapshot |> Bonsai.Private.Snapshot.input |> Bonsai.Private.Input.to_incremental in fun () ~schedule_event model action -> match action with | Action.Dynamic action -> apply_dynamic ~inject_dynamic ~inject_static ~schedule_event (Some input) model action | Action.Static action -> apply_static ~inject_dynamic ~inject_static ~schedule_event model action and on_display = let%map lifecycle = Bonsai.Private.Snapshot.lifecycle_or_empty snapshot in fun () ~schedule_event -> Handle.set_started handle; schedule_event (Bonsai.Private.Lifecycle.Collection.diff !prev_lifecycle lifecycle); prev_lifecycle := lifecycle in let update_visibility model ~schedule_event:_ = model in { Incr_dom.App_intf.Private.view; apply_action; update_visibility; on_display } ;; let create model ~old_model ~inject = let open Incr.Let_syntax in let safe_start computation = let (T info') = Bonsai.Private.gather computation in match Bonsai.Private.Meta.( ( Model.Type_id.same_witness info.model.type_id info'.model.type_id , Action.Type_id.same_witness info.dynamic_action info'.dynamic_action , Action.Type_id.same_witness info.static_action info'.static_action , Input.same_witness info.input info'.input )) with | Some T, Some T, Some T, Some T -> create model ~old_model ~inject info'.run | _ -> print_endline "Not starting debugger. An error occurred while attempting to instrument \ the computation; the resulting computation does not typecheck. Reusing \ previously gathered run information to execute"; create model ~old_model ~inject run in match%bind Incr.Var.watch is_debugging_var with | Debugging { host; port; worker_name } -> let { Forward_performance_entries.instrumented_computation; shutdown } = make_instrumented_computation ?host ?port ?worker_name computation in debugger_shutdown := Some shutdown; safe_start instrumented_computation | Not_debugging -> safe_start computation ;; end in Incr_dom.Start_app.Private.start_bonsai ~bind_to_element_with_id ~initial_model:model.default ~stop:(Ivar.read handle.stop) (module Incr_dom_app); let start_bonsai_debugger dry_run host port worker_name = let print_message () = print_endline "Not starting debugger. Be aware that running the debugger will send \ performance data to the debugger server, which may be unacceptable if the \ data you work with is sensitive. Consider running a local server and calling \ this function again with the local host and port. If you wish to proceed, run \ this function again, passing \"true\" as the first parameter" in Js.Optdef.case dry_run print_message (fun dry_run -> if Js.to_bool dry_run then ( start_bonsai_debugger is_debugging_var host port worker_name; Incr.stabilize ()) else print_message ()) in let stop_bonsai_debugger () = Option.iter !debugger_shutdown ~f:(fun f -> f ()); debugger_shutdown := None; Incr.Var.set is_debugging_var Not_debugging; Incr.stabilize () in Js.Unsafe.global##.startBonsaiDebugger := Js.Unsafe.callback start_bonsai_debugger; Js.Unsafe.global##.stopBonsaiDebugger := Js.Unsafe.callback stop_bonsai_debugger; handle ;; let start_generic ~optimize ~get_app_result ~initial_input ~bind_to_element_with_id ~component = let fresh = Type_equal.Id.create ~name:"" sexp_of_opaque in let var = Bonsai.Private.Value.named App_input fresh |> Bonsai.Private.conceal_value in let computation = component var |> Bonsai.Private.reveal_computation |> if optimize then Bonsai.Private.pre_process else Fn.id in let (T info) = Bonsai.Private.gather computation in start_generic_poly ~get_app_result ~initial_input ~bind_to_element_with_id ~computation ~fresh info ;; (* I can't use currying here because of the value restriction. *) let start_standalone ?(optimize = true) ~initial_input ~bind_to_element_with_id component = start_generic ~optimize ~get_app_result:(fun view -> { App_result.view; extra = (); inject_incoming = Nothing.unreachable_code }) ~get_app_input:(fun ~input ~inject_outgoing:_ -> input) ~initial_input ~bind_to_element_with_id ~component ;; let start ?(optimize = true) ~initial_input ~bind_to_element_with_id component = start_generic ~optimize ~get_app_result:Fn.id ~get_app_input:App_input.create ~initial_input ~bind_to_element_with_id ~component ;; end module Proc = struct module Handle = struct include Arrow_deprecated.Handle type ('extra, 'incoming) t = (unit, 'extra, 'incoming, Nothing.t) Arrow_deprecated.Handle.t end module Result_spec = struct module type S = Result_spec type ('r, 'extra, 'incoming) t = (module S with type t = 'r and type extra = 'extra and type incoming = 'incoming) module No_extra = struct type extra = unit let extra _ = () end module No_incoming = struct type incoming = Nothing.t let incoming _ = Nothing.unreachable_code end let just_the_view = (module struct type t = Vdom.Node.t let view = Fn.id include No_extra include No_incoming end : S with type t = Vdom.Node.t and type extra = unit and type incoming = Nothing.t) ;; end let start_and_get_handle result_spec ?(optimize = true) ?(custom_connector = fun _ -> assert false) ~bind_to_element_with_id computation = let computation = Rpc_effect.Private.with_connector (function | Self -> Rpc_effect.Private.self_connector () | Url url -> Rpc_effect.Private.url_connector url | Custom custom -> custom_connector custom) computation in let bonsai = Fn.const computation |> Bonsai.Arrow_deprecated.map ~f:(Arrow_deprecated.App_result.of_result_spec result_spec) in Arrow_deprecated.start ~optimize ~initial_input:() ~bind_to_element_with_id bonsai ;; let start ?custom_connector ?(bind_to_element_with_id = "app") component = let (_ : _ Handle.t) = start_and_get_handle Result_spec.just_the_view ~bind_to_element_with_id ?custom_connector component in () ;; end
null
https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/web/start.ml
ocaml
I can't use currying here because of the value restriction.
open! Core open! Async_kernel open! Import open Js_of_ocaml module type Result_spec = sig type t type extra type incoming val view : t -> Vdom.Node.t val extra : t -> extra val incoming : t -> incoming -> unit Vdom.Effect.t end module Arrow_deprecated = struct module Handle = struct module Injector = struct type 'a t = | Before_app_start of 'a Queue.t | Inject of ('a -> unit Vdom.Effect.t) end type ('input, 'extra, 'incoming, 'outgoing) t = { mutable injector : 'incoming Injector.t ; stop : unit Ivar.t ; started : unit Ivar.t ; input_var : 'input Incr.Var.t ; outgoing_pipe : 'outgoing Pipe.Reader.t ; extra : ('extra -> unit) Bus.Read_write.t ; last_extra : 'extra Moption.t } let create ~input_var ~outgoing_pipe = let extra = Bus.create_exn [%here] Arity1 ~on_subscription_after_first_write:Allow_and_send_last_value ~on_callback_raise:(fun error -> eprint_s [%sexp (error : Error.t)]) in let last_extra = Moption.create () in Bus.iter_exn extra [%here] ~f:(fun extra -> Moption.set_some last_extra extra); { injector = Before_app_start (Queue.create ()) ; stop = Ivar.create () ; started = Ivar.create () ; input_var ; outgoing_pipe ; extra ; last_extra } ;; let stop t = Ivar.fill_if_empty t.stop () let started t = Ivar.read t.started let schedule t a = match t.injector with | Inject f -> f a |> Vdom.Effect.Expert.handle_non_dom_event_exn | Before_app_start queue -> Queue.enqueue queue a ;; let set_started t = Ivar.fill_if_empty t.started () let set_inject t inject = let prev = t.injector in t.injector <- Inject inject; match prev with | Inject _ -> () | Before_app_start queue -> Queue.iter queue ~f:(schedule t) ;; let input t = Incr.Var.value t.input_var let set_input t input = Incr.Var.set t.input_var input let update_input t ~f = set_input t (f (input t)) let outgoing { outgoing_pipe; _ } = outgoing_pipe let extra t = Bus.read_only t.extra let last_extra t = Moption.get t.last_extra end module App_input = struct type ('input, 'outgoing) t = { input : 'input ; inject_outgoing : 'outgoing -> unit Vdom.Effect.t } [@@deriving fields] let create = Fields.create end module App_result = struct type ('extra, 'incoming) t = { view : Vdom.Node.t ; extra : 'extra ; inject_incoming : 'incoming -> unit Vdom.Effect.t } [@@deriving fields] let create = Fields.create let of_result_spec (type result extra incoming) (module Result : Result_spec with type t = result and type extra = extra and type incoming = incoming) (r : Result.t) = { view = Result.view r ; extra = Result.extra r ; inject_incoming = Result.incoming r } ;; end let make_instrumented_computation ?host ?port ?worker_name component = let open Option.Let_syntax in match [%map let host = host and port = port and worker_name = worker_name in host, port, worker_name] with | Some (host, port, worker_name) -> Forward_performance_entries.instrument ~host ~port ~worker_name component | None -> print_endline "debugger host and port not be specified"; { Forward_performance_entries.instrumented_computation = component ; shutdown = (fun () -> ()) } ;; type debugging_state = | Not_debugging | Debugging of { host : string option ; port : int option ; worker_name : string option } let start_bonsai_debugger (is_debugging_var : debugging_state Incr.Var.t) (host : Js.js_string Js.t Js.Optdef.t) (port : int Js.Optdef.t) (worker_name : Js.js_string Js.t Js.Optdef.t) = match Incr.Var.value is_debugging_var with | Debugging _ -> print_endline "Already debugging." | Not_debugging -> print_endline "Starting the debugger."; Incr.Var.set is_debugging_var (Debugging { host = Js.Optdef.to_option host |> Option.map ~f:Js.to_string ; port = Js.Optdef.to_option port ; worker_name = Js.Optdef.to_option worker_name |> Option.map ~f:Js.to_string }) ;; let start_generic_poly (type input action_input input_and_inject model dynamic_action static_action result extra incoming outgoing) ~(get_app_result : result -> (extra, incoming) App_result.t) ~(get_app_input : input:input -> inject_outgoing:(outgoing -> unit Vdom.Effect.t) -> input_and_inject) ~(initial_input : input) ~bind_to_element_with_id ~(computation : result Bonsai.Private.Computation.t) ~fresh ({ model ; input = _ ; dynamic_action ; static_action ; apply_static ; apply_dynamic ; run ; reset = _ } as info : ( model , dynamic_action , static_action , action_input , result ) Bonsai.Private.Computation.info) : (input, extra, incoming, outgoing) Handle.t = let outgoing_pipe, pipe_write = Pipe.create () in let module Out_event = Virtual_dom.Vdom.Effect.Define (struct module Action = struct type t = outgoing end let handle = Pipe.write_without_pushback_if_open pipe_write end) in let input_var = Incr.Var.create initial_input in let handle = Handle.create ~input_var ~outgoing_pipe in let input = let%map.Incr input = Incr.Var.watch input_var in get_app_input ~input ~inject_outgoing:Out_event.inject in let prev_lifecycle = ref Bonsai.Private.Lifecycle.Collection.empty in let is_debugging_var = Incr.Var.create Not_debugging in let debugger_shutdown = ref None in let module Incr_dom_app = struct module Model = struct type t = model let cutoff = phys_equal end module State = struct type t = unit end module Action = struct let sexp_of_dynamic_action = Bonsai.Private.Meta.Action.Type_id.to_sexp dynamic_action ;; let sexp_of_static_action = Bonsai.Private.Meta.Action.Type_id.to_sexp static_action ;; type t = | Dynamic of dynamic_action | Static of static_action [@@deriving sexp_of] end let action_requires_stabilization = function | Action.Dynamic _ -> true | Static _ -> false ;; let on_startup ~schedule_action:_ _ = return () let create model ~old_model:_ ~inject (run : ( model , dynamic_action , static_action , action_input , result ) Bonsai.Private.Computation.eval_fun) = let open Incr.Let_syntax in let environment = Bonsai.Private.Environment.(empty |> add_exn ~key:fresh ~data:input) in let inject_dynamic a = inject (Action.Dynamic a) in let inject_static a = inject (Action.Static a) in let snapshot = run ~environment ~path:Bonsai.Private.Path.empty ~clock:Incr.clock ~model ~inject_dynamic ~inject_static in let%map view = let%map { App_result.view; extra; inject_incoming } = snapshot |> Bonsai.Private.Snapshot.result >>| get_app_result in Handle.set_inject handle inject_incoming; Bus.write handle.extra extra; view and apply_action = let%map input = snapshot |> Bonsai.Private.Snapshot.input |> Bonsai.Private.Input.to_incremental in fun () ~schedule_event model action -> match action with | Action.Dynamic action -> apply_dynamic ~inject_dynamic ~inject_static ~schedule_event (Some input) model action | Action.Static action -> apply_static ~inject_dynamic ~inject_static ~schedule_event model action and on_display = let%map lifecycle = Bonsai.Private.Snapshot.lifecycle_or_empty snapshot in fun () ~schedule_event -> Handle.set_started handle; schedule_event (Bonsai.Private.Lifecycle.Collection.diff !prev_lifecycle lifecycle); prev_lifecycle := lifecycle in let update_visibility model ~schedule_event:_ = model in { Incr_dom.App_intf.Private.view; apply_action; update_visibility; on_display } ;; let create model ~old_model ~inject = let open Incr.Let_syntax in let safe_start computation = let (T info') = Bonsai.Private.gather computation in match Bonsai.Private.Meta.( ( Model.Type_id.same_witness info.model.type_id info'.model.type_id , Action.Type_id.same_witness info.dynamic_action info'.dynamic_action , Action.Type_id.same_witness info.static_action info'.static_action , Input.same_witness info.input info'.input )) with | Some T, Some T, Some T, Some T -> create model ~old_model ~inject info'.run | _ -> print_endline "Not starting debugger. An error occurred while attempting to instrument \ the computation; the resulting computation does not typecheck. Reusing \ previously gathered run information to execute"; create model ~old_model ~inject run in match%bind Incr.Var.watch is_debugging_var with | Debugging { host; port; worker_name } -> let { Forward_performance_entries.instrumented_computation; shutdown } = make_instrumented_computation ?host ?port ?worker_name computation in debugger_shutdown := Some shutdown; safe_start instrumented_computation | Not_debugging -> safe_start computation ;; end in Incr_dom.Start_app.Private.start_bonsai ~bind_to_element_with_id ~initial_model:model.default ~stop:(Ivar.read handle.stop) (module Incr_dom_app); let start_bonsai_debugger dry_run host port worker_name = let print_message () = print_endline "Not starting debugger. Be aware that running the debugger will send \ performance data to the debugger server, which may be unacceptable if the \ data you work with is sensitive. Consider running a local server and calling \ this function again with the local host and port. If you wish to proceed, run \ this function again, passing \"true\" as the first parameter" in Js.Optdef.case dry_run print_message (fun dry_run -> if Js.to_bool dry_run then ( start_bonsai_debugger is_debugging_var host port worker_name; Incr.stabilize ()) else print_message ()) in let stop_bonsai_debugger () = Option.iter !debugger_shutdown ~f:(fun f -> f ()); debugger_shutdown := None; Incr.Var.set is_debugging_var Not_debugging; Incr.stabilize () in Js.Unsafe.global##.startBonsaiDebugger := Js.Unsafe.callback start_bonsai_debugger; Js.Unsafe.global##.stopBonsaiDebugger := Js.Unsafe.callback stop_bonsai_debugger; handle ;; let start_generic ~optimize ~get_app_result ~initial_input ~bind_to_element_with_id ~component = let fresh = Type_equal.Id.create ~name:"" sexp_of_opaque in let var = Bonsai.Private.Value.named App_input fresh |> Bonsai.Private.conceal_value in let computation = component var |> Bonsai.Private.reveal_computation |> if optimize then Bonsai.Private.pre_process else Fn.id in let (T info) = Bonsai.Private.gather computation in start_generic_poly ~get_app_result ~initial_input ~bind_to_element_with_id ~computation ~fresh info ;; let start_standalone ?(optimize = true) ~initial_input ~bind_to_element_with_id component = start_generic ~optimize ~get_app_result:(fun view -> { App_result.view; extra = (); inject_incoming = Nothing.unreachable_code }) ~get_app_input:(fun ~input ~inject_outgoing:_ -> input) ~initial_input ~bind_to_element_with_id ~component ;; let start ?(optimize = true) ~initial_input ~bind_to_element_with_id component = start_generic ~optimize ~get_app_result:Fn.id ~get_app_input:App_input.create ~initial_input ~bind_to_element_with_id ~component ;; end module Proc = struct module Handle = struct include Arrow_deprecated.Handle type ('extra, 'incoming) t = (unit, 'extra, 'incoming, Nothing.t) Arrow_deprecated.Handle.t end module Result_spec = struct module type S = Result_spec type ('r, 'extra, 'incoming) t = (module S with type t = 'r and type extra = 'extra and type incoming = 'incoming) module No_extra = struct type extra = unit let extra _ = () end module No_incoming = struct type incoming = Nothing.t let incoming _ = Nothing.unreachable_code end let just_the_view = (module struct type t = Vdom.Node.t let view = Fn.id include No_extra include No_incoming end : S with type t = Vdom.Node.t and type extra = unit and type incoming = Nothing.t) ;; end let start_and_get_handle result_spec ?(optimize = true) ?(custom_connector = fun _ -> assert false) ~bind_to_element_with_id computation = let computation = Rpc_effect.Private.with_connector (function | Self -> Rpc_effect.Private.self_connector () | Url url -> Rpc_effect.Private.url_connector url | Custom custom -> custom_connector custom) computation in let bonsai = Fn.const computation |> Bonsai.Arrow_deprecated.map ~f:(Arrow_deprecated.App_result.of_result_spec result_spec) in Arrow_deprecated.start ~optimize ~initial_input:() ~bind_to_element_with_id bonsai ;; let start ?custom_connector ?(bind_to_element_with_id = "app") component = let (_ : _ Handle.t) = start_and_get_handle Result_spec.just_the_view ~bind_to_element_with_id ?custom_connector component in () ;; end
ef15cac5b0322469efd8fd85adc7a2455542c2e2df5ab8d52932739aab59164e
TrustInSoft/tis-interpreter
metrics_gui.mli
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * { 1 GUI utilities for Metrics } (** Initialize the main Metrics panel into an upper and lower part. @returns a box containing the lower part of the panel where metrics can display their results. *) val init_panel : Design.main_window_extension_points -> GPack.box ;; (** @returns a value allowing to register the panel into the main GUI *) val coerce_panel_to_ui : < coerce : 'a; .. > -> 'b -> string * 'a * 'c option ;; * Diplay the list of list of strings in a LablgGTK table object val display_as_table : string list list -> GPack.box -> unit ;; (** Reset metrics panel to pristine conditions by removeing children from bottom container *) val reset_panel : 'a -> unit ;; * register_metrics [ ] [ display_function ] ( ) adds a selectable choice for the metrics [ metrics_name ] and add a hook calling [ display_function ] whenever this metrics is selected and launched . choice for the metrics [metrics_name] and add a hook calling [display_function] whenever this metrics is selected and launched. *) val register_metrics : string -> (GPack.box -> unit) -> unit ;;
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/metrics/metrics_gui.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * Initialize the main Metrics panel into an upper and lower part. @returns a box containing the lower part of the panel where metrics can display their results. * @returns a value allowing to register the panel into the main GUI * Reset metrics panel to pristine conditions by removeing children from bottom container
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * { 1 GUI utilities for Metrics } val init_panel : Design.main_window_extension_points -> GPack.box ;; val coerce_panel_to_ui : < coerce : 'a; .. > -> 'b -> string * 'a * 'c option ;; * Diplay the list of list of strings in a LablgGTK table object val display_as_table : string list list -> GPack.box -> unit ;; val reset_panel : 'a -> unit ;; * register_metrics [ ] [ display_function ] ( ) adds a selectable choice for the metrics [ metrics_name ] and add a hook calling [ display_function ] whenever this metrics is selected and launched . choice for the metrics [metrics_name] and add a hook calling [display_function] whenever this metrics is selected and launched. *) val register_metrics : string -> (GPack.box -> unit) -> unit ;;
e31490da1d00d42e28ba8f553ab012cf9013a2af059ae334f9f471d0a2499119
fragnix/fragnix
Data.HashPSQ.hs
# LANGUAGE Haskell98 # # LINE 1 " src / Data / HashPSQ.hs " # | A ' HashPSQ ' offers very similar performance to ' IntPSQ ' . In case of -- collisions, it uses an 'OrdPSQ' locally to solve those. -- This means worst case complexity is usually given by /O(min(n , W ) , log n)/ , where /W/ is the number of bits in an ' Int ' . This simplifies to /O(min(n , W))/ -- since /log n/ is always smaller than /W/ on current machines. module Data.HashPSQ ( -- * Type HashPSQ -- * Query , null , size , member , lookup , findMin -- * Construction , empty , singleton -- * Insertion , insert -- * Delete/update , delete , deleteMin , alter , alterMin -- * Lists , fromList , toList , keys -- * Views , insertView , deleteView , minView -- * Traversal , map , fold' -- * Validity check , valid ) where import Prelude hiding (foldr, lookup, map, null) import Data.HashPSQ.Internal
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/Data.HashPSQ.hs
haskell
collisions, it uses an 'OrdPSQ' locally to solve those. since /log n/ is always smaller than /W/ on current machines. * Type * Query * Construction * Insertion * Delete/update * Lists * Views * Traversal * Validity check
# LANGUAGE Haskell98 # # LINE 1 " src / Data / HashPSQ.hs " # | A ' HashPSQ ' offers very similar performance to ' IntPSQ ' . In case of This means worst case complexity is usually given by /O(min(n , W ) , log n)/ , where /W/ is the number of bits in an ' Int ' . This simplifies to /O(min(n , W))/ module Data.HashPSQ HashPSQ , null , size , member , lookup , findMin , empty , singleton , insert , delete , deleteMin , alter , alterMin , fromList , toList , keys , insertView , deleteView , minView , map , fold' , valid ) where import Prelude hiding (foldr, lookup, map, null) import Data.HashPSQ.Internal
5fd0fd90ffb99b174482e1bde71650fdf40227021813642bb809a1197fea8220
spurious/sagittarius-scheme-mirror
ports.sps
#!r6rs (import (tests r6rs io ports) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs io ports)\n") (run-io-ports-tests) (report-test-results)
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/r6rs-test-suite/tests/r6rs/run/io/ports.sps
scheme
#!r6rs (import (tests r6rs io ports) (tests r6rs test) (rnrs io simple)) (display "Running tests for (rnrs io ports)\n") (run-io-ports-tests) (report-test-results)
b87a3dbf4fb9fb43dfa909e5003ecd4d4f0da4dcf8451d388a322fed0cc81277
mbutterick/brag
internal-support.rkt
#lang racket/base (require brag/support) (provide current-source current-parser-error-handler current-tokenizer-error-handler) ;; During parsing, we should define the source of the input. (define current-source (make-parameter 'unknown)) ;; When an parse error happens, we call the current-parser-error-handler: (define current-parser-error-handler (make-parameter (lambda (tok-name tok-value offset line col span) (raise (exn:fail:parsing (format "Encountered parsing error near ~e (token ~e) while parsing ~e [line=~a, column=~a, offset=~a]" tok-value tok-name (current-source) line col offset) (current-continuation-marks) (list (srcloc (current-source) line col offset span))))))) ;; When a tokenization error happens, we call the current-tokenizer-error-handler. (define current-tokenizer-error-handler (make-parameter (lambda (tok-type tok-value offset line column span) (raise (exn:fail:parsing (string-append (format "Encountered unexpected token of type ~e (value ~e) while parsing" (if (memq tok-type (map string->symbol '("\n" "\t" "\r"))) (format "~a" tok-type) tok-type) tok-value) (if (or (current-source) line column offset) (format " ~e [line=~a, column=~a, offset=~a]" (current-source) line column offset) "")) (current-continuation-marks) (list (srcloc (current-source) line column offset span)))))))
null
https://raw.githubusercontent.com/mbutterick/brag/6c161ae31df9b4ae7f55a14f754c0b216b60c9a6/brag-lib/brag/private/internal-support.rkt
racket
During parsing, we should define the source of the input. When an parse error happens, we call the current-parser-error-handler: When a tokenization error happens, we call the current-tokenizer-error-handler.
#lang racket/base (require brag/support) (provide current-source current-parser-error-handler current-tokenizer-error-handler) (define current-source (make-parameter 'unknown)) (define current-parser-error-handler (make-parameter (lambda (tok-name tok-value offset line col span) (raise (exn:fail:parsing (format "Encountered parsing error near ~e (token ~e) while parsing ~e [line=~a, column=~a, offset=~a]" tok-value tok-name (current-source) line col offset) (current-continuation-marks) (list (srcloc (current-source) line col offset span))))))) (define current-tokenizer-error-handler (make-parameter (lambda (tok-type tok-value offset line column span) (raise (exn:fail:parsing (string-append (format "Encountered unexpected token of type ~e (value ~e) while parsing" (if (memq tok-type (map string->symbol '("\n" "\t" "\r"))) (format "~a" tok-type) tok-type) tok-value) (if (or (current-source) line column offset) (format " ~e [line=~a, column=~a, offset=~a]" (current-source) line column offset) "")) (current-continuation-marks) (list (srcloc (current-source) line column offset span)))))))
747902da055a4566a5e50ada424ca571a9cb504b67d59df35b6efd59eb347f27
dharmatech/abstracting
str.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (str-obj s) (let ((len (string-length s)) (ref (lambda (i) (string-ref s i))) (set (lambda (i elt) (string-set! s i elt)))) (let ((first-index 0) (last-index (- len 1))) (let ((before-beginning? (lambda (i) (< i first-index))) (after-end? (lambda (i) (> i last-index)))) (let ((index-start-at (lambda (pred i past? step) (let loop ((i i)) (cond ((past? i) #f) ((pred (ref i)) i) (else (loop (step i 1)))))))) (let ((index-forward-start-at (lambda (pred i) (index-start-at pred i after-end? +))) (index-backward-start-at (lambda (pred i) (index-start-at pred i before-beginning? -)))) (let ((index-forward (lambda (pred) (index-forward-start-at pred first-index))) (index-backward (lambda (pred) (index-backward-start-at pred last-index)))) (let ((message-handler (lambda (msg) (case msg ((len) len) ((ref) ref) ((set) set) ((index-forward) index-forward) ((index-backward) index-backward) ;; ((raw) s) )))) (vector 'str s message-handler))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
null
https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/src/str/str.scm
scheme
(define (str-obj s) (let ((len (string-length s)) (ref (lambda (i) (string-ref s i))) (set (lambda (i elt) (string-set! s i elt)))) (let ((first-index 0) (last-index (- len 1))) (let ((before-beginning? (lambda (i) (< i first-index))) (after-end? (lambda (i) (> i last-index)))) (let ((index-start-at (lambda (pred i past? step) (let loop ((i i)) (cond ((past? i) #f) ((pred (ref i)) i) (else (loop (step i 1)))))))) (let ((index-forward-start-at (lambda (pred i) (index-start-at pred i after-end? +))) (index-backward-start-at (lambda (pred i) (index-start-at pred i before-beginning? -)))) (let ((index-forward (lambda (pred) (index-forward-start-at pred first-index))) (index-backward (lambda (pred) (index-backward-start-at pred last-index)))) (let ((message-handler (lambda (msg) (case msg ((len) len) ((ref) ref) ((set) set) ((index-forward) index-forward) ((index-backward) index-backward) ((raw) s) )))) (vector 'str s message-handler)))))))))
4a0ad808f1c0b6e209d5fe7b3894c0fa50f72fdadda092ba71836ac33c4d84d0
ocaml-sf/learn-ocaml-corpus
assured_win_incorrect.ml
open Seq (* -------------------------------------------------------------------------- *) (* The size of a tree. *) let rec size (t : tree) : int = match t with | TLeaf _ -> 1 | TNonLeaf offspring -> 1 + size_offspring offspring and size_offspring (offspring : offspring) : int = match offspring() with | Nil -> 0 | Cons ((_move, t), offspring) -> size t + size_offspring offspring (* -------------------------------------------------------------------------- *) (* The height of a tree. *) let rec height (t : tree) : int = match t with | TLeaf _ -> 0 | TNonLeaf offspring -> 1 + height_offspring offspring and height_offspring (offspring : offspring) : int = match offspring() with | Nil -> 0 | Cons ((_move, t), offspring) -> max (height t) (height_offspring offspring) (* -------------------------------------------------------------------------- *) (* Evaluating a tree, with a sense parameter: Minimax. *) let rec eval (sense : sense) (t : tree) : value = match t with | TLeaf v -> interpret sense v | TNonLeaf offspring -> eval_offspring sense offspring and eval_offspring (sense : sense) (offspring : offspring) : value = match offspring() with | Nil -> unit sense | Cons ((_move, t), offspring) -> join sense (eval (opposite sense) t) (eval_offspring sense offspring) (* -------------------------------------------------------------------------- *) (* Evaluating a tree, without a sense parameter: Negamax. *) let rec nval (t : tree) : value = match t with | TLeaf v -> v | TNonLeaf offspring -> nval_offspring offspring and nval_offspring (offspring : offspring) = match offspring() with | Nil -> bottom | Cons ((_move, t), offspring) -> max (- nval t) (nval_offspring offspring) (* -------------------------------------------------------------------------- *) Evaluating a tree , in Negamax style , and looping over children in a tail - recursive manner . a tail-recursive manner. *) let rec ntval (t : tree) : value = match t with | TLeaf v -> v | TNonLeaf offspring -> ntval_offspring bottom offspring and ntval_offspring (running_max : value) (offspring : offspring) : value = match offspring() with | Nil -> running_max | Cons ((_move, t), offspring) -> let v = - ntval t in let running_max = max running_max v in ntval_offspring running_max offspring (* -------------------------------------------------------------------------- *) Evaluating a tree , using the Alpha - Beta algorithm . let rec bval (alpha : value) (beta : value) (t : tree) : value = assert (alpha < beta); match t with | TLeaf v -> (* We could project [v] onto the closed interval [alpha, beta], but this does not make any difference; [v] is equivalent to its projection. *) v | TNonLeaf offspring -> bval_offspring alpha beta offspring and bval_offspring (alpha : value) (beta : value) (offspring : offspring) : value = assert (alpha < beta); match offspring() with | Nil -> (* We could return the maximum of the children that we have examined, but it would be less than or equal to [alpha], so it is equivalent to [alpha]. *) alpha | Cons ((_move, t), offspring) -> let v = - (bval (-beta) (-alpha) t) in if beta <= v then (* Returning [beta] or [v] makes no difference; they are equivalent. *) v else let alpha = max alpha v in (* Because v < beta holds, we still have alpha < beta. *) assert (alpha < beta); bval_offspring alpha beta offspring (* -------------------------------------------------------------------------- *) In a game tree where every leaf carries the value -1 ( loss ) , 0 ( draw ) , or +1 ( win ) , determining whether the first player is assured to win . or +1 (win), determining whether the first player is assured to win. *) let assured_win (t : tree) : bool = let loss = -1 in let draw = 0 in let win = +1 in bval loss draw t >= win (* wrong *) (* -------------------------------------------------------------------------- *) Evaluating a tree using Alpha - Beta and returning the best move . let rec bmove_offspring alpha beta (candidate : move option) offspring : move option = assert (alpha < beta); match offspring() with | Nil -> assert (candidate <> None); candidate | Cons ((move, t), offspring) -> let v = - (bval (-beta) (-alpha) t) in if beta <= v then Some move else let alpha, candidate = if alpha < v then (* This move improves on the previous moves: keep it. *) v, Some move else if candidate = None then (* There are no previous moves, so keep this move as a default. This ensures that we do not return [None] in the end. *) alpha, Some move else (* This move does not improve on the previous candidate move Discard it. *) alpha, candidate in (* Because v < beta holds, we still have alpha < beta. *) assert (alpha < beta); bmove_offspring alpha beta candidate offspring let bmove alpha beta t : move option = assert (alpha < beta); match t with | TLeaf v -> None | TNonLeaf offspring -> bmove_offspring alpha beta None offspring
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/alpha_beta/wrong/assured_win_incorrect.ml
ocaml
-------------------------------------------------------------------------- The size of a tree. -------------------------------------------------------------------------- The height of a tree. -------------------------------------------------------------------------- Evaluating a tree, with a sense parameter: Minimax. -------------------------------------------------------------------------- Evaluating a tree, without a sense parameter: Negamax. -------------------------------------------------------------------------- -------------------------------------------------------------------------- We could project [v] onto the closed interval [alpha, beta], but this does not make any difference; [v] is equivalent to its projection. We could return the maximum of the children that we have examined, but it would be less than or equal to [alpha], so it is equivalent to [alpha]. Returning [beta] or [v] makes no difference; they are equivalent. Because v < beta holds, we still have alpha < beta. -------------------------------------------------------------------------- wrong -------------------------------------------------------------------------- This move improves on the previous moves: keep it. There are no previous moves, so keep this move as a default. This ensures that we do not return [None] in the end. This move does not improve on the previous candidate move Discard it. Because v < beta holds, we still have alpha < beta.
open Seq let rec size (t : tree) : int = match t with | TLeaf _ -> 1 | TNonLeaf offspring -> 1 + size_offspring offspring and size_offspring (offspring : offspring) : int = match offspring() with | Nil -> 0 | Cons ((_move, t), offspring) -> size t + size_offspring offspring let rec height (t : tree) : int = match t with | TLeaf _ -> 0 | TNonLeaf offspring -> 1 + height_offspring offspring and height_offspring (offspring : offspring) : int = match offspring() with | Nil -> 0 | Cons ((_move, t), offspring) -> max (height t) (height_offspring offspring) let rec eval (sense : sense) (t : tree) : value = match t with | TLeaf v -> interpret sense v | TNonLeaf offspring -> eval_offspring sense offspring and eval_offspring (sense : sense) (offspring : offspring) : value = match offspring() with | Nil -> unit sense | Cons ((_move, t), offspring) -> join sense (eval (opposite sense) t) (eval_offspring sense offspring) let rec nval (t : tree) : value = match t with | TLeaf v -> v | TNonLeaf offspring -> nval_offspring offspring and nval_offspring (offspring : offspring) = match offspring() with | Nil -> bottom | Cons ((_move, t), offspring) -> max (- nval t) (nval_offspring offspring) Evaluating a tree , in Negamax style , and looping over children in a tail - recursive manner . a tail-recursive manner. *) let rec ntval (t : tree) : value = match t with | TLeaf v -> v | TNonLeaf offspring -> ntval_offspring bottom offspring and ntval_offspring (running_max : value) (offspring : offspring) : value = match offspring() with | Nil -> running_max | Cons ((_move, t), offspring) -> let v = - ntval t in let running_max = max running_max v in ntval_offspring running_max offspring Evaluating a tree , using the Alpha - Beta algorithm . let rec bval (alpha : value) (beta : value) (t : tree) : value = assert (alpha < beta); match t with | TLeaf v -> v | TNonLeaf offspring -> bval_offspring alpha beta offspring and bval_offspring (alpha : value) (beta : value) (offspring : offspring) : value = assert (alpha < beta); match offspring() with | Nil -> alpha | Cons ((_move, t), offspring) -> let v = - (bval (-beta) (-alpha) t) in if beta <= v then v else let alpha = max alpha v in assert (alpha < beta); bval_offspring alpha beta offspring In a game tree where every leaf carries the value -1 ( loss ) , 0 ( draw ) , or +1 ( win ) , determining whether the first player is assured to win . or +1 (win), determining whether the first player is assured to win. *) let assured_win (t : tree) : bool = let loss = -1 in let draw = 0 in let win = +1 in Evaluating a tree using Alpha - Beta and returning the best move . let rec bmove_offspring alpha beta (candidate : move option) offspring : move option = assert (alpha < beta); match offspring() with | Nil -> assert (candidate <> None); candidate | Cons ((move, t), offspring) -> let v = - (bval (-beta) (-alpha) t) in if beta <= v then Some move else let alpha, candidate = if alpha < v then v, Some move else if candidate = None then alpha, Some move else alpha, candidate in assert (alpha < beta); bmove_offspring alpha beta candidate offspring let bmove alpha beta t : move option = assert (alpha < beta); match t with | TLeaf v -> None | TNonLeaf offspring -> bmove_offspring alpha beta None offspring
774e2a201a85bebf960ada5241e855a2a14ebf57dae5337cb4561bacf7c91cb8
mirage/ptt
aggregate.ml
let ( <.> ) f g x = f (g x) module By_domain = Map.Make (struct type t = [ `host ] Domain_name.t let compare = Domain_name.compare end) module By_ipaddr = Map.Make (Ipaddr) type unresolved_elt = [ `All | `Postmaster | `Local of Emile.local list ] type resolved_elt = [ `All | `Local of Emile.local list ] let postmaster = [`Atom "Postmaster"] let equal_local = Emile.equal_local ~case_sensitive:true let add_unresolved ~domain elt unresolved = match elt, By_domain.find_opt domain unresolved with | `All, _ -> By_domain.add domain `All unresolved | _, Some `All | `Postmaster, Some `Postmaster -> unresolved | `Postmaster, Some (`Local vs) -> if List.exists (equal_local postmaster) vs then unresolved else By_domain.add domain (`Local (postmaster :: vs)) unresolved | `Local v, Some (`Local vs) -> if List.exists (equal_local v) vs then unresolved else By_domain.add domain (`Local (v :: vs)) unresolved | `Local v, Some `Postmaster -> By_domain.add domain (`Local [v; postmaster]) unresolved | `Postmaster, None -> By_domain.add domain `Postmaster unresolved | `Local v, None -> By_domain.add domain (`Local [v]) unresolved let add_resolved ipaddr elt resolved = match elt, By_ipaddr.find_opt ipaddr resolved with | `All, _ -> By_ipaddr.add ipaddr `All resolved | _, Some `All -> resolved | `Local v, Some (`Local vs) -> if List.exists (equal_local v) vs then resolved else By_ipaddr.add ipaddr (`Local (v :: vs)) resolved | `Local v, None -> By_ipaddr.add ipaddr (`Local [v]) resolved let aggregate_by_domains ~domain = let open Colombe in let open Forward_path in let fold (unresolved, resolved) = function | Postmaster -> add_unresolved ~domain `Postmaster unresolved, resolved | Forward_path {Path.domain= Domain.Domain v; Path.local; _} -> let domain = Domain_name.(host_exn <.> of_strings_exn) v in let local = Colombe_emile.of_local local in add_unresolved ~domain (`Local local) unresolved, resolved | Domain (Domain.Domain v) -> let domain = Domain_name.(host_exn <.> of_strings_exn) v in add_unresolved ~domain `All unresolved, resolved | Domain (Domain.IPv4 v4) -> unresolved, add_resolved (Ipaddr.V4 v4) `All resolved | Domain (Domain.IPv6 v6) -> unresolved, add_resolved (Ipaddr.V6 v6) `All resolved | Forward_path {Path.domain= Domain.IPv4 v4; Path.local; _} -> let local = Colombe_emile.of_local local in unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved | Forward_path {Path.domain= Domain.IPv6 v6; Path.local; _} -> let local = Colombe_emile.of_local local in unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved | Domain (Domain.Extension _) | Forward_path {Path.domain= Domain.Extension _; _} -> unresolved, resolved in TODO List.fold_left fold (By_domain.empty, By_ipaddr.empty)
null
https://raw.githubusercontent.com/mirage/ptt/b555f7b132850de257d8f8d731cdf2a7723c9ab1/lib/aggregate.ml
ocaml
let ( <.> ) f g x = f (g x) module By_domain = Map.Make (struct type t = [ `host ] Domain_name.t let compare = Domain_name.compare end) module By_ipaddr = Map.Make (Ipaddr) type unresolved_elt = [ `All | `Postmaster | `Local of Emile.local list ] type resolved_elt = [ `All | `Local of Emile.local list ] let postmaster = [`Atom "Postmaster"] let equal_local = Emile.equal_local ~case_sensitive:true let add_unresolved ~domain elt unresolved = match elt, By_domain.find_opt domain unresolved with | `All, _ -> By_domain.add domain `All unresolved | _, Some `All | `Postmaster, Some `Postmaster -> unresolved | `Postmaster, Some (`Local vs) -> if List.exists (equal_local postmaster) vs then unresolved else By_domain.add domain (`Local (postmaster :: vs)) unresolved | `Local v, Some (`Local vs) -> if List.exists (equal_local v) vs then unresolved else By_domain.add domain (`Local (v :: vs)) unresolved | `Local v, Some `Postmaster -> By_domain.add domain (`Local [v; postmaster]) unresolved | `Postmaster, None -> By_domain.add domain `Postmaster unresolved | `Local v, None -> By_domain.add domain (`Local [v]) unresolved let add_resolved ipaddr elt resolved = match elt, By_ipaddr.find_opt ipaddr resolved with | `All, _ -> By_ipaddr.add ipaddr `All resolved | _, Some `All -> resolved | `Local v, Some (`Local vs) -> if List.exists (equal_local v) vs then resolved else By_ipaddr.add ipaddr (`Local (v :: vs)) resolved | `Local v, None -> By_ipaddr.add ipaddr (`Local [v]) resolved let aggregate_by_domains ~domain = let open Colombe in let open Forward_path in let fold (unresolved, resolved) = function | Postmaster -> add_unresolved ~domain `Postmaster unresolved, resolved | Forward_path {Path.domain= Domain.Domain v; Path.local; _} -> let domain = Domain_name.(host_exn <.> of_strings_exn) v in let local = Colombe_emile.of_local local in add_unresolved ~domain (`Local local) unresolved, resolved | Domain (Domain.Domain v) -> let domain = Domain_name.(host_exn <.> of_strings_exn) v in add_unresolved ~domain `All unresolved, resolved | Domain (Domain.IPv4 v4) -> unresolved, add_resolved (Ipaddr.V4 v4) `All resolved | Domain (Domain.IPv6 v6) -> unresolved, add_resolved (Ipaddr.V6 v6) `All resolved | Forward_path {Path.domain= Domain.IPv4 v4; Path.local; _} -> let local = Colombe_emile.of_local local in unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved | Forward_path {Path.domain= Domain.IPv6 v6; Path.local; _} -> let local = Colombe_emile.of_local local in unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved | Domain (Domain.Extension _) | Forward_path {Path.domain= Domain.Extension _; _} -> unresolved, resolved in TODO List.fold_left fold (By_domain.empty, By_ipaddr.empty)
91bb1be5ed7a6e24c6b3ba61e69b1b78092b15c1e504096b06c87d9b1eba2e75
fulcro-legacy/semantic-ui-wrapper
ui_placeholder_line.cljs
(ns fulcrologic.semantic-ui.elements.placeholder.ui-placeholder-line (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/elements/Placeholder/PlaceholderLine" :default PlaceholderLine])) (def ui-placeholder-line "A placeholder can contain have lines of text. Props: - as (custom): An element type to render as (string or function). - className (string): Additional classes. - length (enum): A line can specify how long its contents should appear. (full, very long, long, medium, short, very short)" (h/factory-apply PlaceholderLine))
null
https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/elements/placeholder/ui_placeholder_line.cljs
clojure
(ns fulcrologic.semantic-ui.elements.placeholder.ui-placeholder-line (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/elements/Placeholder/PlaceholderLine" :default PlaceholderLine])) (def ui-placeholder-line "A placeholder can contain have lines of text. Props: - as (custom): An element type to render as (string or function). - className (string): Additional classes. - length (enum): A line can specify how long its contents should appear. (full, very long, long, medium, short, very short)" (h/factory-apply PlaceholderLine))
993717a32a6ce8cab9c5c3469552b2e8956c63ae4f0bf08710b7c876ad444856
ivanjovanovic/sicp
e-2.9.scm
Exercise 2.9 . ; The width of an interval is half of the difference between its upper and lower bounds . ; The width is a measure of the uncertainty of the number specified by the interval. For some arithmetic operations the width of the result of combining two intervals ; is a function only of the widths of the argument intervals, whereas for others the width ; of the combination is not a function of the widths of the argument intervals. Show that the width of the sum ( or difference ) of two intervals is a function only of the widths ; of the intervals being added (or subtracted). Give examples to show that this is not true ; for multiplication or division. ; ---------------------------------------------------- we can prove that sum - interval and sub - interaval produce ; forms where widths depend only on the widths of intervals. ; r1 = c1 - w1, c1 + w1 ; r2 = c2 - w2, c2 + w2 ; ; r1 + r2 = c1 - w1 + c2 - w2, c1 + w1 + c2 + w2 ; => c1 + c2 - (w1 + w2), c1 + c2 + (w1 + w2) ; r3 , c3 + w3 ; where c3 = c1 + c2 and w3 = w1 + w2 ; ; Similar we can prove for the substitution. ; ; We can check this on example (load "2.1.scm") (load "e-2.7.scm") (load "e-2.8.scm") c = 1 , w = 0.1 c = 3 , w = 0.5 what we expect is to get result for summation c = 4 , w = 0.6 (display (lower-bound (add-interval r1 r2))) (newline) (display (upper-bound (add-interval r2 r1))) (newline) here we expect c = 2 , w = 0.4 (display (lower-bound (sub-interval r2 r1))) (newline) (display (upper-bound (sub-interval r2 r1))) (newline) ; on next couple of examples we can show that for multiplication and ; division it is not that linear as before lets say that we expect c = c1*c2 and w = w1*w2 but it is not like that in fact . It can be expressed how ; w depends on c1, c2, w1 and w2 (display (lower-bound (mul-interval r1 r2))) (newline) (display (upper-bound (mul-interval r1 r2))) (newline)
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/2.1/e-2.9.scm
scheme
The width is a measure of the uncertainty of the number specified by the interval. is a function only of the widths of the argument intervals, whereas for others the width of the combination is not a function of the widths of the argument intervals. Show that of the intervals being added (or subtracted). Give examples to show that this is not true for multiplication or division. ---------------------------------------------------- forms where widths depend only on the widths of intervals. r1 = c1 - w1, c1 + w1 r2 = c2 - w2, c2 + w2 r1 + r2 = c1 - w1 + c2 - w2, c1 + w1 + c2 + w2 => c1 + c2 - (w1 + w2), c1 + c2 + (w1 + w2) where c3 = c1 + c2 and w3 = w1 + w2 Similar we can prove for the substitution. We can check this on example on next couple of examples we can show that for multiplication and division it is not that linear as before w depends on c1, c2, w1 and w2
Exercise 2.9 . The width of an interval is half of the difference between its upper and lower bounds . For some arithmetic operations the width of the result of combining two intervals the width of the sum ( or difference ) of two intervals is a function only of the widths we can prove that sum - interval and sub - interaval produce (load "2.1.scm") (load "e-2.7.scm") (load "e-2.8.scm") c = 1 , w = 0.1 c = 3 , w = 0.5 what we expect is to get result for summation c = 4 , w = 0.6 (display (lower-bound (add-interval r1 r2))) (newline) (display (upper-bound (add-interval r2 r1))) (newline) here we expect c = 2 , w = 0.4 (display (lower-bound (sub-interval r2 r1))) (newline) (display (upper-bound (sub-interval r2 r1))) (newline) lets say that we expect c = c1*c2 and w = w1*w2 but it is not like that in fact . It can be expressed how (display (lower-bound (mul-interval r1 r2))) (newline) (display (upper-bound (mul-interval r1 r2))) (newline)