_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
b7f2f4d7e4265caa50252f945e912620b1b0c4bf539531784181a82aa752282b
soegaard/urlang
test-async-and-await.rkt
#lang racket (require urlang urlang/extra) ;;; ;;; TEST ;;; ; This file contains tests for the async and await. ; Note: the keyword for ES6 let declarations is let-decl. ; we have used the keyword let for Racket-like let-expressions. ;;; Note: No output means all tests ran successfully. ;;; Note: You need to install node in order to run these tests. ;;; / ;;; Running these tests will for each module produce both a JavaScript file and a file containing names of exports . Then node ( a command line version of the JavaScript engine used in Chrome ) is invoked on the JavaScript file , and the ;;; output is compared with the expected output. run using Node ? print generated JavaScript ? (current-urlang-console.log-module-level-expr? #f) (require rackunit) note : only reads FIRST value (check-equal? (rs (urlang (urmodule test-async-and-await (import this setTimeout Promise) (define (pause value milliseconds) (new Promise (λ (resolve reject) (setTimeout (λ() (resolve value)) milliseconds)))) (var [result 0]) (define/async (f) (var [promise (await (pause "done" 1000))]) (:= result promise)) (f) ; don't exit before output (setTimeout (λ () (console.log result)) 2000)))) 'done)
null
https://raw.githubusercontent.com/soegaard/urlang/086622e2306e72731016c7108aca3328e5082aee/urlang/tests/test-async-and-await.rkt
racket
TEST This file contains tests for the async and await. Note: the keyword for ES6 let declarations is let-decl. we have used the keyword let for Racket-like let-expressions. Note: No output means all tests ran successfully. Note: You need to install node in order to run these tests. / Running these tests will for each module produce output is compared with the expected output. don't exit before output
#lang racket (require urlang urlang/extra) both a JavaScript file and a file containing names of exports . Then node ( a command line version of the JavaScript engine used in Chrome ) is invoked on the JavaScript file , and the run using Node ? print generated JavaScript ? (current-urlang-console.log-module-level-expr? #f) (require rackunit) note : only reads FIRST value (check-equal? (rs (urlang (urmodule test-async-and-await (import this setTimeout Promise) (define (pause value milliseconds) (new Promise (λ (resolve reject) (setTimeout (λ() (resolve value)) milliseconds)))) (var [result 0]) (define/async (f) (var [promise (await (pause "done" 1000))]) (:= result promise)) (f) (setTimeout (λ () (console.log result)) 2000)))) 'done)
02787600ca2bb1a2cccf28f654deec8b5a1a0ad6d184adfd854ccacf5558ba31
locusmath/locus
object.clj
(ns locus.associative-algebra.core.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.sequence.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.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.algebra.commutative.monoid.arithmetic :refer :all] [locus.set.action.core.protocols :refer :all] [locus.additive.base.core.protocols :refer :all] [locus.additive.semiring.core.object :refer :all] [locus.additive.semiring.core.morphism :refer :all] [locus.additive.ring.core.object :refer :all] [locus.additive.ring.core.morphism :refer :all])) ; Associative algebras ; Let R be a ring, then an associative algebra over R is a ring over R ; that is simultaneously a module over R. In some cases, the underlying ; base ring might be required to be a field, so that the associative ; algebra must necessarily form a field. (deftype AssociativeAlgebra [elems add mul scalars scale] ConcreteObject (underlying-set [this] elems) EffectSystem (actions [this] (underlying-set scalars)) (action-domain [this elem] elems) (apply-action [this action arg] (scale action arg))) (defmethod additive-semigroup AssociativeAlgebra [^AssociativeAlgebra algebra] (.add algebra)) (defmethod multiplicative-semigroup AssociativeAlgebra [^AssociativeAlgebra algebra] (.mul algebra)) (derive AssociativeAlgebra :locus.additive.base.core.protocols/semiring) ; Convert a ring homomorphism into an associative algebra (defn ring-homomorphism->algebra [hom] (let [target-ring (target-object hom) source-ring (source-object hom)] (AssociativeAlgebra. (underlying-set target-ring) (additive-semigroup target-ring) (multiplicative-semigroup target-ring) (underlying-set source-ring) (fn [source-element target-element] ((multiplicative-semigroup target-ring) [(hom source-element) target-element])))))
null
https://raw.githubusercontent.com/locusmath/locus/b232579217be4e39458410893827a84d744168e4/src/clojure/locus/associative_algebra/core/object.clj
clojure
Associative algebras Let R be a ring, then an associative algebra over R is a ring over R that is simultaneously a module over R. In some cases, the underlying base ring might be required to be a field, so that the associative algebra must necessarily form a field. Convert a ring homomorphism into an associative algebra
(ns locus.associative-algebra.core.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.sequence.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.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.algebra.commutative.monoid.arithmetic :refer :all] [locus.set.action.core.protocols :refer :all] [locus.additive.base.core.protocols :refer :all] [locus.additive.semiring.core.object :refer :all] [locus.additive.semiring.core.morphism :refer :all] [locus.additive.ring.core.object :refer :all] [locus.additive.ring.core.morphism :refer :all])) (deftype AssociativeAlgebra [elems add mul scalars scale] ConcreteObject (underlying-set [this] elems) EffectSystem (actions [this] (underlying-set scalars)) (action-domain [this elem] elems) (apply-action [this action arg] (scale action arg))) (defmethod additive-semigroup AssociativeAlgebra [^AssociativeAlgebra algebra] (.add algebra)) (defmethod multiplicative-semigroup AssociativeAlgebra [^AssociativeAlgebra algebra] (.mul algebra)) (derive AssociativeAlgebra :locus.additive.base.core.protocols/semiring) (defn ring-homomorphism->algebra [hom] (let [target-ring (target-object hom) source-ring (source-object hom)] (AssociativeAlgebra. (underlying-set target-ring) (additive-semigroup target-ring) (multiplicative-semigroup target-ring) (underlying-set source-ring) (fn [source-element target-element] ((multiplicative-semigroup target-ring) [(hom source-element) target-element])))))
cace17418a34f26ae046ccb32a9e2e23775017ab97b2591069e5626508bf7844
oakes/tile-soup
terraintypes.cljc
(ns tile-soup.terraintypes (:require [clojure.spec.alpha :as s] [tile-soup.utils :as u] [tile-soup.terrain :as terrain])) (defmulti spec :tag) (defmethod spec :terrain [_] ::terrain/terrain) (defmethod spec :default [x] (throw (ex-info (str (:tag x) " not supported in terraintypes tags") {}))) (s/def ::content (u/conformer spec)) (s/def ::terraintypes (s/keys :req-un [::content]))
null
https://raw.githubusercontent.com/oakes/tile-soup/e2d495523af59322891f667859d39478d118a7c2/src/tile_soup/terraintypes.cljc
clojure
(ns tile-soup.terraintypes (:require [clojure.spec.alpha :as s] [tile-soup.utils :as u] [tile-soup.terrain :as terrain])) (defmulti spec :tag) (defmethod spec :terrain [_] ::terrain/terrain) (defmethod spec :default [x] (throw (ex-info (str (:tag x) " not supported in terraintypes tags") {}))) (s/def ::content (u/conformer spec)) (s/def ::terraintypes (s/keys :req-un [::content]))
8d9679131fbff8289d21bad823880c70b4af4ce182195a64a0d67c1c117d6e81
illiichi/orenolisp
transforms.clj
(ns orenolisp.commands.transforms (:require [orenolisp.model.conversion :as conv] [orenolisp.model.forms :as form] [orenolisp.model.editor :as ed])) (defn- find-nearest-ident [editor ident-value] (ed/find-by-first-element editor #(ed/move % :parent) #(= (:value %) ident-value))) (defn- wrap-by-map [editor arg-node-id] (let [parent-editor (-> '(map (fn [___]) [___]) conv/convert-sexp->editor (ed/move [:root :child :right])) element-id (last (ed/get-ids parent-editor [:right :child]))] (-> editor (ed/add-editor :parent parent-editor) (ed/jump arg-node-id) (ed/swap element-id)))) (defn- add-map-arguments [editor ugen-name] (let [editor-map (find-nearest-ident editor ugen-name) map-ident-id (ed/get-id editor-map :child) target-id (ed/get-id editor :self) end-of-arg (-> editor-map (ed/move [:child :right :child :right :child :right]) (ed/move-most :right) (ed/get-id :self))] (-> editor (ed/jump end-of-arg) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/move [:parent :parent]) (ed/move-most :right) (ed/add :right (form/vector)) (ed/add :child (form/input-ident)) (ed/add-as-multiple-cursors) (ed/swap target-id) (ed/jump map-ident-id) (ed/move-most :right) (ed/move :child)))) (defn transform-to-map [editor] (if (ed/has-mark? editor) (-> editor (ed/with-marks (fn [editor [first-node-id & rest-node-ids]] (-> (reduce (fn [editor node-id] (-> editor (ed/push-new-multiple-cursors) (ed/jump node-id) (add-map-arguments "map"))) (wrap-by-map editor first-node-id) rest-node-ids)))) (ed/reverse-multicursors)) (add-map-arguments editor "map"))) (defn- transpose-vector [editor] (let [current-id (-> editor (ed/get-id :self)) arg-vectors (->> (-> editor (ed/move :parent) (ed/get-children-ids)) (drop-while #(not= current-id %))) [first-arg-ids & initial-rest-args-ids] (->> arg-vectors (map #(ed/get-children-ids editor %)))] (loop [editor editor [first-arg-id & rest-first-ids] first-arg-ids rest-args-ids initial-rest-args-ids] (let [next-editor (-> editor (ed/add first-arg-id :parent (form/vector))) parent-vec-id (ed/get-id next-editor :self) [next-editor rest-args-ids] (reduce (fn [[editor acc] [rest-arg-id & rest-ids]] [(if rest-arg-id (-> editor (ed/jump rest-arg-id) (ed/transport :child parent-vec-id)) editor) (conj acc rest-ids)]) [next-editor []] rest-args-ids)] (if (nil? rest-first-ids) (reduce ed/delete next-editor (rest arg-vectors)) (recur next-editor rest-first-ids rest-args-ids)))))) (defn- convert-additional-t-map-argument [org-editor] (-> (reduce (fn [editor node-id] (ed/add-editor editor node-id :child (conv/sub-editor org-editor))) org-editor (ed/get-children-ids (-> org-editor (ed/move [:parent :left])))) (ed/delete (ed/get-id org-editor :parent)))) (defn transform-to-t-map [editor] (if (ed/has-mark? editor) (let [editor (-> (transform-to-map editor) (find-nearest-ident "map") (ed/move :child)) map-id (ed/get-id editor :self)] (-> editor (ed/edit map-id #(assoc % :value "u/t-map")) (ed/move [:right :right]) (transpose-vector))) (-> editor (add-map-arguments "u/t-map") (convert-additional-t-map-argument)))) (defn wrap-by-reduce [editor] (let [parent-editor (-> '(u/reduce-> (fn [acc x]) [x]) conv/convert-sexp->editor (ed/move [:root :child :right])) element-id (last (ed/get-ids parent-editor [:right :child]))] (-> editor (ed/add-editor :parent parent-editor) (ed/with-marks (fn [editor [arg-node-id]] (when arg-node-id (-> editor (ed/jump arg-node-id) (ed/add :left (form/ident "acc")) (ed/move :right) (ed/swap element-id)))))))) (defn threading [editor] (let [parent-editor (-> (conv/convert-sexp->editor '(->)) (ed/move :root)) first-arg-id (ed/get-id parent-editor :child)] (-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :child :right]) (ed/transport :right first-arg-id)))) (defn- transform-sexp [editor f] (let [new-editor (-> editor (conv/convert-editor->sexp (ed/get-id editor :self)) f (conv/convert-sexp->editor))] (ed/add-editor editor :self new-editor))) (defn wrap-by-range [ugen] (fn [editor] (transform-sexp editor (fn [sexp] (list 'u/lin-lin (list ugen 1) sexp sexp))))) (defn wrap-by-line [editor] (let [node-id (ed/get-id editor :self)] (-> editor (transform-sexp (fn [sexp] (list 'u/tap-line node-id sexp sexp 16 false))) (ed/move :parent) ;; fixme when node-id has been changed (as-> editor (ed/edit editor #(assoc % :node-id (ed/get-id editor :self))))))) (defn- let-binding-for-new [editor] (let [parent-editor (-> '(let [___ ___]) conv/convert-sexp->editor (ed/move :root)) func-arg-id (last (ed/get-ids parent-editor [:child :right :child :right]))] (some-> editor (ed/add-editor :parent parent-editor) (ed/with-marks (fn [editor [arg-node-id]] (when arg-node-id (-> editor (ed/jump arg-node-id) (ed/swap func-arg-id) (ed/move :left)))))))) (defn- let-binding-for-add [editor] (when-let [editor-let (find-nearest-ident editor "let")] (let [end-of-binding (-> editor-let (ed/move [:child :right :child]) (ed/move-most :right) (ed/get-id :self)) target-id (ed/get-id editor :self)] (-> editor (ed/jump end-of-binding) (ed/add :right (form/new-line)) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/swap target-id))))) (defn let-binding [editor] (if (ed/has-mark? editor) (let-binding-for-new editor) (let-binding-for-add editor))) (defn append-splay-tanh [editor] (let [parent-editor (-> '(-> (splay) tanh) conv/convert-sexp->editor (ed/move :root)) threading-node-id (ed/get-id parent-editor :child)] (some-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :right :right]) (ed/transport :right threading-node-id)))) (defn iterate-multiply [editor] (let [parent-editor (-> '(iterate (fn [x] (* x))) conv/convert-sexp->editor (ed/move :root))] (some-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :child :right :right :child :right]) (ed/add :right (form/input-ident)))))
null
https://raw.githubusercontent.com/illiichi/orenolisp/7b085fb687dbe16b5cbe8c739238bbaf79156814/src/orenolisp/commands/transforms.clj
clojure
fixme when node-id has been changed
(ns orenolisp.commands.transforms (:require [orenolisp.model.conversion :as conv] [orenolisp.model.forms :as form] [orenolisp.model.editor :as ed])) (defn- find-nearest-ident [editor ident-value] (ed/find-by-first-element editor #(ed/move % :parent) #(= (:value %) ident-value))) (defn- wrap-by-map [editor arg-node-id] (let [parent-editor (-> '(map (fn [___]) [___]) conv/convert-sexp->editor (ed/move [:root :child :right])) element-id (last (ed/get-ids parent-editor [:right :child]))] (-> editor (ed/add-editor :parent parent-editor) (ed/jump arg-node-id) (ed/swap element-id)))) (defn- add-map-arguments [editor ugen-name] (let [editor-map (find-nearest-ident editor ugen-name) map-ident-id (ed/get-id editor-map :child) target-id (ed/get-id editor :self) end-of-arg (-> editor-map (ed/move [:child :right :child :right :child :right]) (ed/move-most :right) (ed/get-id :self))] (-> editor (ed/jump end-of-arg) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/move [:parent :parent]) (ed/move-most :right) (ed/add :right (form/vector)) (ed/add :child (form/input-ident)) (ed/add-as-multiple-cursors) (ed/swap target-id) (ed/jump map-ident-id) (ed/move-most :right) (ed/move :child)))) (defn transform-to-map [editor] (if (ed/has-mark? editor) (-> editor (ed/with-marks (fn [editor [first-node-id & rest-node-ids]] (-> (reduce (fn [editor node-id] (-> editor (ed/push-new-multiple-cursors) (ed/jump node-id) (add-map-arguments "map"))) (wrap-by-map editor first-node-id) rest-node-ids)))) (ed/reverse-multicursors)) (add-map-arguments editor "map"))) (defn- transpose-vector [editor] (let [current-id (-> editor (ed/get-id :self)) arg-vectors (->> (-> editor (ed/move :parent) (ed/get-children-ids)) (drop-while #(not= current-id %))) [first-arg-ids & initial-rest-args-ids] (->> arg-vectors (map #(ed/get-children-ids editor %)))] (loop [editor editor [first-arg-id & rest-first-ids] first-arg-ids rest-args-ids initial-rest-args-ids] (let [next-editor (-> editor (ed/add first-arg-id :parent (form/vector))) parent-vec-id (ed/get-id next-editor :self) [next-editor rest-args-ids] (reduce (fn [[editor acc] [rest-arg-id & rest-ids]] [(if rest-arg-id (-> editor (ed/jump rest-arg-id) (ed/transport :child parent-vec-id)) editor) (conj acc rest-ids)]) [next-editor []] rest-args-ids)] (if (nil? rest-first-ids) (reduce ed/delete next-editor (rest arg-vectors)) (recur next-editor rest-first-ids rest-args-ids)))))) (defn- convert-additional-t-map-argument [org-editor] (-> (reduce (fn [editor node-id] (ed/add-editor editor node-id :child (conv/sub-editor org-editor))) org-editor (ed/get-children-ids (-> org-editor (ed/move [:parent :left])))) (ed/delete (ed/get-id org-editor :parent)))) (defn transform-to-t-map [editor] (if (ed/has-mark? editor) (let [editor (-> (transform-to-map editor) (find-nearest-ident "map") (ed/move :child)) map-id (ed/get-id editor :self)] (-> editor (ed/edit map-id #(assoc % :value "u/t-map")) (ed/move [:right :right]) (transpose-vector))) (-> editor (add-map-arguments "u/t-map") (convert-additional-t-map-argument)))) (defn wrap-by-reduce [editor] (let [parent-editor (-> '(u/reduce-> (fn [acc x]) [x]) conv/convert-sexp->editor (ed/move [:root :child :right])) element-id (last (ed/get-ids parent-editor [:right :child]))] (-> editor (ed/add-editor :parent parent-editor) (ed/with-marks (fn [editor [arg-node-id]] (when arg-node-id (-> editor (ed/jump arg-node-id) (ed/add :left (form/ident "acc")) (ed/move :right) (ed/swap element-id)))))))) (defn threading [editor] (let [parent-editor (-> (conv/convert-sexp->editor '(->)) (ed/move :root)) first-arg-id (ed/get-id parent-editor :child)] (-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :child :right]) (ed/transport :right first-arg-id)))) (defn- transform-sexp [editor f] (let [new-editor (-> editor (conv/convert-editor->sexp (ed/get-id editor :self)) f (conv/convert-sexp->editor))] (ed/add-editor editor :self new-editor))) (defn wrap-by-range [ugen] (fn [editor] (transform-sexp editor (fn [sexp] (list 'u/lin-lin (list ugen 1) sexp sexp))))) (defn wrap-by-line [editor] (let [node-id (ed/get-id editor :self)] (-> editor (transform-sexp (fn [sexp] (list 'u/tap-line node-id sexp sexp 16 false))) (ed/move :parent) (as-> editor (ed/edit editor #(assoc % :node-id (ed/get-id editor :self))))))) (defn- let-binding-for-new [editor] (let [parent-editor (-> '(let [___ ___]) conv/convert-sexp->editor (ed/move :root)) func-arg-id (last (ed/get-ids parent-editor [:child :right :child :right]))] (some-> editor (ed/add-editor :parent parent-editor) (ed/with-marks (fn [editor [arg-node-id]] (when arg-node-id (-> editor (ed/jump arg-node-id) (ed/swap func-arg-id) (ed/move :left)))))))) (defn- let-binding-for-add [editor] (when-let [editor-let (find-nearest-ident editor "let")] (let [end-of-binding (-> editor-let (ed/move [:child :right :child]) (ed/move-most :right) (ed/get-id :self)) target-id (ed/get-id editor :self)] (-> editor (ed/jump end-of-binding) (ed/add :right (form/new-line)) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/add :right (form/input-ident)) (ed/add-as-multiple-cursors) (ed/swap target-id))))) (defn let-binding [editor] (if (ed/has-mark? editor) (let-binding-for-new editor) (let-binding-for-add editor))) (defn append-splay-tanh [editor] (let [parent-editor (-> '(-> (splay) tanh) conv/convert-sexp->editor (ed/move :root)) threading-node-id (ed/get-id parent-editor :child)] (some-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :right :right]) (ed/transport :right threading-node-id)))) (defn iterate-multiply [editor] (let [parent-editor (-> '(iterate (fn [x] (* x))) conv/convert-sexp->editor (ed/move :root))] (some-> editor (ed/add-editor :parent parent-editor) (ed/move [:child :right :child :right :right :child :right]) (ed/add :right (form/input-ident)))))
a305ac3b8932d2a325d756d4d04fccbf5409adac3253b2991b316615a1e944ba
timothypratley/leaderboardx
common.cljs
(ns algopop.leaderboardx.app.views.common (:require [goog.dom.forms :as forms] [reagent.core :as reagent] [reagent.dom :as dom] [cljs.test :as t :include-macros true :refer-macros [testing is]] [devcards.core :as dc :refer-macros [defcard deftest]] [cljs.tools.reader.edn :as edn])) TODO : advanced mode ( set / map - invert ( js->clj KeyCodes ) ) (def key-code-name {13 "ENTER" 27 "ESC" 46 "DELETE" 8 "BACKSPACE"}) (defn blur-active-input [] (let [activeElement (.-activeElement js/document)] (when (some-> activeElement (.-tagName) #{"INPUT" "TEXTAREA"}) (.blur activeElement)))) (defn save [write a b] (when (and write (not= a b)) (write b))) (defn editable-string [default-value write attrs input-type] (let [visible-value (reagent/atom default-value) current-default (reagent/atom default-value)] (fn an-editable-string [default-value write attrs input-type] (when (not= default-value @current-default) (reset! current-default default-value) (reset! visible-value default-value)) [:input (merge-with merge ;; TODO: what about decimal numbers? {:type input-type :style {:width "100%" :border "1px solid #f0f0f0" :background-color (if (= default-value @visible-value) "white" "#f8f8f8")} :value @visible-value :on-change (fn editable-string-change [e] (reset! visible-value ;; TODO: is this the right way to get numbers? /shrug seems to work (cond-> (.. e -target -value) (= input-type "number") (js/parseFloat)))) :on-blur (fn editable-string-blur [e] (save write default-value @visible-value)) :on-key-down (fn editable-string-key-down [e] (.stopPropagation e) (.stopImmediatePropagation (.-nativeEvent e)) (case (key-code-name (.-keyCode e)) "ESC" (do (reset! visible-value default-value) (blur-active-input)) "ENTER" (do (.preventDefault e) (save write default-value @visible-value)) nil))} attrs)]))) (defcard editable-string-example "editable string" (dc/reagent [editable-string "foo" (fn [x] x)])) ;; TODO: move tests to another namespace to save production build size (deftest some-test "blah blah blah" (testing "zzz" (is (= 1 2) "nah") (is (= 1 1) "obviously"))) (defn form-data "Returns a kewordized map of forms input name, value pairs." [e] (.preventDefault e) (into {} (for [[k v] (js->clj (.toObject (forms/getFormDataMap (.-target e))))] [(keyword k) (if (<= (count v) 1) (first v) v)]))) (defn selectable [default-value write values labels] (into [:select {:value (pr-str default-value) :on-change (fn selection-change [e] (save write default-value (edn/read-string (.. e -target -value))))}] (for [[value label] (map vector values (or labels (map str values)))] [:option {:value (pr-str value)} label]))) (defn add [label write] (let [show? (reagent/atom false)] (fn an-add [label write] (if @show? [editable-string "" (fn [v] (swap! show? not) (write v)) {:auto-focus true :style {:text-align "right"}}] [:button.btn.btn-default.btn-sm {:style {:width "100%"} :on-click (fn add-click [e] (swap! show? not))} label])))) (defn single-entity-editor [id entity title add-attribute remove-attribute schema] ;; TODO: make collapsable?? (let [just-added (reagent/atom nil)] (fn a-single-entity-editor [id entity title add-attribute remove-attribute schema] [:div.form-inline [:table.table.table-responsive.panel.panel-default [:thead [:tr [:td {:col-span 3} [:h3 [:i title]]]]] [:tbody (doall (for [[attribute value] (sort entity) :let [options (get schema attribute)] :when (not= options :hide)] ^{:key attribute} [:tr [:td {:style {:font-weight "bold" :width "40%" :text-align "right"}} attribute ":"] [:td {:style {:width "60%"}} (cond (seq? options) (if (<= (count options) 1) [:div value] [selectable value #(add-attribute id attribute %) options]) (= options :number) [editable-string value #(add-attribute id attribute %) {:auto-focus (= attribute @just-added)} "number"] :else [editable-string value #(add-attribute id attribute %) {:auto-focus (= attribute @just-added)}])] [:td [:button.close {:on-click (fn click-clear-attribute [e] TODO : currently you can remove a node / type ! that seems wrong ... ;; maybe... but it works? maybe not a bad thing? (remove-attribute id attribute))} "×"]]])) [:tr [:td {:style {:text-align "right" :width "40%"}} [add "Add attribute" (fn click-add-attribute [x] ;; TODO: entities might not be either nodes or edges? (let [attribute (keyword (if (vector? id) "edge" "node") x)] (reset! just-added attribute) (add-attribute id attribute "")))]] [:td] [:td]]]]]))) TODO : idea - have 3 text boxes , just like graph node entry but for entity / (defn entity-editor [heading entities add-entity remove-entity add-attribute remove-attribute schema] [:div [:h3 heading] [:ul.list-unstyled [:li.row [:div.col-xs-3 {:style {:text-align "right"}} [add "Add" add-entity]]] (for [[entity-name entity] (sort entities)] ^{:key entity-name} [:li.row {:style {:padding "10px"}} [:div.col-xs-11 [single-entity-editor entity-name entity entity-name add-attribute remove-attribute schema]] [:div.col-xs-1 {:style {:text-align "right"}} [:button.close {:style {:float "left"} :on-click (fn [e] (remove-entity entity-name))} "×"]]])]])
null
https://raw.githubusercontent.com/timothypratley/leaderboardx/ad1719b3bb49fb7ab495ed833f1a451ebb3aec4d/src/algopop/leaderboardx/app/views/common.cljs
clojure
TODO: what about decimal numbers? TODO: is this the right way to get numbers? /shrug seems to work TODO: move tests to another namespace to save production build size TODO: make collapsable?? maybe... but it works? maybe not a bad thing? TODO: entities might not be either nodes or edges?
(ns algopop.leaderboardx.app.views.common (:require [goog.dom.forms :as forms] [reagent.core :as reagent] [reagent.dom :as dom] [cljs.test :as t :include-macros true :refer-macros [testing is]] [devcards.core :as dc :refer-macros [defcard deftest]] [cljs.tools.reader.edn :as edn])) TODO : advanced mode ( set / map - invert ( js->clj KeyCodes ) ) (def key-code-name {13 "ENTER" 27 "ESC" 46 "DELETE" 8 "BACKSPACE"}) (defn blur-active-input [] (let [activeElement (.-activeElement js/document)] (when (some-> activeElement (.-tagName) #{"INPUT" "TEXTAREA"}) (.blur activeElement)))) (defn save [write a b] (when (and write (not= a b)) (write b))) (defn editable-string [default-value write attrs input-type] (let [visible-value (reagent/atom default-value) current-default (reagent/atom default-value)] (fn an-editable-string [default-value write attrs input-type] (when (not= default-value @current-default) (reset! current-default default-value) (reset! visible-value default-value)) [:input (merge-with merge {:type input-type :style {:width "100%" :border "1px solid #f0f0f0" :background-color (if (= default-value @visible-value) "white" "#f8f8f8")} :value @visible-value :on-change (fn editable-string-change [e] (reset! visible-value (cond-> (.. e -target -value) (= input-type "number") (js/parseFloat)))) :on-blur (fn editable-string-blur [e] (save write default-value @visible-value)) :on-key-down (fn editable-string-key-down [e] (.stopPropagation e) (.stopImmediatePropagation (.-nativeEvent e)) (case (key-code-name (.-keyCode e)) "ESC" (do (reset! visible-value default-value) (blur-active-input)) "ENTER" (do (.preventDefault e) (save write default-value @visible-value)) nil))} attrs)]))) (defcard editable-string-example "editable string" (dc/reagent [editable-string "foo" (fn [x] x)])) (deftest some-test "blah blah blah" (testing "zzz" (is (= 1 2) "nah") (is (= 1 1) "obviously"))) (defn form-data "Returns a kewordized map of forms input name, value pairs." [e] (.preventDefault e) (into {} (for [[k v] (js->clj (.toObject (forms/getFormDataMap (.-target e))))] [(keyword k) (if (<= (count v) 1) (first v) v)]))) (defn selectable [default-value write values labels] (into [:select {:value (pr-str default-value) :on-change (fn selection-change [e] (save write default-value (edn/read-string (.. e -target -value))))}] (for [[value label] (map vector values (or labels (map str values)))] [:option {:value (pr-str value)} label]))) (defn add [label write] (let [show? (reagent/atom false)] (fn an-add [label write] (if @show? [editable-string "" (fn [v] (swap! show? not) (write v)) {:auto-focus true :style {:text-align "right"}}] [:button.btn.btn-default.btn-sm {:style {:width "100%"} :on-click (fn add-click [e] (swap! show? not))} label])))) (defn single-entity-editor [id entity title add-attribute remove-attribute schema] (let [just-added (reagent/atom nil)] (fn a-single-entity-editor [id entity title add-attribute remove-attribute schema] [:div.form-inline [:table.table.table-responsive.panel.panel-default [:thead [:tr [:td {:col-span 3} [:h3 [:i title]]]]] [:tbody (doall (for [[attribute value] (sort entity) :let [options (get schema attribute)] :when (not= options :hide)] ^{:key attribute} [:tr [:td {:style {:font-weight "bold" :width "40%" :text-align "right"}} attribute ":"] [:td {:style {:width "60%"}} (cond (seq? options) (if (<= (count options) 1) [:div value] [selectable value #(add-attribute id attribute %) options]) (= options :number) [editable-string value #(add-attribute id attribute %) {:auto-focus (= attribute @just-added)} "number"] :else [editable-string value #(add-attribute id attribute %) {:auto-focus (= attribute @just-added)}])] [:td [:button.close {:on-click (fn click-clear-attribute [e] TODO : currently you can remove a node / type ! that seems wrong ... (remove-attribute id attribute))} "×"]]])) [:tr [:td {:style {:text-align "right" :width "40%"}} [add "Add attribute" (fn click-add-attribute [x] (let [attribute (keyword (if (vector? id) "edge" "node") x)] (reset! just-added attribute) (add-attribute id attribute "")))]] [:td] [:td]]]]]))) TODO : idea - have 3 text boxes , just like graph node entry but for entity / (defn entity-editor [heading entities add-entity remove-entity add-attribute remove-attribute schema] [:div [:h3 heading] [:ul.list-unstyled [:li.row [:div.col-xs-3 {:style {:text-align "right"}} [add "Add" add-entity]]] (for [[entity-name entity] (sort entities)] ^{:key entity-name} [:li.row {:style {:padding "10px"}} [:div.col-xs-11 [single-entity-editor entity-name entity entity-name add-attribute remove-attribute schema]] [:div.col-xs-1 {:style {:text-align "right"}} [:button.close {:style {:float "left"} :on-click (fn [e] (remove-entity entity-name))} "×"]]])]])
bd46ac01cf5148546a2b55a652661902f4494e21dffd61b6a5b228ebeb864317
rd--/hsc3
hairCell.help.hs
hairCell ; constantly self oscillates at 5 Hz pan2 (X.hairCell (soundIn 0) 5.0 100 1000 0.99) 0 0.1 -- hairCell pan2 (X.hairCell (saw ar (mouseX kr 1 10 Linear 0.2)) 0 (mouseY kr 0 10000 Linear 0.2) 1000 0.99) 0 0.5
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/hairCell.help.hs
haskell
hairCell
hairCell ; constantly self oscillates at 5 Hz pan2 (X.hairCell (soundIn 0) 5.0 100 1000 0.99) 0 0.1 pan2 (X.hairCell (saw ar (mouseX kr 1 10 Linear 0.2)) 0 (mouseY kr 0 10000 Linear 0.2) 1000 0.99) 0 0.5
b4efdc6fe07b902ed3a6388fc1a80cf09c984458741a14c84c1dc1bcb10d7df2
ArtichOwO/r86
main.ml
open R86 open Args let () = Arg.parse speclist anon_fun usage_msg; match List.hd !input_file with | "" -> Log.log @@ Log.SysError "No input file specified."; exit 1 | _ -> ( if !compile then let file_content = try Core.In_channel.read_all @@ List.hd !input_file with e -> ( match e with | Sys_error se -> Log.log @@ Log.SysError se; exit 1 | _ as error -> raise error) in if !write_asm then ( let oc = open_out !output_file in match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> output_string oc @@ Ast.eval_program ast | Error msg -> Log.log msg; close_out oc) else if !to_stdout then match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> print_endline @@ Ast.eval_program ast | Error msg -> Log.log msg else let _ = Sys.command "mkdir -p /tmp/r86" and id = let replace_char = function '-' -> '_' | _ as c -> c in Uuidm.v4_gen (Random.State.make_self_init ()) () |> Uuidm.to_string ~upper:true |> String.map replace_char in let oc = open_out @@ Printf.sprintf "/tmp/r86/%s.asm" id in match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> output_string oc @@ Ast.eval_program ast; let status = Unix.create_process "nasm" [| "nasm"; Printf.sprintf "/tmp/r86/%s.asm" id; "-f"; "elf"; "-o"; !output_file; |] Unix.stdin Unix.stdout Unix.stderr in exit status | Error msg -> Log.log msg; close_out oc)
null
https://raw.githubusercontent.com/ArtichOwO/r86/85d118561ec7c52e969a6439a0e6a451ff81c796/bin/main.ml
ocaml
open R86 open Args let () = Arg.parse speclist anon_fun usage_msg; match List.hd !input_file with | "" -> Log.log @@ Log.SysError "No input file specified."; exit 1 | _ -> ( if !compile then let file_content = try Core.In_channel.read_all @@ List.hd !input_file with e -> ( match e with | Sys_error se -> Log.log @@ Log.SysError se; exit 1 | _ as error -> raise error) in if !write_asm then ( let oc = open_out !output_file in match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> output_string oc @@ Ast.eval_program ast | Error msg -> Log.log msg; close_out oc) else if !to_stdout then match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> print_endline @@ Ast.eval_program ast | Error msg -> Log.log msg else let _ = Sys.command "mkdir -p /tmp/r86" and id = let replace_char = function '-' -> '_' | _ as c -> c in Uuidm.v4_gen (Random.State.make_self_init ()) () |> Uuidm.to_string ~upper:true |> String.map replace_char in let oc = open_out @@ Printf.sprintf "/tmp/r86/%s.asm" id in match Parsing.parse (Lexing.from_string file_content) with | Ok ast -> output_string oc @@ Ast.eval_program ast; let status = Unix.create_process "nasm" [| "nasm"; Printf.sprintf "/tmp/r86/%s.asm" id; "-f"; "elf"; "-o"; !output_file; |] Unix.stdin Unix.stdout Unix.stderr in exit status | Error msg -> Log.log msg; close_out oc)
781f450accf268862b28007ce8bab6fa2934f35286d723e61411faff4ec23e6e
realworldocaml/book
ppx_bin_prot.ml
(** Ppx_bin_prot: Preprocessing Module for a Type Safe Binary Protocol *) open Base open Ppxlib open Ast_builder.Default let ( @@ ) a b = a b (* +-----------------------------------------------------------------+ | Signature generators | +-----------------------------------------------------------------+ *) module Sig = struct let mk_sig_generator combinators = let mk_sig ~ctxt:_ (_rf, tds) = List.concat_map tds ~f:(fun td -> let td = name_type_params_in_td td in List.map combinators ~f:(fun mk -> mk td)) in Deriving.Generator.V2.make Deriving.Args.empty mk_sig ;; let mk_typ ?(wrap_result = fun ~loc:_ x -> x) type_constr td = let loc = td.ptype_loc in let id = Longident.parse type_constr in let wrap_type ~loc t = ptyp_constr ~loc (Located.mk ~loc id) [ t ] in let result_type = wrap_type ~loc:td.ptype_name.loc (wrap_result ~loc (core_type_of_type_declaration td)) in List.fold_right td.ptype_params ~init:result_type ~f:(fun (tp, _variance) acc -> let loc = tp.ptyp_loc in ptyp_arrow ~loc Nolabel (wrap_type ~loc tp) acc) ;; let mk name_format type_constr ?wrap_result td = let loc = td.ptype_loc in let name = Loc.map ~f:(Printf.sprintf name_format) td.ptype_name in let typ = mk_typ ?wrap_result type_constr td in psig_value ~loc (value_description ~loc ~name ~type_:typ ~prim:[]) ;; let bin_write = mk_sig_generator [ mk "bin_size_%s" "Bin_prot.Size.sizer" ; mk "bin_write_%s" "Bin_prot.Write.writer" ; mk "bin_writer_%s" "Bin_prot.Type_class.writer" ] ;; let bin_read = mk_sig_generator [ mk "bin_read_%s" "Bin_prot.Read.reader" ; mk "__bin_read_%s__" "Bin_prot.Read.reader" ~wrap_result:(fun ~loc t -> [%type: int -> [%t t]]) ; mk "bin_reader_%s" "Bin_prot.Type_class.reader" ] ;; let bin_type_class = mk_sig_generator [ mk "bin_%s" "Bin_prot.Type_class.t" ] let named = let mk_named_sig ~ctxt (rf, tds) = let loc = Expansion_context.Deriver.derived_item_loc ctxt in match mk_named_sig ~loc ~sg_name:"Bin_prot.Binable.S" ~handle_polymorphic_variant:true tds with | Some incl -> [ psig_include ~loc incl ] | None -> List.concat_map [ Bin_shape_expand.sig_gen; bin_write; bin_read; bin_type_class ] ~f:(fun gen -> Deriving.Generator.apply ~name:"unused" gen ~ctxt (rf, tds) []) in Deriving.Generator.V2.make Deriving.Args.empty mk_named_sig ;; end (* +-----------------------------------------------------------------+ | Utility functions | +-----------------------------------------------------------------+ *) let atoms_in_row_fields row_fields = List.exists row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag (_, is_constant, _) -> is_constant | Rinherit _ -> false) ;; let atoms_in_variant cds = List.filter cds ~f:(fun cds -> match cds.pcd_args with | Pcstr_tuple [] -> true | Pcstr_tuple _ -> false | Pcstr_record _ -> false) ;; let let_ins loc bindings expr = List.fold_right bindings ~init:expr ~f:(fun binding expr -> pexp_let ~loc Nonrecursive [ binding ] expr) ;; let alias_or_fun expr fct = let is_id = match expr.pexp_desc with | Pexp_ident _ -> true | _ -> false in if is_id then expr else fct ;; let td_is_nil td = match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, None -> true | _ -> false ;; type var = string Located.t let vars_of_params ~prefix td = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in { name with txt = prefix ^ name.txt }) ;; let map_vars vars ~f = List.map vars ~f:(fun (v : var) -> f ~loc:v.loc v.txt) let patts_of_vars = map_vars ~f:pvar let exprs_of_vars = map_vars ~f:evar let project_vars expr vars ~record_type ~field_name = let args = map_vars vars ~f:(fun ~loc txt -> let record = pexp_constraint ~loc (evar ~loc txt) record_type in pexp_field ~loc record (Located.mk ~loc (Lident field_name))) in let loc = expr.pexp_loc in eapply ~loc expr args ;; module Full_type_name : sig type t val make : path:string -> type_declaration -> t val absent : t val get : t -> string option val get_exn : loc:Location.t -> t -> string end = struct type t = string option let make ~path td = Some (Printf.sprintf "%s.%s" path td.ptype_name.txt) let absent = None let get t = t let get_exn ~loc t = match t with | Some n -> n | None -> Location.raise_errorf ~loc "Bug in ppx_bin_prot: full type name needed but not in a type declaration.\n\ Callstack:\n\ %s" (Stdlib.Printexc.get_callstack 256 |> Stdlib.Printexc.raw_backtrace_to_string) ;; end let generate_poly_type ?wrap_result ~loc td constructor = ptyp_poly ~loc (List.map td.ptype_params ~f:get_type_param_name) (Sig.mk_typ ?wrap_result constructor td) ;; Determines whether or not the generated code associated with a type declaration should include explicit type signatures . In particular , we 'd rather not add an explicit type signature when polymorphic variants are involved . As discussed in However , if we have mutually recursive type declarations involving polymorphic type constructors where we add a type declaration to one of them , we need it on all of them , otherwise we 'll generate ill - typed code . a type declaration should include explicit type signatures. In particular, we'd rather not add an explicit type signature when polymorphic variants are involved. As discussed in However, if we have mutually recursive type declarations involving polymorphic type constructors where we add a type declaration to one of them, we need it on all of them, otherwise we'll generate ill-typed code. *) let would_rather_omit_type_signatures = let module M = struct exception E end in let has_variant = object inherit Ast_traverse.iter as super method! core_type ct = match ct.ptyp_desc with | Ptyp_variant _ -> Exn.raise_without_backtrace M.E | _ -> super#core_type ct end in fun td -> match td.ptype_kind with | Ptype_variant _ | Ptype_record _ | Ptype_open -> false | Ptype_abstract -> (match td.ptype_manifest with | None -> false | Some body -> (try has_variant#core_type body; false with | M.E -> true)) ;; let should_omit_type_annot ~f_sharp_compatible tds = Universal quantifier annotations are not supported in F # so we never generate any annotations . any annotations. *) f_sharp_compatible || List.for_all ~f:would_rather_omit_type_signatures tds ;; + -----------------------------------------------------------------+ | Generator for size computation of OCaml - values for bin_prot | + -----------------------------------------------------------------+ | Generator for size computation of OCaml-values for bin_prot | +-----------------------------------------------------------------+ *) module Generate_bin_size = struct let mk_abst_call ~loc id args = type_constr_conv ~loc id ~f:(fun s -> "bin_size_" ^ s) args ;; (* Conversion of types *) let rec bin_size_type full_type_name _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> `Fun (bin_size_appl_fun full_type_name loc id args) | Ptyp_tuple l -> bin_size_tuple full_type_name loc l | Ptyp_var parm -> `Fun (evar ~loc @@ "_size_of_" ^ parm) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_size_type: cannot convert functions to the binary protocol" | Ptyp_variant (row_fields, _, _) -> bin_size_variant full_type_name loc row_fields | Ptyp_poly (parms, ty) -> bin_size_poly full_type_name loc parms ty | _ -> Location.raise_errorf ~loc "bin_size_type: unknown type construct" (* Conversion of polymorphic types *) and bin_size_appl_fun full_type_name loc id args = let loc = { loc with loc_ghost = true } in let sizers = List.map args ~f:(fun ty -> match bin_size_type full_type_name ty.ptyp_loc ty with | `Fun e -> e | `Match cases -> pexp_function ~loc:{ ty.ptyp_loc with loc_ghost = true } cases) in match mk_abst_call ~loc id sizers with | [%expr Bin_prot.Size.bin_size_array Bin_prot.Size.bin_size_float] -> [%expr Bin_prot.Size.bin_size_float_array] | e -> e (* Conversion of tuples and records *) and bin_size_args : 'a 'b. Full_type_name.t -> Location.t -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> 'b list * expression = fun full_type_name loc get_tp mk_patt tps -> let rec loop i = function | el :: rest -> let tp = get_tp el in let v_name = "v" ^ Int.to_string i in let v_expr = let e_name = evar ~loc v_name in let expr = match bin_size_type full_type_name loc tp with | `Fun fun_expr -> eapply ~loc fun_expr [ e_name ] | `Match cases -> pexp_match ~loc e_name cases in [%expr Bin_prot.Common.( + ) size [%e expr]] in let patt = mk_patt loc v_name el in if List.is_empty rest then [ patt ], v_expr else ( let patts, in_expr = loop (i + 1) rest in ( patt :: patts , [%expr let size = [%e v_expr] in [%e in_expr]] )) | [] -> assert false (* impossible *) in loop 1 tps and bin_size_tup_rec : 'a 'b. Full_type_name.t -> Location.t -> ('b list -> pattern) -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> _ = fun full_type_name loc cnv_patts get_tp mk_patt tp -> let patts, expr = bin_size_args full_type_name loc get_tp mk_patt tp in `Match [ case ~lhs:(cnv_patts patts) ~guard:None ~rhs: [%expr let size = 0 in [%e expr]] ] (* Conversion of tuples *) and bin_size_tuple full_type_name loc l = let cnv_patts patts = ppat_tuple ~loc patts in let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in bin_size_tup_rec full_type_name loc cnv_patts get_tp mk_patt l (* Conversion of records *) and bin_size_record full_type_name loc tp = let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in bin_size_tup_rec full_type_name loc cnv_patts get_tp mk_patt tp (* Conversion of variant types *) and bin_size_variant full_type_name loc row_fields = let nonatom_matchings = List.fold_left row_fields ~init:[] ~f:(fun acc rf -> match rf.prf_desc with | Rtag (_, true, _) -> acc | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let size_args = match bin_size_type full_type_name tp.ptyp_loc tp with | `Fun fun_expr -> eapply ~loc fun_expr [ [%expr args] ] | `Match cases -> pexp_match ~loc [%expr args] cases in case ~lhs:(ppat_variant cnstr ~loc (Some [%pat? args])) ~guard:None ~rhs: [%expr let size_args = [%e size_args] in Bin_prot.Common.( + ) size_args 4] :: acc | Rtag (_, false, []) -> acc (* Impossible, let the OCaml compiler fail *) | Rinherit ty -> let loc = { ty.ptyp_loc with loc_ghost = true } in (match ty.ptyp_desc with | Ptyp_constr (id, args) -> let call = bin_size_appl_fun full_type_name loc id args in case ~lhs:(ppat_alias ~loc (ppat_type ~loc id) (Located.mk ~loc "v")) ~guard:None ~rhs:(eapply ~loc call [ [%expr v] ]) :: acc | _ -> Location.raise_errorf ~loc "bin_size_variant: unknown type")) in let matchings = if atoms_in_row_fields row_fields then case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:[%expr 4] :: nonatom_matchings else nonatom_matchings in `Match (List.rev matchings) (* Polymorphic record fields *) and bin_size_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_size_of_" ^ parm.txt) ~expr: [%expr fun _v -> raise (Bin_prot.Common.Poly_rec_write [%e estring ~loc full_type_name])] in List.map parms ~f:mk_binding in match bin_size_type full_type_name loc tp with | `Fun fun_expr -> `Fun (pexp_let ~loc Nonrecursive bindings fun_expr) | `Match matchings -> `Match [ case ~lhs:(pvar ~loc "arg") ~guard:None ~rhs: (pexp_let ~loc Nonrecursive bindings (pexp_match ~loc (evar ~loc "arg") matchings)) ] ;; (* Conversion of sum types *) let bin_size_sum full_type_name loc alts = let n_alts = List.length alts in let size_tag = if n_alts <= 256 then [%expr 1] else if n_alts <= 65536 then [%expr 2] else Location.raise_errorf ~loc "bin_size_sum: too many alternatives (%d > 65536)" n_alts in let nonatom_matchings = List.fold_left alts ~init:[] ~f:(fun acc cd -> (match cd.pcd_res with | None -> () | Some ty -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_size_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> acc | Pcstr_tuple args -> let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in let patts, size_args = bin_size_args full_type_name loc get_tp mk_patt args in let args = match patts with | [ patt ] -> patt | _ -> ppat_tuple ~loc patts in case ~lhs:(pconstruct cd (Some args)) ~guard:None ~rhs: [%expr let size = [%e size_tag] in [%e size_args]] :: acc | Pcstr_record fields -> let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in let patts, size_args = bin_size_args full_type_name loc get_tp mk_patt fields in case ~lhs:(pconstruct cd (Some (cnv_patts patts))) ~guard:None ~rhs: [%expr let size = [%e size_tag] in [%e size_args]] :: acc) in let atom_matching init atoms = List.fold_left atoms ~init:(pconstruct init None) ~f:(fun acc atom -> ppat_or ~loc acc (pconstruct atom None)) in let matchings = match atoms_in_variant alts with | [] -> nonatom_matchings | init :: atoms -> case ~lhs:(atom_matching init atoms) ~guard:None ~rhs:size_tag :: nonatom_matchings in `Match (List.rev matchings) ;; (* Empty types *) let bin_size_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Fun [%expr fun _v -> raise (Bin_prot.Common.Empty_type [%e estring ~loc full_type_name])] ;; let make_fun ~loc ?(don't_expand = false) fun_or_match = match fun_or_match with | `Fun fun_expr when don't_expand -> fun_expr | `Fun fun_expr -> alias_or_fun fun_expr [%expr fun v -> [%e eapply ~loc fun_expr [ [%expr v] ]]] | `Match matchings -> pexp_function ~loc matchings ;; let sizer_body_of_td ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let res = match td.ptype_kind with | Ptype_variant alts -> bin_size_sum full_type_name loc alts | Ptype_record flds -> bin_size_record full_type_name loc flds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_size_nil full_type_name loc | Some ty -> bin_size_type full_type_name loc ty) in make_fun ~loc ~don't_expand:(td_is_nil td) res ;; (* Generate code from type definitions *) let bin_size_td ~should_omit_type_annot ~loc ~path td = let body = sizer_body_of_td ~path td in let tparam_patts = vars_of_params td ~prefix:"_size_of_" |> patts_of_vars in let pat = pvar ~loc @@ "bin_size_" ^ td.ptype_name.txt in let pat_with_type = if should_omit_type_annot then pat else ppat_constraint ~loc pat (generate_poly_type ~loc td "Bin_prot.Size.sizer") in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc tparam_patts body) ;; let bin_size ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let bindings = List.map tds ~f:(bin_size_td ~should_omit_type_annot ~loc ~path) in pstr_value ~loc rec_flag bindings ;; end (* +-----------------------------------------------------------------+ | Generator for converters of OCaml-values to the binary protocol | +-----------------------------------------------------------------+ *) module Generate_bin_write = struct let mk_abst_call ~loc id args = type_constr_conv ~loc id ~f:(fun s -> "bin_write_" ^ s) args ;; (* Conversion of types *) let rec bin_write_type full_type_name _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> `Fun (bin_write_appl_fun full_type_name loc id args) | Ptyp_tuple l -> bin_write_tuple full_type_name loc l | Ptyp_var parm -> `Fun (evar ~loc @@ "_write_" ^ parm) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_write_type: cannot convert functions to the binary protocol" | Ptyp_variant (row_fields, _, _) -> bin_write_variant full_type_name loc row_fields | Ptyp_poly (parms, ty) -> bin_write_poly full_type_name loc parms ty | _ -> Location.raise_errorf ~loc "bin_write_type: unknown type construct" (* Conversion of polymorphic types *) and bin_write_appl_fun full_type_name loc id args = let loc = { loc with loc_ghost = true } in let writers = List.map args ~f:(fun ty -> match bin_write_type full_type_name ty.ptyp_loc ty with | `Fun e -> e | `Match cases -> [%expr fun buf ~pos -> [%e pexp_function ~loc:ty.ptyp_loc cases]]) in let e = match mk_abst_call ~loc id writers with | [%expr Bin_prot.Write.bin_write_array Bin_prot.Write.bin_write_float] -> [%expr Bin_prot.Write.bin_write_float_array] | e -> e in e (* Conversion of tuples and records *) and bin_write_args : 'a 'b. Full_type_name.t -> Location.t -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> 'b list * expression = fun full_type_name loc get_tp mk_patt tp -> let rec loop i = function | el :: rest -> let tp = get_tp el in let v_name = "v" ^ Int.to_string i in let v_expr = let e_name = evar ~loc v_name in match bin_write_type full_type_name loc tp with | `Fun fun_expr -> [%expr [%e fun_expr] buf ~pos [%e e_name]] | `Match cases -> pexp_match ~loc e_name cases in let patt = mk_patt loc v_name el in if List.is_empty rest then [ patt ], v_expr else ( let patts, in_expr = loop (i + 1) rest in ( patt :: patts , [%expr let pos = [%e v_expr] in [%e in_expr]] )) | [] -> assert false (* impossible *) in loop 1 tp and bin_write_tup_rec : 'a 'b. Full_type_name.t -> Location.t -> ('b list -> pattern) -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> _ = fun full_type_name loc cnv_patts get_tp mk_patt tp -> let patts, expr = bin_write_args full_type_name loc get_tp mk_patt tp in `Match [ case ~lhs:(cnv_patts patts) ~guard:None ~rhs:expr ] (* Conversion of tuples *) and bin_write_tuple full_type_name loc l = let cnv_patts patts = ppat_tuple ~loc patts in let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in bin_write_tup_rec full_type_name loc cnv_patts get_tp mk_patt l (* Conversion of records *) and bin_write_record full_type_name loc tp = let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in bin_write_tup_rec full_type_name loc cnv_patts get_tp mk_patt tp (* Conversion of variant types *) and bin_write_variant full_type_name loc row_fields = let matchings = List.map row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag ({ txt = cnstr; _ }, true, _) | Rtag ({ txt = cnstr; _ }, false, []) -> case ~lhs:(ppat_variant ~loc cnstr None) ~guard:None ~rhs: [%expr Bin_prot.Write.bin_write_variant_int buf ~pos [%e eint ~loc (Ocaml_common.Btype.hash_variant cnstr)]] | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let write_args = match bin_write_type full_type_name tp.ptyp_loc tp with | `Fun fun_expr -> [%expr [%e fun_expr] buf ~pos args] | `Match cases -> pexp_match ~loc [%expr args] cases in case ~lhs:(ppat_variant ~loc cnstr (Some [%pat? args])) ~guard:None ~rhs: [%expr let pos = Bin_prot.Write.bin_write_variant_int buf ~pos [%e eint ~loc (Ocaml_common.Btype.hash_variant cnstr)] in [%e write_args]] | Rinherit ty -> let loc = { ty.ptyp_loc with loc_ghost = true } in (match ty.ptyp_desc with | Ptyp_constr (id, args) -> let call = bin_write_appl_fun full_type_name loc id args in case ~lhs:(ppat_alias ~loc (ppat_type ~loc id) (Located.mk ~loc "v")) ~guard:None ~rhs:[%expr [%e call] buf ~pos v] | _ -> Location.raise_errorf ~loc "bin_write_variant: unknown type")) in `Match matchings (* Polymorphic record fields *) and bin_write_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_write_" ^ parm.txt) ~expr: [%expr fun _buf ~pos:_ _v -> raise (Bin_prot.Common.Poly_rec_write [%e estring ~loc full_type_name])] in List.map parms ~f:mk_binding in match bin_write_type full_type_name loc tp with | `Fun fun_expr -> `Fun (pexp_let ~loc Nonrecursive bindings fun_expr) | `Match matchings -> `Match [ case ~lhs:(pvar ~loc "arg") ~guard:None ~rhs: (pexp_let ~loc Nonrecursive bindings (pexp_match ~loc (evar ~loc "arg") matchings)) ] ;; (* Conversion of sum types *) let bin_write_sum full_type_name loc alts = let n_alts = List.length alts in let write_tag = if n_alts <= 256 then [%expr Bin_prot.Write.bin_write_int_8bit buf ~pos] else if n_alts <= 65536 then [%expr Bin_prot.Write.bin_write_int_16bit buf ~pos] else Location.raise_errorf ~loc "bin_write_sum: too many alternatives (%d > 65536)" n_alts in let matchings = List.mapi alts ~f:(fun i cd -> (match cd.pcd_res with | None -> () | Some ty -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_write_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> let loc = cd.pcd_loc in case ~lhs:(pconstruct cd None) ~guard:None ~rhs:(eapply ~loc write_tag [ eint ~loc i ]) | Pcstr_tuple args -> let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in let patts, write_args = bin_write_args full_type_name loc get_tp mk_patt args in let args = match patts with | [ patt ] -> patt | _ -> ppat_tuple ~loc patts in case ~lhs:(pconstruct cd (Some args)) ~guard:None ~rhs: [%expr let pos = [%e eapply ~loc write_tag [ eint ~loc i ]] in [%e write_args]] | Pcstr_record fields -> let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in let patts, expr = bin_write_args full_type_name loc get_tp mk_patt fields in case ~lhs:(pconstruct cd (Some (cnv_patts patts))) ~guard:None ~rhs: [%expr let pos = [%e eapply ~loc write_tag [ eint ~loc i ]] in [%e expr]]) in `Match matchings ;; (* Empty types *) let bin_write_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Fun [%expr fun _buf ~pos:_ _v -> raise (Bin_prot.Common.Empty_type [%e estring ~loc full_type_name])] ;; let make_fun ~loc ?(don't_expand = false) fun_or_match = match fun_or_match with | `Fun fun_expr when don't_expand -> fun_expr | `Fun fun_expr -> alias_or_fun fun_expr [%expr fun buf ~pos v -> [%e fun_expr] buf ~pos v] | `Match matchings -> [%expr fun buf ~pos -> [%e pexp_function ~loc matchings]] ;; let writer_type_class_record ~loc ~size ~write = [%expr { Bin_prot.Type_class.size = [%e size]; Bin_prot.Type_class.write = [%e write] }] ;; let writer_body_of_td ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let res = match td.ptype_kind with | Ptype_variant alts -> bin_write_sum full_type_name loc alts | Ptype_record flds -> bin_write_record full_type_name loc flds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_write_nil full_type_name loc | Some ty -> bin_write_type full_type_name loc ty) in make_fun ~loc ~don't_expand:(td_is_nil td) res ;; let project_vars expr vars ~field_name = let loc = expr.pexp_loc in let call = project_vars expr vars ~record_type:[%type: _ Bin_prot.Type_class.writer] ~field_name in alias_or_fun call [%expr fun v -> [%e eapply ~loc call [ [%expr v] ]]] ;; (* Generate code from type definitions *) let bin_write_td ~should_omit_type_annot ~loc ~path td = let body = writer_body_of_td ~path td in let size_name = "bin_size_" ^ td.ptype_name.txt in let write_name = "bin_write_" ^ td.ptype_name.txt in let write_binding = let tparam_patts = vars_of_params td ~prefix:"_write_" |> patts_of_vars in let pat = pvar ~loc write_name in let pat_with_type = if should_omit_type_annot then pat else ppat_constraint ~loc pat (generate_poly_type ~loc td "Bin_prot.Write.writer") in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc tparam_patts body) in let writer_binding = let vars = vars_of_params td ~prefix:"bin_writer_" in let writer_record = writer_type_class_record ~loc ~size:(project_vars (evar ~loc size_name) vars ~field_name:"size") ~write:(project_vars (evar ~loc write_name) vars ~field_name:"write") in value_binding ~loc ~pat:(pvar ~loc @@ "bin_writer_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc (patts_of_vars vars) writer_record) in write_binding, writer_binding ;; let bin_write ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let write_bindings, writer_bindings = List.map tds ~f:(bin_write_td ~should_omit_type_annot ~loc ~path) |> List.unzip in [ Generate_bin_size.bin_size ~f_sharp_compatible ~loc ~path (rec_flag, tds) ; pstr_value ~loc rec_flag write_bindings ; pstr_value ~loc Nonrecursive writer_bindings ] ;; let gen = Deriving.Generator.make Deriving.Args.empty (bin_write ~f_sharp_compatible:false) ;; let extension ~loc ~path:_ ty = let loc = { loc with loc_ghost = true } in let full_type_name = Full_type_name.absent in let size = Generate_bin_size.bin_size_type full_type_name loc ty |> Generate_bin_size.make_fun ~loc in let write = bin_write_type full_type_name loc ty |> make_fun ~loc in writer_type_class_record ~loc ~size ~write ;; end (* +-----------------------------------------------------------------+ | Generator for converters of binary protocol to OCaml-values | +-----------------------------------------------------------------+ *) module Generate_bin_read = struct let full_type_name_or_anonymous full_type_name = match Full_type_name.get full_type_name with | None -> "<anonymous type>" | Some s -> s ;; let mk_abst_call loc ?(internal = false) id args = type_constr_conv ~loc id args ~f:(fun s -> let s = "bin_read_" ^ s in if internal then "__" ^ s ^ "__" else s) ;; (* Conversion of type paths *) let bin_read_path_fun loc id args = mk_abst_call { loc with loc_ghost = true } id args let get_closed_expr loc = function | `Open expr -> [%expr fun buf ~pos_ref -> [%e expr]] | `Closed expr -> expr ;; let get_open_expr loc = function | `Open expr -> expr | `Closed expr -> [%expr [%e expr] buf ~pos_ref] ;; (* Conversion of arguments *) let rec handle_arg_tp loc full_type_name arg_tp = let args, bindings = let arg_map ai tp = let f = get_open_expr loc (bin_read_type full_type_name loc tp) in let arg_name = "arg_" ^ Int.to_string (ai + 1) in evar ~loc arg_name, value_binding ~loc ~pat:(pvar ~loc arg_name) ~expr:f in List.mapi arg_tp ~f:arg_map |> List.unzip in let args_expr = match args with | [ expr ] -> expr | _ -> pexp_tuple ~loc args in bindings, args_expr (* Conversion of types *) and bin_read_type_internal full_type_name ~full_type _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> let args_expr = List.map args ~f:(fun tp -> get_closed_expr _loc (bin_read_type full_type_name _loc tp)) in let expr = match bin_read_path_fun id.loc id args_expr with | [%expr Bin_prot.Read.bin_read_array Bin_prot.Read.bin_read_float] -> [%expr Bin_prot.Read.bin_read_float_array] | expr -> expr in `Closed expr | Ptyp_tuple tp -> bin_read_tuple full_type_name loc tp | Ptyp_var parm -> `Closed (evar ~loc ("_of__" ^ parm)) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_read_arrow: cannot convert functions" | Ptyp_variant (row_fields, _, _) -> bin_read_variant full_type_name loc ?full_type row_fields | Ptyp_poly (parms, poly_tp) -> bin_read_poly full_type_name loc parms poly_tp | _ -> Location.raise_errorf ~loc "bin_read_type: unknown type construct" and bin_read_type full_type_name loc ty = bin_read_type_internal full_type_name ~full_type:None loc ty and bin_read_type_toplevel full_type_name ~full_type loc ty = bin_read_type_internal full_type_name ~full_type:(Some full_type) loc ty (* Conversion of tuples *) and bin_read_tuple full_type_name loc tps = let bindings, exprs = let map i tp = let v_name = "v" ^ Int.to_string (i + 1) in let expr = get_open_expr loc (bin_read_type full_type_name loc tp) in value_binding ~loc ~pat:(pvar ~loc v_name) ~expr, evar ~loc v_name in List.mapi tps ~f:map |> List.unzip in `Open (let_ins loc bindings (pexp_tuple ~loc exprs)) (* Variant conversions *) (* Generate internal call *) and mk_internal_call full_type_name loc ty = let loc = { loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) | Ptyp_class (id, args) -> let arg_exprs = List.map args ~f:(fun tp -> get_closed_expr loc (bin_read_type full_type_name loc tp)) in mk_abst_call loc ~internal:true id arg_exprs | _ -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_read: unknown type" (* Generate matching code for variants *) and bin_read_variant full_type_name loc ?full_type row_fields = let is_contained, full_type = match full_type with | None -> true, ptyp_variant ~loc row_fields Closed None | Some full_type -> false, full_type in let code = let mk_check_vint mcs = pexp_match ~loc (evar ~loc "vint") mcs in let mk_try_next_expr call next_expr = [%expr try [%e call] with | Bin_prot.Common.No_variant_match -> [%e next_expr]] in let raise_nvm = [%expr raise Bin_prot.Common.No_variant_match] in let rec loop_many next = function | h :: t -> loop_one next t h | [] -> (match next with | `Matches mcs -> mk_check_vint mcs | `Expr expr -> expr | `None -> raise_nvm) and loop_one next t row_field = match row_field.prf_desc with | Rtag ({ txt = cnstr; _ }, is_constant, tps) -> let rhs = match is_constant, tps with | false, arg_tp :: _ -> let bnds, args_expr = handle_arg_tp loc full_type_name [ arg_tp ] in let_ins loc bnds (pexp_variant ~loc cnstr (Some args_expr)) | _ -> pexp_variant ~loc cnstr None in let this_mc = case ~lhs:(pint ~loc (Ocaml_common.Btype.hash_variant cnstr)) ~guard:None ~rhs in add_mc next this_mc t | Rinherit ty -> let call = [%expr ([%e mk_internal_call full_type_name ty.ptyp_loc ty] buf ~pos_ref vint :> [%t full_type])] in let expr = match next with | `Matches mcs -> mk_try_next_expr call (mk_check_vint mcs) | `Expr expr -> mk_try_next_expr call expr | `None -> call in loop_many (`Expr expr) t and add_mc next this_mc t = let next_mcs = match next with | `Matches mcs -> mcs | `Expr expr -> [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:expr ] | `None -> [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:raise_nvm ] in loop_many (`Matches (this_mc :: next_mcs)) t in loop_many `None (List.rev row_fields) in if is_contained then ( let full_type_name = full_type_name_or_anonymous full_type_name in `Open [%expr let vint = Bin_prot.Read.bin_read_variant_int buf ~pos_ref in try [%e code] with | Bin_prot.Common.No_variant_match -> Bin_prot.Common.raise_variant_wrong_type [%e estring ~loc full_type_name] !pos_ref]) else `Open code (* Polymorphic record field conversion *) and bin_read_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_of__" ^ parm.txt) ~expr: [%expr fun _buf ~pos_ref -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Poly_rec_bound [%e estring ~loc full_type_name]) !pos_ref] in List.map parms ~f:mk_binding in let f = get_open_expr loc (bin_read_type full_type_name loc tp) in `Open (pexp_let ~loc Nonrecursive bindings f) ;; (* Record conversions *) let bin_read_label_declaration_list full_type_name loc fields wrap = let bindings, rec_bindings = let map field = let loc = field.pld_loc in let v_name = "v_" ^ field.pld_name.txt in let f = get_open_expr loc (bin_read_type full_type_name loc field.pld_type) in ( value_binding ~loc ~pat:(pvar ~loc:field.pld_name.loc v_name) ~expr:f , (Located.map lident field.pld_name, evar ~loc:field.pld_name.loc v_name) ) in List.map fields ~f:map |> List.unzip in let_ins loc bindings (wrap (pexp_record ~loc rec_bindings None)) ;; (* Sum type conversions *) let bin_read_sum full_type_name loc alts = let map mi cd = (match cd.pcd_res with | None -> () | Some _ -> Location.raise_errorf ~loc:cd.pcd_loc "bin_read_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> let loc = cd.pcd_loc in case ~lhs:(pint ~loc mi) ~guard:None ~rhs:(econstruct cd None) | Pcstr_tuple args -> let bindings, args_expr = handle_arg_tp loc full_type_name args in let rhs = let_ins loc bindings (econstruct cd (Some args_expr)) in case ~lhs:(pint ~loc mi) ~guard:None ~rhs | Pcstr_record fields -> let rhs = bin_read_label_declaration_list full_type_name loc fields (fun e -> econstruct cd (Some e)) in case ~lhs:(pint ~loc mi) ~guard:None ~rhs in let mcs = List.mapi alts ~f:map in let n_alts = List.length alts in let read_fun = if n_alts <= 256 then [%expr Bin_prot.Read.bin_read_int_8bit] else if n_alts <= 65536 then [%expr Bin_prot.Read.bin_read_int_16bit] else Location.raise_errorf ~loc "bin_size_sum: too many alternatives (%d > 65536)" n_alts in let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Open (pexp_match ~loc [%expr [%e read_fun] buf ~pos_ref] (mcs @ [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs: [%expr Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Sum_tag [%e estring ~loc full_type_name]) !pos_ref] ])) ;; (* Record conversions *) let bin_read_record full_type_name loc fields = let rhs = bin_read_label_declaration_list full_type_name loc fields (fun x -> x) in `Open rhs ;; (* Empty types *) let bin_read_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Closed [%expr fun _buf ~pos_ref -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Empty_type [%e estring ~loc full_type_name]) !pos_ref] ;; (* Generate code from type definitions *) let reader_body_of_td td full_type_name = let loc = td.ptype_loc in match td.ptype_kind with | Ptype_variant cds -> bin_read_sum full_type_name loc cds | Ptype_record lds -> bin_read_record full_type_name loc lds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_read_nil full_type_name loc | Some ty -> bin_read_type_toplevel full_type_name loc ty ~full_type:(core_type_of_type_declaration td)) ;; (* When the type is a polymorphic variant the main bin_read_NAME function reads an integer and calls the __bin_read_NAME__ function wrapped into a try-with. *) let main_body_for_polymorphic_variant ~loc ~vtag_read_name ~full_type_name ~args = let full_type_name = full_type_name_or_anonymous full_type_name in let vtag_read_expr = evar ~loc vtag_read_name in [%expr fun buf ~pos_ref -> let vint = Bin_prot.Read.bin_read_variant_int buf ~pos_ref in try [%e eapply ~loc vtag_read_expr (exprs_of_vars args)] buf ~pos_ref vint with | Bin_prot.Common.No_variant_match -> let err = Bin_prot.Common.ReadError.Variant [%e estring ~loc full_type_name] in Bin_prot.Common.raise_read_error err !pos_ref] ;; module Td_class = struct type polymorphic_variant = { all_atoms : bool } type t = | Polymorphic_variant of polymorphic_variant | Alias_but_not_polymorphic_variant | Other let of_core_type ty = match ty.ptyp_desc with | Ptyp_variant (row_fields, _, _) -> let all_atoms = List.for_all row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag (_, is_constant, _) -> is_constant | Rinherit _ -> false) in Polymorphic_variant { all_atoms } | _ -> Alias_but_not_polymorphic_variant ;; let of_td td = match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, Some ty -> of_core_type ty | _ -> Other ;; end let variant_wrong_type ~loc full_type_name = let full_type_name = full_type_name_or_anonymous full_type_name in [%expr fun _buf ~pos_ref _vint -> Bin_prot.Common.raise_variant_wrong_type [%e estring ~loc full_type_name] !pos_ref] ;; let vtag_reader ~loc ~(td_class : Td_class.t) ~full_type_name ~oc_body = match td_class with | Alias_but_not_polymorphic_variant -> (match oc_body with | `Closed call -> let rec rewrite_call cnv e = let loc = e.pexp_loc in match e.pexp_desc with | Pexp_apply (f, [ arg ]) -> rewrite_call (fun new_f -> cnv (pexp_apply ~loc new_f [ arg ])) f | Pexp_ident { txt = Ldot (Ldot (Lident "Bin_prot", "Read"), _); _ } -> variant_wrong_type ~loc full_type_name | Pexp_ident { txt = Lident name; _ } when String.is_prefix name ~prefix:"_o" -> let full_type_name = Full_type_name.get_exn ~loc full_type_name in [%expr fun _buf ~pos_ref _vint -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Silly_type [%e estring ~loc full_type_name]) !pos_ref] | Pexp_ident id -> let expr = unapplied_type_constr_conv ~loc id ~f:(fun s -> "__" ^ s ^ "__") in let cnv_expr = cnv expr in alias_or_fun cnv_expr [%expr fun buf ~pos_ref vint -> [%e cnv_expr] buf ~pos_ref vint] | _ -> let s = Pprintast.string_of_expression e in Location.raise_errorf ~loc "ppx_bin_prot: impossible case: %s" s in rewrite_call (fun x -> x) (curry_applications call) | _ -> variant_wrong_type ~loc full_type_name) | Polymorphic_variant { all_atoms } -> (match oc_body with | `Open body when all_atoms -> [%expr fun _buf ~pos_ref:_ vint -> [%e body]] | `Open body -> [%expr fun buf ~pos_ref vint -> [%e body]] | _ -> assert false (* impossible *)) | Other -> variant_wrong_type ~loc full_type_name ;; let read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type ~vtag_read_name ~vtag_read_binding_type ~full_type_name ~(td_class : Td_class.t) ~args ~oc_body = let read_binding = let body = match td_class with | Polymorphic_variant _ -> main_body_for_polymorphic_variant ~loc ~vtag_read_name ~full_type_name ~args | Alias_but_not_polymorphic_variant | Other -> (match oc_body with | `Closed expr -> alias_or_fun expr [%expr fun buf ~pos_ref -> [%e expr] buf ~pos_ref] | `Open body -> [%expr fun buf ~pos_ref -> [%e body]]) in let pat = pvar ~loc read_name in let pat_with_type = match read_binding_type with | None -> pat | Some ty -> ppat_constraint ~loc pat ty in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc (patts_of_vars args) body) in let vtag_read_binding = let pat = pvar ~loc vtag_read_name in let pat_with_type = match vtag_read_binding_type with | None -> pat | Some ty -> ppat_constraint ~loc pat ty in value_binding ~loc ~pat:pat_with_type ~expr: (eabstract ~loc (patts_of_vars args) (vtag_reader ~loc ~td_class ~full_type_name ~oc_body)) in read_binding, vtag_read_binding ;; let reader_type_class_record ~loc ~read ~vtag_read = [%expr { Bin_prot.Type_class.read = [%e read] ; Bin_prot.Type_class.vtag_read = [%e vtag_read] }] ;; let bin_read_td ~should_omit_type_annot ~loc:_ ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let oc_body = reader_body_of_td td full_type_name in let read_name = "bin_read_" ^ td.ptype_name.txt in let vtag_read_name = "__bin_read_" ^ td.ptype_name.txt ^ "__" in let vtag_read_binding_type, read_binding_type = if should_omit_type_annot then None, None else ( Some (generate_poly_type ~loc td "Bin_prot.Read.reader" ~wrap_result:(fun ~loc t -> [%type: int -> [%t t]])) , Some (generate_poly_type ~loc td "Bin_prot.Read.reader") ) in let read_binding, vtag_read_binding = let args = vars_of_params td ~prefix:"_of__" in read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type ~vtag_read_name ~vtag_read_binding_type ~full_type_name ~td_class:(Td_class.of_td td) ~args ~oc_body in let vars = vars_of_params td ~prefix:"bin_reader_" in let project_vars = project_vars ~record_type:[%type: _ Bin_prot.Type_class.reader] in let read = let call = project_vars (evar ~loc read_name) vars ~field_name:"read" in alias_or_fun call [%expr fun buf ~pos_ref -> [%e call] buf ~pos_ref] in let vtag_read = let call = project_vars (evar ~loc vtag_read_name) vars ~field_name:"read" in alias_or_fun call [%expr fun buf ~pos_ref vtag -> [%e call] buf ~pos_ref vtag] in let reader = reader_type_class_record ~loc ~read ~vtag_read in let reader_binding = value_binding ~loc ~pat:(pvar ~loc @@ "bin_reader_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc (patts_of_vars vars) reader) in vtag_read_binding, (read_binding, reader_binding) ;; (* Generate code from type definitions *) let bin_read ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in (match rec_flag, tds with | Nonrecursive, _ :: _ :: _ -> (* there can be captures in the generated code if we allow this *) Location.raise_errorf ~loc "bin_prot doesn't support multiple nonrecursive definitions." | _ -> ()); let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let vtag_read_bindings, read_and_reader_bindings = List.map tds ~f:(bin_read_td ~should_omit_type_annot ~loc ~path) |> List.unzip in let read_bindings, reader_bindings = List.unzip read_and_reader_bindings in let defs = match rec_flag with | Recursive -> [ pstr_value ~loc Recursive (vtag_read_bindings @ read_bindings) ] | Nonrecursive -> let cnv binding = pstr_value ~loc Nonrecursive [ binding ] in List.map vtag_read_bindings ~f:cnv @ List.map read_bindings ~f:cnv in defs @ [ pstr_value ~loc Nonrecursive reader_bindings ] ;; let gen = Deriving.Generator.make Deriving.Args.empty (bin_read ~f_sharp_compatible:false) ;; let extension ~loc ~path:_ ty = let loc = { loc with loc_ghost = true } in let full_type_name = Full_type_name.absent in let read_name = "read" in let vtag_read_name = "vtag_read" in let read_binding, vtag_read_binding = let oc_body = bin_read_type_toplevel full_type_name loc ty ~full_type:ty in read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type:None ~vtag_read_name ~vtag_read_binding_type:None ~full_type_name ~td_class:(Td_class.of_core_type ty) ~args:[] ~oc_body in pexp_let ~loc Nonrecursive [ vtag_read_binding ] (pexp_let ~loc Nonrecursive [ read_binding ] (reader_type_class_record ~loc ~read:(evar ~loc read_name) ~vtag_read:(evar ~loc vtag_read_name))) ;; end (* Generator for binary protocol type classes *) module Generate_tp_class = struct let tp_record ~loc ~writer ~reader ~shape = [%expr { Bin_prot.Type_class.writer = [%e writer] ; reader = [%e reader] ; shape = [%e shape] }] ;; let bin_tp_class_td td = let loc = td.ptype_loc in let tparam_cnvs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in "bin_" ^ name.txt) in let mk_pat id = pvar ~loc id in let tparam_patts = List.map tparam_cnvs ~f:mk_pat in let writer = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .writer]) in eapply ~loc (evar ~loc @@ "bin_writer_" ^ td.ptype_name.txt) tparam_exprs in let reader = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .reader]) in eapply ~loc (evar ~loc @@ "bin_reader_" ^ td.ptype_name.txt) tparam_exprs in let shape = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .shape]) in eapply ~loc (evar ~loc @@ "bin_shape_" ^ td.ptype_name.txt) tparam_exprs in let body = tp_record ~loc ~writer ~reader ~shape in value_binding ~loc ~pat:(pvar ~loc @@ "bin_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc tparam_patts body) ;; (* Generate code from type definitions *) let bin_tp_class ~loc ~path:_ (_rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let bindings = List.map tds ~f:bin_tp_class_td in [ pstr_value ~loc Nonrecursive bindings ] ;; (* Add code generator to the set of known generators *) let gen = Deriving.Generator.make Deriving.Args.empty bin_tp_class let extension ~loc ~path ty = let loc = { loc with loc_ghost = true } in tp_record ~loc ~writer:(Generate_bin_write.extension ~loc ~path ty) ~reader:(Generate_bin_read.extension ~loc ~path ty) ~shape:(Bin_shape_expand.shape_extension ~loc ty) ;; end let bin_shape = Deriving.add "bin_shape" ~str_type_decl:Bin_shape_expand.str_gen ~sig_type_decl:Bin_shape_expand.sig_gen ~extension:(fun ~loc ~path:_ -> Bin_shape_expand.shape_extension ~loc) ;; let () = Deriving.add "bin_digest" ~extension:(fun ~loc ~path:_ -> Bin_shape_expand.digest_extension ~loc) |> Deriving.ignore ;; let bin_write = Deriving.add "bin_write" ~str_type_decl:Generate_bin_write.gen ~sig_type_decl:Sig.bin_write ;; let () = Deriving.add "bin_writer" ~extension:Generate_bin_write.extension |> Deriving.ignore ;; let bin_read = Deriving.add "bin_read" ~str_type_decl:Generate_bin_read.gen ~sig_type_decl:Sig.bin_read ;; let () = Deriving.add "bin_reader" ~extension:Generate_bin_read.extension |> Deriving.ignore ;; let bin_type_class = Deriving.add "bin_type_class" ~str_type_decl:Generate_tp_class.gen ~sig_type_decl:Sig.bin_type_class ~extension:Generate_tp_class.extension ;; let bin_io_named_sig = Deriving.add "bin_io.named_sig.prevent using this in source files" ~sig_type_decl:Sig.named ;; let bin_io = let set = [ bin_shape; bin_write; bin_read; bin_type_class ] in Deriving.add_alias "bin_io" set ~sig_type_decl:[ bin_io_named_sig ] ~str_type_decl:(List.rev set) ;; The differences between F # and : 1 . F # does n't have labeled arguments so all labeled arguments are changed into not labeled . This implies we must pass all arguments in definition order even if they are labeled . 2 . Universal quantifier annotations are not supported in F # so we never generate the annotation that uses it . These are only needed for polymorphic recursion anyway . Changes compatible with OCaml to support F # : 1 . When prefixing record fields with path to module OCaml only requires one field to be prefixed but F # requires all fields to be prefixed , 2 . Accessing fields with a qualified path [ record.M.field ] does n't work in F # , so use type - directed disambiguation . 1. F# doesn't have labeled arguments so all labeled arguments are changed into not labeled. This implies we must pass all arguments in definition order even if they are labeled. 2. Universal quantifier annotations are not supported in F# so we never generate the annotation that uses it. These are only needed for polymorphic recursion anyway. Changes compatible with OCaml to support F#: 1. When prefixing record fields with path to module OCaml only requires one field to be prefixed but F# requires all fields to be prefixed, 2. Accessing fields with a qualified path [record.M.field] doesn't work in F#, so use type-directed disambiguation. *) module For_f_sharp = struct let remove_labeled_arguments = object inherit Ast_traverse.map method! arg_label (_ : arg_label) = Nolabel end ;; let bin_write ~loc ~path (rec_flag, tds) = let structure = Generate_bin_write.bin_write ~f_sharp_compatible:true ~loc ~path (rec_flag, tds) in remove_labeled_arguments#structure structure ;; let bin_read ~loc ~path (rec_flag, tds) = let structure = Generate_bin_read.bin_read ~f_sharp_compatible:true ~loc ~path (rec_flag, tds) in remove_labeled_arguments#structure structure ;; end
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppx_bin_prot/src/ppx_bin_prot.ml
ocaml
* Ppx_bin_prot: Preprocessing Module for a Type Safe Binary Protocol +-----------------------------------------------------------------+ | Signature generators | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Utility functions | +-----------------------------------------------------------------+ Conversion of types Conversion of polymorphic types Conversion of tuples and records impossible Conversion of tuples Conversion of records Conversion of variant types Impossible, let the OCaml compiler fail Polymorphic record fields Conversion of sum types Empty types Generate code from type definitions +-----------------------------------------------------------------+ | Generator for converters of OCaml-values to the binary protocol | +-----------------------------------------------------------------+ Conversion of types Conversion of polymorphic types Conversion of tuples and records impossible Conversion of tuples Conversion of records Conversion of variant types Polymorphic record fields Conversion of sum types Empty types Generate code from type definitions +-----------------------------------------------------------------+ | Generator for converters of binary protocol to OCaml-values | +-----------------------------------------------------------------+ Conversion of type paths Conversion of arguments Conversion of types Conversion of tuples Variant conversions Generate internal call Generate matching code for variants Polymorphic record field conversion Record conversions Sum type conversions Record conversions Empty types Generate code from type definitions When the type is a polymorphic variant the main bin_read_NAME function reads an integer and calls the __bin_read_NAME__ function wrapped into a try-with. impossible Generate code from type definitions there can be captures in the generated code if we allow this Generator for binary protocol type classes Generate code from type definitions Add code generator to the set of known generators
open Base open Ppxlib open Ast_builder.Default let ( @@ ) a b = a b module Sig = struct let mk_sig_generator combinators = let mk_sig ~ctxt:_ (_rf, tds) = List.concat_map tds ~f:(fun td -> let td = name_type_params_in_td td in List.map combinators ~f:(fun mk -> mk td)) in Deriving.Generator.V2.make Deriving.Args.empty mk_sig ;; let mk_typ ?(wrap_result = fun ~loc:_ x -> x) type_constr td = let loc = td.ptype_loc in let id = Longident.parse type_constr in let wrap_type ~loc t = ptyp_constr ~loc (Located.mk ~loc id) [ t ] in let result_type = wrap_type ~loc:td.ptype_name.loc (wrap_result ~loc (core_type_of_type_declaration td)) in List.fold_right td.ptype_params ~init:result_type ~f:(fun (tp, _variance) acc -> let loc = tp.ptyp_loc in ptyp_arrow ~loc Nolabel (wrap_type ~loc tp) acc) ;; let mk name_format type_constr ?wrap_result td = let loc = td.ptype_loc in let name = Loc.map ~f:(Printf.sprintf name_format) td.ptype_name in let typ = mk_typ ?wrap_result type_constr td in psig_value ~loc (value_description ~loc ~name ~type_:typ ~prim:[]) ;; let bin_write = mk_sig_generator [ mk "bin_size_%s" "Bin_prot.Size.sizer" ; mk "bin_write_%s" "Bin_prot.Write.writer" ; mk "bin_writer_%s" "Bin_prot.Type_class.writer" ] ;; let bin_read = mk_sig_generator [ mk "bin_read_%s" "Bin_prot.Read.reader" ; mk "__bin_read_%s__" "Bin_prot.Read.reader" ~wrap_result:(fun ~loc t -> [%type: int -> [%t t]]) ; mk "bin_reader_%s" "Bin_prot.Type_class.reader" ] ;; let bin_type_class = mk_sig_generator [ mk "bin_%s" "Bin_prot.Type_class.t" ] let named = let mk_named_sig ~ctxt (rf, tds) = let loc = Expansion_context.Deriver.derived_item_loc ctxt in match mk_named_sig ~loc ~sg_name:"Bin_prot.Binable.S" ~handle_polymorphic_variant:true tds with | Some incl -> [ psig_include ~loc incl ] | None -> List.concat_map [ Bin_shape_expand.sig_gen; bin_write; bin_read; bin_type_class ] ~f:(fun gen -> Deriving.Generator.apply ~name:"unused" gen ~ctxt (rf, tds) []) in Deriving.Generator.V2.make Deriving.Args.empty mk_named_sig ;; end let atoms_in_row_fields row_fields = List.exists row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag (_, is_constant, _) -> is_constant | Rinherit _ -> false) ;; let atoms_in_variant cds = List.filter cds ~f:(fun cds -> match cds.pcd_args with | Pcstr_tuple [] -> true | Pcstr_tuple _ -> false | Pcstr_record _ -> false) ;; let let_ins loc bindings expr = List.fold_right bindings ~init:expr ~f:(fun binding expr -> pexp_let ~loc Nonrecursive [ binding ] expr) ;; let alias_or_fun expr fct = let is_id = match expr.pexp_desc with | Pexp_ident _ -> true | _ -> false in if is_id then expr else fct ;; let td_is_nil td = match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, None -> true | _ -> false ;; type var = string Located.t let vars_of_params ~prefix td = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in { name with txt = prefix ^ name.txt }) ;; let map_vars vars ~f = List.map vars ~f:(fun (v : var) -> f ~loc:v.loc v.txt) let patts_of_vars = map_vars ~f:pvar let exprs_of_vars = map_vars ~f:evar let project_vars expr vars ~record_type ~field_name = let args = map_vars vars ~f:(fun ~loc txt -> let record = pexp_constraint ~loc (evar ~loc txt) record_type in pexp_field ~loc record (Located.mk ~loc (Lident field_name))) in let loc = expr.pexp_loc in eapply ~loc expr args ;; module Full_type_name : sig type t val make : path:string -> type_declaration -> t val absent : t val get : t -> string option val get_exn : loc:Location.t -> t -> string end = struct type t = string option let make ~path td = Some (Printf.sprintf "%s.%s" path td.ptype_name.txt) let absent = None let get t = t let get_exn ~loc t = match t with | Some n -> n | None -> Location.raise_errorf ~loc "Bug in ppx_bin_prot: full type name needed but not in a type declaration.\n\ Callstack:\n\ %s" (Stdlib.Printexc.get_callstack 256 |> Stdlib.Printexc.raw_backtrace_to_string) ;; end let generate_poly_type ?wrap_result ~loc td constructor = ptyp_poly ~loc (List.map td.ptype_params ~f:get_type_param_name) (Sig.mk_typ ?wrap_result constructor td) ;; Determines whether or not the generated code associated with a type declaration should include explicit type signatures . In particular , we 'd rather not add an explicit type signature when polymorphic variants are involved . As discussed in However , if we have mutually recursive type declarations involving polymorphic type constructors where we add a type declaration to one of them , we need it on all of them , otherwise we 'll generate ill - typed code . a type declaration should include explicit type signatures. In particular, we'd rather not add an explicit type signature when polymorphic variants are involved. As discussed in However, if we have mutually recursive type declarations involving polymorphic type constructors where we add a type declaration to one of them, we need it on all of them, otherwise we'll generate ill-typed code. *) let would_rather_omit_type_signatures = let module M = struct exception E end in let has_variant = object inherit Ast_traverse.iter as super method! core_type ct = match ct.ptyp_desc with | Ptyp_variant _ -> Exn.raise_without_backtrace M.E | _ -> super#core_type ct end in fun td -> match td.ptype_kind with | Ptype_variant _ | Ptype_record _ | Ptype_open -> false | Ptype_abstract -> (match td.ptype_manifest with | None -> false | Some body -> (try has_variant#core_type body; false with | M.E -> true)) ;; let should_omit_type_annot ~f_sharp_compatible tds = Universal quantifier annotations are not supported in F # so we never generate any annotations . any annotations. *) f_sharp_compatible || List.for_all ~f:would_rather_omit_type_signatures tds ;; + -----------------------------------------------------------------+ | Generator for size computation of OCaml - values for bin_prot | + -----------------------------------------------------------------+ | Generator for size computation of OCaml-values for bin_prot | +-----------------------------------------------------------------+ *) module Generate_bin_size = struct let mk_abst_call ~loc id args = type_constr_conv ~loc id ~f:(fun s -> "bin_size_" ^ s) args ;; let rec bin_size_type full_type_name _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> `Fun (bin_size_appl_fun full_type_name loc id args) | Ptyp_tuple l -> bin_size_tuple full_type_name loc l | Ptyp_var parm -> `Fun (evar ~loc @@ "_size_of_" ^ parm) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_size_type: cannot convert functions to the binary protocol" | Ptyp_variant (row_fields, _, _) -> bin_size_variant full_type_name loc row_fields | Ptyp_poly (parms, ty) -> bin_size_poly full_type_name loc parms ty | _ -> Location.raise_errorf ~loc "bin_size_type: unknown type construct" and bin_size_appl_fun full_type_name loc id args = let loc = { loc with loc_ghost = true } in let sizers = List.map args ~f:(fun ty -> match bin_size_type full_type_name ty.ptyp_loc ty with | `Fun e -> e | `Match cases -> pexp_function ~loc:{ ty.ptyp_loc with loc_ghost = true } cases) in match mk_abst_call ~loc id sizers with | [%expr Bin_prot.Size.bin_size_array Bin_prot.Size.bin_size_float] -> [%expr Bin_prot.Size.bin_size_float_array] | e -> e and bin_size_args : 'a 'b. Full_type_name.t -> Location.t -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> 'b list * expression = fun full_type_name loc get_tp mk_patt tps -> let rec loop i = function | el :: rest -> let tp = get_tp el in let v_name = "v" ^ Int.to_string i in let v_expr = let e_name = evar ~loc v_name in let expr = match bin_size_type full_type_name loc tp with | `Fun fun_expr -> eapply ~loc fun_expr [ e_name ] | `Match cases -> pexp_match ~loc e_name cases in [%expr Bin_prot.Common.( + ) size [%e expr]] in let patt = mk_patt loc v_name el in if List.is_empty rest then [ patt ], v_expr else ( let patts, in_expr = loop (i + 1) rest in ( patt :: patts , [%expr let size = [%e v_expr] in [%e in_expr]] )) | [] -> assert false in loop 1 tps and bin_size_tup_rec : 'a 'b. Full_type_name.t -> Location.t -> ('b list -> pattern) -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> _ = fun full_type_name loc cnv_patts get_tp mk_patt tp -> let patts, expr = bin_size_args full_type_name loc get_tp mk_patt tp in `Match [ case ~lhs:(cnv_patts patts) ~guard:None ~rhs: [%expr let size = 0 in [%e expr]] ] and bin_size_tuple full_type_name loc l = let cnv_patts patts = ppat_tuple ~loc patts in let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in bin_size_tup_rec full_type_name loc cnv_patts get_tp mk_patt l and bin_size_record full_type_name loc tp = let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in bin_size_tup_rec full_type_name loc cnv_patts get_tp mk_patt tp and bin_size_variant full_type_name loc row_fields = let nonatom_matchings = List.fold_left row_fields ~init:[] ~f:(fun acc rf -> match rf.prf_desc with | Rtag (_, true, _) -> acc | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let size_args = match bin_size_type full_type_name tp.ptyp_loc tp with | `Fun fun_expr -> eapply ~loc fun_expr [ [%expr args] ] | `Match cases -> pexp_match ~loc [%expr args] cases in case ~lhs:(ppat_variant cnstr ~loc (Some [%pat? args])) ~guard:None ~rhs: [%expr let size_args = [%e size_args] in Bin_prot.Common.( + ) size_args 4] :: acc | Rinherit ty -> let loc = { ty.ptyp_loc with loc_ghost = true } in (match ty.ptyp_desc with | Ptyp_constr (id, args) -> let call = bin_size_appl_fun full_type_name loc id args in case ~lhs:(ppat_alias ~loc (ppat_type ~loc id) (Located.mk ~loc "v")) ~guard:None ~rhs:(eapply ~loc call [ [%expr v] ]) :: acc | _ -> Location.raise_errorf ~loc "bin_size_variant: unknown type")) in let matchings = if atoms_in_row_fields row_fields then case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:[%expr 4] :: nonatom_matchings else nonatom_matchings in `Match (List.rev matchings) and bin_size_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_size_of_" ^ parm.txt) ~expr: [%expr fun _v -> raise (Bin_prot.Common.Poly_rec_write [%e estring ~loc full_type_name])] in List.map parms ~f:mk_binding in match bin_size_type full_type_name loc tp with | `Fun fun_expr -> `Fun (pexp_let ~loc Nonrecursive bindings fun_expr) | `Match matchings -> `Match [ case ~lhs:(pvar ~loc "arg") ~guard:None ~rhs: (pexp_let ~loc Nonrecursive bindings (pexp_match ~loc (evar ~loc "arg") matchings)) ] ;; let bin_size_sum full_type_name loc alts = let n_alts = List.length alts in let size_tag = if n_alts <= 256 then [%expr 1] else if n_alts <= 65536 then [%expr 2] else Location.raise_errorf ~loc "bin_size_sum: too many alternatives (%d > 65536)" n_alts in let nonatom_matchings = List.fold_left alts ~init:[] ~f:(fun acc cd -> (match cd.pcd_res with | None -> () | Some ty -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_size_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> acc | Pcstr_tuple args -> let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in let patts, size_args = bin_size_args full_type_name loc get_tp mk_patt args in let args = match patts with | [ patt ] -> patt | _ -> ppat_tuple ~loc patts in case ~lhs:(pconstruct cd (Some args)) ~guard:None ~rhs: [%expr let size = [%e size_tag] in [%e size_args]] :: acc | Pcstr_record fields -> let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in let patts, size_args = bin_size_args full_type_name loc get_tp mk_patt fields in case ~lhs:(pconstruct cd (Some (cnv_patts patts))) ~guard:None ~rhs: [%expr let size = [%e size_tag] in [%e size_args]] :: acc) in let atom_matching init atoms = List.fold_left atoms ~init:(pconstruct init None) ~f:(fun acc atom -> ppat_or ~loc acc (pconstruct atom None)) in let matchings = match atoms_in_variant alts with | [] -> nonatom_matchings | init :: atoms -> case ~lhs:(atom_matching init atoms) ~guard:None ~rhs:size_tag :: nonatom_matchings in `Match (List.rev matchings) ;; let bin_size_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Fun [%expr fun _v -> raise (Bin_prot.Common.Empty_type [%e estring ~loc full_type_name])] ;; let make_fun ~loc ?(don't_expand = false) fun_or_match = match fun_or_match with | `Fun fun_expr when don't_expand -> fun_expr | `Fun fun_expr -> alias_or_fun fun_expr [%expr fun v -> [%e eapply ~loc fun_expr [ [%expr v] ]]] | `Match matchings -> pexp_function ~loc matchings ;; let sizer_body_of_td ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let res = match td.ptype_kind with | Ptype_variant alts -> bin_size_sum full_type_name loc alts | Ptype_record flds -> bin_size_record full_type_name loc flds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_size_nil full_type_name loc | Some ty -> bin_size_type full_type_name loc ty) in make_fun ~loc ~don't_expand:(td_is_nil td) res ;; let bin_size_td ~should_omit_type_annot ~loc ~path td = let body = sizer_body_of_td ~path td in let tparam_patts = vars_of_params td ~prefix:"_size_of_" |> patts_of_vars in let pat = pvar ~loc @@ "bin_size_" ^ td.ptype_name.txt in let pat_with_type = if should_omit_type_annot then pat else ppat_constraint ~loc pat (generate_poly_type ~loc td "Bin_prot.Size.sizer") in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc tparam_patts body) ;; let bin_size ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let bindings = List.map tds ~f:(bin_size_td ~should_omit_type_annot ~loc ~path) in pstr_value ~loc rec_flag bindings ;; end module Generate_bin_write = struct let mk_abst_call ~loc id args = type_constr_conv ~loc id ~f:(fun s -> "bin_write_" ^ s) args ;; let rec bin_write_type full_type_name _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> `Fun (bin_write_appl_fun full_type_name loc id args) | Ptyp_tuple l -> bin_write_tuple full_type_name loc l | Ptyp_var parm -> `Fun (evar ~loc @@ "_write_" ^ parm) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_write_type: cannot convert functions to the binary protocol" | Ptyp_variant (row_fields, _, _) -> bin_write_variant full_type_name loc row_fields | Ptyp_poly (parms, ty) -> bin_write_poly full_type_name loc parms ty | _ -> Location.raise_errorf ~loc "bin_write_type: unknown type construct" and bin_write_appl_fun full_type_name loc id args = let loc = { loc with loc_ghost = true } in let writers = List.map args ~f:(fun ty -> match bin_write_type full_type_name ty.ptyp_loc ty with | `Fun e -> e | `Match cases -> [%expr fun buf ~pos -> [%e pexp_function ~loc:ty.ptyp_loc cases]]) in let e = match mk_abst_call ~loc id writers with | [%expr Bin_prot.Write.bin_write_array Bin_prot.Write.bin_write_float] -> [%expr Bin_prot.Write.bin_write_float_array] | e -> e in e and bin_write_args : 'a 'b. Full_type_name.t -> Location.t -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> 'b list * expression = fun full_type_name loc get_tp mk_patt tp -> let rec loop i = function | el :: rest -> let tp = get_tp el in let v_name = "v" ^ Int.to_string i in let v_expr = let e_name = evar ~loc v_name in match bin_write_type full_type_name loc tp with | `Fun fun_expr -> [%expr [%e fun_expr] buf ~pos [%e e_name]] | `Match cases -> pexp_match ~loc e_name cases in let patt = mk_patt loc v_name el in if List.is_empty rest then [ patt ], v_expr else ( let patts, in_expr = loop (i + 1) rest in ( patt :: patts , [%expr let pos = [%e v_expr] in [%e in_expr]] )) | [] -> assert false in loop 1 tp and bin_write_tup_rec : 'a 'b. Full_type_name.t -> Location.t -> ('b list -> pattern) -> ('a -> core_type) -> (Location.t -> string -> 'a -> 'b) -> 'a list -> _ = fun full_type_name loc cnv_patts get_tp mk_patt tp -> let patts, expr = bin_write_args full_type_name loc get_tp mk_patt tp in `Match [ case ~lhs:(cnv_patts patts) ~guard:None ~rhs:expr ] and bin_write_tuple full_type_name loc l = let cnv_patts patts = ppat_tuple ~loc patts in let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in bin_write_tup_rec full_type_name loc cnv_patts get_tp mk_patt l and bin_write_record full_type_name loc tp = let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in bin_write_tup_rec full_type_name loc cnv_patts get_tp mk_patt tp and bin_write_variant full_type_name loc row_fields = let matchings = List.map row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag ({ txt = cnstr; _ }, true, _) | Rtag ({ txt = cnstr; _ }, false, []) -> case ~lhs:(ppat_variant ~loc cnstr None) ~guard:None ~rhs: [%expr Bin_prot.Write.bin_write_variant_int buf ~pos [%e eint ~loc (Ocaml_common.Btype.hash_variant cnstr)]] | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let write_args = match bin_write_type full_type_name tp.ptyp_loc tp with | `Fun fun_expr -> [%expr [%e fun_expr] buf ~pos args] | `Match cases -> pexp_match ~loc [%expr args] cases in case ~lhs:(ppat_variant ~loc cnstr (Some [%pat? args])) ~guard:None ~rhs: [%expr let pos = Bin_prot.Write.bin_write_variant_int buf ~pos [%e eint ~loc (Ocaml_common.Btype.hash_variant cnstr)] in [%e write_args]] | Rinherit ty -> let loc = { ty.ptyp_loc with loc_ghost = true } in (match ty.ptyp_desc with | Ptyp_constr (id, args) -> let call = bin_write_appl_fun full_type_name loc id args in case ~lhs:(ppat_alias ~loc (ppat_type ~loc id) (Located.mk ~loc "v")) ~guard:None ~rhs:[%expr [%e call] buf ~pos v] | _ -> Location.raise_errorf ~loc "bin_write_variant: unknown type")) in `Match matchings and bin_write_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_write_" ^ parm.txt) ~expr: [%expr fun _buf ~pos:_ _v -> raise (Bin_prot.Common.Poly_rec_write [%e estring ~loc full_type_name])] in List.map parms ~f:mk_binding in match bin_write_type full_type_name loc tp with | `Fun fun_expr -> `Fun (pexp_let ~loc Nonrecursive bindings fun_expr) | `Match matchings -> `Match [ case ~lhs:(pvar ~loc "arg") ~guard:None ~rhs: (pexp_let ~loc Nonrecursive bindings (pexp_match ~loc (evar ~loc "arg") matchings)) ] ;; let bin_write_sum full_type_name loc alts = let n_alts = List.length alts in let write_tag = if n_alts <= 256 then [%expr Bin_prot.Write.bin_write_int_8bit buf ~pos] else if n_alts <= 65536 then [%expr Bin_prot.Write.bin_write_int_16bit buf ~pos] else Location.raise_errorf ~loc "bin_write_sum: too many alternatives (%d > 65536)" n_alts in let matchings = List.mapi alts ~f:(fun i cd -> (match cd.pcd_res with | None -> () | Some ty -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_write_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> let loc = cd.pcd_loc in case ~lhs:(pconstruct cd None) ~guard:None ~rhs:(eapply ~loc write_tag [ eint ~loc i ]) | Pcstr_tuple args -> let get_tp tp = tp in let mk_patt loc v_name _ = pvar ~loc v_name in let patts, write_args = bin_write_args full_type_name loc get_tp mk_patt args in let args = match patts with | [ patt ] -> patt | _ -> ppat_tuple ~loc patts in case ~lhs:(pconstruct cd (Some args)) ~guard:None ~rhs: [%expr let pos = [%e eapply ~loc write_tag [ eint ~loc i ]] in [%e write_args]] | Pcstr_record fields -> let cnv_patts lbls = ppat_record ~loc lbls Closed in let get_tp ld = ld.pld_type in let mk_patt loc v_name ld = Located.map lident ld.pld_name, pvar ~loc v_name in let patts, expr = bin_write_args full_type_name loc get_tp mk_patt fields in case ~lhs:(pconstruct cd (Some (cnv_patts patts))) ~guard:None ~rhs: [%expr let pos = [%e eapply ~loc write_tag [ eint ~loc i ]] in [%e expr]]) in `Match matchings ;; let bin_write_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Fun [%expr fun _buf ~pos:_ _v -> raise (Bin_prot.Common.Empty_type [%e estring ~loc full_type_name])] ;; let make_fun ~loc ?(don't_expand = false) fun_or_match = match fun_or_match with | `Fun fun_expr when don't_expand -> fun_expr | `Fun fun_expr -> alias_or_fun fun_expr [%expr fun buf ~pos v -> [%e fun_expr] buf ~pos v] | `Match matchings -> [%expr fun buf ~pos -> [%e pexp_function ~loc matchings]] ;; let writer_type_class_record ~loc ~size ~write = [%expr { Bin_prot.Type_class.size = [%e size]; Bin_prot.Type_class.write = [%e write] }] ;; let writer_body_of_td ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let res = match td.ptype_kind with | Ptype_variant alts -> bin_write_sum full_type_name loc alts | Ptype_record flds -> bin_write_record full_type_name loc flds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_write_nil full_type_name loc | Some ty -> bin_write_type full_type_name loc ty) in make_fun ~loc ~don't_expand:(td_is_nil td) res ;; let project_vars expr vars ~field_name = let loc = expr.pexp_loc in let call = project_vars expr vars ~record_type:[%type: _ Bin_prot.Type_class.writer] ~field_name in alias_or_fun call [%expr fun v -> [%e eapply ~loc call [ [%expr v] ]]] ;; let bin_write_td ~should_omit_type_annot ~loc ~path td = let body = writer_body_of_td ~path td in let size_name = "bin_size_" ^ td.ptype_name.txt in let write_name = "bin_write_" ^ td.ptype_name.txt in let write_binding = let tparam_patts = vars_of_params td ~prefix:"_write_" |> patts_of_vars in let pat = pvar ~loc write_name in let pat_with_type = if should_omit_type_annot then pat else ppat_constraint ~loc pat (generate_poly_type ~loc td "Bin_prot.Write.writer") in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc tparam_patts body) in let writer_binding = let vars = vars_of_params td ~prefix:"bin_writer_" in let writer_record = writer_type_class_record ~loc ~size:(project_vars (evar ~loc size_name) vars ~field_name:"size") ~write:(project_vars (evar ~loc write_name) vars ~field_name:"write") in value_binding ~loc ~pat:(pvar ~loc @@ "bin_writer_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc (patts_of_vars vars) writer_record) in write_binding, writer_binding ;; let bin_write ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let write_bindings, writer_bindings = List.map tds ~f:(bin_write_td ~should_omit_type_annot ~loc ~path) |> List.unzip in [ Generate_bin_size.bin_size ~f_sharp_compatible ~loc ~path (rec_flag, tds) ; pstr_value ~loc rec_flag write_bindings ; pstr_value ~loc Nonrecursive writer_bindings ] ;; let gen = Deriving.Generator.make Deriving.Args.empty (bin_write ~f_sharp_compatible:false) ;; let extension ~loc ~path:_ ty = let loc = { loc with loc_ghost = true } in let full_type_name = Full_type_name.absent in let size = Generate_bin_size.bin_size_type full_type_name loc ty |> Generate_bin_size.make_fun ~loc in let write = bin_write_type full_type_name loc ty |> make_fun ~loc in writer_type_class_record ~loc ~size ~write ;; end module Generate_bin_read = struct let full_type_name_or_anonymous full_type_name = match Full_type_name.get full_type_name with | None -> "<anonymous type>" | Some s -> s ;; let mk_abst_call loc ?(internal = false) id args = type_constr_conv ~loc id args ~f:(fun s -> let s = "bin_read_" ^ s in if internal then "__" ^ s ^ "__" else s) ;; let bin_read_path_fun loc id args = mk_abst_call { loc with loc_ghost = true } id args let get_closed_expr loc = function | `Open expr -> [%expr fun buf ~pos_ref -> [%e expr]] | `Closed expr -> expr ;; let get_open_expr loc = function | `Open expr -> expr | `Closed expr -> [%expr [%e expr] buf ~pos_ref] ;; let rec handle_arg_tp loc full_type_name arg_tp = let args, bindings = let arg_map ai tp = let f = get_open_expr loc (bin_read_type full_type_name loc tp) in let arg_name = "arg_" ^ Int.to_string (ai + 1) in evar ~loc arg_name, value_binding ~loc ~pat:(pvar ~loc arg_name) ~expr:f in List.mapi arg_tp ~f:arg_map |> List.unzip in let args_expr = match args with | [ expr ] -> expr | _ -> pexp_tuple ~loc args in bindings, args_expr and bin_read_type_internal full_type_name ~full_type _loc ty = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) -> let args_expr = List.map args ~f:(fun tp -> get_closed_expr _loc (bin_read_type full_type_name _loc tp)) in let expr = match bin_read_path_fun id.loc id args_expr with | [%expr Bin_prot.Read.bin_read_array Bin_prot.Read.bin_read_float] -> [%expr Bin_prot.Read.bin_read_float_array] | expr -> expr in `Closed expr | Ptyp_tuple tp -> bin_read_tuple full_type_name loc tp | Ptyp_var parm -> `Closed (evar ~loc ("_of__" ^ parm)) | Ptyp_arrow _ -> Location.raise_errorf ~loc "bin_read_arrow: cannot convert functions" | Ptyp_variant (row_fields, _, _) -> bin_read_variant full_type_name loc ?full_type row_fields | Ptyp_poly (parms, poly_tp) -> bin_read_poly full_type_name loc parms poly_tp | _ -> Location.raise_errorf ~loc "bin_read_type: unknown type construct" and bin_read_type full_type_name loc ty = bin_read_type_internal full_type_name ~full_type:None loc ty and bin_read_type_toplevel full_type_name ~full_type loc ty = bin_read_type_internal full_type_name ~full_type:(Some full_type) loc ty and bin_read_tuple full_type_name loc tps = let bindings, exprs = let map i tp = let v_name = "v" ^ Int.to_string (i + 1) in let expr = get_open_expr loc (bin_read_type full_type_name loc tp) in value_binding ~loc ~pat:(pvar ~loc v_name) ~expr, evar ~loc v_name in List.mapi tps ~f:map |> List.unzip in `Open (let_ins loc bindings (pexp_tuple ~loc exprs)) and mk_internal_call full_type_name loc ty = let loc = { loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (id, args) | Ptyp_class (id, args) -> let arg_exprs = List.map args ~f:(fun tp -> get_closed_expr loc (bin_read_type full_type_name loc tp)) in mk_abst_call loc ~internal:true id arg_exprs | _ -> Location.raise_errorf ~loc:ty.ptyp_loc "bin_read: unknown type" and bin_read_variant full_type_name loc ?full_type row_fields = let is_contained, full_type = match full_type with | None -> true, ptyp_variant ~loc row_fields Closed None | Some full_type -> false, full_type in let code = let mk_check_vint mcs = pexp_match ~loc (evar ~loc "vint") mcs in let mk_try_next_expr call next_expr = [%expr try [%e call] with | Bin_prot.Common.No_variant_match -> [%e next_expr]] in let raise_nvm = [%expr raise Bin_prot.Common.No_variant_match] in let rec loop_many next = function | h :: t -> loop_one next t h | [] -> (match next with | `Matches mcs -> mk_check_vint mcs | `Expr expr -> expr | `None -> raise_nvm) and loop_one next t row_field = match row_field.prf_desc with | Rtag ({ txt = cnstr; _ }, is_constant, tps) -> let rhs = match is_constant, tps with | false, arg_tp :: _ -> let bnds, args_expr = handle_arg_tp loc full_type_name [ arg_tp ] in let_ins loc bnds (pexp_variant ~loc cnstr (Some args_expr)) | _ -> pexp_variant ~loc cnstr None in let this_mc = case ~lhs:(pint ~loc (Ocaml_common.Btype.hash_variant cnstr)) ~guard:None ~rhs in add_mc next this_mc t | Rinherit ty -> let call = [%expr ([%e mk_internal_call full_type_name ty.ptyp_loc ty] buf ~pos_ref vint :> [%t full_type])] in let expr = match next with | `Matches mcs -> mk_try_next_expr call (mk_check_vint mcs) | `Expr expr -> mk_try_next_expr call expr | `None -> call in loop_many (`Expr expr) t and add_mc next this_mc t = let next_mcs = match next with | `Matches mcs -> mcs | `Expr expr -> [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:expr ] | `None -> [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:raise_nvm ] in loop_many (`Matches (this_mc :: next_mcs)) t in loop_many `None (List.rev row_fields) in if is_contained then ( let full_type_name = full_type_name_or_anonymous full_type_name in `Open [%expr let vint = Bin_prot.Read.bin_read_variant_int buf ~pos_ref in try [%e code] with | Bin_prot.Common.No_variant_match -> Bin_prot.Common.raise_variant_wrong_type [%e estring ~loc full_type_name] !pos_ref]) else `Open code and bin_read_poly full_type_name loc parms tp = let bindings = let mk_binding parm = let full_type_name = Full_type_name.get_exn ~loc full_type_name in value_binding ~loc ~pat:(pvar ~loc @@ "_of__" ^ parm.txt) ~expr: [%expr fun _buf ~pos_ref -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Poly_rec_bound [%e estring ~loc full_type_name]) !pos_ref] in List.map parms ~f:mk_binding in let f = get_open_expr loc (bin_read_type full_type_name loc tp) in `Open (pexp_let ~loc Nonrecursive bindings f) ;; let bin_read_label_declaration_list full_type_name loc fields wrap = let bindings, rec_bindings = let map field = let loc = field.pld_loc in let v_name = "v_" ^ field.pld_name.txt in let f = get_open_expr loc (bin_read_type full_type_name loc field.pld_type) in ( value_binding ~loc ~pat:(pvar ~loc:field.pld_name.loc v_name) ~expr:f , (Located.map lident field.pld_name, evar ~loc:field.pld_name.loc v_name) ) in List.map fields ~f:map |> List.unzip in let_ins loc bindings (wrap (pexp_record ~loc rec_bindings None)) ;; let bin_read_sum full_type_name loc alts = let map mi cd = (match cd.pcd_res with | None -> () | Some _ -> Location.raise_errorf ~loc:cd.pcd_loc "bin_read_sum: GADTs are not supported by bin_prot"); match cd.pcd_args with | Pcstr_tuple [] -> let loc = cd.pcd_loc in case ~lhs:(pint ~loc mi) ~guard:None ~rhs:(econstruct cd None) | Pcstr_tuple args -> let bindings, args_expr = handle_arg_tp loc full_type_name args in let rhs = let_ins loc bindings (econstruct cd (Some args_expr)) in case ~lhs:(pint ~loc mi) ~guard:None ~rhs | Pcstr_record fields -> let rhs = bin_read_label_declaration_list full_type_name loc fields (fun e -> econstruct cd (Some e)) in case ~lhs:(pint ~loc mi) ~guard:None ~rhs in let mcs = List.mapi alts ~f:map in let n_alts = List.length alts in let read_fun = if n_alts <= 256 then [%expr Bin_prot.Read.bin_read_int_8bit] else if n_alts <= 65536 then [%expr Bin_prot.Read.bin_read_int_16bit] else Location.raise_errorf ~loc "bin_size_sum: too many alternatives (%d > 65536)" n_alts in let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Open (pexp_match ~loc [%expr [%e read_fun] buf ~pos_ref] (mcs @ [ case ~lhs:(ppat_any ~loc) ~guard:None ~rhs: [%expr Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Sum_tag [%e estring ~loc full_type_name]) !pos_ref] ])) ;; let bin_read_record full_type_name loc fields = let rhs = bin_read_label_declaration_list full_type_name loc fields (fun x -> x) in `Open rhs ;; let bin_read_nil full_type_name loc = let full_type_name = Full_type_name.get_exn ~loc full_type_name in `Closed [%expr fun _buf ~pos_ref -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Empty_type [%e estring ~loc full_type_name]) !pos_ref] ;; let reader_body_of_td td full_type_name = let loc = td.ptype_loc in match td.ptype_kind with | Ptype_variant cds -> bin_read_sum full_type_name loc cds | Ptype_record lds -> bin_read_record full_type_name loc lds | Ptype_open -> Location.raise_errorf ~loc "bin_size_td: open types not yet supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> bin_read_nil full_type_name loc | Some ty -> bin_read_type_toplevel full_type_name loc ty ~full_type:(core_type_of_type_declaration td)) ;; let main_body_for_polymorphic_variant ~loc ~vtag_read_name ~full_type_name ~args = let full_type_name = full_type_name_or_anonymous full_type_name in let vtag_read_expr = evar ~loc vtag_read_name in [%expr fun buf ~pos_ref -> let vint = Bin_prot.Read.bin_read_variant_int buf ~pos_ref in try [%e eapply ~loc vtag_read_expr (exprs_of_vars args)] buf ~pos_ref vint with | Bin_prot.Common.No_variant_match -> let err = Bin_prot.Common.ReadError.Variant [%e estring ~loc full_type_name] in Bin_prot.Common.raise_read_error err !pos_ref] ;; module Td_class = struct type polymorphic_variant = { all_atoms : bool } type t = | Polymorphic_variant of polymorphic_variant | Alias_but_not_polymorphic_variant | Other let of_core_type ty = match ty.ptyp_desc with | Ptyp_variant (row_fields, _, _) -> let all_atoms = List.for_all row_fields ~f:(fun row_field -> match row_field.prf_desc with | Rtag (_, is_constant, _) -> is_constant | Rinherit _ -> false) in Polymorphic_variant { all_atoms } | _ -> Alias_but_not_polymorphic_variant ;; let of_td td = match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, Some ty -> of_core_type ty | _ -> Other ;; end let variant_wrong_type ~loc full_type_name = let full_type_name = full_type_name_or_anonymous full_type_name in [%expr fun _buf ~pos_ref _vint -> Bin_prot.Common.raise_variant_wrong_type [%e estring ~loc full_type_name] !pos_ref] ;; let vtag_reader ~loc ~(td_class : Td_class.t) ~full_type_name ~oc_body = match td_class with | Alias_but_not_polymorphic_variant -> (match oc_body with | `Closed call -> let rec rewrite_call cnv e = let loc = e.pexp_loc in match e.pexp_desc with | Pexp_apply (f, [ arg ]) -> rewrite_call (fun new_f -> cnv (pexp_apply ~loc new_f [ arg ])) f | Pexp_ident { txt = Ldot (Ldot (Lident "Bin_prot", "Read"), _); _ } -> variant_wrong_type ~loc full_type_name | Pexp_ident { txt = Lident name; _ } when String.is_prefix name ~prefix:"_o" -> let full_type_name = Full_type_name.get_exn ~loc full_type_name in [%expr fun _buf ~pos_ref _vint -> Bin_prot.Common.raise_read_error (Bin_prot.Common.ReadError.Silly_type [%e estring ~loc full_type_name]) !pos_ref] | Pexp_ident id -> let expr = unapplied_type_constr_conv ~loc id ~f:(fun s -> "__" ^ s ^ "__") in let cnv_expr = cnv expr in alias_or_fun cnv_expr [%expr fun buf ~pos_ref vint -> [%e cnv_expr] buf ~pos_ref vint] | _ -> let s = Pprintast.string_of_expression e in Location.raise_errorf ~loc "ppx_bin_prot: impossible case: %s" s in rewrite_call (fun x -> x) (curry_applications call) | _ -> variant_wrong_type ~loc full_type_name) | Polymorphic_variant { all_atoms } -> (match oc_body with | `Open body when all_atoms -> [%expr fun _buf ~pos_ref:_ vint -> [%e body]] | `Open body -> [%expr fun buf ~pos_ref vint -> [%e body]] | Other -> variant_wrong_type ~loc full_type_name ;; let read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type ~vtag_read_name ~vtag_read_binding_type ~full_type_name ~(td_class : Td_class.t) ~args ~oc_body = let read_binding = let body = match td_class with | Polymorphic_variant _ -> main_body_for_polymorphic_variant ~loc ~vtag_read_name ~full_type_name ~args | Alias_but_not_polymorphic_variant | Other -> (match oc_body with | `Closed expr -> alias_or_fun expr [%expr fun buf ~pos_ref -> [%e expr] buf ~pos_ref] | `Open body -> [%expr fun buf ~pos_ref -> [%e body]]) in let pat = pvar ~loc read_name in let pat_with_type = match read_binding_type with | None -> pat | Some ty -> ppat_constraint ~loc pat ty in value_binding ~loc ~pat:pat_with_type ~expr:(eabstract ~loc (patts_of_vars args) body) in let vtag_read_binding = let pat = pvar ~loc vtag_read_name in let pat_with_type = match vtag_read_binding_type with | None -> pat | Some ty -> ppat_constraint ~loc pat ty in value_binding ~loc ~pat:pat_with_type ~expr: (eabstract ~loc (patts_of_vars args) (vtag_reader ~loc ~td_class ~full_type_name ~oc_body)) in read_binding, vtag_read_binding ;; let reader_type_class_record ~loc ~read ~vtag_read = [%expr { Bin_prot.Type_class.read = [%e read] ; Bin_prot.Type_class.vtag_read = [%e vtag_read] }] ;; let bin_read_td ~should_omit_type_annot ~loc:_ ~path td = let full_type_name = Full_type_name.make ~path td in let loc = td.ptype_loc in let oc_body = reader_body_of_td td full_type_name in let read_name = "bin_read_" ^ td.ptype_name.txt in let vtag_read_name = "__bin_read_" ^ td.ptype_name.txt ^ "__" in let vtag_read_binding_type, read_binding_type = if should_omit_type_annot then None, None else ( Some (generate_poly_type ~loc td "Bin_prot.Read.reader" ~wrap_result:(fun ~loc t -> [%type: int -> [%t t]])) , Some (generate_poly_type ~loc td "Bin_prot.Read.reader") ) in let read_binding, vtag_read_binding = let args = vars_of_params td ~prefix:"_of__" in read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type ~vtag_read_name ~vtag_read_binding_type ~full_type_name ~td_class:(Td_class.of_td td) ~args ~oc_body in let vars = vars_of_params td ~prefix:"bin_reader_" in let project_vars = project_vars ~record_type:[%type: _ Bin_prot.Type_class.reader] in let read = let call = project_vars (evar ~loc read_name) vars ~field_name:"read" in alias_or_fun call [%expr fun buf ~pos_ref -> [%e call] buf ~pos_ref] in let vtag_read = let call = project_vars (evar ~loc vtag_read_name) vars ~field_name:"read" in alias_or_fun call [%expr fun buf ~pos_ref vtag -> [%e call] buf ~pos_ref vtag] in let reader = reader_type_class_record ~loc ~read ~vtag_read in let reader_binding = value_binding ~loc ~pat:(pvar ~loc @@ "bin_reader_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc (patts_of_vars vars) reader) in vtag_read_binding, (read_binding, reader_binding) ;; let bin_read ~f_sharp_compatible ~loc ~path (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = really_recursive rec_flag tds in (match rec_flag, tds with | Nonrecursive, _ :: _ :: _ -> Location.raise_errorf ~loc "bin_prot doesn't support multiple nonrecursive definitions." | _ -> ()); let should_omit_type_annot = should_omit_type_annot ~f_sharp_compatible tds in let vtag_read_bindings, read_and_reader_bindings = List.map tds ~f:(bin_read_td ~should_omit_type_annot ~loc ~path) |> List.unzip in let read_bindings, reader_bindings = List.unzip read_and_reader_bindings in let defs = match rec_flag with | Recursive -> [ pstr_value ~loc Recursive (vtag_read_bindings @ read_bindings) ] | Nonrecursive -> let cnv binding = pstr_value ~loc Nonrecursive [ binding ] in List.map vtag_read_bindings ~f:cnv @ List.map read_bindings ~f:cnv in defs @ [ pstr_value ~loc Nonrecursive reader_bindings ] ;; let gen = Deriving.Generator.make Deriving.Args.empty (bin_read ~f_sharp_compatible:false) ;; let extension ~loc ~path:_ ty = let loc = { loc with loc_ghost = true } in let full_type_name = Full_type_name.absent in let read_name = "read" in let vtag_read_name = "vtag_read" in let read_binding, vtag_read_binding = let oc_body = bin_read_type_toplevel full_type_name loc ty ~full_type:ty in read_and_vtag_read_bindings ~loc ~read_name ~read_binding_type:None ~vtag_read_name ~vtag_read_binding_type:None ~full_type_name ~td_class:(Td_class.of_core_type ty) ~args:[] ~oc_body in pexp_let ~loc Nonrecursive [ vtag_read_binding ] (pexp_let ~loc Nonrecursive [ read_binding ] (reader_type_class_record ~loc ~read:(evar ~loc read_name) ~vtag_read:(evar ~loc vtag_read_name))) ;; end module Generate_tp_class = struct let tp_record ~loc ~writer ~reader ~shape = [%expr { Bin_prot.Type_class.writer = [%e writer] ; reader = [%e reader] ; shape = [%e shape] }] ;; let bin_tp_class_td td = let loc = td.ptype_loc in let tparam_cnvs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in "bin_" ^ name.txt) in let mk_pat id = pvar ~loc id in let tparam_patts = List.map tparam_cnvs ~f:mk_pat in let writer = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .writer]) in eapply ~loc (evar ~loc @@ "bin_writer_" ^ td.ptype_name.txt) tparam_exprs in let reader = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .reader]) in eapply ~loc (evar ~loc @@ "bin_reader_" ^ td.ptype_name.txt) tparam_exprs in let shape = let tparam_exprs = List.map td.ptype_params ~f:(fun tp -> let name = get_type_param_name tp in [%expr ([%e evar ~loc:name.loc @@ "bin_" ^ name.txt] : _ Bin_prot.Type_class.t) .shape]) in eapply ~loc (evar ~loc @@ "bin_shape_" ^ td.ptype_name.txt) tparam_exprs in let body = tp_record ~loc ~writer ~reader ~shape in value_binding ~loc ~pat:(pvar ~loc @@ "bin_" ^ td.ptype_name.txt) ~expr:(eabstract ~loc tparam_patts body) ;; let bin_tp_class ~loc ~path:_ (_rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let bindings = List.map tds ~f:bin_tp_class_td in [ pstr_value ~loc Nonrecursive bindings ] ;; let gen = Deriving.Generator.make Deriving.Args.empty bin_tp_class let extension ~loc ~path ty = let loc = { loc with loc_ghost = true } in tp_record ~loc ~writer:(Generate_bin_write.extension ~loc ~path ty) ~reader:(Generate_bin_read.extension ~loc ~path ty) ~shape:(Bin_shape_expand.shape_extension ~loc ty) ;; end let bin_shape = Deriving.add "bin_shape" ~str_type_decl:Bin_shape_expand.str_gen ~sig_type_decl:Bin_shape_expand.sig_gen ~extension:(fun ~loc ~path:_ -> Bin_shape_expand.shape_extension ~loc) ;; let () = Deriving.add "bin_digest" ~extension:(fun ~loc ~path:_ -> Bin_shape_expand.digest_extension ~loc) |> Deriving.ignore ;; let bin_write = Deriving.add "bin_write" ~str_type_decl:Generate_bin_write.gen ~sig_type_decl:Sig.bin_write ;; let () = Deriving.add "bin_writer" ~extension:Generate_bin_write.extension |> Deriving.ignore ;; let bin_read = Deriving.add "bin_read" ~str_type_decl:Generate_bin_read.gen ~sig_type_decl:Sig.bin_read ;; let () = Deriving.add "bin_reader" ~extension:Generate_bin_read.extension |> Deriving.ignore ;; let bin_type_class = Deriving.add "bin_type_class" ~str_type_decl:Generate_tp_class.gen ~sig_type_decl:Sig.bin_type_class ~extension:Generate_tp_class.extension ;; let bin_io_named_sig = Deriving.add "bin_io.named_sig.prevent using this in source files" ~sig_type_decl:Sig.named ;; let bin_io = let set = [ bin_shape; bin_write; bin_read; bin_type_class ] in Deriving.add_alias "bin_io" set ~sig_type_decl:[ bin_io_named_sig ] ~str_type_decl:(List.rev set) ;; The differences between F # and : 1 . F # does n't have labeled arguments so all labeled arguments are changed into not labeled . This implies we must pass all arguments in definition order even if they are labeled . 2 . Universal quantifier annotations are not supported in F # so we never generate the annotation that uses it . These are only needed for polymorphic recursion anyway . Changes compatible with OCaml to support F # : 1 . When prefixing record fields with path to module OCaml only requires one field to be prefixed but F # requires all fields to be prefixed , 2 . Accessing fields with a qualified path [ record.M.field ] does n't work in F # , so use type - directed disambiguation . 1. F# doesn't have labeled arguments so all labeled arguments are changed into not labeled. This implies we must pass all arguments in definition order even if they are labeled. 2. Universal quantifier annotations are not supported in F# so we never generate the annotation that uses it. These are only needed for polymorphic recursion anyway. Changes compatible with OCaml to support F#: 1. When prefixing record fields with path to module OCaml only requires one field to be prefixed but F# requires all fields to be prefixed, 2. Accessing fields with a qualified path [record.M.field] doesn't work in F#, so use type-directed disambiguation. *) module For_f_sharp = struct let remove_labeled_arguments = object inherit Ast_traverse.map method! arg_label (_ : arg_label) = Nolabel end ;; let bin_write ~loc ~path (rec_flag, tds) = let structure = Generate_bin_write.bin_write ~f_sharp_compatible:true ~loc ~path (rec_flag, tds) in remove_labeled_arguments#structure structure ;; let bin_read ~loc ~path (rec_flag, tds) = let structure = Generate_bin_read.bin_read ~f_sharp_compatible:true ~loc ~path (rec_flag, tds) in remove_labeled_arguments#structure structure ;; end
513f7048e32b2af93d628092525f1c0699be18a4041f6547c88420126f1e0201
sorted-falnyd/clj-airlock-client
api.clj
(ns sorted-falnyd.airlock.client.api (:require [sorted-falnyd.airlock.ship :as ship] [sorted-falnyd.airlock.connection :as conn] [sorted-falnyd.airlock.http :as http])) (defn client "Construct an API Client. Returns a map describing the connection which contains a channel on which all subscription updates and responses are sent. Pass to [[send!]] as a first argument. Handle incoming updates by subscribing to the connection `:channel`. Available options: Ship options: - `:port` ship port. int(optional, default 8080). - `:uri` ship URI. string(optional, default ). - `:code` HTTP login code. Optional but you probably want to provide a real one when connecting to a real ship. Connection options: - `:client` http client. Optional. - `:buf-or-n` buffer or size of the connection channel. - `:callbacks` - map of callbacks for handling incoming SSE updates. see: [[sorted-falnyd.airlock.connection/default-callbacks]]" ([] (client {})) ([options] (-> options ship/make-ship ship/login! conn/make-connection conn/build! conn/start!))) (defn send! [client action] (http/send! client action))
null
https://raw.githubusercontent.com/sorted-falnyd/clj-airlock-client/44f7756e927433628b6758179f460681c3994e1d/src/main/clojure/sorted_falnyd/airlock/client/api.clj
clojure
(ns sorted-falnyd.airlock.client.api (:require [sorted-falnyd.airlock.ship :as ship] [sorted-falnyd.airlock.connection :as conn] [sorted-falnyd.airlock.http :as http])) (defn client "Construct an API Client. Returns a map describing the connection which contains a channel on which all subscription updates and responses are sent. Pass to [[send!]] as a first argument. Handle incoming updates by subscribing to the connection `:channel`. Available options: Ship options: - `:port` ship port. int(optional, default 8080). - `:uri` ship URI. string(optional, default ). - `:code` HTTP login code. Optional but you probably want to provide a real one when connecting to a real ship. Connection options: - `:client` http client. Optional. - `:buf-or-n` buffer or size of the connection channel. - `:callbacks` - map of callbacks for handling incoming SSE updates. see: [[sorted-falnyd.airlock.connection/default-callbacks]]" ([] (client {})) ([options] (-> options ship/make-ship ship/login! conn/make-connection conn/build! conn/start!))) (defn send! [client action] (http/send! client action))
cfb692209fc419f606c245142e1b27137428921b4aaeb15d1db405eca598da77
thattommyhall/offline-4clojure
p34.clj
;; Implement range - Easy ;; Write a function which creates a list of all integers in a given range. ;; tags - seqs:core-functions ;; restricted - range (ns offline-4clojure.p34 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= (__ 1 4) '(1 2 3)) (= (__ -2 2) '(-2 -1 0 1)) (= (__ 5 8) '(5 6 7)) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p34.clj
clojure
Implement range - Easy Write a function which creates a list of all integers in a given range. tags - seqs:core-functions restricted - range your solution here
(ns offline-4clojure.p34 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= (__ 1 4) '(1 2 3)) (= (__ -2 2) '(-2 -1 0 1)) (= (__ 5 8) '(5 6 7)) ))
2ae904faa8064cd188aa365dc2f87f1c8a30ea0a4ae9c6d85869a4545ac77360
fishcakez/acceptor_pool
acceptor.erl
%%------------------------------------------------------------------- %% Copyright ( c ) 2016 , < > %% This file is provided to you 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. %% %%------------------------------------------------------------------- @doc This module provides a ` gen_tcp ' acceptor behaviour for use with ` acceptor_pool ' . There are three callbacks . %% Before accepting a socket ` acceptor_init/3 ' : %% ``` -callback acceptor_init(SockName , LSock , ) - > { ok , State } | { ok , State , TimeoutOrHib } | ignore | { error , Reason } when %% SockName :: acceptor_pool:name(), %% LSock :: gen_tcp:socket(), : : term ( ) , %% State :: term(), %% TimeoutOrHib :: timeout() | hibernate, %% Reason :: term(). %% ''' %% `SockName' is the `inet:sockname/1' of the listen socket, which may be ` { { 0,0,0,0 } , Port } ' if bound to all ip addresses . ` LSock ' is the listen socket and ` ' is the argument from the ` acceptor_pool : acceptor_spec/0 ' %% in the `acceptor_pool'. This callback should do any setup required before %% trying to accept on the socket. %% %% To be able to gracefully close open connections it is recommended for an acceptor process to ` monitor(port , LSock ) ' and gracefully close on receiving %% the DOWN messages. This can be combined with the listen socket being shut %% down before the `acceptor_pool' in the supervisor tree (e.g. after the ` acceptor_pool ' in a ` rest_for_one ' or ` one_for_all ' ) and the %% `acceptor_pool' defining the `grace' specification. %% %% To accept on the socket for `Timeout' timeout return ` { ok , State , Timeout : : timeout ( ) } ' with ` { ok , State } ' and ` { ok , State , hibernate } ' being equivalent to ` { ok , State , infinity } ' with the %% later also causing the process to hibernate before trying to accept a connection . ` State ' will be passed to either ` acceptor_continue/3 ' or %% `acceptor_continue/2'. %% %% To ignore this process and try again with another process return `ignore', or %% if an error occurs `{error, term()}'. Start errors always count towards the %% restart intensity of the `acceptor_pool', even with a `restart' of %% `temporary' but `ignore' does not. %% Once a socket is accepted ` acceptor_continue/3 ' : %% ``` -callback acceptor_continue(PeerName , , State ) - > no_return ( ) when %% PeerName :: acceptor_pool:name(), %% Sock :: gen_tcp:socket(), %% State :: term(). %% ''' ` PeerName ' the ` inet : peername/1 ' of the accepted socket ` Sock ' and ` State ' is the state returned by ` acceptor_init/3 ' . The callback module now has full %% control of the process and should enter its main loop, perhaps with %% `gen_statem:enter_loop/6'. %% It can be a long wait for a socket and so it possible for the ` State ' to have %% been created using an old version of the module. During the wait the process is hidden from the supervision tree and so hidden from the relup system . %% However it is possible to `load' both `acceptor' and the acceptor callback %% module during an appup with a soft post purge because neither module is on %% the call stack. %% If accepting a socket fails ` acceptor_terminate/2 ' : %% ``` -callback acceptor_terminate(Reason , State ) - > any ( ) when Reason : : { shutdown , timeout | closed | system_limit | inet : ( ) } | %% term(), %% State :: term(). %% ''' %% `Reason' is the reason for termination, and the exit reason of the process. %% If a socket error caused the termination the reason is ` { shutdown , timeout | closed | system_limit | inet : ( ) } ' . Otherwise the %% reason is an exit signal from the `acceptor_pool'. %% ` State ' is the state returned by ` acceptor_init/3 ' . -module(acceptor). -behaviour(acceptor_loop). %% public api -export([spawn_opt/6]). %% private api -export([init_it/7]). %% acceptor_loop api -export([acceptor_continue/3]). -export([acceptor_terminate/3]). -type option() :: {spawn_opt, [proc_lib:spawn_option()]}. -export_type([option/0]). -type data() :: #{module => module(), state => term(), socket_module => module(), socket => gen_tcp:socket(), ack => reference()}. -callback acceptor_init(SockName, LSock, Args) -> {ok, State} | {ok, State, TimeoutOrHib} | ignore | {error, Reason} when SockName :: acceptor_pool:name(), LSock :: gen_tcp:socket(), Args :: term(), State :: term(), TimeoutOrHib :: timeout() | hibernate, Reason :: term(). -callback acceptor_continue(PeerName, Sock, State) -> no_return() when PeerName :: acceptor_pool:name(), Sock :: gen_tcp:socket(), State :: term(). -callback acceptor_terminate(Reason, State) -> any() when Reason :: {shutdown, timeout | closed | system_limit | inet:posix()} | term(), State :: term(). %% public api @private -spec spawn_opt(Mod, SockMod, SockName, LSock, Args, Opts) -> {Pid, Ref} when Mod :: module(), SockMod :: module(), SockName :: acceptor_pool:name(), LSock :: gen_tcp:socket(), Args :: term(), Opts :: [option()], Pid :: pid(), Ref :: reference(). spawn_opt(Mod, SockMod, SockName, LSock, Args, Opts) -> AckRef = make_ref(), SArgs = [self(), AckRef, Mod, SockMod, SockName, LSock, Args], Pid = proc_lib:spawn_opt(?MODULE, init_it, SArgs, spawn_options(Opts)), {Pid, AckRef}. %% private api @private -ifdef(OTP_RELEASE). init_it(Parent, AckRef, Mod, SockMod, SockName, LSock, Args) -> _ = put('$initial_call', {Mod, init, 3}), try Mod:acceptor_init(SockName, LSock, Args) of Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName) catch throw:Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName); error:Reason:Stacktrace -> exit({Reason, Stacktrace}) end. -else. init_it(Parent, AckRef, Mod, SockMod, SockName, LSock, Args) -> _ = put('$initial_call', {Mod, init, 3}), try Mod:acceptor_init(SockName, LSock, Args) of Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName) catch throw:Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName); error:Reason -> exit({Reason, erlang:get_stacktrace()}) end. -endif. %% acceptor_loop api @private -spec acceptor_continue({ok, Sock} | {error, Reason}, Parent, Data) -> no_return() when Sock :: gen_tcp:socket(), Reason :: timeout | closed | system_limit | inet:posix(), Parent :: pid(), Data :: data(). acceptor_continue({ok, Sock}, Parent, #{socket := LSock} = Data) -> % As done by prim_inet:accept/2 OptNames = [active, nodelay, keepalive, delay_send, priority, tos], case inet:getopts(LSock, OptNames) of {ok, Opts} -> success(Sock, Opts, Parent, Data); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Parent, Data) end; acceptor_continue({error, Reason}, Parent, Data) -> failure(Reason, Parent, Data). @private -spec acceptor_terminate(Reason, Parent, Data) -> no_return() when Reason :: term(), Parent :: pid(), Data :: data(). acceptor_terminate(Reason, _, Data) -> terminate(Reason, Data). %% internal spawn_options(Opts) -> case lists:keyfind(spawn_options, 1, Opts) of {_, SpawnOpts} -> [link | SpawnOpts]; false -> [link] end. handle_init({ok, State}, Mod, SockMod, LSock, Parent, AckRef, SockName) -> handle_init({ok, State, infinity}, Mod, SockMod, LSock, Parent, AckRef, SockName); handle_init({ok, State, Timeout}, Mod, SockMod, LSock, Parent, AckRef, SockName) -> Data = #{module => Mod, state => State, socket_module => SockMod, socket => LSock, ack => AckRef, sockname => SockName}, % Use another module to accept so can reload this module. acceptor_loop:accept(LSock, Timeout, Parent, ?MODULE, Data); handle_init(ignore, _, _, _, Parent, AckRef, _) -> _ = Parent ! {'IGNORE', self(), AckRef}, exit(normal); handle_init(Other, _, _, _, _, _, _) -> handle_init(Other). handle_init({error, Reason}) -> exit(Reason); handle_init(Other) -> exit({bad_return_value, Other}). success(Sock, Opts, Parent, Data) -> case inet:peername(Sock) of {ok, PeerName} -> AcceptMsg = accept_message(Sock, PeerName, Data), _ = Parent ! AcceptMsg, continue(Sock, Opts, PeerName, Data); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Data) end. accept_message(Sock, PeerName, #{ack := AckRef, sockname := {{0,0,0,0}, _}}) -> case inet:sockname(Sock) of {ok, SockName} -> {'ACCEPT', self(), AckRef, SockName, PeerName}; _ -> {'ACCEPT', self(), AckRef, PeerName} end; accept_message(_, PeerName, #{ack := AckRef}) -> {'ACCEPT', self(), AckRef, PeerName}. continue(Sock, Opts, PeerName, Data) -> #{socket_module := SockMod, module := Mod, state := State} = Data, _ = inet_db:register_socket(Sock, SockMod), case inet:setopts(Sock, Opts) of ok -> Mod:acceptor_continue(PeerName, Sock, State); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Data) end. -spec failure(timeout | closed | system_limit | inet:posix(), pid(), data()) -> no_return(). failure(Reason, Parent, #{ack := AckRef} = Data) -> _ = Parent ! {'CANCEL', self(), AckRef}, failure(Reason, Data). -spec failure(timeout | closed | system_limit | inet:posix(), data()) -> no_return(). failure(timeout, Data) -> terminate({shutdown, timeout}, Data); failure(Reason, #{socket := LSock} = Data) -> Ref = monitor(port, LSock), exit(LSock, Reason), receive {'DOWN', Ref, _, _, _} -> terminate({shutdown, Reason}, Data) end. -spec terminate(any(), data()) -> no_return(). -ifdef(OTP_RELEASE). terminate(Reason, #{module := Mod, state := State} = Data) -> try Mod:acceptor_terminate(Reason, State) of _ -> terminated(Reason, Data) catch throw:_ -> terminated(Reason, Data); exit:NReason -> terminated(NReason, Data); error:NReason:Stacktrace -> terminated({NReason, Stacktrace}, Data) end. -else. terminate(Reason, #{module := Mod, state := State} = Data) -> try Mod:acceptor_terminate(Reason, State) of _ -> terminated(Reason, Data) catch throw:_ -> terminated(Reason, Data); exit:NReason -> terminated(NReason, Data); error:NReason -> terminated({NReason, erlang:get_stacktrace()}, Data) end. -endif. terminated(normal, _) -> exit(normal); terminated(shutdown, _) -> exit(shutdown); terminated({shutdown, _} = Shutdown, _) -> exit(Shutdown); terminated(Reason, #{module := Mod, state := State}) -> Msg = "** Acceptor ~p terminating~n" "** When acceptor state == ~p~n" "** Reason for termination ==~n** ~p~n", error_logger:format(Msg, [{self(), Mod}, State, Reason]), exit(Reason).
null
https://raw.githubusercontent.com/fishcakez/acceptor_pool/7eeda6c129577723e968735ee5495e00dd2e47da/src/acceptor.erl
erlang
------------------------------------------------------------------- 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, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- ``` SockName :: acceptor_pool:name(), LSock :: gen_tcp:socket(), State :: term(), TimeoutOrHib :: timeout() | hibernate, Reason :: term(). ''' `SockName' is the `inet:sockname/1' of the listen socket, which may be in the `acceptor_pool'. This callback should do any setup required before trying to accept on the socket. To be able to gracefully close open connections it is recommended for an the DOWN messages. This can be combined with the listen socket being shut down before the `acceptor_pool' in the supervisor tree (e.g. after the `acceptor_pool' defining the `grace' specification. To accept on the socket for `Timeout' timeout return later also causing the process to hibernate before trying to accept a `acceptor_continue/2'. To ignore this process and try again with another process return `ignore', or if an error occurs `{error, term()}'. Start errors always count towards the restart intensity of the `acceptor_pool', even with a `restart' of `temporary' but `ignore' does not. ``` PeerName :: acceptor_pool:name(), Sock :: gen_tcp:socket(), State :: term(). ''' control of the process and should enter its main loop, perhaps with `gen_statem:enter_loop/6'. been created using an old version of the module. During the wait the process However it is possible to `load' both `acceptor' and the acceptor callback module during an appup with a soft post purge because neither module is on the call stack. ``` term(), State :: term(). ''' `Reason' is the reason for termination, and the exit reason of the process. If a socket error caused the termination the reason is reason is an exit signal from the `acceptor_pool'. public api private api acceptor_loop api public api private api acceptor_loop api As done by prim_inet:accept/2 internal Use another module to accept so can reload this module.
Copyright ( c ) 2016 , < > This file is provided to you under the Apache License , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY @doc This module provides a ` gen_tcp ' acceptor behaviour for use with ` acceptor_pool ' . There are three callbacks . Before accepting a socket ` acceptor_init/3 ' : -callback acceptor_init(SockName , LSock , ) - > { ok , State } | { ok , State , TimeoutOrHib } | ignore | { error , Reason } when : : term ( ) , ` { { 0,0,0,0 } , Port } ' if bound to all ip addresses . ` LSock ' is the listen socket and ` ' is the argument from the ` acceptor_pool : acceptor_spec/0 ' acceptor process to ` monitor(port , LSock ) ' and gracefully close on receiving ` acceptor_pool ' in a ` rest_for_one ' or ` one_for_all ' ) and the ` { ok , State , Timeout : : timeout ( ) } ' with ` { ok , State } ' and ` { ok , State , hibernate } ' being equivalent to ` { ok , State , infinity } ' with the connection . ` State ' will be passed to either ` acceptor_continue/3 ' or Once a socket is accepted ` acceptor_continue/3 ' : -callback acceptor_continue(PeerName , , State ) - > no_return ( ) when ` PeerName ' the ` inet : peername/1 ' of the accepted socket ` Sock ' and ` State ' is the state returned by ` acceptor_init/3 ' . The callback module now has full It can be a long wait for a socket and so it possible for the ` State ' to have is hidden from the supervision tree and so hidden from the relup system . If accepting a socket fails ` acceptor_terminate/2 ' : -callback acceptor_terminate(Reason , State ) - > any ( ) when Reason : : { shutdown , timeout | closed | system_limit | inet : ( ) } | ` { shutdown , timeout | closed | system_limit | inet : ( ) } ' . Otherwise the ` State ' is the state returned by ` acceptor_init/3 ' . -module(acceptor). -behaviour(acceptor_loop). -export([spawn_opt/6]). -export([init_it/7]). -export([acceptor_continue/3]). -export([acceptor_terminate/3]). -type option() :: {spawn_opt, [proc_lib:spawn_option()]}. -export_type([option/0]). -type data() :: #{module => module(), state => term(), socket_module => module(), socket => gen_tcp:socket(), ack => reference()}. -callback acceptor_init(SockName, LSock, Args) -> {ok, State} | {ok, State, TimeoutOrHib} | ignore | {error, Reason} when SockName :: acceptor_pool:name(), LSock :: gen_tcp:socket(), Args :: term(), State :: term(), TimeoutOrHib :: timeout() | hibernate, Reason :: term(). -callback acceptor_continue(PeerName, Sock, State) -> no_return() when PeerName :: acceptor_pool:name(), Sock :: gen_tcp:socket(), State :: term(). -callback acceptor_terminate(Reason, State) -> any() when Reason :: {shutdown, timeout | closed | system_limit | inet:posix()} | term(), State :: term(). @private -spec spawn_opt(Mod, SockMod, SockName, LSock, Args, Opts) -> {Pid, Ref} when Mod :: module(), SockMod :: module(), SockName :: acceptor_pool:name(), LSock :: gen_tcp:socket(), Args :: term(), Opts :: [option()], Pid :: pid(), Ref :: reference(). spawn_opt(Mod, SockMod, SockName, LSock, Args, Opts) -> AckRef = make_ref(), SArgs = [self(), AckRef, Mod, SockMod, SockName, LSock, Args], Pid = proc_lib:spawn_opt(?MODULE, init_it, SArgs, spawn_options(Opts)), {Pid, AckRef}. @private -ifdef(OTP_RELEASE). init_it(Parent, AckRef, Mod, SockMod, SockName, LSock, Args) -> _ = put('$initial_call', {Mod, init, 3}), try Mod:acceptor_init(SockName, LSock, Args) of Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName) catch throw:Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName); error:Reason:Stacktrace -> exit({Reason, Stacktrace}) end. -else. init_it(Parent, AckRef, Mod, SockMod, SockName, LSock, Args) -> _ = put('$initial_call', {Mod, init, 3}), try Mod:acceptor_init(SockName, LSock, Args) of Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName) catch throw:Result -> handle_init(Result, Mod, SockMod, LSock, Parent, AckRef, SockName); error:Reason -> exit({Reason, erlang:get_stacktrace()}) end. -endif. @private -spec acceptor_continue({ok, Sock} | {error, Reason}, Parent, Data) -> no_return() when Sock :: gen_tcp:socket(), Reason :: timeout | closed | system_limit | inet:posix(), Parent :: pid(), Data :: data(). acceptor_continue({ok, Sock}, Parent, #{socket := LSock} = Data) -> OptNames = [active, nodelay, keepalive, delay_send, priority, tos], case inet:getopts(LSock, OptNames) of {ok, Opts} -> success(Sock, Opts, Parent, Data); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Parent, Data) end; acceptor_continue({error, Reason}, Parent, Data) -> failure(Reason, Parent, Data). @private -spec acceptor_terminate(Reason, Parent, Data) -> no_return() when Reason :: term(), Parent :: pid(), Data :: data(). acceptor_terminate(Reason, _, Data) -> terminate(Reason, Data). spawn_options(Opts) -> case lists:keyfind(spawn_options, 1, Opts) of {_, SpawnOpts} -> [link | SpawnOpts]; false -> [link] end. handle_init({ok, State}, Mod, SockMod, LSock, Parent, AckRef, SockName) -> handle_init({ok, State, infinity}, Mod, SockMod, LSock, Parent, AckRef, SockName); handle_init({ok, State, Timeout}, Mod, SockMod, LSock, Parent, AckRef, SockName) -> Data = #{module => Mod, state => State, socket_module => SockMod, socket => LSock, ack => AckRef, sockname => SockName}, acceptor_loop:accept(LSock, Timeout, Parent, ?MODULE, Data); handle_init(ignore, _, _, _, Parent, AckRef, _) -> _ = Parent ! {'IGNORE', self(), AckRef}, exit(normal); handle_init(Other, _, _, _, _, _, _) -> handle_init(Other). handle_init({error, Reason}) -> exit(Reason); handle_init(Other) -> exit({bad_return_value, Other}). success(Sock, Opts, Parent, Data) -> case inet:peername(Sock) of {ok, PeerName} -> AcceptMsg = accept_message(Sock, PeerName, Data), _ = Parent ! AcceptMsg, continue(Sock, Opts, PeerName, Data); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Data) end. accept_message(Sock, PeerName, #{ack := AckRef, sockname := {{0,0,0,0}, _}}) -> case inet:sockname(Sock) of {ok, SockName} -> {'ACCEPT', self(), AckRef, SockName, PeerName}; _ -> {'ACCEPT', self(), AckRef, PeerName} end; accept_message(_, PeerName, #{ack := AckRef}) -> {'ACCEPT', self(), AckRef, PeerName}. continue(Sock, Opts, PeerName, Data) -> #{socket_module := SockMod, module := Mod, state := State} = Data, _ = inet_db:register_socket(Sock, SockMod), case inet:setopts(Sock, Opts) of ok -> Mod:acceptor_continue(PeerName, Sock, State); {error, Reason} -> gen_tcp:close(Sock), failure(Reason, Data) end. -spec failure(timeout | closed | system_limit | inet:posix(), pid(), data()) -> no_return(). failure(Reason, Parent, #{ack := AckRef} = Data) -> _ = Parent ! {'CANCEL', self(), AckRef}, failure(Reason, Data). -spec failure(timeout | closed | system_limit | inet:posix(), data()) -> no_return(). failure(timeout, Data) -> terminate({shutdown, timeout}, Data); failure(Reason, #{socket := LSock} = Data) -> Ref = monitor(port, LSock), exit(LSock, Reason), receive {'DOWN', Ref, _, _, _} -> terminate({shutdown, Reason}, Data) end. -spec terminate(any(), data()) -> no_return(). -ifdef(OTP_RELEASE). terminate(Reason, #{module := Mod, state := State} = Data) -> try Mod:acceptor_terminate(Reason, State) of _ -> terminated(Reason, Data) catch throw:_ -> terminated(Reason, Data); exit:NReason -> terminated(NReason, Data); error:NReason:Stacktrace -> terminated({NReason, Stacktrace}, Data) end. -else. terminate(Reason, #{module := Mod, state := State} = Data) -> try Mod:acceptor_terminate(Reason, State) of _ -> terminated(Reason, Data) catch throw:_ -> terminated(Reason, Data); exit:NReason -> terminated(NReason, Data); error:NReason -> terminated({NReason, erlang:get_stacktrace()}, Data) end. -endif. terminated(normal, _) -> exit(normal); terminated(shutdown, _) -> exit(shutdown); terminated({shutdown, _} = Shutdown, _) -> exit(Shutdown); terminated(Reason, #{module := Mod, state := State}) -> Msg = "** Acceptor ~p terminating~n" "** When acceptor state == ~p~n" "** Reason for termination ==~n** ~p~n", error_logger:format(Msg, [{self(), Mod}, State, Reason]), exit(Reason).
64b3139c5790de37bb86fe3c3f733e48568357a30bc500888875fd722f50c539
tmattio/js-bindings
http2.mli
[@@@ocaml.warning "-7-11-32-33-39"] [@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"] ] open Ts2ocaml_baselib unknown identifiers : - Buffer - BufferEncoding - Error - EventEmitter - Http1IncomingHttpHeaders - NodeJS.ArrayBufferView - NodeJS.ErrnoException - OutgoingHttpHeaders - Uint8Array - fs . Stats - fs.promises . - net . Server - net . Socket - stream . Duplex - stream . Readable - stream . ReadableOptions - stream . Writable - tls . ConnectionOptions - tls . Server - tls . TLSSocket - tls . TlsOptions - url . URL unknown identifiers: - Buffer - BufferEncoding - Error - EventEmitter - Http1IncomingHttpHeaders - NodeJS.ArrayBufferView - NodeJS.ErrnoException - OutgoingHttpHeaders - Uint8Array - fs.Stats - fs.promises.FileHandle - net.Server - net.Socket - stream.Duplex - stream.Readable - stream.ReadableOptions - stream.Writable - tls.ConnectionOptions - tls.Server - tls.TLSSocket - tls.TlsOptions - url.URL *) [@@@js.stop] module type Missing = sig module Buffer : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module BufferEncoding : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Error : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module EventEmitter : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Http1IncomingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module NodeJS : sig module ArrayBufferView : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ErrnoException : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module OutgoingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Uint8Array : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module fs : sig module Stats : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module promises : sig module FileHandle : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end module net : sig module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Socket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module stream : sig module Duplex : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Readable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ReadableOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Writable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module tls : sig module ConnectionOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TLSSocket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TlsOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module url : sig module URL : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end [@@@js.start] [@@@js.implem module type Missing = sig module Buffer : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module BufferEncoding : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Error : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module EventEmitter : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Http1IncomingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module NodeJS : sig module ArrayBufferView : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ErrnoException : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module OutgoingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Uint8Array : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module fs : sig module Stats : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module promises : sig module FileHandle : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end module net : sig module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Socket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module stream : sig module Duplex : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Readable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ReadableOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Writable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module tls : sig module ConnectionOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TLSSocket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TlsOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module url : sig module URL : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end ] module Make (M: Missing) : sig open M module Internal : sig module AnonymousInterfaces : sig type anonymous_interface_0 = [`anonymous_interface_0] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] type anonymous_interface_1 = [`anonymous_interface_1] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] end module Types : sig open AnonymousInterfaces type http2_AlternativeServiceOptions = [`Http2_AlternativeServiceOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientHttp2Session = [`Http2_ClientHttp2Session | `Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientHttp2Stream = [`Http2_ClientHttp2Stream | `Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientSessionOptions = [`Http2_ClientSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientSessionRequestOptions = [`Http2_ClientSessionRequestOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2SecureServer = [`Http2_Http2SecureServer] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Server = [`Http2_Http2Server] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2ServerRequest = [`Http2_Http2ServerRequest] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2ServerResponse = [`Http2_Http2ServerResponse] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Session = [`Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Stream = [`Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_IncomingHttpHeaders = [`Http2_IncomingHttpHeaders] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_IncomingHttpStatusHeader = [`Http2_IncomingHttpStatusHeader] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureClientSessionOptions = [`Http2_SecureClientSessionOptions | `Http2_ClientSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureServerOptions = [`Http2_SecureServerOptions | `Http2_SecureServerSessionOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureServerSessionOptions = [`Http2_SecureServerSessionOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerHttp2Session = [`Http2_ServerHttp2Session | `Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerHttp2Stream = [`Http2_ServerHttp2Stream | `Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerOptions = [`Http2_ServerOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerSessionOptions = [`Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamFileResponseOptions = [`Http2_ServerStreamFileResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamFileResponseOptionsWithError = [`Http2_ServerStreamFileResponseOptionsWithError | `Http2_ServerStreamFileResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamResponseOptions = [`Http2_ServerStreamResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SessionOptions = [`Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SessionState = [`Http2_SessionState] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Settings = [`Http2_Settings] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StatOptions = [`Http2_StatOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StreamPriorityOptions = [`Http2_StreamPriorityOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StreamState = [`Http2_StreamState] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] end end open Internal open AnonymousInterfaces open Types module AnonymousInterface0 : sig type t = anonymous_interface_0 val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module AnonymousInterface1 : sig type t = anonymous_interface_1 val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_origin: t -> string [@@js.get "origin"] val set_origin: t -> string -> unit [@@js.set "origin"] end module[@js.scope "node:http2"] Node_http2 : sig export * from ' ' ; end module[@js.scope "http2"] Http2 : sig import EventEmitter = require('node : events ' ) ; (* import * as fs from 'node:fs'; *) (* import * as net from 'node:net'; *) (* import * as stream from 'node:stream'; *) (* import * as tls from 'node:tls'; *) (* import * as url from 'node:url'; *) import { IncomingHttpHeaders as Http1IncomingHttpHeaders , OutgoingHttpHeaders , IncomingMessage , ServerResponse , } from ' node : http ' ; IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse, } from 'node:http'; *) (* export { OutgoingHttpHeaders } from 'node:http'; *) module[@js.scope "IncomingHttpStatusHeader"] IncomingHttpStatusHeader : sig type t = http2_IncomingHttpStatusHeader val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get__status: t -> float [@@js.get ":status"] val set__status: t -> float -> unit [@@js.set ":status"] end module[@js.scope "IncomingHttpHeaders"] IncomingHttpHeaders : sig type t = http2_IncomingHttpHeaders val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get__path: t -> string [@@js.get ":path"] val set__path: t -> string -> unit [@@js.set ":path"] val get__method: t -> string [@@js.get ":method"] val set__method: t -> string -> unit [@@js.set ":method"] val get__authority: t -> string [@@js.get ":authority"] val set__authority: t -> string -> unit [@@js.set ":authority"] val get__scheme: t -> string [@@js.get ":scheme"] val set__scheme: t -> string -> unit [@@js.set ":scheme"] val cast: t -> Http1IncomingHttpHeaders.t_0 [@@js.cast] end module[@js.scope "StreamPriorityOptions"] StreamPriorityOptions : sig type t = http2_StreamPriorityOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_exclusive: t -> bool [@@js.get "exclusive"] val set_exclusive: t -> bool -> unit [@@js.set "exclusive"] val get_parent: t -> float [@@js.get "parent"] val set_parent: t -> float -> unit [@@js.set "parent"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] val get_silent: t -> bool [@@js.get "silent"] val set_silent: t -> bool -> unit [@@js.set "silent"] end module[@js.scope "StreamState"] StreamState : sig type t = http2_StreamState val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_localWindowSize: t -> float [@@js.get "localWindowSize"] val set_localWindowSize: t -> float -> unit [@@js.set "localWindowSize"] val get_state: t -> float [@@js.get "state"] val set_state: t -> float -> unit [@@js.set "state"] val get_localClose: t -> float [@@js.get "localClose"] val set_localClose: t -> float -> unit [@@js.set "localClose"] val get_remoteClose: t -> float [@@js.get "remoteClose"] val set_remoteClose: t -> float -> unit [@@js.set "remoteClose"] val get_sumDependencyWeight: t -> float [@@js.get "sumDependencyWeight"] val set_sumDependencyWeight: t -> float -> unit [@@js.set "sumDependencyWeight"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] end module[@js.scope "ServerStreamResponseOptions"] ServerStreamResponseOptions : sig type t = http2_ServerStreamResponseOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_endStream: t -> bool [@@js.get "endStream"] val set_endStream: t -> bool -> unit [@@js.set "endStream"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] end module[@js.scope "StatOptions"] StatOptions : sig type t = http2_StatOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_offset: t -> float [@@js.get "offset"] val set_offset: t -> float -> unit [@@js.set "offset"] val get_length: t -> float [@@js.get "length"] val set_length: t -> float -> unit [@@js.set "length"] end module[@js.scope "ServerStreamFileResponseOptions"] ServerStreamFileResponseOptions : sig type t = http2_ServerStreamFileResponseOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val statCheck: t -> stats:Fs.Stats.t_0 -> headers:OutgoingHttpHeaders.t_0 -> statOptions:http2_StatOptions -> unit or_boolean [@@js.call "statCheck"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] val get_offset: t -> float [@@js.get "offset"] val set_offset: t -> float -> unit [@@js.set "offset"] val get_length: t -> float [@@js.get "length"] val set_length: t -> float -> unit [@@js.set "length"] end module[@js.scope "ServerStreamFileResponseOptionsWithError"] ServerStreamFileResponseOptionsWithError : sig type t = http2_ServerStreamFileResponseOptionsWithError val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val onError: t -> err:NodeJS.ErrnoException.t_0 -> unit [@@js.call "onError"] val cast: t -> http2_ServerStreamFileResponseOptions [@@js.cast] end module[@js.scope "Http2Stream"] Http2Stream : sig type t = http2_Http2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_aborted: t -> bool [@@js.get "aborted"] val get_bufferSize: t -> float [@@js.get "bufferSize"] val get_closed: t -> bool [@@js.get "closed"] val get_destroyed: t -> bool [@@js.get "destroyed"] val get_endAfterHeaders: t -> bool [@@js.get "endAfterHeaders"] val get_id: t -> float [@@js.get "id"] val get_pending: t -> bool [@@js.get "pending"] val get_rstCode: t -> float [@@js.get "rstCode"] val get_sentHeaders: t -> OutgoingHttpHeaders.t_0 [@@js.get "sentHeaders"] val get_sentInfoHeaders: t -> OutgoingHttpHeaders.t_0 list [@@js.get "sentInfoHeaders"] val get_sentTrailers: t -> OutgoingHttpHeaders.t_0 [@@js.get "sentTrailers"] val get_session: t -> http2_Http2Session [@@js.get "session"] val get_state: t -> http2_StreamState [@@js.get "state"] val close: t -> ?code:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "close"] val priority: t -> options:http2_StreamPriorityOptions -> unit [@@js.call "priority"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val sendTrailers: t -> headers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "sendTrailers"] val addListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "addListener"] val addListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "addListener"] val addListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s1_aborted] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s7_data] [@js.enum]) -> chunk:Buffer.t_0 or_string -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s8_drain] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s9_end] [@js.enum]) -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s11_finish] [@js.enum]) -> bool [@@js.call "emit"] val emit''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> frameType:float -> errorCode:float -> bool [@@js.call "emit"] val emit'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> code:float -> bool [@@js.call "emit"] val emit''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> trailers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "on"] val on'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "on"] val on''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "once"] val once'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "once"] val once''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Duplex.t_0 [@@js.cast] end module[@js.scope "ClientHttp2Stream"] ClientHttp2Stream : sig type t = http2_ClientHttp2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s6_continue] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s14_headers] [@js.enum]) -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s21_push] [@js.enum]) -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s25_response] [@js.enum]) -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "on"] val on': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "once"] val once': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Stream [@@js.cast] end module[@js.scope "ServerHttp2Stream"] ServerHttp2Stream : sig type t = http2_ServerHttp2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_headersSent: t -> bool [@@js.get "headersSent"] val get_pushAllowed: t -> bool [@@js.get "pushAllowed"] val additionalHeaders: t -> headers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "additionalHeaders"] val pushStream: t -> headers:OutgoingHttpHeaders.t_0 -> ?callback:(err:Error.t_0 or_null -> pushStream:t -> headers:OutgoingHttpHeaders.t_0 -> unit) -> unit -> unit [@@js.call "pushStream"] val pushStream': t -> headers:OutgoingHttpHeaders.t_0 -> ?options:http2_StreamPriorityOptions -> ?callback:(err:Error.t_0 or_null -> pushStream:t -> headers:OutgoingHttpHeaders.t_0 -> unit) -> unit -> unit [@@js.call "pushStream"] val respond: t -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamResponseOptions -> unit -> unit [@@js.call "respond"] val respondWithFD: t -> fd:Fs.Promises.FileHandle.t_0 or_number -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamFileResponseOptions -> unit -> unit [@@js.call "respondWithFD"] val respondWithFile: t -> path:string -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamFileResponseOptionsWithError -> unit -> unit [@@js.call "respondWithFile"] val cast: t -> http2_Http2Stream [@@js.cast] end module[@js.scope "Settings"] Settings : sig type t = http2_Settings val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_headerTableSize: t -> float [@@js.get "headerTableSize"] val set_headerTableSize: t -> float -> unit [@@js.set "headerTableSize"] val get_enablePush: t -> bool [@@js.get "enablePush"] val set_enablePush: t -> bool -> unit [@@js.set "enablePush"] val get_initialWindowSize: t -> float [@@js.get "initialWindowSize"] val set_initialWindowSize: t -> float -> unit [@@js.set "initialWindowSize"] val get_maxFrameSize: t -> float [@@js.get "maxFrameSize"] val set_maxFrameSize: t -> float -> unit [@@js.set "maxFrameSize"] val get_maxConcurrentStreams: t -> float [@@js.get "maxConcurrentStreams"] val set_maxConcurrentStreams: t -> float -> unit [@@js.set "maxConcurrentStreams"] val get_maxHeaderListSize: t -> float [@@js.get "maxHeaderListSize"] val set_maxHeaderListSize: t -> float -> unit [@@js.set "maxHeaderListSize"] val get_enableConnectProtocol: t -> bool [@@js.get "enableConnectProtocol"] val set_enableConnectProtocol: t -> bool -> unit [@@js.set "enableConnectProtocol"] end module[@js.scope "ClientSessionRequestOptions"] ClientSessionRequestOptions : sig type t = http2_ClientSessionRequestOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_endStream: t -> bool [@@js.get "endStream"] val set_endStream: t -> bool -> unit [@@js.set "endStream"] val get_exclusive: t -> bool [@@js.get "exclusive"] val set_exclusive: t -> bool -> unit [@@js.set "exclusive"] val get_parent: t -> float [@@js.get "parent"] val set_parent: t -> float -> unit [@@js.set "parent"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] end module[@js.scope "SessionState"] SessionState : sig type t = http2_SessionState val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_effectiveLocalWindowSize: t -> float [@@js.get "effectiveLocalWindowSize"] val set_effectiveLocalWindowSize: t -> float -> unit [@@js.set "effectiveLocalWindowSize"] val get_effectiveRecvDataLength: t -> float [@@js.get "effectiveRecvDataLength"] val set_effectiveRecvDataLength: t -> float -> unit [@@js.set "effectiveRecvDataLength"] val get_nextStreamID: t -> float [@@js.get "nextStreamID"] val set_nextStreamID: t -> float -> unit [@@js.set "nextStreamID"] val get_localWindowSize: t -> float [@@js.get "localWindowSize"] val set_localWindowSize: t -> float -> unit [@@js.set "localWindowSize"] val get_lastProcStreamID: t -> float [@@js.get "lastProcStreamID"] val set_lastProcStreamID: t -> float -> unit [@@js.set "lastProcStreamID"] val get_remoteWindowSize: t -> float [@@js.get "remoteWindowSize"] val set_remoteWindowSize: t -> float -> unit [@@js.set "remoteWindowSize"] val get_outboundQueueSize: t -> float [@@js.get "outboundQueueSize"] val set_outboundQueueSize: t -> float -> unit [@@js.set "outboundQueueSize"] val get_deflateDynamicTableSize: t -> float [@@js.get "deflateDynamicTableSize"] val set_deflateDynamicTableSize: t -> float -> unit [@@js.set "deflateDynamicTableSize"] val get_inflateDynamicTableSize: t -> float [@@js.get "inflateDynamicTableSize"] val set_inflateDynamicTableSize: t -> float -> unit [@@js.set "inflateDynamicTableSize"] end module[@js.scope "Http2Session"] Http2Session : sig type t = http2_Http2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_alpnProtocol: t -> string [@@js.get "alpnProtocol"] val get_closed: t -> bool [@@js.get "closed"] val get_connecting: t -> bool [@@js.get "connecting"] val get_destroyed: t -> bool [@@js.get "destroyed"] val get_encrypted: t -> bool [@@js.get "encrypted"] val get_localSettings: t -> http2_Settings [@@js.get "localSettings"] val get_originSet: t -> string list [@@js.get "originSet"] val get_pendingSettingsAck: t -> bool [@@js.get "pendingSettingsAck"] val get_remoteSettings: t -> http2_Settings [@@js.get "remoteSettings"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_state: t -> http2_SessionState [@@js.get "state"] val get_type: t -> float [@@js.get "type"] val close: t -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "close"] val destroy: t -> ?error:Error.t_0 -> ?code:float -> unit -> unit [@@js.call "destroy"] val goaway: t -> ?code:float -> ?lastStreamID:float -> ?opaqueData:NodeJS.ArrayBufferView.t_0 -> unit -> unit [@@js.call "goaway"] val ping: t -> callback:(err:Error.t_0 or_null -> duration:float -> payload:Buffer.t_0 -> unit) -> bool [@@js.call "ping"] val ping': t -> payload:NodeJS.ArrayBufferView.t_0 -> callback:(err:Error.t_0 or_null -> duration:float -> payload:Buffer.t_0 -> unit) -> bool [@@js.call "ping"] val ref: t -> unit [@@js.call "ref"] val setLocalWindowSize: t -> windowSize:float -> unit [@@js.call "setLocalWindowSize"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val settings: t -> settings:http2_Settings -> unit [@@js.call "settings"] val unref: t -> unit [@@js.call "unref"] val addListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s12_frameError] [@js.enum]) -> frameType:float -> errorCode:float -> streamID:float -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s13_goaway] [@js.enum]) -> errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> settings:http2_Settings -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s19_ping] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> settings:http2_Settings -> bool [@@js.call "emit"] val emit''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "on"] val on''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "once"] val once''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> EventEmitter.t_0 [@@js.cast] end module[@js.scope "ClientHttp2Session"] ClientHttp2Session : sig type t = http2_ClientHttp2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val request: t -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ClientSessionRequestOptions -> unit -> http2_ClientHttp2Stream [@@js.call "request"] val addListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s2_altsvc] [@js.enum]) -> alt:string -> origin:string -> stream:float -> bool [@@js.call "emit"] val emit': t -> event:([`L_s18_origin] [@js.enum]) -> origins:string list -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s5_connect] [@js.enum]) -> session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Session [@@js.cast] end module[@js.scope "AlternativeServiceOptions"] AlternativeServiceOptions : sig type t = http2_AlternativeServiceOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_origin: t -> Url.URL.t_0 or_string or_number [@@js.get "origin"] val set_origin: t -> Url.URL.t_0 or_string or_number -> unit [@@js.set "origin"] end module[@js.scope "ServerHttp2Session"] ServerHttp2Session : sig type t = http2_ServerHttp2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_server: t -> (http2_Http2SecureServer, http2_Http2Server) union2 [@@js.get "server"] val altsvc: t -> alt:string -> originOrStream:(http2_AlternativeServiceOptions, Url.URL.t_0) union2 or_string or_number -> unit [@@js.call "altsvc"] val origin: t -> args:((* FIXME: type 'Array<union<String | ?url.URL | {..}>>' cannot be used for variadic argument *)any list [@js.variadic]) -> unit [@@js.call "origin"] val addListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s5_connect] [@js.enum]) -> session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> bool [@@js.call "emit"] val emit': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit'': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Session [@@js.cast] end module[@js.scope "SessionOptions"] SessionOptions : sig type t = http2_SessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_maxDeflateDynamicTableSize: t -> float [@@js.get "maxDeflateDynamicTableSize"] val set_maxDeflateDynamicTableSize: t -> float -> unit [@@js.set "maxDeflateDynamicTableSize"] val get_maxSessionMemory: t -> float [@@js.get "maxSessionMemory"] val set_maxSessionMemory: t -> float -> unit [@@js.set "maxSessionMemory"] val get_maxHeaderListPairs: t -> float [@@js.get "maxHeaderListPairs"] val set_maxHeaderListPairs: t -> float -> unit [@@js.set "maxHeaderListPairs"] val get_maxOutstandingPings: t -> float [@@js.get "maxOutstandingPings"] val set_maxOutstandingPings: t -> float -> unit [@@js.set "maxOutstandingPings"] val get_maxSendHeaderBlockLength: t -> float [@@js.get "maxSendHeaderBlockLength"] val set_maxSendHeaderBlockLength: t -> float -> unit [@@js.set "maxSendHeaderBlockLength"] val get_paddingStrategy: t -> float [@@js.get "paddingStrategy"] val set_paddingStrategy: t -> float -> unit [@@js.set "paddingStrategy"] val get_peerMaxConcurrentStreams: t -> float [@@js.get "peerMaxConcurrentStreams"] val set_peerMaxConcurrentStreams: t -> float -> unit [@@js.set "peerMaxConcurrentStreams"] val get_settings: t -> http2_Settings [@@js.get "settings"] val set_settings: t -> http2_Settings -> unit [@@js.set "settings"] val selectPadding: t -> frameLen:float -> maxFrameLen:float -> float [@@js.call "selectPadding"] val createConnection: t -> authority:Url.URL.t_0 -> option:t -> Stream.Duplex.t_0 [@@js.call "createConnection"] end module[@js.scope "ClientSessionOptions"] ClientSessionOptions : sig type t = http2_ClientSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_maxReservedRemoteStreams: t -> float [@@js.get "maxReservedRemoteStreams"] val set_maxReservedRemoteStreams: t -> float -> unit [@@js.set "maxReservedRemoteStreams"] val createConnection: t -> authority:Url.URL.t_0 -> option:http2_SessionOptions -> Stream.Duplex.t_0 [@@js.call "createConnection"] val get_protocol: t -> ([`L_s15_http_[@js "http:"] | `L_s16_https_[@js "https:"]] [@js.enum]) [@@js.get "protocol"] val set_protocol: t -> ([`L_s15_http_ | `L_s16_https_] [@js.enum]) -> unit [@@js.set "protocol"] val cast: t -> http2_SessionOptions [@@js.cast] end module[@js.scope "ServerSessionOptions"] ServerSessionOptions : sig type t = http2_ServerSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 FIXME : unknown type ' typeof IncomingMessage ' FIXME : unknown type ' typeof IncomingMessage ' val get_Http1ServerResponse: t -> (* FIXME: unknown type 'typeof ServerResponse' *)any [@@js.get "Http1ServerResponse"] val set_Http1ServerResponse: t -> (* FIXME: unknown type 'typeof ServerResponse' *)any -> unit [@@js.set "Http1ServerResponse"] val get_Http2ServerRequest: t -> (* FIXME: unknown type 'typeof Http2ServerRequest' *)any [@@js.get "Http2ServerRequest"] val set_Http2ServerRequest: t -> (* FIXME: unknown type 'typeof Http2ServerRequest' *)any -> unit [@@js.set "Http2ServerRequest"] val get_Http2ServerResponse: t -> (* FIXME: unknown type 'typeof Http2ServerResponse' *)any [@@js.get "Http2ServerResponse"] val set_Http2ServerResponse: t -> (* FIXME: unknown type 'typeof Http2ServerResponse' *)any -> unit [@@js.set "Http2ServerResponse"] val cast: t -> http2_SessionOptions [@@js.cast] end module[@js.scope "SecureClientSessionOptions"] SecureClientSessionOptions : sig type t = http2_SecureClientSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ClientSessionOptions [@@js.cast] val cast': t -> Tls.ConnectionOptions.t_0 [@@js.cast] end module[@js.scope "SecureServerSessionOptions"] SecureServerSessionOptions : sig type t = http2_SecureServerSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ServerSessionOptions [@@js.cast] val cast': t -> Tls.TlsOptions.t_0 [@@js.cast] end module[@js.scope "ServerOptions"] ServerOptions : sig type t = http2_ServerOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ServerSessionOptions [@@js.cast] end module[@js.scope "SecureServerOptions"] SecureServerOptions : sig type t = http2_SecureServerOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_allowHTTP1: t -> bool [@@js.get "allowHTTP1"] val set_allowHTTP1: t -> bool -> unit [@@js.set "allowHTTP1"] val get_origins: t -> string list [@@js.get "origins"] val set_origins: t -> string list -> unit [@@js.set "origins"] val cast: t -> http2_SecureServerSessionOptions [@@js.cast] end module[@js.scope "Http2Server"] Http2Server : sig type t = http2_Http2Server val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s3_checkContinue] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit': t -> event:([`L_s24_request] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s26_session] [@js.enum]) -> session:http2_ServerHttp2Session -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s27_sessionError] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val setTimeout: t -> ?msec:float -> ?callback:(unit -> unit) -> unit -> t [@@js.call "setTimeout"] val cast: t -> Net.Server.t_0 [@@js.cast] end module[@js.scope "Http2SecureServer"] Http2SecureServer : sig type t = http2_Http2SecureServer val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s3_checkContinue] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit': t -> event:([`L_s24_request] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s26_session] [@js.enum]) -> session:http2_ServerHttp2Session -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s27_sessionError] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> socket:Tls.TLSSocket.t_0 -> bool [@@js.call "emit"] val emit''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "on"] val on''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "once"] val once''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val setTimeout: t -> ?msec:float -> ?callback:(unit -> unit) -> unit -> t [@@js.call "setTimeout"] val cast: t -> Tls.Server.t_0 [@@js.cast] end module[@js.scope "Http2ServerRequest"] Http2ServerRequest : sig type t = http2_Http2ServerRequest val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val create: stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> options:Stream.ReadableOptions.t_0 -> rawHeaders:string list -> t [@@js.create] val get_aborted: t -> bool [@@js.get "aborted"] val get_authority: t -> string [@@js.get "authority"] val get_connection: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "connection"] val get_complete: t -> bool [@@js.get "complete"] val get_headers: t -> http2_IncomingHttpHeaders [@@js.get "headers"] val get_httpVersion: t -> string [@@js.get "httpVersion"] val get_httpVersionMinor: t -> float [@@js.get "httpVersionMinor"] val get_httpVersionMajor: t -> float [@@js.get "httpVersionMajor"] val get_method: t -> string [@@js.get "method"] val get_rawHeaders: t -> string list [@@js.get "rawHeaders"] val get_rawTrailers: t -> string list [@@js.get "rawTrailers"] val get_scheme: t -> string [@@js.get "scheme"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_stream: t -> http2_ServerHttp2Stream [@@js.get "stream"] val get_trailers: t -> http2_IncomingHttpHeaders [@@js.get "trailers"] val get_url: t -> string [@@js.get "url"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val read: t -> ?size:float -> unit -> Buffer.t_0 or_string or_null [@@js.call "read"] val addListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s1_aborted] [@js.enum]) -> hadError:bool -> code:float -> bool [@@js.call "emit"] val emit': t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s7_data] [@js.enum]) -> chunk:Buffer.t_0 or_string -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s9_end] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s22_readable] [@js.enum]) -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Readable.t_0 [@@js.cast] end module[@js.scope "Http2ServerResponse"] Http2ServerResponse : sig type t = http2_Http2ServerResponse val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val create: stream:http2_ServerHttp2Stream -> t [@@js.create] val get_connection: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "connection"] val get_finished: t -> bool [@@js.get "finished"] val get_headersSent: t -> bool [@@js.get "headersSent"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_stream: t -> http2_ServerHttp2Stream [@@js.get "stream"] val get_sendDate: t -> bool [@@js.get "sendDate"] val set_sendDate: t -> bool -> unit [@@js.set "sendDate"] val get_statusCode: t -> float [@@js.get "statusCode"] val set_statusCode: t -> float -> unit [@@js.set "statusCode"] val get_statusMessage: t -> ([`L_s0[@js ""]] [@js.enum]) [@@js.get "statusMessage"] val set_statusMessage: t -> ([`L_s0] [@js.enum]) -> unit [@@js.set "statusMessage"] val addTrailers: t -> trailers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "addTrailers"] val end_: t -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val end_': t -> data:Uint8Array.t_0 or_string -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val end_'': t -> data:Uint8Array.t_0 or_string -> encoding:BufferEncoding.t_0 -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val getHeader: t -> name:string -> string [@@js.call "getHeader"] val getHeaderNames: t -> string list [@@js.call "getHeaderNames"] val getHeaders: t -> OutgoingHttpHeaders.t_0 [@@js.call "getHeaders"] val hasHeader: t -> name:string -> bool [@@js.call "hasHeader"] val removeHeader: t -> name:string -> unit [@@js.call "removeHeader"] val setHeader: t -> name:string -> value:string list or_string or_number -> unit [@@js.call "setHeader"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val write: t -> chunk:Uint8Array.t_0 or_string -> ?callback:(err:Error.t_0 -> unit) -> unit -> bool [@@js.call "write"] val write': t -> chunk:Uint8Array.t_0 or_string -> encoding:BufferEncoding.t_0 -> ?callback:(err:Error.t_0 -> unit) -> unit -> bool [@@js.call "write"] val writeContinue: t -> unit [@@js.call "writeContinue"] val writeHead: t -> statusCode:float -> ?headers:OutgoingHttpHeaders.t_0 -> unit -> t [@@js.call "writeHead"] val writeHead': t -> statusCode:float -> statusMessage:string -> ?headers:OutgoingHttpHeaders.t_0 -> unit -> t [@@js.call "writeHead"] val createPushResponse: t -> headers:OutgoingHttpHeaders.t_0 -> callback:(err:Error.t_0 or_null -> res:t -> unit) -> unit [@@js.call "createPushResponse"] val addListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s8_drain] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s10_error] [@js.enum]) -> error:Error.t_0 -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s11_finish] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s20_pipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Writable.t_0 [@@js.cast] end module[@js.scope "constants"] Constants : sig val nGHTTP2_SESSION_SERVER: float [@@js.global "NGHTTP2_SESSION_SERVER"] val nGHTTP2_SESSION_CLIENT: float [@@js.global "NGHTTP2_SESSION_CLIENT"] val nGHTTP2_STREAM_STATE_IDLE: float [@@js.global "NGHTTP2_STREAM_STATE_IDLE"] val nGHTTP2_STREAM_STATE_OPEN: float [@@js.global "NGHTTP2_STREAM_STATE_OPEN"] val nGHTTP2_STREAM_STATE_RESERVED_LOCAL: float [@@js.global "NGHTTP2_STREAM_STATE_RESERVED_LOCAL"] val nGHTTP2_STREAM_STATE_RESERVED_REMOTE: float [@@js.global "NGHTTP2_STREAM_STATE_RESERVED_REMOTE"] val nGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: float [@@js.global "NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL"] val nGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: float [@@js.global "NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE"] val nGHTTP2_STREAM_STATE_CLOSED: float [@@js.global "NGHTTP2_STREAM_STATE_CLOSED"] val nGHTTP2_NO_ERROR: float [@@js.global "NGHTTP2_NO_ERROR"] val nGHTTP2_PROTOCOL_ERROR: float [@@js.global "NGHTTP2_PROTOCOL_ERROR"] val nGHTTP2_INTERNAL_ERROR: float [@@js.global "NGHTTP2_INTERNAL_ERROR"] val nGHTTP2_FLOW_CONTROL_ERROR: float [@@js.global "NGHTTP2_FLOW_CONTROL_ERROR"] val nGHTTP2_SETTINGS_TIMEOUT: float [@@js.global "NGHTTP2_SETTINGS_TIMEOUT"] val nGHTTP2_STREAM_CLOSED: float [@@js.global "NGHTTP2_STREAM_CLOSED"] val nGHTTP2_FRAME_SIZE_ERROR: float [@@js.global "NGHTTP2_FRAME_SIZE_ERROR"] val nGHTTP2_REFUSED_STREAM: float [@@js.global "NGHTTP2_REFUSED_STREAM"] val nGHTTP2_CANCEL: float [@@js.global "NGHTTP2_CANCEL"] val nGHTTP2_COMPRESSION_ERROR: float [@@js.global "NGHTTP2_COMPRESSION_ERROR"] val nGHTTP2_CONNECT_ERROR: float [@@js.global "NGHTTP2_CONNECT_ERROR"] val nGHTTP2_ENHANCE_YOUR_CALM: float [@@js.global "NGHTTP2_ENHANCE_YOUR_CALM"] val nGHTTP2_INADEQUATE_SECURITY: float [@@js.global "NGHTTP2_INADEQUATE_SECURITY"] val nGHTTP2_HTTP_1_1_REQUIRED: float [@@js.global "NGHTTP2_HTTP_1_1_REQUIRED"] val nGHTTP2_ERR_FRAME_SIZE_ERROR: float [@@js.global "NGHTTP2_ERR_FRAME_SIZE_ERROR"] val nGHTTP2_FLAG_NONE: float [@@js.global "NGHTTP2_FLAG_NONE"] val nGHTTP2_FLAG_END_STREAM: float [@@js.global "NGHTTP2_FLAG_END_STREAM"] val nGHTTP2_FLAG_END_HEADERS: float [@@js.global "NGHTTP2_FLAG_END_HEADERS"] val nGHTTP2_FLAG_ACK: float [@@js.global "NGHTTP2_FLAG_ACK"] val nGHTTP2_FLAG_PADDED: float [@@js.global "NGHTTP2_FLAG_PADDED"] val nGHTTP2_FLAG_PRIORITY: float [@@js.global "NGHTTP2_FLAG_PRIORITY"] val dEFAULT_SETTINGS_HEADER_TABLE_SIZE: float [@@js.global "DEFAULT_SETTINGS_HEADER_TABLE_SIZE"] val dEFAULT_SETTINGS_ENABLE_PUSH: float [@@js.global "DEFAULT_SETTINGS_ENABLE_PUSH"] val dEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: float [@@js.global "DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE"] val dEFAULT_SETTINGS_MAX_FRAME_SIZE: float [@@js.global "DEFAULT_SETTINGS_MAX_FRAME_SIZE"] val mAX_MAX_FRAME_SIZE: float [@@js.global "MAX_MAX_FRAME_SIZE"] val mIN_MAX_FRAME_SIZE: float [@@js.global "MIN_MAX_FRAME_SIZE"] val mAX_INITIAL_WINDOW_SIZE: float [@@js.global "MAX_INITIAL_WINDOW_SIZE"] val nGHTTP2_DEFAULT_WEIGHT: float [@@js.global "NGHTTP2_DEFAULT_WEIGHT"] val nGHTTP2_SETTINGS_HEADER_TABLE_SIZE: float [@@js.global "NGHTTP2_SETTINGS_HEADER_TABLE_SIZE"] val nGHTTP2_SETTINGS_ENABLE_PUSH: float [@@js.global "NGHTTP2_SETTINGS_ENABLE_PUSH"] val nGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: float [@@js.global "NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS"] val nGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: float [@@js.global "NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE"] val nGHTTP2_SETTINGS_MAX_FRAME_SIZE: float [@@js.global "NGHTTP2_SETTINGS_MAX_FRAME_SIZE"] val nGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: float [@@js.global "NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE"] val pADDING_STRATEGY_NONE: float [@@js.global "PADDING_STRATEGY_NONE"] val pADDING_STRATEGY_MAX: float [@@js.global "PADDING_STRATEGY_MAX"] val pADDING_STRATEGY_CALLBACK: float [@@js.global "PADDING_STRATEGY_CALLBACK"] val hTTP2_HEADER_STATUS: string [@@js.global "HTTP2_HEADER_STATUS"] val hTTP2_HEADER_METHOD: string [@@js.global "HTTP2_HEADER_METHOD"] val hTTP2_HEADER_AUTHORITY: string [@@js.global "HTTP2_HEADER_AUTHORITY"] val hTTP2_HEADER_SCHEME: string [@@js.global "HTTP2_HEADER_SCHEME"] val hTTP2_HEADER_PATH: string [@@js.global "HTTP2_HEADER_PATH"] val hTTP2_HEADER_ACCEPT_CHARSET: string [@@js.global "HTTP2_HEADER_ACCEPT_CHARSET"] val hTTP2_HEADER_ACCEPT_ENCODING: string [@@js.global "HTTP2_HEADER_ACCEPT_ENCODING"] val hTTP2_HEADER_ACCEPT_LANGUAGE: string [@@js.global "HTTP2_HEADER_ACCEPT_LANGUAGE"] val hTTP2_HEADER_ACCEPT_RANGES: string [@@js.global "HTTP2_HEADER_ACCEPT_RANGES"] val hTTP2_HEADER_ACCEPT: string [@@js.global "HTTP2_HEADER_ACCEPT"] val hTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string [@@js.global "HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN"] val hTTP2_HEADER_AGE: string [@@js.global "HTTP2_HEADER_AGE"] val hTTP2_HEADER_ALLOW: string [@@js.global "HTTP2_HEADER_ALLOW"] val hTTP2_HEADER_AUTHORIZATION: string [@@js.global "HTTP2_HEADER_AUTHORIZATION"] val hTTP2_HEADER_CACHE_CONTROL: string [@@js.global "HTTP2_HEADER_CACHE_CONTROL"] val hTTP2_HEADER_CONNECTION: string [@@js.global "HTTP2_HEADER_CONNECTION"] val hTTP2_HEADER_CONTENT_DISPOSITION: string [@@js.global "HTTP2_HEADER_CONTENT_DISPOSITION"] val hTTP2_HEADER_CONTENT_ENCODING: string [@@js.global "HTTP2_HEADER_CONTENT_ENCODING"] val hTTP2_HEADER_CONTENT_LANGUAGE: string [@@js.global "HTTP2_HEADER_CONTENT_LANGUAGE"] val hTTP2_HEADER_CONTENT_LENGTH: string [@@js.global "HTTP2_HEADER_CONTENT_LENGTH"] val hTTP2_HEADER_CONTENT_LOCATION: string [@@js.global "HTTP2_HEADER_CONTENT_LOCATION"] val hTTP2_HEADER_CONTENT_MD5: string [@@js.global "HTTP2_HEADER_CONTENT_MD5"] val hTTP2_HEADER_CONTENT_RANGE: string [@@js.global "HTTP2_HEADER_CONTENT_RANGE"] val hTTP2_HEADER_CONTENT_TYPE: string [@@js.global "HTTP2_HEADER_CONTENT_TYPE"] val hTTP2_HEADER_COOKIE: string [@@js.global "HTTP2_HEADER_COOKIE"] val hTTP2_HEADER_DATE: string [@@js.global "HTTP2_HEADER_DATE"] val hTTP2_HEADER_ETAG: string [@@js.global "HTTP2_HEADER_ETAG"] val hTTP2_HEADER_EXPECT: string [@@js.global "HTTP2_HEADER_EXPECT"] val hTTP2_HEADER_EXPIRES: string [@@js.global "HTTP2_HEADER_EXPIRES"] val hTTP2_HEADER_FROM: string [@@js.global "HTTP2_HEADER_FROM"] val hTTP2_HEADER_HOST: string [@@js.global "HTTP2_HEADER_HOST"] val hTTP2_HEADER_IF_MATCH: string [@@js.global "HTTP2_HEADER_IF_MATCH"] val hTTP2_HEADER_IF_MODIFIED_SINCE: string [@@js.global "HTTP2_HEADER_IF_MODIFIED_SINCE"] val hTTP2_HEADER_IF_NONE_MATCH: string [@@js.global "HTTP2_HEADER_IF_NONE_MATCH"] val hTTP2_HEADER_IF_RANGE: string [@@js.global "HTTP2_HEADER_IF_RANGE"] val hTTP2_HEADER_IF_UNMODIFIED_SINCE: string [@@js.global "HTTP2_HEADER_IF_UNMODIFIED_SINCE"] val hTTP2_HEADER_LAST_MODIFIED: string [@@js.global "HTTP2_HEADER_LAST_MODIFIED"] val hTTP2_HEADER_LINK: string [@@js.global "HTTP2_HEADER_LINK"] val hTTP2_HEADER_LOCATION: string [@@js.global "HTTP2_HEADER_LOCATION"] val hTTP2_HEADER_MAX_FORWARDS: string [@@js.global "HTTP2_HEADER_MAX_FORWARDS"] val hTTP2_HEADER_PREFER: string [@@js.global "HTTP2_HEADER_PREFER"] val hTTP2_HEADER_PROXY_AUTHENTICATE: string [@@js.global "HTTP2_HEADER_PROXY_AUTHENTICATE"] val hTTP2_HEADER_PROXY_AUTHORIZATION: string [@@js.global "HTTP2_HEADER_PROXY_AUTHORIZATION"] val hTTP2_HEADER_RANGE: string [@@js.global "HTTP2_HEADER_RANGE"] val hTTP2_HEADER_REFERER: string [@@js.global "HTTP2_HEADER_REFERER"] val hTTP2_HEADER_REFRESH: string [@@js.global "HTTP2_HEADER_REFRESH"] val hTTP2_HEADER_RETRY_AFTER: string [@@js.global "HTTP2_HEADER_RETRY_AFTER"] val hTTP2_HEADER_SERVER: string [@@js.global "HTTP2_HEADER_SERVER"] val hTTP2_HEADER_SET_COOKIE: string [@@js.global "HTTP2_HEADER_SET_COOKIE"] val hTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string [@@js.global "HTTP2_HEADER_STRICT_TRANSPORT_SECURITY"] val hTTP2_HEADER_TRANSFER_ENCODING: string [@@js.global "HTTP2_HEADER_TRANSFER_ENCODING"] val hTTP2_HEADER_TE: string [@@js.global "HTTP2_HEADER_TE"] val hTTP2_HEADER_UPGRADE: string [@@js.global "HTTP2_HEADER_UPGRADE"] val hTTP2_HEADER_USER_AGENT: string [@@js.global "HTTP2_HEADER_USER_AGENT"] val hTTP2_HEADER_VARY: string [@@js.global "HTTP2_HEADER_VARY"] val hTTP2_HEADER_VIA: string [@@js.global "HTTP2_HEADER_VIA"] val hTTP2_HEADER_WWW_AUTHENTICATE: string [@@js.global "HTTP2_HEADER_WWW_AUTHENTICATE"] val hTTP2_HEADER_HTTP2_SETTINGS: string [@@js.global "HTTP2_HEADER_HTTP2_SETTINGS"] val hTTP2_HEADER_KEEP_ALIVE: string [@@js.global "HTTP2_HEADER_KEEP_ALIVE"] val hTTP2_HEADER_PROXY_CONNECTION: string [@@js.global "HTTP2_HEADER_PROXY_CONNECTION"] val hTTP2_METHOD_ACL: string [@@js.global "HTTP2_METHOD_ACL"] val hTTP2_METHOD_BASELINE_CONTROL: string [@@js.global "HTTP2_METHOD_BASELINE_CONTROL"] val hTTP2_METHOD_BIND: string [@@js.global "HTTP2_METHOD_BIND"] val hTTP2_METHOD_CHECKIN: string [@@js.global "HTTP2_METHOD_CHECKIN"] val hTTP2_METHOD_CHECKOUT: string [@@js.global "HTTP2_METHOD_CHECKOUT"] val hTTP2_METHOD_CONNECT: string [@@js.global "HTTP2_METHOD_CONNECT"] val hTTP2_METHOD_COPY: string [@@js.global "HTTP2_METHOD_COPY"] val hTTP2_METHOD_DELETE: string [@@js.global "HTTP2_METHOD_DELETE"] val hTTP2_METHOD_GET: string [@@js.global "HTTP2_METHOD_GET"] val hTTP2_METHOD_HEAD: string [@@js.global "HTTP2_METHOD_HEAD"] val hTTP2_METHOD_LABEL: string [@@js.global "HTTP2_METHOD_LABEL"] val hTTP2_METHOD_LINK: string [@@js.global "HTTP2_METHOD_LINK"] val hTTP2_METHOD_LOCK: string [@@js.global "HTTP2_METHOD_LOCK"] val hTTP2_METHOD_MERGE: string [@@js.global "HTTP2_METHOD_MERGE"] val hTTP2_METHOD_MKACTIVITY: string [@@js.global "HTTP2_METHOD_MKACTIVITY"] val hTTP2_METHOD_MKCALENDAR: string [@@js.global "HTTP2_METHOD_MKCALENDAR"] val hTTP2_METHOD_MKCOL: string [@@js.global "HTTP2_METHOD_MKCOL"] val hTTP2_METHOD_MKREDIRECTREF: string [@@js.global "HTTP2_METHOD_MKREDIRECTREF"] val hTTP2_METHOD_MKWORKSPACE: string [@@js.global "HTTP2_METHOD_MKWORKSPACE"] val hTTP2_METHOD_MOVE: string [@@js.global "HTTP2_METHOD_MOVE"] val hTTP2_METHOD_OPTIONS: string [@@js.global "HTTP2_METHOD_OPTIONS"] val hTTP2_METHOD_ORDERPATCH: string [@@js.global "HTTP2_METHOD_ORDERPATCH"] val hTTP2_METHOD_PATCH: string [@@js.global "HTTP2_METHOD_PATCH"] val hTTP2_METHOD_POST: string [@@js.global "HTTP2_METHOD_POST"] val hTTP2_METHOD_PRI: string [@@js.global "HTTP2_METHOD_PRI"] val hTTP2_METHOD_PROPFIND: string [@@js.global "HTTP2_METHOD_PROPFIND"] val hTTP2_METHOD_PROPPATCH: string [@@js.global "HTTP2_METHOD_PROPPATCH"] val hTTP2_METHOD_PUT: string [@@js.global "HTTP2_METHOD_PUT"] val hTTP2_METHOD_REBIND: string [@@js.global "HTTP2_METHOD_REBIND"] val hTTP2_METHOD_REPORT: string [@@js.global "HTTP2_METHOD_REPORT"] val hTTP2_METHOD_SEARCH: string [@@js.global "HTTP2_METHOD_SEARCH"] val hTTP2_METHOD_TRACE: string [@@js.global "HTTP2_METHOD_TRACE"] val hTTP2_METHOD_UNBIND: string [@@js.global "HTTP2_METHOD_UNBIND"] val hTTP2_METHOD_UNCHECKOUT: string [@@js.global "HTTP2_METHOD_UNCHECKOUT"] val hTTP2_METHOD_UNLINK: string [@@js.global "HTTP2_METHOD_UNLINK"] val hTTP2_METHOD_UNLOCK: string [@@js.global "HTTP2_METHOD_UNLOCK"] val hTTP2_METHOD_UPDATE: string [@@js.global "HTTP2_METHOD_UPDATE"] val hTTP2_METHOD_UPDATEREDIRECTREF: string [@@js.global "HTTP2_METHOD_UPDATEREDIRECTREF"] val hTTP2_METHOD_VERSION_CONTROL: string [@@js.global "HTTP2_METHOD_VERSION_CONTROL"] val hTTP_STATUS_CONTINUE: float [@@js.global "HTTP_STATUS_CONTINUE"] val hTTP_STATUS_SWITCHING_PROTOCOLS: float [@@js.global "HTTP_STATUS_SWITCHING_PROTOCOLS"] val hTTP_STATUS_PROCESSING: float [@@js.global "HTTP_STATUS_PROCESSING"] val hTTP_STATUS_OK: float [@@js.global "HTTP_STATUS_OK"] val hTTP_STATUS_CREATED: float [@@js.global "HTTP_STATUS_CREATED"] val hTTP_STATUS_ACCEPTED: float [@@js.global "HTTP_STATUS_ACCEPTED"] val hTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: float [@@js.global "HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION"] val hTTP_STATUS_NO_CONTENT: float [@@js.global "HTTP_STATUS_NO_CONTENT"] val hTTP_STATUS_RESET_CONTENT: float [@@js.global "HTTP_STATUS_RESET_CONTENT"] val hTTP_STATUS_PARTIAL_CONTENT: float [@@js.global "HTTP_STATUS_PARTIAL_CONTENT"] val hTTP_STATUS_MULTI_STATUS: float [@@js.global "HTTP_STATUS_MULTI_STATUS"] val hTTP_STATUS_ALREADY_REPORTED: float [@@js.global "HTTP_STATUS_ALREADY_REPORTED"] val hTTP_STATUS_IM_USED: float [@@js.global "HTTP_STATUS_IM_USED"] val hTTP_STATUS_MULTIPLE_CHOICES: float [@@js.global "HTTP_STATUS_MULTIPLE_CHOICES"] val hTTP_STATUS_MOVED_PERMANENTLY: float [@@js.global "HTTP_STATUS_MOVED_PERMANENTLY"] val hTTP_STATUS_FOUND: float [@@js.global "HTTP_STATUS_FOUND"] val hTTP_STATUS_SEE_OTHER: float [@@js.global "HTTP_STATUS_SEE_OTHER"] val hTTP_STATUS_NOT_MODIFIED: float [@@js.global "HTTP_STATUS_NOT_MODIFIED"] val hTTP_STATUS_USE_PROXY: float [@@js.global "HTTP_STATUS_USE_PROXY"] val hTTP_STATUS_TEMPORARY_REDIRECT: float [@@js.global "HTTP_STATUS_TEMPORARY_REDIRECT"] val hTTP_STATUS_PERMANENT_REDIRECT: float [@@js.global "HTTP_STATUS_PERMANENT_REDIRECT"] val hTTP_STATUS_BAD_REQUEST: float [@@js.global "HTTP_STATUS_BAD_REQUEST"] val hTTP_STATUS_UNAUTHORIZED: float [@@js.global "HTTP_STATUS_UNAUTHORIZED"] val hTTP_STATUS_PAYMENT_REQUIRED: float [@@js.global "HTTP_STATUS_PAYMENT_REQUIRED"] val hTTP_STATUS_FORBIDDEN: float [@@js.global "HTTP_STATUS_FORBIDDEN"] val hTTP_STATUS_NOT_FOUND: float [@@js.global "HTTP_STATUS_NOT_FOUND"] val hTTP_STATUS_METHOD_NOT_ALLOWED: float [@@js.global "HTTP_STATUS_METHOD_NOT_ALLOWED"] val hTTP_STATUS_NOT_ACCEPTABLE: float [@@js.global "HTTP_STATUS_NOT_ACCEPTABLE"] val hTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: float [@@js.global "HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED"] val hTTP_STATUS_REQUEST_TIMEOUT: float [@@js.global "HTTP_STATUS_REQUEST_TIMEOUT"] val hTTP_STATUS_CONFLICT: float [@@js.global "HTTP_STATUS_CONFLICT"] val hTTP_STATUS_GONE: float [@@js.global "HTTP_STATUS_GONE"] val hTTP_STATUS_LENGTH_REQUIRED: float [@@js.global "HTTP_STATUS_LENGTH_REQUIRED"] val hTTP_STATUS_PRECONDITION_FAILED: float [@@js.global "HTTP_STATUS_PRECONDITION_FAILED"] val hTTP_STATUS_PAYLOAD_TOO_LARGE: float [@@js.global "HTTP_STATUS_PAYLOAD_TOO_LARGE"] val hTTP_STATUS_URI_TOO_LONG: float [@@js.global "HTTP_STATUS_URI_TOO_LONG"] val hTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: float [@@js.global "HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE"] val hTTP_STATUS_RANGE_NOT_SATISFIABLE: float [@@js.global "HTTP_STATUS_RANGE_NOT_SATISFIABLE"] val hTTP_STATUS_EXPECTATION_FAILED: float [@@js.global "HTTP_STATUS_EXPECTATION_FAILED"] val hTTP_STATUS_TEAPOT: float [@@js.global "HTTP_STATUS_TEAPOT"] val hTTP_STATUS_MISDIRECTED_REQUEST: float [@@js.global "HTTP_STATUS_MISDIRECTED_REQUEST"] val hTTP_STATUS_UNPROCESSABLE_ENTITY: float [@@js.global "HTTP_STATUS_UNPROCESSABLE_ENTITY"] val hTTP_STATUS_LOCKED: float [@@js.global "HTTP_STATUS_LOCKED"] val hTTP_STATUS_FAILED_DEPENDENCY: float [@@js.global "HTTP_STATUS_FAILED_DEPENDENCY"] val hTTP_STATUS_UNORDERED_COLLECTION: float [@@js.global "HTTP_STATUS_UNORDERED_COLLECTION"] val hTTP_STATUS_UPGRADE_REQUIRED: float [@@js.global "HTTP_STATUS_UPGRADE_REQUIRED"] val hTTP_STATUS_PRECONDITION_REQUIRED: float [@@js.global "HTTP_STATUS_PRECONDITION_REQUIRED"] val hTTP_STATUS_TOO_MANY_REQUESTS: float [@@js.global "HTTP_STATUS_TOO_MANY_REQUESTS"] val hTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: float [@@js.global "HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE"] val hTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: float [@@js.global "HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS"] val hTTP_STATUS_INTERNAL_SERVER_ERROR: float [@@js.global "HTTP_STATUS_INTERNAL_SERVER_ERROR"] val hTTP_STATUS_NOT_IMPLEMENTED: float [@@js.global "HTTP_STATUS_NOT_IMPLEMENTED"] val hTTP_STATUS_BAD_GATEWAY: float [@@js.global "HTTP_STATUS_BAD_GATEWAY"] val hTTP_STATUS_SERVICE_UNAVAILABLE: float [@@js.global "HTTP_STATUS_SERVICE_UNAVAILABLE"] val hTTP_STATUS_GATEWAY_TIMEOUT: float [@@js.global "HTTP_STATUS_GATEWAY_TIMEOUT"] val hTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: float [@@js.global "HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED"] val hTTP_STATUS_VARIANT_ALSO_NEGOTIATES: float [@@js.global "HTTP_STATUS_VARIANT_ALSO_NEGOTIATES"] val hTTP_STATUS_INSUFFICIENT_STORAGE: float [@@js.global "HTTP_STATUS_INSUFFICIENT_STORAGE"] val hTTP_STATUS_LOOP_DETECTED: float [@@js.global "HTTP_STATUS_LOOP_DETECTED"] val hTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: float [@@js.global "HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED"] val hTTP_STATUS_NOT_EXTENDED: float [@@js.global "HTTP_STATUS_NOT_EXTENDED"] val hTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: float [@@js.global "HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED"] end val getDefaultSettings: unit -> http2_Settings [@@js.global "getDefaultSettings"] val getPackedSettings: settings:http2_Settings -> Buffer.t_0 [@@js.global "getPackedSettings"] val getUnpackedSettings: buf:Uint8Array.t_0 -> http2_Settings [@@js.global "getUnpackedSettings"] val createServer: ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2Server [@@js.global "createServer"] val createServer: options:http2_ServerOptions -> ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2Server [@@js.global "createServer"] val createSecureServer: ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2SecureServer [@@js.global "createSecureServer"] val createSecureServer: options:http2_SecureServerOptions -> ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2SecureServer [@@js.global "createSecureServer"] val connect: authority:Url.URL.t_0 or_string -> listener:(session:http2_ClientHttp2Session -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> http2_ClientHttp2Session [@@js.global "connect"] val connect: authority:Url.URL.t_0 or_string -> ?options:([`U_s15_http_ of (http2_ClientSessionOptions, http2_SecureClientSessionOptions) union2 | `U_s16_https_ of (http2_ClientSessionOptions, http2_SecureClientSessionOptions) union2 ] [@js.union on_field "protocol"]) -> ?listener:(session:http2_ClientHttp2Session -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> unit -> http2_ClientHttp2Session [@@js.global "connect"] end end
null
https://raw.githubusercontent.com/tmattio/js-bindings/fe1d40a5b8cae157af85fa84ca482fb6b0ddf1e0/lib/node/_gen/http2.mli
ocaml
import * as fs from 'node:fs'; import * as net from 'node:net'; import * as stream from 'node:stream'; import * as tls from 'node:tls'; import * as url from 'node:url'; export { OutgoingHttpHeaders } from 'node:http'; FIXME: type 'Array<union<String | ?url.URL | {..}>>' cannot be used for variadic argument FIXME: unknown type 'typeof ServerResponse' FIXME: unknown type 'typeof ServerResponse' FIXME: unknown type 'typeof Http2ServerRequest' FIXME: unknown type 'typeof Http2ServerRequest' FIXME: unknown type 'typeof Http2ServerResponse' FIXME: unknown type 'typeof Http2ServerResponse'
[@@@ocaml.warning "-7-11-32-33-39"] [@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"] ] open Ts2ocaml_baselib unknown identifiers : - Buffer - BufferEncoding - Error - EventEmitter - Http1IncomingHttpHeaders - NodeJS.ArrayBufferView - NodeJS.ErrnoException - OutgoingHttpHeaders - Uint8Array - fs . Stats - fs.promises . - net . Server - net . Socket - stream . Duplex - stream . Readable - stream . ReadableOptions - stream . Writable - tls . ConnectionOptions - tls . Server - tls . TLSSocket - tls . TlsOptions - url . URL unknown identifiers: - Buffer - BufferEncoding - Error - EventEmitter - Http1IncomingHttpHeaders - NodeJS.ArrayBufferView - NodeJS.ErrnoException - OutgoingHttpHeaders - Uint8Array - fs.Stats - fs.promises.FileHandle - net.Server - net.Socket - stream.Duplex - stream.Readable - stream.ReadableOptions - stream.Writable - tls.ConnectionOptions - tls.Server - tls.TLSSocket - tls.TlsOptions - url.URL *) [@@@js.stop] module type Missing = sig module Buffer : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module BufferEncoding : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Error : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module EventEmitter : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Http1IncomingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module NodeJS : sig module ArrayBufferView : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ErrnoException : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module OutgoingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Uint8Array : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module fs : sig module Stats : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module promises : sig module FileHandle : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end module net : sig module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Socket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module stream : sig module Duplex : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Readable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ReadableOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Writable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module tls : sig module ConnectionOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TLSSocket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TlsOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module url : sig module URL : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end [@@@js.start] [@@@js.implem module type Missing = sig module Buffer : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module BufferEncoding : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Error : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module EventEmitter : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Http1IncomingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module NodeJS : sig module ArrayBufferView : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ErrnoException : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module OutgoingHttpHeaders : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Uint8Array : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module fs : sig module Stats : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module promises : sig module FileHandle : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end module net : sig module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Socket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module stream : sig module Duplex : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Readable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module ReadableOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Writable : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module tls : sig module ConnectionOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module Server : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TLSSocket : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module TlsOptions : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end module url : sig module URL : sig type t_0 val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end end end ] module Make (M: Missing) : sig open M module Internal : sig module AnonymousInterfaces : sig type anonymous_interface_0 = [`anonymous_interface_0] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] type anonymous_interface_1 = [`anonymous_interface_1] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] end module Types : sig open AnonymousInterfaces type http2_AlternativeServiceOptions = [`Http2_AlternativeServiceOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientHttp2Session = [`Http2_ClientHttp2Session | `Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientHttp2Stream = [`Http2_ClientHttp2Stream | `Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientSessionOptions = [`Http2_ClientSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ClientSessionRequestOptions = [`Http2_ClientSessionRequestOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2SecureServer = [`Http2_Http2SecureServer] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Server = [`Http2_Http2Server] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2ServerRequest = [`Http2_Http2ServerRequest] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2ServerResponse = [`Http2_Http2ServerResponse] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Session = [`Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Http2Stream = [`Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_IncomingHttpHeaders = [`Http2_IncomingHttpHeaders] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_IncomingHttpStatusHeader = [`Http2_IncomingHttpStatusHeader] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureClientSessionOptions = [`Http2_SecureClientSessionOptions | `Http2_ClientSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureServerOptions = [`Http2_SecureServerOptions | `Http2_SecureServerSessionOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SecureServerSessionOptions = [`Http2_SecureServerSessionOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerHttp2Session = [`Http2_ServerHttp2Session | `Http2_Http2Session] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerHttp2Stream = [`Http2_ServerHttp2Stream | `Http2_Http2Stream] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerOptions = [`Http2_ServerOptions | `Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerSessionOptions = [`Http2_ServerSessionOptions | `Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamFileResponseOptions = [`Http2_ServerStreamFileResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamFileResponseOptionsWithError = [`Http2_ServerStreamFileResponseOptionsWithError | `Http2_ServerStreamFileResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_ServerStreamResponseOptions = [`Http2_ServerStreamResponseOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SessionOptions = [`Http2_SessionOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_SessionState = [`Http2_SessionState] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_Settings = [`Http2_Settings] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StatOptions = [`Http2_StatOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StreamPriorityOptions = [`Http2_StreamPriorityOptions] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] and http2_StreamState = [`Http2_StreamState] intf [@@js.custom { of_js=Obj.magic; to_js=Obj.magic }] end end open Internal open AnonymousInterfaces open Types module AnonymousInterface0 : sig type t = anonymous_interface_0 val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 end module AnonymousInterface1 : sig type t = anonymous_interface_1 val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_origin: t -> string [@@js.get "origin"] val set_origin: t -> string -> unit [@@js.set "origin"] end module[@js.scope "node:http2"] Node_http2 : sig export * from ' ' ; end module[@js.scope "http2"] Http2 : sig import EventEmitter = require('node : events ' ) ; import { IncomingHttpHeaders as Http1IncomingHttpHeaders , OutgoingHttpHeaders , IncomingMessage , ServerResponse , } from ' node : http ' ; IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse, } from 'node:http'; *) module[@js.scope "IncomingHttpStatusHeader"] IncomingHttpStatusHeader : sig type t = http2_IncomingHttpStatusHeader val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get__status: t -> float [@@js.get ":status"] val set__status: t -> float -> unit [@@js.set ":status"] end module[@js.scope "IncomingHttpHeaders"] IncomingHttpHeaders : sig type t = http2_IncomingHttpHeaders val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get__path: t -> string [@@js.get ":path"] val set__path: t -> string -> unit [@@js.set ":path"] val get__method: t -> string [@@js.get ":method"] val set__method: t -> string -> unit [@@js.set ":method"] val get__authority: t -> string [@@js.get ":authority"] val set__authority: t -> string -> unit [@@js.set ":authority"] val get__scheme: t -> string [@@js.get ":scheme"] val set__scheme: t -> string -> unit [@@js.set ":scheme"] val cast: t -> Http1IncomingHttpHeaders.t_0 [@@js.cast] end module[@js.scope "StreamPriorityOptions"] StreamPriorityOptions : sig type t = http2_StreamPriorityOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_exclusive: t -> bool [@@js.get "exclusive"] val set_exclusive: t -> bool -> unit [@@js.set "exclusive"] val get_parent: t -> float [@@js.get "parent"] val set_parent: t -> float -> unit [@@js.set "parent"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] val get_silent: t -> bool [@@js.get "silent"] val set_silent: t -> bool -> unit [@@js.set "silent"] end module[@js.scope "StreamState"] StreamState : sig type t = http2_StreamState val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_localWindowSize: t -> float [@@js.get "localWindowSize"] val set_localWindowSize: t -> float -> unit [@@js.set "localWindowSize"] val get_state: t -> float [@@js.get "state"] val set_state: t -> float -> unit [@@js.set "state"] val get_localClose: t -> float [@@js.get "localClose"] val set_localClose: t -> float -> unit [@@js.set "localClose"] val get_remoteClose: t -> float [@@js.get "remoteClose"] val set_remoteClose: t -> float -> unit [@@js.set "remoteClose"] val get_sumDependencyWeight: t -> float [@@js.get "sumDependencyWeight"] val set_sumDependencyWeight: t -> float -> unit [@@js.set "sumDependencyWeight"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] end module[@js.scope "ServerStreamResponseOptions"] ServerStreamResponseOptions : sig type t = http2_ServerStreamResponseOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_endStream: t -> bool [@@js.get "endStream"] val set_endStream: t -> bool -> unit [@@js.set "endStream"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] end module[@js.scope "StatOptions"] StatOptions : sig type t = http2_StatOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_offset: t -> float [@@js.get "offset"] val set_offset: t -> float -> unit [@@js.set "offset"] val get_length: t -> float [@@js.get "length"] val set_length: t -> float -> unit [@@js.set "length"] end module[@js.scope "ServerStreamFileResponseOptions"] ServerStreamFileResponseOptions : sig type t = http2_ServerStreamFileResponseOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val statCheck: t -> stats:Fs.Stats.t_0 -> headers:OutgoingHttpHeaders.t_0 -> statOptions:http2_StatOptions -> unit or_boolean [@@js.call "statCheck"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] val get_offset: t -> float [@@js.get "offset"] val set_offset: t -> float -> unit [@@js.set "offset"] val get_length: t -> float [@@js.get "length"] val set_length: t -> float -> unit [@@js.set "length"] end module[@js.scope "ServerStreamFileResponseOptionsWithError"] ServerStreamFileResponseOptionsWithError : sig type t = http2_ServerStreamFileResponseOptionsWithError val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val onError: t -> err:NodeJS.ErrnoException.t_0 -> unit [@@js.call "onError"] val cast: t -> http2_ServerStreamFileResponseOptions [@@js.cast] end module[@js.scope "Http2Stream"] Http2Stream : sig type t = http2_Http2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_aborted: t -> bool [@@js.get "aborted"] val get_bufferSize: t -> float [@@js.get "bufferSize"] val get_closed: t -> bool [@@js.get "closed"] val get_destroyed: t -> bool [@@js.get "destroyed"] val get_endAfterHeaders: t -> bool [@@js.get "endAfterHeaders"] val get_id: t -> float [@@js.get "id"] val get_pending: t -> bool [@@js.get "pending"] val get_rstCode: t -> float [@@js.get "rstCode"] val get_sentHeaders: t -> OutgoingHttpHeaders.t_0 [@@js.get "sentHeaders"] val get_sentInfoHeaders: t -> OutgoingHttpHeaders.t_0 list [@@js.get "sentInfoHeaders"] val get_sentTrailers: t -> OutgoingHttpHeaders.t_0 [@@js.get "sentTrailers"] val get_session: t -> http2_Http2Session [@@js.get "session"] val get_state: t -> http2_StreamState [@@js.get "state"] val close: t -> ?code:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "close"] val priority: t -> options:http2_StreamPriorityOptions -> unit [@@js.call "priority"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val sendTrailers: t -> headers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "sendTrailers"] val addListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "addListener"] val addListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "addListener"] val addListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s1_aborted] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s7_data] [@js.enum]) -> chunk:Buffer.t_0 or_string -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s8_drain] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s9_end] [@js.enum]) -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s11_finish] [@js.enum]) -> bool [@@js.call "emit"] val emit''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> frameType:float -> errorCode:float -> bool [@@js.call "emit"] val emit'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> code:float -> bool [@@js.call "emit"] val emit''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> trailers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "on"] val on'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "on"] val on''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "once"] val once'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "once"] val once''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''': t -> event:([`L_s29_streamClosed] [@js.enum]) -> listener:(code:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''''': t -> event:([`L_s31_trailers] [@js.enum]) -> listener:(trailers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''''''''': t -> event:([`L_s34_wantTrailers] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Duplex.t_0 [@@js.cast] end module[@js.scope "ClientHttp2Stream"] ClientHttp2Stream : sig type t = http2_ClientHttp2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s6_continue] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s14_headers] [@js.enum]) -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s21_push] [@js.enum]) -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s25_response] [@js.enum]) -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "on"] val on': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "once"] val once': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s6_continue] [@js.enum]) -> listener:(unit -> anonymous_interface_0) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s14_headers] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s21_push] [@js.enum]) -> listener:(headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s25_response] [@js.enum]) -> listener:(headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Stream [@@js.cast] end module[@js.scope "ServerHttp2Stream"] ServerHttp2Stream : sig type t = http2_ServerHttp2Stream val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_headersSent: t -> bool [@@js.get "headersSent"] val get_pushAllowed: t -> bool [@@js.get "pushAllowed"] val additionalHeaders: t -> headers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "additionalHeaders"] val pushStream: t -> headers:OutgoingHttpHeaders.t_0 -> ?callback:(err:Error.t_0 or_null -> pushStream:t -> headers:OutgoingHttpHeaders.t_0 -> unit) -> unit -> unit [@@js.call "pushStream"] val pushStream': t -> headers:OutgoingHttpHeaders.t_0 -> ?options:http2_StreamPriorityOptions -> ?callback:(err:Error.t_0 or_null -> pushStream:t -> headers:OutgoingHttpHeaders.t_0 -> unit) -> unit -> unit [@@js.call "pushStream"] val respond: t -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamResponseOptions -> unit -> unit [@@js.call "respond"] val respondWithFD: t -> fd:Fs.Promises.FileHandle.t_0 or_number -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamFileResponseOptions -> unit -> unit [@@js.call "respondWithFD"] val respondWithFile: t -> path:string -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ServerStreamFileResponseOptionsWithError -> unit -> unit [@@js.call "respondWithFile"] val cast: t -> http2_Http2Stream [@@js.cast] end module[@js.scope "Settings"] Settings : sig type t = http2_Settings val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_headerTableSize: t -> float [@@js.get "headerTableSize"] val set_headerTableSize: t -> float -> unit [@@js.set "headerTableSize"] val get_enablePush: t -> bool [@@js.get "enablePush"] val set_enablePush: t -> bool -> unit [@@js.set "enablePush"] val get_initialWindowSize: t -> float [@@js.get "initialWindowSize"] val set_initialWindowSize: t -> float -> unit [@@js.set "initialWindowSize"] val get_maxFrameSize: t -> float [@@js.get "maxFrameSize"] val set_maxFrameSize: t -> float -> unit [@@js.set "maxFrameSize"] val get_maxConcurrentStreams: t -> float [@@js.get "maxConcurrentStreams"] val set_maxConcurrentStreams: t -> float -> unit [@@js.set "maxConcurrentStreams"] val get_maxHeaderListSize: t -> float [@@js.get "maxHeaderListSize"] val set_maxHeaderListSize: t -> float -> unit [@@js.set "maxHeaderListSize"] val get_enableConnectProtocol: t -> bool [@@js.get "enableConnectProtocol"] val set_enableConnectProtocol: t -> bool -> unit [@@js.set "enableConnectProtocol"] end module[@js.scope "ClientSessionRequestOptions"] ClientSessionRequestOptions : sig type t = http2_ClientSessionRequestOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_endStream: t -> bool [@@js.get "endStream"] val set_endStream: t -> bool -> unit [@@js.set "endStream"] val get_exclusive: t -> bool [@@js.get "exclusive"] val set_exclusive: t -> bool -> unit [@@js.set "exclusive"] val get_parent: t -> float [@@js.get "parent"] val set_parent: t -> float -> unit [@@js.set "parent"] val get_weight: t -> float [@@js.get "weight"] val set_weight: t -> float -> unit [@@js.set "weight"] val get_waitForTrailers: t -> bool [@@js.get "waitForTrailers"] val set_waitForTrailers: t -> bool -> unit [@@js.set "waitForTrailers"] end module[@js.scope "SessionState"] SessionState : sig type t = http2_SessionState val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_effectiveLocalWindowSize: t -> float [@@js.get "effectiveLocalWindowSize"] val set_effectiveLocalWindowSize: t -> float -> unit [@@js.set "effectiveLocalWindowSize"] val get_effectiveRecvDataLength: t -> float [@@js.get "effectiveRecvDataLength"] val set_effectiveRecvDataLength: t -> float -> unit [@@js.set "effectiveRecvDataLength"] val get_nextStreamID: t -> float [@@js.get "nextStreamID"] val set_nextStreamID: t -> float -> unit [@@js.set "nextStreamID"] val get_localWindowSize: t -> float [@@js.get "localWindowSize"] val set_localWindowSize: t -> float -> unit [@@js.set "localWindowSize"] val get_lastProcStreamID: t -> float [@@js.get "lastProcStreamID"] val set_lastProcStreamID: t -> float -> unit [@@js.set "lastProcStreamID"] val get_remoteWindowSize: t -> float [@@js.get "remoteWindowSize"] val set_remoteWindowSize: t -> float -> unit [@@js.set "remoteWindowSize"] val get_outboundQueueSize: t -> float [@@js.get "outboundQueueSize"] val set_outboundQueueSize: t -> float -> unit [@@js.set "outboundQueueSize"] val get_deflateDynamicTableSize: t -> float [@@js.get "deflateDynamicTableSize"] val set_deflateDynamicTableSize: t -> float -> unit [@@js.set "deflateDynamicTableSize"] val get_inflateDynamicTableSize: t -> float [@@js.get "inflateDynamicTableSize"] val set_inflateDynamicTableSize: t -> float -> unit [@@js.set "inflateDynamicTableSize"] end module[@js.scope "Http2Session"] Http2Session : sig type t = http2_Http2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_alpnProtocol: t -> string [@@js.get "alpnProtocol"] val get_closed: t -> bool [@@js.get "closed"] val get_connecting: t -> bool [@@js.get "connecting"] val get_destroyed: t -> bool [@@js.get "destroyed"] val get_encrypted: t -> bool [@@js.get "encrypted"] val get_localSettings: t -> http2_Settings [@@js.get "localSettings"] val get_originSet: t -> string list [@@js.get "originSet"] val get_pendingSettingsAck: t -> bool [@@js.get "pendingSettingsAck"] val get_remoteSettings: t -> http2_Settings [@@js.get "remoteSettings"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_state: t -> http2_SessionState [@@js.get "state"] val get_type: t -> float [@@js.get "type"] val close: t -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "close"] val destroy: t -> ?error:Error.t_0 -> ?code:float -> unit -> unit [@@js.call "destroy"] val goaway: t -> ?code:float -> ?lastStreamID:float -> ?opaqueData:NodeJS.ArrayBufferView.t_0 -> unit -> unit [@@js.call "goaway"] val ping: t -> callback:(err:Error.t_0 or_null -> duration:float -> payload:Buffer.t_0 -> unit) -> bool [@@js.call "ping"] val ping': t -> payload:NodeJS.ArrayBufferView.t_0 -> callback:(err:Error.t_0 or_null -> duration:float -> payload:Buffer.t_0 -> unit) -> bool [@@js.call "ping"] val ref: t -> unit [@@js.call "ref"] val setLocalWindowSize: t -> windowSize:float -> unit [@@js.call "setLocalWindowSize"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val settings: t -> settings:http2_Settings -> unit [@@js.call "settings"] val unref: t -> unit [@@js.call "unref"] val addListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s12_frameError] [@js.enum]) -> frameType:float -> errorCode:float -> streamID:float -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s13_goaway] [@js.enum]) -> errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> settings:http2_Settings -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s19_ping] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> settings:http2_Settings -> bool [@@js.call "emit"] val emit''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "on"] val on''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "once"] val once''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s12_frameError] [@js.enum]) -> listener:(frameType:float -> errorCode:float -> streamID:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s13_goaway] [@js.enum]) -> listener:(errorCode:float -> lastStreamID:float -> opaqueData:Buffer.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s17_localSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s19_ping] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s23_remoteSettings] [@js.enum]) -> listener:(settings:http2_Settings -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> EventEmitter.t_0 [@@js.cast] end module[@js.scope "ClientHttp2Session"] ClientHttp2Session : sig type t = http2_ClientHttp2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val request: t -> ?headers:OutgoingHttpHeaders.t_0 -> ?options:http2_ClientSessionRequestOptions -> unit -> http2_ClientHttp2Stream [@@js.call "request"] val addListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s2_altsvc] [@js.enum]) -> alt:string -> origin:string -> stream:float -> bool [@@js.call "emit"] val emit': t -> event:([`L_s18_origin] [@js.enum]) -> origins:string list -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s5_connect] [@js.enum]) -> session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> bool [@@js.call "emit"] val emit'''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "on"] val on'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "once"] val once'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s2_altsvc] [@js.enum]) -> listener:(alt:string -> origin:string -> stream:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s18_origin] [@js.enum]) -> listener:(origins:string list -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ClientHttp2Stream -> headers:(http2_IncomingHttpHeaders, http2_IncomingHttpStatusHeader) intersection2 -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Session [@@js.cast] end module[@js.scope "AlternativeServiceOptions"] AlternativeServiceOptions : sig type t = http2_AlternativeServiceOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_origin: t -> Url.URL.t_0 or_string or_number [@@js.get "origin"] val set_origin: t -> Url.URL.t_0 or_string or_number -> unit [@@js.set "origin"] end module[@js.scope "ServerHttp2Session"] ServerHttp2Session : sig type t = http2_ServerHttp2Session val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_server: t -> (http2_Http2SecureServer, http2_Http2Server) union2 [@@js.get "server"] val altsvc: t -> alt:string -> originOrStream:(http2_AlternativeServiceOptions, Url.URL.t_0) union2 or_string or_number -> unit [@@js.call "altsvc"] val addListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s5_connect] [@js.enum]) -> session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> bool [@@js.call "emit"] val emit': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit'': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s5_connect] [@js.enum]) -> listener:(session:t -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> http2_Http2Session [@@js.cast] end module[@js.scope "SessionOptions"] SessionOptions : sig type t = http2_SessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_maxDeflateDynamicTableSize: t -> float [@@js.get "maxDeflateDynamicTableSize"] val set_maxDeflateDynamicTableSize: t -> float -> unit [@@js.set "maxDeflateDynamicTableSize"] val get_maxSessionMemory: t -> float [@@js.get "maxSessionMemory"] val set_maxSessionMemory: t -> float -> unit [@@js.set "maxSessionMemory"] val get_maxHeaderListPairs: t -> float [@@js.get "maxHeaderListPairs"] val set_maxHeaderListPairs: t -> float -> unit [@@js.set "maxHeaderListPairs"] val get_maxOutstandingPings: t -> float [@@js.get "maxOutstandingPings"] val set_maxOutstandingPings: t -> float -> unit [@@js.set "maxOutstandingPings"] val get_maxSendHeaderBlockLength: t -> float [@@js.get "maxSendHeaderBlockLength"] val set_maxSendHeaderBlockLength: t -> float -> unit [@@js.set "maxSendHeaderBlockLength"] val get_paddingStrategy: t -> float [@@js.get "paddingStrategy"] val set_paddingStrategy: t -> float -> unit [@@js.set "paddingStrategy"] val get_peerMaxConcurrentStreams: t -> float [@@js.get "peerMaxConcurrentStreams"] val set_peerMaxConcurrentStreams: t -> float -> unit [@@js.set "peerMaxConcurrentStreams"] val get_settings: t -> http2_Settings [@@js.get "settings"] val set_settings: t -> http2_Settings -> unit [@@js.set "settings"] val selectPadding: t -> frameLen:float -> maxFrameLen:float -> float [@@js.call "selectPadding"] val createConnection: t -> authority:Url.URL.t_0 -> option:t -> Stream.Duplex.t_0 [@@js.call "createConnection"] end module[@js.scope "ClientSessionOptions"] ClientSessionOptions : sig type t = http2_ClientSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_maxReservedRemoteStreams: t -> float [@@js.get "maxReservedRemoteStreams"] val set_maxReservedRemoteStreams: t -> float -> unit [@@js.set "maxReservedRemoteStreams"] val createConnection: t -> authority:Url.URL.t_0 -> option:http2_SessionOptions -> Stream.Duplex.t_0 [@@js.call "createConnection"] val get_protocol: t -> ([`L_s15_http_[@js "http:"] | `L_s16_https_[@js "https:"]] [@js.enum]) [@@js.get "protocol"] val set_protocol: t -> ([`L_s15_http_ | `L_s16_https_] [@js.enum]) -> unit [@@js.set "protocol"] val cast: t -> http2_SessionOptions [@@js.cast] end module[@js.scope "ServerSessionOptions"] ServerSessionOptions : sig type t = http2_ServerSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 FIXME : unknown type ' typeof IncomingMessage ' FIXME : unknown type ' typeof IncomingMessage ' val cast: t -> http2_SessionOptions [@@js.cast] end module[@js.scope "SecureClientSessionOptions"] SecureClientSessionOptions : sig type t = http2_SecureClientSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ClientSessionOptions [@@js.cast] val cast': t -> Tls.ConnectionOptions.t_0 [@@js.cast] end module[@js.scope "SecureServerSessionOptions"] SecureServerSessionOptions : sig type t = http2_SecureServerSessionOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ServerSessionOptions [@@js.cast] val cast': t -> Tls.TlsOptions.t_0 [@@js.cast] end module[@js.scope "ServerOptions"] ServerOptions : sig type t = http2_ServerOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val cast: t -> http2_ServerSessionOptions [@@js.cast] end module[@js.scope "SecureServerOptions"] SecureServerOptions : sig type t = http2_SecureServerOptions val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val get_allowHTTP1: t -> bool [@@js.get "allowHTTP1"] val set_allowHTTP1: t -> bool -> unit [@@js.set "allowHTTP1"] val get_origins: t -> string list [@@js.get "origins"] val set_origins: t -> string list -> unit [@@js.set "origins"] val cast: t -> http2_SecureServerSessionOptions [@@js.cast] end module[@js.scope "Http2Server"] Http2Server : sig type t = http2_Http2Server val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s3_checkContinue] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit': t -> event:([`L_s24_request] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s26_session] [@js.enum]) -> session:http2_ServerHttp2Session -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s27_sessionError] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val setTimeout: t -> ?msec:float -> ?callback:(unit -> unit) -> unit -> t [@@js.call "setTimeout"] val cast: t -> Net.Server.t_0 [@@js.cast] end module[@js.scope "Http2SecureServer"] Http2SecureServer : sig type t = http2_Http2SecureServer val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val addListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s3_checkContinue] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit': t -> event:([`L_s24_request] [@js.enum]) -> request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s26_session] [@js.enum]) -> session:http2_ServerHttp2Session -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s27_sessionError] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s28_stream] [@js.enum]) -> stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s30_timeout] [@js.enum]) -> bool [@@js.call "emit"] val emit'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> socket:Tls.TLSSocket.t_0 -> bool [@@js.call "emit"] val emit''''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "on"] val on''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "once"] val once''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s3_checkContinue] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s24_request] [@js.enum]) -> listener:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s26_session] [@js.enum]) -> listener:(session:http2_ServerHttp2Session -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s27_sessionError] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s28_stream] [@js.enum]) -> listener:(stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> flags:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s30_timeout] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:([`L_s32_unknownProtocol] [@js.enum]) -> listener:(socket:Tls.TLSSocket.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val setTimeout: t -> ?msec:float -> ?callback:(unit -> unit) -> unit -> t [@@js.call "setTimeout"] val cast: t -> Tls.Server.t_0 [@@js.cast] end module[@js.scope "Http2ServerRequest"] Http2ServerRequest : sig type t = http2_Http2ServerRequest val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val create: stream:http2_ServerHttp2Stream -> headers:http2_IncomingHttpHeaders -> options:Stream.ReadableOptions.t_0 -> rawHeaders:string list -> t [@@js.create] val get_aborted: t -> bool [@@js.get "aborted"] val get_authority: t -> string [@@js.get "authority"] val get_connection: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "connection"] val get_complete: t -> bool [@@js.get "complete"] val get_headers: t -> http2_IncomingHttpHeaders [@@js.get "headers"] val get_httpVersion: t -> string [@@js.get "httpVersion"] val get_httpVersionMinor: t -> float [@@js.get "httpVersionMinor"] val get_httpVersionMajor: t -> float [@@js.get "httpVersionMajor"] val get_method: t -> string [@@js.get "method"] val get_rawHeaders: t -> string list [@@js.get "rawHeaders"] val get_rawTrailers: t -> string list [@@js.get "rawTrailers"] val get_scheme: t -> string [@@js.get "scheme"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_stream: t -> http2_ServerHttp2Stream [@@js.get "stream"] val get_trailers: t -> http2_IncomingHttpHeaders [@@js.get "trailers"] val get_url: t -> string [@@js.get "url"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val read: t -> ?size:float -> unit -> Buffer.t_0 or_string or_null [@@js.call "read"] val addListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s1_aborted] [@js.enum]) -> hadError:bool -> code:float -> bool [@@js.call "emit"] val emit': t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s7_data] [@js.enum]) -> chunk:Buffer.t_0 or_string -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s9_end] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s22_readable] [@js.enum]) -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s10_error] [@js.enum]) -> err:Error.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s1_aborted] [@js.enum]) -> listener:(hadError:bool -> code:float -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s7_data] [@js.enum]) -> listener:(chunk:Buffer.t_0 or_string -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s9_end] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s22_readable] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s10_error] [@js.enum]) -> listener:(err:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Readable.t_0 [@@js.cast] end module[@js.scope "Http2ServerResponse"] Http2ServerResponse : sig type t = http2_Http2ServerResponse val t_to_js: t -> Ojs.t val t_of_js: Ojs.t -> t type t_0 = t val t_0_to_js: t_0 -> Ojs.t val t_0_of_js: Ojs.t -> t_0 val create: stream:http2_ServerHttp2Stream -> t [@@js.create] val get_connection: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "connection"] val get_finished: t -> bool [@@js.get "finished"] val get_headersSent: t -> bool [@@js.get "headersSent"] val get_socket: t -> (Net.Socket.t_0, Tls.TLSSocket.t_0) union2 [@@js.get "socket"] val get_stream: t -> http2_ServerHttp2Stream [@@js.get "stream"] val get_sendDate: t -> bool [@@js.get "sendDate"] val set_sendDate: t -> bool -> unit [@@js.set "sendDate"] val get_statusCode: t -> float [@@js.get "statusCode"] val set_statusCode: t -> float -> unit [@@js.set "statusCode"] val get_statusMessage: t -> ([`L_s0[@js ""]] [@js.enum]) [@@js.get "statusMessage"] val set_statusMessage: t -> ([`L_s0] [@js.enum]) -> unit [@@js.set "statusMessage"] val addTrailers: t -> trailers:OutgoingHttpHeaders.t_0 -> unit [@@js.call "addTrailers"] val end_: t -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val end_': t -> data:Uint8Array.t_0 or_string -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val end_'': t -> data:Uint8Array.t_0 or_string -> encoding:BufferEncoding.t_0 -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "end"] val getHeader: t -> name:string -> string [@@js.call "getHeader"] val getHeaderNames: t -> string list [@@js.call "getHeaderNames"] val getHeaders: t -> OutgoingHttpHeaders.t_0 [@@js.call "getHeaders"] val hasHeader: t -> name:string -> bool [@@js.call "hasHeader"] val removeHeader: t -> name:string -> unit [@@js.call "removeHeader"] val setHeader: t -> name:string -> value:string list or_string or_number -> unit [@@js.call "setHeader"] val setTimeout: t -> msecs:float -> ?callback:(unit -> unit) -> unit -> unit [@@js.call "setTimeout"] val write: t -> chunk:Uint8Array.t_0 or_string -> ?callback:(err:Error.t_0 -> unit) -> unit -> bool [@@js.call "write"] val write': t -> chunk:Uint8Array.t_0 or_string -> encoding:BufferEncoding.t_0 -> ?callback:(err:Error.t_0 -> unit) -> unit -> bool [@@js.call "write"] val writeContinue: t -> unit [@@js.call "writeContinue"] val writeHead: t -> statusCode:float -> ?headers:OutgoingHttpHeaders.t_0 -> unit -> t [@@js.call "writeHead"] val writeHead': t -> statusCode:float -> statusMessage:string -> ?headers:OutgoingHttpHeaders.t_0 -> unit -> t [@@js.call "writeHead"] val createPushResponse: t -> headers:OutgoingHttpHeaders.t_0 -> callback:(err:Error.t_0 or_null -> res:t -> unit) -> unit [@@js.call "createPushResponse"] val addListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "addListener"] val addListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "addListener"] val addListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "addListener"] val emit: t -> event:([`L_s4_close] [@js.enum]) -> bool [@@js.call "emit"] val emit': t -> event:([`L_s8_drain] [@js.enum]) -> bool [@@js.call "emit"] val emit'': t -> event:([`L_s10_error] [@js.enum]) -> error:Error.t_0 -> bool [@@js.call "emit"] val emit''': t -> event:([`L_s11_finish] [@js.enum]) -> bool [@@js.call "emit"] val emit'''': t -> event:([`L_s20_pipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> src:Stream.Readable.t_0 -> bool [@@js.call "emit"] val emit'''''': t -> event:symbol or_string -> args:(any list [@js.variadic]) -> bool [@@js.call "emit"] val on: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "on"] val on''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "on"] val on'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "on"] val on'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "on"] val once: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "once"] val once''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "once"] val once'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "once"] val once'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "once"] val prependListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependListener"] val prependListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependListener"] val prependListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependListener"] val prependOnceListener: t -> event:([`L_s4_close] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener': t -> event:([`L_s8_drain] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'': t -> event:([`L_s10_error] [@js.enum]) -> listener:(error:Error.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''': t -> event:([`L_s11_finish] [@js.enum]) -> listener:(unit -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''': t -> event:([`L_s20_pipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener''''': t -> event:([`L_s33_unpipe] [@js.enum]) -> listener:(src:Stream.Readable.t_0 -> unit) -> t [@@js.call "prependOnceListener"] val prependOnceListener'''''': t -> event:symbol or_string -> listener:(args:(any list [@js.variadic]) -> unit) -> t [@@js.call "prependOnceListener"] val cast: t -> Stream.Writable.t_0 [@@js.cast] end module[@js.scope "constants"] Constants : sig val nGHTTP2_SESSION_SERVER: float [@@js.global "NGHTTP2_SESSION_SERVER"] val nGHTTP2_SESSION_CLIENT: float [@@js.global "NGHTTP2_SESSION_CLIENT"] val nGHTTP2_STREAM_STATE_IDLE: float [@@js.global "NGHTTP2_STREAM_STATE_IDLE"] val nGHTTP2_STREAM_STATE_OPEN: float [@@js.global "NGHTTP2_STREAM_STATE_OPEN"] val nGHTTP2_STREAM_STATE_RESERVED_LOCAL: float [@@js.global "NGHTTP2_STREAM_STATE_RESERVED_LOCAL"] val nGHTTP2_STREAM_STATE_RESERVED_REMOTE: float [@@js.global "NGHTTP2_STREAM_STATE_RESERVED_REMOTE"] val nGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: float [@@js.global "NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL"] val nGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: float [@@js.global "NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE"] val nGHTTP2_STREAM_STATE_CLOSED: float [@@js.global "NGHTTP2_STREAM_STATE_CLOSED"] val nGHTTP2_NO_ERROR: float [@@js.global "NGHTTP2_NO_ERROR"] val nGHTTP2_PROTOCOL_ERROR: float [@@js.global "NGHTTP2_PROTOCOL_ERROR"] val nGHTTP2_INTERNAL_ERROR: float [@@js.global "NGHTTP2_INTERNAL_ERROR"] val nGHTTP2_FLOW_CONTROL_ERROR: float [@@js.global "NGHTTP2_FLOW_CONTROL_ERROR"] val nGHTTP2_SETTINGS_TIMEOUT: float [@@js.global "NGHTTP2_SETTINGS_TIMEOUT"] val nGHTTP2_STREAM_CLOSED: float [@@js.global "NGHTTP2_STREAM_CLOSED"] val nGHTTP2_FRAME_SIZE_ERROR: float [@@js.global "NGHTTP2_FRAME_SIZE_ERROR"] val nGHTTP2_REFUSED_STREAM: float [@@js.global "NGHTTP2_REFUSED_STREAM"] val nGHTTP2_CANCEL: float [@@js.global "NGHTTP2_CANCEL"] val nGHTTP2_COMPRESSION_ERROR: float [@@js.global "NGHTTP2_COMPRESSION_ERROR"] val nGHTTP2_CONNECT_ERROR: float [@@js.global "NGHTTP2_CONNECT_ERROR"] val nGHTTP2_ENHANCE_YOUR_CALM: float [@@js.global "NGHTTP2_ENHANCE_YOUR_CALM"] val nGHTTP2_INADEQUATE_SECURITY: float [@@js.global "NGHTTP2_INADEQUATE_SECURITY"] val nGHTTP2_HTTP_1_1_REQUIRED: float [@@js.global "NGHTTP2_HTTP_1_1_REQUIRED"] val nGHTTP2_ERR_FRAME_SIZE_ERROR: float [@@js.global "NGHTTP2_ERR_FRAME_SIZE_ERROR"] val nGHTTP2_FLAG_NONE: float [@@js.global "NGHTTP2_FLAG_NONE"] val nGHTTP2_FLAG_END_STREAM: float [@@js.global "NGHTTP2_FLAG_END_STREAM"] val nGHTTP2_FLAG_END_HEADERS: float [@@js.global "NGHTTP2_FLAG_END_HEADERS"] val nGHTTP2_FLAG_ACK: float [@@js.global "NGHTTP2_FLAG_ACK"] val nGHTTP2_FLAG_PADDED: float [@@js.global "NGHTTP2_FLAG_PADDED"] val nGHTTP2_FLAG_PRIORITY: float [@@js.global "NGHTTP2_FLAG_PRIORITY"] val dEFAULT_SETTINGS_HEADER_TABLE_SIZE: float [@@js.global "DEFAULT_SETTINGS_HEADER_TABLE_SIZE"] val dEFAULT_SETTINGS_ENABLE_PUSH: float [@@js.global "DEFAULT_SETTINGS_ENABLE_PUSH"] val dEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: float [@@js.global "DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE"] val dEFAULT_SETTINGS_MAX_FRAME_SIZE: float [@@js.global "DEFAULT_SETTINGS_MAX_FRAME_SIZE"] val mAX_MAX_FRAME_SIZE: float [@@js.global "MAX_MAX_FRAME_SIZE"] val mIN_MAX_FRAME_SIZE: float [@@js.global "MIN_MAX_FRAME_SIZE"] val mAX_INITIAL_WINDOW_SIZE: float [@@js.global "MAX_INITIAL_WINDOW_SIZE"] val nGHTTP2_DEFAULT_WEIGHT: float [@@js.global "NGHTTP2_DEFAULT_WEIGHT"] val nGHTTP2_SETTINGS_HEADER_TABLE_SIZE: float [@@js.global "NGHTTP2_SETTINGS_HEADER_TABLE_SIZE"] val nGHTTP2_SETTINGS_ENABLE_PUSH: float [@@js.global "NGHTTP2_SETTINGS_ENABLE_PUSH"] val nGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: float [@@js.global "NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS"] val nGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: float [@@js.global "NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE"] val nGHTTP2_SETTINGS_MAX_FRAME_SIZE: float [@@js.global "NGHTTP2_SETTINGS_MAX_FRAME_SIZE"] val nGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: float [@@js.global "NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE"] val pADDING_STRATEGY_NONE: float [@@js.global "PADDING_STRATEGY_NONE"] val pADDING_STRATEGY_MAX: float [@@js.global "PADDING_STRATEGY_MAX"] val pADDING_STRATEGY_CALLBACK: float [@@js.global "PADDING_STRATEGY_CALLBACK"] val hTTP2_HEADER_STATUS: string [@@js.global "HTTP2_HEADER_STATUS"] val hTTP2_HEADER_METHOD: string [@@js.global "HTTP2_HEADER_METHOD"] val hTTP2_HEADER_AUTHORITY: string [@@js.global "HTTP2_HEADER_AUTHORITY"] val hTTP2_HEADER_SCHEME: string [@@js.global "HTTP2_HEADER_SCHEME"] val hTTP2_HEADER_PATH: string [@@js.global "HTTP2_HEADER_PATH"] val hTTP2_HEADER_ACCEPT_CHARSET: string [@@js.global "HTTP2_HEADER_ACCEPT_CHARSET"] val hTTP2_HEADER_ACCEPT_ENCODING: string [@@js.global "HTTP2_HEADER_ACCEPT_ENCODING"] val hTTP2_HEADER_ACCEPT_LANGUAGE: string [@@js.global "HTTP2_HEADER_ACCEPT_LANGUAGE"] val hTTP2_HEADER_ACCEPT_RANGES: string [@@js.global "HTTP2_HEADER_ACCEPT_RANGES"] val hTTP2_HEADER_ACCEPT: string [@@js.global "HTTP2_HEADER_ACCEPT"] val hTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string [@@js.global "HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN"] val hTTP2_HEADER_AGE: string [@@js.global "HTTP2_HEADER_AGE"] val hTTP2_HEADER_ALLOW: string [@@js.global "HTTP2_HEADER_ALLOW"] val hTTP2_HEADER_AUTHORIZATION: string [@@js.global "HTTP2_HEADER_AUTHORIZATION"] val hTTP2_HEADER_CACHE_CONTROL: string [@@js.global "HTTP2_HEADER_CACHE_CONTROL"] val hTTP2_HEADER_CONNECTION: string [@@js.global "HTTP2_HEADER_CONNECTION"] val hTTP2_HEADER_CONTENT_DISPOSITION: string [@@js.global "HTTP2_HEADER_CONTENT_DISPOSITION"] val hTTP2_HEADER_CONTENT_ENCODING: string [@@js.global "HTTP2_HEADER_CONTENT_ENCODING"] val hTTP2_HEADER_CONTENT_LANGUAGE: string [@@js.global "HTTP2_HEADER_CONTENT_LANGUAGE"] val hTTP2_HEADER_CONTENT_LENGTH: string [@@js.global "HTTP2_HEADER_CONTENT_LENGTH"] val hTTP2_HEADER_CONTENT_LOCATION: string [@@js.global "HTTP2_HEADER_CONTENT_LOCATION"] val hTTP2_HEADER_CONTENT_MD5: string [@@js.global "HTTP2_HEADER_CONTENT_MD5"] val hTTP2_HEADER_CONTENT_RANGE: string [@@js.global "HTTP2_HEADER_CONTENT_RANGE"] val hTTP2_HEADER_CONTENT_TYPE: string [@@js.global "HTTP2_HEADER_CONTENT_TYPE"] val hTTP2_HEADER_COOKIE: string [@@js.global "HTTP2_HEADER_COOKIE"] val hTTP2_HEADER_DATE: string [@@js.global "HTTP2_HEADER_DATE"] val hTTP2_HEADER_ETAG: string [@@js.global "HTTP2_HEADER_ETAG"] val hTTP2_HEADER_EXPECT: string [@@js.global "HTTP2_HEADER_EXPECT"] val hTTP2_HEADER_EXPIRES: string [@@js.global "HTTP2_HEADER_EXPIRES"] val hTTP2_HEADER_FROM: string [@@js.global "HTTP2_HEADER_FROM"] val hTTP2_HEADER_HOST: string [@@js.global "HTTP2_HEADER_HOST"] val hTTP2_HEADER_IF_MATCH: string [@@js.global "HTTP2_HEADER_IF_MATCH"] val hTTP2_HEADER_IF_MODIFIED_SINCE: string [@@js.global "HTTP2_HEADER_IF_MODIFIED_SINCE"] val hTTP2_HEADER_IF_NONE_MATCH: string [@@js.global "HTTP2_HEADER_IF_NONE_MATCH"] val hTTP2_HEADER_IF_RANGE: string [@@js.global "HTTP2_HEADER_IF_RANGE"] val hTTP2_HEADER_IF_UNMODIFIED_SINCE: string [@@js.global "HTTP2_HEADER_IF_UNMODIFIED_SINCE"] val hTTP2_HEADER_LAST_MODIFIED: string [@@js.global "HTTP2_HEADER_LAST_MODIFIED"] val hTTP2_HEADER_LINK: string [@@js.global "HTTP2_HEADER_LINK"] val hTTP2_HEADER_LOCATION: string [@@js.global "HTTP2_HEADER_LOCATION"] val hTTP2_HEADER_MAX_FORWARDS: string [@@js.global "HTTP2_HEADER_MAX_FORWARDS"] val hTTP2_HEADER_PREFER: string [@@js.global "HTTP2_HEADER_PREFER"] val hTTP2_HEADER_PROXY_AUTHENTICATE: string [@@js.global "HTTP2_HEADER_PROXY_AUTHENTICATE"] val hTTP2_HEADER_PROXY_AUTHORIZATION: string [@@js.global "HTTP2_HEADER_PROXY_AUTHORIZATION"] val hTTP2_HEADER_RANGE: string [@@js.global "HTTP2_HEADER_RANGE"] val hTTP2_HEADER_REFERER: string [@@js.global "HTTP2_HEADER_REFERER"] val hTTP2_HEADER_REFRESH: string [@@js.global "HTTP2_HEADER_REFRESH"] val hTTP2_HEADER_RETRY_AFTER: string [@@js.global "HTTP2_HEADER_RETRY_AFTER"] val hTTP2_HEADER_SERVER: string [@@js.global "HTTP2_HEADER_SERVER"] val hTTP2_HEADER_SET_COOKIE: string [@@js.global "HTTP2_HEADER_SET_COOKIE"] val hTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string [@@js.global "HTTP2_HEADER_STRICT_TRANSPORT_SECURITY"] val hTTP2_HEADER_TRANSFER_ENCODING: string [@@js.global "HTTP2_HEADER_TRANSFER_ENCODING"] val hTTP2_HEADER_TE: string [@@js.global "HTTP2_HEADER_TE"] val hTTP2_HEADER_UPGRADE: string [@@js.global "HTTP2_HEADER_UPGRADE"] val hTTP2_HEADER_USER_AGENT: string [@@js.global "HTTP2_HEADER_USER_AGENT"] val hTTP2_HEADER_VARY: string [@@js.global "HTTP2_HEADER_VARY"] val hTTP2_HEADER_VIA: string [@@js.global "HTTP2_HEADER_VIA"] val hTTP2_HEADER_WWW_AUTHENTICATE: string [@@js.global "HTTP2_HEADER_WWW_AUTHENTICATE"] val hTTP2_HEADER_HTTP2_SETTINGS: string [@@js.global "HTTP2_HEADER_HTTP2_SETTINGS"] val hTTP2_HEADER_KEEP_ALIVE: string [@@js.global "HTTP2_HEADER_KEEP_ALIVE"] val hTTP2_HEADER_PROXY_CONNECTION: string [@@js.global "HTTP2_HEADER_PROXY_CONNECTION"] val hTTP2_METHOD_ACL: string [@@js.global "HTTP2_METHOD_ACL"] val hTTP2_METHOD_BASELINE_CONTROL: string [@@js.global "HTTP2_METHOD_BASELINE_CONTROL"] val hTTP2_METHOD_BIND: string [@@js.global "HTTP2_METHOD_BIND"] val hTTP2_METHOD_CHECKIN: string [@@js.global "HTTP2_METHOD_CHECKIN"] val hTTP2_METHOD_CHECKOUT: string [@@js.global "HTTP2_METHOD_CHECKOUT"] val hTTP2_METHOD_CONNECT: string [@@js.global "HTTP2_METHOD_CONNECT"] val hTTP2_METHOD_COPY: string [@@js.global "HTTP2_METHOD_COPY"] val hTTP2_METHOD_DELETE: string [@@js.global "HTTP2_METHOD_DELETE"] val hTTP2_METHOD_GET: string [@@js.global "HTTP2_METHOD_GET"] val hTTP2_METHOD_HEAD: string [@@js.global "HTTP2_METHOD_HEAD"] val hTTP2_METHOD_LABEL: string [@@js.global "HTTP2_METHOD_LABEL"] val hTTP2_METHOD_LINK: string [@@js.global "HTTP2_METHOD_LINK"] val hTTP2_METHOD_LOCK: string [@@js.global "HTTP2_METHOD_LOCK"] val hTTP2_METHOD_MERGE: string [@@js.global "HTTP2_METHOD_MERGE"] val hTTP2_METHOD_MKACTIVITY: string [@@js.global "HTTP2_METHOD_MKACTIVITY"] val hTTP2_METHOD_MKCALENDAR: string [@@js.global "HTTP2_METHOD_MKCALENDAR"] val hTTP2_METHOD_MKCOL: string [@@js.global "HTTP2_METHOD_MKCOL"] val hTTP2_METHOD_MKREDIRECTREF: string [@@js.global "HTTP2_METHOD_MKREDIRECTREF"] val hTTP2_METHOD_MKWORKSPACE: string [@@js.global "HTTP2_METHOD_MKWORKSPACE"] val hTTP2_METHOD_MOVE: string [@@js.global "HTTP2_METHOD_MOVE"] val hTTP2_METHOD_OPTIONS: string [@@js.global "HTTP2_METHOD_OPTIONS"] val hTTP2_METHOD_ORDERPATCH: string [@@js.global "HTTP2_METHOD_ORDERPATCH"] val hTTP2_METHOD_PATCH: string [@@js.global "HTTP2_METHOD_PATCH"] val hTTP2_METHOD_POST: string [@@js.global "HTTP2_METHOD_POST"] val hTTP2_METHOD_PRI: string [@@js.global "HTTP2_METHOD_PRI"] val hTTP2_METHOD_PROPFIND: string [@@js.global "HTTP2_METHOD_PROPFIND"] val hTTP2_METHOD_PROPPATCH: string [@@js.global "HTTP2_METHOD_PROPPATCH"] val hTTP2_METHOD_PUT: string [@@js.global "HTTP2_METHOD_PUT"] val hTTP2_METHOD_REBIND: string [@@js.global "HTTP2_METHOD_REBIND"] val hTTP2_METHOD_REPORT: string [@@js.global "HTTP2_METHOD_REPORT"] val hTTP2_METHOD_SEARCH: string [@@js.global "HTTP2_METHOD_SEARCH"] val hTTP2_METHOD_TRACE: string [@@js.global "HTTP2_METHOD_TRACE"] val hTTP2_METHOD_UNBIND: string [@@js.global "HTTP2_METHOD_UNBIND"] val hTTP2_METHOD_UNCHECKOUT: string [@@js.global "HTTP2_METHOD_UNCHECKOUT"] val hTTP2_METHOD_UNLINK: string [@@js.global "HTTP2_METHOD_UNLINK"] val hTTP2_METHOD_UNLOCK: string [@@js.global "HTTP2_METHOD_UNLOCK"] val hTTP2_METHOD_UPDATE: string [@@js.global "HTTP2_METHOD_UPDATE"] val hTTP2_METHOD_UPDATEREDIRECTREF: string [@@js.global "HTTP2_METHOD_UPDATEREDIRECTREF"] val hTTP2_METHOD_VERSION_CONTROL: string [@@js.global "HTTP2_METHOD_VERSION_CONTROL"] val hTTP_STATUS_CONTINUE: float [@@js.global "HTTP_STATUS_CONTINUE"] val hTTP_STATUS_SWITCHING_PROTOCOLS: float [@@js.global "HTTP_STATUS_SWITCHING_PROTOCOLS"] val hTTP_STATUS_PROCESSING: float [@@js.global "HTTP_STATUS_PROCESSING"] val hTTP_STATUS_OK: float [@@js.global "HTTP_STATUS_OK"] val hTTP_STATUS_CREATED: float [@@js.global "HTTP_STATUS_CREATED"] val hTTP_STATUS_ACCEPTED: float [@@js.global "HTTP_STATUS_ACCEPTED"] val hTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: float [@@js.global "HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION"] val hTTP_STATUS_NO_CONTENT: float [@@js.global "HTTP_STATUS_NO_CONTENT"] val hTTP_STATUS_RESET_CONTENT: float [@@js.global "HTTP_STATUS_RESET_CONTENT"] val hTTP_STATUS_PARTIAL_CONTENT: float [@@js.global "HTTP_STATUS_PARTIAL_CONTENT"] val hTTP_STATUS_MULTI_STATUS: float [@@js.global "HTTP_STATUS_MULTI_STATUS"] val hTTP_STATUS_ALREADY_REPORTED: float [@@js.global "HTTP_STATUS_ALREADY_REPORTED"] val hTTP_STATUS_IM_USED: float [@@js.global "HTTP_STATUS_IM_USED"] val hTTP_STATUS_MULTIPLE_CHOICES: float [@@js.global "HTTP_STATUS_MULTIPLE_CHOICES"] val hTTP_STATUS_MOVED_PERMANENTLY: float [@@js.global "HTTP_STATUS_MOVED_PERMANENTLY"] val hTTP_STATUS_FOUND: float [@@js.global "HTTP_STATUS_FOUND"] val hTTP_STATUS_SEE_OTHER: float [@@js.global "HTTP_STATUS_SEE_OTHER"] val hTTP_STATUS_NOT_MODIFIED: float [@@js.global "HTTP_STATUS_NOT_MODIFIED"] val hTTP_STATUS_USE_PROXY: float [@@js.global "HTTP_STATUS_USE_PROXY"] val hTTP_STATUS_TEMPORARY_REDIRECT: float [@@js.global "HTTP_STATUS_TEMPORARY_REDIRECT"] val hTTP_STATUS_PERMANENT_REDIRECT: float [@@js.global "HTTP_STATUS_PERMANENT_REDIRECT"] val hTTP_STATUS_BAD_REQUEST: float [@@js.global "HTTP_STATUS_BAD_REQUEST"] val hTTP_STATUS_UNAUTHORIZED: float [@@js.global "HTTP_STATUS_UNAUTHORIZED"] val hTTP_STATUS_PAYMENT_REQUIRED: float [@@js.global "HTTP_STATUS_PAYMENT_REQUIRED"] val hTTP_STATUS_FORBIDDEN: float [@@js.global "HTTP_STATUS_FORBIDDEN"] val hTTP_STATUS_NOT_FOUND: float [@@js.global "HTTP_STATUS_NOT_FOUND"] val hTTP_STATUS_METHOD_NOT_ALLOWED: float [@@js.global "HTTP_STATUS_METHOD_NOT_ALLOWED"] val hTTP_STATUS_NOT_ACCEPTABLE: float [@@js.global "HTTP_STATUS_NOT_ACCEPTABLE"] val hTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: float [@@js.global "HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED"] val hTTP_STATUS_REQUEST_TIMEOUT: float [@@js.global "HTTP_STATUS_REQUEST_TIMEOUT"] val hTTP_STATUS_CONFLICT: float [@@js.global "HTTP_STATUS_CONFLICT"] val hTTP_STATUS_GONE: float [@@js.global "HTTP_STATUS_GONE"] val hTTP_STATUS_LENGTH_REQUIRED: float [@@js.global "HTTP_STATUS_LENGTH_REQUIRED"] val hTTP_STATUS_PRECONDITION_FAILED: float [@@js.global "HTTP_STATUS_PRECONDITION_FAILED"] val hTTP_STATUS_PAYLOAD_TOO_LARGE: float [@@js.global "HTTP_STATUS_PAYLOAD_TOO_LARGE"] val hTTP_STATUS_URI_TOO_LONG: float [@@js.global "HTTP_STATUS_URI_TOO_LONG"] val hTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: float [@@js.global "HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE"] val hTTP_STATUS_RANGE_NOT_SATISFIABLE: float [@@js.global "HTTP_STATUS_RANGE_NOT_SATISFIABLE"] val hTTP_STATUS_EXPECTATION_FAILED: float [@@js.global "HTTP_STATUS_EXPECTATION_FAILED"] val hTTP_STATUS_TEAPOT: float [@@js.global "HTTP_STATUS_TEAPOT"] val hTTP_STATUS_MISDIRECTED_REQUEST: float [@@js.global "HTTP_STATUS_MISDIRECTED_REQUEST"] val hTTP_STATUS_UNPROCESSABLE_ENTITY: float [@@js.global "HTTP_STATUS_UNPROCESSABLE_ENTITY"] val hTTP_STATUS_LOCKED: float [@@js.global "HTTP_STATUS_LOCKED"] val hTTP_STATUS_FAILED_DEPENDENCY: float [@@js.global "HTTP_STATUS_FAILED_DEPENDENCY"] val hTTP_STATUS_UNORDERED_COLLECTION: float [@@js.global "HTTP_STATUS_UNORDERED_COLLECTION"] val hTTP_STATUS_UPGRADE_REQUIRED: float [@@js.global "HTTP_STATUS_UPGRADE_REQUIRED"] val hTTP_STATUS_PRECONDITION_REQUIRED: float [@@js.global "HTTP_STATUS_PRECONDITION_REQUIRED"] val hTTP_STATUS_TOO_MANY_REQUESTS: float [@@js.global "HTTP_STATUS_TOO_MANY_REQUESTS"] val hTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: float [@@js.global "HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE"] val hTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: float [@@js.global "HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS"] val hTTP_STATUS_INTERNAL_SERVER_ERROR: float [@@js.global "HTTP_STATUS_INTERNAL_SERVER_ERROR"] val hTTP_STATUS_NOT_IMPLEMENTED: float [@@js.global "HTTP_STATUS_NOT_IMPLEMENTED"] val hTTP_STATUS_BAD_GATEWAY: float [@@js.global "HTTP_STATUS_BAD_GATEWAY"] val hTTP_STATUS_SERVICE_UNAVAILABLE: float [@@js.global "HTTP_STATUS_SERVICE_UNAVAILABLE"] val hTTP_STATUS_GATEWAY_TIMEOUT: float [@@js.global "HTTP_STATUS_GATEWAY_TIMEOUT"] val hTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: float [@@js.global "HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED"] val hTTP_STATUS_VARIANT_ALSO_NEGOTIATES: float [@@js.global "HTTP_STATUS_VARIANT_ALSO_NEGOTIATES"] val hTTP_STATUS_INSUFFICIENT_STORAGE: float [@@js.global "HTTP_STATUS_INSUFFICIENT_STORAGE"] val hTTP_STATUS_LOOP_DETECTED: float [@@js.global "HTTP_STATUS_LOOP_DETECTED"] val hTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: float [@@js.global "HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED"] val hTTP_STATUS_NOT_EXTENDED: float [@@js.global "HTTP_STATUS_NOT_EXTENDED"] val hTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: float [@@js.global "HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED"] end val getDefaultSettings: unit -> http2_Settings [@@js.global "getDefaultSettings"] val getPackedSettings: settings:http2_Settings -> Buffer.t_0 [@@js.global "getPackedSettings"] val getUnpackedSettings: buf:Uint8Array.t_0 -> http2_Settings [@@js.global "getUnpackedSettings"] val createServer: ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2Server [@@js.global "createServer"] val createServer: options:http2_ServerOptions -> ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2Server [@@js.global "createServer"] val createSecureServer: ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2SecureServer [@@js.global "createSecureServer"] val createSecureServer: options:http2_SecureServerOptions -> ?onRequestHandler:(request:http2_Http2ServerRequest -> response:http2_Http2ServerResponse -> unit) -> unit -> http2_Http2SecureServer [@@js.global "createSecureServer"] val connect: authority:Url.URL.t_0 or_string -> listener:(session:http2_ClientHttp2Session -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> http2_ClientHttp2Session [@@js.global "connect"] val connect: authority:Url.URL.t_0 or_string -> ?options:([`U_s15_http_ of (http2_ClientSessionOptions, http2_SecureClientSessionOptions) union2 | `U_s16_https_ of (http2_ClientSessionOptions, http2_SecureClientSessionOptions) union2 ] [@js.union on_field "protocol"]) -> ?listener:(session:http2_ClientHttp2Session -> socket:(Net.Socket.t_0, Tls.TLSSocket.t_0) union2 -> unit) -> unit -> http2_ClientHttp2Session [@@js.global "connect"] end end
1d8b1737b8f84d6c5c5746bda201f096a83144d3fdb288038484f881fa63cc8e
ygmpkk/house
Initialization.hs
-------------------------------------------------------------------------------- -- | Module : Graphics . UI.GLUT.Initialization Copyright : ( c ) 2003 -- License : BSD-style (see the file libraries/GLUT/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : portable -- Actions and state variables in this module are used to initialize GLUT state . -- The primary initialization routine is 'initialize', which should only be called exactly once in a GLUT program . No other GLUT or OpenGL actions should -- be called before 'initialize', apart from getting or setting the state -- variables in this module. -- -- The reason is that these state variables can be used to set default window -- initialization state that might be modified by the command processing done in -- 'initialize'. For example, 'initialWindowSize' can be set to @('WindowSize' 400 400)@ before ' initialize ' is called to indicate 400 by 400 is the 's default window size . Setting the initial window size or position before ' initialize ' allows the GLUT program user to specify the initial size -- or position using command line arguments. -- -------------------------------------------------------------------------------- module Graphics.UI.GLUT.Initialization ( -- * Primary initialization initialize, getArgsAndInitialize, -- * Initial window geometry initialWindowPosition, initialWindowSize, -- * Setting the initial display mode (I) DisplayMode(..), initialDisplayMode, displayModePossible, * Setting the initial display mode ( II ) DisplayCapability(..), Relation(..), DisplayCapabilityDescription(..), initialDisplayCapabilities ) where import Data.Bits ( Bits((.|.),(.&.)) ) import Data.List ( genericLength, intersperse ) import Foreign.C.String ( CString, withCString, peekCString ) import Foreign.C.Types ( CInt, CUInt ) import Foreign.Marshal.Array ( withArray0, peekArray ) import Foreign.Marshal.Utils ( with, withMany ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(..) ) import System.Environment ( getProgName, getArgs ) import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) ) import Graphics.Rendering.OpenGL.GL.StateVar ( GettableStateVar, makeGettableStateVar, SettableStateVar, makeSettableStateVar, StateVar, makeStateVar ) import Graphics.UI.GLUT.Constants ( glut_INIT_WINDOW_X, glut_INIT_WINDOW_Y, glut_INIT_WINDOW_WIDTH, glut_INIT_WINDOW_HEIGHT, glut_RGBA, glut_RGB, glut_INDEX, glut_SINGLE, glut_DOUBLE, glut_ACCUM, glut_ALPHA, glut_DEPTH, glut_STENCIL, glut_MULTISAMPLE, glut_STEREO, glut_LUMINANCE, glut_INIT_DISPLAY_MODE, glut_DISPLAY_MODE_POSSIBLE ) import Graphics.UI.GLUT.QueryUtils ( simpleGet ) import Graphics.UI.GLUT.Types ( Relation(..), relationToString ) -------------------------------------------------------------------------------- | Given the program name and command line arguments , initialize the GLUT -- library and negotiate a session with the window system. During this process , ' initialize ' may cause the termination of the GLUT program with an error message to the user if GLUT can not be properly initialized . -- Examples of this situation include the failure to connect to the window -- system, the lack of window system support for OpenGL, and invalid command -- line options. -- -- 'initialized.' also processes command line options, but the specific options -- parsed are window system dependent. Any command line arguments which are not GLUT - specific are returned . -- -- /X Implementation Notes:/ The X Window System specific options parsed by -- 'initialize' are as follows: -- -- * @-display /DISPLAY/@: Specify the X server to connect to. If not specified, -- the value of the @DISPLAY@ environment variable is used. -- -- * @-geometry /WxH+X+Y/@: Determines where windows should be created on the -- screen. The parameter following @-geometry@ should be formatted as a -- standard X geometry specification. The effect of using this option is to change the GLUT initial size and initial position the same as if -- 'initialWindowSize' or 'initialWindowPosition' were modified directly. -- -- * @-iconic@: Requests all top-level windows be created in an iconic state. -- -- * @-indirect@: Force the use of indirect OpenGL rendering contexts. -- * @-direct@ : Force the use of direct OpenGL rendering contexts ( not all GLX -- implementations support direct rendering contexts). A fatal error is -- generated if direct rendering is not supported by the OpenGL -- implementation. If neither @-indirect@ or @-direct@ are used to force a particular behavior , GLUT will attempt to use direct rendering if -- possible and otherwise fallback to indirect rendering. -- -- * @-gldebug@: After processing callbacks and\/or events, call -- 'Graphics.UI.GLUT.Debugging.reportErrors' to check if there are any pending -- OpenGL errors. Using this option is helpful in detecting OpenGL run-time -- errors. -- -- * @-sync@: Enable synchronous X protocol transactions. This option makes -- it easier to track down potential X protocol errors. initialize :: String -- ^ The program name. -> [String] -- ^ The command line arguments ^ Non - GLUT command line arguments initialize prog args = with (1 + genericLength args) $ \argcBuf -> withMany withCString (prog : args) $ \argvPtrs -> withArray0 nullPtr argvPtrs $ \argvBuf -> do glutInit argcBuf argvBuf newArgc <- peek argcBuf newArgvPtrs <- peekArray (fromIntegral newArgc) argvBuf newArgv <- mapM peekCString newArgvPtrs return $ tail newArgv foreign import CALLCONV unsafe "glutInit" glutInit :: Ptr CInt -> Ptr CString -> IO () | Convenience action : Initialize GLUT , returning the program name and any non - GLUT command line arguments . getArgsAndInitialize :: IO (String, [String]) getArgsAndInitialize = do prog <- getProgName args <- getArgs nonGLUTArgs <- initialize prog args return (prog, nonGLUTArgs) -------------------------------------------------------------------------------- | Controls the /initial window position/. Windows created by ' Graphics . UI.GLUT.Window.createWindow ' will be requested to be created with -- the current /initial window position/. The initial value of the /initial window position/ GLUT state is @'Size ' ( -1 ) ( -1)@. If either the X or Y -- component of the /initial window position/ is negative, the actual window -- position is left to the window system to determine. -- -- The intent of the /initial window position/ is to provide a suggestion to -- the window system for a window\'s initial position. The window system is not obligated to use this information . Therefore , GLUT programs should not -- assume the window was created at the specified position. initialWindowPosition :: StateVar Position initialWindowPosition = makeStateVar getInitialWindowPosition setInitialWindowPosition getInitialWindowPosition :: IO Position getInitialWindowPosition = do x <- simpleGet fromIntegral glut_INIT_WINDOW_X y <- simpleGet fromIntegral glut_INIT_WINDOW_Y return $ Position x y setInitialWindowPosition :: Position -> IO () setInitialWindowPosition (Position x y) = glutInitWindowPosition (fromIntegral x) (fromIntegral y) foreign import CALLCONV unsafe "glutInitWindowPosition" glutInitWindowPosition :: CInt -> CInt -> IO () -------------------------------------------------------------------------------- | Controls the /initial window size/. Windows created by ' Graphics . UI.GLUT.Window.createWindow ' will be requested to be created with -- the current /initial window size/. The initial value of the /initial window size/ GLUT state is @'Size ' 300 300@. If either the width or the height -- component of the /initial window size/ is non-positive, the actual window -- size is left to the window system to determine. -- -- The intent of the /initial window size/ is to provide a suggestion to the -- window system for a window\'s initial size. The window system is not obligated to use this information . Therefore , GLUT programs should not assume the window was created at the specified size . A GLUT program should -- use the window\'s reshape callback to determine the true size of the -- window. initialWindowSize :: StateVar Size initialWindowSize = makeStateVar getInitialWindowSize setInitialWindowSize getInitialWindowSize :: IO Size getInitialWindowSize = do w <- simpleGet fromIntegral glut_INIT_WINDOW_WIDTH h <- simpleGet fromIntegral glut_INIT_WINDOW_HEIGHT return $ Size w h setInitialWindowSize :: Size -> IO () setInitialWindowSize (Size w h) = glutInitWindowSize (fromIntegral w) (fromIntegral h) foreign import CALLCONV unsafe "glutInitWindowSize" glutInitWindowSize :: CInt -> CInt -> IO () -------------------------------------------------------------------------------- -- | A single aspect of a window which is to be created, used in conjunction -- with 'initialDisplayMode'. data DisplayMode ^ Select an RGBA mode window . This is the default if neither ' ' nor ' IndexMode ' are specified . ^ An alias for ' ' . ^ Select a color index mode window . This overrides ' ' if it is also specified . ^ Select a window with a " color model . This model provides the functionality of OpenGL\ 's -- RGBA color model, but the green and blue components are not maintained in the frame buffer. Instead each pixel\ 's red component is converted to an index between zero and ' Graphics . UI.GLUT.Colormap.numColorMapEntries ' -- and looked up in a per-window color map to determine the color of pixels within the window. The initial colormap of ' LuminanceMode ' windows is initialized to be a linear gray ramp , but can be modified with GLUT\ 's actions . /Implementation Notes:/ ' LuminanceMode ' is not supported on most OpenGL platforms . | WithAlphaComponent -- ^ Select a window with an alpha component to the color buffer(s). | WithAccumBuffer -- ^ Select a window with an accumulation buffer. | WithDepthBuffer -- ^ Select a window with a depth buffer. | WithStencilBuffer -- ^ Select a window with a stencil buffer. | SingleBuffered -- ^ Select a single buffered window. This is the default if neither 'DoubleBuffered' nor 'SingleBuffered' are specified. | DoubleBuffered -- ^ Select a double buffered window. This overrides 'SingleBuffered' if it is also specified. | Multisampling -- ^ Select a window with multisampling support. If multisampling is not available, a non-multisampling -- window will automatically be chosen. Note: both the OpenGL client-side and server-side implementations -- must support the @GLX_SAMPLE_SGIS@ extension for multisampling to be available. ^ Select A Stereo Window . deriving ( Eq, Ord, Show ) marshalDisplayMode :: DisplayMode -> CUInt marshalDisplayMode m = case m of RGBAMode -> glut_RGBA RGBMode -> glut_RGB IndexMode -> glut_INDEX SingleBuffered -> glut_SINGLE DoubleBuffered -> glut_DOUBLE WithAccumBuffer -> glut_ACCUM WithAlphaComponent -> glut_ALPHA WithDepthBuffer -> glut_DEPTH WithStencilBuffer -> glut_STENCIL Multisampling -> glut_MULTISAMPLE Stereoscopic -> glut_STEREO LuminanceMode -> glut_LUMINANCE -------------------------------------------------------------------------------- | Controls the /initial display used when creating top - level windows , -- subwindows, and overlays to determine the OpenGL display mode for the -- to-be-created window or overlay. -- Note that ' ' selects the RGBA color model , but it does not request any -- bits of alpha (sometimes called an /alpha buffer/ or /destination alpha/) -- be allocated. To request alpha, specify 'WithAlphaComponent'. The same applies to ' LuminanceMode ' . initialDisplayMode :: StateVar [DisplayMode] initialDisplayMode = makeStateVar getInitialDisplayMode setInitialDisplayMode getInitialDisplayMode :: IO [DisplayMode] getInitialDisplayMode = simpleGet i2dms glut_INIT_DISPLAY_MODE i2dms :: CInt -> [DisplayMode] i2dms bitfield = [ c | c <- [ RGBAMode, RGBMode, IndexMode, SingleBuffered, DoubleBuffered, WithAccumBuffer, WithAlphaComponent, WithDepthBuffer, WithStencilBuffer, Multisampling, Stereoscopic, LuminanceMode ] , (fromIntegral bitfield .&. marshalDisplayMode c) /= 0 ] setInitialDisplayMode :: [DisplayMode] -> IO () setInitialDisplayMode = glutInitDisplayMode . toBitfield marshalDisplayMode toBitfield :: (Bits b) => (a -> b) -> [a] -> b toBitfield marshal = foldl (.|.) 0 . map marshal foreign import CALLCONV unsafe "glutInitDisplayMode" glutInitDisplayMode :: CUInt -> IO () | Contains ' True ' if the /current display is supported , ' False ' -- otherwise. displayModePossible :: GettableStateVar Bool displayModePossible = makeGettableStateVar $ simpleGet (/= 0) glut_DISPLAY_MODE_POSSIBLE -------------------------------------------------------------------------------- -- | Capabilities for 'initialDisplayCapabilities', most of them are extensions of ' 's constructors . data DisplayCapability = DisplayRGBA -- ^ Number of bits of red, green, blue, and alpha in the RGBA color buffer . Default is \"'IsAtLeast ' " for red , green , blue , and alpha capabilities , and \"'IsEqualTo ' " for the RGBA color model capability . | DisplayRGB -- ^ Number of bits of red, green, and blue in the RGBA color buffer and zero bits of alpha color buffer precision . Default is \"'IsAtLeast ' " for the red , green , and blue capabilities , and ' @0@\ " for alpha capability , and \"'IsEqualTo ' " for the RGBA color -- model capability. | DisplayRed -- ^ Red color buffer precision in bits. Default is \"'IsAtLeast ' " . | DisplayGreen -- ^ Green color buffer precision in bits. Default is \"'IsAtLeast ' " . | DisplayBlue -- ^ Blue color buffer precision in bits. Default is \"'IsAtLeast ' " . | DisplayIndex -- ^ Boolean if the color model is color index or not. True is color index . Default is \"'IsAtLeast ' " . | DisplayBuffer -- ^ Number of bits in the color index color buffer. Default is \"'IsAtLeast ' " . | DisplaySingle -- ^ Boolean indicate the color buffer is single buffered. Default is \"'IsEqualTo ' " . | DisplayDouble -- ^ Boolean indicating if the color buffer is double buffered . Default is \"'IsEqualTo ' " . | DisplayAccA -- ^ Red, green, blue, and alpha accumulation buffer precision in bits . Default is \"'IsAtLeast ' " for red , green , -- blue, and alpha capabilities. | DisplayAcc -- ^ Red, green, and green accumulation buffer precision in bits and zero bits of alpha accumulation buffer precision . Default is \"'IsAtLeast ' " for red , green , and blue capabilities , and ' @0@\ " for the alpha -- capability. | DisplayAlpha -- ^ Alpha color buffer precision in bits. Default is \"'IsAtLeast ' " . | DisplayDepth -- ^ Number of bits of precsion in the depth buffer. Default is \"'IsAtLeast ' @12@\ " . | DisplayStencil -- ^ Number of bits in the stencil buffer. Default is ' " . | DisplaySamples -- ^ Indicates the number of multisamples to use based on -- GLX\'s @SGIS_multisample@ extension (for antialiasing). -- Default is \"'IsNotGreaterThan' @4@\". This default means that a GLUT application can request multisampling if -- available by simply specifying \"'With' 'Samples'\". | DisplayStereo -- ^ Boolean indicating the color buffer is supports OpenGL - style stereo . Default is \"'IsEqualTo ' " . ^ Number of bits of red in the RGBA and zero bits of green , -- blue (alpha not specified) of color buffer precision. Default is \"'IsAtLeast ' " for the red capabilitis , and \"'IsEqualTo ' @0@\ " for the green and blue capabilities , and \"'IsEqualTo ' " for the RGBA color model capability , and , for X11 , \"'IsEqualTo ' " for the ' XStaticGray ' capability . SGI InfiniteReality ( and other future machines ) support a 16 - bit luminance ( single channel ) display mode ( an additional 16 - bit alpha channel -- can also be requested). The red channel maps to gray -- scale and green and blue channels are not available. A 16 - bit precision luminance display mode is often -- appropriate for medical imaging applications. Do not -- expect many machines to support extended precision -- luminance display modes. | DisplayNum -- ^ A special capability name indicating where the value represents the Nth frame buffer configuration matching -- the description string. When not specified, ' initialDisplayCapabilitiesString ' also returns the first ( best matching ) configuration . ' ' requires a relation -- and numeric value. | DisplayConformant -- ^ Boolean indicating if the frame buffer configuration is -- conformant or not. Conformance information is based on -- GLX\'s @EXT_visual_rating@ extension if supported. If the -- extension is not supported, all visuals are assumed conformant . Default is \"'IsEqualTo ' " . | DisplaySlow -- ^ Boolean indicating if the frame buffer configuration is -- slow or not. Slowness information is based on GLX\'s -- @EXT_visual_rating@ extension if supported. If the -- extension is not supported, all visuals are assumed fast. -- Note that slowness is a relative designation relative to -- other frame buffer configurations available. The intent -- of the slow capability is to help programs avoid frame -- buffer configurations that are slower (but perhaps higher -- precision) for the current machine. Default is -- \"'IsAtLeast' @0@\". This default means that slow visuals -- are used in preference to fast visuals, but fast visuals -- will still be allowed. ^ Only recognized on GLUT implementations for , this -- capability name matches the Win32 Pixel Format Descriptor -- by number. 'Win32PFD' can only be used with 'Where'. ^ Only recongized on GLUT implementations for the X Window -- System, this capability name matches the X visual ID by -- number. 'XVisual' requires a relation and numeric value. ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer configuration\ 's X visual is of type Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer -- configuration\'s X visual is of type @GrayScale@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer -- configuration\'s X visual is of type @StaticColor@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer configuration\ 's X visual is of type @PsuedoColor@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer configuration\ 's X visual is of type @TrueColor@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window -- System, boolean indicating if the frame buffer -- configuration\'s X visual is of type @DirectColor@. Default is \"'IsEqualTo ' " . deriving ( Eq, Ord, Show ) displayCapabilityToString :: DisplayCapability -> String displayCapabilityToString x = case x of DisplayRGBA -> "rgba" DisplayRGB -> "rgb" DisplayRed -> "red" DisplayGreen -> "green" DisplayBlue -> "blue" DisplayIndex -> "index" DisplayBuffer -> "buffer" DisplaySingle -> "single" DisplayDouble -> "double" DisplayAccA -> "acca" DisplayAcc -> "acc" DisplayAlpha -> "alpha" DisplayDepth -> "depth" DisplayStencil -> "stencil" DisplaySamples -> "samples" DisplayStereo -> "stereo" DisplayLuminance -> "luminance" DisplayNum -> "num" DisplayConformant -> "conformant" DisplaySlow -> "slow" DisplayWin32PFD -> "win32pfd" DisplayXVisual -> "xvisual" DisplayXStaticGray -> "xstaticgray" DisplayXGrayScale -> "xgrayscale" DisplayXStaticColor -> "xstaticcolor" DisplayXPseudoColor -> "xpseudocolor" DisplayXTrueColor -> "xtruecolor" DisplayXDirectColor -> "xdirectcolor" -- | A single capability description for 'initialDisplayCapabilities'. data DisplayCapabilityDescription = Where DisplayCapability Relation Int -- ^ A description of a capability with a specific relation to a numeric -- value. | With DisplayCapability -- ^ When the relation and numeric value are not specified, each capability -- has a different default, see the different constructors of -- 'DisplayCapability'. deriving ( Eq, Ord, Show ) displayCapabilityDescriptionToString :: DisplayCapabilityDescription -> String displayCapabilityDescriptionToString (Where c r i) = displayCapabilityToString c ++ relationToString r ++ show i displayCapabilityDescriptionToString (With c) = displayCapabilityToString c | Controls the /initial display used when creating top - level windows , -- subwindows, and overlays to determine the OpenGL display mode for the to - be - created window or overlay . It is described by a list of zero or more -- capability descriptions, which are translated into a set of criteria used to -- select the appropriate frame buffer configuration. The criteria are matched in strict left to right order of precdence . That is , the first specified -- criterion (leftmost) takes precedence over the later criteria for non-exact criteria ( ' IsGreaterThan ' , ' IsLessThan ' , etc . ) . Exact criteria ( ' IsEqualTo ' , ' IsNotEqualTo ' ) must match exactly so precedence is not relevant . -- -- Unspecified capability descriptions will result in unspecified criteria being -- generated. These unspecified criteria help 'initialDisplayCapabilities' -- behave sensibly with terse display mode descriptions. -- -- Here is an example using 'initialDisplayCapabilities': -- -- @ initialDisplayCapabilities $ = [ With , Where DisplayDepth IsAtLeast 16 , -- With DisplaySamples, -- Where DisplayStencil IsNotLessThan 2, With DisplayDouble ] -- @ -- -- The above call requests a window with an RGBA color model (but requesting no bits of alpha ) , a depth buffer with at least 16 bits of precision but preferring more , multisampling if available , at least 2 bits of stencil -- (favoring less stencil to more as long as 2 bits are available), and double -- buffering. initialDisplayCapabilities :: SettableStateVar [DisplayCapabilityDescription] initialDisplayCapabilities = makeSettableStateVar $ \caps -> withCString (concat . intersperse " " . map displayCapabilityDescriptionToString $ caps) glutInitDisplayString foreign import CALLCONV unsafe "glutInitDisplayString" glutInitDisplayString :: CString -> IO ()
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/GLUT/Graphics/UI/GLUT/Initialization.hs
haskell
------------------------------------------------------------------------------ | License : BSD-style (see the file libraries/GLUT/LICENSE) Maintainer : Stability : provisional Portability : portable The primary initialization routine is 'initialize', which should only be be called before 'initialize', apart from getting or setting the state variables in this module. The reason is that these state variables can be used to set default window initialization state that might be modified by the command processing done in 'initialize'. For example, 'initialWindowSize' can be set to @('WindowSize' or position using command line arguments. ------------------------------------------------------------------------------ * Primary initialization * Initial window geometry * Setting the initial display mode (I) ------------------------------------------------------------------------------ library and negotiate a session with the window system. During this Examples of this situation include the failure to connect to the window system, the lack of window system support for OpenGL, and invalid command line options. 'initialized.' also processes command line options, but the specific options parsed are window system dependent. Any command line arguments which are /X Implementation Notes:/ The X Window System specific options parsed by 'initialize' are as follows: * @-display /DISPLAY/@: Specify the X server to connect to. If not specified, the value of the @DISPLAY@ environment variable is used. * @-geometry /WxH+X+Y/@: Determines where windows should be created on the screen. The parameter following @-geometry@ should be formatted as a standard X geometry specification. The effect of using this option is to 'initialWindowSize' or 'initialWindowPosition' were modified directly. * @-iconic@: Requests all top-level windows be created in an iconic state. * @-indirect@: Force the use of indirect OpenGL rendering contexts. implementations support direct rendering contexts). A fatal error is generated if direct rendering is not supported by the OpenGL implementation. If neither @-indirect@ or @-direct@ are used to force a possible and otherwise fallback to indirect rendering. * @-gldebug@: After processing callbacks and\/or events, call 'Graphics.UI.GLUT.Debugging.reportErrors' to check if there are any pending OpenGL errors. Using this option is helpful in detecting OpenGL run-time errors. * @-sync@: Enable synchronous X protocol transactions. This option makes it easier to track down potential X protocol errors. ^ The program name. ^ The command line arguments ------------------------------------------------------------------------------ the current /initial window position/. The initial value of the /initial component of the /initial window position/ is negative, the actual window position is left to the window system to determine. The intent of the /initial window position/ is to provide a suggestion to the window system for a window\'s initial position. The window system is assume the window was created at the specified position. ------------------------------------------------------------------------------ the current /initial window size/. The initial value of the /initial window component of the /initial window size/ is non-positive, the actual window size is left to the window system to determine. The intent of the /initial window size/ is to provide a suggestion to the window system for a window\'s initial size. The window system is not use the window\'s reshape callback to determine the true size of the window. ------------------------------------------------------------------------------ | A single aspect of a window which is to be created, used in conjunction with 'initialDisplayMode'. RGBA color model, but the green and blue components are not maintained in the frame buffer. Instead and looked up in a per-window color map to determine the color of pixels within the window. The initial ^ Select a window with an alpha component to the color buffer(s). ^ Select a window with an accumulation buffer. ^ Select a window with a depth buffer. ^ Select a window with a stencil buffer. ^ Select a single buffered window. This is the default if neither 'DoubleBuffered' nor 'SingleBuffered' are specified. ^ Select a double buffered window. This overrides 'SingleBuffered' if it is also specified. ^ Select a window with multisampling support. If multisampling is not available, a non-multisampling window will automatically be chosen. Note: both the OpenGL client-side and server-side implementations must support the @GLX_SAMPLE_SGIS@ extension for multisampling to be available. ------------------------------------------------------------------------------ subwindows, and overlays to determine the OpenGL display mode for the to-be-created window or overlay. bits of alpha (sometimes called an /alpha buffer/ or /destination alpha/) be allocated. To request alpha, specify 'WithAlphaComponent'. The same otherwise. ------------------------------------------------------------------------------ | Capabilities for 'initialDisplayCapabilities', most of them are extensions ^ Number of bits of red, green, blue, and alpha in the RGBA ^ Number of bits of red, green, and blue in the RGBA color model capability. ^ Red color buffer precision in bits. Default is ^ Green color buffer precision in bits. Default is ^ Blue color buffer precision in bits. Default is ^ Boolean if the color model is color index or not. True is ^ Number of bits in the color index color buffer. Default ^ Boolean indicate the color buffer is single buffered. ^ Boolean indicating if the color buffer is double ^ Red, green, blue, and alpha accumulation buffer precision blue, and alpha capabilities. ^ Red, green, and green accumulation buffer precision in capability. ^ Alpha color buffer precision in bits. Default is ^ Number of bits of precsion in the depth buffer. Default ^ Number of bits in the stencil buffer. Default is ^ Indicates the number of multisamples to use based on GLX\'s @SGIS_multisample@ extension (for antialiasing). Default is \"'IsNotGreaterThan' @4@\". This default means available by simply specifying \"'With' 'Samples'\". ^ Boolean indicating the color buffer is supports blue (alpha not specified) of color buffer precision. can also be requested). The red channel maps to gray scale and green and blue channels are not available. A appropriate for medical imaging applications. Do not expect many machines to support extended precision luminance display modes. ^ A special capability name indicating where the value the description string. When not specified, and numeric value. ^ Boolean indicating if the frame buffer configuration is conformant or not. Conformance information is based on GLX\'s @EXT_visual_rating@ extension if supported. If the extension is not supported, all visuals are assumed ^ Boolean indicating if the frame buffer configuration is slow or not. Slowness information is based on GLX\'s @EXT_visual_rating@ extension if supported. If the extension is not supported, all visuals are assumed fast. Note that slowness is a relative designation relative to other frame buffer configurations available. The intent of the slow capability is to help programs avoid frame buffer configurations that are slower (but perhaps higher precision) for the current machine. Default is \"'IsAtLeast' @0@\". This default means that slow visuals are used in preference to fast visuals, but fast visuals will still be allowed. capability name matches the Win32 Pixel Format Descriptor by number. 'Win32PFD' can only be used with 'Where'. System, this capability name matches the X visual ID by number. 'XVisual' requires a relation and numeric value. System, boolean indicating if the frame buffer System, boolean indicating if the frame buffer configuration\'s X visual is of type @GrayScale@. Default System, boolean indicating if the frame buffer configuration\'s X visual is of type @StaticColor@. System, boolean indicating if the frame buffer System, boolean indicating if the frame buffer System, boolean indicating if the frame buffer configuration\'s X visual is of type @DirectColor@. | A single capability description for 'initialDisplayCapabilities'. ^ A description of a capability with a specific relation to a numeric value. ^ When the relation and numeric value are not specified, each capability has a different default, see the different constructors of 'DisplayCapability'. subwindows, and overlays to determine the OpenGL display mode for the capability descriptions, which are translated into a set of criteria used to select the appropriate frame buffer configuration. The criteria are matched criterion (leftmost) takes precedence over the later criteria for non-exact Unspecified capability descriptions will result in unspecified criteria being generated. These unspecified criteria help 'initialDisplayCapabilities' behave sensibly with terse display mode descriptions. Here is an example using 'initialDisplayCapabilities': @ With DisplaySamples, Where DisplayStencil IsNotLessThan 2, @ The above call requests a window with an RGBA color model (but requesting (favoring less stencil to more as long as 2 bits are available), and double buffering.
Module : Graphics . UI.GLUT.Initialization Copyright : ( c ) 2003 Actions and state variables in this module are used to initialize GLUT state . called exactly once in a GLUT program . No other GLUT or OpenGL actions should 400 400)@ before ' initialize ' is called to indicate 400 by 400 is the 's default window size . Setting the initial window size or position before ' initialize ' allows the GLUT program user to specify the initial size module Graphics.UI.GLUT.Initialization ( initialize, getArgsAndInitialize, initialWindowPosition, initialWindowSize, DisplayMode(..), initialDisplayMode, displayModePossible, * Setting the initial display mode ( II ) DisplayCapability(..), Relation(..), DisplayCapabilityDescription(..), initialDisplayCapabilities ) where import Data.Bits ( Bits((.|.),(.&.)) ) import Data.List ( genericLength, intersperse ) import Foreign.C.String ( CString, withCString, peekCString ) import Foreign.C.Types ( CInt, CUInt ) import Foreign.Marshal.Array ( withArray0, peekArray ) import Foreign.Marshal.Utils ( with, withMany ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(..) ) import System.Environment ( getProgName, getArgs ) import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) ) import Graphics.Rendering.OpenGL.GL.StateVar ( GettableStateVar, makeGettableStateVar, SettableStateVar, makeSettableStateVar, StateVar, makeStateVar ) import Graphics.UI.GLUT.Constants ( glut_INIT_WINDOW_X, glut_INIT_WINDOW_Y, glut_INIT_WINDOW_WIDTH, glut_INIT_WINDOW_HEIGHT, glut_RGBA, glut_RGB, glut_INDEX, glut_SINGLE, glut_DOUBLE, glut_ACCUM, glut_ALPHA, glut_DEPTH, glut_STENCIL, glut_MULTISAMPLE, glut_STEREO, glut_LUMINANCE, glut_INIT_DISPLAY_MODE, glut_DISPLAY_MODE_POSSIBLE ) import Graphics.UI.GLUT.QueryUtils ( simpleGet ) import Graphics.UI.GLUT.Types ( Relation(..), relationToString ) | Given the program name and command line arguments , initialize the GLUT process , ' initialize ' may cause the termination of the GLUT program with an error message to the user if GLUT can not be properly initialized . not GLUT - specific are returned . change the GLUT initial size and initial position the same as if * @-direct@ : Force the use of direct OpenGL rendering contexts ( not all GLX particular behavior , GLUT will attempt to use direct rendering if ^ Non - GLUT command line arguments initialize prog args = with (1 + genericLength args) $ \argcBuf -> withMany withCString (prog : args) $ \argvPtrs -> withArray0 nullPtr argvPtrs $ \argvBuf -> do glutInit argcBuf argvBuf newArgc <- peek argcBuf newArgvPtrs <- peekArray (fromIntegral newArgc) argvBuf newArgv <- mapM peekCString newArgvPtrs return $ tail newArgv foreign import CALLCONV unsafe "glutInit" glutInit :: Ptr CInt -> Ptr CString -> IO () | Convenience action : Initialize GLUT , returning the program name and any non - GLUT command line arguments . getArgsAndInitialize :: IO (String, [String]) getArgsAndInitialize = do prog <- getProgName args <- getArgs nonGLUTArgs <- initialize prog args return (prog, nonGLUTArgs) | Controls the /initial window position/. Windows created by ' Graphics . UI.GLUT.Window.createWindow ' will be requested to be created with window position/ GLUT state is @'Size ' ( -1 ) ( -1)@. If either the X or Y not obligated to use this information . Therefore , GLUT programs should not initialWindowPosition :: StateVar Position initialWindowPosition = makeStateVar getInitialWindowPosition setInitialWindowPosition getInitialWindowPosition :: IO Position getInitialWindowPosition = do x <- simpleGet fromIntegral glut_INIT_WINDOW_X y <- simpleGet fromIntegral glut_INIT_WINDOW_Y return $ Position x y setInitialWindowPosition :: Position -> IO () setInitialWindowPosition (Position x y) = glutInitWindowPosition (fromIntegral x) (fromIntegral y) foreign import CALLCONV unsafe "glutInitWindowPosition" glutInitWindowPosition :: CInt -> CInt -> IO () | Controls the /initial window size/. Windows created by ' Graphics . UI.GLUT.Window.createWindow ' will be requested to be created with size/ GLUT state is @'Size ' 300 300@. If either the width or the height obligated to use this information . Therefore , GLUT programs should not assume the window was created at the specified size . A GLUT program should initialWindowSize :: StateVar Size initialWindowSize = makeStateVar getInitialWindowSize setInitialWindowSize getInitialWindowSize :: IO Size getInitialWindowSize = do w <- simpleGet fromIntegral glut_INIT_WINDOW_WIDTH h <- simpleGet fromIntegral glut_INIT_WINDOW_HEIGHT return $ Size w h setInitialWindowSize :: Size -> IO () setInitialWindowSize (Size w h) = glutInitWindowSize (fromIntegral w) (fromIntegral h) foreign import CALLCONV unsafe "glutInitWindowSize" glutInitWindowSize :: CInt -> CInt -> IO () data DisplayMode ^ Select an RGBA mode window . This is the default if neither ' ' nor ' IndexMode ' are specified . ^ An alias for ' ' . ^ Select a color index mode window . This overrides ' ' if it is also specified . ^ Select a window with a " color model . This model provides the functionality of OpenGL\ 's each pixel\ 's red component is converted to an index between zero and ' Graphics . UI.GLUT.Colormap.numColorMapEntries ' colormap of ' LuminanceMode ' windows is initialized to be a linear gray ramp , but can be modified with GLUT\ 's actions . /Implementation Notes:/ ' LuminanceMode ' is not supported on most OpenGL platforms . ^ Select A Stereo Window . deriving ( Eq, Ord, Show ) marshalDisplayMode :: DisplayMode -> CUInt marshalDisplayMode m = case m of RGBAMode -> glut_RGBA RGBMode -> glut_RGB IndexMode -> glut_INDEX SingleBuffered -> glut_SINGLE DoubleBuffered -> glut_DOUBLE WithAccumBuffer -> glut_ACCUM WithAlphaComponent -> glut_ALPHA WithDepthBuffer -> glut_DEPTH WithStencilBuffer -> glut_STENCIL Multisampling -> glut_MULTISAMPLE Stereoscopic -> glut_STEREO LuminanceMode -> glut_LUMINANCE | Controls the /initial display used when creating top - level windows , Note that ' ' selects the RGBA color model , but it does not request any applies to ' LuminanceMode ' . initialDisplayMode :: StateVar [DisplayMode] initialDisplayMode = makeStateVar getInitialDisplayMode setInitialDisplayMode getInitialDisplayMode :: IO [DisplayMode] getInitialDisplayMode = simpleGet i2dms glut_INIT_DISPLAY_MODE i2dms :: CInt -> [DisplayMode] i2dms bitfield = [ c | c <- [ RGBAMode, RGBMode, IndexMode, SingleBuffered, DoubleBuffered, WithAccumBuffer, WithAlphaComponent, WithDepthBuffer, WithStencilBuffer, Multisampling, Stereoscopic, LuminanceMode ] , (fromIntegral bitfield .&. marshalDisplayMode c) /= 0 ] setInitialDisplayMode :: [DisplayMode] -> IO () setInitialDisplayMode = glutInitDisplayMode . toBitfield marshalDisplayMode toBitfield :: (Bits b) => (a -> b) -> [a] -> b toBitfield marshal = foldl (.|.) 0 . map marshal foreign import CALLCONV unsafe "glutInitDisplayMode" glutInitDisplayMode :: CUInt -> IO () | Contains ' True ' if the /current display is supported , ' False ' displayModePossible :: GettableStateVar Bool displayModePossible = makeGettableStateVar $ simpleGet (/= 0) glut_DISPLAY_MODE_POSSIBLE of ' 's constructors . data DisplayCapability color buffer . Default is \"'IsAtLeast ' " for red , green , blue , and alpha capabilities , and \"'IsEqualTo ' " for the RGBA color model capability . buffer and zero bits of alpha color buffer precision . Default is \"'IsAtLeast ' " for the red , green , and blue capabilities , and ' @0@\ " for alpha capability , and \"'IsEqualTo ' " for the RGBA color \"'IsAtLeast ' " . \"'IsAtLeast ' " . \"'IsAtLeast ' " . color index . Default is \"'IsAtLeast ' " . is \"'IsAtLeast ' " . Default is \"'IsEqualTo ' " . buffered . Default is \"'IsEqualTo ' " . in bits . Default is \"'IsAtLeast ' " for red , green , bits and zero bits of alpha accumulation buffer precision . Default is \"'IsAtLeast ' " for red , green , and blue capabilities , and ' @0@\ " for the alpha \"'IsAtLeast ' " . is \"'IsAtLeast ' @12@\ " . ' " . that a GLUT application can request multisampling if OpenGL - style stereo . Default is \"'IsEqualTo ' " . ^ Number of bits of red in the RGBA and zero bits of green , Default is \"'IsAtLeast ' " for the red capabilitis , and \"'IsEqualTo ' @0@\ " for the green and blue capabilities , and \"'IsEqualTo ' " for the RGBA color model capability , and , for X11 , \"'IsEqualTo ' " for the ' XStaticGray ' capability . SGI InfiniteReality ( and other future machines ) support a 16 - bit luminance ( single channel ) display mode ( an additional 16 - bit alpha channel 16 - bit precision luminance display mode is often represents the Nth frame buffer configuration matching ' initialDisplayCapabilitiesString ' also returns the first ( best matching ) configuration . ' ' requires a relation conformant . Default is \"'IsEqualTo ' " . ^ Only recognized on GLUT implementations for , this ^ Only recongized on GLUT implementations for the X Window ^ Only recongized on GLUT implementations for the X Window configuration\ 's X visual is of type Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window configuration\ 's X visual is of type @PsuedoColor@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window configuration\ 's X visual is of type @TrueColor@. Default is \"'IsEqualTo ' " . ^ Only recongized on GLUT implementations for the X Window Default is \"'IsEqualTo ' " . deriving ( Eq, Ord, Show ) displayCapabilityToString :: DisplayCapability -> String displayCapabilityToString x = case x of DisplayRGBA -> "rgba" DisplayRGB -> "rgb" DisplayRed -> "red" DisplayGreen -> "green" DisplayBlue -> "blue" DisplayIndex -> "index" DisplayBuffer -> "buffer" DisplaySingle -> "single" DisplayDouble -> "double" DisplayAccA -> "acca" DisplayAcc -> "acc" DisplayAlpha -> "alpha" DisplayDepth -> "depth" DisplayStencil -> "stencil" DisplaySamples -> "samples" DisplayStereo -> "stereo" DisplayLuminance -> "luminance" DisplayNum -> "num" DisplayConformant -> "conformant" DisplaySlow -> "slow" DisplayWin32PFD -> "win32pfd" DisplayXVisual -> "xvisual" DisplayXStaticGray -> "xstaticgray" DisplayXGrayScale -> "xgrayscale" DisplayXStaticColor -> "xstaticcolor" DisplayXPseudoColor -> "xpseudocolor" DisplayXTrueColor -> "xtruecolor" DisplayXDirectColor -> "xdirectcolor" data DisplayCapabilityDescription = Where DisplayCapability Relation Int | With DisplayCapability deriving ( Eq, Ord, Show ) displayCapabilityDescriptionToString :: DisplayCapabilityDescription -> String displayCapabilityDescriptionToString (Where c r i) = displayCapabilityToString c ++ relationToString r ++ show i displayCapabilityDescriptionToString (With c) = displayCapabilityToString c | Controls the /initial display used when creating top - level windows , to - be - created window or overlay . It is described by a list of zero or more in strict left to right order of precdence . That is , the first specified criteria ( ' IsGreaterThan ' , ' IsLessThan ' , etc . ) . Exact criteria ( ' IsEqualTo ' , ' IsNotEqualTo ' ) must match exactly so precedence is not relevant . initialDisplayCapabilities $ = [ With , Where DisplayDepth IsAtLeast 16 , With DisplayDouble ] no bits of alpha ) , a depth buffer with at least 16 bits of precision but preferring more , multisampling if available , at least 2 bits of stencil initialDisplayCapabilities :: SettableStateVar [DisplayCapabilityDescription] initialDisplayCapabilities = makeSettableStateVar $ \caps -> withCString (concat . intersperse " " . map displayCapabilityDescriptionToString $ caps) glutInitDisplayString foreign import CALLCONV unsafe "glutInitDisplayString" glutInitDisplayString :: CString -> IO ()
9e3c67df49ca9b84df11558bd0c8bfe326a4e5811ca683f45b48bab1a3ee07dc
RefactoringTools/wrangler
refac_intro_new_var.erl
Copyright ( c ) 2010 , , %% 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 copyright holders nor the %% names of its contributors may be used to endoorse or promote products %% derived from this software without specific prior written permission. %% %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' %% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR %% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR %% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, %% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR %% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF %% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %% ============================================================================================ %% Refactoring: Introduce a new variable to represent an expression selected. %% %% Author contact: , %% %% ============================================================================================= %% ============================================================================================= @private -module(refac_intro_new_var). -export([intro_new_var/7, intro_new_var_eclipse/6, is_available_at/3]). -export([do_intro_new_var_in_fun/3]). -include("../include/wrangler_internal.hrl"). -spec is_available_at(filename(), pos(), pos()) -> boolean(). is_available_at(FileName, Start, End) -> {ok, {AnnAST, _Info}} = wrangler_ast_server:parse_annotate_file(FileName, true), case api_interface:pos_to_expr(AnnAST, Start, End) of {error, _} -> false; _Exp -> true end. %% ============================================================================================= %%-spec(intro_new_var/6::(filename(), pos(), pos(), string(), [dir()],atom(), integer()) -> %% {'ok', [filename()]}). intro_new_var(FileName, Start={_SLine,_SCol}, End={_ELine, _ECol}, NewVarName, SearchPaths, Editor, TabWidth) -> ?wrangler_io("\nCMD: ~p:intro_new_var(~p, {~p,~p}, {~p,~p}, ~p, ~p, ~p,~p).\n", [?MODULE, FileName, _SLine, _SCol, _ELine, _ECol, NewVarName, SearchPaths, Editor, TabWidth]), intro_new_var_1(FileName, Start, End, NewVarName, SearchPaths, TabWidth, Editor). %%-spec(intro_new_var_eclipse/6::(filename(), pos(), pos(), string(), [dir()], integer()) -> %% {ok, [{filename(), filename(), string()}]}). intro_new_var_eclipse(FileName, Start, End, NewVarName, SearchPaths, TabWidth) -> intro_new_var_1(FileName, Start, End, NewVarName, SearchPaths, TabWidth, eclipse). intro_new_var_1(FileName, Start = {Line, Col}, End = {Line1, Col1}, NewVarName0, SearchPaths, TabWidth, Editor) -> Cmd = "CMD: " ++ atom_to_list(?MODULE) ++ ":intro_new_var(" ++ "\"" ++ FileName ++ "\", {" ++ integer_to_list(Line) ++ ", " ++ integer_to_list(Col) ++ "}," ++ "{" ++ integer_to_list(Line1) ++ ", " ++ integer_to_list(Col1) ++ "}," ++ "\"" ++ NewVarName0 ++ "\"," ++ integer_to_list(TabWidth) ++ " " ++ atom_to_list(Editor)++ ").", case api_refac:is_var_name(NewVarName0) of true -> ok; false -> throw({error, "Invalid new variable name."}) end, NewVarName = list_to_atom(NewVarName0), {ok, {AnnAST, _Info}} = wrangler_ast_server:parse_annotate_file(FileName, true, SearchPaths, TabWidth), case api_interface:pos_to_expr(AnnAST, Start, End) of {ok, Exp} -> Exp; {error, _} -> throw({error, "You have not selected an expression, " "or the function containing the expression does not parse."}), Exp = none end, case api_interface:expr_to_fun(AnnAST, Exp) of {ok, Fun} -> Fun; {error, _} -> throw({error, "You have not selected an expression within a function."}), Fun = none end, ok = cond_check(Fun, Exp, NewVarName), intro_new_var_1(FileName, AnnAST, Fun, Exp, NewVarName, Editor, TabWidth, Cmd). intro_new_var_1(FileName, AnnAST, Fun, Expr, NewVarName, Editor, TabWidth, Cmd) -> AnnAST1 = do_intro_new_var(AnnAST, Fun, Expr, NewVarName), Res = [{{FileName, FileName}, AnnAST1}], wrangler_write_file:write_refactored_files(Res, Editor, TabWidth, Cmd). cond_check(Form, Expr, NewVarName) -> ok=variable_replaceable(Expr), {Body, Statement} = get_inmost_enclosing_body_expr(Form, Expr), ExprFVs = api_refac:free_vars(Expr), SEnvs = api_refac:env_vars(Statement), Vs = [V||{V, Loc}<-ExprFVs--SEnvs, Loc/={0,0}], case Vs of [] -> ok; _ -> Msg = io_lib:format("The exprssion selected contains locally " "declared variables(s) ~p.", [Vs]), throw({error, lists:flatten(Msg)}) end, BodyBdVars = get_bound_vars(wrangler_syntax:block_expr(Body)), ExistingVars = element(1, lists:unzip(BodyBdVars ++ SEnvs)), case lists:member(NewVarName, ExistingVars) of true -> throw({error, "The new variable name conflicts with, or shadows, " "existing variable declarations."}); false -> ok end. variable_replaceable(Exp) -> Ann = wrangler_syntax:get_ann(Exp), case lists:keysearch(category, 1, Ann) of {value, {category, guard_expression}} -> throw({error, "Introducing a variable in a guard expression is not supported."}); _ -> ok end. get_bound_vars(Tree) -> F = fun (T, B) -> As = wrangler_syntax:get_ann(T), case lists:keysearch(bound, 1, As) of {value, {bound, BdVars1}} -> BdVars1++B; _ -> B end end, lists:usort(api_ast_traverse:fold(F, [], Tree)). do_intro_new_var(AnnAST, FunForm, Expr, NewVarName) -> NewFun = do_intro_new_var_in_fun(FunForm, Expr, NewVarName), Forms = wrangler_syntax:form_list_elements(AnnAST), Fun = fun (Form) -> case wrangler_syntax:type(Form) of function -> FormPos = wrangler_syntax:get_pos(Form), FunFormPos = wrangler_syntax:get_pos(FunForm), case FormPos == FunFormPos of true -> NewFun; false -> Form end; _ -> Form end end, wrangler_syntax:form_list([Fun(Form) || Form <- Forms]). do_intro_new_var_in_fun(Fun, Expr, NewVarName) -> Body = get_inmost_enclosing_clause(Fun, Expr), {NewFun1, _} = api_ast_traverse:stop_tdTP( fun insert_and_replace/2, Fun, {Body, Expr, NewVarName}), NewFun1. insert_and_replace(Node, {InMostClauseExpr, Expr, NewVarName}) -> case Node of InMostClauseExpr -> {do_insert_and_replace(Node, Expr, NewVarName), true}; _ -> {Node, false} end. do_insert_and_replace(Node, Expr, NewVarName) -> MatchExpr = make_match_expr(Expr, NewVarName), ExprPos = wrangler_syntax:get_pos(Expr), Body = case wrangler_syntax:type(Node) of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, Fun = fun (ExprStatement) -> Range = wrangler_misc:get_start_end_loc_with_comment(ExprStatement), NewExpr=wrangler_syntax:copy_pos(ExprStatement, wrangler_misc:update_ann(MatchExpr, {range, Range})), {ExprStatement1, _} = replace_expr_with_var(Expr, NewVarName, ExprStatement), [NewExpr, ExprStatement1] end, {Body1, Body2} = lists:splitwith( fun(E) -> {Start, End} = wrangler_misc:start_end_loc(E), not (Start=<ExprPos andalso ExprPos=<End) end, Body), NewBody =case Body2 of [] -> Body1; [B|Bs] -> [B1,B2] = Fun(B), case wrangler_syntax:type(B2) == variable andalso Bs /= [] of true -> Body1++[B1|Bs]; false -> case {lists:reverse(Body1), Bs} of {[], []} -> [B1,wrangler_syntax:add_ann({layout, vertical}, B2)]; {[], [B3|Bs1]} -> {{BL, _}, _} = wrangler_misc:start_end_loc(B), {{B3L, _},_} = wrangler_misc:start_end_loc(B3), case BL==B3L of true -> B21=wrangler_syntax:add_ann({layout, horizontal}, B2), B31=wrangler_syntax:add_ann({layout, horizontal}, B3), [B1, B21, B31|Bs1]; false -> B21=wrangler_syntax:add_ann({layout, vertical}, B2), B31=wrangler_syntax:add_ann({layout, vertical}, B3), [B1, B21, B31|Bs1] end; {[B0|_], []} -> {{B0L, _},_} =wrangler_misc:start_end_loc(B0), {{BL, _}, _} = wrangler_misc:start_end_loc(B), case B0L==BL of true -> B21=wrangler_syntax:add_ann({layout, horizontal}, B2), Body1 ++ [B1,B21]; false-> B21=wrangler_syntax:add_ann({layout, vertical}, B2), Body1++[B1, B21] end; {[B0|_], [B3|Bs1]} -> {{B0L, _},_} =wrangler_misc:start_end_loc(B0), {{BL, _}, _} = wrangler_misc:start_end_loc(B), B21= case B0L==BL of true -> wrangler_syntax:add_ann({layout, horizontal}, B2); false-> wrangler_syntax:add_ann({layout, vertical}, B2) end, {{B3L, _},_} = wrangler_misc:start_end_loc(B3), case BL==B3L of true -> B31=wrangler_syntax:add_ann({layout, horizontal}, B3), Body1++[B1, B21, B31|Bs1]; false -> B31=wrangler_syntax:add_ann({layout, vertical}, B3), Body1++[B1, B21, B31|Bs1] end end end end, case wrangler_syntax:type(Node) of clause -> Pat = wrangler_syntax:clause_patterns(Node), Guard = wrangler_syntax:clause_guard(Node), wrangler_misc:rewrite(Node, wrangler_syntax:clause (Pat, Guard, NewBody)); block_expr -> wrangler_misc:rewrite(Node,wrangler_syntax:block_expr(NewBody)); try_expr -> C = wrangler_syntax:try_expr_clauses(Node), H = wrangler_syntax:try_expr_handlers(Node), A = wrangler_syntax:try_expr_after(Node), wrangler_misc:rewrite(Node,wrangler_syntax:try_expr(NewBody, C, H, A)) end. replace_expr_with_var(Expr, NewVarName, ExprStatement) -> api_ast_traverse:stop_tdTP(fun do_replace_expr_with_var/2, ExprStatement, {Expr, NewVarName}). do_replace_expr_with_var(Node, {Expr, NewVarName}) -> case Node of Expr -> NewVarExpr = wrangler_misc:rewrite( Expr,wrangler_syntax:variable(NewVarName)), {NewVarExpr, true}; _ -> {Node, false} end. make_match_expr(Expr, NewVarName) -> Pat = wrangler_syntax:variable(NewVarName), PreComs = wrangler_syntax:get_precomments(Expr), PostComs=wrangler_syntax:get_postcomments(Expr), Expr1=wrangler_syntax:set_precomments(wrangler_syntax:set_postcomments(Expr, []),[]), MatchExpr=wrangler_syntax:match_expr(Pat, Expr1), wrangler_syntax:set_precomments(wrangler_syntax:set_postcomments(MatchExpr, PostComs), PreComs). get_inmost_enclosing_clause(Form, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (Node, S) -> Type = wrangler_syntax:type(Node), case lists:member(Type, [clause, block_expr, try_expr]) of true -> Body = case Type of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, {Start, _End} = wrangler_misc:start_end_loc(hd(Body)), {_, End} = wrangler_misc:start_end_loc(lists:last(Body)), case Start =< ExprPos andalso ExprPos =< End of true -> [{Node, End}| S]; _ -> S end; _ -> S end end, Res = lists:keysort(2, api_ast_traverse:fold(Fun, [], Form)), case Res of [{Node, _}| _] -> Node; _ -> throw({error, "Wrangler internal error."}) end. get_inmost_enclosing_body_expr(Form, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (Node, S) -> Type = wrangler_syntax:type(Node), case lists:member(Type, [clause, block_expr, try_expr]) of true -> Body = case Type of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, {Start, _End} = wrangler_misc:start_end_loc(hd(Body)), {_, End} = wrangler_misc:start_end_loc(lists:last(Body)), case Start =< ExprPos andalso ExprPos =< End of true -> EnclosingExpr = get_enclosing_expr(Body, Expr), [{Body, End, EnclosingExpr}| S]; _ -> S end; _ -> S end end, Res = lists:keysort(2, api_ast_traverse:fold(Fun, [], Form)), case Res of [{Body, _, E}| _] -> {Body, E}; _ -> throw({error, "Wrangler failed to perform this refactoring."}) end. get_enclosing_expr(Body, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (ExprStatement) -> {Start, End} = wrangler_misc:start_end_loc(ExprStatement), case Start =< ExprPos andalso ExprPos =< End of true -> [ExprStatement]; false -> [] end end, hd(lists:append([Fun(B) || B <- Body])).
null
https://raw.githubusercontent.com/RefactoringTools/wrangler/7f4c120e4bf06a39d8762caa60b4c88ef03086b0/src/refac_intro_new_var.erl
erlang
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 copyright holders nor the names of its contributors may be used to endoorse 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 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================================ Refactoring: Introduce a new variable to represent an expression selected. Author contact: , ============================================================================================= ============================================================================================= ============================================================================================= -spec(intro_new_var/6::(filename(), pos(), pos(), string(), [dir()],atom(), integer()) -> {'ok', [filename()]}). -spec(intro_new_var_eclipse/6::(filename(), pos(), pos(), string(), [dir()], integer()) -> {ok, [{filename(), filename(), string()}]}).
Copyright ( c ) 2010 , , IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR @private -module(refac_intro_new_var). -export([intro_new_var/7, intro_new_var_eclipse/6, is_available_at/3]). -export([do_intro_new_var_in_fun/3]). -include("../include/wrangler_internal.hrl"). -spec is_available_at(filename(), pos(), pos()) -> boolean(). is_available_at(FileName, Start, End) -> {ok, {AnnAST, _Info}} = wrangler_ast_server:parse_annotate_file(FileName, true), case api_interface:pos_to_expr(AnnAST, Start, End) of {error, _} -> false; _Exp -> true end. intro_new_var(FileName, Start={_SLine,_SCol}, End={_ELine, _ECol}, NewVarName, SearchPaths, Editor, TabWidth) -> ?wrangler_io("\nCMD: ~p:intro_new_var(~p, {~p,~p}, {~p,~p}, ~p, ~p, ~p,~p).\n", [?MODULE, FileName, _SLine, _SCol, _ELine, _ECol, NewVarName, SearchPaths, Editor, TabWidth]), intro_new_var_1(FileName, Start, End, NewVarName, SearchPaths, TabWidth, Editor). intro_new_var_eclipse(FileName, Start, End, NewVarName, SearchPaths, TabWidth) -> intro_new_var_1(FileName, Start, End, NewVarName, SearchPaths, TabWidth, eclipse). intro_new_var_1(FileName, Start = {Line, Col}, End = {Line1, Col1}, NewVarName0, SearchPaths, TabWidth, Editor) -> Cmd = "CMD: " ++ atom_to_list(?MODULE) ++ ":intro_new_var(" ++ "\"" ++ FileName ++ "\", {" ++ integer_to_list(Line) ++ ", " ++ integer_to_list(Col) ++ "}," ++ "{" ++ integer_to_list(Line1) ++ ", " ++ integer_to_list(Col1) ++ "}," ++ "\"" ++ NewVarName0 ++ "\"," ++ integer_to_list(TabWidth) ++ " " ++ atom_to_list(Editor)++ ").", case api_refac:is_var_name(NewVarName0) of true -> ok; false -> throw({error, "Invalid new variable name."}) end, NewVarName = list_to_atom(NewVarName0), {ok, {AnnAST, _Info}} = wrangler_ast_server:parse_annotate_file(FileName, true, SearchPaths, TabWidth), case api_interface:pos_to_expr(AnnAST, Start, End) of {ok, Exp} -> Exp; {error, _} -> throw({error, "You have not selected an expression, " "or the function containing the expression does not parse."}), Exp = none end, case api_interface:expr_to_fun(AnnAST, Exp) of {ok, Fun} -> Fun; {error, _} -> throw({error, "You have not selected an expression within a function."}), Fun = none end, ok = cond_check(Fun, Exp, NewVarName), intro_new_var_1(FileName, AnnAST, Fun, Exp, NewVarName, Editor, TabWidth, Cmd). intro_new_var_1(FileName, AnnAST, Fun, Expr, NewVarName, Editor, TabWidth, Cmd) -> AnnAST1 = do_intro_new_var(AnnAST, Fun, Expr, NewVarName), Res = [{{FileName, FileName}, AnnAST1}], wrangler_write_file:write_refactored_files(Res, Editor, TabWidth, Cmd). cond_check(Form, Expr, NewVarName) -> ok=variable_replaceable(Expr), {Body, Statement} = get_inmost_enclosing_body_expr(Form, Expr), ExprFVs = api_refac:free_vars(Expr), SEnvs = api_refac:env_vars(Statement), Vs = [V||{V, Loc}<-ExprFVs--SEnvs, Loc/={0,0}], case Vs of [] -> ok; _ -> Msg = io_lib:format("The exprssion selected contains locally " "declared variables(s) ~p.", [Vs]), throw({error, lists:flatten(Msg)}) end, BodyBdVars = get_bound_vars(wrangler_syntax:block_expr(Body)), ExistingVars = element(1, lists:unzip(BodyBdVars ++ SEnvs)), case lists:member(NewVarName, ExistingVars) of true -> throw({error, "The new variable name conflicts with, or shadows, " "existing variable declarations."}); false -> ok end. variable_replaceable(Exp) -> Ann = wrangler_syntax:get_ann(Exp), case lists:keysearch(category, 1, Ann) of {value, {category, guard_expression}} -> throw({error, "Introducing a variable in a guard expression is not supported."}); _ -> ok end. get_bound_vars(Tree) -> F = fun (T, B) -> As = wrangler_syntax:get_ann(T), case lists:keysearch(bound, 1, As) of {value, {bound, BdVars1}} -> BdVars1++B; _ -> B end end, lists:usort(api_ast_traverse:fold(F, [], Tree)). do_intro_new_var(AnnAST, FunForm, Expr, NewVarName) -> NewFun = do_intro_new_var_in_fun(FunForm, Expr, NewVarName), Forms = wrangler_syntax:form_list_elements(AnnAST), Fun = fun (Form) -> case wrangler_syntax:type(Form) of function -> FormPos = wrangler_syntax:get_pos(Form), FunFormPos = wrangler_syntax:get_pos(FunForm), case FormPos == FunFormPos of true -> NewFun; false -> Form end; _ -> Form end end, wrangler_syntax:form_list([Fun(Form) || Form <- Forms]). do_intro_new_var_in_fun(Fun, Expr, NewVarName) -> Body = get_inmost_enclosing_clause(Fun, Expr), {NewFun1, _} = api_ast_traverse:stop_tdTP( fun insert_and_replace/2, Fun, {Body, Expr, NewVarName}), NewFun1. insert_and_replace(Node, {InMostClauseExpr, Expr, NewVarName}) -> case Node of InMostClauseExpr -> {do_insert_and_replace(Node, Expr, NewVarName), true}; _ -> {Node, false} end. do_insert_and_replace(Node, Expr, NewVarName) -> MatchExpr = make_match_expr(Expr, NewVarName), ExprPos = wrangler_syntax:get_pos(Expr), Body = case wrangler_syntax:type(Node) of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, Fun = fun (ExprStatement) -> Range = wrangler_misc:get_start_end_loc_with_comment(ExprStatement), NewExpr=wrangler_syntax:copy_pos(ExprStatement, wrangler_misc:update_ann(MatchExpr, {range, Range})), {ExprStatement1, _} = replace_expr_with_var(Expr, NewVarName, ExprStatement), [NewExpr, ExprStatement1] end, {Body1, Body2} = lists:splitwith( fun(E) -> {Start, End} = wrangler_misc:start_end_loc(E), not (Start=<ExprPos andalso ExprPos=<End) end, Body), NewBody =case Body2 of [] -> Body1; [B|Bs] -> [B1,B2] = Fun(B), case wrangler_syntax:type(B2) == variable andalso Bs /= [] of true -> Body1++[B1|Bs]; false -> case {lists:reverse(Body1), Bs} of {[], []} -> [B1,wrangler_syntax:add_ann({layout, vertical}, B2)]; {[], [B3|Bs1]} -> {{BL, _}, _} = wrangler_misc:start_end_loc(B), {{B3L, _},_} = wrangler_misc:start_end_loc(B3), case BL==B3L of true -> B21=wrangler_syntax:add_ann({layout, horizontal}, B2), B31=wrangler_syntax:add_ann({layout, horizontal}, B3), [B1, B21, B31|Bs1]; false -> B21=wrangler_syntax:add_ann({layout, vertical}, B2), B31=wrangler_syntax:add_ann({layout, vertical}, B3), [B1, B21, B31|Bs1] end; {[B0|_], []} -> {{B0L, _},_} =wrangler_misc:start_end_loc(B0), {{BL, _}, _} = wrangler_misc:start_end_loc(B), case B0L==BL of true -> B21=wrangler_syntax:add_ann({layout, horizontal}, B2), Body1 ++ [B1,B21]; false-> B21=wrangler_syntax:add_ann({layout, vertical}, B2), Body1++[B1, B21] end; {[B0|_], [B3|Bs1]} -> {{B0L, _},_} =wrangler_misc:start_end_loc(B0), {{BL, _}, _} = wrangler_misc:start_end_loc(B), B21= case B0L==BL of true -> wrangler_syntax:add_ann({layout, horizontal}, B2); false-> wrangler_syntax:add_ann({layout, vertical}, B2) end, {{B3L, _},_} = wrangler_misc:start_end_loc(B3), case BL==B3L of true -> B31=wrangler_syntax:add_ann({layout, horizontal}, B3), Body1++[B1, B21, B31|Bs1]; false -> B31=wrangler_syntax:add_ann({layout, vertical}, B3), Body1++[B1, B21, B31|Bs1] end end end end, case wrangler_syntax:type(Node) of clause -> Pat = wrangler_syntax:clause_patterns(Node), Guard = wrangler_syntax:clause_guard(Node), wrangler_misc:rewrite(Node, wrangler_syntax:clause (Pat, Guard, NewBody)); block_expr -> wrangler_misc:rewrite(Node,wrangler_syntax:block_expr(NewBody)); try_expr -> C = wrangler_syntax:try_expr_clauses(Node), H = wrangler_syntax:try_expr_handlers(Node), A = wrangler_syntax:try_expr_after(Node), wrangler_misc:rewrite(Node,wrangler_syntax:try_expr(NewBody, C, H, A)) end. replace_expr_with_var(Expr, NewVarName, ExprStatement) -> api_ast_traverse:stop_tdTP(fun do_replace_expr_with_var/2, ExprStatement, {Expr, NewVarName}). do_replace_expr_with_var(Node, {Expr, NewVarName}) -> case Node of Expr -> NewVarExpr = wrangler_misc:rewrite( Expr,wrangler_syntax:variable(NewVarName)), {NewVarExpr, true}; _ -> {Node, false} end. make_match_expr(Expr, NewVarName) -> Pat = wrangler_syntax:variable(NewVarName), PreComs = wrangler_syntax:get_precomments(Expr), PostComs=wrangler_syntax:get_postcomments(Expr), Expr1=wrangler_syntax:set_precomments(wrangler_syntax:set_postcomments(Expr, []),[]), MatchExpr=wrangler_syntax:match_expr(Pat, Expr1), wrangler_syntax:set_precomments(wrangler_syntax:set_postcomments(MatchExpr, PostComs), PreComs). get_inmost_enclosing_clause(Form, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (Node, S) -> Type = wrangler_syntax:type(Node), case lists:member(Type, [clause, block_expr, try_expr]) of true -> Body = case Type of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, {Start, _End} = wrangler_misc:start_end_loc(hd(Body)), {_, End} = wrangler_misc:start_end_loc(lists:last(Body)), case Start =< ExprPos andalso ExprPos =< End of true -> [{Node, End}| S]; _ -> S end; _ -> S end end, Res = lists:keysort(2, api_ast_traverse:fold(Fun, [], Form)), case Res of [{Node, _}| _] -> Node; _ -> throw({error, "Wrangler internal error."}) end. get_inmost_enclosing_body_expr(Form, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (Node, S) -> Type = wrangler_syntax:type(Node), case lists:member(Type, [clause, block_expr, try_expr]) of true -> Body = case Type of clause -> wrangler_syntax:clause_body(Node); block_expr -> wrangler_syntax:block_expr_body(Node); try_expr -> wrangler_syntax:try_expr_body(Node) end, {Start, _End} = wrangler_misc:start_end_loc(hd(Body)), {_, End} = wrangler_misc:start_end_loc(lists:last(Body)), case Start =< ExprPos andalso ExprPos =< End of true -> EnclosingExpr = get_enclosing_expr(Body, Expr), [{Body, End, EnclosingExpr}| S]; _ -> S end; _ -> S end end, Res = lists:keysort(2, api_ast_traverse:fold(Fun, [], Form)), case Res of [{Body, _, E}| _] -> {Body, E}; _ -> throw({error, "Wrangler failed to perform this refactoring."}) end. get_enclosing_expr(Body, Expr) -> ExprPos = wrangler_syntax:get_pos(Expr), Fun = fun (ExprStatement) -> {Start, End} = wrangler_misc:start_end_loc(ExprStatement), case Start =< ExprPos andalso ExprPos =< End of true -> [ExprStatement]; false -> [] end end, hd(lists:append([Fun(B) || B <- Body])).
f0e300be03fe3204cf42ab392166ef5ffcd1a16f8ed48fa7fdfb6510809a47e8
apache/couchdb-rebar
protobuffs_compile.erl
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- %% ex: ts=4 sw=4 et %% ------------------------------------------------------------------- %% rebar : Erlang Build Tools %% Copyright ( c ) 2015 ( ) %% %% 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. %% ------------------------------------------------------------------- -module(protobuffs_compile). -export([scan_file/2]). Simulate protobuffs compiling some proto files , %% but generate only enough of what's needed for testing -- dummy stuff only. scan_file(Proto, _Opts) -> ProtoBase = filename:basename(Proto, ".proto"), ModBase = ProtoBase ++ "_pb", BeamDest = filename:join(get_beam_outdir(), ModBase ++ ".beam"), HrlDest = filename:join(get_hrl_outdir(), ModBase ++ ".hrl"), ok = file:write_file(BeamDest, beam_text(ModBase)), ok = file:write_file(HrlDest, hrl_text(ModBase)). beam_text(ModBase) -> Mod = list_to_atom(ModBase), Forms = [mk_attr(module, Mod)], % just a -module(...). line {ok, Mod, Bin} = compile:forms(Forms), Bin. mk_attr(AttrName, AttrValue) -> erl_syntax:revert( erl_syntax:attribute(erl_syntax:atom(AttrName), [erl_syntax:abstract(AttrValue)])). hrl_text(ModBase) -> io_lib:format( lines(["-ifndef(~s_hrl).", "-define(~s_hrl, true).", "", "%% some record definitions would normally go here...", "" "-endif. %% ~s_hrl"]), [ModBase, ModBase, ModBase]). get_beam_outdir() -> ".". get_hrl_outdir() -> ".". lines(Lines) -> lists:flatten([[L, $\n] || L <- Lines]).
null
https://raw.githubusercontent.com/apache/couchdb-rebar/8578221c20d0caa3deb724e5622a924045ffa8bf/inttest/proto_protobuffs/mock/protobuffs/src/protobuffs_compile.erl
erlang
ex: ts=4 sw=4 et ------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------- but generate only enough of what's needed for testing -- dummy stuff only. just a -module(...). line
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- rebar : Erlang Build Tools Copyright ( c ) 2015 ( ) in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , -module(protobuffs_compile). -export([scan_file/2]). Simulate protobuffs compiling some proto files , scan_file(Proto, _Opts) -> ProtoBase = filename:basename(Proto, ".proto"), ModBase = ProtoBase ++ "_pb", BeamDest = filename:join(get_beam_outdir(), ModBase ++ ".beam"), HrlDest = filename:join(get_hrl_outdir(), ModBase ++ ".hrl"), ok = file:write_file(BeamDest, beam_text(ModBase)), ok = file:write_file(HrlDest, hrl_text(ModBase)). beam_text(ModBase) -> Mod = list_to_atom(ModBase), {ok, Mod, Bin} = compile:forms(Forms), Bin. mk_attr(AttrName, AttrValue) -> erl_syntax:revert( erl_syntax:attribute(erl_syntax:atom(AttrName), [erl_syntax:abstract(AttrValue)])). hrl_text(ModBase) -> io_lib:format( lines(["-ifndef(~s_hrl).", "-define(~s_hrl, true).", "", "%% some record definitions would normally go here...", "" "-endif. %% ~s_hrl"]), [ModBase, ModBase, ModBase]). get_beam_outdir() -> ".". get_hrl_outdir() -> ".". lines(Lines) -> lists:flatten([[L, $\n] || L <- Lines]).
d32cfd042eccde9457d44add41b1eeb9a0ccea391ff99eff2646ea528735e394
anmonteiro/lumo
preload.cljs
(ns preloads-test.preload) (def preload-var :foo)
null
https://raw.githubusercontent.com/anmonteiro/lumo/6709c9f1b7b342c8108e6ed6e034e19dc786f00b/src/test/cljs/preloads_test/preload.cljs
clojure
(ns preloads-test.preload) (def preload-var :foo)
de92d0e4a40b0be83e386497d459ae01ad5581ca7bc621dea8a80faa0428bfd2
ekmett/haskell
Evaluation.hs
{-# Language CPP #-} {-# Language LambdaCase #-} {-# Language BlockArguments #-} {-# Language ScopedTypeVariables #-} {-# Language BangPatterns #-} -- | Copyright : ( c ) 2020 , 2020 License : BSD-2 - Clause OR Apache-2.0 Maintainer : < > -- Stability : experimental -- Portability: non-portable QLF.Elaborate . Evaluation module Elaborate.Evaluation where import Common.Icit #ifdef FCIF import Common.Names #endif import Data.Functor ((<&>)) import Elaborate.Term import Elaborate.Value import GHC.IO.Unsafe valsLen :: Vals -> Int valsLen = go 0 where go !acc VNil = acc go acc (VDef vs _) = go (acc + 1) vs go acc (VSkip vs) = go (acc + 1) vs -- eval evalVar :: Ix -> Vals -> Val evalVar 0 (VDef _ v) = v evalVar 0 (VSkip vs) = VVar (valsLen vs) evalVar x (VDef vs _) = evalVar (x - 1) vs evalVar x (VSkip vs) = evalVar (x - 1) vs evalVar _ _ = panic evalMeta :: Meta -> IO Val evalMeta m = readMeta m <&> \case Unsolved{} -> VMeta m Solved v -> v #ifdef FCIF _ -> panic #endif #ifdef FCIF evalCar :: Val -> IO Val evalCar (VTcons t _) = pure t evalCar (VNe h sp) = pure $ VNe h (SCar sp) evalCar (VLamTel x a t) = evalLamTel pure x a t >>= evalCar evalCar _ = panic evalCdr :: Val -> IO Val evalCdr (VTcons _ u) = pure u evalCdr (VNe h sp) = pure $ VNe h (SCdr sp) evalCdr (VLamTel x a t) = evalLamTel pure x a t >>= evalCdr evalCdr _ = panic evalPiTel :: EVal -> Name -> VTy -> EVal -> IO Val evalPiTel k x a0 b = force a0 >>= \case VTNil -> b VTnil >>= k VTCons _ a as -> pure let (x',x'') = splitName x in VPi x' Implicit a \ ~x1 -> do ~x1v <- as x1 evalPiTel pure x'' x1v \ ~x2 -> b (VTcons x1 x2) a -> pure $ VPiTel x a b evalLamTel :: EVal -> Name -> VTy -> EVal -> IO Val evalLamTel k x a0 t = force a0 >>= \case VTNil -> t VTnil >>= k VTCons _ a as -> pure let (x',x'') = splitName x in VLam x' Implicit a \ ~x1 -> do ~x1v <- as x1 evalLamTel pure x'' x1v \ ~x2 -> t (VTcons x1 x2) a -> pure $ VLamTel x a t evalAppTel :: VTy -> Val -> Val -> IO Val evalAppTel a0 t u = force a0 >>= \case VTNil -> pure t VTCons _ _ as -> do u1 <- evalCar u u1v <- as u1 u2 <- evalCdr u t' <- evalApp Implicit t u1 evalAppTel u1v t' u2 a -> case t of VNe h sp -> pure $ VNe h (SAppTel a sp u) VLamTel _ _ t' -> t' u _ -> panic #endif evalApp :: Icit -> Val -> Val -> IO Val evalApp _ (VLam _ _ _ t) u = t u evalApp i (VNe h sp) u = pure $ VNe h (SApp i sp u) #ifdef FCIF evalApp i (VLamTel x a t) u = do y <- evalLamTel pure x a t evalApp i y u #endif evalApp _ _ _ = panic evalAppSp :: Val -> Spine -> IO Val evalAppSp h = go where go SNil = pure h go (SApp i sp u) = do sp' <- go sp; evalApp i sp' u #ifdef FCIF go (SAppTel a sp u) = do sp' <- go sp; evalAppTel a sp' u go (SCar sp) = go sp >>= evalCar go (SCdr sp) = go sp >>= evalCdr #endif force :: Val -> IO Val force = \case v0@(VNe (HMeta m) sp) -> readMeta m >>= \case Unsolved{} -> pure v0 Solved v -> evalAppSp v sp >>= force #ifdef FCIF _ -> panic VPiTel x a b -> evalPiTel force x a b VLamTel x a t -> evalLamTel force x a t #endif v -> pure v forceSp :: Spine -> IO Spine forceSp sp = This is a cheeky hack , the point is that ( VVar ( -1 ) ) blocks computation , and -- we get back the new spine. We use (-1) in order to make the hack clear in -- potential debugging situations. evalAppSp (VVar (-1)) sp >>= \case VNe _ sp' -> pure sp' _ -> panic eval :: Vals -> TM -> IO Val eval vs = go where go = \case Var x -> pure $ evalVar x vs Let _ _ t u -> go t >>= goBind u U -> pure VU Meta m -> evalMeta m Pi x i a b -> unsafeInterleaveIO (go a) <&> \a' -> VPi x i a' (goBind b) Lam x i a t -> unsafeInterleaveIO (go a) <&> \a' -> VLam x i a' (goBind t) App i t u -> do t' <- unsafeInterleaveIO (go t) u' <- unsafeInterleaveIO (go u) evalApp i t' u' #ifdef FCIF Tel -> pure VTel TNil -> pure VTNil TCons x a b -> unsafeInterleaveIO (go a) <&> \a' -> VTCons x a' (goBind b) Rec a -> VRec <$> go a Tnil -> pure VTnil Tcons t u -> VTcons <$> unsafeInterleaveIO (go t) <*> unsafeInterleaveIO (go u) Car t -> go t >>= evalCar Cdr t -> go t >>= evalCdr PiTel x a b -> do a' <- unsafeInterleaveIO (go a) evalPiTel pure x a' (goBind b) AppTel a t u -> do a' <- unsafeInterleaveIO (go a) t' <- unsafeInterleaveIO (go t) u' <- unsafeInterleaveIO (go u) evalAppTel a' t' u' LamTel x a t -> do a' <- unsafeInterleaveIO (go a) evalLamTel pure x a' (goBind t) #endif Skip t -> eval (VSkip vs) t goBind t x = eval (VDef vs x) t uneval :: Lvl -> Val -> IO TM uneval d = go where go v = force v >>= \case VNe h sp0 -> let goSp SNil = case h of HMeta m -> pure $ Meta m HVar x -> pure $ Var (d - x - 1) goSp (SApp i sp u) = App i <$> goSp sp <*> go u #ifdef FCIF goSp (SAppTel a sp u) = AppTel <$> go a <*> goSp sp <*> go u goSp (SCar sp) = Car <$> goSp sp goSp (SCdr sp) = Cdr <$> goSp sp #endif in forceSp sp0 >>= goSp VLam x i a t -> Lam x i <$> go a <*> goBind t VPi x i a b -> Pi x i <$> go a <*> goBind b VU -> pure U #ifdef FCIF VTel -> pure Tel VRec a -> Rec <$> go a VTNil -> pure TNil VTCons x a as -> TCons x <$> go a <*> goBind as VTnil -> pure Tnil VTcons t u -> Tcons <$> go t <*> go u VPiTel x a b -> PiTel x <$> go a <*> goBind b VLamTel x a t -> LamTel x <$> go a <*> goBind t #endif goBind t = t (VVar d) >>= uneval (d + 1) nf :: Vals -> TM -> IO TM nf vs t = do v <- eval vs t uneval 0 v {-# inline nf #-}
null
https://raw.githubusercontent.com/ekmett/haskell/37ad048531f5a3a13c6dfbf4772ee4325f0e4458/ulf/src/Elaborate/Evaluation.hs
haskell
# Language CPP # # Language LambdaCase # # Language BlockArguments # # Language ScopedTypeVariables # # Language BangPatterns # | Stability : experimental Portability: non-portable eval we get back the new spine. We use (-1) in order to make the hack clear in potential debugging situations. # inline nf #
Copyright : ( c ) 2020 , 2020 License : BSD-2 - Clause OR Apache-2.0 Maintainer : < > QLF.Elaborate . Evaluation module Elaborate.Evaluation where import Common.Icit #ifdef FCIF import Common.Names #endif import Data.Functor ((<&>)) import Elaborate.Term import Elaborate.Value import GHC.IO.Unsafe valsLen :: Vals -> Int valsLen = go 0 where go !acc VNil = acc go acc (VDef vs _) = go (acc + 1) vs go acc (VSkip vs) = go (acc + 1) vs evalVar :: Ix -> Vals -> Val evalVar 0 (VDef _ v) = v evalVar 0 (VSkip vs) = VVar (valsLen vs) evalVar x (VDef vs _) = evalVar (x - 1) vs evalVar x (VSkip vs) = evalVar (x - 1) vs evalVar _ _ = panic evalMeta :: Meta -> IO Val evalMeta m = readMeta m <&> \case Unsolved{} -> VMeta m Solved v -> v #ifdef FCIF _ -> panic #endif #ifdef FCIF evalCar :: Val -> IO Val evalCar (VTcons t _) = pure t evalCar (VNe h sp) = pure $ VNe h (SCar sp) evalCar (VLamTel x a t) = evalLamTel pure x a t >>= evalCar evalCar _ = panic evalCdr :: Val -> IO Val evalCdr (VTcons _ u) = pure u evalCdr (VNe h sp) = pure $ VNe h (SCdr sp) evalCdr (VLamTel x a t) = evalLamTel pure x a t >>= evalCdr evalCdr _ = panic evalPiTel :: EVal -> Name -> VTy -> EVal -> IO Val evalPiTel k x a0 b = force a0 >>= \case VTNil -> b VTnil >>= k VTCons _ a as -> pure let (x',x'') = splitName x in VPi x' Implicit a \ ~x1 -> do ~x1v <- as x1 evalPiTel pure x'' x1v \ ~x2 -> b (VTcons x1 x2) a -> pure $ VPiTel x a b evalLamTel :: EVal -> Name -> VTy -> EVal -> IO Val evalLamTel k x a0 t = force a0 >>= \case VTNil -> t VTnil >>= k VTCons _ a as -> pure let (x',x'') = splitName x in VLam x' Implicit a \ ~x1 -> do ~x1v <- as x1 evalLamTel pure x'' x1v \ ~x2 -> t (VTcons x1 x2) a -> pure $ VLamTel x a t evalAppTel :: VTy -> Val -> Val -> IO Val evalAppTel a0 t u = force a0 >>= \case VTNil -> pure t VTCons _ _ as -> do u1 <- evalCar u u1v <- as u1 u2 <- evalCdr u t' <- evalApp Implicit t u1 evalAppTel u1v t' u2 a -> case t of VNe h sp -> pure $ VNe h (SAppTel a sp u) VLamTel _ _ t' -> t' u _ -> panic #endif evalApp :: Icit -> Val -> Val -> IO Val evalApp _ (VLam _ _ _ t) u = t u evalApp i (VNe h sp) u = pure $ VNe h (SApp i sp u) #ifdef FCIF evalApp i (VLamTel x a t) u = do y <- evalLamTel pure x a t evalApp i y u #endif evalApp _ _ _ = panic evalAppSp :: Val -> Spine -> IO Val evalAppSp h = go where go SNil = pure h go (SApp i sp u) = do sp' <- go sp; evalApp i sp' u #ifdef FCIF go (SAppTel a sp u) = do sp' <- go sp; evalAppTel a sp' u go (SCar sp) = go sp >>= evalCar go (SCdr sp) = go sp >>= evalCdr #endif force :: Val -> IO Val force = \case v0@(VNe (HMeta m) sp) -> readMeta m >>= \case Unsolved{} -> pure v0 Solved v -> evalAppSp v sp >>= force #ifdef FCIF _ -> panic VPiTel x a b -> evalPiTel force x a b VLamTel x a t -> evalLamTel force x a t #endif v -> pure v forceSp :: Spine -> IO Spine forceSp sp = This is a cheeky hack , the point is that ( VVar ( -1 ) ) blocks computation , and evalAppSp (VVar (-1)) sp >>= \case VNe _ sp' -> pure sp' _ -> panic eval :: Vals -> TM -> IO Val eval vs = go where go = \case Var x -> pure $ evalVar x vs Let _ _ t u -> go t >>= goBind u U -> pure VU Meta m -> evalMeta m Pi x i a b -> unsafeInterleaveIO (go a) <&> \a' -> VPi x i a' (goBind b) Lam x i a t -> unsafeInterleaveIO (go a) <&> \a' -> VLam x i a' (goBind t) App i t u -> do t' <- unsafeInterleaveIO (go t) u' <- unsafeInterleaveIO (go u) evalApp i t' u' #ifdef FCIF Tel -> pure VTel TNil -> pure VTNil TCons x a b -> unsafeInterleaveIO (go a) <&> \a' -> VTCons x a' (goBind b) Rec a -> VRec <$> go a Tnil -> pure VTnil Tcons t u -> VTcons <$> unsafeInterleaveIO (go t) <*> unsafeInterleaveIO (go u) Car t -> go t >>= evalCar Cdr t -> go t >>= evalCdr PiTel x a b -> do a' <- unsafeInterleaveIO (go a) evalPiTel pure x a' (goBind b) AppTel a t u -> do a' <- unsafeInterleaveIO (go a) t' <- unsafeInterleaveIO (go t) u' <- unsafeInterleaveIO (go u) evalAppTel a' t' u' LamTel x a t -> do a' <- unsafeInterleaveIO (go a) evalLamTel pure x a' (goBind t) #endif Skip t -> eval (VSkip vs) t goBind t x = eval (VDef vs x) t uneval :: Lvl -> Val -> IO TM uneval d = go where go v = force v >>= \case VNe h sp0 -> let goSp SNil = case h of HMeta m -> pure $ Meta m HVar x -> pure $ Var (d - x - 1) goSp (SApp i sp u) = App i <$> goSp sp <*> go u #ifdef FCIF goSp (SAppTel a sp u) = AppTel <$> go a <*> goSp sp <*> go u goSp (SCar sp) = Car <$> goSp sp goSp (SCdr sp) = Cdr <$> goSp sp #endif in forceSp sp0 >>= goSp VLam x i a t -> Lam x i <$> go a <*> goBind t VPi x i a b -> Pi x i <$> go a <*> goBind b VU -> pure U #ifdef FCIF VTel -> pure Tel VRec a -> Rec <$> go a VTNil -> pure TNil VTCons x a as -> TCons x <$> go a <*> goBind as VTnil -> pure Tnil VTcons t u -> Tcons <$> go t <*> go u VPiTel x a b -> PiTel x <$> go a <*> goBind b VLamTel x a t -> LamTel x <$> go a <*> goBind t #endif goBind t = t (VVar d) >>= uneval (d + 1) nf :: Vals -> TM -> IO TM nf vs t = do v <- eval vs t uneval 0 v
8f88b9e6900a92ab564e66634d58c6d74b5554fc4123805a11b2e79d07a8695c
dhleong/spade
dom.cljs
(ns spade.container.dom "The DomStyleContainer renders styles into DOM elements. References to those elements are stored in a `styles` atom, or `*injected-styles*` if that is not provided. Similarly, if no `target-dom` is provided, the `document.head` element is used." (:require [spade.container :refer [IStyleContainer]])) (defonce ^:dynamic *injected-styles* (atom nil)) (defn- perform-update! [obj css] (set! (.-innerHTML (:element obj)) css)) (defn update! [styles-container id css] (swap! styles-container update id (fn update-injected-style [obj] (when-not (= (:source obj) css) (perform-update! obj css)) (assoc obj :source css)))) (defn inject! [target-dom styles-container id css] (let [element (doto (js/document.createElement "style") (.setAttribute "spade-id" (str id))) obj {:element element :source css :id id}] (assert (some? target-dom) "An <head> element or target DOM is required to inject the style.") (.appendChild target-dom element) (swap! styles-container assoc id obj) (perform-update! obj css))) (deftype DomStyleContainer [target-dom styles] IStyleContainer (mount-style! [_ style-name css] (let [resolved-container (or styles *injected-styles*)] (if (contains? @resolved-container style-name) (update! resolved-container style-name css) (let [resolved-dom (or (when (ifn? target-dom) (target-dom)) target-dom (.-head js/document))] (inject! resolved-dom resolved-container style-name css)))))) (defn create-container "Create a DomStyleContainer. With no args, the default is created, which renders into the `document.head` element. For rendering into a custom target, such as when using Shadow DOM, you may provide a custom `target-dom`: this may either be the element itself, or a function which returns that element. If you also wish to provide your own storage for the style references, you may use the 3-arity version and provide an atom." ([] (create-container nil)) ([target-dom] (create-container target-dom (when target-dom (atom nil)))) ([target-dom styles-container] (->DomStyleContainer target-dom styles-container)))
null
https://raw.githubusercontent.com/dhleong/spade/d77c2adcf451aa9c0b55bd0a835d53f95c7becf4/src/spade/container/dom.cljs
clojure
(ns spade.container.dom "The DomStyleContainer renders styles into DOM elements. References to those elements are stored in a `styles` atom, or `*injected-styles*` if that is not provided. Similarly, if no `target-dom` is provided, the `document.head` element is used." (:require [spade.container :refer [IStyleContainer]])) (defonce ^:dynamic *injected-styles* (atom nil)) (defn- perform-update! [obj css] (set! (.-innerHTML (:element obj)) css)) (defn update! [styles-container id css] (swap! styles-container update id (fn update-injected-style [obj] (when-not (= (:source obj) css) (perform-update! obj css)) (assoc obj :source css)))) (defn inject! [target-dom styles-container id css] (let [element (doto (js/document.createElement "style") (.setAttribute "spade-id" (str id))) obj {:element element :source css :id id}] (assert (some? target-dom) "An <head> element or target DOM is required to inject the style.") (.appendChild target-dom element) (swap! styles-container assoc id obj) (perform-update! obj css))) (deftype DomStyleContainer [target-dom styles] IStyleContainer (mount-style! [_ style-name css] (let [resolved-container (or styles *injected-styles*)] (if (contains? @resolved-container style-name) (update! resolved-container style-name css) (let [resolved-dom (or (when (ifn? target-dom) (target-dom)) target-dom (.-head js/document))] (inject! resolved-dom resolved-container style-name css)))))) (defn create-container "Create a DomStyleContainer. With no args, the default is created, which renders into the `document.head` element. For rendering into a custom target, such as when using Shadow DOM, you may provide a custom `target-dom`: this may either be the element itself, or a function which returns that element. If you also wish to provide your own storage for the style references, you may use the 3-arity version and provide an atom." ([] (create-container nil)) ([target-dom] (create-container target-dom (when target-dom (atom nil)))) ([target-dom styles-container] (->DomStyleContainer target-dom styles-container)))
269db7597cdd804b677adcf7abb58d69dd6a22e39fabe9458f048f3ba3e84418
ggreif/omega
TwoHoles.hs
# LANGUAGE GADTs , KindSignatures , DataKinds # module TwoHoles where data Nat = Z | S Nat data Tree a = Node (Tree a) (Tree a) | Leaf a deriving Show data TreeWithHoles :: Nat -> Nat -> * -> * where HLeaf :: a -> TreeWithHoles n n a HNode :: TreeWithHoles m n a -> TreeWithHoles n o a -> TreeWithHoles m o a Hole :: TreeWithHoles (S n) n a type TreeWith1Hole a = TreeWithHoles (S Z) Z a type TreeWith2Holes a = TreeWithHoles (S (S Z)) Z a data Vec :: Nat -> * -> * where (:::) :: a -> Vec n a -> Vec (S n) a Nil :: Vec Z a fill :: TreeWithHoles n Z a -> Vec n a -> Tree a fill t xs = fst (fill' t xs) fill' :: TreeWithHoles m n a -> Vec m a -> (Tree a, Vec n a) fill' Hole (x ::: xs) = (Leaf x, xs) fill' (HLeaf x) xs = (Leaf x, xs) fill' (HNode l r) xs = case fill' l xs of (l', ys) -> case fill' r ys of (r', zs) -> (Node l' r', zs) -- fill' Hole _ = error "inaccessible"
null
https://raw.githubusercontent.com/ggreif/omega/016a3b48313ec2c68e8d8ad60147015bc38f2767/mosaic/TwoHoles.hs
haskell
# LANGUAGE GADTs , KindSignatures , DataKinds # module TwoHoles where data Nat = Z | S Nat data Tree a = Node (Tree a) (Tree a) | Leaf a deriving Show data TreeWithHoles :: Nat -> Nat -> * -> * where HLeaf :: a -> TreeWithHoles n n a HNode :: TreeWithHoles m n a -> TreeWithHoles n o a -> TreeWithHoles m o a Hole :: TreeWithHoles (S n) n a type TreeWith1Hole a = TreeWithHoles (S Z) Z a type TreeWith2Holes a = TreeWithHoles (S (S Z)) Z a data Vec :: Nat -> * -> * where (:::) :: a -> Vec n a -> Vec (S n) a Nil :: Vec Z a fill :: TreeWithHoles n Z a -> Vec n a -> Tree a fill t xs = fst (fill' t xs) fill' :: TreeWithHoles m n a -> Vec m a -> (Tree a, Vec n a) fill' Hole (x ::: xs) = (Leaf x, xs) fill' (HLeaf x) xs = (Leaf x, xs) fill' (HNode l r) xs = case fill' l xs of (l', ys) -> case fill' r ys of (r', zs) -> (Node l' r', zs) fill' Hole _ = error "inaccessible"
c9afdba19fb66b2f55a009483d7e56efebaa0bec11815c7d21f36e46e4aadf4d
mzp/coq-for-ipad
topdirs.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : topdirs.mli 4694 2002 - 04 - 18 07:27:47Z garrigue $ (* The toplevel directives. *) open Format val dir_quit : unit -> unit val dir_directory : string -> unit val dir_cd : string -> unit val dir_load : formatter -> string -> unit val dir_use : formatter -> string -> unit val dir_install_printer : formatter -> Longident.t -> unit val dir_remove_printer : formatter -> Longident.t -> unit val dir_trace : formatter -> Longident.t -> unit val dir_untrace : formatter -> Longident.t -> unit val dir_untrace_all : formatter -> unit -> unit type 'a printer_type_new = Format.formatter -> 'a -> unit type 'a printer_type_old = 'a -> unit (* For topmain.ml. Maybe shouldn't be there *) val load_file : formatter -> string -> bool
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/toplevel/topdirs.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* The toplevel directives. For topmain.ml. Maybe shouldn't be there
, 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 Q Public License version 1.0 . $ I d : topdirs.mli 4694 2002 - 04 - 18 07:27:47Z garrigue $ open Format val dir_quit : unit -> unit val dir_directory : string -> unit val dir_cd : string -> unit val dir_load : formatter -> string -> unit val dir_use : formatter -> string -> unit val dir_install_printer : formatter -> Longident.t -> unit val dir_remove_printer : formatter -> Longident.t -> unit val dir_trace : formatter -> Longident.t -> unit val dir_untrace : formatter -> Longident.t -> unit val dir_untrace_all : formatter -> unit -> unit type 'a printer_type_new = Format.formatter -> 'a -> unit type 'a printer_type_old = 'a -> unit val load_file : formatter -> string -> bool
b025b65da6769f03116609f9d3c501f4560f5d4cb267cf5587f096486898ed66
vimus/libmpd-haskell
Class.hs
# LANGUAGE FlexibleContexts # -- | Module : Network.MPD.Core.Class Copyright : ( c ) 2005 - 2009 , Joachim Fasting 2010 License : MIT ( see LICENSE ) -- Maintainer : Joachim Fasting <> -- Stability : alpha -- -- The MPD typeclass. module Network.MPD.Core.Class where import Data.ByteString (ByteString) import Network.MPD.Core.Error (MPDError) import Control.Monad.Except (MonadError) type Password = String -- | A typeclass to allow for multiple implementations of a connection to an MPD server . class (Monad m, MonadError MPDError m) => MonadMPD m where | Open ( or re - open ) a connection to the MPD server . open :: m () -- | Close the connection. close :: m () -- | Send a string to the server and return its response. send :: String -> m [ByteString] -- | Produce a password to send to the server should it ask for -- one. getPassword :: m Password -- | Alters password to be sent to the server. setPassword :: Password -> m () -- | Get MPD protocol version getVersion :: m (Int, Int, Int)
null
https://raw.githubusercontent.com/vimus/libmpd-haskell/1ec02deba33ce2a16012d8f0954e648eb4b5c485/src/Network/MPD/Core/Class.hs
haskell
| Module : Network.MPD.Core.Class Maintainer : Joachim Fasting <> Stability : alpha The MPD typeclass. | A typeclass to allow for multiple implementations of a connection | Close the connection. | Send a string to the server and return its response. | Produce a password to send to the server should it ask for one. | Alters password to be sent to the server. | Get MPD protocol version
# LANGUAGE FlexibleContexts # Copyright : ( c ) 2005 - 2009 , Joachim Fasting 2010 License : MIT ( see LICENSE ) module Network.MPD.Core.Class where import Data.ByteString (ByteString) import Network.MPD.Core.Error (MPDError) import Control.Monad.Except (MonadError) type Password = String to an MPD server . class (Monad m, MonadError MPDError m) => MonadMPD m where | Open ( or re - open ) a connection to the MPD server . open :: m () close :: m () send :: String -> m [ByteString] getPassword :: m Password setPassword :: Password -> m () getVersion :: m (Int, Int, Int)
4bc3199650024373173fae7851cd4e814afcb854bbe5c61d2a9c9099e4a0b0a8
OCamlPro/drom
commandTest.ml
(**************************************************************************) (* *) Copyright 2020 OCamlPro & Origin Labs (* *) (* 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 Ezcmd.V2 open EZCMD.TYPES open Ez_file.V1 open EzFile.OP let cmd_name = "test" let action ~all ~args () = let (p : Types.project) = Build.build ~dev_deps:true ~args () in let workspace = if all then begin let root = Globals.opam_root () in let oc = open_out "_drom/dune-workspace.dev" in Printf.fprintf oc "(lang dune 2.7)\n"; let files = Sys.readdir root in Array.sort compare files; Array.iter (fun switch -> match switch.[0] with | '3' .. '9' when not (String.contains switch '+') -> if switch >= p.min_edition && Sys.file_exists (root // switch // ".opam-switch") then begin Printf.eprintf "Adding switch %s\n%!" switch; Printf.fprintf oc "(context (opam (switch %s)))\n" switch end | _ -> () ) files; close_out oc; [ "--workspace"; "_drom/dune-workspace.dev" ] end else [] in Misc.call (Array.of_list ([ "opam"; "exec"; "--"; "dune"; "build"; "@runtest" ] @ workspace) ); Printf.eprintf "Tests OK\n%!"; () let cmd = let all = ref false in let args, specs = Build.build_args () in EZCMD.sub cmd_name (fun () -> action ~all:!all ~args ()) ~args: ( specs @ [ ( [ "all" ], Arg.Set all, EZCMD.info "Build and run tests on all compatible switches" ) ] ) ~doc:"Run tests" ~man: [ `S "DESCRIPTION"; `Blocks [ `P "This command performs the following actions:"; `I ( "1.", "Build the project, installing required test dependencies if \ needed" ); `I ( "2.", "Run the test command $(b,opam exec -- dune build @runtest)" ); `P "If the $(b,--all) argument was provided, a file \ $(b,_drom/dune-workspace.dev) is created containing a context \ for every existing opam switch compatible with the project \ $(b,min-edition) field, and the tests are run on all of them. \ Before using this option, you should make sure that \ dependencies are correctly installed on all of them, using the \ command $(drom build --switch SWITCH) on every $(b,SWITCH) in \ the list. Only switches starting with a number and without the \ $(i,+) character are selected." ] ]
null
https://raw.githubusercontent.com/OCamlPro/drom/dbbb5f9225df65c589e6f307ac28be4c408b9cae/src/drom_lib/commandTest.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************
Copyright 2020 OCamlPro & Origin Labs GNU Lesser General Public License version 2.1 , with the special open Ezcmd.V2 open EZCMD.TYPES open Ez_file.V1 open EzFile.OP let cmd_name = "test" let action ~all ~args () = let (p : Types.project) = Build.build ~dev_deps:true ~args () in let workspace = if all then begin let root = Globals.opam_root () in let oc = open_out "_drom/dune-workspace.dev" in Printf.fprintf oc "(lang dune 2.7)\n"; let files = Sys.readdir root in Array.sort compare files; Array.iter (fun switch -> match switch.[0] with | '3' .. '9' when not (String.contains switch '+') -> if switch >= p.min_edition && Sys.file_exists (root // switch // ".opam-switch") then begin Printf.eprintf "Adding switch %s\n%!" switch; Printf.fprintf oc "(context (opam (switch %s)))\n" switch end | _ -> () ) files; close_out oc; [ "--workspace"; "_drom/dune-workspace.dev" ] end else [] in Misc.call (Array.of_list ([ "opam"; "exec"; "--"; "dune"; "build"; "@runtest" ] @ workspace) ); Printf.eprintf "Tests OK\n%!"; () let cmd = let all = ref false in let args, specs = Build.build_args () in EZCMD.sub cmd_name (fun () -> action ~all:!all ~args ()) ~args: ( specs @ [ ( [ "all" ], Arg.Set all, EZCMD.info "Build and run tests on all compatible switches" ) ] ) ~doc:"Run tests" ~man: [ `S "DESCRIPTION"; `Blocks [ `P "This command performs the following actions:"; `I ( "1.", "Build the project, installing required test dependencies if \ needed" ); `I ( "2.", "Run the test command $(b,opam exec -- dune build @runtest)" ); `P "If the $(b,--all) argument was provided, a file \ $(b,_drom/dune-workspace.dev) is created containing a context \ for every existing opam switch compatible with the project \ $(b,min-edition) field, and the tests are run on all of them. \ Before using this option, you should make sure that \ dependencies are correctly installed on all of them, using the \ command $(drom build --switch SWITCH) on every $(b,SWITCH) in \ the list. Only switches starting with a number and without the \ $(i,+) character are selected." ] ]
14ec1a9c61391b427487e880fb44d35eccd30327d7db757b25034e3df4b0ea8d
ormf/cm
midi1.lisp
;;; ********************************************************************** Copyright ( C ) 2009 , < taube ( at ) uiuc ( dot ) edu > ;;; ;;; This program is free software; you can redistribute it and/or modify it under the terms of the Lisp Lesser Gnu Public License . See for the text of this agreement . ;;; ********************************************************************** generated by scheme->cltl from midi1.scm on 04 - Aug-2009 14:11:46 (in-package :cm) (defparameter +enc-route-byte+ (byte 10 22)) (defparameter +enc-lower-status-byte+ (byte 4 18)) (defparameter +enc-upper-status-byte+ (byte 4 14)) (defparameter +enc-swapped-status-byte+ (byte 8 14)) (defparameter +enc-logical-channel-byte+ (byte 14 18)) (defparameter +enc-opcode-byte+ +enc-upper-status-byte+) (defparameter +enc-data-1-byte+ (byte 7 7)) (defparameter +enc-data-2-byte+ (byte 7 0)) (defparameter +enc-route-offs+ -22) (defparameter +enc-lower-status-offs+ -18) (defparameter +enc-upper-status-offs+ -10) (defparameter +enc-swapped-status-offs+ -14) (defparameter +enc-logical-channel-offs+ +enc-lower-status-offs+) (defparameter +enc-opcode-offs+ +enc-upper-status-offs+) (defparameter +enc-data-1-offs+ -7) (defparameter +enc-data-2-offs+ 0) (defparameter +enc-note-off-mask+ 4294852480) (defparameter +ml-note-off-opcode+ 8) (defparameter +ml-note-on-opcode+ 9) (defparameter +ml-key-pressure-opcode+ 10) (defparameter +ml-control-change-opcode+ 11) (defparameter +ml-program-change-opcode+ 12) (defparameter +ml-channel-pressure-opcode+ 13) (defparameter +ml-pitch-bend-opcode+ 14) (defparameter +ml-default-note-on-velocity+ 64) (defparameter +ml-default-note-off-velocity+ 64) (defparameter +ml-msg-sysex-type+ 15) (defparameter +ml-msg-mtc-quarter-frame-type+ 31) (defparameter +ml-msg-song-position-type+ 47) (defparameter +ml-msg-song-select-type+ 63) (defparameter +ml-msg-cable-select-type+ 95) (defparameter +ml-msg-tune-request-type+ 111) (defparameter +ml-msg-eox-type+ 127) (defparameter +ml-msg-timing-clock-type+ 143) (defparameter +ml-msg-timing-tick-type+ 159) (defparameter +ml-msg-start-type+ 175) (defparameter +ml-msg-continue-type+ 191) (defparameter +ml-msg-stop-type+ 207) (defparameter +ml-msg-active-sensing-type+ 239) (defparameter +ml-msg-system-reset-type+ 255) (defparameter +ml-meta-type+ 0) (defparameter +ml-file-meta-marker+ 255) (defparameter +ml-file-sequence-number-opcode+ 0) (defparameter +ml-file-text-event-opcode+ 1) (defparameter +ml-file-copyright-note-opcode+ 2) (defparameter +ml-file-sequence/track-name-opcode+ 3) (defparameter +ml-file-instrument-name-opcode+ 4) (defparameter +ml-file-lyric-opcode+ 5) (defparameter +ml-file-marker-opcode+ 6) (defparameter +ml-file-cue-point-opcode+ 7) (defparameter +ml-file-midi-channel-opcode+ 32) (defparameter +ml-file-midi-port-opcode+ 33) (defparameter +ml-file-eot-opcode+ 47) (defparameter +ml-file-tempo-change-opcode+ 81) (defparameter +ml-file-smpte-offset-opcode+ 84) (defparameter +ml-file-time-signature-opcode+ 88) (defparameter +ml-file-key-signature-opcode+ 89) (defparameter +ml-file-sequencer-event-opcode+ 127) (defun midimsg-data1 (message) (ldb +enc-data-1-byte+ message)) (defun midimsg-data2 (message) (ldb +enc-data-2-byte+ message)) (defun midi-channel-message-p (message) (< 0 (ldb +enc-opcode-byte+ message) 15)) (defun midi-system-message-p (message) (= (ldb +enc-upper-status-byte+ message) 15)) (defun midi-meta-message-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-meta-type+)) (defparameter +channel-message-sizes+ #(3 3 3 3 2 2 3)) (defparameter +system-message-sizes+ #(0 2 3 2 -1 2 1 1 1 1 1 1 1 -1 1 1)) (defparameter +ml-channel-msg-type-strings+ #("Note-Off" "Note-On" "Key-Pressure" "Control-Change" "Program-Change" "Channel-Pressure" "Pitch-Bend")) (defparameter +ml-msg-type-strings+ #("Sysex" "MTC Quarter Frame" "Song-Position" "Song-Select" "Undefined" "Cable-Select" "Tune-Request" "Eox" "Timing-Clock" "Timing-Tick" "Start" "Continue" "Stop" "Undefined" "Active-Sensing" "System-Reset")) (defparameter +ml-meta-msg-type-strings+ #((0 . "Sequence Number") (1 . "Text Event") (2 . "Copyright Note") (3 . "Sequence/Track Name") (4 . "Instrument Name") (5 . "Lyric") (6 . "Marker") (7 . "Cue Point") (32 . "MIDI Channel") (33 . "MIDI Port") (47 . "End of Track") (81 . "Tempo Change") (84 . "SMPTE Offset") (88 . "Time Signature") (89 . "Key Signature") (127 . "Sequencer Event"))) (defun get-meta-msg-type-string (type) (let ((res (do ((i 0 (+ i 1)) (l (length +ml-meta-msg-type-strings+)) (x nil) (f nil)) ((or f (= i l)) f) (setf x (elt +ml-meta-msg-type-strings+ i)) (if (= (car x) type) (setf f x))))) (if res (cdr res) "Unknown Meta Event"))) (defun midimsg-logical-channel (m) (ldb +enc-logical-channel-byte+ m)) (defun midimsg-route (m) (ldb +enc-route-byte+ m)) (defun midimsg-opcode (m) (ldb +enc-opcode-byte+ m)) (defun midimsg-upper-status (m) (ldb +enc-upper-status-byte+ m)) (defun midimsg-lower-status (m) (ldb +enc-lower-status-byte+ m)) (defun midimsg-status (m) (ldb +enc-swapped-status-byte+ m)) (defun midimsg-size (m) (if (midi-channel-message-p m) (elt +channel-message-sizes+ (logand (ash m +enc-swapped-status-offs+) 7)) (elt +system-message-sizes+ (logand (ash m +enc-lower-status-offs+) 15)))) (defun channel-note-hash (m) (logior (ash (ldb +enc-logical-channel-byte+ m) 8) (midimsg-data1 m))) (defun %midi-encode-channel-message (bytes size) (if (= size 3) (make-channel-message (ash (logand bytes 15728640) -20) (ash (logand bytes 983040) -16) (ash (logand bytes 32512) -8) (logand bytes 127)) (if (= size 2) (make-channel-message (ash (logand bytes 61440) -12) (ash (logand bytes 3840) -8) (logand bytes 127) 0) (error "Size ~s cannot be a channel message." size)))) (defparameter *midi-open* ()) (defparameter *midi-time* -1) (defmacro define-message-set! (accessor bytespec) (make-midi-message-set! accessor bytespec)) (defun midi-copy-message (msg &key opcode channel data1 data2) (when opcode (setf msg (dpb opcode +enc-opcode-byte+ msg))) (when channel (setf msg (dpb channel +enc-logical-channel-byte+ msg))) (when data1 (setf msg (dpb data1 +enc-data-1-byte+ msg))) (when data2 (setf msg (dpb data2 +enc-data-2-byte+ msg))) msg) (defun make-channel-message (opcode channel data1 data2) (logior (ash (logand channel 16383) 18) (ash (logand opcode 15) 14) (ash (logand data1 127) 7) (logand data2 127))) (defun channel-message-p (message) (midi-channel-message-p message)) (defun channel-message-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun channel-message-opcode (message) (ldb +enc-opcode-byte+ message)) (defun channel-message-data1 (message) (ldb +enc-data-1-byte+ message)) (defun channel-message-data2 (message) (ldb +enc-data-2-byte+ message)) (define-message-set! channel-message-channel +enc-logical-channel-byte+) (define-message-set! channel-message-opcode +enc-opcode-byte+) (define-message-set! channel-message-data1 +enc-data-1-byte+) (define-message-set! channel-message-data2 +enc-data-2-byte+) (defun make-note-off (channel key velocity) (make-channel-message +ml-note-off-opcode+ channel key velocity)) (defun note-off-p (message) (= (ldb +enc-opcode-byte+ message) +ml-note-off-opcode+)) (defun note-off-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun note-off-key (message) (ldb +enc-data-1-byte+ message)) (defun note-off-velocity (message) (ldb +enc-data-2-byte+ message)) (define-message-set! note-off-channel +enc-logical-channel-byte+) (define-message-set! note-off-key +enc-data-1-byte+) (define-message-set! note-off-velocity +enc-data-2-byte+) (defun make-note-on (channel key velocity) (make-channel-message +ml-note-on-opcode+ channel key velocity)) (defun note-on-p (message) (= (ldb +enc-opcode-byte+ message) +ml-note-on-opcode+)) (defun note-on-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun note-on-key (message) (ldb +enc-data-1-byte+ message)) (defun note-on-velocity (message) (ldb +enc-data-2-byte+ message)) (define-message-set! note-on-channel +enc-logical-channel-byte+) (define-message-set! note-on-key +enc-data-1-byte+) (define-message-set! note-on-velocity +enc-data-2-byte+) (defun make-key-pressure (channel key pressure) (make-channel-message +ml-key-pressure-opcode+ channel key pressure)) (defun key-pressure-p (message) (= (ldb +enc-opcode-byte+ message) +ml-key-pressure-opcode+)) (defun key-pressure-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun key-pressure-key (message) (ldb +enc-data-1-byte+ message)) (defun key-pressure-pressure (message) (ldb +enc-data-2-byte+ message)) (define-message-set! key-pressure-channel +enc-logical-channel-byte+) (define-message-set! key-pressure-key +enc-data-1-byte+) (define-message-set! key-pressure-pressure +enc-data-2-byte+) (defun make-control-change (channel controller value) (make-channel-message +ml-control-change-opcode+ channel controller value)) (defun control-change-p (message) (= (ldb +enc-opcode-byte+ message) +ml-control-change-opcode+)) (defun control-change-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun control-change-controller (message) (ldb +enc-data-1-byte+ message)) (defun control-change-value (message) (ldb +enc-data-2-byte+ message)) (define-message-set! control-change-channel +enc-logical-channel-byte+) (define-message-set! control-change-controller +enc-data-1-byte+) (define-message-set! control-change-value +enc-data-2-byte+) (defun make-program-change (channel program) (make-channel-message +ml-program-change-opcode+ channel program 0)) (defun program-change-p (message) (= (ldb +enc-opcode-byte+ message) +ml-program-change-opcode+)) (defun program-change-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun program-change-program (message) (ldb +enc-data-1-byte+ message)) (define-message-set! program-change-channel +enc-logical-channel-byte+) (define-message-set! program-change-program +enc-data-1-byte+) (defun make-channel-pressure (channel pressure) (make-channel-message +ml-channel-pressure-opcode+ channel pressure 0)) (defun channel-pressure-p (message) (= (ldb +enc-opcode-byte+ message) +ml-channel-pressure-opcode+)) (defun channel-pressure-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun channel-pressure-pressure (message) (ldb +enc-data-1-byte+ message)) (define-message-set! channel-pressure-channel +enc-logical-channel-byte+) (define-message-set! channel-pressure-pressure +enc-data-1-byte+) (defun make-pitch-bend (channel value &rest args) (let ((width (if (null args) 2 (car args)))) (let ((bend (floor (rescale value (- width) width 0 16383)))) (make-channel-message +ml-pitch-bend-opcode+ channel (ldb (byte 7 0) bend) (ldb (byte 7 7) bend))))) (defun pitch-bend-p (message) (= (ldb +enc-opcode-byte+ message) +ml-pitch-bend-opcode+)) (defun pitch-bend-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun pitch-bend-lsb (message) (ldb +enc-data-1-byte+ message)) (defun pitch-bend-msb (message) (ldb +enc-data-2-byte+ message)) (define-message-set! pitch-bend-channel +enc-logical-channel-byte+) (define-message-set! pitch-bend-lsb +enc-data-1-byte+) (define-message-set! pitch-bend-msb +enc-data-2-byte+) (defun make-system-message (type route &optional (data1 0) (data2 0)) (dpb route +enc-route-byte+ (dpb type +enc-swapped-status-byte+ (dpb data1 +enc-data-1-byte+ (dpb data2 +enc-data-2-byte+ 0))))) (defun system-message-p (message) (midi-system-message-p message)) (defun system-message-route (message) (ldb +enc-route-byte+ message)) (defun system-message-status (message) (ldb +enc-swapped-status-byte+ message)) (defun system-message-data1 (message) (ldb +enc-data-1-byte+ message)) (defun system-message-data2 (message) (ldb +enc-data-2-byte+ message)) (define-message-set! system-message-route +enc-route-byte+) (define-message-set! system-message-status +enc-swapped-status-byte+) (define-message-set! system-message-data1 +enc-data-1-byte+) (define-message-set! system-message-data2 +enc-data-2-byte+) (defun make-sysex-data (&rest args) (let ((len 2) (i 0) (msg #())) (labels ((incflen (args) (dolist (a args) (cond ((characterp a) (incf len)) ((and (integerp a) (<= 0 i 255)) (incf len)) ((stringp a) (incf len (+ (length a) 1))) ((consp a) (incflen a)) (t (error "~s not char, byte or string." a))))) (stuff (byte) (incf i) (setf (elt msg i) byte)) (stuffdata (args) (dolist (a args) (cond ((characterp a) (stuff (char-code a))) ((stringp a) (loop for i below (length a) for c = (elt a i) do (stuff (char-code c)) finally (stuff 0))) ((and (integerp a) (<= 0 i 255)) (stuff a)) ((consp a) (stuffdata a)) (t (error "~s not char, byte or string." a)))))) (incflen args) (setf msg (make-array len :initial-element 0)) (stuffdata args) (setf (elt msg 0) 240) (setf (elt msg (- len 1)) 247) msg))) (defun make-sysex (route data) (values (make-system-message +ml-msg-sysex-type+ route) (if (consp data) (apply #'make-sysex-data data) (if (vectorp data) data (error "~s is not a pair or a vector." data))))) (defun sysex-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-sysex-type+)) (defun sysex-route (message) (ldb +enc-route-byte+ message)) (define-message-set! sysex-route +enc-route-byte+) (defun make-mtc-quarter-frame (route tag nibble) (make-system-message +ml-msg-mtc-quarter-frame-type+ route (logior (ash tag 4) nibble))) (defun mtc-quarter-frame-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-mtc-quarter-frame-type+)) (defun mtc-quarter-frame-route (message) (ldb +enc-route-byte+ message)) (defun mtc-quarter-frame-tag (message) (logand (ldb +enc-data-1-byte+ message) 112)) (defun mtc-quarter-frame-nibble (message) (logand (ldb +enc-data-1-byte+ message) 15)) (define-message-set! mtc-quarter-frame-route +enc-route-byte+) (defun make-song-position (route lsb msb) (make-system-message +ml-msg-song-position-type+ route lsb msb)) (defun song-position-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-song-position-type+)) (defun song-position-route (message) (ldb +enc-route-byte+ message)) (defun song-position-lsb (message) (ldb +enc-data-1-byte+ message)) (defun song-position-msb (message) (ldb +enc-data-2-byte+ message)) (define-message-set! song-position-route +enc-route-byte+) (define-message-set! song-position-lsb +enc-data-1-byte+) (define-message-set! song-position-msb +enc-data-2-byte+) (defun make-song-select (route song) (make-system-message +ml-msg-song-select-type+ route song)) (defun song-select-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-song-select-type+)) (defun song-select-route (message) (ldb +enc-route-byte+ message)) (defun song-select-song (message) (ldb +enc-data-1-byte+ message)) (define-message-set! song-select-route +enc-route-byte+) (define-message-set! song-select-song +enc-data-1-byte+) (defun make-cable-select (route cable) (make-system-message +ml-msg-cable-select-type+ route cable)) (defun cable-select-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-cable-select-type+)) (defun cable-select-route (message) (ldb +enc-route-byte+ message)) (defun cable-select-cable (message) (ldb +enc-data-1-byte+ message)) (define-message-set! cable-select-route +enc-route-byte+) (define-message-set! cable-select-cable +enc-data-1-byte+) (defun make-tune-request (route) (make-system-message +ml-msg-tune-request-type+ route)) (defun tune-request-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-tune-request-type+)) (defun tune-request-route (message) (ldb +enc-route-byte+ message)) (define-message-set! tune-request-route +enc-route-byte+) (defun make-eox (route) (make-system-message +ml-msg-eox-type+ route)) (defun eox-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-eox-type+)) (defun eox-route (message) (ldb +enc-route-byte+ message)) (define-message-set! eox-route +enc-route-byte+) (defun make-timing-clock (route) (make-system-message +ml-msg-timing-clock-type+ route)) (defun timing-clock-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-timing-clock-type+)) (defun timing-clock-route (message) (ldb +enc-route-byte+ message)) (define-message-set! timing-clock-route +enc-route-byte+) (defun make-timing-tick (route) (make-system-message +ml-msg-timing-tick-type+ route)) (defun timing-tick-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-timing-tick-type+)) (defun timing-tick-route (message) (ldb +enc-route-byte+ message)) (define-message-set! timing-tick-route +enc-route-byte+) (defun make-start (route) (make-system-message +ml-msg-start-type+ route)) (defun start-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-start-type+)) (defun start-route (message) (ldb +enc-route-byte+ message)) (define-message-set! start-route +enc-route-byte+) (defun make-continue (route) (make-system-message +ml-msg-continue-type+ route)) (defun continue-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-continue-type+)) (defun continue-route (message) (ldb +enc-route-byte+ message)) (define-message-set! continue-route +enc-route-byte+) (defun make-stop (route) (make-system-message +ml-msg-stop-type+ route)) (defun stop-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-stop-type+)) (defun stop-route (message) (ldb +enc-route-byte+ message)) (define-message-set! stop-route +enc-route-byte+) (defun make-active-sensing (route) (make-system-message +ml-msg-active-sensing-type+ route)) (defun active-sensing-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-active-sensing-type+)) (defun active-sensing-route (message) (ldb +enc-route-byte+ message)) (define-message-set! active-sensing-route +enc-route-byte+) (defun make-system-reset (route) (make-system-message +ml-msg-system-reset-type+ route)) (defun system-reset-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-system-reset-type+)) (defun system-reset-route (message) (ldb +enc-route-byte+ message)) (define-message-set! system-reset-route +enc-route-byte+) (defun make-meta-message (type &rest data-bytes) (values (dpb +ml-meta-type+ +enc-swapped-status-byte+ (dpb type +enc-data-1-byte+ 0)) (let ((l (length data-bytes)) (v nil) (d nil)) (setf v (if (< l 128) 1 (if (< l 16384) 2 (if (< l 2097152) 3 (if (< l 268435456) 4 (error "Illegal length: ~s" l)))))) (setf d (make-array (+ v l) :initial-element 0)) (do ((i 0 (+ 1 i)) (offs (* (- v 1) 7) (- offs 7))) ((not (< i v)) nil) (setf (elt d i) (if (= offs 0) (ldb (byte 7 offs) l) (logior (ldb (byte 7 offs) l) 128)))) (do ((i v (+ i 1)) (b data-bytes (cdr b))) ((null b) nil) (setf (elt d i) (car b))) d))) (defun meta-message-p (message) (midi-meta-message-p message)) (defun meta-message-type (message) (ldb +enc-data-1-byte+ message)) (define-message-set! meta-message-type +enc-data-1-byte+) (defun make-sequence-number (num) (when (>= num 65536) (error "~s too big for a sequence number." num)) (make-meta-message +ml-file-sequence-number-opcode+ (ldb (byte 8 8) num) (ldb (byte 8 0) num))) (defun sequence-number-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequence-number-opcode+))) (defun make-text-event (string &optional (type +ml-file-text-event-opcode+)) (apply #'make-meta-message type (loop for i below (length string) collect (char-code (elt string i))))) (defun text-event-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-text-event-opcode+))) (defparameter +text-meta-event-types+ (list +ml-file-text-event-opcode+ +ml-file-copyright-note-opcode+ +ml-file-sequence/track-name-opcode+ +ml-file-instrument-name-opcode+ +ml-file-lyric-opcode+ +ml-file-marker-opcode+ +ml-file-cue-point-opcode+)) (defun text-meta-event-p (message) (and (midi-meta-message-p message) (member (ldb +enc-data-1-byte+ message) +text-meta-event-types+) t)) (defun text-meta-event-data-to-string (data) (let ((len (elt data 0))) (when (= (elt data len) 0) (setf len (max (- len 1) 0))) (loop with str = (make-string len) for i below len do (setf (elt str i) (code-char (elt data (+ i 1)))) finally (return str)))) (defun make-copyright-note (string) (make-text-event string +ml-file-copyright-note-opcode+)) (defun copyright-note-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-copyright-note-opcode+))) (defun make-sequence/track-name (string) (make-text-event string +ml-file-sequence/track-name-opcode+)) (defun sequence/track-name-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequence/track-name-opcode+))) (defun make-instrument-name (string) (make-text-event string +ml-file-instrument-name-opcode+)) (defun instrument-name-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-instrument-name-opcode+))) (defun make-lyric (string) (make-text-event string +ml-file-lyric-opcode+)) (defun lyric-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-lyric-opcode+))) (defun make-marker (string) (make-text-event string +ml-file-marker-opcode+)) (defun marker-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-marker-opcode+))) (defun make-cue-point (string) (make-text-event string +ml-file-cue-point-opcode+)) (defun cue-point-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-cue-point-opcode+))) (defun make-midi-channel (channel) (make-meta-message +ml-file-midi-channel-opcode+ channel)) (defun midi-channel-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-midi-channel-opcode+))) (defun make-midi-port (port) (make-meta-message +ml-file-midi-port-opcode+ port)) (defun midi-port-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-midi-port-opcode+))) (defun make-eot () (make-meta-message +ml-file-eot-opcode+)) (defun eot-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-eot-opcode+))) (defun make-tempo-change (usecs-per-beat) (apply #'make-meta-message +ml-file-tempo-change-opcode+ (loop for pos from 16 by 8 downto 0 collect (ldb (byte 8 pos) usecs-per-beat)))) (defun tempo-change-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-tempo-change-opcode+))) (defun make-smpte-offset (hours mins secs frames fractional-frames) (make-meta-message +ml-file-smpte-offset-opcode+ hours mins secs frames fractional-frames)) (defun smpte-offset-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-smpte-offset-opcode+))) (defun make-time-signature (numerator denominator &optional (clocks 24) (32nds 8)) (multiple-value-bind (f r) (floor (log2 denominator)) (unless (zerop r) (error "Time signature denominator ~s is not a power of 2." denominator)) (make-meta-message +ml-file-time-signature-opcode+ numerator f clocks 32nds))) (defun time-signature-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-time-signature-opcode+))) (defun make-key-signature (key &optional (mode ':major)) (let ((sf nil)) (setf mode (case mode ((:major major 0) 0) ((:minor minor 1) 1) (t (error "key signature mode not :major or :minor")))) (cond ((numberp key) (unless (<= -7 key 7) (error "Key signature must be between -7 (b) and 7 (#).")) (setf sf key)) (t (error "~s is not a number or symbol." key))) (setf sf (if (< sf 0) (+ sf 256) sf)) (make-meta-message +ml-file-key-signature-opcode+ sf mode))) (defun key-signature-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-key-signature-opcode+))) (defun make-sequencer-event (&rest data) (apply #'make-meta-message +ml-file-sequencer-event-opcode+ data)) (defun sequencer-event-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequencer-event-opcode+))) (defun midi-print-channel-message (stream gm? size type channel data1 data2 time-string) (let ((name (elt +ml-channel-msg-type-strings+ (logand type 7)))) (format stream "~a~a" name time-string) (when gm? (let ((p (gm-percussion-channel-p channel))) (if p (setf channel "P")) (cond ((= type 12) (setf data1 (gm-patch-name data1))) ((= type 11) (setf data1 (midi-controller-name data1))) ((or (= type 10) (= type 8) (= type 9)) (if p (setf data1 (gm-drum-kit-name data1))))))) (format stream " ~a" channel) (if (= size 3) (format stream " ~s ~s" data1 data2) (format stream " ~s" data1)))) (defparameter *midi-gm-mode* t) (defun %print-sysex-aux (stream data bytes rest indent) (let ((offs 0) (toprint bytes) (n 0) (oldn nil) (blank nil)) (loop while (> toprint 0) do (when indent (format stream indent)) (format stream (format-integer offs 6 #\0)) (format stream ":") (setf oldn n) (do ((i 0 (+ i 1))) ((or (= i 16) (>= n bytes)) (setf blank (- 16 i))) (format stream (format-integer (elt data n) 2 #\0)) (if (oddp i) (format stream " ")) (incf n)) (dotimes (i (- (+ (* blank 3) 2) (floor (/ blank 2)))) (format stream " ")) (setf n oldn) (do ((i 0 (+ i 1)) (b nil)) ((or (not (< i 16)) (not (< n bytes))) (decf toprint i)) (setf b (elt data n)) (if (< 31 b 127) (format stream (make-string 1 :initial-element (code-char b))) (format stream ".")) (incf n)) (format stream "~%") (incf offs 16)) (when (> rest 0) (format stream " [... (~s Bytes remaining)]~%" rest)) (values))) (defun print-sysex-data (stream string lines data length) (let ((bytes 0) (rest 0)) (unless length (setf length (length data))) (setf lines (if (numberp lines) lines 0)) (setf bytes (if (and (> lines 0) (< (* lines 16) length)) (* (- lines 1) 16) length)) (setf rest (- length bytes)) (if string (error "string output not supported") (when stream (%print-sysex-aux stream data bytes rest nil))))) (defun midi-print-message (msg time &key data length (stream t) (time-format t) (time-string "") (gm *midi-gm-mode*) (eol t) (delimit t)) (when (and time time-format) (format stream "~a " (format-integer time 8 #\ ))) (when delimit (format stream "#<")) (cond ((midi-channel-message-p msg) (let* ((size (midimsg-size msg)) (op (channel-message-opcode msg)) (chan (channel-message-channel msg)) (data1 (channel-message-data1 msg)) (data2 (channel-message-data2 msg))) (midi-print-channel-message stream gm size op chan data1 data2 time-string))) ((midi-system-message-p msg) (let ((name (elt +ml-msg-type-strings+ (ldb +enc-lower-status-byte+ msg))) (route (ldb +enc-route-byte+ msg)) (size (midimsg-size msg))) (format stream "~a~a ~s" name time-string route) (cond ((= size 3) (format stream " ~s ~s" (midimsg-data1 msg) (midimsg-data2 msg))) ((= size 2) (format stream " ~s" (midimsg-data1 msg))) (t (when delimit (format stream ">") (setf delimit nil)) (when (sysex-p msg) (format stream "~%") (print-sysex-data t nil 0 data length)))))) ((midi-meta-message-p msg) (cond ((or (midi-channel-p msg) (midi-port-p msg)) (format stream "~a~a ~s" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (if data (elt data 1) "?"))) ((tempo-change-p msg) (format stream "~a~a ~s ms" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (/ (+ (ash (elt data 1) 16) (ash (elt data 2) 8) (elt data 3)) 1000))) ((time-signature-p msg) (format stream "~a~a ~s/~s (~s clocks, ~s 32nds)" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (elt data 1) (expt 2 (elt data 2)) (elt data 3) (elt data 4))) ((key-signature-p msg) (let ((a (elt data 1)) (s nil)) (setf a (or (and (logtest a 128) (- a 256)) a)) (setf s (if (> (abs a) 1) "s" "")) (format stream "~a~a ~a ~a~a, ~a" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (if (zerop a) "no" (abs a)) (case (signum a) ((-1) "flat") ((0) "accidentals") ((1) "sharp")) s (if (zerop (elt data 2)) "major" "minor")))) (t (format stream "~a~a" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string) (if data (format stream " ~s" (if (text-meta-event-p msg) (text-meta-event-data-to-string data) data)) (format stream ">"))))) (t (format stream "Bogus Midi Message~a]" time-string))) (when delimit (format stream ">")) (when eol (terpri stream)) msg) (defparameter %deflabelvar% (gensym)) (defmacro deflabel (sym val vector str pos) `(progn (defparameter ,sym ,val) ,(if str `(setf (elt ,vector ,pos) ,str) `(let ((*print-case* ':downcase)) (setf %deflabelvar% (format nil "~a" ',sym)) (do ((i 0 (+ i 1)) (e (length %deflabelvar%))) ((not (< i e)) nil) (if (char= (elt %deflabelvar% i) #\ ) (setf (elt %deflabelvar% i) #\-))) (setf (elt ,vector ,pos) (subseq %deflabelvar% 1 (- (length %deflabelvar%) 1))))))) (defparameter +midi-controller-strings+ (make-array 128 :initial-element "")) (defmacro defcontroller (sym val &body str) `(deflabel ,sym ,val +midi-controller-strings+ ,(if (null str) nil (car str)) ,val)) (defun midi-opcode-name (vec code lb ub delta) (cond ((and (integerp code) (<= lb code ub)) (elt vec (+ code delta))) ((stringp code) code) (t (error "MIDI opcode ~s not string or int ~s-~s." code lb ub)))) (defun midi-controller-name (c) (midi-opcode-name +midi-controller-strings+ c 0 127 0)) (defcontroller +bank-select+ 0) (defcontroller +modulation-wheel+ 1) (defcontroller +breath-control+ 2) (defcontroller +foot-controller+ 4) (defcontroller +portamento-time+ 5) (defcontroller +data-entry+ 6) (defcontroller +channel-volume+ 7) (defparameter +volume+ 7) (defcontroller +balance+ 8) (defcontroller +pan+ 10) (defcontroller +expression-controller+ 11) (defcontroller +effect-control-1+ 12) (defcontroller +effect-control-2+ 13) (defcontroller +general-purpose-controller-1+ 16 "General-Purpose Controller 1") (defcontroller +general-purpose-controller-2+ 17 "General-Purpose Controller 2") (defcontroller +general-purpose-controller-3+ 18 "General-Purpose Controller 3") (defcontroller +general-purpose-controller-4+ 19 "General-Purpose Controller 4") (defcontroller +bank-select-fine+ 32 "Bank Select (Fine)") (defcontroller +modulation-wheel-fine+ 33 "Modulation Wheel (Fine)") (defcontroller +breath-control-fine+ 34 "Breath Control (Fine)") (defcontroller +foot-controller-fine+ 36 "Foot Controller (Fine)") (defcontroller +portamento-time-fine+ 37 "Portamento Time (Fine)") (defcontroller +data-entry-fine+ 38 "Data Entry (Fine)") (defcontroller +channel-volume-fine+ 39 "Channel Volume (Fine)") (defparameter +volume-fine+ 39) (defcontroller +balance-fine+ 40 "Balance (Fine)") (defcontroller +pan-fine+ 42 "Pan (Fine)") (defcontroller +expression-controller-fine+ 43 "Expression Controller (Fine)") (defcontroller +effect-control-1-fine+ 44 "Effect Control 1 (Fine)") (defcontroller +effect-control-2-fine+ 45 "Effect Control 2 (Fine)") (defcontroller +general-purpose-controller-1-fine+ 48 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-2-fine+ 49 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-3-fine+ 50 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-4-fine+ 51 "General-Purpose Controller 1 (Fine)") (defcontroller +hold-1+ 64) (defparameter +sustain+ 64) (defparameter +damper-pedal+ 64) (defcontroller +portamento+ 65) (defcontroller +sostenuto+ 66) (defcontroller +soft-pedal+ 67) (defcontroller +legato-footswitch+ 68) (defcontroller +hold-2+ 69) (defcontroller +sound-control-1+ 70) (defparameter +sound-variation+ 70) (defcontroller +sound-control-2+ 71) (defparameter +sound-timbre+ 71) (defcontroller +sound-control-3+ 72) (defparameter +sound-release-time+ 72) (defcontroller +sound-control-4+ 73) (defparameter +sound-attack-time+ 73) (defcontroller +sound-control-5+ 74) (defparameter +sound-brightness+ 74) (defcontroller +sound-control-6+ 75) (defcontroller +sound-control-7+ 76) (defcontroller +sound-control-8+ 77) (defcontroller +sound-control-9+ 78) (defcontroller +sound-control-10+ 79) (defcontroller +general-purpose-controller-5+ 80 "General-Purpose Controller 5") (defcontroller +general-purpose-controller-6+ 81 "General-Purpose Controller 6") (defcontroller +general-purpose-controller-7+ 82 "General-Purpose Controller 7") (defcontroller +general-purpose-controller-8+ 83 "General-Purpose Controller 8") (defcontroller +portamento-control+ 84) (defcontroller +effects-1-depth+ 91) (defparameter +effects-level+ 91) (defcontroller +effects-2-depth+ 92) (defparameter +tremolo-level+ 92) (defcontroller +effects-3-depth+ 93) (defparameter +chorus-level+ 93) (defcontroller +effects-4-depth+ 94) (defparameter +detune-level+ 94) (defcontroller +effects-5-depth+ 95) (defparameter +phasor-level+ 95) (defcontroller +data-entry-+1+ 96) (defparameter +data-entry-increment+ 96) (defcontroller +data-entry--1+ 97 "Data Entry -1") (defparameter +data-entry-decrement+ 97) (defcontroller +non-registered-parameter-number-fine+ 98 "Non-Registered Parameter Number (Fine)") (defcontroller +non-registered-parameter-number+ 99 "Non-Registered Parameter Number") (defcontroller +registered-parameter-number-fine+ 100 "Registered Parameter Number (Fine)") (defcontroller +registered-parameter-number+ 101) (defcontroller +all-sound-off+ 120) (defcontroller +reset-all-controllers+ 121) (defcontroller +local-control+ 122) (defcontroller +all-notes-off+ 123) (defcontroller +omni-mode-off+ 124) (defcontroller +omni-mode-on+ 125) (defcontroller +poly-mode-on/off+ 126) (defcontroller +poly-mode-on+ 127) (defparameter +rpn-pitch-bend-sensitivity+ (quote (0 0))) (defparameter +rpn-fine-tuning+ (quote (0 1))) (defparameter +rpn-coarse-tuning+ (quote (0 2))) (defparameter +rpn-reset+ (quote (63 255))) (defparameter +gm-patch-strings+ (make-array 128 :initial-element '"")) (defparameter +gm-drum-kit-strings+ (make-array 50 :initial-element '"")) (defmacro defgmpatch (sym val &body str) `(deflabel ,sym ,val +gm-patch-strings+ ,(if (null str) nil (car str)) ,val)) (defmacro defgmdrum (sym val &body str) `(deflabel ,sym ,val +gm-drum-kit-strings+ ,(if (null str) nil (car str)) ,(- val 32))) (defun gm-patch-name (patch) (midi-opcode-name +gm-patch-strings+ patch 0 127 0)) (defun gm-drum-kit-name (key) (midi-opcode-name +gm-drum-kit-strings+ key 35 81 -32)) (defgmpatch +acoustic-grand-piano+ 0) (defgmpatch +bright-acoustic-piano+ 1) (defgmpatch +electric-grand-piano+ 2) (defgmpatch +honky-tonk-piano+ 3) (defgmpatch +electric-piano-1+ 4) (defgmpatch +electric-piano-2+ 5) (defgmpatch +harpsichord+ 6) (defgmpatch +clavi+ 7) (defgmpatch +celesta+ 8) (defgmpatch +glockenspiel+ 9) (defgmpatch +music-box+ 10) (defgmpatch +vibraphone+ 11) (defgmpatch +marimba+ 12) (defgmpatch +xylophone+ 13) (defgmpatch +tubular-bells+ 14) (defgmpatch +dulcimer+ 15) (defgmpatch +drawbar-organ+ 16) (defgmpatch +percussive-organ+ 17) (defgmpatch +rock-organ+ 18) (defgmpatch +church-organ+ 19) (defgmpatch +reed-organ+ 20) (defgmpatch +accordion+ 21) (defgmpatch +harmonica+ 22) (defgmpatch +tango-accordion+ 23) (defgmpatch +acoustic-guitar-nylon+ 24) (defgmpatch +acoustic-guitar-steel+ 25) (defgmpatch +electric-guitar-jazz+ 26) (defgmpatch +electric-guitar-clean+ 27) (defgmpatch +electric-guitar-muted+ 28) (defgmpatch +overdriven-guitar+ 29) (defgmpatch +distortion-guitar+ 30) (defgmpatch +guitar-harmonics+ 31) (defgmpatch +acoustic-bass+ 32) (defgmpatch +electric-bass-finger+ 33) (defgmpatch +electric-bass-pick+ 34) (defgmpatch +fretless-bass+ 35) (defgmpatch +slap-bass-1+ 36) (defgmpatch +slap-bass-2+ 37) (defgmpatch +synth-bass-1+ 38) (defgmpatch +synth-bass-2+ 39) (defgmpatch +violin+ 40) (defgmpatch +viola+ 41) (defgmpatch +cello+ 42) (defgmpatch +contrabass+ 43) (defgmpatch +tremolo-strings+ 44) (defgmpatch +pizzicato-strings+ 45) (defgmpatch +orchestral-strings+ 46) (defgmpatch +timpani+ 47) (defgmpatch +string-ensemble-1+ 48) (defgmpatch +string-ensemble-2+ 49) (defgmpatch +synthstrings-1+ 50) (defgmpatch +synthstrings-2+ 51) (defgmpatch +choir-aahs+ 52) (defgmpatch +voice-oohs+ 53) (defgmpatch +synth-voice+ 54) (defgmpatch +orchestra-hit+ 55) (defgmpatch +trumpet+ 56) (defgmpatch +trombone+ 57) (defgmpatch +tuba+ 58) (defgmpatch +muted-trumpet+ 59) (defgmpatch +french-horn+ 60) (defgmpatch +brass-section+ 61) (defgmpatch +synthbrass-1+ 62) (defgmpatch +synthbrass-2+ 63) (defgmpatch +soprano-sax+ 64) (defgmpatch +alto-sax+ 65) (defgmpatch +tenor-sax+ 66) (defgmpatch +baritone-sax+ 67) (defgmpatch +oboe+ 68) (defgmpatch +english-horn+ 69) (defgmpatch +bassoon+ 70) (defgmpatch +clarinet+ 71) (defgmpatch +piccolo+ 72) (defgmpatch +flute+ 73) (defgmpatch +recorder+ 74) (defgmpatch +pan-flute+ 75) (defgmpatch +blown-bottle+ 76) (defgmpatch +skakuhachi+ 77) (defgmpatch +whistle+ 78) (defgmpatch +ocarina+ 79) (defgmpatch +lead-1-square+ 80 "Lead 1 (Square)") (defparameter +lead-1+ 80) (defparameter +square-lead+ 80) (defparameter +square+ 80) (defgmpatch +lead-2-sawtooth+ 81 "Lead 2 (Sawtooth)") (defparameter +lead-2+ 81) (defparameter +sawtooth-lead+ 81) (defparameter +sawtooth+ 81) (defgmpatch +lead-3-calliope+ 82 "Lead 3 (Calliope)") (defparameter +lead-3+ 82) (defparameter +calliope-lead+ 82) (defparameter +calliope+ 82) (defgmpatch +lead-4-chiff+ 83 "Lead 4 (Chiff)") (defparameter +lead-4+ 83) (defparameter +chiff-lead+ 83) (defparameter +chiff+ 83) (defgmpatch +lead-5-charang+ 84 "Lead 5 (Charang)") (defparameter +lead-5+ 84) (defparameter +charang-lead+ 84) (defparameter +charang+ 84) (defgmpatch +lead-6-voice+ 85 "Lead 6 (Voice)") (defparameter +lead-6+ 85) (defparameter +voice-lead+ 85) (defparameter +voice+ 85) (defgmpatch +lead-7-fifths+ 86 "Lead 7 (Fifths)") (defparameter +lead-7+ 86) (defparameter +fifths-lead+ 86) (defparameter +fifths+ 86) (defgmpatch +lead-8-bass+lead+ 87 "Lead 8 (Bass+Lead)") (defparameter +lead-8+ 87) (defparameter +bass+lead-lead+ 87) (defparameter +bass+lead+ 87) (defgmpatch +pad-1-new-age+ 88 "Pad 1 (New Age)") (defparameter +pad-1+ 88) (defparameter +new-age-pad+ 88) (defparameter +new-age+ 88) (defgmpatch +pad-2-warm+ 89 "Pad 2 (Warm)") (defparameter +pad-2+ 89) (defparameter +warm-pad+ 89) (defparameter +warm+ 89) (defgmpatch +pad-3-polysynth+ 90 "Pad 3 (Polysynth)") (defparameter +pad-3+ 90) (defparameter +polysynth-pad+ 90) (defparameter +polysynth+ 90) (defgmpatch +pad-4-choir+ 91 "Pad 4 (Choir)") (defparameter +pad-4+ 91) (defparameter +choir-pad+ 91) (defparameter +choir+ 91) (defgmpatch +pad-5-bowed+ 92 "Pad 5 (Bowed)") (defparameter +pad-5+ 92) (defparameter +bowed-pad+ 92) (defparameter +bowed+ 92) (defgmpatch +pad-6-metallic+ 93 "Pad 6 (Metallic)") (defparameter +pad-6+ 93) (defparameter +metallic-pad+ 93) (defparameter +metallic+ 93) (defgmpatch +pad-7-halo+ 94 "Pad 7 (Halo)") (defparameter +pad-7+ 94) (defparameter +halo-pad+ 94) (defparameter +halo+ 94) (defgmpatch +pad-8-sweep+ 95 "Pad 8 (Sweep)") (defparameter +pad-8+ 95) (defparameter +sweep-pad+ 95) (defparameter +sweep+ 95) (defgmpatch +fx-1-rain+ 96 "FX 1 (Rain)") (defparameter +fx-1+ 96) (defparameter +rain-fx+ 96) (defparameter +rain+ 96) (defgmpatch +fx-2-soundtrack+ 97 "FX 2 (Soundtrack)") (defparameter +fx-2+ 97) (defparameter +soundtrack-fx+ 97) (defparameter +soundtrack+ 97) (defgmpatch +fx-3-crystal+ 98 "FX 3 (Crystal)") (defparameter +fx-3+ 98) (defparameter +crystal-fx+ 98) (defparameter +crystal+ 98) (defgmpatch +fx-4-atmosphere+ 99 "FX 4 (Atmosphere)") (defparameter +fx-4+ 99) (defparameter +atmosphere-fx+ 99) (defparameter +atmosphere+ 99) (defgmpatch +fx-5-brightness+ 100 "FX 5 (Brightness)") (defparameter +fx-5+ 100) (defparameter +brightness-fx+ 100) (defparameter +brightness+ 100) (defgmpatch +fx-6-goblins+ 101 "FX 6 (Goblins)") (defparameter +fx-6+ 101) (defparameter +goblins-fx+ 101) (defparameter +goblins+ 101) (defgmpatch +fx-7-echoes+ 102 "FX 7 (Echoes)") (defparameter +fx-7+ 102) (defparameter +echoes-fx+ 102) (defparameter +echoes+ 102) (defgmpatch +fx-8-sci-fi+ 103 "FX 8 (Sci-Fi)") (defparameter +fx-8+ 103) (defparameter +sci-fi-fx+ 103) (defparameter +sci-fi+ 103) (defgmpatch +sitar+ 104) (defgmpatch +banjo+ 105) (defgmpatch +shamisen+ 106) (defgmpatch +koto+ 107) (defgmpatch +kalimba+ 108) (defgmpatch +bagpipe+ 109) (defgmpatch +fiddle+ 110) (defgmpatch +shanai+ 111) (defgmpatch +tinkle-bell+ 112) (defgmpatch +agogo+ 113) (defgmpatch +steel-drums+ 114) (defgmpatch +woodblock+ 115) (defgmpatch +taiko-drum+ 116) (defgmpatch +melodic-tom+ 117) (defgmpatch +synth-drum+ 118) (defgmpatch +reverse-cymbal+ 119) (defgmpatch +guitar-fret-noise+ 120) (defgmpatch +breath-noise+ 121) (defgmpatch +seashore+ 122) (defgmpatch +bird-tweet+ 123) (defgmpatch +telephone-ring+ 124) (defgmpatch +helicopter+ 125) (defgmpatch +applause+ 126) (defgmpatch +gunshot+ 127) (defparameter *gm-percussion-channels* #(9)) (defun gm-percussion-channel-p (chan) (do ((i 0 (+ i 1)) (f nil) (e (length *gm-percussion-channels*))) ((or f (not (< i e))) f) (setf f (= (elt *gm-percussion-channels* i) chan)))) (defgmdrum +acoustic-bass-drum+ 35) (defgmdrum +bass-drum-1+ 36) (defgmdrum +side-stick+ 37) (defgmdrum +acoustic-snare+ 38) (defgmdrum +hand-clap+ 39) (defgmdrum +electric-snare+ 40) (defgmdrum +low-floor-tom+ 41) (defgmdrum +closed-hi-hat+ 42) (defgmdrum +high-floor-tom+ 43) (defgmdrum +pedal-hi-hat+ 44) (defgmdrum +low-tom+ 45) (defgmdrum +open-hi-hat+ 46) (defgmdrum +low-mid-tom+ 47) (defgmdrum +hi-mid-tom+ 48) (defgmdrum +crash-cymbal-1+ 49) (defgmdrum +high-tom+ 50) (defgmdrum +ride-cymbal-1+ 51) (defgmdrum +chinese-cymbal+ 52) (defgmdrum +ride-bell+ 53) (defgmdrum +tambourine+ 54) (defgmdrum +splash-cymbal+ 55) (defgmdrum +cowbell+ 56) (defgmdrum +crash-cymbal-2+ 57) (defgmdrum +vibraslap+ 58) (defgmdrum +ride-cymbal-2+ 59) (defgmdrum +hi-bongo+ 60) (defgmdrum +low-bongo+ 61) (defgmdrum +mute-hi-conga+ 62) (defgmdrum +open-hi-conga+ 63) (defgmdrum +low-conga+ 64) (defgmdrum +high-timbale+ 65) (defgmdrum +low-timbale+ 66) (defgmdrum +high-agogo+ 67) (defgmdrum +low-agogo+ 68) (defgmdrum +cabasa+ 69) (defgmdrum +maracas+ 70) (defgmdrum +short-whistle+ 71) (defgmdrum +long-whistle+ 72) (defgmdrum +short-guiro+ 73) (defgmdrum +long-guiro+ 74) (defgmdrum +claves+ 75) (defgmdrum +hi-wood-block+ 76) (defgmdrum +low-wood-block+ 77) (defgmdrum +mute-cuica+ 78) (defgmdrum +open-cuica+ 79) (defgmdrum +mute-triangle+ 80) (defgmdrum +open-triangle+ 81) (defparameter +sequential-circuits-id+ 1) (defparameter +idp-id+ 2) (defparameter +voyetra-id+ 3) (defparameter +moog-id+ 4) (defparameter +passport-id+ 5) (defparameter +lexicon-id+ 6) (defparameter +kurzweil-id+ 7) (defparameter +fender-id+ 8) (defparameter +gulbransen-id+ 9) (defparameter +akg-id+ 10) (defparameter +voyce-id+ 11) (defparameter +waveframe-id+ 12) (defparameter +ada-id+ 13) (defparameter +garfield-id+ 14) (defparameter +ensoniq-id+ 15) (defparameter +oberheim-id+ 16) (defparameter +apple-id+ 17) (defparameter +grey-matter-id+ 18) (defparameter +digidesign-id+ 19) (defparameter +palm-tree-id+ 20) (defparameter +jl-cooper-id+ 21) (defparameter +lowrey-id+ 22) (defparameter +adams-smith-id+ 23) (defparameter +e-mu-id+ 24) (defparameter +harmony-id+ 25) (defparameter +art-id+ 26) (defparameter +baldwin-id+ 27) (defparameter +eventide-id+ 28) (defparameter +inventronics-id+ 29) (defparameter +key-concepts-id+ 30) (defparameter +clarity-id+ 31) (defparameter +passac-id+ 32) (defparameter +siel-id+ 33) (defparameter +synthaxe-id+ 34) (defparameter +stepp-id+ 35) (defparameter +hohner-id+ 36) (defparameter +twister-id+ 37) (defparameter +solton-id+ 38) (defparameter +jellinghaus-id+ 39) (defparameter +southworth-id+ 40) (defparameter +ppg-id+ 41) (defparameter +jen-id+ 42) (defparameter +solid-state-id+ 43) (defparameter +audio-vertrieb-id+ 44) (defparameter +hinton-id+ 45) (defparameter +soundtracs-id+ 46) (defparameter +elka-id+ 47) (defparameter +dynachord-id+ 48) (defparameter +clavia-id+ 51) (defparameter +audio-architecture-id+ 52) (defparameter +soundcraft-id+ 57) (defparameter +wersi-id+ 59) (defparameter +avab-id+ 60) (defparameter +digigram-id+ 61) (defparameter +waldorf-id+ 62) (defparameter +quasimidi-id+ 63) (defparameter +kawai-id+ 64) (defparameter +roland-id+ 65) (defparameter +korg-id+ 66) (defparameter +yamaha-id+ 67) (defparameter +casio-id+ 68) (defparameter +moridaira-id+ 69) (defparameter +kamiya-id+ 70) (defparameter +akai-id+ 71) (defparameter +japan-victor-id+ 72) (defparameter +meisosha-id+ 73) (defparameter +hoshino-gakki-id+ 74) (defparameter +fujitsu-id+ 75) (defparameter +sony-id+ 76) (defparameter +nishin-onpa-id+ 77) (defparameter +teac-id+ 78) (defparameter +matsushita-electric-id+ 80) (defparameter +fostex-id+ 81) (defparameter +zoom-id+ 82) (defparameter +midori-id+ 83) (defparameter +matsushita-communication-id+ 84) (defparameter +suzuki-id+ 85) (defparameter +warner-id+ (quote (0 0 1))) (defparameter +digital-music-id+ (quote (0 0 7))) (defparameter +iota-id+ (quote (0 0 8))) (defparameter +new-england-id+ (quote (0 0 9))) (defparameter +artisyn-id+ (quote (0 0 10))) (defparameter +ivl-id+ (quote (0 0 11))) (defparameter +southern-music-id+ (quote (0 0 12))) (defparameter +lake-butler-id+ (quote (0 0 13))) (defparameter +alesis-id+ (quote (0 0 14))) (defparameter +dod-id+ (quote (0 0 16))) (defparameter +studer-id+ (quote (0 0 17))) (defparameter +perfect-fretworks-id+ (quote (0 0 20))) (defparameter +kat-id+ (quote (0 0 21))) (defparameter +opcode-id+ (quote (0 0 22))) (defparameter +rane-id+ (quote (0 0 23))) (defparameter +spatial-sound-id+ (quote (0 0 24))) (defparameter +kmx-id+ (quote (0 0 25))) (defparameter +allen-&-heath-id+ (quote (0 0 26))) (defparameter +peavey-id+ (quote (0 0 27))) (defparameter +360-id+ (quote (0 0 28))) (defparameter +spectrum-id+ (quote (0 0 29))) (defparameter +marquis-musi-id+ (quote (0 0 30))) (defparameter +zeta-id+ (quote (0 0 31))) (defparameter +axxes-id+ (quote (0 0 32))) (defparameter +orban-id+ (quote (0 0 33))) (defparameter +kti-id+ (quote (0 0 36))) (defparameter +breakaway-id+ (quote (0 0 37))) (defparameter +cae-id+ (quote (0 0 38))) (defparameter +rocktron-id+ (quote (0 0 41))) (defparameter +pianodisc-id+ (quote (0 0 42))) (defparameter +cannon-id+ (quote (0 0 43))) (defparameter +rogers-id+ (quote (0 0 45))) (defparameter +blue-sky-id+ (quote (0 0 46))) (defparameter +encore-id+ (quote (0 0 47))) (defparameter +uptown-id+ (quote (0 0 48))) (defparameter +voce-id+ (quote (0 0 49))) (defparameter +cti-id+ (quote (0 0 50))) (defparameter +s&s-id+ (quote (0 0 51))) (defparameter +broderbund-id+ (quote (0 0 52))) (defparameter +allen-organ-id+ (quote (0 0 53))) (defparameter +music-quest-id+ (quote (0 0 55))) (defparameter +aphex-id+ (quote (0 0 56))) (defparameter +gallien-krueger-id+ (quote (0 0 57))) (defparameter +ibm-id+ (quote (0 0 58))) (defparameter +hotz-id+ (quote (0 0 60))) (defparameter +eta-id+ (quote (0 0 61))) (defparameter +nsi-id+ (quote (0 0 62))) (defparameter +ad-lib-id+ (quote (0 0 63))) (defparameter +richmond-id+ (quote (0 0 64))) (defparameter +microsoft-id+ (quote (0 0 65))) (defparameter +software-toolworks-id+ (quote (0 0 66))) (defparameter +rjmg/niche-id+ (quote (0 0 67))) (defparameter +intone-id+ (quote (0 0 68))) (defparameter +gt-electronics-id+ (quote (0 0 71))) (defparameter +intermidi-id+ (quote (0 0 72))) (defparameter +lone-wolf-id+ (quote (0 0 85))) (defparameter +musonix-id+ (quote (0 0 100))) (defparameter +sgi-id+ (quote (0 1 4))) (defparameter +dream-id+ (quote (0 32 0))) (defparameter +strand-id+ (quote (0 32 0))) (defparameter +amek-id+ (quote (0 32 0))) (defparameter +dr.boehm-id+ (quote (0 32 0))) (defparameter +trident-id+ (quote (0 32 0))) (defparameter +real-world-id+ (quote (0 32 0))) (defparameter +yes-id+ (quote (0 32 0))) (defparameter +audiomatica-id+ (quote (0 32 0))) (defparameter +bontempi-id+ (quote (0 32 0))) (defparameter +fbt-id+ (quote (0 32 0))) (defparameter +larking-id+ (quote (0 32 0))) (defparameter +zero-88-id+ (quote (0 32 0))) (defparameter +micon-id+ (quote (0 32 16))) (defparameter +forefront-id+ (quote (0 32 16))) (defparameter +kenton-id+ (quote (0 32 16))) (defparameter +adb-id+ (quote (0 32 16))) (defparameter +marshall-id+ (quote (0 32 16))) (defparameter +dda-id+ (quote (0 32 16))) (defparameter +tc-id+ (quote (0 32 16))) (defparameter +non-commercial-id+ 125) (defparameter +non-real-time-id+ 126) (defparameter +sample-dump-header-sub-id+ 1) (defparameter +sample-dump-packet-sub-id+ 2) (defparameter +dump-request-sub-id+ 3) (defparameter +midi-time-code-setup-sub-id+ 4) (defparameter +sample-dump-extensions-sub-id+ 5) (defparameter +inquiry-message-sub-id+ 6) (defparameter +file-dump-sub-id+ 7) (defparameter +midi-tuning-standard-sub-id+ 8) (defparameter +general-midi-message-sub-id+ 9) (defparameter +end-of-file-sub-id+ 123) (defparameter +wait-sub-id+ 124) (defparameter +cancel-sub-id+ 125) (defparameter +nak-sub-id+ 126) (defparameter +ack-sub-id+ 127) (defparameter +real-time-id+ 127) (defparameter +long-form-mtc-sub-id+ 1) (defparameter +midi-show-control-sub-id+ 2) (defparameter +notation-information-sub-id+ 3) (defparameter +device-control-sub-id+ 4) (defparameter +real-time-mtc-cueing-sub-id+ 5) (defparameter +midi-machine-control-command-sub-id+ 6) (defparameter +midi-machine-control-response-sub-id+ 7) (defparameter +single-note-retune-sub-id+ 8) (defun n-bit-twoscomp-p (num bits signed? &rest args) (let ((error? (if (null args) nil (car args)))) (if signed? (if (and (< num 0) (<= (integer-length num) bits)) t (if error? (error "Not a signed ~s-bit byte: ~s." bits num) nil)) (if (and (not (< num 0)) (<= (integer-length num) bits)) t (if error? (error "Not an unsigned ~s-bit byte: ~s." bits num) nil))))) (defun n-bit-twoscomp (num bits signed?) (n-bit-twoscomp-p num bits signed? t) (if (< num 0) (+ num (expt 2 bits)) num)) (defun n-bit-bytes (num bytes bits lsb-first?) (n-bit-twoscomp-p num (* bytes bits) (< num 0) t) (let ((l '())) (do ((i 0 (+ i 1))) ((not (< i bytes)) nil) (setf l (cons (ldb (byte bits (* i bits)) num) l))) (if lsb-first? (reverse l) l))) (defun nibblize (lsb-first? &rest data) (let ((res '()) (o1 (if lsb-first? 0 4)) (o2 (if lsb-first? 4 0))) (labels ((nblize (x) (cond ((stringp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i))) (nblize 0)) ((vectorp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i)))) ((consp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i)))) ((characterp x) (setf x (char-code x)) (push (ldb (byte 4 o1) x) res) (push (ldb (byte 4 o2) x) res)) ((integerp x) (push (ldb (byte 4 o1) x) res) (push (ldb (byte 4 o2) x) res)) (t nil)))) (loop for d in data do (nblize d)) (nreverse res)))) (defparameter +all-device-ids+ 127) (defun make-gm-mode-sysex-data (gm-on? &key (device-id +all-device-ids+)) (make-sysex-data +non-real-time-id+ device-id +general-midi-message-sub-id+ (if gm-on? 1 0))) (defparameter +master-volume-sub-id-2+ 1) (defun make-master-volume-sysex-data (&key coarse fine (device-id +all-device-ids+)) (unless (or coarse fine) (error "No volume specified.")) (unless (or (and coarse (n-bit-twoscomp-p coarse 7 nil)) (and fine (n-bit-twoscomp-p fine 14 nil))) (error "~a volume ~a is not a ~a-bit value." (if fine "Fine" "Course") (or coarse fine) (if fine "14" "7"))) (make-sysex-data +real-time-id+ device-id +device-control-sub-id+ +master-volume-sub-id-2+ (if fine (logand fine 127) coarse) (if fine (ash (logand fine 16256) -7) coarse))) (defparameter +smpte-full-frame-sub-id-2+ 1) (defparameter +smpte-user-bits-sub-id-2+ 2) (defparameter +smpte-format-24fps+ 0) (defparameter +smpte-format-25fps+ 1) (defparameter +smpte-format-30fps-drop+ 2) (defparameter +smpte-format-30fps+ 3) (defun encode-smpte-data (hr mn sc fr &key subframes format) (unless (and (<= 0 hr 23) (<= 0 mn 59) (<= 0 sc 59) (<= 0 fr (cond ((= format +smpte-format-24fps+) 23) ((= format +smpte-format-25fps+) 24) ((or (= format +smpte-format-30fps-drop+) (= format +smpte-format-30fps+)) 29) (t (error "Not a valid SMPTE format ID: ~a." format)))) (or (not subframes) (<= 0 subframes 99))) (error "SMPTE values out of range: ~a ~a ~a ~a ~s." hr mn sc fr subframes)) (setf hr (dpb format (byte 3 5) hr)) (if subframes (list hr mn sc fr subframes) (list hr mn sc fr))) (defun make-smpte-full-frame-sysex-data (hr mn sc fr &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (make-sysex-data +real-time-id+ device-id +long-form-mtc-sub-id+ +smpte-full-frame-sub-id-2+ (encode-smpte-data hr mn sc fr :format format))) (defparameter +smpte-user-bits-raw+ 0) (defparameter +smpte-user-bits-chars+ 2) (defun make-smpte-user-bits-sysex-data (format data &key (device-id +all-device-ids+)) (let* ((fmt (case format ((:raw) 0) ((:bytes) 1) ((:chars) 2) ((:string) 3) (t (error ":format not one of :raw :bytes :chars :string")))) (size (if (= fmt 0) 4 8)) (len nil) (ref nil)) (cond ((stringp data) (setf len (length data)) (setf ref #'elt)) ((vectorp data) (setf len (length data)) (setf ref #'elt)) ((listp data) (setf len (length len)) (setf ref #'elt))) (unless (= len (if (= size 4) 8 4)) (error "~a format requires ~d data bytes, got: ~s." format (if (= size 4) 8 4) data)) (unless (case fmt ((0 1) (do ((f t) (i 0 (+ i 1)) (z nil)) ((or (not (< i len)) (not f)) f) (setf z (funcall ref data)) (setf f (and (integerp z) (<= 0 z size))))) ((2) (do ((f t) (i 0 (+ i 1))) ((or (not (< i len)) (not f)) f) (setf f (characterp (funcall ref data))))) ((3) (stringp data))) (error "Not valid ~d-bit data: ~s" size data)) (flet ((datafn (n) (if (= fmt 0) (funcall ref data n) (let ((d (funcall ref data (floor n 2)))) (when (>= fmt 2) (setf d (char-code d))) (if (evenp n) (ash (logand d 240) -4) (logand d 15)))))) (make-sysex-data +real-time-id+ device-id +long-form-mtc-sub-id+ +smpte-user-bits-sub-id-2+ (datafn 0) (datafn 1) (datafn 2) (datafn 3) (datafn 4) (datafn 5) (datafn 6) (datafn 7) (if (= fmt 2) +smpte-user-bits-chars+ +smpte-user-bits-raw+))))) (defparameter +bar-marker-sub-id-2+ 1) (defun make-measure-number-sysex-data (num &key (countoff nil) (device-id +all-device-ids+)) (when countoff (setf num (- (abs num)))) (setf num (n-bit-twoscomp num 14 t)) (make-sysex-data +real-time-id+ device-id +notation-information-sub-id+ +bar-marker-sub-id-2+ (ldb (byte 7 0) num) (ldb (byte 7 7) num))) (defparameter +time-signature-now-sub-id-2+ 2) (defparameter +time-signature-next-measure-sub-id-2+ 66) (defun make-time-signature-sysex-data (numerators denominators &key (32nds 8) (defer nil) (device-id +all-device-ids+)) (unless (listp numerators) (setf numerators (list numerators))) (unless (listp denominators) (setf denominators (list denominators))) (let* ((len (max (length numerators) (length denominators))) (args (loop with f and r for i from 0 for n = (or (elt numerators i) n) for d = (or (elt denominators i) d) repeat len do (multiple-value-setq (f r) (floor (log2 d))) collect n collect (if (not (zerop r)) (error "Not a power of 2: ~s" d) f)))) (make-sysex-data +real-time-id+ device-id +notation-information-sub-id+ (if defer +time-signature-next-measure-sub-id-2+ +time-signature-now-sub-id-2+) (+ (* 2 len) 1) (first args) (second args) 32nds (cdr (cdr args))))) (defparameter +setup-special-sub-id-2+ 0) (defparameter +setup-punch-in-point-sub-id-2+ 1) (defparameter +setup-punch-out-point-sub-id-2+ 2) (defparameter +setup-delete-punch-in-point-sub-id-2+ 3) (defparameter +setup-delete-punch-out-point-sub-id-2+ 4) (defparameter +setup-event-start-point-sub-id-2+ 5) (defparameter +setup-event-stop-point-sub-id-2+ 6) (defparameter +setup-xtnd-event-start-point-sub-id-2+ 7) (defparameter +setup-xtnd-event-stop-point-sub-id-2+ 8) (defparameter +setup-delete-event-start-point-sub-id-2+ 9) (defparameter +setup-delete-event-stop-point-sub-id-2+ 10) (defparameter +setup-cue-point-sub-id-2+ 11) (defparameter +setup-xtnd-cue-point-sub-id-2+ 12) (defparameter +setup-delete-cue-point-sub-id-2+ 13) (defparameter +setup-event-name-sub-id-2+ 14) (defun %make-setup-data (dev subid2 fmt hr mn sc fr ff num &optional xtnd) (make-sysex-data +non-real-time-id+ dev +midi-time-code-setup-sub-id+ subid2 (encode-smpte-data hr mn sc fr :subframes ff :format fmt) (cond ((and (listp num) (= (length num) 2)) (n-bit-twoscomp-p (car num) 7 (< (car num) 0) t) (n-bit-twoscomp-p (cadr num) 7 (< (cadr num) 0) t) num) ((and (vectorp num) (= (length num) 2)) (n-bit-twoscomp-p (elt num 0) 7 (< (elt num 0) 0) t) (n-bit-twoscomp-p (elt num 1) 7 (< (elt num 1) 0) t) num) (t (n-bit-bytes num 2 7 t))) (nibblize t xtnd))) (defparameter +setup-special-time-code-offset-type+ (quote (0 0))) (defparameter +setup-special-enable-event-list-type+ (quote (1 0))) (defparameter +setup-special-disable-event-list-type+ (quote (2 0))) (defparameter +setup-special-clear-event-list-type+ (quote (3 0))) (defparameter +setup-special-system-stop-type+ (quote (4 0))) (defparameter +setup-special-event-list-request-type+ (quote (5 0))) (defun make-time-code-offset-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-time-code-offset-type+)) (defun make-enable-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-enable-event-list-type+)) (defun make-disable-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-disable-event-list-type+)) (defun make-clear-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-clear-event-list-type+)) (defun make-system-stop-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-system-stop-type+)) (defun make-event-list-request-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-event-list-request-type+)) (defun make-punch-in-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-punch-in-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-punch-out-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-punch-out-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-delete-punch-in-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-punch-in-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-delete-punch-out-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-punch-out-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-event-start-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-event-stop-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-xtnd-event-start-point-sysex-data (event-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr data)) (defun make-xtnd-event-stop-point-sysex-data (event-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr data)) (defun make-delete-event-start-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-delete-event-stop-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-cue-point-sysex-data (cue-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr)) (defun make-xtnd-cue-point-sysex-data (cue-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr data)) (defun make-delete-cue-point-sysex-data (cue-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr)) (defun make-event-name-sysex-data (event-nr hr mn sc fr ff name &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-name-sub-id-2+ format hr mn sc fr ff event-nr name)) (progn (defclass midi-event (event) ((opcode :accessor midi-event-opcode :allocation :class))) (defparameter <midi-event> (find-class 'midi-event)) (finalize-class <midi-event>) (values)) (defmethod midi-event-data1 ((obj midi-event)) obj nil) (defmethod midi-event-data2 ((obj midi-event)) obj nil) (progn (defclass midi-channel-event (midi-event) ((channel :initform 0 :initarg :channel :accessor midi-event-channel))) (defparameter <midi-channel-event> (find-class 'midi-channel-event)) (finalize-class <midi-channel-event>) (values)) (progn (defclass midi-system-event (midi-event) ((opcode :initform 240) (type :initform 0 :initarg :type :accessor midi-event-data1) (data :initform nil :initarg :data :accessor midi-event-data2))) (defparameter <midi-system-event> (find-class 'midi-system-event)) (finalize-class <midi-system-event>) (values)) (progn (defclass midi-meta-event (midi-event) ((opcode :initform 255))) (defparameter <midi-meta-event> (find-class 'midi-meta-event)) (finalize-class <midi-meta-event>) (values)) (defmethod midi-event->midi-message ((event midi-channel-event)) (values (make-channel-message (slot-value event 'opcode) (midi-event-channel event) (midi-event-data1 event) (or (midi-event-data2 event) 0)) nil)) (defmethod midi-event->midi-message ((event midi-system-event)) (let* ((type (midi-event-data1 event)) (code (logior 240 type)) (data (midi-event-data2 event))) (cond ((eq type 0) (make-sysex 0 data)) ((<= 1 type 3) (make-system-message 0 code (midi-event-data2 event))) (t (make-system-message 0 code))))) (defmethod midi-event->midi-message ((event midi-meta-event)) (let ((op (slot-value event 'opcode))) (cond ((eq op +ml-file-sequence-number-opcode+) (make-sequence-number (midi-event-data1 event))) ((eq op +ml-file-text-event-opcode+) (make-text-event (midi-event-data2 event) (midi-event-data1 event))) ((eq op +ml-file-eot-opcode+) (make-eot)) ((eq op +ml-file-tempo-change-opcode+) (make-tempo-change (midi-event-data1 event))) ((eq op +ml-file-smpte-offset-opcode+) (apply #'make-smpte-offset (midi-event-data1 event))) ((eq op +ml-file-time-signature-opcode+) (make-time-signature (midi-event-data1 event) (midi-event-data2 event) (midi-event-data3 event) (midi-event-data4 event))) ((eq op +ml-file-key-signature-opcode+) (make-key-signature (midi-event-data1 event) (midi-event-data2 event))) ((eq op +ml-file-sequencer-event-opcode+) (make-sequencer-event (midi-event-data1 event))) (t (error "Unimplemented meta-event opcode: ~s" op)))))
null
https://raw.githubusercontent.com/ormf/cm/26843eec009bd6c214992a8e67c49fffa16d9530/src/midi1.lisp
lisp
********************************************************************** This program is free software; you can redistribute it and/or **********************************************************************
Copyright ( C ) 2009 , < taube ( at ) uiuc ( dot ) edu > modify it under the terms of the Lisp Lesser Gnu Public License . See for the text of this agreement . generated by scheme->cltl from midi1.scm on 04 - Aug-2009 14:11:46 (in-package :cm) (defparameter +enc-route-byte+ (byte 10 22)) (defparameter +enc-lower-status-byte+ (byte 4 18)) (defparameter +enc-upper-status-byte+ (byte 4 14)) (defparameter +enc-swapped-status-byte+ (byte 8 14)) (defparameter +enc-logical-channel-byte+ (byte 14 18)) (defparameter +enc-opcode-byte+ +enc-upper-status-byte+) (defparameter +enc-data-1-byte+ (byte 7 7)) (defparameter +enc-data-2-byte+ (byte 7 0)) (defparameter +enc-route-offs+ -22) (defparameter +enc-lower-status-offs+ -18) (defparameter +enc-upper-status-offs+ -10) (defparameter +enc-swapped-status-offs+ -14) (defparameter +enc-logical-channel-offs+ +enc-lower-status-offs+) (defparameter +enc-opcode-offs+ +enc-upper-status-offs+) (defparameter +enc-data-1-offs+ -7) (defparameter +enc-data-2-offs+ 0) (defparameter +enc-note-off-mask+ 4294852480) (defparameter +ml-note-off-opcode+ 8) (defparameter +ml-note-on-opcode+ 9) (defparameter +ml-key-pressure-opcode+ 10) (defparameter +ml-control-change-opcode+ 11) (defparameter +ml-program-change-opcode+ 12) (defparameter +ml-channel-pressure-opcode+ 13) (defparameter +ml-pitch-bend-opcode+ 14) (defparameter +ml-default-note-on-velocity+ 64) (defparameter +ml-default-note-off-velocity+ 64) (defparameter +ml-msg-sysex-type+ 15) (defparameter +ml-msg-mtc-quarter-frame-type+ 31) (defparameter +ml-msg-song-position-type+ 47) (defparameter +ml-msg-song-select-type+ 63) (defparameter +ml-msg-cable-select-type+ 95) (defparameter +ml-msg-tune-request-type+ 111) (defparameter +ml-msg-eox-type+ 127) (defparameter +ml-msg-timing-clock-type+ 143) (defparameter +ml-msg-timing-tick-type+ 159) (defparameter +ml-msg-start-type+ 175) (defparameter +ml-msg-continue-type+ 191) (defparameter +ml-msg-stop-type+ 207) (defparameter +ml-msg-active-sensing-type+ 239) (defparameter +ml-msg-system-reset-type+ 255) (defparameter +ml-meta-type+ 0) (defparameter +ml-file-meta-marker+ 255) (defparameter +ml-file-sequence-number-opcode+ 0) (defparameter +ml-file-text-event-opcode+ 1) (defparameter +ml-file-copyright-note-opcode+ 2) (defparameter +ml-file-sequence/track-name-opcode+ 3) (defparameter +ml-file-instrument-name-opcode+ 4) (defparameter +ml-file-lyric-opcode+ 5) (defparameter +ml-file-marker-opcode+ 6) (defparameter +ml-file-cue-point-opcode+ 7) (defparameter +ml-file-midi-channel-opcode+ 32) (defparameter +ml-file-midi-port-opcode+ 33) (defparameter +ml-file-eot-opcode+ 47) (defparameter +ml-file-tempo-change-opcode+ 81) (defparameter +ml-file-smpte-offset-opcode+ 84) (defparameter +ml-file-time-signature-opcode+ 88) (defparameter +ml-file-key-signature-opcode+ 89) (defparameter +ml-file-sequencer-event-opcode+ 127) (defun midimsg-data1 (message) (ldb +enc-data-1-byte+ message)) (defun midimsg-data2 (message) (ldb +enc-data-2-byte+ message)) (defun midi-channel-message-p (message) (< 0 (ldb +enc-opcode-byte+ message) 15)) (defun midi-system-message-p (message) (= (ldb +enc-upper-status-byte+ message) 15)) (defun midi-meta-message-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-meta-type+)) (defparameter +channel-message-sizes+ #(3 3 3 3 2 2 3)) (defparameter +system-message-sizes+ #(0 2 3 2 -1 2 1 1 1 1 1 1 1 -1 1 1)) (defparameter +ml-channel-msg-type-strings+ #("Note-Off" "Note-On" "Key-Pressure" "Control-Change" "Program-Change" "Channel-Pressure" "Pitch-Bend")) (defparameter +ml-msg-type-strings+ #("Sysex" "MTC Quarter Frame" "Song-Position" "Song-Select" "Undefined" "Cable-Select" "Tune-Request" "Eox" "Timing-Clock" "Timing-Tick" "Start" "Continue" "Stop" "Undefined" "Active-Sensing" "System-Reset")) (defparameter +ml-meta-msg-type-strings+ #((0 . "Sequence Number") (1 . "Text Event") (2 . "Copyright Note") (3 . "Sequence/Track Name") (4 . "Instrument Name") (5 . "Lyric") (6 . "Marker") (7 . "Cue Point") (32 . "MIDI Channel") (33 . "MIDI Port") (47 . "End of Track") (81 . "Tempo Change") (84 . "SMPTE Offset") (88 . "Time Signature") (89 . "Key Signature") (127 . "Sequencer Event"))) (defun get-meta-msg-type-string (type) (let ((res (do ((i 0 (+ i 1)) (l (length +ml-meta-msg-type-strings+)) (x nil) (f nil)) ((or f (= i l)) f) (setf x (elt +ml-meta-msg-type-strings+ i)) (if (= (car x) type) (setf f x))))) (if res (cdr res) "Unknown Meta Event"))) (defun midimsg-logical-channel (m) (ldb +enc-logical-channel-byte+ m)) (defun midimsg-route (m) (ldb +enc-route-byte+ m)) (defun midimsg-opcode (m) (ldb +enc-opcode-byte+ m)) (defun midimsg-upper-status (m) (ldb +enc-upper-status-byte+ m)) (defun midimsg-lower-status (m) (ldb +enc-lower-status-byte+ m)) (defun midimsg-status (m) (ldb +enc-swapped-status-byte+ m)) (defun midimsg-size (m) (if (midi-channel-message-p m) (elt +channel-message-sizes+ (logand (ash m +enc-swapped-status-offs+) 7)) (elt +system-message-sizes+ (logand (ash m +enc-lower-status-offs+) 15)))) (defun channel-note-hash (m) (logior (ash (ldb +enc-logical-channel-byte+ m) 8) (midimsg-data1 m))) (defun %midi-encode-channel-message (bytes size) (if (= size 3) (make-channel-message (ash (logand bytes 15728640) -20) (ash (logand bytes 983040) -16) (ash (logand bytes 32512) -8) (logand bytes 127)) (if (= size 2) (make-channel-message (ash (logand bytes 61440) -12) (ash (logand bytes 3840) -8) (logand bytes 127) 0) (error "Size ~s cannot be a channel message." size)))) (defparameter *midi-open* ()) (defparameter *midi-time* -1) (defmacro define-message-set! (accessor bytespec) (make-midi-message-set! accessor bytespec)) (defun midi-copy-message (msg &key opcode channel data1 data2) (when opcode (setf msg (dpb opcode +enc-opcode-byte+ msg))) (when channel (setf msg (dpb channel +enc-logical-channel-byte+ msg))) (when data1 (setf msg (dpb data1 +enc-data-1-byte+ msg))) (when data2 (setf msg (dpb data2 +enc-data-2-byte+ msg))) msg) (defun make-channel-message (opcode channel data1 data2) (logior (ash (logand channel 16383) 18) (ash (logand opcode 15) 14) (ash (logand data1 127) 7) (logand data2 127))) (defun channel-message-p (message) (midi-channel-message-p message)) (defun channel-message-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun channel-message-opcode (message) (ldb +enc-opcode-byte+ message)) (defun channel-message-data1 (message) (ldb +enc-data-1-byte+ message)) (defun channel-message-data2 (message) (ldb +enc-data-2-byte+ message)) (define-message-set! channel-message-channel +enc-logical-channel-byte+) (define-message-set! channel-message-opcode +enc-opcode-byte+) (define-message-set! channel-message-data1 +enc-data-1-byte+) (define-message-set! channel-message-data2 +enc-data-2-byte+) (defun make-note-off (channel key velocity) (make-channel-message +ml-note-off-opcode+ channel key velocity)) (defun note-off-p (message) (= (ldb +enc-opcode-byte+ message) +ml-note-off-opcode+)) (defun note-off-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun note-off-key (message) (ldb +enc-data-1-byte+ message)) (defun note-off-velocity (message) (ldb +enc-data-2-byte+ message)) (define-message-set! note-off-channel +enc-logical-channel-byte+) (define-message-set! note-off-key +enc-data-1-byte+) (define-message-set! note-off-velocity +enc-data-2-byte+) (defun make-note-on (channel key velocity) (make-channel-message +ml-note-on-opcode+ channel key velocity)) (defun note-on-p (message) (= (ldb +enc-opcode-byte+ message) +ml-note-on-opcode+)) (defun note-on-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun note-on-key (message) (ldb +enc-data-1-byte+ message)) (defun note-on-velocity (message) (ldb +enc-data-2-byte+ message)) (define-message-set! note-on-channel +enc-logical-channel-byte+) (define-message-set! note-on-key +enc-data-1-byte+) (define-message-set! note-on-velocity +enc-data-2-byte+) (defun make-key-pressure (channel key pressure) (make-channel-message +ml-key-pressure-opcode+ channel key pressure)) (defun key-pressure-p (message) (= (ldb +enc-opcode-byte+ message) +ml-key-pressure-opcode+)) (defun key-pressure-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun key-pressure-key (message) (ldb +enc-data-1-byte+ message)) (defun key-pressure-pressure (message) (ldb +enc-data-2-byte+ message)) (define-message-set! key-pressure-channel +enc-logical-channel-byte+) (define-message-set! key-pressure-key +enc-data-1-byte+) (define-message-set! key-pressure-pressure +enc-data-2-byte+) (defun make-control-change (channel controller value) (make-channel-message +ml-control-change-opcode+ channel controller value)) (defun control-change-p (message) (= (ldb +enc-opcode-byte+ message) +ml-control-change-opcode+)) (defun control-change-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun control-change-controller (message) (ldb +enc-data-1-byte+ message)) (defun control-change-value (message) (ldb +enc-data-2-byte+ message)) (define-message-set! control-change-channel +enc-logical-channel-byte+) (define-message-set! control-change-controller +enc-data-1-byte+) (define-message-set! control-change-value +enc-data-2-byte+) (defun make-program-change (channel program) (make-channel-message +ml-program-change-opcode+ channel program 0)) (defun program-change-p (message) (= (ldb +enc-opcode-byte+ message) +ml-program-change-opcode+)) (defun program-change-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun program-change-program (message) (ldb +enc-data-1-byte+ message)) (define-message-set! program-change-channel +enc-logical-channel-byte+) (define-message-set! program-change-program +enc-data-1-byte+) (defun make-channel-pressure (channel pressure) (make-channel-message +ml-channel-pressure-opcode+ channel pressure 0)) (defun channel-pressure-p (message) (= (ldb +enc-opcode-byte+ message) +ml-channel-pressure-opcode+)) (defun channel-pressure-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun channel-pressure-pressure (message) (ldb +enc-data-1-byte+ message)) (define-message-set! channel-pressure-channel +enc-logical-channel-byte+) (define-message-set! channel-pressure-pressure +enc-data-1-byte+) (defun make-pitch-bend (channel value &rest args) (let ((width (if (null args) 2 (car args)))) (let ((bend (floor (rescale value (- width) width 0 16383)))) (make-channel-message +ml-pitch-bend-opcode+ channel (ldb (byte 7 0) bend) (ldb (byte 7 7) bend))))) (defun pitch-bend-p (message) (= (ldb +enc-opcode-byte+ message) +ml-pitch-bend-opcode+)) (defun pitch-bend-channel (message) (ldb +enc-logical-channel-byte+ message)) (defun pitch-bend-lsb (message) (ldb +enc-data-1-byte+ message)) (defun pitch-bend-msb (message) (ldb +enc-data-2-byte+ message)) (define-message-set! pitch-bend-channel +enc-logical-channel-byte+) (define-message-set! pitch-bend-lsb +enc-data-1-byte+) (define-message-set! pitch-bend-msb +enc-data-2-byte+) (defun make-system-message (type route &optional (data1 0) (data2 0)) (dpb route +enc-route-byte+ (dpb type +enc-swapped-status-byte+ (dpb data1 +enc-data-1-byte+ (dpb data2 +enc-data-2-byte+ 0))))) (defun system-message-p (message) (midi-system-message-p message)) (defun system-message-route (message) (ldb +enc-route-byte+ message)) (defun system-message-status (message) (ldb +enc-swapped-status-byte+ message)) (defun system-message-data1 (message) (ldb +enc-data-1-byte+ message)) (defun system-message-data2 (message) (ldb +enc-data-2-byte+ message)) (define-message-set! system-message-route +enc-route-byte+) (define-message-set! system-message-status +enc-swapped-status-byte+) (define-message-set! system-message-data1 +enc-data-1-byte+) (define-message-set! system-message-data2 +enc-data-2-byte+) (defun make-sysex-data (&rest args) (let ((len 2) (i 0) (msg #())) (labels ((incflen (args) (dolist (a args) (cond ((characterp a) (incf len)) ((and (integerp a) (<= 0 i 255)) (incf len)) ((stringp a) (incf len (+ (length a) 1))) ((consp a) (incflen a)) (t (error "~s not char, byte or string." a))))) (stuff (byte) (incf i) (setf (elt msg i) byte)) (stuffdata (args) (dolist (a args) (cond ((characterp a) (stuff (char-code a))) ((stringp a) (loop for i below (length a) for c = (elt a i) do (stuff (char-code c)) finally (stuff 0))) ((and (integerp a) (<= 0 i 255)) (stuff a)) ((consp a) (stuffdata a)) (t (error "~s not char, byte or string." a)))))) (incflen args) (setf msg (make-array len :initial-element 0)) (stuffdata args) (setf (elt msg 0) 240) (setf (elt msg (- len 1)) 247) msg))) (defun make-sysex (route data) (values (make-system-message +ml-msg-sysex-type+ route) (if (consp data) (apply #'make-sysex-data data) (if (vectorp data) data (error "~s is not a pair or a vector." data))))) (defun sysex-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-sysex-type+)) (defun sysex-route (message) (ldb +enc-route-byte+ message)) (define-message-set! sysex-route +enc-route-byte+) (defun make-mtc-quarter-frame (route tag nibble) (make-system-message +ml-msg-mtc-quarter-frame-type+ route (logior (ash tag 4) nibble))) (defun mtc-quarter-frame-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-mtc-quarter-frame-type+)) (defun mtc-quarter-frame-route (message) (ldb +enc-route-byte+ message)) (defun mtc-quarter-frame-tag (message) (logand (ldb +enc-data-1-byte+ message) 112)) (defun mtc-quarter-frame-nibble (message) (logand (ldb +enc-data-1-byte+ message) 15)) (define-message-set! mtc-quarter-frame-route +enc-route-byte+) (defun make-song-position (route lsb msb) (make-system-message +ml-msg-song-position-type+ route lsb msb)) (defun song-position-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-song-position-type+)) (defun song-position-route (message) (ldb +enc-route-byte+ message)) (defun song-position-lsb (message) (ldb +enc-data-1-byte+ message)) (defun song-position-msb (message) (ldb +enc-data-2-byte+ message)) (define-message-set! song-position-route +enc-route-byte+) (define-message-set! song-position-lsb +enc-data-1-byte+) (define-message-set! song-position-msb +enc-data-2-byte+) (defun make-song-select (route song) (make-system-message +ml-msg-song-select-type+ route song)) (defun song-select-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-song-select-type+)) (defun song-select-route (message) (ldb +enc-route-byte+ message)) (defun song-select-song (message) (ldb +enc-data-1-byte+ message)) (define-message-set! song-select-route +enc-route-byte+) (define-message-set! song-select-song +enc-data-1-byte+) (defun make-cable-select (route cable) (make-system-message +ml-msg-cable-select-type+ route cable)) (defun cable-select-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-cable-select-type+)) (defun cable-select-route (message) (ldb +enc-route-byte+ message)) (defun cable-select-cable (message) (ldb +enc-data-1-byte+ message)) (define-message-set! cable-select-route +enc-route-byte+) (define-message-set! cable-select-cable +enc-data-1-byte+) (defun make-tune-request (route) (make-system-message +ml-msg-tune-request-type+ route)) (defun tune-request-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-tune-request-type+)) (defun tune-request-route (message) (ldb +enc-route-byte+ message)) (define-message-set! tune-request-route +enc-route-byte+) (defun make-eox (route) (make-system-message +ml-msg-eox-type+ route)) (defun eox-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-eox-type+)) (defun eox-route (message) (ldb +enc-route-byte+ message)) (define-message-set! eox-route +enc-route-byte+) (defun make-timing-clock (route) (make-system-message +ml-msg-timing-clock-type+ route)) (defun timing-clock-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-timing-clock-type+)) (defun timing-clock-route (message) (ldb +enc-route-byte+ message)) (define-message-set! timing-clock-route +enc-route-byte+) (defun make-timing-tick (route) (make-system-message +ml-msg-timing-tick-type+ route)) (defun timing-tick-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-timing-tick-type+)) (defun timing-tick-route (message) (ldb +enc-route-byte+ message)) (define-message-set! timing-tick-route +enc-route-byte+) (defun make-start (route) (make-system-message +ml-msg-start-type+ route)) (defun start-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-start-type+)) (defun start-route (message) (ldb +enc-route-byte+ message)) (define-message-set! start-route +enc-route-byte+) (defun make-continue (route) (make-system-message +ml-msg-continue-type+ route)) (defun continue-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-continue-type+)) (defun continue-route (message) (ldb +enc-route-byte+ message)) (define-message-set! continue-route +enc-route-byte+) (defun make-stop (route) (make-system-message +ml-msg-stop-type+ route)) (defun stop-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-stop-type+)) (defun stop-route (message) (ldb +enc-route-byte+ message)) (define-message-set! stop-route +enc-route-byte+) (defun make-active-sensing (route) (make-system-message +ml-msg-active-sensing-type+ route)) (defun active-sensing-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-active-sensing-type+)) (defun active-sensing-route (message) (ldb +enc-route-byte+ message)) (define-message-set! active-sensing-route +enc-route-byte+) (defun make-system-reset (route) (make-system-message +ml-msg-system-reset-type+ route)) (defun system-reset-p (message) (= (ldb +enc-swapped-status-byte+ message) +ml-msg-system-reset-type+)) (defun system-reset-route (message) (ldb +enc-route-byte+ message)) (define-message-set! system-reset-route +enc-route-byte+) (defun make-meta-message (type &rest data-bytes) (values (dpb +ml-meta-type+ +enc-swapped-status-byte+ (dpb type +enc-data-1-byte+ 0)) (let ((l (length data-bytes)) (v nil) (d nil)) (setf v (if (< l 128) 1 (if (< l 16384) 2 (if (< l 2097152) 3 (if (< l 268435456) 4 (error "Illegal length: ~s" l)))))) (setf d (make-array (+ v l) :initial-element 0)) (do ((i 0 (+ 1 i)) (offs (* (- v 1) 7) (- offs 7))) ((not (< i v)) nil) (setf (elt d i) (if (= offs 0) (ldb (byte 7 offs) l) (logior (ldb (byte 7 offs) l) 128)))) (do ((i v (+ i 1)) (b data-bytes (cdr b))) ((null b) nil) (setf (elt d i) (car b))) d))) (defun meta-message-p (message) (midi-meta-message-p message)) (defun meta-message-type (message) (ldb +enc-data-1-byte+ message)) (define-message-set! meta-message-type +enc-data-1-byte+) (defun make-sequence-number (num) (when (>= num 65536) (error "~s too big for a sequence number." num)) (make-meta-message +ml-file-sequence-number-opcode+ (ldb (byte 8 8) num) (ldb (byte 8 0) num))) (defun sequence-number-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequence-number-opcode+))) (defun make-text-event (string &optional (type +ml-file-text-event-opcode+)) (apply #'make-meta-message type (loop for i below (length string) collect (char-code (elt string i))))) (defun text-event-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-text-event-opcode+))) (defparameter +text-meta-event-types+ (list +ml-file-text-event-opcode+ +ml-file-copyright-note-opcode+ +ml-file-sequence/track-name-opcode+ +ml-file-instrument-name-opcode+ +ml-file-lyric-opcode+ +ml-file-marker-opcode+ +ml-file-cue-point-opcode+)) (defun text-meta-event-p (message) (and (midi-meta-message-p message) (member (ldb +enc-data-1-byte+ message) +text-meta-event-types+) t)) (defun text-meta-event-data-to-string (data) (let ((len (elt data 0))) (when (= (elt data len) 0) (setf len (max (- len 1) 0))) (loop with str = (make-string len) for i below len do (setf (elt str i) (code-char (elt data (+ i 1)))) finally (return str)))) (defun make-copyright-note (string) (make-text-event string +ml-file-copyright-note-opcode+)) (defun copyright-note-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-copyright-note-opcode+))) (defun make-sequence/track-name (string) (make-text-event string +ml-file-sequence/track-name-opcode+)) (defun sequence/track-name-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequence/track-name-opcode+))) (defun make-instrument-name (string) (make-text-event string +ml-file-instrument-name-opcode+)) (defun instrument-name-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-instrument-name-opcode+))) (defun make-lyric (string) (make-text-event string +ml-file-lyric-opcode+)) (defun lyric-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-lyric-opcode+))) (defun make-marker (string) (make-text-event string +ml-file-marker-opcode+)) (defun marker-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-marker-opcode+))) (defun make-cue-point (string) (make-text-event string +ml-file-cue-point-opcode+)) (defun cue-point-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-cue-point-opcode+))) (defun make-midi-channel (channel) (make-meta-message +ml-file-midi-channel-opcode+ channel)) (defun midi-channel-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-midi-channel-opcode+))) (defun make-midi-port (port) (make-meta-message +ml-file-midi-port-opcode+ port)) (defun midi-port-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-midi-port-opcode+))) (defun make-eot () (make-meta-message +ml-file-eot-opcode+)) (defun eot-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-eot-opcode+))) (defun make-tempo-change (usecs-per-beat) (apply #'make-meta-message +ml-file-tempo-change-opcode+ (loop for pos from 16 by 8 downto 0 collect (ldb (byte 8 pos) usecs-per-beat)))) (defun tempo-change-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-tempo-change-opcode+))) (defun make-smpte-offset (hours mins secs frames fractional-frames) (make-meta-message +ml-file-smpte-offset-opcode+ hours mins secs frames fractional-frames)) (defun smpte-offset-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-smpte-offset-opcode+))) (defun make-time-signature (numerator denominator &optional (clocks 24) (32nds 8)) (multiple-value-bind (f r) (floor (log2 denominator)) (unless (zerop r) (error "Time signature denominator ~s is not a power of 2." denominator)) (make-meta-message +ml-file-time-signature-opcode+ numerator f clocks 32nds))) (defun time-signature-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-time-signature-opcode+))) (defun make-key-signature (key &optional (mode ':major)) (let ((sf nil)) (setf mode (case mode ((:major major 0) 0) ((:minor minor 1) 1) (t (error "key signature mode not :major or :minor")))) (cond ((numberp key) (unless (<= -7 key 7) (error "Key signature must be between -7 (b) and 7 (#).")) (setf sf key)) (t (error "~s is not a number or symbol." key))) (setf sf (if (< sf 0) (+ sf 256) sf)) (make-meta-message +ml-file-key-signature-opcode+ sf mode))) (defun key-signature-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-key-signature-opcode+))) (defun make-sequencer-event (&rest data) (apply #'make-meta-message +ml-file-sequencer-event-opcode+ data)) (defun sequencer-event-p (message) (and (midi-meta-message-p message) (= (ldb +enc-data-1-byte+ message) +ml-file-sequencer-event-opcode+))) (defun midi-print-channel-message (stream gm? size type channel data1 data2 time-string) (let ((name (elt +ml-channel-msg-type-strings+ (logand type 7)))) (format stream "~a~a" name time-string) (when gm? (let ((p (gm-percussion-channel-p channel))) (if p (setf channel "P")) (cond ((= type 12) (setf data1 (gm-patch-name data1))) ((= type 11) (setf data1 (midi-controller-name data1))) ((or (= type 10) (= type 8) (= type 9)) (if p (setf data1 (gm-drum-kit-name data1))))))) (format stream " ~a" channel) (if (= size 3) (format stream " ~s ~s" data1 data2) (format stream " ~s" data1)))) (defparameter *midi-gm-mode* t) (defun %print-sysex-aux (stream data bytes rest indent) (let ((offs 0) (toprint bytes) (n 0) (oldn nil) (blank nil)) (loop while (> toprint 0) do (when indent (format stream indent)) (format stream (format-integer offs 6 #\0)) (format stream ":") (setf oldn n) (do ((i 0 (+ i 1))) ((or (= i 16) (>= n bytes)) (setf blank (- 16 i))) (format stream (format-integer (elt data n) 2 #\0)) (if (oddp i) (format stream " ")) (incf n)) (dotimes (i (- (+ (* blank 3) 2) (floor (/ blank 2)))) (format stream " ")) (setf n oldn) (do ((i 0 (+ i 1)) (b nil)) ((or (not (< i 16)) (not (< n bytes))) (decf toprint i)) (setf b (elt data n)) (if (< 31 b 127) (format stream (make-string 1 :initial-element (code-char b))) (format stream ".")) (incf n)) (format stream "~%") (incf offs 16)) (when (> rest 0) (format stream " [... (~s Bytes remaining)]~%" rest)) (values))) (defun print-sysex-data (stream string lines data length) (let ((bytes 0) (rest 0)) (unless length (setf length (length data))) (setf lines (if (numberp lines) lines 0)) (setf bytes (if (and (> lines 0) (< (* lines 16) length)) (* (- lines 1) 16) length)) (setf rest (- length bytes)) (if string (error "string output not supported") (when stream (%print-sysex-aux stream data bytes rest nil))))) (defun midi-print-message (msg time &key data length (stream t) (time-format t) (time-string "") (gm *midi-gm-mode*) (eol t) (delimit t)) (when (and time time-format) (format stream "~a " (format-integer time 8 #\ ))) (when delimit (format stream "#<")) (cond ((midi-channel-message-p msg) (let* ((size (midimsg-size msg)) (op (channel-message-opcode msg)) (chan (channel-message-channel msg)) (data1 (channel-message-data1 msg)) (data2 (channel-message-data2 msg))) (midi-print-channel-message stream gm size op chan data1 data2 time-string))) ((midi-system-message-p msg) (let ((name (elt +ml-msg-type-strings+ (ldb +enc-lower-status-byte+ msg))) (route (ldb +enc-route-byte+ msg)) (size (midimsg-size msg))) (format stream "~a~a ~s" name time-string route) (cond ((= size 3) (format stream " ~s ~s" (midimsg-data1 msg) (midimsg-data2 msg))) ((= size 2) (format stream " ~s" (midimsg-data1 msg))) (t (when delimit (format stream ">") (setf delimit nil)) (when (sysex-p msg) (format stream "~%") (print-sysex-data t nil 0 data length)))))) ((midi-meta-message-p msg) (cond ((or (midi-channel-p msg) (midi-port-p msg)) (format stream "~a~a ~s" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (if data (elt data 1) "?"))) ((tempo-change-p msg) (format stream "~a~a ~s ms" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (/ (+ (ash (elt data 1) 16) (ash (elt data 2) 8) (elt data 3)) 1000))) ((time-signature-p msg) (format stream "~a~a ~s/~s (~s clocks, ~s 32nds)" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (elt data 1) (expt 2 (elt data 2)) (elt data 3) (elt data 4))) ((key-signature-p msg) (let ((a (elt data 1)) (s nil)) (setf a (or (and (logtest a 128) (- a 256)) a)) (setf s (if (> (abs a) 1) "s" "")) (format stream "~a~a ~a ~a~a, ~a" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string (if (zerop a) "no" (abs a)) (case (signum a) ((-1) "flat") ((0) "accidentals") ((1) "sharp")) s (if (zerop (elt data 2)) "major" "minor")))) (t (format stream "~a~a" (get-meta-msg-type-string (ldb +enc-data-1-byte+ msg)) time-string) (if data (format stream " ~s" (if (text-meta-event-p msg) (text-meta-event-data-to-string data) data)) (format stream ">"))))) (t (format stream "Bogus Midi Message~a]" time-string))) (when delimit (format stream ">")) (when eol (terpri stream)) msg) (defparameter %deflabelvar% (gensym)) (defmacro deflabel (sym val vector str pos) `(progn (defparameter ,sym ,val) ,(if str `(setf (elt ,vector ,pos) ,str) `(let ((*print-case* ':downcase)) (setf %deflabelvar% (format nil "~a" ',sym)) (do ((i 0 (+ i 1)) (e (length %deflabelvar%))) ((not (< i e)) nil) (if (char= (elt %deflabelvar% i) #\ ) (setf (elt %deflabelvar% i) #\-))) (setf (elt ,vector ,pos) (subseq %deflabelvar% 1 (- (length %deflabelvar%) 1))))))) (defparameter +midi-controller-strings+ (make-array 128 :initial-element "")) (defmacro defcontroller (sym val &body str) `(deflabel ,sym ,val +midi-controller-strings+ ,(if (null str) nil (car str)) ,val)) (defun midi-opcode-name (vec code lb ub delta) (cond ((and (integerp code) (<= lb code ub)) (elt vec (+ code delta))) ((stringp code) code) (t (error "MIDI opcode ~s not string or int ~s-~s." code lb ub)))) (defun midi-controller-name (c) (midi-opcode-name +midi-controller-strings+ c 0 127 0)) (defcontroller +bank-select+ 0) (defcontroller +modulation-wheel+ 1) (defcontroller +breath-control+ 2) (defcontroller +foot-controller+ 4) (defcontroller +portamento-time+ 5) (defcontroller +data-entry+ 6) (defcontroller +channel-volume+ 7) (defparameter +volume+ 7) (defcontroller +balance+ 8) (defcontroller +pan+ 10) (defcontroller +expression-controller+ 11) (defcontroller +effect-control-1+ 12) (defcontroller +effect-control-2+ 13) (defcontroller +general-purpose-controller-1+ 16 "General-Purpose Controller 1") (defcontroller +general-purpose-controller-2+ 17 "General-Purpose Controller 2") (defcontroller +general-purpose-controller-3+ 18 "General-Purpose Controller 3") (defcontroller +general-purpose-controller-4+ 19 "General-Purpose Controller 4") (defcontroller +bank-select-fine+ 32 "Bank Select (Fine)") (defcontroller +modulation-wheel-fine+ 33 "Modulation Wheel (Fine)") (defcontroller +breath-control-fine+ 34 "Breath Control (Fine)") (defcontroller +foot-controller-fine+ 36 "Foot Controller (Fine)") (defcontroller +portamento-time-fine+ 37 "Portamento Time (Fine)") (defcontroller +data-entry-fine+ 38 "Data Entry (Fine)") (defcontroller +channel-volume-fine+ 39 "Channel Volume (Fine)") (defparameter +volume-fine+ 39) (defcontroller +balance-fine+ 40 "Balance (Fine)") (defcontroller +pan-fine+ 42 "Pan (Fine)") (defcontroller +expression-controller-fine+ 43 "Expression Controller (Fine)") (defcontroller +effect-control-1-fine+ 44 "Effect Control 1 (Fine)") (defcontroller +effect-control-2-fine+ 45 "Effect Control 2 (Fine)") (defcontroller +general-purpose-controller-1-fine+ 48 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-2-fine+ 49 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-3-fine+ 50 "General-Purpose Controller 1 (Fine)") (defcontroller +general-purpose-controller-4-fine+ 51 "General-Purpose Controller 1 (Fine)") (defcontroller +hold-1+ 64) (defparameter +sustain+ 64) (defparameter +damper-pedal+ 64) (defcontroller +portamento+ 65) (defcontroller +sostenuto+ 66) (defcontroller +soft-pedal+ 67) (defcontroller +legato-footswitch+ 68) (defcontroller +hold-2+ 69) (defcontroller +sound-control-1+ 70) (defparameter +sound-variation+ 70) (defcontroller +sound-control-2+ 71) (defparameter +sound-timbre+ 71) (defcontroller +sound-control-3+ 72) (defparameter +sound-release-time+ 72) (defcontroller +sound-control-4+ 73) (defparameter +sound-attack-time+ 73) (defcontroller +sound-control-5+ 74) (defparameter +sound-brightness+ 74) (defcontroller +sound-control-6+ 75) (defcontroller +sound-control-7+ 76) (defcontroller +sound-control-8+ 77) (defcontroller +sound-control-9+ 78) (defcontroller +sound-control-10+ 79) (defcontroller +general-purpose-controller-5+ 80 "General-Purpose Controller 5") (defcontroller +general-purpose-controller-6+ 81 "General-Purpose Controller 6") (defcontroller +general-purpose-controller-7+ 82 "General-Purpose Controller 7") (defcontroller +general-purpose-controller-8+ 83 "General-Purpose Controller 8") (defcontroller +portamento-control+ 84) (defcontroller +effects-1-depth+ 91) (defparameter +effects-level+ 91) (defcontroller +effects-2-depth+ 92) (defparameter +tremolo-level+ 92) (defcontroller +effects-3-depth+ 93) (defparameter +chorus-level+ 93) (defcontroller +effects-4-depth+ 94) (defparameter +detune-level+ 94) (defcontroller +effects-5-depth+ 95) (defparameter +phasor-level+ 95) (defcontroller +data-entry-+1+ 96) (defparameter +data-entry-increment+ 96) (defcontroller +data-entry--1+ 97 "Data Entry -1") (defparameter +data-entry-decrement+ 97) (defcontroller +non-registered-parameter-number-fine+ 98 "Non-Registered Parameter Number (Fine)") (defcontroller +non-registered-parameter-number+ 99 "Non-Registered Parameter Number") (defcontroller +registered-parameter-number-fine+ 100 "Registered Parameter Number (Fine)") (defcontroller +registered-parameter-number+ 101) (defcontroller +all-sound-off+ 120) (defcontroller +reset-all-controllers+ 121) (defcontroller +local-control+ 122) (defcontroller +all-notes-off+ 123) (defcontroller +omni-mode-off+ 124) (defcontroller +omni-mode-on+ 125) (defcontroller +poly-mode-on/off+ 126) (defcontroller +poly-mode-on+ 127) (defparameter +rpn-pitch-bend-sensitivity+ (quote (0 0))) (defparameter +rpn-fine-tuning+ (quote (0 1))) (defparameter +rpn-coarse-tuning+ (quote (0 2))) (defparameter +rpn-reset+ (quote (63 255))) (defparameter +gm-patch-strings+ (make-array 128 :initial-element '"")) (defparameter +gm-drum-kit-strings+ (make-array 50 :initial-element '"")) (defmacro defgmpatch (sym val &body str) `(deflabel ,sym ,val +gm-patch-strings+ ,(if (null str) nil (car str)) ,val)) (defmacro defgmdrum (sym val &body str) `(deflabel ,sym ,val +gm-drum-kit-strings+ ,(if (null str) nil (car str)) ,(- val 32))) (defun gm-patch-name (patch) (midi-opcode-name +gm-patch-strings+ patch 0 127 0)) (defun gm-drum-kit-name (key) (midi-opcode-name +gm-drum-kit-strings+ key 35 81 -32)) (defgmpatch +acoustic-grand-piano+ 0) (defgmpatch +bright-acoustic-piano+ 1) (defgmpatch +electric-grand-piano+ 2) (defgmpatch +honky-tonk-piano+ 3) (defgmpatch +electric-piano-1+ 4) (defgmpatch +electric-piano-2+ 5) (defgmpatch +harpsichord+ 6) (defgmpatch +clavi+ 7) (defgmpatch +celesta+ 8) (defgmpatch +glockenspiel+ 9) (defgmpatch +music-box+ 10) (defgmpatch +vibraphone+ 11) (defgmpatch +marimba+ 12) (defgmpatch +xylophone+ 13) (defgmpatch +tubular-bells+ 14) (defgmpatch +dulcimer+ 15) (defgmpatch +drawbar-organ+ 16) (defgmpatch +percussive-organ+ 17) (defgmpatch +rock-organ+ 18) (defgmpatch +church-organ+ 19) (defgmpatch +reed-organ+ 20) (defgmpatch +accordion+ 21) (defgmpatch +harmonica+ 22) (defgmpatch +tango-accordion+ 23) (defgmpatch +acoustic-guitar-nylon+ 24) (defgmpatch +acoustic-guitar-steel+ 25) (defgmpatch +electric-guitar-jazz+ 26) (defgmpatch +electric-guitar-clean+ 27) (defgmpatch +electric-guitar-muted+ 28) (defgmpatch +overdriven-guitar+ 29) (defgmpatch +distortion-guitar+ 30) (defgmpatch +guitar-harmonics+ 31) (defgmpatch +acoustic-bass+ 32) (defgmpatch +electric-bass-finger+ 33) (defgmpatch +electric-bass-pick+ 34) (defgmpatch +fretless-bass+ 35) (defgmpatch +slap-bass-1+ 36) (defgmpatch +slap-bass-2+ 37) (defgmpatch +synth-bass-1+ 38) (defgmpatch +synth-bass-2+ 39) (defgmpatch +violin+ 40) (defgmpatch +viola+ 41) (defgmpatch +cello+ 42) (defgmpatch +contrabass+ 43) (defgmpatch +tremolo-strings+ 44) (defgmpatch +pizzicato-strings+ 45) (defgmpatch +orchestral-strings+ 46) (defgmpatch +timpani+ 47) (defgmpatch +string-ensemble-1+ 48) (defgmpatch +string-ensemble-2+ 49) (defgmpatch +synthstrings-1+ 50) (defgmpatch +synthstrings-2+ 51) (defgmpatch +choir-aahs+ 52) (defgmpatch +voice-oohs+ 53) (defgmpatch +synth-voice+ 54) (defgmpatch +orchestra-hit+ 55) (defgmpatch +trumpet+ 56) (defgmpatch +trombone+ 57) (defgmpatch +tuba+ 58) (defgmpatch +muted-trumpet+ 59) (defgmpatch +french-horn+ 60) (defgmpatch +brass-section+ 61) (defgmpatch +synthbrass-1+ 62) (defgmpatch +synthbrass-2+ 63) (defgmpatch +soprano-sax+ 64) (defgmpatch +alto-sax+ 65) (defgmpatch +tenor-sax+ 66) (defgmpatch +baritone-sax+ 67) (defgmpatch +oboe+ 68) (defgmpatch +english-horn+ 69) (defgmpatch +bassoon+ 70) (defgmpatch +clarinet+ 71) (defgmpatch +piccolo+ 72) (defgmpatch +flute+ 73) (defgmpatch +recorder+ 74) (defgmpatch +pan-flute+ 75) (defgmpatch +blown-bottle+ 76) (defgmpatch +skakuhachi+ 77) (defgmpatch +whistle+ 78) (defgmpatch +ocarina+ 79) (defgmpatch +lead-1-square+ 80 "Lead 1 (Square)") (defparameter +lead-1+ 80) (defparameter +square-lead+ 80) (defparameter +square+ 80) (defgmpatch +lead-2-sawtooth+ 81 "Lead 2 (Sawtooth)") (defparameter +lead-2+ 81) (defparameter +sawtooth-lead+ 81) (defparameter +sawtooth+ 81) (defgmpatch +lead-3-calliope+ 82 "Lead 3 (Calliope)") (defparameter +lead-3+ 82) (defparameter +calliope-lead+ 82) (defparameter +calliope+ 82) (defgmpatch +lead-4-chiff+ 83 "Lead 4 (Chiff)") (defparameter +lead-4+ 83) (defparameter +chiff-lead+ 83) (defparameter +chiff+ 83) (defgmpatch +lead-5-charang+ 84 "Lead 5 (Charang)") (defparameter +lead-5+ 84) (defparameter +charang-lead+ 84) (defparameter +charang+ 84) (defgmpatch +lead-6-voice+ 85 "Lead 6 (Voice)") (defparameter +lead-6+ 85) (defparameter +voice-lead+ 85) (defparameter +voice+ 85) (defgmpatch +lead-7-fifths+ 86 "Lead 7 (Fifths)") (defparameter +lead-7+ 86) (defparameter +fifths-lead+ 86) (defparameter +fifths+ 86) (defgmpatch +lead-8-bass+lead+ 87 "Lead 8 (Bass+Lead)") (defparameter +lead-8+ 87) (defparameter +bass+lead-lead+ 87) (defparameter +bass+lead+ 87) (defgmpatch +pad-1-new-age+ 88 "Pad 1 (New Age)") (defparameter +pad-1+ 88) (defparameter +new-age-pad+ 88) (defparameter +new-age+ 88) (defgmpatch +pad-2-warm+ 89 "Pad 2 (Warm)") (defparameter +pad-2+ 89) (defparameter +warm-pad+ 89) (defparameter +warm+ 89) (defgmpatch +pad-3-polysynth+ 90 "Pad 3 (Polysynth)") (defparameter +pad-3+ 90) (defparameter +polysynth-pad+ 90) (defparameter +polysynth+ 90) (defgmpatch +pad-4-choir+ 91 "Pad 4 (Choir)") (defparameter +pad-4+ 91) (defparameter +choir-pad+ 91) (defparameter +choir+ 91) (defgmpatch +pad-5-bowed+ 92 "Pad 5 (Bowed)") (defparameter +pad-5+ 92) (defparameter +bowed-pad+ 92) (defparameter +bowed+ 92) (defgmpatch +pad-6-metallic+ 93 "Pad 6 (Metallic)") (defparameter +pad-6+ 93) (defparameter +metallic-pad+ 93) (defparameter +metallic+ 93) (defgmpatch +pad-7-halo+ 94 "Pad 7 (Halo)") (defparameter +pad-7+ 94) (defparameter +halo-pad+ 94) (defparameter +halo+ 94) (defgmpatch +pad-8-sweep+ 95 "Pad 8 (Sweep)") (defparameter +pad-8+ 95) (defparameter +sweep-pad+ 95) (defparameter +sweep+ 95) (defgmpatch +fx-1-rain+ 96 "FX 1 (Rain)") (defparameter +fx-1+ 96) (defparameter +rain-fx+ 96) (defparameter +rain+ 96) (defgmpatch +fx-2-soundtrack+ 97 "FX 2 (Soundtrack)") (defparameter +fx-2+ 97) (defparameter +soundtrack-fx+ 97) (defparameter +soundtrack+ 97) (defgmpatch +fx-3-crystal+ 98 "FX 3 (Crystal)") (defparameter +fx-3+ 98) (defparameter +crystal-fx+ 98) (defparameter +crystal+ 98) (defgmpatch +fx-4-atmosphere+ 99 "FX 4 (Atmosphere)") (defparameter +fx-4+ 99) (defparameter +atmosphere-fx+ 99) (defparameter +atmosphere+ 99) (defgmpatch +fx-5-brightness+ 100 "FX 5 (Brightness)") (defparameter +fx-5+ 100) (defparameter +brightness-fx+ 100) (defparameter +brightness+ 100) (defgmpatch +fx-6-goblins+ 101 "FX 6 (Goblins)") (defparameter +fx-6+ 101) (defparameter +goblins-fx+ 101) (defparameter +goblins+ 101) (defgmpatch +fx-7-echoes+ 102 "FX 7 (Echoes)") (defparameter +fx-7+ 102) (defparameter +echoes-fx+ 102) (defparameter +echoes+ 102) (defgmpatch +fx-8-sci-fi+ 103 "FX 8 (Sci-Fi)") (defparameter +fx-8+ 103) (defparameter +sci-fi-fx+ 103) (defparameter +sci-fi+ 103) (defgmpatch +sitar+ 104) (defgmpatch +banjo+ 105) (defgmpatch +shamisen+ 106) (defgmpatch +koto+ 107) (defgmpatch +kalimba+ 108) (defgmpatch +bagpipe+ 109) (defgmpatch +fiddle+ 110) (defgmpatch +shanai+ 111) (defgmpatch +tinkle-bell+ 112) (defgmpatch +agogo+ 113) (defgmpatch +steel-drums+ 114) (defgmpatch +woodblock+ 115) (defgmpatch +taiko-drum+ 116) (defgmpatch +melodic-tom+ 117) (defgmpatch +synth-drum+ 118) (defgmpatch +reverse-cymbal+ 119) (defgmpatch +guitar-fret-noise+ 120) (defgmpatch +breath-noise+ 121) (defgmpatch +seashore+ 122) (defgmpatch +bird-tweet+ 123) (defgmpatch +telephone-ring+ 124) (defgmpatch +helicopter+ 125) (defgmpatch +applause+ 126) (defgmpatch +gunshot+ 127) (defparameter *gm-percussion-channels* #(9)) (defun gm-percussion-channel-p (chan) (do ((i 0 (+ i 1)) (f nil) (e (length *gm-percussion-channels*))) ((or f (not (< i e))) f) (setf f (= (elt *gm-percussion-channels* i) chan)))) (defgmdrum +acoustic-bass-drum+ 35) (defgmdrum +bass-drum-1+ 36) (defgmdrum +side-stick+ 37) (defgmdrum +acoustic-snare+ 38) (defgmdrum +hand-clap+ 39) (defgmdrum +electric-snare+ 40) (defgmdrum +low-floor-tom+ 41) (defgmdrum +closed-hi-hat+ 42) (defgmdrum +high-floor-tom+ 43) (defgmdrum +pedal-hi-hat+ 44) (defgmdrum +low-tom+ 45) (defgmdrum +open-hi-hat+ 46) (defgmdrum +low-mid-tom+ 47) (defgmdrum +hi-mid-tom+ 48) (defgmdrum +crash-cymbal-1+ 49) (defgmdrum +high-tom+ 50) (defgmdrum +ride-cymbal-1+ 51) (defgmdrum +chinese-cymbal+ 52) (defgmdrum +ride-bell+ 53) (defgmdrum +tambourine+ 54) (defgmdrum +splash-cymbal+ 55) (defgmdrum +cowbell+ 56) (defgmdrum +crash-cymbal-2+ 57) (defgmdrum +vibraslap+ 58) (defgmdrum +ride-cymbal-2+ 59) (defgmdrum +hi-bongo+ 60) (defgmdrum +low-bongo+ 61) (defgmdrum +mute-hi-conga+ 62) (defgmdrum +open-hi-conga+ 63) (defgmdrum +low-conga+ 64) (defgmdrum +high-timbale+ 65) (defgmdrum +low-timbale+ 66) (defgmdrum +high-agogo+ 67) (defgmdrum +low-agogo+ 68) (defgmdrum +cabasa+ 69) (defgmdrum +maracas+ 70) (defgmdrum +short-whistle+ 71) (defgmdrum +long-whistle+ 72) (defgmdrum +short-guiro+ 73) (defgmdrum +long-guiro+ 74) (defgmdrum +claves+ 75) (defgmdrum +hi-wood-block+ 76) (defgmdrum +low-wood-block+ 77) (defgmdrum +mute-cuica+ 78) (defgmdrum +open-cuica+ 79) (defgmdrum +mute-triangle+ 80) (defgmdrum +open-triangle+ 81) (defparameter +sequential-circuits-id+ 1) (defparameter +idp-id+ 2) (defparameter +voyetra-id+ 3) (defparameter +moog-id+ 4) (defparameter +passport-id+ 5) (defparameter +lexicon-id+ 6) (defparameter +kurzweil-id+ 7) (defparameter +fender-id+ 8) (defparameter +gulbransen-id+ 9) (defparameter +akg-id+ 10) (defparameter +voyce-id+ 11) (defparameter +waveframe-id+ 12) (defparameter +ada-id+ 13) (defparameter +garfield-id+ 14) (defparameter +ensoniq-id+ 15) (defparameter +oberheim-id+ 16) (defparameter +apple-id+ 17) (defparameter +grey-matter-id+ 18) (defparameter +digidesign-id+ 19) (defparameter +palm-tree-id+ 20) (defparameter +jl-cooper-id+ 21) (defparameter +lowrey-id+ 22) (defparameter +adams-smith-id+ 23) (defparameter +e-mu-id+ 24) (defparameter +harmony-id+ 25) (defparameter +art-id+ 26) (defparameter +baldwin-id+ 27) (defparameter +eventide-id+ 28) (defparameter +inventronics-id+ 29) (defparameter +key-concepts-id+ 30) (defparameter +clarity-id+ 31) (defparameter +passac-id+ 32) (defparameter +siel-id+ 33) (defparameter +synthaxe-id+ 34) (defparameter +stepp-id+ 35) (defparameter +hohner-id+ 36) (defparameter +twister-id+ 37) (defparameter +solton-id+ 38) (defparameter +jellinghaus-id+ 39) (defparameter +southworth-id+ 40) (defparameter +ppg-id+ 41) (defparameter +jen-id+ 42) (defparameter +solid-state-id+ 43) (defparameter +audio-vertrieb-id+ 44) (defparameter +hinton-id+ 45) (defparameter +soundtracs-id+ 46) (defparameter +elka-id+ 47) (defparameter +dynachord-id+ 48) (defparameter +clavia-id+ 51) (defparameter +audio-architecture-id+ 52) (defparameter +soundcraft-id+ 57) (defparameter +wersi-id+ 59) (defparameter +avab-id+ 60) (defparameter +digigram-id+ 61) (defparameter +waldorf-id+ 62) (defparameter +quasimidi-id+ 63) (defparameter +kawai-id+ 64) (defparameter +roland-id+ 65) (defparameter +korg-id+ 66) (defparameter +yamaha-id+ 67) (defparameter +casio-id+ 68) (defparameter +moridaira-id+ 69) (defparameter +kamiya-id+ 70) (defparameter +akai-id+ 71) (defparameter +japan-victor-id+ 72) (defparameter +meisosha-id+ 73) (defparameter +hoshino-gakki-id+ 74) (defparameter +fujitsu-id+ 75) (defparameter +sony-id+ 76) (defparameter +nishin-onpa-id+ 77) (defparameter +teac-id+ 78) (defparameter +matsushita-electric-id+ 80) (defparameter +fostex-id+ 81) (defparameter +zoom-id+ 82) (defparameter +midori-id+ 83) (defparameter +matsushita-communication-id+ 84) (defparameter +suzuki-id+ 85) (defparameter +warner-id+ (quote (0 0 1))) (defparameter +digital-music-id+ (quote (0 0 7))) (defparameter +iota-id+ (quote (0 0 8))) (defparameter +new-england-id+ (quote (0 0 9))) (defparameter +artisyn-id+ (quote (0 0 10))) (defparameter +ivl-id+ (quote (0 0 11))) (defparameter +southern-music-id+ (quote (0 0 12))) (defparameter +lake-butler-id+ (quote (0 0 13))) (defparameter +alesis-id+ (quote (0 0 14))) (defparameter +dod-id+ (quote (0 0 16))) (defparameter +studer-id+ (quote (0 0 17))) (defparameter +perfect-fretworks-id+ (quote (0 0 20))) (defparameter +kat-id+ (quote (0 0 21))) (defparameter +opcode-id+ (quote (0 0 22))) (defparameter +rane-id+ (quote (0 0 23))) (defparameter +spatial-sound-id+ (quote (0 0 24))) (defparameter +kmx-id+ (quote (0 0 25))) (defparameter +allen-&-heath-id+ (quote (0 0 26))) (defparameter +peavey-id+ (quote (0 0 27))) (defparameter +360-id+ (quote (0 0 28))) (defparameter +spectrum-id+ (quote (0 0 29))) (defparameter +marquis-musi-id+ (quote (0 0 30))) (defparameter +zeta-id+ (quote (0 0 31))) (defparameter +axxes-id+ (quote (0 0 32))) (defparameter +orban-id+ (quote (0 0 33))) (defparameter +kti-id+ (quote (0 0 36))) (defparameter +breakaway-id+ (quote (0 0 37))) (defparameter +cae-id+ (quote (0 0 38))) (defparameter +rocktron-id+ (quote (0 0 41))) (defparameter +pianodisc-id+ (quote (0 0 42))) (defparameter +cannon-id+ (quote (0 0 43))) (defparameter +rogers-id+ (quote (0 0 45))) (defparameter +blue-sky-id+ (quote (0 0 46))) (defparameter +encore-id+ (quote (0 0 47))) (defparameter +uptown-id+ (quote (0 0 48))) (defparameter +voce-id+ (quote (0 0 49))) (defparameter +cti-id+ (quote (0 0 50))) (defparameter +s&s-id+ (quote (0 0 51))) (defparameter +broderbund-id+ (quote (0 0 52))) (defparameter +allen-organ-id+ (quote (0 0 53))) (defparameter +music-quest-id+ (quote (0 0 55))) (defparameter +aphex-id+ (quote (0 0 56))) (defparameter +gallien-krueger-id+ (quote (0 0 57))) (defparameter +ibm-id+ (quote (0 0 58))) (defparameter +hotz-id+ (quote (0 0 60))) (defparameter +eta-id+ (quote (0 0 61))) (defparameter +nsi-id+ (quote (0 0 62))) (defparameter +ad-lib-id+ (quote (0 0 63))) (defparameter +richmond-id+ (quote (0 0 64))) (defparameter +microsoft-id+ (quote (0 0 65))) (defparameter +software-toolworks-id+ (quote (0 0 66))) (defparameter +rjmg/niche-id+ (quote (0 0 67))) (defparameter +intone-id+ (quote (0 0 68))) (defparameter +gt-electronics-id+ (quote (0 0 71))) (defparameter +intermidi-id+ (quote (0 0 72))) (defparameter +lone-wolf-id+ (quote (0 0 85))) (defparameter +musonix-id+ (quote (0 0 100))) (defparameter +sgi-id+ (quote (0 1 4))) (defparameter +dream-id+ (quote (0 32 0))) (defparameter +strand-id+ (quote (0 32 0))) (defparameter +amek-id+ (quote (0 32 0))) (defparameter +dr.boehm-id+ (quote (0 32 0))) (defparameter +trident-id+ (quote (0 32 0))) (defparameter +real-world-id+ (quote (0 32 0))) (defparameter +yes-id+ (quote (0 32 0))) (defparameter +audiomatica-id+ (quote (0 32 0))) (defparameter +bontempi-id+ (quote (0 32 0))) (defparameter +fbt-id+ (quote (0 32 0))) (defparameter +larking-id+ (quote (0 32 0))) (defparameter +zero-88-id+ (quote (0 32 0))) (defparameter +micon-id+ (quote (0 32 16))) (defparameter +forefront-id+ (quote (0 32 16))) (defparameter +kenton-id+ (quote (0 32 16))) (defparameter +adb-id+ (quote (0 32 16))) (defparameter +marshall-id+ (quote (0 32 16))) (defparameter +dda-id+ (quote (0 32 16))) (defparameter +tc-id+ (quote (0 32 16))) (defparameter +non-commercial-id+ 125) (defparameter +non-real-time-id+ 126) (defparameter +sample-dump-header-sub-id+ 1) (defparameter +sample-dump-packet-sub-id+ 2) (defparameter +dump-request-sub-id+ 3) (defparameter +midi-time-code-setup-sub-id+ 4) (defparameter +sample-dump-extensions-sub-id+ 5) (defparameter +inquiry-message-sub-id+ 6) (defparameter +file-dump-sub-id+ 7) (defparameter +midi-tuning-standard-sub-id+ 8) (defparameter +general-midi-message-sub-id+ 9) (defparameter +end-of-file-sub-id+ 123) (defparameter +wait-sub-id+ 124) (defparameter +cancel-sub-id+ 125) (defparameter +nak-sub-id+ 126) (defparameter +ack-sub-id+ 127) (defparameter +real-time-id+ 127) (defparameter +long-form-mtc-sub-id+ 1) (defparameter +midi-show-control-sub-id+ 2) (defparameter +notation-information-sub-id+ 3) (defparameter +device-control-sub-id+ 4) (defparameter +real-time-mtc-cueing-sub-id+ 5) (defparameter +midi-machine-control-command-sub-id+ 6) (defparameter +midi-machine-control-response-sub-id+ 7) (defparameter +single-note-retune-sub-id+ 8) (defun n-bit-twoscomp-p (num bits signed? &rest args) (let ((error? (if (null args) nil (car args)))) (if signed? (if (and (< num 0) (<= (integer-length num) bits)) t (if error? (error "Not a signed ~s-bit byte: ~s." bits num) nil)) (if (and (not (< num 0)) (<= (integer-length num) bits)) t (if error? (error "Not an unsigned ~s-bit byte: ~s." bits num) nil))))) (defun n-bit-twoscomp (num bits signed?) (n-bit-twoscomp-p num bits signed? t) (if (< num 0) (+ num (expt 2 bits)) num)) (defun n-bit-bytes (num bytes bits lsb-first?) (n-bit-twoscomp-p num (* bytes bits) (< num 0) t) (let ((l '())) (do ((i 0 (+ i 1))) ((not (< i bytes)) nil) (setf l (cons (ldb (byte bits (* i bits)) num) l))) (if lsb-first? (reverse l) l))) (defun nibblize (lsb-first? &rest data) (let ((res '()) (o1 (if lsb-first? 0 4)) (o2 (if lsb-first? 4 0))) (labels ((nblize (x) (cond ((stringp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i))) (nblize 0)) ((vectorp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i)))) ((consp x) (do ((i 0 (+ i 1)) (e (length x))) ((not (< i e)) nil) (nblize (elt x i)))) ((characterp x) (setf x (char-code x)) (push (ldb (byte 4 o1) x) res) (push (ldb (byte 4 o2) x) res)) ((integerp x) (push (ldb (byte 4 o1) x) res) (push (ldb (byte 4 o2) x) res)) (t nil)))) (loop for d in data do (nblize d)) (nreverse res)))) (defparameter +all-device-ids+ 127) (defun make-gm-mode-sysex-data (gm-on? &key (device-id +all-device-ids+)) (make-sysex-data +non-real-time-id+ device-id +general-midi-message-sub-id+ (if gm-on? 1 0))) (defparameter +master-volume-sub-id-2+ 1) (defun make-master-volume-sysex-data (&key coarse fine (device-id +all-device-ids+)) (unless (or coarse fine) (error "No volume specified.")) (unless (or (and coarse (n-bit-twoscomp-p coarse 7 nil)) (and fine (n-bit-twoscomp-p fine 14 nil))) (error "~a volume ~a is not a ~a-bit value." (if fine "Fine" "Course") (or coarse fine) (if fine "14" "7"))) (make-sysex-data +real-time-id+ device-id +device-control-sub-id+ +master-volume-sub-id-2+ (if fine (logand fine 127) coarse) (if fine (ash (logand fine 16256) -7) coarse))) (defparameter +smpte-full-frame-sub-id-2+ 1) (defparameter +smpte-user-bits-sub-id-2+ 2) (defparameter +smpte-format-24fps+ 0) (defparameter +smpte-format-25fps+ 1) (defparameter +smpte-format-30fps-drop+ 2) (defparameter +smpte-format-30fps+ 3) (defun encode-smpte-data (hr mn sc fr &key subframes format) (unless (and (<= 0 hr 23) (<= 0 mn 59) (<= 0 sc 59) (<= 0 fr (cond ((= format +smpte-format-24fps+) 23) ((= format +smpte-format-25fps+) 24) ((or (= format +smpte-format-30fps-drop+) (= format +smpte-format-30fps+)) 29) (t (error "Not a valid SMPTE format ID: ~a." format)))) (or (not subframes) (<= 0 subframes 99))) (error "SMPTE values out of range: ~a ~a ~a ~a ~s." hr mn sc fr subframes)) (setf hr (dpb format (byte 3 5) hr)) (if subframes (list hr mn sc fr subframes) (list hr mn sc fr))) (defun make-smpte-full-frame-sysex-data (hr mn sc fr &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (make-sysex-data +real-time-id+ device-id +long-form-mtc-sub-id+ +smpte-full-frame-sub-id-2+ (encode-smpte-data hr mn sc fr :format format))) (defparameter +smpte-user-bits-raw+ 0) (defparameter +smpte-user-bits-chars+ 2) (defun make-smpte-user-bits-sysex-data (format data &key (device-id +all-device-ids+)) (let* ((fmt (case format ((:raw) 0) ((:bytes) 1) ((:chars) 2) ((:string) 3) (t (error ":format not one of :raw :bytes :chars :string")))) (size (if (= fmt 0) 4 8)) (len nil) (ref nil)) (cond ((stringp data) (setf len (length data)) (setf ref #'elt)) ((vectorp data) (setf len (length data)) (setf ref #'elt)) ((listp data) (setf len (length len)) (setf ref #'elt))) (unless (= len (if (= size 4) 8 4)) (error "~a format requires ~d data bytes, got: ~s." format (if (= size 4) 8 4) data)) (unless (case fmt ((0 1) (do ((f t) (i 0 (+ i 1)) (z nil)) ((or (not (< i len)) (not f)) f) (setf z (funcall ref data)) (setf f (and (integerp z) (<= 0 z size))))) ((2) (do ((f t) (i 0 (+ i 1))) ((or (not (< i len)) (not f)) f) (setf f (characterp (funcall ref data))))) ((3) (stringp data))) (error "Not valid ~d-bit data: ~s" size data)) (flet ((datafn (n) (if (= fmt 0) (funcall ref data n) (let ((d (funcall ref data (floor n 2)))) (when (>= fmt 2) (setf d (char-code d))) (if (evenp n) (ash (logand d 240) -4) (logand d 15)))))) (make-sysex-data +real-time-id+ device-id +long-form-mtc-sub-id+ +smpte-user-bits-sub-id-2+ (datafn 0) (datafn 1) (datafn 2) (datafn 3) (datafn 4) (datafn 5) (datafn 6) (datafn 7) (if (= fmt 2) +smpte-user-bits-chars+ +smpte-user-bits-raw+))))) (defparameter +bar-marker-sub-id-2+ 1) (defun make-measure-number-sysex-data (num &key (countoff nil) (device-id +all-device-ids+)) (when countoff (setf num (- (abs num)))) (setf num (n-bit-twoscomp num 14 t)) (make-sysex-data +real-time-id+ device-id +notation-information-sub-id+ +bar-marker-sub-id-2+ (ldb (byte 7 0) num) (ldb (byte 7 7) num))) (defparameter +time-signature-now-sub-id-2+ 2) (defparameter +time-signature-next-measure-sub-id-2+ 66) (defun make-time-signature-sysex-data (numerators denominators &key (32nds 8) (defer nil) (device-id +all-device-ids+)) (unless (listp numerators) (setf numerators (list numerators))) (unless (listp denominators) (setf denominators (list denominators))) (let* ((len (max (length numerators) (length denominators))) (args (loop with f and r for i from 0 for n = (or (elt numerators i) n) for d = (or (elt denominators i) d) repeat len do (multiple-value-setq (f r) (floor (log2 d))) collect n collect (if (not (zerop r)) (error "Not a power of 2: ~s" d) f)))) (make-sysex-data +real-time-id+ device-id +notation-information-sub-id+ (if defer +time-signature-next-measure-sub-id-2+ +time-signature-now-sub-id-2+) (+ (* 2 len) 1) (first args) (second args) 32nds (cdr (cdr args))))) (defparameter +setup-special-sub-id-2+ 0) (defparameter +setup-punch-in-point-sub-id-2+ 1) (defparameter +setup-punch-out-point-sub-id-2+ 2) (defparameter +setup-delete-punch-in-point-sub-id-2+ 3) (defparameter +setup-delete-punch-out-point-sub-id-2+ 4) (defparameter +setup-event-start-point-sub-id-2+ 5) (defparameter +setup-event-stop-point-sub-id-2+ 6) (defparameter +setup-xtnd-event-start-point-sub-id-2+ 7) (defparameter +setup-xtnd-event-stop-point-sub-id-2+ 8) (defparameter +setup-delete-event-start-point-sub-id-2+ 9) (defparameter +setup-delete-event-stop-point-sub-id-2+ 10) (defparameter +setup-cue-point-sub-id-2+ 11) (defparameter +setup-xtnd-cue-point-sub-id-2+ 12) (defparameter +setup-delete-cue-point-sub-id-2+ 13) (defparameter +setup-event-name-sub-id-2+ 14) (defun %make-setup-data (dev subid2 fmt hr mn sc fr ff num &optional xtnd) (make-sysex-data +non-real-time-id+ dev +midi-time-code-setup-sub-id+ subid2 (encode-smpte-data hr mn sc fr :subframes ff :format fmt) (cond ((and (listp num) (= (length num) 2)) (n-bit-twoscomp-p (car num) 7 (< (car num) 0) t) (n-bit-twoscomp-p (cadr num) 7 (< (cadr num) 0) t) num) ((and (vectorp num) (= (length num) 2)) (n-bit-twoscomp-p (elt num 0) 7 (< (elt num 0) 0) t) (n-bit-twoscomp-p (elt num 1) 7 (< (elt num 1) 0) t) num) (t (n-bit-bytes num 2 7 t))) (nibblize t xtnd))) (defparameter +setup-special-time-code-offset-type+ (quote (0 0))) (defparameter +setup-special-enable-event-list-type+ (quote (1 0))) (defparameter +setup-special-disable-event-list-type+ (quote (2 0))) (defparameter +setup-special-clear-event-list-type+ (quote (3 0))) (defparameter +setup-special-system-stop-type+ (quote (4 0))) (defparameter +setup-special-event-list-request-type+ (quote (5 0))) (defun make-time-code-offset-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-time-code-offset-type+)) (defun make-enable-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-enable-event-list-type+)) (defun make-disable-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-disable-event-list-type+)) (defun make-clear-event-list-sysex-data (&key (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ 0 0 0 0 0 0 +setup-special-clear-event-list-type+)) (defun make-system-stop-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-system-stop-type+)) (defun make-event-list-request-sysex-data (hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-special-sub-id-2+ format hr mn sc fr ff +setup-special-event-list-request-type+)) (defun make-punch-in-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-punch-in-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-punch-out-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-punch-out-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-delete-punch-in-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-punch-in-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-delete-punch-out-point-sysex-data (track hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-punch-out-point-sub-id-2+ format hr mn sc fr ff track)) (defun make-event-start-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-event-stop-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-xtnd-event-start-point-sysex-data (event-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr data)) (defun make-xtnd-event-stop-point-sysex-data (event-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr data)) (defun make-delete-event-start-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-event-start-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-delete-event-stop-point-sysex-data (event-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-event-stop-point-sub-id-2+ format hr mn sc fr ff event-nr)) (defun make-cue-point-sysex-data (cue-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr)) (defun make-xtnd-cue-point-sysex-data (cue-nr hr mn sc fr ff data &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-xtnd-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr data)) (defun make-delete-cue-point-sysex-data (cue-nr hr mn sc fr ff &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-delete-cue-point-sub-id-2+ format hr mn sc fr ff cue-nr)) (defun make-event-name-sysex-data (event-nr hr mn sc fr ff name &key (format +smpte-format-30fps+) (device-id +all-device-ids+)) (%make-setup-data device-id +setup-event-name-sub-id-2+ format hr mn sc fr ff event-nr name)) (progn (defclass midi-event (event) ((opcode :accessor midi-event-opcode :allocation :class))) (defparameter <midi-event> (find-class 'midi-event)) (finalize-class <midi-event>) (values)) (defmethod midi-event-data1 ((obj midi-event)) obj nil) (defmethod midi-event-data2 ((obj midi-event)) obj nil) (progn (defclass midi-channel-event (midi-event) ((channel :initform 0 :initarg :channel :accessor midi-event-channel))) (defparameter <midi-channel-event> (find-class 'midi-channel-event)) (finalize-class <midi-channel-event>) (values)) (progn (defclass midi-system-event (midi-event) ((opcode :initform 240) (type :initform 0 :initarg :type :accessor midi-event-data1) (data :initform nil :initarg :data :accessor midi-event-data2))) (defparameter <midi-system-event> (find-class 'midi-system-event)) (finalize-class <midi-system-event>) (values)) (progn (defclass midi-meta-event (midi-event) ((opcode :initform 255))) (defparameter <midi-meta-event> (find-class 'midi-meta-event)) (finalize-class <midi-meta-event>) (values)) (defmethod midi-event->midi-message ((event midi-channel-event)) (values (make-channel-message (slot-value event 'opcode) (midi-event-channel event) (midi-event-data1 event) (or (midi-event-data2 event) 0)) nil)) (defmethod midi-event->midi-message ((event midi-system-event)) (let* ((type (midi-event-data1 event)) (code (logior 240 type)) (data (midi-event-data2 event))) (cond ((eq type 0) (make-sysex 0 data)) ((<= 1 type 3) (make-system-message 0 code (midi-event-data2 event))) (t (make-system-message 0 code))))) (defmethod midi-event->midi-message ((event midi-meta-event)) (let ((op (slot-value event 'opcode))) (cond ((eq op +ml-file-sequence-number-opcode+) (make-sequence-number (midi-event-data1 event))) ((eq op +ml-file-text-event-opcode+) (make-text-event (midi-event-data2 event) (midi-event-data1 event))) ((eq op +ml-file-eot-opcode+) (make-eot)) ((eq op +ml-file-tempo-change-opcode+) (make-tempo-change (midi-event-data1 event))) ((eq op +ml-file-smpte-offset-opcode+) (apply #'make-smpte-offset (midi-event-data1 event))) ((eq op +ml-file-time-signature-opcode+) (make-time-signature (midi-event-data1 event) (midi-event-data2 event) (midi-event-data3 event) (midi-event-data4 event))) ((eq op +ml-file-key-signature-opcode+) (make-key-signature (midi-event-data1 event) (midi-event-data2 event))) ((eq op +ml-file-sequencer-event-opcode+) (make-sequencer-event (midi-event-data1 event))) (t (error "Unimplemented meta-event opcode: ~s" op)))))
d5cb298ff0e6932f6fe8345e04876637ecccd271881215bcf54d31bd0c2adaca
dropbox/datagraph
NumberDataSource.hs
# LANGUAGE StandaloneDeriving , GADTs , TypeFamilies , MultiParamTypeClasses , GeneralizedNewtypeDeriving , OverloadedStrings # # OPTIONS_GHC -fno - warn - orphans # module NumberDataSource where import Data.Hashable import Haxl.Core import Data.IORef import Control.Monad (forM_) import Text.Printf import GraphQLHelpers import qualified Data.HashMap.Strict as HashMap data NumberRequest a where AddToNumber :: Int -> NumberRequest () FetchCurrentNumber :: NumberRequest NumberObject deriving instance Eq (NumberRequest a) deriving instance Show (NumberRequest a) instance Hashable (NumberRequest a) where hashWithSalt salt (AddToNumber i) = hashWithSalt salt (0 :: Int, i) hashWithSalt salt (FetchCurrentNumber) = hashWithSalt salt (1 :: Int) data NumberObject = NumberObject { theNumber :: Int } deriving (Show) instance GraphQLObject NumberObject where resolveObject (NumberObject v) = HashMap.fromList [ ("theNumber", knownValue v) ] instance StateKey NumberRequest where data State NumberRequest = NumberRequestState (IORef Int) runNumberRequest :: IORef Int -> NumberRequest a -> ResultVar a -> IO () runNumberRequest numberRef (AddToNumber i) var = do modifyIORef numberRef (+ i) putSuccess var () runNumberRequest numberRef FetchCurrentNumber var = do NumberObject <$> readIORef numberRef >>= putSuccess var instance DataSourceName NumberRequest where dataSourceName _ = "NumberRequestDataSource" instance Show1 NumberRequest where show1 (AddToNumber i) = printf "AddToNumber(%i)" i show1 (FetchCurrentNumber) = "FetchCurrentNumber" instance DataSource () NumberRequest where fetch (NumberRequestState numberRef) _ _ reqs = SyncFetch $ do putStrLn $ "do some number requests: " ++ show [show1 req | BlockedFetch req _ <- reqs] forM_ reqs $ \(BlockedFetch req var) -> do runNumberRequest numberRef req var initializeNumberDataSource :: Int -> IO (State NumberRequest) initializeNumberDataSource i = NumberRequestState <$> newIORef i
null
https://raw.githubusercontent.com/dropbox/datagraph/429957ebdbf1ef3553dabb2a8f7b16056ef4ac41/src/NumberDataSource.hs
haskell
# LANGUAGE StandaloneDeriving , GADTs , TypeFamilies , MultiParamTypeClasses , GeneralizedNewtypeDeriving , OverloadedStrings # # OPTIONS_GHC -fno - warn - orphans # module NumberDataSource where import Data.Hashable import Haxl.Core import Data.IORef import Control.Monad (forM_) import Text.Printf import GraphQLHelpers import qualified Data.HashMap.Strict as HashMap data NumberRequest a where AddToNumber :: Int -> NumberRequest () FetchCurrentNumber :: NumberRequest NumberObject deriving instance Eq (NumberRequest a) deriving instance Show (NumberRequest a) instance Hashable (NumberRequest a) where hashWithSalt salt (AddToNumber i) = hashWithSalt salt (0 :: Int, i) hashWithSalt salt (FetchCurrentNumber) = hashWithSalt salt (1 :: Int) data NumberObject = NumberObject { theNumber :: Int } deriving (Show) instance GraphQLObject NumberObject where resolveObject (NumberObject v) = HashMap.fromList [ ("theNumber", knownValue v) ] instance StateKey NumberRequest where data State NumberRequest = NumberRequestState (IORef Int) runNumberRequest :: IORef Int -> NumberRequest a -> ResultVar a -> IO () runNumberRequest numberRef (AddToNumber i) var = do modifyIORef numberRef (+ i) putSuccess var () runNumberRequest numberRef FetchCurrentNumber var = do NumberObject <$> readIORef numberRef >>= putSuccess var instance DataSourceName NumberRequest where dataSourceName _ = "NumberRequestDataSource" instance Show1 NumberRequest where show1 (AddToNumber i) = printf "AddToNumber(%i)" i show1 (FetchCurrentNumber) = "FetchCurrentNumber" instance DataSource () NumberRequest where fetch (NumberRequestState numberRef) _ _ reqs = SyncFetch $ do putStrLn $ "do some number requests: " ++ show [show1 req | BlockedFetch req _ <- reqs] forM_ reqs $ \(BlockedFetch req var) -> do runNumberRequest numberRef req var initializeNumberDataSource :: Int -> IO (State NumberRequest) initializeNumberDataSource i = NumberRequestState <$> newIORef i
0126149db5d99d806261ec2d87ab09f03252e85a0eaeb8d43de40ba7716f6a73
2600hz/kazoo
kzt_twiml_util.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kzt_twiml_util). -export([get_terminators/1 ,loop_count/1 ,get_voice/1 ,get_engine/1 ,get_lang/1 ,finish_dtmf/1, finish_dtmf/2 ,get_finish_key/1 ,get_max_length/1 ,pause_for/1 ,action_url/1 ,timeout_s/1, timeout_s/2 ,num_digits/1 ,reject_prompt/1 ,reject_reason/1 ,reject_code/1 ,reject_status/1 ]). -include("kzt.hrl"). -spec get_terminators(kz_term:proplist()) -> kz_term:ne_binaries(). get_terminators(Props) -> kapi_dialplan:terminators(props:get_binary_value('terminators', Props)). -spec get_lang(kz_term:proplist()) -> kz_term:ne_binary(). get_lang(Props) -> case props:get_binary_value('language', Props) of 'undefined' -> ?DEFAULT_TTS_LANG; <<"en">> -> <<"en-US">>; <<"en-gb">> -> <<"en-GB">>; <<"es">> -> <<"es">>; <<"fr">> -> <<"fr">>; <<"de">> -> <<"de">>; <<"it">> -> <<"it">> end. -spec get_voice(kz_term:proplist()) -> kz_term:ne_binary(). get_voice(Props) -> case props:get_binary_value('voice', Props) of <<"man">> -> <<"male">>; <<"male">> -> <<"male">>; <<"woman">> -> <<"female">>; <<"female">> -> <<"female">>; 'undefined' -> ?DEFAULT_TTS_VOICE end. -spec get_engine(kz_term:proplist()) -> kz_term:ne_binary(). get_engine(Props) -> case props:get_binary_value('engine', Props) of 'undefined' -> ?DEFAULT_TTS_ENGINE; Engine -> Engine end. -spec loop_count(kz_term:proplist()) -> integer(). loop_count(Props) -> props:get_integer_value('loop', Props, 1). -spec finish_dtmf(kz_term:proplist()) -> kz_term:ne_binary(). finish_dtmf(Props) -> finish_dtmf(Props, <<"#">>). -spec finish_dtmf(kz_term:proplist(), kz_term:ne_binary()) -> kz_term:api_ne_binary(). finish_dtmf(Props, Default) when is_list(Props) -> case props:get_binary_value('finishOnKey', Props) of 'undefined' -> Default; <<>> -> 'undefined'; DTMF -> 'true' = lists:member(DTMF, ?ANY_DIGIT), DTMF end. -spec get_finish_key(kz_term:proplist()) -> kz_term:ne_binaries(). get_finish_key(Props) -> kapi_dialplan:terminators(props:get_binary_value('finishOnKey', Props)). -spec get_max_length(kz_term:proplist()) -> pos_integer(). get_max_length(Props) -> Max = kapps_config:get_integer(<<?MODULE_STRING>>, <<"max_length">>, 3600), case props:get_integer_value('maxLength', Props) of 'undefined' -> Max; N when N > 0, N =< Max -> N end. limit pause to 1 hour ( 3600000 ms ) -spec pause_for(kz_term:proplist()) -> 1000..3600000. pause_for(Props) -> case props:get_integer_value('length', Props) of 'undefined' -> ?MILLISECONDS_IN_SECOND; N when is_integer(N), N > 0, N =< 3600 -> N * ?MILLISECONDS_IN_SECOND; N when is_integer(N), N > 3600 -> 3600000 end. -spec action_url(kz_term:proplist()) -> kz_term:api_binary(). action_url(Props) -> props:get_binary_value('action', Props). -spec reject_prompt(kz_term:proplist()) -> kz_term:api_binary(). reject_prompt(Props) -> props:get_binary_value('prompt', Props). -spec timeout_s(kz_term:proplist()) -> pos_integer(). timeout_s(Props) -> timeout_s(Props, 30). -spec timeout_s(kz_term:proplist(), pos_integer()) -> pos_integer(). timeout_s(Props, Default) -> case props:get_integer_value('timeout', Props, Default) of N when is_integer(N), N > 3600 -> 3600; N when is_integer(N), N > 0 -> N end. -spec num_digits(kz_term:proplist()) -> timeout(). num_digits(Props) -> case props:get_integer_value('numDigits', Props) of 'undefined' -> 'infinity'; N when is_integer(N), N > 0 -> N end. -spec reject_reason(kz_term:proplist()) -> kz_term:ne_binary(). reject_reason(Props) -> case props:get_binary_value('reason', Props) of 'undefined' -> <<"rejected">>; <<"rejected">> -> <<"rejected">>; <<"busy">> -> <<"busy">> end. -spec reject_code(kz_term:ne_binary()) -> kz_term:ne_binary(). reject_code(<<"busy">>) -> <<"486">>; reject_code(<<"rejected">>) -> <<"503">>. -spec reject_status(kz_term:ne_binary()) -> kz_term:ne_binary(). reject_status(<<"486">>) -> ?STATUS_BUSY; reject_status(<<"503">>) -> ?STATUS_NOANSWER.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_translator/src/converters/kzt_twiml_util.erl
erlang
----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(kzt_twiml_util). -export([get_terminators/1 ,loop_count/1 ,get_voice/1 ,get_engine/1 ,get_lang/1 ,finish_dtmf/1, finish_dtmf/2 ,get_finish_key/1 ,get_max_length/1 ,pause_for/1 ,action_url/1 ,timeout_s/1, timeout_s/2 ,num_digits/1 ,reject_prompt/1 ,reject_reason/1 ,reject_code/1 ,reject_status/1 ]). -include("kzt.hrl"). -spec get_terminators(kz_term:proplist()) -> kz_term:ne_binaries(). get_terminators(Props) -> kapi_dialplan:terminators(props:get_binary_value('terminators', Props)). -spec get_lang(kz_term:proplist()) -> kz_term:ne_binary(). get_lang(Props) -> case props:get_binary_value('language', Props) of 'undefined' -> ?DEFAULT_TTS_LANG; <<"en">> -> <<"en-US">>; <<"en-gb">> -> <<"en-GB">>; <<"es">> -> <<"es">>; <<"fr">> -> <<"fr">>; <<"de">> -> <<"de">>; <<"it">> -> <<"it">> end. -spec get_voice(kz_term:proplist()) -> kz_term:ne_binary(). get_voice(Props) -> case props:get_binary_value('voice', Props) of <<"man">> -> <<"male">>; <<"male">> -> <<"male">>; <<"woman">> -> <<"female">>; <<"female">> -> <<"female">>; 'undefined' -> ?DEFAULT_TTS_VOICE end. -spec get_engine(kz_term:proplist()) -> kz_term:ne_binary(). get_engine(Props) -> case props:get_binary_value('engine', Props) of 'undefined' -> ?DEFAULT_TTS_ENGINE; Engine -> Engine end. -spec loop_count(kz_term:proplist()) -> integer(). loop_count(Props) -> props:get_integer_value('loop', Props, 1). -spec finish_dtmf(kz_term:proplist()) -> kz_term:ne_binary(). finish_dtmf(Props) -> finish_dtmf(Props, <<"#">>). -spec finish_dtmf(kz_term:proplist(), kz_term:ne_binary()) -> kz_term:api_ne_binary(). finish_dtmf(Props, Default) when is_list(Props) -> case props:get_binary_value('finishOnKey', Props) of 'undefined' -> Default; <<>> -> 'undefined'; DTMF -> 'true' = lists:member(DTMF, ?ANY_DIGIT), DTMF end. -spec get_finish_key(kz_term:proplist()) -> kz_term:ne_binaries(). get_finish_key(Props) -> kapi_dialplan:terminators(props:get_binary_value('finishOnKey', Props)). -spec get_max_length(kz_term:proplist()) -> pos_integer(). get_max_length(Props) -> Max = kapps_config:get_integer(<<?MODULE_STRING>>, <<"max_length">>, 3600), case props:get_integer_value('maxLength', Props) of 'undefined' -> Max; N when N > 0, N =< Max -> N end. limit pause to 1 hour ( 3600000 ms ) -spec pause_for(kz_term:proplist()) -> 1000..3600000. pause_for(Props) -> case props:get_integer_value('length', Props) of 'undefined' -> ?MILLISECONDS_IN_SECOND; N when is_integer(N), N > 0, N =< 3600 -> N * ?MILLISECONDS_IN_SECOND; N when is_integer(N), N > 3600 -> 3600000 end. -spec action_url(kz_term:proplist()) -> kz_term:api_binary(). action_url(Props) -> props:get_binary_value('action', Props). -spec reject_prompt(kz_term:proplist()) -> kz_term:api_binary(). reject_prompt(Props) -> props:get_binary_value('prompt', Props). -spec timeout_s(kz_term:proplist()) -> pos_integer(). timeout_s(Props) -> timeout_s(Props, 30). -spec timeout_s(kz_term:proplist(), pos_integer()) -> pos_integer(). timeout_s(Props, Default) -> case props:get_integer_value('timeout', Props, Default) of N when is_integer(N), N > 3600 -> 3600; N when is_integer(N), N > 0 -> N end. -spec num_digits(kz_term:proplist()) -> timeout(). num_digits(Props) -> case props:get_integer_value('numDigits', Props) of 'undefined' -> 'infinity'; N when is_integer(N), N > 0 -> N end. -spec reject_reason(kz_term:proplist()) -> kz_term:ne_binary(). reject_reason(Props) -> case props:get_binary_value('reason', Props) of 'undefined' -> <<"rejected">>; <<"rejected">> -> <<"rejected">>; <<"busy">> -> <<"busy">> end. -spec reject_code(kz_term:ne_binary()) -> kz_term:ne_binary(). reject_code(<<"busy">>) -> <<"486">>; reject_code(<<"rejected">>) -> <<"503">>. -spec reject_status(kz_term:ne_binary()) -> kz_term:ne_binary(). reject_status(<<"486">>) -> ?STATUS_BUSY; reject_status(<<"503">>) -> ?STATUS_NOANSWER.
934f90d7a3252719a1472e72447a99d231f833973e81dadaf97f54f96dde2aa9
dongcarl/guix
haskell-crypto.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > Copyright © 2015 , 2017 , 2018 , 2019 < > Copyright © 2016 Nikita < > Copyright © 2017 rsiddharth < > Copyright © 2017 , 2019 < > Copyright © 2020 < > ;;; ;;; 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 haskell-crypto) #:use-module (gnu packages) #:use-module (gnu packages compression) #:use-module (gnu packages haskell) #:use-module (gnu packages haskell-check) #:use-module (gnu packages haskell-xyz) #:use-module (gnu packages tls) #:use-module (guix build-system haskell) #:use-module (guix download) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix utils)) (define-public ghc-asn1-types (package (name "ghc-asn1-types") (version "0.3.3") (source (origin (method url-fetch) (uri (string-append "/" "asn1-types/asn1-types-" version ".tar.gz")) (sha256 (base32 "162lacdl9jr42pdhaj9hxqlba6hjxm6g866anna74q6v3cvw5ssp")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-hourglass" ,ghc-hourglass))) (home-page "-asn1-types") (synopsis "ASN.1 types for Haskell") (description "The package provides the standard types for dealing with the ASN.1 format.") (license license:bsd-3))) (define-public ghc-asn1-encoding (package (name "ghc-asn1-encoding") (version "0.9.6") (source (origin (method url-fetch) (uri (string-append "/" "asn1-encoding/asn1-encoding-" version ".tar.gz")) (sha256 (base32 "02nsr30h5yic1mk7znf0q4z3n560ip017n60hg7ya25rsfmxxy6r")))) (build-system haskell-build-system) (inputs `(("ghc-hourglass" ,ghc-hourglass) ("ghc-asn1-types" ,ghc-asn1-types))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (home-page "-asn1") (synopsis "ASN1 data reader and writer in RAW, BER and DER forms") (description "This package provides a reader and writer for ASN1 data in raw form with supports for high level forms of ASN1 (BER, and DER).") (license license:bsd-3))) (define-public ghc-asn1-parse (package (name "ghc-asn1-parse") (version "0.9.5") (source (origin (method url-fetch) (uri (string-append "/" "asn1-parse/asn1-parse-" version ".tar.gz")) (sha256 (base32 "17pk8y3nwv9b9i5j15qlmwi7fmq9ab2z4kfpjk2rvcrh9lsf27wg")))) (build-system haskell-build-system) (inputs `(("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding))) (home-page "-asn1") (synopsis "Simple monadic parser for ASN1 stream types") (description "This package provides a simple monadic parser for ASN1 stream types, when ASN1 pattern matching is not convenient.") (license license:bsd-3))) (define-public ghc-crypto-api (package (name "ghc-crypto-api") (version "0.13.3") (source (origin (method url-fetch) (uri (string-append "/" "crypto-api-" version "/" "crypto-api-" version ".tar.gz")) (sha256 (base32 "19bsmkqkpnvh01b77pmyarx00fic15j4hvg4pzscrj4prskrx2i9")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-tagged" ,ghc-tagged) ("ghc-entropy" ,ghc-entropy))) (home-page "-api") (synopsis "Provides generic interface for cryptographic operations for Haskell") (description "This Haskell package provides a generic interface for cryptographic operations (hashes, ciphers, randomness). Maintainers of hash and cipher implementations are encouraged to add instances for the classes defined in @code{Crypto.Classes}. @code{Crypto} users are similarly encouraged to use the interfaces defined in the @code{Classes} module. Any concepts or functions of general use to more than one cryptographic algorithm (ex: padding) is within scope of this package.") (license license:bsd-3))) (define-public ghc-crypto-api-tests (package (name "ghc-crypto-api-tests") (version "0.3") (source (origin (method url-fetch) (uri (string-append "/" "crypto-api-tests-" version "/" "crypto-api-tests-" version ".tar.gz")) (sha256 (base32 "0w3j43jdrlj28jryp18hc6q84nkl2yf4vs1hhgrsk7gb9kfyqjpl")))) (build-system haskell-build-system) (outputs '("out" "static" "doc")) (inputs `(("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-crypto-api" ,ghc-crypto-api) ("ghc-cereal" ,ghc-cereal) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-api-tests") (synopsis "Test framework and KATs for cryptographic operations for Haskell") (description "This Haskell package provides a test framework for hash and cipher operations using the crypto-api interface. Known answer tests (KATs) for common cryptographic algorithms are included.") (license license:bsd-3))) (define-public ghc-cryptohash (package (name "ghc-cryptohash") (version "0.11.9") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1yr2iyb779znj79j3fq4ky8l1y8a600a2x1fx9p5pmpwq5zq93y2")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-memory" ,ghc-memory) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-cryptohash") (synopsis "Collection of cryptographic hashes in Haskell") (description "A collection of crypto hashes, with a practical incremental and one-pass, pure APIs, with performance close to the fastest implementations available in other languages. The implementations are made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptohash-md5 (package (name "ghc-cryptohash-md5") (version "0.11.100.1") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-md5-" version "/" "cryptohash-md5-" version ".tar.gz")) (sha256 (base32 "1y8q7s2bn4gdknw1wjikdnar2b5pgz3nv3220lxrlgpsf23x82vi")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("4" "0gzaibjkipijwj9m9l6wrhfk5s3kdvfbhdl7cl1373cjfs41v0m3") tests require old version of ghc - hunit ( 0.9 ) (native-inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring) ("ghc-puremd5" ,ghc-puremd5) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-md5") (synopsis "MD5 implementation for Haskell") (description "This Haskell package provides implementation of MD5.") (license license:bsd-3))) (define-public ghc-cryptohash-sha1 (package (name "ghc-cryptohash-sha1") (version "0.11.100.1") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-sha1-" version "/" "cryptohash-sha1-" version ".tar.gz")) (sha256 (base32 "1aqdxdhxhl9jldh951djpwxx8z7gzaqspxl7iwpl84i5ahrsyy9w")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("4" "0qb2wasfc4dpf6f9ahvhlv8njb3p3p9iwblg4032ssi95cg85718") tests require old version of ghc - hunit ( 0.9 ) (native-inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring) ("ghc-sha" ,ghc-sha) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-sha1") (synopsis "SHA-1 implementation for Haskell") (description "This Haskell package provides an incremental and one-pass, pure API to the @uref{-1, SHA-1 hash algorithm}, including @uref{, HMAC support}, with performance close to the fastest implementations available in other languages. The implementation is made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptohash-sha256 (package (name "ghc-cryptohash-sha256") (version "0.11.101.0") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-sha256-" version "/" "cryptohash-sha256-" version ".tar.gz")) (sha256 (base32 "1p85vajcgw9hmq8zsz9krzx0vxh7aggwbg5w9ws8w97avcsn8xaj")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("3" "1arhz4y792kx439s2zv9x291gvvl2zxcfx9sq0nxsjlz7c3hpyp1") tests require old version of ghc - hunit ( 0.9 ) (inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring))) (native-inputs `(("ghc-sha" ,ghc-sha) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-sha1") (synopsis "SHA-256 implementation for Haskell") (description "This Haskell package provides an incremental and one-pass, pure API to the @uref{-2, SHA-256 cryptographic hash algorithm}, with performance close to the fastest implementations available in other languages. The implementation is made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptonite (package (name "ghc-cryptonite") (version "0.25") (source (origin (method url-fetch) (uri (string-append "/" "cryptonite/cryptonite-" version ".tar.gz")) (sha256 (base32 "131wbbdr5yavs5k1ah9sz6fqx1ffyvaxf66pwjzsfc47mwc1mgl9")))) (build-system haskell-build-system) ;; FIXME: tests are broken. ;; See -crypto/cryptonite/issues/260 (arguments '(#:tests? #f)) (outputs '("out" "static" "doc")) (inputs `(("ghc-basement" ,ghc-basement) ("ghc-memory" ,ghc-memory) ("ghc-byteable" ,ghc-byteable))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-tasty-hunit" ,ghc-tasty-hunit) ("ghc-tasty-kat" ,ghc-tasty-kat))) (home-page "-crypto/cryptonite") (synopsis "Cryptography primitives") (description "This package is a repository of cryptographic primitives for Haskell. It supports a wide range of symmetric ciphers, cryptographic hash functions, public key algorithms, key derivation numbers, cryptographic random number generators, and more.") (license license:bsd-3))) (define-public ghc-digest (package (name "ghc-digest") (version "0.0.1.2") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "04gy2zp8yzvv7j9bdfvmfzcz3sqyqa6rwslqcn4vyair2vmif5v4")))) (build-system haskell-build-system) (arguments `(#:extra-directories ("zlib"))) (inputs `(("zlib" ,zlib))) (home-page "") (synopsis "Various cryptographic hashes for bytestrings") (description "This package provides efficient cryptographic hash implementations for strict and lazy bytestrings. For now, CRC32 and Adler32 are supported; they are implemented as FFI bindings to efficient code from zlib.") (license license:bsd-3))) (define-public ghc-entropy (package (name "ghc-entropy") (version "0.4.1.5") (source (origin (method url-fetch) (uri (string-append "/" "entropy-" version "/" "entropy-" version ".tar.gz")) (sha256 (base32 "0szf8hi1pi8g0kxnkcymh65gk1b0niyl1nnkckzdqyar87qal0jm")))) (build-system haskell-build-system) (home-page "") (synopsis "Provides platform independent entropy source for Haskell") (description "This Haskell package provides a platform independent method to obtain cryptographically strong entropy.") (license license:bsd-3))) (define-public ghc-pem (package (name "ghc-pem") (version "0.2.4") (source (origin (method url-fetch) (uri (string-append "/" "pem/pem-" version ".tar.gz")) (sha256 (base32 "1m7qjsxrd8m88cvkqmr8kscril500j2a9y0iynvksjyjkhdlq33p")))) (build-system haskell-build-system) (inputs `(("ghc-basement" ,ghc-basement) ("ghc-memory" ,ghc-memory))) (native-inputs `(("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-pem") (synopsis "Privacy Enhanced Mail (PEM) format reader and writer") (description "This library provides readers and writers for the @dfn{Privacy Enhanced Mail} (PEM) format.") (license license:bsd-3))) (define-public ghc-puremd5 (package (name "ghc-puremd5") (version "2.1.3") (source (origin (method url-fetch) (uri (string-append "/" "pureMD5-" version "/" "pureMD5-" version ".tar.gz")) (sha256 (base32 "0zdilz41cla2ck7mcw1a9702gyg2abq94mqahr4vci9sbs53bwxy")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-crypto-api" ,ghc-crypto-api) ("ghc-tagged" ,ghc-tagged))) (native-inputs `(("ghc-crypto-api-tests" ,ghc-crypto-api-tests) ("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-pretty-hex" ,ghc-pretty-hex))) (home-page "") (synopsis "Haskell implementation of the MD5 hash algorithm") (description "This package provides a Haskell-only implementation of the MD5 digest (hash) algorithm. This now supports the @code{crypto-api} class interface.") (license license:bsd-3))) (define-public ghc-sha (package (name "ghc-sha") (version "1.6.4.4") (source (origin (method url-fetch) (uri (string-append "/" "SHA/SHA-" version ".tar.gz")) (sha256 (base32 "0i4b2wjisivdy72synal711ywhx05mfqfba5n65rk8qidggm1nbb")))) (build-system haskell-build-system) (native-inputs `(("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2))) (home-page "") (synopsis "SHA suite of message digest functions") (description "This library implements the SHA suite of message digest functions, according to NIST FIPS 180-2 (with the SHA-224 addendum), as well as the SHA-based HMAC routines. The functions have been tested against most of the NIST and RFC test vectors for the various functions. While some attention has been paid to performance, these do not presently reach the speed of well-tuned libraries, like OpenSSL.") (license license:bsd-3))) (define-public ghc-x509 (package (name "ghc-x509") (version "1.7.5") (source (origin (method url-fetch) (uri (string-append "/" "x509/x509-" version ".tar.gz")) (sha256 (base32 "1j67c35g8334jx7x32hh6awhr43dplp0qwal5gnlkmx09axzrc5i")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-hourglass" ,ghc-hourglass) ("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-asn1-parse" ,ghc-asn1-parse) ("ghc-cryptonite" ,ghc-cryptonite))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (home-page "-certificate") (synopsis "X509 reader and writer") (description "This library provides functions to read and write X509 certificates.") (license license:bsd-3))) (define-public ghc-x509-store (package (name "ghc-x509-store") (version "1.6.7") (source (origin (method url-fetch) (uri (string-append "/" "x509-store/x509-store-" version ".tar.gz")) (sha256 (base32 "1y8yyr1i95jkllg8k0z54k5v4vachp848clc07m33xpxidn3b1lp")))) (build-system haskell-build-system) (inputs `(("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-x509" ,ghc-x509))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-certificate") (synopsis "X.509 collection accessing and storing methods") (description "This package provides functions for accessing and storing X.509 collections, certificates, revocation lists, and exception lists.") (license license:bsd-3))) (define-public ghc-x509-validation (package (name "ghc-x509-validation") (version "1.6.11") (source (origin (method url-fetch) (uri (string-append "/" "x509-validation/x509-validation-" version ".tar.gz")) (sha256 (base32 "16yihzljql3z8w5rgdl95fv3hgk7yd86kbl9b3glllsark5j2hzr")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-byteable" ,ghc-byteable) ("ghc-hourglass" ,ghc-hourglass) ("ghc-data-default-class" ,ghc-data-default-class) ("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store) ("ghc-cryptonite" ,ghc-cryptonite))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-certificate") (synopsis "X.509 certificate and revocation list validation") (description "This package provides functions for X.509 certificate and revocation list validation.") (license license:bsd-3))) (define-public ghc-x509-system (package (name "ghc-x509-system") (version "1.6.6") (source (origin (method url-fetch) (uri (string-append "/" "x509-system/x509-system-" version ".tar.gz")) (sha256 (base32 "06a4m9c7vlr9nhp9gmqbb46arf0yj1dkdm4nip03hzy67spdmp20")))) (build-system haskell-build-system) (inputs `(("ghc-pem" ,ghc-pem) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store))) (home-page "-certificate") (synopsis "Handle system X.509 accessors and storage") (description "This package provides a library to handle system accessors and storage for X.509 certificates.") (license license:bsd-3))) (define-public ghc-crypto-cipher-types (package (name "ghc-crypto-cipher-types") (version "0.0.9") (source (origin (method url-fetch) (uri (string-append "/" "crypto-cipher-types-" version "/" "crypto-cipher-types-" version ".tar.gz")) (sha256 (base32 "03qa1i1kj07pfrxsi7fiaqnnd0vi94jd4jfswbmnm4gp1nvzcwr0")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-securemem" ,ghc-securemem))) (home-page "-crypto-cipher") (synopsis "Generic cryptography cipher types for Haskell") (description "This Haskell package provides basic typeclasses and types for symmetric ciphers.") (license license:bsd-3))) (define-public ghc-cipher-aes (package (name "ghc-cipher-aes") (version "0.2.11") (source (origin (method url-fetch) (uri (string-append "/" "cipher-aes-" version "/" "cipher-aes-" version ".tar.gz")) (sha256 (base32 "05ahz6kjq0fl1w66gpiqy0vndli5yx1pbsbw9ni3viwqas4p3cfk")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-securemem" ,ghc-securemem) ("ghc-crypto-cipher-types" ,ghc-crypto-cipher-types))) (native-inputs `(("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-crypto-cipher-tests" ,ghc-crypto-cipher-tests))) (home-page "-cipher-aes") (synopsis "AES cipher implementation with advanced mode of operations for Haskell") (description "This Haskell package provides AES cipher implementation. The modes of operations available are ECB (Electronic code book), CBC (Cipher block chaining), CTR (Counter), XTS (XEX with ciphertext stealing), GCM (Galois Counter Mode). The AES implementation uses AES-NI when available (on x86 and x86-64 architecture), but fallback gracefully to a software C implementation. The software implementation uses S-Boxes, which might suffer for cache timing issues. However do notes that most other known software implementations, including very popular one (openssl, gnutls) also uses similar implementation. If it matters for your case, you should make sure you have AES-NI available, or you'll need to use a different implementation.") (license license:bsd-3))) (define-public ghc-crypto-random (package (name "ghc-crypto-random") (version "0.0.9") (source (origin (method url-fetch) (uri (string-append "/" "crypto-random-" version "/" "crypto-random-" version ".tar.gz")) (sha256 (base32 "0139kbbb2h7vshf68y3fvjda29lhj7jjwl4vq78w4y8k8hc7l2hp")))) (build-system haskell-build-system) (inputs `(("ghc-securemem" ,ghc-securemem) ("ghc-vector" ,ghc-vector))) (home-page "-crypto-random") (synopsis "Simple cryptographic random related types for Haskell") (description "Simple cryptographic random related types: a safe abstraction for CPRNGs.") (license license:bsd-3))) (define-public ghc-cprng-aes (package (name "ghc-cprng-aes") (version "0.6.1") (source (origin (method url-fetch) (uri (string-append "/" "cprng-aes-" version "/" "cprng-aes-" version ".tar.gz")) (sha256 (base32 "1wr15kbmk1g3l8a75n0iwbzqg24ixv78slwzwb2q6rlcvq0jlnb4")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-crypto-random" ,ghc-crypto-random) ("ghc-cipher-aes" ,ghc-cipher-aes))) (home-page "-cprng-aes") (synopsis "Crypto Pseudo Random Number Generator using AES in counter mode in Haskell") (description "Simple crypto pseudo-random-number-generator with really good randomness property. Using ent, a randomness property maker on one 1Mb sample: @itemize @item Entropy = 7.999837 bits per byte. @item Optimum compression would reduce the size of this 1048576 byte file by 0 percent. @item Chi square distribution for 1048576 samples is 237.02. @item Arithmbetic mean value of data bytes is 127.3422 (127.5 = random). @item Monte Carlo value for Pi is 3.143589568 (error 0.06 percent). @end itemize Compared to urandom with the same sampling: @itemize @item Entropy = 7.999831 bits per byte. @item Optimum compression would reduce the size of this 1048576 byte file by 0 percent. @item Chi square distribution for 1048576 samples is 246.63. @item Arithmetic mean value of data bytes is 127.6347 (127.5 = random). @item Monte Carlo value for Pi is 3.132465868 (error 0.29 percent). @end itemize") (license license:bsd-3))) (define-public ghc-ed25519 (package (name "ghc-ed25519") (version "0.0.5.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0v8msqvgzimhs7p5ri25hrb1ni2wvisl5rmdxy89fc59py79b9fq")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("2" "1cq6h3jqkb1kvd9fjfhsllg5gq78sdiyf2gy9862xhlbv6wil19f") ;; We omit these test suites because they require old versions of ;; packages and packages we do not have. #:configure-flags '("--flags=-test-hlint -test-doctests -test-properties"))) (home-page "-ed25519") (synopsis "Ed25519 cryptographic signatures") (description "This package provides a simple, fast, self-contained copy of the Ed25519 public-key signature system with a clean interface. It also includes support for detached signatures, and thorough documentation on the design and implementation, including usage guidelines.") (license license:expat))) (define-public ghc-tls (package (name "ghc-tls") (version "1.4.1") (source (origin (method url-fetch) (uri (string-append "/" "tls/tls-" version ".tar.gz")) (sha256 (base32 "1y083724mym28n6xfaz7pcc7zqxdhjpaxpbvzxfbs25qq2px3smv")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-data-default-class" ,ghc-data-default-class) ("ghc-memory" ,ghc-memory) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store) ("ghc-x509-validation" ,ghc-x509-validation) ("ghc-async" ,ghc-async) ("ghc-network" ,ghc-network) ("ghc-hourglass" ,ghc-hourglass))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-tls") (synopsis "TLS/SSL protocol native implementation (Server and Client)") (description "Native Haskell TLS and SSL protocol implementation for server and client. This provides a high-level implementation of a sensitive security protocol, eliminating a common set of security issues through the use of the advanced type system, high level constructions and common Haskell features. Currently implement the SSL3.0, TLS1.0, TLS1.1 and TLS1.2 protocol, and support RSA and Ephemeral (Elliptic curve and regular) Diffie Hellman key exchanges, and many extensions.") (license license:bsd-3))) (define-public ghc-hsopenssl (package (name "ghc-hsopenssl") (version "0.11.4.17") (source (origin (method url-fetch) (uri (string-append "/" "HsOpenSSL/HsOpenSSL-" version ".tar.gz")) (sha256 (base32 "0qivl9clmybfglwxqp2sq308rv4ia4rhwshcsc8b029bvpp0mpsi")))) (build-system haskell-build-system) (arguments `(#:extra-directories ("openssl"))) (inputs `(("ghc-network" ,ghc-network) ("openssl" ,openssl))) (home-page "") (synopsis "Partial OpenSSL binding for Haskell") (description "HsOpenSSL is an OpenSSL binding for Haskell. It can generate RSA and DSA keys, read and write PEM files, generate message digests, sign and verify messages, encrypt and decrypt messages. It has also some capabilities of creating SSL clients and servers. This package is in production use by a number of Haskell based systems and stable. You may also be interested in the tls package, @uref{}, which is a pure Haskell implementation of SSL.") (license license:public-domain))) (define-public ghc-openssl-streams (package (name "ghc-openssl-streams") (version "1.2.2.0") (source (origin (method url-fetch) (uri (string-append "/" "openssl-streams/openssl-streams-" version ".tar.gz")) (sha256 (base32 "0rplym6ayydkpr7x9mw3l13p0vzzfzzxw244d7sd3jcvaxpv0rmr")))) (build-system haskell-build-system) (inputs `(("ghc-hsopenssl" ,ghc-hsopenssl) ("ghc-io-streams" ,ghc-io-streams) ("ghc-network" ,ghc-network))) (native-inputs `(("ghc-hunit" ,ghc-hunit) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit))) (home-page "-streams") (synopsis "OpenSSL network support for io-streams") (description "This library contains io-streams routines for secure networking using OpenSSL (by way of HsOpenSSL).") (license license:bsd-3))) (define-public ghc-cryptonite-conduit (package (name "ghc-cryptonite-conduit") (version "0.2.2") (source (origin (method url-fetch) (uri (string-append "/" "cryptonite-conduit/cryptonite-conduit-" version ".tar.gz")) (sha256 (base32 "1bldcmda4xh52mw1wfrjljv8crhw3al7v7kv1j0vidvr7ymnjpbh")))) (build-system haskell-build-system) (inputs `(("ghc-conduit" ,ghc-conduit) ("ghc-conduit-extra" ,ghc-conduit-extra) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-exceptions" ,ghc-exceptions) ("ghc-memory" ,ghc-memory) ("ghc-resourcet" ,ghc-resourcet))) (native-inputs `(("ghc-conduit-combinators" ,ghc-conduit-combinators) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (arguments `(#:cabal-revision ("1" "1hh2nzfz4qpxgivfilgk4ll416lph8b2fdkzpzrmqfjglivydfmz"))) (home-page "-crypto/cryptonite-conduit") (synopsis "Cryptonite bridge for conduit") (description "This package provides conduit interfaces for some of cryptonite's implementations of cryptographic primitives.") (license license:bsd-3)))
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/haskell-crypto.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. FIXME: tests are broken. See -crypto/cryptonite/issues/260 they We omit these test suites because they require old versions of packages and packages we do not have.
Copyright © 2015 < > Copyright © 2015 , 2017 , 2018 , 2019 < > Copyright © 2016 Nikita < > Copyright © 2017 rsiddharth < > Copyright © 2017 , 2019 < > Copyright © 2020 < > 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 haskell-crypto) #:use-module (gnu packages) #:use-module (gnu packages compression) #:use-module (gnu packages haskell) #:use-module (gnu packages haskell-check) #:use-module (gnu packages haskell-xyz) #:use-module (gnu packages tls) #:use-module (guix build-system haskell) #:use-module (guix download) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix utils)) (define-public ghc-asn1-types (package (name "ghc-asn1-types") (version "0.3.3") (source (origin (method url-fetch) (uri (string-append "/" "asn1-types/asn1-types-" version ".tar.gz")) (sha256 (base32 "162lacdl9jr42pdhaj9hxqlba6hjxm6g866anna74q6v3cvw5ssp")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-hourglass" ,ghc-hourglass))) (home-page "-asn1-types") (synopsis "ASN.1 types for Haskell") (description "The package provides the standard types for dealing with the ASN.1 format.") (license license:bsd-3))) (define-public ghc-asn1-encoding (package (name "ghc-asn1-encoding") (version "0.9.6") (source (origin (method url-fetch) (uri (string-append "/" "asn1-encoding/asn1-encoding-" version ".tar.gz")) (sha256 (base32 "02nsr30h5yic1mk7znf0q4z3n560ip017n60hg7ya25rsfmxxy6r")))) (build-system haskell-build-system) (inputs `(("ghc-hourglass" ,ghc-hourglass) ("ghc-asn1-types" ,ghc-asn1-types))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (home-page "-asn1") (synopsis "ASN1 data reader and writer in RAW, BER and DER forms") (description "This package provides a reader and writer for ASN1 data in raw form with supports for high level forms of ASN1 (BER, and DER).") (license license:bsd-3))) (define-public ghc-asn1-parse (package (name "ghc-asn1-parse") (version "0.9.5") (source (origin (method url-fetch) (uri (string-append "/" "asn1-parse/asn1-parse-" version ".tar.gz")) (sha256 (base32 "17pk8y3nwv9b9i5j15qlmwi7fmq9ab2z4kfpjk2rvcrh9lsf27wg")))) (build-system haskell-build-system) (inputs `(("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding))) (home-page "-asn1") (synopsis "Simple monadic parser for ASN1 stream types") (description "This package provides a simple monadic parser for ASN1 stream types, when ASN1 pattern matching is not convenient.") (license license:bsd-3))) (define-public ghc-crypto-api (package (name "ghc-crypto-api") (version "0.13.3") (source (origin (method url-fetch) (uri (string-append "/" "crypto-api-" version "/" "crypto-api-" version ".tar.gz")) (sha256 (base32 "19bsmkqkpnvh01b77pmyarx00fic15j4hvg4pzscrj4prskrx2i9")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-tagged" ,ghc-tagged) ("ghc-entropy" ,ghc-entropy))) (home-page "-api") (synopsis "Provides generic interface for cryptographic operations for Haskell") (description "This Haskell package provides a generic interface for cryptographic operations (hashes, ciphers, randomness). Maintainers of hash and cipher implementations are encouraged to add instances for the classes defined in @code{Crypto.Classes}. @code{Crypto} users are similarly encouraged to use the interfaces defined in the @code{Classes} module. Any concepts or functions of general use to more than one cryptographic algorithm (ex: padding) is within scope of this package.") (license license:bsd-3))) (define-public ghc-crypto-api-tests (package (name "ghc-crypto-api-tests") (version "0.3") (source (origin (method url-fetch) (uri (string-append "/" "crypto-api-tests-" version "/" "crypto-api-tests-" version ".tar.gz")) (sha256 (base32 "0w3j43jdrlj28jryp18hc6q84nkl2yf4vs1hhgrsk7gb9kfyqjpl")))) (build-system haskell-build-system) (outputs '("out" "static" "doc")) (inputs `(("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-crypto-api" ,ghc-crypto-api) ("ghc-cereal" ,ghc-cereal) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-api-tests") (synopsis "Test framework and KATs for cryptographic operations for Haskell") (description "This Haskell package provides a test framework for hash and cipher operations using the crypto-api interface. Known answer tests (KATs) for common cryptographic algorithms are included.") (license license:bsd-3))) (define-public ghc-cryptohash (package (name "ghc-cryptohash") (version "0.11.9") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1yr2iyb779znj79j3fq4ky8l1y8a600a2x1fx9p5pmpwq5zq93y2")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-memory" ,ghc-memory) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-cryptohash") (synopsis "Collection of cryptographic hashes in Haskell") (description "A collection of crypto hashes, with a practical incremental and one-pass, pure APIs, with performance close to the fastest implementations available in other languages. The implementations are made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptohash-md5 (package (name "ghc-cryptohash-md5") (version "0.11.100.1") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-md5-" version "/" "cryptohash-md5-" version ".tar.gz")) (sha256 (base32 "1y8q7s2bn4gdknw1wjikdnar2b5pgz3nv3220lxrlgpsf23x82vi")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("4" "0gzaibjkipijwj9m9l6wrhfk5s3kdvfbhdl7cl1373cjfs41v0m3") tests require old version of ghc - hunit ( 0.9 ) (native-inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring) ("ghc-puremd5" ,ghc-puremd5) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-md5") (synopsis "MD5 implementation for Haskell") (description "This Haskell package provides implementation of MD5.") (license license:bsd-3))) (define-public ghc-cryptohash-sha1 (package (name "ghc-cryptohash-sha1") (version "0.11.100.1") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-sha1-" version "/" "cryptohash-sha1-" version ".tar.gz")) (sha256 (base32 "1aqdxdhxhl9jldh951djpwxx8z7gzaqspxl7iwpl84i5ahrsyy9w")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("4" "0qb2wasfc4dpf6f9ahvhlv8njb3p3p9iwblg4032ssi95cg85718") tests require old version of ghc - hunit ( 0.9 ) (native-inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring) ("ghc-sha" ,ghc-sha) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-sha1") (synopsis "SHA-1 implementation for Haskell") (description "This Haskell package provides an incremental and one-pass, pure API to the @uref{-1, SHA-1 hash algorithm}, including @uref{, HMAC support}, with performance close to the fastest implementations available in other languages. The implementation is made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptohash-sha256 (package (name "ghc-cryptohash-sha256") (version "0.11.101.0") (source (origin (method url-fetch) (uri (string-append "/" "cryptohash-sha256-" version "/" "cryptohash-sha256-" version ".tar.gz")) (sha256 (base32 "1p85vajcgw9hmq8zsz9krzx0vxh7aggwbg5w9ws8w97avcsn8xaj")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("3" "1arhz4y792kx439s2zv9x291gvvl2zxcfx9sq0nxsjlz7c3hpyp1") tests require old version of ghc - hunit ( 0.9 ) (inputs `(("ghc-base16-bytestring" ,ghc-base16-bytestring))) (native-inputs `(("ghc-sha" ,ghc-sha) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-hunit" ,ghc-hunit))) (home-page "-sha1") (synopsis "SHA-256 implementation for Haskell") (description "This Haskell package provides an incremental and one-pass, pure API to the @uref{-2, SHA-256 cryptographic hash algorithm}, with performance close to the fastest implementations available in other languages. The implementation is made in C with a haskell FFI wrapper that hides the C implementation.") (license license:bsd-3))) (define-public ghc-cryptonite (package (name "ghc-cryptonite") (version "0.25") (source (origin (method url-fetch) (uri (string-append "/" "cryptonite/cryptonite-" version ".tar.gz")) (sha256 (base32 "131wbbdr5yavs5k1ah9sz6fqx1ffyvaxf66pwjzsfc47mwc1mgl9")))) (build-system haskell-build-system) (arguments '(#:tests? #f)) (outputs '("out" "static" "doc")) (inputs `(("ghc-basement" ,ghc-basement) ("ghc-memory" ,ghc-memory) ("ghc-byteable" ,ghc-byteable))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-tasty-hunit" ,ghc-tasty-hunit) ("ghc-tasty-kat" ,ghc-tasty-kat))) (home-page "-crypto/cryptonite") (synopsis "Cryptography primitives") (description "This package is a repository of cryptographic primitives for Haskell. It supports a wide range of symmetric ciphers, cryptographic hash functions, public key algorithms, key derivation numbers, cryptographic random number generators, and more.") (license license:bsd-3))) (define-public ghc-digest (package (name "ghc-digest") (version "0.0.1.2") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "04gy2zp8yzvv7j9bdfvmfzcz3sqyqa6rwslqcn4vyair2vmif5v4")))) (build-system haskell-build-system) (arguments `(#:extra-directories ("zlib"))) (inputs `(("zlib" ,zlib))) (home-page "") (synopsis "Various cryptographic hashes for bytestrings") (description "This package provides efficient cryptographic hash implementations for are implemented as FFI bindings to efficient code from zlib.") (license license:bsd-3))) (define-public ghc-entropy (package (name "ghc-entropy") (version "0.4.1.5") (source (origin (method url-fetch) (uri (string-append "/" "entropy-" version "/" "entropy-" version ".tar.gz")) (sha256 (base32 "0szf8hi1pi8g0kxnkcymh65gk1b0niyl1nnkckzdqyar87qal0jm")))) (build-system haskell-build-system) (home-page "") (synopsis "Provides platform independent entropy source for Haskell") (description "This Haskell package provides a platform independent method to obtain cryptographically strong entropy.") (license license:bsd-3))) (define-public ghc-pem (package (name "ghc-pem") (version "0.2.4") (source (origin (method url-fetch) (uri (string-append "/" "pem/pem-" version ".tar.gz")) (sha256 (base32 "1m7qjsxrd8m88cvkqmr8kscril500j2a9y0iynvksjyjkhdlq33p")))) (build-system haskell-build-system) (inputs `(("ghc-basement" ,ghc-basement) ("ghc-memory" ,ghc-memory))) (native-inputs `(("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit) ("ghc-hunit" ,ghc-hunit) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-pem") (synopsis "Privacy Enhanced Mail (PEM) format reader and writer") (description "This library provides readers and writers for the @dfn{Privacy Enhanced Mail} (PEM) format.") (license license:bsd-3))) (define-public ghc-puremd5 (package (name "ghc-puremd5") (version "2.1.3") (source (origin (method url-fetch) (uri (string-append "/" "pureMD5-" version "/" "pureMD5-" version ".tar.gz")) (sha256 (base32 "0zdilz41cla2ck7mcw1a9702gyg2abq94mqahr4vci9sbs53bwxy")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-crypto-api" ,ghc-crypto-api) ("ghc-tagged" ,ghc-tagged))) (native-inputs `(("ghc-crypto-api-tests" ,ghc-crypto-api-tests) ("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-pretty-hex" ,ghc-pretty-hex))) (home-page "") (synopsis "Haskell implementation of the MD5 hash algorithm") (description "This package provides a Haskell-only implementation of the MD5 digest (hash) algorithm. This now supports the @code{crypto-api} class interface.") (license license:bsd-3))) (define-public ghc-sha (package (name "ghc-sha") (version "1.6.4.4") (source (origin (method url-fetch) (uri (string-append "/" "SHA/SHA-" version ".tar.gz")) (sha256 (base32 "0i4b2wjisivdy72synal711ywhx05mfqfba5n65rk8qidggm1nbb")))) (build-system haskell-build-system) (native-inputs `(("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2))) (home-page "") (synopsis "SHA suite of message digest functions") (description "This library implements the SHA suite of message digest functions, according to NIST FIPS 180-2 (with the SHA-224 addendum), as well as the SHA-based HMAC routines. The functions have been tested against most of the NIST and RFC test vectors for the various functions. While some attention has been paid to performance, these do not presently reach the speed of well-tuned libraries, like OpenSSL.") (license license:bsd-3))) (define-public ghc-x509 (package (name "ghc-x509") (version "1.7.5") (source (origin (method url-fetch) (uri (string-append "/" "x509/x509-" version ".tar.gz")) (sha256 (base32 "1j67c35g8334jx7x32hh6awhr43dplp0qwal5gnlkmx09axzrc5i")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-hourglass" ,ghc-hourglass) ("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-asn1-parse" ,ghc-asn1-parse) ("ghc-cryptonite" ,ghc-cryptonite))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (home-page "-certificate") (synopsis "X509 reader and writer") (description "This library provides functions to read and write X509 certificates.") (license license:bsd-3))) (define-public ghc-x509-store (package (name "ghc-x509-store") (version "1.6.7") (source (origin (method url-fetch) (uri (string-append "/" "x509-store/x509-store-" version ".tar.gz")) (sha256 (base32 "1y8yyr1i95jkllg8k0z54k5v4vachp848clc07m33xpxidn3b1lp")))) (build-system haskell-build-system) (inputs `(("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-x509" ,ghc-x509))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-certificate") (synopsis "X.509 collection accessing and storing methods") (description "This package provides functions for accessing and storing X.509 collections, certificates, revocation lists, and exception lists.") (license license:bsd-3))) (define-public ghc-x509-validation (package (name "ghc-x509-validation") (version "1.6.11") (source (origin (method url-fetch) (uri (string-append "/" "x509-validation/x509-validation-" version ".tar.gz")) (sha256 (base32 "16yihzljql3z8w5rgdl95fv3hgk7yd86kbl9b3glllsark5j2hzr")))) (build-system haskell-build-system) (inputs `(("ghc-memory" ,ghc-memory) ("ghc-byteable" ,ghc-byteable) ("ghc-hourglass" ,ghc-hourglass) ("ghc-data-default-class" ,ghc-data-default-class) ("ghc-pem" ,ghc-pem) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store) ("ghc-cryptonite" ,ghc-cryptonite))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit))) (home-page "-certificate") (synopsis "X.509 certificate and revocation list validation") (description "This package provides functions for X.509 certificate and revocation list validation.") (license license:bsd-3))) (define-public ghc-x509-system (package (name "ghc-x509-system") (version "1.6.6") (source (origin (method url-fetch) (uri (string-append "/" "x509-system/x509-system-" version ".tar.gz")) (sha256 (base32 "06a4m9c7vlr9nhp9gmqbb46arf0yj1dkdm4nip03hzy67spdmp20")))) (build-system haskell-build-system) (inputs `(("ghc-pem" ,ghc-pem) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store))) (home-page "-certificate") (synopsis "Handle system X.509 accessors and storage") (description "This package provides a library to handle system accessors and storage for X.509 certificates.") (license license:bsd-3))) (define-public ghc-crypto-cipher-types (package (name "ghc-crypto-cipher-types") (version "0.0.9") (source (origin (method url-fetch) (uri (string-append "/" "crypto-cipher-types-" version "/" "crypto-cipher-types-" version ".tar.gz")) (sha256 (base32 "03qa1i1kj07pfrxsi7fiaqnnd0vi94jd4jfswbmnm4gp1nvzcwr0")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-securemem" ,ghc-securemem))) (home-page "-crypto-cipher") (synopsis "Generic cryptography cipher types for Haskell") (description "This Haskell package provides basic typeclasses and types for symmetric ciphers.") (license license:bsd-3))) (define-public ghc-cipher-aes (package (name "ghc-cipher-aes") (version "0.2.11") (source (origin (method url-fetch) (uri (string-append "/" "cipher-aes-" version "/" "cipher-aes-" version ".tar.gz")) (sha256 (base32 "05ahz6kjq0fl1w66gpiqy0vndli5yx1pbsbw9ni3viwqas4p3cfk")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-securemem" ,ghc-securemem) ("ghc-crypto-cipher-types" ,ghc-crypto-cipher-types))) (native-inputs `(("ghc-quickcheck" ,ghc-quickcheck) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-quickcheck2" ,ghc-test-framework-quickcheck2) ("ghc-crypto-cipher-tests" ,ghc-crypto-cipher-tests))) (home-page "-cipher-aes") (synopsis "AES cipher implementation with advanced mode of operations for Haskell") (description "This Haskell package provides AES cipher implementation. The modes of operations available are ECB (Electronic code book), CBC (Cipher block chaining), CTR (Counter), XTS (XEX with ciphertext stealing), GCM (Galois Counter Mode). The AES implementation uses AES-NI when available (on x86 and x86-64 architecture), but fallback gracefully to a software C implementation. The software implementation uses S-Boxes, which might suffer for cache timing issues. However do notes that most other known software implementations, including very popular one (openssl, gnutls) also uses similar implementation. If it matters for your case, you should make sure you have AES-NI available, or you'll need to use a different implementation.") (license license:bsd-3))) (define-public ghc-crypto-random (package (name "ghc-crypto-random") (version "0.0.9") (source (origin (method url-fetch) (uri (string-append "/" "crypto-random-" version "/" "crypto-random-" version ".tar.gz")) (sha256 (base32 "0139kbbb2h7vshf68y3fvjda29lhj7jjwl4vq78w4y8k8hc7l2hp")))) (build-system haskell-build-system) (inputs `(("ghc-securemem" ,ghc-securemem) ("ghc-vector" ,ghc-vector))) (home-page "-crypto-random") (synopsis "Simple cryptographic random related types for Haskell") (description "Simple cryptographic random related types: a safe abstraction for CPRNGs.") (license license:bsd-3))) (define-public ghc-cprng-aes (package (name "ghc-cprng-aes") (version "0.6.1") (source (origin (method url-fetch) (uri (string-append "/" "cprng-aes-" version "/" "cprng-aes-" version ".tar.gz")) (sha256 (base32 "1wr15kbmk1g3l8a75n0iwbzqg24ixv78slwzwb2q6rlcvq0jlnb4")))) (build-system haskell-build-system) (inputs `(("ghc-byteable" ,ghc-byteable) ("ghc-crypto-random" ,ghc-crypto-random) ("ghc-cipher-aes" ,ghc-cipher-aes))) (home-page "-cprng-aes") (synopsis "Crypto Pseudo Random Number Generator using AES in counter mode in Haskell") (description "Simple crypto pseudo-random-number-generator with really good randomness property. Using ent, a randomness property maker on one 1Mb sample: @itemize @item Entropy = 7.999837 bits per byte. @item Optimum compression would reduce the size of this 1048576 byte file by 0 percent. @item Chi square distribution for 1048576 samples is 237.02. @item Arithmbetic mean value of data bytes is 127.3422 (127.5 = random). @item Monte Carlo value for Pi is 3.143589568 (error 0.06 percent). @end itemize Compared to urandom with the same sampling: @itemize @item Entropy = 7.999831 bits per byte. @item Optimum compression would reduce the size of this 1048576 byte file by 0 percent. @item Chi square distribution for 1048576 samples is 246.63. @item Arithmetic mean value of data bytes is 127.6347 (127.5 = random). @item Monte Carlo value for Pi is 3.132465868 (error 0.29 percent). @end itemize") (license license:bsd-3))) (define-public ghc-ed25519 (package (name "ghc-ed25519") (version "0.0.5.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0v8msqvgzimhs7p5ri25hrb1ni2wvisl5rmdxy89fc59py79b9fq")))) (build-system haskell-build-system) (arguments `(#:cabal-revision ("2" "1cq6h3jqkb1kvd9fjfhsllg5gq78sdiyf2gy9862xhlbv6wil19f") #:configure-flags '("--flags=-test-hlint -test-doctests -test-properties"))) (home-page "-ed25519") (synopsis "Ed25519 cryptographic signatures") (description "This package provides a simple, fast, self-contained copy of the Ed25519 public-key signature system with a clean interface. It also includes support for detached signatures, and thorough documentation on the design and implementation, including usage guidelines.") (license license:expat))) (define-public ghc-tls (package (name "ghc-tls") (version "1.4.1") (source (origin (method url-fetch) (uri (string-append "/" "tls/tls-" version ".tar.gz")) (sha256 (base32 "1y083724mym28n6xfaz7pcc7zqxdhjpaxpbvzxfbs25qq2px3smv")))) (build-system haskell-build-system) (inputs `(("ghc-cereal" ,ghc-cereal) ("ghc-data-default-class" ,ghc-data-default-class) ("ghc-memory" ,ghc-memory) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-asn1-types" ,ghc-asn1-types) ("ghc-asn1-encoding" ,ghc-asn1-encoding) ("ghc-x509" ,ghc-x509) ("ghc-x509-store" ,ghc-x509-store) ("ghc-x509-validation" ,ghc-x509-validation) ("ghc-async" ,ghc-async) ("ghc-network" ,ghc-network) ("ghc-hourglass" ,ghc-hourglass))) (native-inputs `(("ghc-tasty" ,ghc-tasty) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck) ("ghc-quickcheck" ,ghc-quickcheck))) (home-page "-tls") (synopsis "TLS/SSL protocol native implementation (Server and Client)") (description "Native Haskell TLS and SSL protocol implementation for server and client. This provides a high-level implementation of a sensitive security protocol, eliminating a common set of security issues through the use of the advanced type system, high level constructions and common Haskell features. Currently implement the SSL3.0, TLS1.0, TLS1.1 and TLS1.2 protocol, and support RSA and Ephemeral (Elliptic curve and regular) Diffie Hellman key exchanges, and many extensions.") (license license:bsd-3))) (define-public ghc-hsopenssl (package (name "ghc-hsopenssl") (version "0.11.4.17") (source (origin (method url-fetch) (uri (string-append "/" "HsOpenSSL/HsOpenSSL-" version ".tar.gz")) (sha256 (base32 "0qivl9clmybfglwxqp2sq308rv4ia4rhwshcsc8b029bvpp0mpsi")))) (build-system haskell-build-system) (arguments `(#:extra-directories ("openssl"))) (inputs `(("ghc-network" ,ghc-network) ("openssl" ,openssl))) (home-page "") (synopsis "Partial OpenSSL binding for Haskell") (description "HsOpenSSL is an OpenSSL binding for Haskell. It can generate RSA and DSA keys, read and write PEM files, generate message digests, sign and verify messages, encrypt and decrypt messages. It has also some capabilities of creating SSL clients and servers. This package is in production use by a number of Haskell based systems and stable. You may also be interested in the tls package, @uref{}, which is a pure Haskell implementation of SSL.") (license license:public-domain))) (define-public ghc-openssl-streams (package (name "ghc-openssl-streams") (version "1.2.2.0") (source (origin (method url-fetch) (uri (string-append "/" "openssl-streams/openssl-streams-" version ".tar.gz")) (sha256 (base32 "0rplym6ayydkpr7x9mw3l13p0vzzfzzxw244d7sd3jcvaxpv0rmr")))) (build-system haskell-build-system) (inputs `(("ghc-hsopenssl" ,ghc-hsopenssl) ("ghc-io-streams" ,ghc-io-streams) ("ghc-network" ,ghc-network))) (native-inputs `(("ghc-hunit" ,ghc-hunit) ("ghc-test-framework" ,ghc-test-framework) ("ghc-test-framework-hunit" ,ghc-test-framework-hunit))) (home-page "-streams") (synopsis "OpenSSL network support for io-streams") (description "This library contains io-streams routines for secure networking using OpenSSL (by way of HsOpenSSL).") (license license:bsd-3))) (define-public ghc-cryptonite-conduit (package (name "ghc-cryptonite-conduit") (version "0.2.2") (source (origin (method url-fetch) (uri (string-append "/" "cryptonite-conduit/cryptonite-conduit-" version ".tar.gz")) (sha256 (base32 "1bldcmda4xh52mw1wfrjljv8crhw3al7v7kv1j0vidvr7ymnjpbh")))) (build-system haskell-build-system) (inputs `(("ghc-conduit" ,ghc-conduit) ("ghc-conduit-extra" ,ghc-conduit-extra) ("ghc-cryptonite" ,ghc-cryptonite) ("ghc-exceptions" ,ghc-exceptions) ("ghc-memory" ,ghc-memory) ("ghc-resourcet" ,ghc-resourcet))) (native-inputs `(("ghc-conduit-combinators" ,ghc-conduit-combinators) ("ghc-tasty" ,ghc-tasty) ("ghc-tasty-hunit" ,ghc-tasty-hunit) ("ghc-tasty-quickcheck" ,ghc-tasty-quickcheck))) (arguments `(#:cabal-revision ("1" "1hh2nzfz4qpxgivfilgk4ll416lph8b2fdkzpzrmqfjglivydfmz"))) (home-page "-crypto/cryptonite-conduit") (synopsis "Cryptonite bridge for conduit") (description "This package provides conduit interfaces for some of cryptonite's implementations of cryptographic primitives.") (license license:bsd-3)))
dc995401bca7025e8eeead5b4ceb709debff2471dd2443bdfab2451cac1744a0
marianoguerra/jwt-erl
jwt_SUITE.erl
-module(jwt_SUITE). -compile(export_all). -include("jwt.hrl"). all() -> [encode_decode, decode_with_bad_secret, decode_empty_token, decode_bad_token, decode_bad_token_3_parts, decode_bad_sig, decode_expired]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. check_encode_decode(Algorithm) -> {ok, Jwt} = jwt:encode(Algorithm, [{name, <<"bob">>}, {age, 29}], <<"secret">>), {ok, Decoded} = jwt:decode(Jwt, <<"secret">>), Body = jsx:decode(Decoded#jwt.body, [{return_maps, true}]), Name = maps:get(<<"name">>, Body, undefined), Age = maps:get(<<"age">>, Body, undefined), <<"JWT">> = Decoded#jwt.typ, Algorithm = Decoded#jwt.alg, 29 = Age, <<"bob">> = Name. encode_decode(_) -> check_encode_decode(hs256), check_encode_decode(hs384), check_encode_decode(hs512). decode_with_bad_secret(_) -> {ok, Jwt} = jwt:encode(hs256, [{name, <<"bob">>}, {age, 29}], <<"secret">>), {error, {badsig, _Decoded}} = jwt:decode(Jwt, <<"notsecret">>). decode_bad_sig(_) -> Encoded = <<"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." "eyJ1IjoiYWRtaW4ifQ." "KS4+DGuMMuJTcsDApSmmB11TR+O1FkeUu8ByL2qVUlk">>, Signature = <<41,46,62,12,107,140,50,226,83,114,192,192,165,41, 166,7,93,83,71,227,181,22,71,148,187,192,114,47, 106,149,82,89>>, ActualSignature = <<210,21,116,4,249,201,17,92,117,190,215,176, 22,187,0,69,214,249,100,119,220,25,108,132, 138,80,4,37,248,30,15,80>>, {error, {badsig, #jwt{typ = <<"JWT">>, body = <<"{\"u\":\"admin\"}">>, alg = hs256, sig = Signature, actual_sig = ActualSignature}}} = jwt:decode(Encoded, <<"changeme">>). decode_empty_token(_) -> {error, badtoken} = jwt:decode(<<"">>, <<"secret">>). decode_bad_token(_) -> {error, badtoken} = jwt:decode(<<"asd">>, <<"secret">>). decode_bad_token_3_parts(_) -> {error, badarg} = jwt:decode(<<"asd.dsa.lala">>, <<"secret">>), {error, function_clause} = jwt:decode(<<"a.b.c">>, <<"secret">>). decode_expired(_) -> Expiration = jwt:now_secs() - 10, {ok, Jwt} = jwt:encode(hs256, [{name, <<"bob">>}, {age, 29}], <<"secret">>, [{exp, Expiration}]), {error, {expired, Expiration}} = jwt:decode(Jwt, <<"secret">>).
null
https://raw.githubusercontent.com/marianoguerra/jwt-erl/a9cd8af4d3318bcb79de523d4e95d5f1ff414542/test/jwt_SUITE.erl
erlang
-module(jwt_SUITE). -compile(export_all). -include("jwt.hrl"). all() -> [encode_decode, decode_with_bad_secret, decode_empty_token, decode_bad_token, decode_bad_token_3_parts, decode_bad_sig, decode_expired]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. check_encode_decode(Algorithm) -> {ok, Jwt} = jwt:encode(Algorithm, [{name, <<"bob">>}, {age, 29}], <<"secret">>), {ok, Decoded} = jwt:decode(Jwt, <<"secret">>), Body = jsx:decode(Decoded#jwt.body, [{return_maps, true}]), Name = maps:get(<<"name">>, Body, undefined), Age = maps:get(<<"age">>, Body, undefined), <<"JWT">> = Decoded#jwt.typ, Algorithm = Decoded#jwt.alg, 29 = Age, <<"bob">> = Name. encode_decode(_) -> check_encode_decode(hs256), check_encode_decode(hs384), check_encode_decode(hs512). decode_with_bad_secret(_) -> {ok, Jwt} = jwt:encode(hs256, [{name, <<"bob">>}, {age, 29}], <<"secret">>), {error, {badsig, _Decoded}} = jwt:decode(Jwt, <<"notsecret">>). decode_bad_sig(_) -> Encoded = <<"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." "eyJ1IjoiYWRtaW4ifQ." "KS4+DGuMMuJTcsDApSmmB11TR+O1FkeUu8ByL2qVUlk">>, Signature = <<41,46,62,12,107,140,50,226,83,114,192,192,165,41, 166,7,93,83,71,227,181,22,71,148,187,192,114,47, 106,149,82,89>>, ActualSignature = <<210,21,116,4,249,201,17,92,117,190,215,176, 22,187,0,69,214,249,100,119,220,25,108,132, 138,80,4,37,248,30,15,80>>, {error, {badsig, #jwt{typ = <<"JWT">>, body = <<"{\"u\":\"admin\"}">>, alg = hs256, sig = Signature, actual_sig = ActualSignature}}} = jwt:decode(Encoded, <<"changeme">>). decode_empty_token(_) -> {error, badtoken} = jwt:decode(<<"">>, <<"secret">>). decode_bad_token(_) -> {error, badtoken} = jwt:decode(<<"asd">>, <<"secret">>). decode_bad_token_3_parts(_) -> {error, badarg} = jwt:decode(<<"asd.dsa.lala">>, <<"secret">>), {error, function_clause} = jwt:decode(<<"a.b.c">>, <<"secret">>). decode_expired(_) -> Expiration = jwt:now_secs() - 10, {ok, Jwt} = jwt:encode(hs256, [{name, <<"bob">>}, {age, 29}], <<"secret">>, [{exp, Expiration}]), {error, {expired, Expiration}} = jwt:decode(Jwt, <<"secret">>).
b3c870bf43511369f905486fcf46e5a2123aeca0062ef0eca4c5250d49ade4da
bugczw/Introduction-to-Functional-Programming-in-OCaml
functions.ml
let f x = x+1;; (* global definition *) f 17;; let g y = 2*y (* local definition *) in g 42;; f f 1;; (f f) 1;; f (f 1);;
null
https://raw.githubusercontent.com/bugczw/Introduction-to-Functional-Programming-in-OCaml/13c4d1f92e7479f8eb10ea5d4c43a598b6676d0f/OCaml_MOOC_W1_ALL/functions.ml
ocaml
global definition local definition
f 17;; in g 42;; f f 1;; (f f) 1;; f (f 1);;
e2fc1f7df9665156a7f754477e4acfac95117ef95fdc798534f8354687ec7ba7
openmusic-project/openmusic
traject-editor.lisp
;========================================================================= OpenMusic : Visual Programming Language for Music Composition ; Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France . ; This file is part of the OpenMusic environment sources ; OpenMusic 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. ; OpenMusic 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 OpenMusic . If not , see < / > . ; ;=========================================================================== (in-package :om) (defparameter *OM-TRAJ-COLOR-MODE* 0) (defparameter *OM-TRAJ-COLOR-MIN* (list 0.4 0.8 1.0)) (defparameter *OM-TRAJ-COLOR-MAX* (list 0.0 0.9 1.0)) ;;; 3D timed Curve (defclass 3D-timed-curve (3D-curve) ((times :accessor times :initarg :times :initform nil) (color-mode :accessor color-mode :initarg :color-mode) (color-min :accessor color-min :initarg :color-min :initform *OM-TRAJ-COLOR-MIN*) (color-max :accessor color-max :initarg :color-max :initform *OM-TRAJ-COLOR-MAX*)) ) (defmethod get-vertices-colors ((self 3d-timed-curve)) "create a vector of colors for a 3D-timed-curve depending on the mode selected" (let* ((points (om-3dobj-points self)) (size (length points)) (cmi (or (color-min self) '(0 0 0))) (cma (or (color-max self) '(1.0 1.0 1.0))) (min_h (max 0 (nth 0 cmi))) (min_s (max 0 (nth 1 cmi))) (min_v (max 0 (nth 2 cmi))) (max_h (min 1.0 (nth 0 cma))) (max_s (min 1.0 (nth 1 cma))) (max_v (min 1.0 (nth 2 cma))) (range_h (- max_h min_h)) (range_s (- max_s min_s)) (range_v (- max_v min_v))) (case (color-mode self) (1 (loop for i from 0 to (1- size) collect (hsv2rgb (list (+ min_h (* (/ range_h size) i)) (+ min_s (* (/ range_s size) i)) (+ min_v (* (/ range_v size) i)))) ) ) (2 (let ((speeds nil) (times (times self))) (setf speeds (loop for i from 0 to (1- (1- size)) collect (let ((dist (3d-points-distance (nth i points) (nth (1+ i) points))) (time (- (or (nth (1+ i) times) 0) (or (nth i times) 0)))) ;; added (OR 0) in case a point is added and has no time... (if (= time 0) -1 (/ dist time))))) (setf speeds (append (last speeds) speeds)) (setf speeds (filter-and-normalize-speeds-list speeds)) (loop for speed in speeds collect (hsv2rgb (list (+ min_h (* range_h speed)) (+ min_s (* range_s speed)) (+ min_v (* range_v speed)))) ) ) ) (otherwise (default-color-vertices self))))) (defun filter-and-normalize-speeds-list (speeds) (let ((max_speed (reduce 'max speeds)) (min_speed nil) (range_speed nil)) ;removing -1 and replacing by max speed (loop for speed in speeds collect (if (= speed -1) max_speed speed)) (setf min_speed (reduce 'min speeds)) (setf range_speed (- max_speed min_speed)) (setf speeds (om/ (om- speeds min_speed) range_speed)))) (defun 3D-points-distance (p1 p2) (let ((x1 (nth 0 p1)) (x2 (nth 0 p2)) (y1 (nth 1 p1)) (y2 (nth 1 p2)) (z1 (nth 2 p1)) (z2 (nth 2 p2))) (sqrt (+ (+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))) (* (- z1 z2) (- z1 z2)))) )) (defun rgb2hsv (col) "convert RGB values into HSV values (list in float format (0.0 to 1.0))" (let* ( ;be sure we have a correct range for input (r (min (nth 0 col) 1.0)) (r (max r 0.0)) (g (min (nth 1 col) 1.0)) (g (max g 0.0)) (b (min (nth 2 col) 1.0)) (b (max b 0.0)) (min_rgb (min r g b)) (max_rgb (max r g b)) ) (if (= min_rgb max_rgb) (list 0.0 0.0 min_rgb) (progn (let* ( (tmp_d (if (= r min_rgb) (- g b) ( if (= b min_rgb) (- r g) (- b r)))) (tmp_h (if (= r min_rgb) 3 (if (= b min_rgb) 1 5))) (h (/ (* 60 (- tmp_h (/ tmp_d (- max_rgb min_rgb)))) 360)) (v max_rgb) (s (/ (- max_rgb min_rgb) max_rgb))) (list h s v)))))) (defun hsv2rgb (col) "convert HSV values into RGB values (list in float format (0.0 to 1.0))" (let* ( (h (min 1.0 (nth 0 col))) (s (min 1.0 (nth 1 col))) (v (min 1.0 (nth 2 col))) (i (floor (* h 6))) (f (- (* h 6) i)) (p (* v (- 1 s))) (q (* v (- 1 (* f s)))) (tt (* v (- 1 (* (- 1 f) s))))) (case (mod i 6) (0 (list v tt p)) (1 (list q v p)) (2 (list p v tt)) (3 (list p q v)) (4 (list tt p v)) (5 (list v p q))))) ;;; EDITOR (defclass traject-editor (3DEditor) ((color-mode-buttons :accessor color-mode-buttons :initarg :color-mode-buttons :initform nil) (interpol-show-p :accessor interpol-show-p :initarg :interpol-show-p :initform nil))) (defmethod default-edition-params ((self 3D-trajectory)) (append (call-next-method) (pairlis '(color-mode color-min color-max) (list *OM-TRAJ-COLOR-MODE* *OM-TRAJ-COLOR-MIN* *om-traj-color-max*)))) ;parameters stored with the editor (defmethod param-color-mode ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val (set-edit-param self 'color-mode set-val) (get-edit-param self 'color-mode))) (defmethod param-color-min ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val-supplied-p (set-edit-param self 'color-min set-val) (get-edit-param self 'color-min))) (defmethod param-color-max ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val (set-edit-param self 'color-max set-val) (get-edit-param self 'color-max))) (defmethod get-editor-class ((self 3D-trajectory)) 'traject-editor) (defmethod gl-3DC-from-obj ((self traject-editor)) (let* ((obj (if (and (multibpf? self) (not (show-back-p self))) (get-current-object self) (object self)))) (let ((newobj (gen-3D-timed-obj obj (lines-p self) (param-line-width self) (param-color-mode self) (param-color-min self) (param-color-max self)))) newobj))) (defmethod gen-3D-timed-obj ((obj 3D-trajectory) mode line-width color-mode color-min color-max) (let ((glpoints (format-3d-points obj))) (3D-timed-obj-from-points glpoints mode (bpfcolor obj) line-width (times obj) color-mode color-min color-max))) (defun 3D-timed-obj-from-points (points drawmode color line-width times color-mode color-min color-max) (let ((clist (when color (list (float (om-color-r color)) (float (om-color-g color)) (float (om-color-b color)))))) (make-instance '3D-timed-curve :points points :color clist :lines drawmode :line-width line-width :times times :color-mode color-mode :color-min color-min :color-max color-max))) (defmethod initialize-instance :after ((self traject-editor) &rest l) (declare (ignore l)) ;pour compatibilité ;(unless (param-color-mode self) ( param - color - mode self * OM - TRAJ - COLOR - MODE * ) ) (when (= 2 (param-color-mode self)) (when (member nil (times (object self))) (param-color-mode self *OM-TRAJ-COLOR-MODE*))) ;(unless (param-color-min self) ( param - color - min self * OM - TRAJ - COLOR - MIN * ) ) ;(unless (param-color-max self) ( param - color - max self * OM - TRAJ - COLOR - MAX * ) ) (om-add-subviews (ctrlp self) ; (om-make-dialog-item 'om-check-box (om-make-point 5 510) (om-make-point 100 60) ; "Show interpolated curve" ; :font *controls-font* ; :checked-p (interpol-show-p self) ; :fg-color *om-black-color* ; :di-action (om-dialog-item-act item ( setf ( interpol - show - p self ) ( om - checked - p item ) ) ( om - set - gl - object ( 3Dp self ) ( gl-3DC - from - obj self ) ) ( om - invalidate - view ( 3Dp self ) ) ; ) ; ) (om-make-dialog-item 'om-static-text (om-make-point 8 550) (om-make-point 70 40) "Sample Rate" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'om-editable-text (om-make-point 70 555) (om-make-point 40 20) (format nil " ~a" (sample-params (object self))) :-action nil :font *controls-font* :bg-color *om-white-color* :modify-action #'(lambda (item) (let ((val (ignore-errors (read-from-string (om-dialog-item-text item))))) (when (or (numberp val) (null val) (and (listp val) (list-subtypep val 'number))) (setf (sample-params (object self)) val)))) ) (om-make-dialog-item 'om-pop-up-dialog-item (om-make-point 8 600) (om-make-point 100 20) "" :range '("points (constant time)" "distance (constant speed)") :value (if (equal (interpol-mode (object self)) 'dist) "distance (constant speed)" "points (constant time)") :di-action (om-dialog-item-act item (setf (interpol-mode (object self)) (if (= (om-get-selected-item-index item) 1) 'dist 'points)))) ) (update-color-mode-buttons self)) (defmethod add-curve-edit-buttons ((self traject-editor) panel) (setf (curve-buttons panel) (list (om-make-dialog-item 'om-static-text (om-make-point 5 230) (om-make-point 70 20) "Line width" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'edit-numbox (om-make-point 80 230) (om-make-point 30 20) (format nil " ~D" (param-line-width self)) :font *controls-font* :bg-color *om-white-color* :value (param-line-width self) :min-val 1.0 :max-val 6.0 :di-action #'(lambda (item) (param-line-width self (value item)) (update-3D-view self) (om-invalidate-view (3Dp self))) ) (om-make-dialog-item 'om-static-text (om-make-point 5 260) (om-make-point 70 20) "Color Mode" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'om-pop-up-dialog-item (om-make-point 8 280) (om-make-point 100 20) "" :range '("Simple" "Path" "Speed") :value (case (param-color-mode self) ((equal 0) "Simple") ((equal 1) "Path") ((equal 2) "Speed")) :di-action (om-dialog-item-act item (let ((test nil)) (when (= 2 (om-get-selected-item-index item)) (when (member nil (times (object self))) (setf test t) (om-set-selected-item-index item (param-color-mode self)) (om-message-dialog "Not valid curve (Missing times)") (update-3D-view self) (om-invalidate-view (3Dp self))) ) (unless test (param-color-mode self (om-get-selected-item-index item)) (update-color-mode-buttons self) (update-3D-view self) (om-invalidate-view (3Dp self))))) ) )) (apply 'om-add-subviews (cons panel (curve-buttons panel))) ) (defmethod remove-curve-edit-buttons ((self traject-editor) panel) (apply 'om-remove-subviews (cons panel (curve-buttons panel))) (when (color-mode-buttons self) (apply 'om-remove-subviews (cons panel (color-mode-buttons self))))) (defmethod update-color-mode-buttons ((self traject-editor)) (when (color-mode-buttons self) (apply 'om-remove-subviews (cons (ctrlp self) (color-mode-buttons self)))) (let ((mode (param-color-mode self)) (_x 5) (_y 310)) (setf (color-mode-buttons self) (case mode ((= 0) (list (om-make-dialog-item 'om-static-text (om-make-point _x _y) (om-make-point 70 40) "Curve color" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 75) (+ _y 2)) :size (om-make-point 25 18) :color (bpfcolor (get-current-object self)) :after-fun #'(lambda (item) (setf (bpfcolor (get-current-object self)) (color item)) (update-3D-view self) (om-invalidate-view (3Dp self))) ))) (otherwise (list (om-make-dialog-item 'om-static-text (om-make-point _x _y) (om-make-point 70 40) "Min" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 25) (+ _y 2)) :size (om-make-point 25 18) :color (let ((rgb (hsv2rgb (param-color-min self)))) (om-make-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb))) :after-fun #'(lambda (item) (param-color-min self (rgb2hsv (list (om-color-r (color item)) (om-color-g (color item)) (om-color-b (color item))))) (update-3D-view self) (om-invalidate-view (3Dp self))) ) (om-make-dialog-item 'om-static-text (om-make-point (+ _x 55) _y) (om-make-point 70 40) "Max" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 85) (+ _y 2)) :size (om-make-point 25 18) :color (let ((rgb (hsv2rgb (param-color-max self)))) (om-make-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb))) :after-fun #'(lambda (item) (param-color-max self (rgb2hsv (list (om-color-r (color item)) (om-color-g (color item)) (om-color-b (color item))))) (update-3D-view self) (om-invalidate-view (3Dp self))) ))) ))) (apply 'om-add-subviews (cons (ctrlp self) (color-mode-buttons self))) ) (defmethod get-help-list ((self 3DEditor)) (remove nil (list '((#+cocoa "cmd+clic" #-cocoa "ctrl+clic" "Add point / Draw") ("lrud" "Move selected points") ("del" "Delete selected points") (("c") "Change curve color") (("b") "Change 3D background color") (("p") "Show point indices") (("t") "Show point times") ) (when (multibpf? self) '(("tab" "Change current curve") (("n") "Change curve name") ))))) ;;; 2D EDITORS (defmethod special-move-point ((self bpcPanel) (point timedpoint) i) (let* ((dec (decimals (get-bpf-obj self))) (xsize (max 50 (* 10 dec))) (mydialog (om-make-window 'om-dialog :size (om-make-point (max 180 (+ 100 (* 12 dec))) 120) :window-title "" :position (om-add-points (om-view-position (window self)) (om-mouse-position self)))) (xed (om-make-dialog-item 'om-editable-text (om-make-point 30 5) (om-make-point xsize 10) (if (zerop dec) (format () "~D" (om-point-h point)) (format () (format nil "~S,~DF" '~ dec) (/ (om-point-h point) (expt 10.0 dec)))) )) (yed (om-make-dialog-item 'om-editable-text (om-make-point 30 35) (om-make-point xsize 10) (if (zerop dec) (format () "~D" (om-point-v point)) (format () (format nil "~S,~DF" '~ dec) (/ (om-point-v point) (expt 10.0 dec)))) )) (time-ed (om-make-dialog-item 'om-editable-text (om-make-point 30 65) (om-make-point xsize 10) (format () "~D" (timedpoint-time point)) )) ) (om-add-subviews mydialog (om-make-dialog-item 'om-static-text (om-make-point 5 5) (om-make-point 20 20) (x-label self) :font *om-default-font3b* :bg-color *om-window-def-color*) (om-make-dialog-item 'om-static-text (om-make-point 5 35) (om-make-point 20 20) (y-label self) :font *om-default-font3b* :bg-color *om-window-def-color*) (om-make-dialog-item 'om-static-text (om-make-point 5 65) (om-make-point 20 20) "time" :font *om-default-font3b* :bg-color *om-window-def-color*) xed yed time-ed (om-make-dialog-item 'om-button (om-make-point (- (w mydialog) 80) 5) (om-make-point 70 20) "Cancel" :di-action (om-dialog-item-act item (declare (ignore item)) (om-return-from-modal-dialog mydialog ())) :default-button nil) (om-make-dialog-item 'om-button (om-make-point (- (w mydialog) 80) 36) (om-make-point 70 20) "OK" :di-action (om-dialog-item-act item (declare (ignore item)) (let ((tvalue (ignore-errors (read-from-string (om-dialog-item-text time-ed))))) (if (move-timedpoints-in-bpf (currentbpf self) (list (list point i)) (- (round (* (read-from-string (om-dialog-item-text xed)) (expt 10.0 dec))) (om-point-h point)) (- (round (* (read-from-string (om-dialog-item-text yed)) (expt 10.0 dec))) (om-point-v point)) (if (numberp tvalue) tvalue nil)) (do-after-move self) (om-beep-msg "Ilegal move")) (om-return-from-modal-dialog mydialog ()))) :default-button t)) (om-modal-dialog mydialog))) (defmethod move-timedpoints-in-bpf ((self bpc) points deltax deltay time) (let ((legalmove t)) (loop for point in points do (let* ((pos (second point)) (tmin (or (list-max (remove nil (mapcar 'get-point-time (subseq (point-list self) 0 pos)))) 0.0)) (tmax (list-min (remove nil (mapcar 'get-point-time (subseq (point-list self) (1+ pos))))))) (if (or (null time) (and (or (equal pos 0) (> time tmin)) (or (null tmax) (< time tmax)))) (setf (nth pos (point-list self)) (make-timedpoint :point (om-make-point (+ (om-point-h (car point)) deltax) (+ (om-point-v (car point)) deltay)) :time time)) (setf legalmove nil)))) legalmove)) (defmethod init-tmp-objs ((self traject-editor)) (call-next-method) (set-times-to-tmpobjs self)) (defmethod editor-change-precision ((self traject-editor) newvalue) (call-next-method) (set-times-to-tmpobjs self)) (defun set-times-to-tmpobjs (traject-editor) (let ((curr3dc (if (multibpf? traject-editor) (if (selected-component traject-editor) (nth (selected-component traject-editor) (bpf-list (object traject-editor))) (car (bpf-list (object traject-editor)))) (object traject-editor)))) (mapcar #'(lambda (tobj) (setf (point-list tobj) (loop for pt in (point-list tobj) for trpoint in (point-list curr3Dc) collect (make-timedpoint :point pt :time (timedpoint-time trpoint)))) ) (tmpview-objs traject-editor)) )) (defmethod report-bpfmodif ((self traject-editor) &key xpts ypts zpts times) (let ((3Dobj (if (multibpf? self) (nth (selected-component self) (bpf-list (object self))) (object self)))) (unless xpts (setf xpts (x-points 3Dobj))) (unless ypts (setf ypts (y-points 3Dobj))) (unless zpts (setf zpts (z-points 3Dobj))) (let ((new-bpf (traject-from-list xpts ypts zpts times (type-of 3Dobj) (decimals 3Dobj) (sample-params 3Dobj) (interpol-mode 3Dobj) ))) (cons-bpf 3Dobj (point-list new-bpf)) ( setf ( traject - points 3Dobj ) ( traject - points new - bpf ) ) ) (init-tmp-objs self) (update-editor-contents self))) (defmethod more-bpc-draw ((self internalbpcpanel) point pos index) (call-next-method) (when (and (show-time self) (get-point-time point)) (om-with-fg-color self *om-red2-color* (om-draw-string (+ (om-point-h pos) -6) (+ (om-point-v pos) 14) (format nil "~d" (get-point-time point))))))
null
https://raw.githubusercontent.com/openmusic-project/openmusic/0bd8613a844a382e5db7185be1b5a5d026d66b20/OPENMUSIC/code/projects/space/3D/traject-editor.lisp
lisp
========================================================================= (at your option) any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. =========================================================================== 3D timed Curve added (OR 0) in case a point is added and has no time... removing -1 and replacing by max speed be sure we have a correct range for input EDITOR parameters stored with the editor pour compatibilité (unless (param-color-mode self) (unless (param-color-min self) (unless (param-color-max self) (om-make-dialog-item 'om-check-box (om-make-point 5 510) (om-make-point 100 60) "Show interpolated curve" :font *controls-font* :checked-p (interpol-show-p self) :fg-color *om-black-color* :di-action (om-dialog-item-act item ) ) 2D EDITORS
OpenMusic : Visual Programming Language for Music Composition Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France . This file is part of the OpenMusic environment sources OpenMusic 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 OpenMusic is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with OpenMusic . If not , see < / > . (in-package :om) (defparameter *OM-TRAJ-COLOR-MODE* 0) (defparameter *OM-TRAJ-COLOR-MIN* (list 0.4 0.8 1.0)) (defparameter *OM-TRAJ-COLOR-MAX* (list 0.0 0.9 1.0)) (defclass 3D-timed-curve (3D-curve) ((times :accessor times :initarg :times :initform nil) (color-mode :accessor color-mode :initarg :color-mode) (color-min :accessor color-min :initarg :color-min :initform *OM-TRAJ-COLOR-MIN*) (color-max :accessor color-max :initarg :color-max :initform *OM-TRAJ-COLOR-MAX*)) ) (defmethod get-vertices-colors ((self 3d-timed-curve)) "create a vector of colors for a 3D-timed-curve depending on the mode selected" (let* ((points (om-3dobj-points self)) (size (length points)) (cmi (or (color-min self) '(0 0 0))) (cma (or (color-max self) '(1.0 1.0 1.0))) (min_h (max 0 (nth 0 cmi))) (min_s (max 0 (nth 1 cmi))) (min_v (max 0 (nth 2 cmi))) (max_h (min 1.0 (nth 0 cma))) (max_s (min 1.0 (nth 1 cma))) (max_v (min 1.0 (nth 2 cma))) (range_h (- max_h min_h)) (range_s (- max_s min_s)) (range_v (- max_v min_v))) (case (color-mode self) (1 (loop for i from 0 to (1- size) collect (hsv2rgb (list (+ min_h (* (/ range_h size) i)) (+ min_s (* (/ range_s size) i)) (+ min_v (* (/ range_v size) i)))) ) ) (2 (let ((speeds nil) (times (times self))) (setf speeds (loop for i from 0 to (1- (1- size)) collect (let ((dist (3d-points-distance (nth i points) (nth (1+ i) points))) (if (= time 0) -1 (/ dist time))))) (setf speeds (append (last speeds) speeds)) (setf speeds (filter-and-normalize-speeds-list speeds)) (loop for speed in speeds collect (hsv2rgb (list (+ min_h (* range_h speed)) (+ min_s (* range_s speed)) (+ min_v (* range_v speed)))) ) ) ) (otherwise (default-color-vertices self))))) (defun filter-and-normalize-speeds-list (speeds) (let ((max_speed (reduce 'max speeds)) (min_speed nil) (range_speed nil)) (loop for speed in speeds collect (if (= speed -1) max_speed speed)) (setf min_speed (reduce 'min speeds)) (setf range_speed (- max_speed min_speed)) (setf speeds (om/ (om- speeds min_speed) range_speed)))) (defun 3D-points-distance (p1 p2) (let ((x1 (nth 0 p1)) (x2 (nth 0 p2)) (y1 (nth 1 p1)) (y2 (nth 1 p2)) (z1 (nth 2 p1)) (z2 (nth 2 p2))) (sqrt (+ (+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))) (* (- z1 z2) (- z1 z2)))) )) (defun rgb2hsv (col) "convert RGB values into HSV values (list in float format (0.0 to 1.0))" (let* ( (r (min (nth 0 col) 1.0)) (r (max r 0.0)) (g (min (nth 1 col) 1.0)) (g (max g 0.0)) (b (min (nth 2 col) 1.0)) (b (max b 0.0)) (min_rgb (min r g b)) (max_rgb (max r g b)) ) (if (= min_rgb max_rgb) (list 0.0 0.0 min_rgb) (progn (let* ( (tmp_d (if (= r min_rgb) (- g b) ( if (= b min_rgb) (- r g) (- b r)))) (tmp_h (if (= r min_rgb) 3 (if (= b min_rgb) 1 5))) (h (/ (* 60 (- tmp_h (/ tmp_d (- max_rgb min_rgb)))) 360)) (v max_rgb) (s (/ (- max_rgb min_rgb) max_rgb))) (list h s v)))))) (defun hsv2rgb (col) "convert HSV values into RGB values (list in float format (0.0 to 1.0))" (let* ( (h (min 1.0 (nth 0 col))) (s (min 1.0 (nth 1 col))) (v (min 1.0 (nth 2 col))) (i (floor (* h 6))) (f (- (* h 6) i)) (p (* v (- 1 s))) (q (* v (- 1 (* f s)))) (tt (* v (- 1 (* (- 1 f) s))))) (case (mod i 6) (0 (list v tt p)) (1 (list q v p)) (2 (list p v tt)) (3 (list p q v)) (4 (list tt p v)) (5 (list v p q))))) (defclass traject-editor (3DEditor) ((color-mode-buttons :accessor color-mode-buttons :initarg :color-mode-buttons :initform nil) (interpol-show-p :accessor interpol-show-p :initarg :interpol-show-p :initform nil))) (defmethod default-edition-params ((self 3D-trajectory)) (append (call-next-method) (pairlis '(color-mode color-min color-max) (list *OM-TRAJ-COLOR-MODE* *OM-TRAJ-COLOR-MIN* *om-traj-color-max*)))) (defmethod param-color-mode ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val (set-edit-param self 'color-mode set-val) (get-edit-param self 'color-mode))) (defmethod param-color-min ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val-supplied-p (set-edit-param self 'color-min set-val) (get-edit-param self 'color-min))) (defmethod param-color-max ((self traject-editor) &optional (set-val nil set-val-supplied-p)) (if set-val (set-edit-param self 'color-max set-val) (get-edit-param self 'color-max))) (defmethod get-editor-class ((self 3D-trajectory)) 'traject-editor) (defmethod gl-3DC-from-obj ((self traject-editor)) (let* ((obj (if (and (multibpf? self) (not (show-back-p self))) (get-current-object self) (object self)))) (let ((newobj (gen-3D-timed-obj obj (lines-p self) (param-line-width self) (param-color-mode self) (param-color-min self) (param-color-max self)))) newobj))) (defmethod gen-3D-timed-obj ((obj 3D-trajectory) mode line-width color-mode color-min color-max) (let ((glpoints (format-3d-points obj))) (3D-timed-obj-from-points glpoints mode (bpfcolor obj) line-width (times obj) color-mode color-min color-max))) (defun 3D-timed-obj-from-points (points drawmode color line-width times color-mode color-min color-max) (let ((clist (when color (list (float (om-color-r color)) (float (om-color-g color)) (float (om-color-b color)))))) (make-instance '3D-timed-curve :points points :color clist :lines drawmode :line-width line-width :times times :color-mode color-mode :color-min color-min :color-max color-max))) (defmethod initialize-instance :after ((self traject-editor) &rest l) (declare (ignore l)) ( param - color - mode self * OM - TRAJ - COLOR - MODE * ) ) (when (= 2 (param-color-mode self)) (when (member nil (times (object self))) (param-color-mode self *OM-TRAJ-COLOR-MODE*))) ( param - color - min self * OM - TRAJ - COLOR - MIN * ) ) ( param - color - max self * OM - TRAJ - COLOR - MAX * ) ) (om-add-subviews (ctrlp self) ( setf ( interpol - show - p self ) ( om - checked - p item ) ) ( om - set - gl - object ( 3Dp self ) ( gl-3DC - from - obj self ) ) ( om - invalidate - view ( 3Dp self ) ) (om-make-dialog-item 'om-static-text (om-make-point 8 550) (om-make-point 70 40) "Sample Rate" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'om-editable-text (om-make-point 70 555) (om-make-point 40 20) (format nil " ~a" (sample-params (object self))) :-action nil :font *controls-font* :bg-color *om-white-color* :modify-action #'(lambda (item) (let ((val (ignore-errors (read-from-string (om-dialog-item-text item))))) (when (or (numberp val) (null val) (and (listp val) (list-subtypep val 'number))) (setf (sample-params (object self)) val)))) ) (om-make-dialog-item 'om-pop-up-dialog-item (om-make-point 8 600) (om-make-point 100 20) "" :range '("points (constant time)" "distance (constant speed)") :value (if (equal (interpol-mode (object self)) 'dist) "distance (constant speed)" "points (constant time)") :di-action (om-dialog-item-act item (setf (interpol-mode (object self)) (if (= (om-get-selected-item-index item) 1) 'dist 'points)))) ) (update-color-mode-buttons self)) (defmethod add-curve-edit-buttons ((self traject-editor) panel) (setf (curve-buttons panel) (list (om-make-dialog-item 'om-static-text (om-make-point 5 230) (om-make-point 70 20) "Line width" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'edit-numbox (om-make-point 80 230) (om-make-point 30 20) (format nil " ~D" (param-line-width self)) :font *controls-font* :bg-color *om-white-color* :value (param-line-width self) :min-val 1.0 :max-val 6.0 :di-action #'(lambda (item) (param-line-width self (value item)) (update-3D-view self) (om-invalidate-view (3Dp self))) ) (om-make-dialog-item 'om-static-text (om-make-point 5 260) (om-make-point 70 20) "Color Mode" :font *controls-font* :fg-color *om-black-color*) (om-make-dialog-item 'om-pop-up-dialog-item (om-make-point 8 280) (om-make-point 100 20) "" :range '("Simple" "Path" "Speed") :value (case (param-color-mode self) ((equal 0) "Simple") ((equal 1) "Path") ((equal 2) "Speed")) :di-action (om-dialog-item-act item (let ((test nil)) (when (= 2 (om-get-selected-item-index item)) (when (member nil (times (object self))) (setf test t) (om-set-selected-item-index item (param-color-mode self)) (om-message-dialog "Not valid curve (Missing times)") (update-3D-view self) (om-invalidate-view (3Dp self))) ) (unless test (param-color-mode self (om-get-selected-item-index item)) (update-color-mode-buttons self) (update-3D-view self) (om-invalidate-view (3Dp self))))) ) )) (apply 'om-add-subviews (cons panel (curve-buttons panel))) ) (defmethod remove-curve-edit-buttons ((self traject-editor) panel) (apply 'om-remove-subviews (cons panel (curve-buttons panel))) (when (color-mode-buttons self) (apply 'om-remove-subviews (cons panel (color-mode-buttons self))))) (defmethod update-color-mode-buttons ((self traject-editor)) (when (color-mode-buttons self) (apply 'om-remove-subviews (cons (ctrlp self) (color-mode-buttons self)))) (let ((mode (param-color-mode self)) (_x 5) (_y 310)) (setf (color-mode-buttons self) (case mode ((= 0) (list (om-make-dialog-item 'om-static-text (om-make-point _x _y) (om-make-point 70 40) "Curve color" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 75) (+ _y 2)) :size (om-make-point 25 18) :color (bpfcolor (get-current-object self)) :after-fun #'(lambda (item) (setf (bpfcolor (get-current-object self)) (color item)) (update-3D-view self) (om-invalidate-view (3Dp self))) ))) (otherwise (list (om-make-dialog-item 'om-static-text (om-make-point _x _y) (om-make-point 70 40) "Min" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 25) (+ _y 2)) :size (om-make-point 25 18) :color (let ((rgb (hsv2rgb (param-color-min self)))) (om-make-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb))) :after-fun #'(lambda (item) (param-color-min self (rgb2hsv (list (om-color-r (color item)) (om-color-g (color item)) (om-color-b (color item))))) (update-3D-view self) (om-invalidate-view (3Dp self))) ) (om-make-dialog-item 'om-static-text (om-make-point (+ _x 55) _y) (om-make-point 70 40) "Max" :font *controls-font* :fg-color *om-black-color*) (om-make-view 'om-color-view :position (om-make-point (+ _x 85) (+ _y 2)) :size (om-make-point 25 18) :color (let ((rgb (hsv2rgb (param-color-max self)))) (om-make-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb))) :after-fun #'(lambda (item) (param-color-max self (rgb2hsv (list (om-color-r (color item)) (om-color-g (color item)) (om-color-b (color item))))) (update-3D-view self) (om-invalidate-view (3Dp self))) ))) ))) (apply 'om-add-subviews (cons (ctrlp self) (color-mode-buttons self))) ) (defmethod get-help-list ((self 3DEditor)) (remove nil (list '((#+cocoa "cmd+clic" #-cocoa "ctrl+clic" "Add point / Draw") ("lrud" "Move selected points") ("del" "Delete selected points") (("c") "Change curve color") (("b") "Change 3D background color") (("p") "Show point indices") (("t") "Show point times") ) (when (multibpf? self) '(("tab" "Change current curve") (("n") "Change curve name") ))))) (defmethod special-move-point ((self bpcPanel) (point timedpoint) i) (let* ((dec (decimals (get-bpf-obj self))) (xsize (max 50 (* 10 dec))) (mydialog (om-make-window 'om-dialog :size (om-make-point (max 180 (+ 100 (* 12 dec))) 120) :window-title "" :position (om-add-points (om-view-position (window self)) (om-mouse-position self)))) (xed (om-make-dialog-item 'om-editable-text (om-make-point 30 5) (om-make-point xsize 10) (if (zerop dec) (format () "~D" (om-point-h point)) (format () (format nil "~S,~DF" '~ dec) (/ (om-point-h point) (expt 10.0 dec)))) )) (yed (om-make-dialog-item 'om-editable-text (om-make-point 30 35) (om-make-point xsize 10) (if (zerop dec) (format () "~D" (om-point-v point)) (format () (format nil "~S,~DF" '~ dec) (/ (om-point-v point) (expt 10.0 dec)))) )) (time-ed (om-make-dialog-item 'om-editable-text (om-make-point 30 65) (om-make-point xsize 10) (format () "~D" (timedpoint-time point)) )) ) (om-add-subviews mydialog (om-make-dialog-item 'om-static-text (om-make-point 5 5) (om-make-point 20 20) (x-label self) :font *om-default-font3b* :bg-color *om-window-def-color*) (om-make-dialog-item 'om-static-text (om-make-point 5 35) (om-make-point 20 20) (y-label self) :font *om-default-font3b* :bg-color *om-window-def-color*) (om-make-dialog-item 'om-static-text (om-make-point 5 65) (om-make-point 20 20) "time" :font *om-default-font3b* :bg-color *om-window-def-color*) xed yed time-ed (om-make-dialog-item 'om-button (om-make-point (- (w mydialog) 80) 5) (om-make-point 70 20) "Cancel" :di-action (om-dialog-item-act item (declare (ignore item)) (om-return-from-modal-dialog mydialog ())) :default-button nil) (om-make-dialog-item 'om-button (om-make-point (- (w mydialog) 80) 36) (om-make-point 70 20) "OK" :di-action (om-dialog-item-act item (declare (ignore item)) (let ((tvalue (ignore-errors (read-from-string (om-dialog-item-text time-ed))))) (if (move-timedpoints-in-bpf (currentbpf self) (list (list point i)) (- (round (* (read-from-string (om-dialog-item-text xed)) (expt 10.0 dec))) (om-point-h point)) (- (round (* (read-from-string (om-dialog-item-text yed)) (expt 10.0 dec))) (om-point-v point)) (if (numberp tvalue) tvalue nil)) (do-after-move self) (om-beep-msg "Ilegal move")) (om-return-from-modal-dialog mydialog ()))) :default-button t)) (om-modal-dialog mydialog))) (defmethod move-timedpoints-in-bpf ((self bpc) points deltax deltay time) (let ((legalmove t)) (loop for point in points do (let* ((pos (second point)) (tmin (or (list-max (remove nil (mapcar 'get-point-time (subseq (point-list self) 0 pos)))) 0.0)) (tmax (list-min (remove nil (mapcar 'get-point-time (subseq (point-list self) (1+ pos))))))) (if (or (null time) (and (or (equal pos 0) (> time tmin)) (or (null tmax) (< time tmax)))) (setf (nth pos (point-list self)) (make-timedpoint :point (om-make-point (+ (om-point-h (car point)) deltax) (+ (om-point-v (car point)) deltay)) :time time)) (setf legalmove nil)))) legalmove)) (defmethod init-tmp-objs ((self traject-editor)) (call-next-method) (set-times-to-tmpobjs self)) (defmethod editor-change-precision ((self traject-editor) newvalue) (call-next-method) (set-times-to-tmpobjs self)) (defun set-times-to-tmpobjs (traject-editor) (let ((curr3dc (if (multibpf? traject-editor) (if (selected-component traject-editor) (nth (selected-component traject-editor) (bpf-list (object traject-editor))) (car (bpf-list (object traject-editor)))) (object traject-editor)))) (mapcar #'(lambda (tobj) (setf (point-list tobj) (loop for pt in (point-list tobj) for trpoint in (point-list curr3Dc) collect (make-timedpoint :point pt :time (timedpoint-time trpoint)))) ) (tmpview-objs traject-editor)) )) (defmethod report-bpfmodif ((self traject-editor) &key xpts ypts zpts times) (let ((3Dobj (if (multibpf? self) (nth (selected-component self) (bpf-list (object self))) (object self)))) (unless xpts (setf xpts (x-points 3Dobj))) (unless ypts (setf ypts (y-points 3Dobj))) (unless zpts (setf zpts (z-points 3Dobj))) (let ((new-bpf (traject-from-list xpts ypts zpts times (type-of 3Dobj) (decimals 3Dobj) (sample-params 3Dobj) (interpol-mode 3Dobj) ))) (cons-bpf 3Dobj (point-list new-bpf)) ( setf ( traject - points 3Dobj ) ( traject - points new - bpf ) ) ) (init-tmp-objs self) (update-editor-contents self))) (defmethod more-bpc-draw ((self internalbpcpanel) point pos index) (call-next-method) (when (and (show-time self) (get-point-time point)) (om-with-fg-color self *om-red2-color* (om-draw-string (+ (om-point-h pos) -6) (+ (om-point-v pos) 14) (format nil "~d" (get-point-time point))))))
f84fada4ca7184659d04d7712a2b2211475c68310b6bfa08cb311de1ce25c5bc
shayne-fletcher/zen
unification.ml
(*The type of a term*) type ('a, 'b) term = | Var of 'b | Term of 'a * ('a, 'b) term list (* Assume [term_fold] to operate on arguments of type [('a, 'd) term]. It "returns" either via [f] or [v], and so [f], [v] and [term_fold] must share the same return type, ['c] say. Since the intermediate list results from recursive calls to [term_fold] then it must have type ['c list]. This means [g] must be of type ['c -> 'b -> 'b] for some type ['b] which fixes [x] to ['b] whilst completing [f] as ['a * 'b -> 'c]. Lastly [v] takes arguments of type ['d] meaning it types to ['d -> 'c]. *) let rec term_fold (f : ('a * 'b) -> 'c) (g : 'c -> 'b -> 'b) (x : 'b) (v : 'd -> 'c) : ('a, 'd ) term -> 'c = function | Term (a, tl) -> let l : 'c list = List.map (term_fold f g x v) tl in let res : 'b = List.fold_right g l x in f (a, res) | Var b -> v b (*Compute the size of a term*) let term_size (t : ('a, 'b) term) : int = term_fold (fun (_, s) -> s + 1) (fun x y -> x + y) 0 (fun _ -> 1) t (*Check if a variable occurs in a term*) let rec occurs (x : 'b) : ('a, 'b) term -> bool = function | Var y -> x = y | Term (_, s) -> List.exists (occurs x) s (*The type of a substitution*) type ('a, 'b) substitution = ('b * ('a, 'b) term) list term [ s ] for all occurences of variable [ x ] in term [ t ] let rec subst (s : ('a, 'b) term) (x : 'b) (t : ('a, 'b) term) : ('a, 'b) term = match t with | Var y as v -> if x = y then s else v | Term (f, u) -> Term (f, List.map (subst s x) u) (*Apply a substitution, right to left*) let rec apply (s : ('a, 'b) substitution) (t : ('a, 'b) term) : ('a, 'b) term = List.fold_right (fun ((x : 'b), (u : ('a, 'b) term)) -> subst u x) s t (*Compose substitutions*) let compose_subst (u : ('a, 'b) substitution) (v : ('a, 'b) substitution) : ('a, 'b) substitution = (*Apply the substitutions in [u] to the terms in [v]*) let v' : ('a, 'b) substitution = List.map (fun (x, t) -> (x, apply u t)) v in (*Variables in [v]*) let vs : 'b list = List.map fst v in (*Filter out substitutions in [u] that are in variables for which there is a substitution in in [v]*) let u' : ('a, 'b) substitution = List.filter (fun (x, _) -> not (List.mem x vs)) u in v' @ u' (*We get the image in the composition of a variable modified by [v] when we take the image by [u] by its image in [v]. The image in the composition of a variable not modified by [v] is its image by [u]*) term [ s ] for all occurences of variable [ x ] in term [ t ] let rec subst (s : ('a, 'b) term) (x : 'b) : ('a, 'b) term -> ('a, 'b) term = function | Var y as v -> if x = y then s else v | Term (a, u) -> Term (a, List.map (subst s x) u) (*Apply a substitution, right to left*) let apply (s : ('a, 'b) substitution) (t : ('a, 'b) term) : ('a, 'b) term = List.fold_right (fun (x, u) -> subst u x) s t Unify one pair let rec unify_one (s : ('a, 'b) term) (t : ('a, 'b) term) : ('a, 'b) substitution = match (s, t) with | (Var x, Var y) -> if x = y then [] else [(x, t)] | (Term (f, sc), Term (g, tc)) -> if f = g && List.length sc = List.length tc then unify (List.combine sc tc) else failwith "unification failure : head symbol conflict" | (Var x, (Term (_, _) as t)) | ((Term (_, _) as t), Var x) -> if occurs x t then failwith "unification failure : circularity" else [(x, t)] (*Unify a list of pairs of terms*) and unify (s : (('a, 'b) term * ('a, 'b) term) list) : ('a, 'b) substitution = match s with | [] -> [] | (x, y) :: t -> let t2 = unify t in let t1 = unify_one (apply t2 x) (apply t2 y) in t1 @ t2
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/term/unification.ml
ocaml
The type of a term Assume [term_fold] to operate on arguments of type [('a, 'd) term]. It "returns" either via [f] or [v], and so [f], [v] and [term_fold] must share the same return type, ['c] say. Since the intermediate list results from recursive calls to [term_fold] then it must have type ['c list]. This means [g] must be of type ['c -> 'b -> 'b] for some type ['b] which fixes [x] to ['b] whilst completing [f] as ['a * 'b -> 'c]. Lastly [v] takes arguments of type ['d] meaning it types to ['d -> 'c]. Compute the size of a term Check if a variable occurs in a term The type of a substitution Apply a substitution, right to left Compose substitutions Apply the substitutions in [u] to the terms in [v] Variables in [v] Filter out substitutions in [u] that are in variables for which there is a substitution in in [v] We get the image in the composition of a variable modified by [v] when we take the image by [u] by its image in [v]. The image in the composition of a variable not modified by [v] is its image by [u] Apply a substitution, right to left Unify a list of pairs of terms
type ('a, 'b) term = | Var of 'b | Term of 'a * ('a, 'b) term list let rec term_fold (f : ('a * 'b) -> 'c) (g : 'c -> 'b -> 'b) (x : 'b) (v : 'd -> 'c) : ('a, 'd ) term -> 'c = function | Term (a, tl) -> let l : 'c list = List.map (term_fold f g x v) tl in let res : 'b = List.fold_right g l x in f (a, res) | Var b -> v b let term_size (t : ('a, 'b) term) : int = term_fold (fun (_, s) -> s + 1) (fun x y -> x + y) 0 (fun _ -> 1) t let rec occurs (x : 'b) : ('a, 'b) term -> bool = function | Var y -> x = y | Term (_, s) -> List.exists (occurs x) s type ('a, 'b) substitution = ('b * ('a, 'b) term) list term [ s ] for all occurences of variable [ x ] in term [ t ] let rec subst (s : ('a, 'b) term) (x : 'b) (t : ('a, 'b) term) : ('a, 'b) term = match t with | Var y as v -> if x = y then s else v | Term (f, u) -> Term (f, List.map (subst s x) u) let rec apply (s : ('a, 'b) substitution) (t : ('a, 'b) term) : ('a, 'b) term = List.fold_right (fun ((x : 'b), (u : ('a, 'b) term)) -> subst u x) s t let compose_subst (u : ('a, 'b) substitution) (v : ('a, 'b) substitution) : ('a, 'b) substitution = let v' : ('a, 'b) substitution = List.map (fun (x, t) -> (x, apply u t)) v in let vs : 'b list = List.map fst v in let u' : ('a, 'b) substitution = List.filter (fun (x, _) -> not (List.mem x vs)) u in v' @ u' term [ s ] for all occurences of variable [ x ] in term [ t ] let rec subst (s : ('a, 'b) term) (x : 'b) : ('a, 'b) term -> ('a, 'b) term = function | Var y as v -> if x = y then s else v | Term (a, u) -> Term (a, List.map (subst s x) u) let apply (s : ('a, 'b) substitution) (t : ('a, 'b) term) : ('a, 'b) term = List.fold_right (fun (x, u) -> subst u x) s t Unify one pair let rec unify_one (s : ('a, 'b) term) (t : ('a, 'b) term) : ('a, 'b) substitution = match (s, t) with | (Var x, Var y) -> if x = y then [] else [(x, t)] | (Term (f, sc), Term (g, tc)) -> if f = g && List.length sc = List.length tc then unify (List.combine sc tc) else failwith "unification failure : head symbol conflict" | (Var x, (Term (_, _) as t)) | ((Term (_, _) as t), Var x) -> if occurs x t then failwith "unification failure : circularity" else [(x, t)] and unify (s : (('a, 'b) term * ('a, 'b) term) list) : ('a, 'b) substitution = match s with | [] -> [] | (x, y) :: t -> let t2 = unify t in let t1 = unify_one (apply t2 x) (apply t2 y) in t1 @ t2
abe3f9c528cb175589068f4eb2a0837ec690d32f79436a8c735b095193b9b90f
emotiq/emotiq
generate.lisp
(in-package :emotiq/config/generate) (um:defconstant+ +default-configuration+ `((:hostname . "localhost") (:ip . "127.0.0.1") (:rest-server . :true) (:rest-server-port . 3140) (:websocket-server . :true) (:websocket-server-port . 3145) (:gossip-server . :true) (:gossip-server-port . 65002) (:genesis-block-file . "emotiq-genesis-block.json")) "The default configuration alist Values are changed by pushing key value cons at the beginning of the list, where they override any later identical keys according to the semantics of CL:ASSOC") (defun generate-keys (records) "Generate keys for a list of plist RECORDS" (loop :for (public-key private-key) = (pbc:make-keying-pairs) :for record :in records :collecting (append record HACK adapt to gossip / config needs (unless (find :gossip-server-port record) (list :gossip-server-port 65002)) (list :public public-key) (list :private private-key)))) (defun generate-stakes (public-keys &key (max-stake emotiq/config:*max-stake*)) "Given a list of PUBLIC-KEYS, generate a random stake for each Returns the enumeration of lists of public keys and staked amounts." (mapcar (lambda (pkey) (list pkey (random max-stake))) public-keys)) A list of plists drives the generation routines , as this is what the ;;; devops-ansible hook passes the network generation routines (defparameter *eg-config-zerotier* '((:hostname "zt-emq-01.zt.emotiq.ch" :ip "10.178.2.166" ;;; The ports take the default values if not otherwise specified :gossip-server-port 65002 :rest-server-port 3140 :websocket-server-port 3145) (:hostname "zt-emq-02.zt.emotiq.ch" :ip "10.178.0.71") (:hostname "zt-emq-03.zt.emotiq.ch" :ip "10.178.15.71")) "An example of the syntax to generate network artifacts for a Zerotier testnet configuration") (defparameter *eg-config-localhost* '((:hostname "localhost" :local-process-nodes 4 :gossip-server-port 65002 :rest-server-port 3140 :websocket-server-port 3145)) "An example of the syntax to generate a purely local process 4 node network") (defun generate-network (&key (root (emotiq/fs:new-temporary-directory)) (nodes-dns-ip *eg-config-zerotier*) (force nil) (settings-key-value-alist nil)) "Generate a test network configuration Files are generated under the ROOT directory. NODES-DNS-IP contains a plist of keys describing the tcp/udp service endpoints at which the nodes will run. See *EG-CONFIG-LOCALHOST* and *EG-CONFIG-ZEROTIER* for examples of the configuration syntax." (let* ((nodes-with-keys (generate-keys nodes-dns-ip)) (stakes (generate-stakes (mapcar (lambda (plist) (getf plist :public)) nodes-with-keys))) (address-for-coins (getf (first nodes-with-keys) :public)) directories configurations) (dolist (node nodes-with-keys) (let ((configuration (make-configuration node :address-for-coins address-for-coins :stakes stakes))) ;;; Override by pushing ahead in alist (when settings-key-value-alist (loop :for setting :in settings-key-value-alist :doing (push setting configuration))) (let ((relative-path (generated-directory configuration))) (let ((path (merge-pathnames relative-path root)) (configuration (copy-alist configuration))) (push (generate-node path configuration :force force :key-records nodes-with-keys) directories) (push configuration configurations))))) (values directories configurations))) (defun make-configuration (node &key address-for-coins stakes) (let ((configuration (copy-alist +default-configuration+))) (loop :for key-value-cons :in (alexandria:plist-alist node) :doing (push key-value-cons configuration)) (when address-for-coins (push (cons :address-for-coins address-for-coins) configuration)) (when stakes (push (cons :stakes stakes) configuration)) configuration)) (defun generate-node (directory configuration &key key-records (force nil)) "Generate a complete Emotiq node description within DIRECTORY for CONFIGURATION Returns the directory in which the node configuration was written as the primary values. The genesis block for the node is returned as the second value. " FIXME code explicit re - generation (emotiq:note "Writing node configuration to '~a'." directory) (generate-gossip-node :root directory :host (alexandria:assoc-value configuration :hostname) :eripa (alexandria:assoc-value configuration :ip) :gossip-port (alexandria:assoc-value configuration :gossip-server-port) :public (list (alexandria:assoc-value configuration :public)) :key-records key-records) (with-open-file (o (merge-pathnames emotiq/config:*conf-filename* directory) :if-exists :supersede :direction :output) (cl-json:encode-json (alexandria:alist-hash-table configuration) o)) (output-stakes directory (alexandria:assoc-value configuration :stakes)) (output-keypairs directory key-records) (values directory (create-genesis configuration :directory directory :force t))) (defmacro with-safe-output (&body body) `(with-standard-io-syntax (let ((*print-readably* t)) ,@body))) #+:LISPWORKS (editor:setup-indent "with-safe-output" 0) (defun create-genesis (configuration &key (directory (emotiq/fs:tmp/)) (force nil)) (let ((genesis-block-path (merge-pathnames (alexandria:assoc-value configuration :genesis-block-file) directory))) (when (or force (not (probe-file genesis-block-path))) (let ((genesis-block (cosi/proofs:create-genesis-block (alexandria:assoc-value configuration :address-for-coins) (alexandria:assoc-value configuration :stakes)))) (with-open-file (o genesis-block-path :direction :output :if-exists :supersede) (cl-json:encode-json genesis-block o)) ;;; FIXME: JSON doesn't currently round-trip very well, so use ;;; LISP-OBJECT-ENCODER as a workaround. (let ((p (make-pathname :type "loenc" :defaults genesis-block-path))) (with-open-file (o p :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede) (with-safe-output (lisp-object-encoder:serialize genesis-block o)))) genesis-block)))) (defun output-stakes (directory stakes) (with-open-file (o (merge-pathnames emotiq/config:*stakes-filename* directory) :direction :output :if-exists :supersede) (with-safe-output (format o ";;; Stakes for a generated testnet configuration~%") (dolist (stake stakes) (format o "~s~%" stake))))) (defun output-keypairs (directory nodes) (with-open-file (o (merge-pathnames emotiq/config:*keypairs-filename* directory) :direction :output :if-exists :supersede) (with-safe-output (dolist (node nodes) (format o "~s~%" (list (getf node :public) (getf node :private))))))) (defun generated-directory (configuration) "For CONFIGURATION return a uniquely named relative directory for the network generation process" (let ((host (alexandria:assoc-value configuration :hostname)) (ip (alexandria:assoc-value configuration :ip)) (gossip-server-port (alexandria:assoc-value configuration :gossip-server-port)) (rest-server-port (alexandria:assoc-value configuration :rest-server-port)) (websocket-server-port (alexandria:assoc-value configuration :websocket-server-port))) (make-pathname :directory `(:relative ,(format nil "~{~a~^-~}" (list host ip gossip-server-port rest-server-port websocket-server-port)))))) (defun generate-gossip-node (&key root host eripa gossip-port public key-records) (declare (ignore host)) ;; Hmm? (ensure-directories-exist root) (write-gossip-conf root :eripa eripa :port gossip-port :public-key-or-keys public) (write-hosts-conf root key-records) root) (defun write-gossip-conf (directory &key eripa port public-key-or-keys) (let ((p (merge-pathnames emotiq/config:*local-machine-filename* directory))) (with-open-file (o p :direction :output :if-exists :supersede) (with-safe-output (format o "~s~&" `(:eripa ,eripa :gossip-port ,port :pubkeys ,public-key-or-keys)))))) (defun write-hosts-conf (directory records) (let ((p (merge-pathnames emotiq/config:*hosts-filename* directory))) (with-open-file (o p :direction :output :if-exists :supersede) (with-safe-output (dolist (record records) (format o "~s~&" `(,(getf record :ip) ,(getf record :gossip-server-port)))))))) (defun ensure-defaults (&key force (for-purely-local nil) (nodes-dns-ip *eg-config-zerotier*)) "Ensure that configuration will start up, even in the absence of explicit configuration With FORCE true, overwrite destination without warning. With FOR-PURELY-LOCAL, emits a purely local configuration for the local node." (let ((root (emotiq/fs:new-temporary-directory)) (destination (emotiq/fs:etc/))) (unless force (when (not (zerop (length (directory (make-pathname :name :wild :type :wild :defaults destination)))))) (warn "Refusing to overwrite existing '~a' with defaults. Use force to try again." destination) (return-from ensure-defaults (emotiq/config:settings))) (ensure-directories-exist root) (let ((directories (generate-network :root root :nodes-dns-ip nodes-dns-ip))) (uiop:run-program (format nil "rsync -avzP ~a ~a" (first directories) destination)) (when for-purely-local ;;; FIXME kludge (uiop:run-program (format nil "cat /dev/null > ~a" (merge-pathnames emotiq/config:*hosts-filename* destination))) (let* ((keypairs (emotiq/config:get-keypairs)) (local-machine (emotiq/config:local-machine)) (eripa (getf local-machine :eripa)) (gossip-port (getf local-machine :gossip-port)) (result (write-gossip-conf destination :eripa eripa :port gossip-port :public-key-or-keys (mapcar 'first keypairs)))) (emotiq:note "Finished mangling configuration for purely local nodes~%~t~a" result))) (values (emotiq/config:settings) destination))))
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/generate.lisp
lisp
devops-ansible hook passes the network generation routines The ports take the default values if not otherwise specified Override by pushing ahead in alist FIXME: JSON doesn't currently round-trip very well, so use LISP-OBJECT-ENCODER as a workaround. Hmm? FIXME kludge
(in-package :emotiq/config/generate) (um:defconstant+ +default-configuration+ `((:hostname . "localhost") (:ip . "127.0.0.1") (:rest-server . :true) (:rest-server-port . 3140) (:websocket-server . :true) (:websocket-server-port . 3145) (:gossip-server . :true) (:gossip-server-port . 65002) (:genesis-block-file . "emotiq-genesis-block.json")) "The default configuration alist Values are changed by pushing key value cons at the beginning of the list, where they override any later identical keys according to the semantics of CL:ASSOC") (defun generate-keys (records) "Generate keys for a list of plist RECORDS" (loop :for (public-key private-key) = (pbc:make-keying-pairs) :for record :in records :collecting (append record HACK adapt to gossip / config needs (unless (find :gossip-server-port record) (list :gossip-server-port 65002)) (list :public public-key) (list :private private-key)))) (defun generate-stakes (public-keys &key (max-stake emotiq/config:*max-stake*)) "Given a list of PUBLIC-KEYS, generate a random stake for each Returns the enumeration of lists of public keys and staked amounts." (mapcar (lambda (pkey) (list pkey (random max-stake))) public-keys)) A list of plists drives the generation routines , as this is what the (defparameter *eg-config-zerotier* '((:hostname "zt-emq-01.zt.emotiq.ch" :ip "10.178.2.166" :gossip-server-port 65002 :rest-server-port 3140 :websocket-server-port 3145) (:hostname "zt-emq-02.zt.emotiq.ch" :ip "10.178.0.71") (:hostname "zt-emq-03.zt.emotiq.ch" :ip "10.178.15.71")) "An example of the syntax to generate network artifacts for a Zerotier testnet configuration") (defparameter *eg-config-localhost* '((:hostname "localhost" :local-process-nodes 4 :gossip-server-port 65002 :rest-server-port 3140 :websocket-server-port 3145)) "An example of the syntax to generate a purely local process 4 node network") (defun generate-network (&key (root (emotiq/fs:new-temporary-directory)) (nodes-dns-ip *eg-config-zerotier*) (force nil) (settings-key-value-alist nil)) "Generate a test network configuration Files are generated under the ROOT directory. NODES-DNS-IP contains a plist of keys describing the tcp/udp service endpoints at which the nodes will run. See *EG-CONFIG-LOCALHOST* and *EG-CONFIG-ZEROTIER* for examples of the configuration syntax." (let* ((nodes-with-keys (generate-keys nodes-dns-ip)) (stakes (generate-stakes (mapcar (lambda (plist) (getf plist :public)) nodes-with-keys))) (address-for-coins (getf (first nodes-with-keys) :public)) directories configurations) (dolist (node nodes-with-keys) (let ((configuration (make-configuration node :address-for-coins address-for-coins :stakes stakes))) (when settings-key-value-alist (loop :for setting :in settings-key-value-alist :doing (push setting configuration))) (let ((relative-path (generated-directory configuration))) (let ((path (merge-pathnames relative-path root)) (configuration (copy-alist configuration))) (push (generate-node path configuration :force force :key-records nodes-with-keys) directories) (push configuration configurations))))) (values directories configurations))) (defun make-configuration (node &key address-for-coins stakes) (let ((configuration (copy-alist +default-configuration+))) (loop :for key-value-cons :in (alexandria:plist-alist node) :doing (push key-value-cons configuration)) (when address-for-coins (push (cons :address-for-coins address-for-coins) configuration)) (when stakes (push (cons :stakes stakes) configuration)) configuration)) (defun generate-node (directory configuration &key key-records (force nil)) "Generate a complete Emotiq node description within DIRECTORY for CONFIGURATION Returns the directory in which the node configuration was written as the primary values. The genesis block for the node is returned as the second value. " FIXME code explicit re - generation (emotiq:note "Writing node configuration to '~a'." directory) (generate-gossip-node :root directory :host (alexandria:assoc-value configuration :hostname) :eripa (alexandria:assoc-value configuration :ip) :gossip-port (alexandria:assoc-value configuration :gossip-server-port) :public (list (alexandria:assoc-value configuration :public)) :key-records key-records) (with-open-file (o (merge-pathnames emotiq/config:*conf-filename* directory) :if-exists :supersede :direction :output) (cl-json:encode-json (alexandria:alist-hash-table configuration) o)) (output-stakes directory (alexandria:assoc-value configuration :stakes)) (output-keypairs directory key-records) (values directory (create-genesis configuration :directory directory :force t))) (defmacro with-safe-output (&body body) `(with-standard-io-syntax (let ((*print-readably* t)) ,@body))) #+:LISPWORKS (editor:setup-indent "with-safe-output" 0) (defun create-genesis (configuration &key (directory (emotiq/fs:tmp/)) (force nil)) (let ((genesis-block-path (merge-pathnames (alexandria:assoc-value configuration :genesis-block-file) directory))) (when (or force (not (probe-file genesis-block-path))) (let ((genesis-block (cosi/proofs:create-genesis-block (alexandria:assoc-value configuration :address-for-coins) (alexandria:assoc-value configuration :stakes)))) (with-open-file (o genesis-block-path :direction :output :if-exists :supersede) (cl-json:encode-json genesis-block o)) (let ((p (make-pathname :type "loenc" :defaults genesis-block-path))) (with-open-file (o p :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede) (with-safe-output (lisp-object-encoder:serialize genesis-block o)))) genesis-block)))) (defun output-stakes (directory stakes) (with-open-file (o (merge-pathnames emotiq/config:*stakes-filename* directory) :direction :output :if-exists :supersede) (with-safe-output (format o ";;; Stakes for a generated testnet configuration~%") (dolist (stake stakes) (format o "~s~%" stake))))) (defun output-keypairs (directory nodes) (with-open-file (o (merge-pathnames emotiq/config:*keypairs-filename* directory) :direction :output :if-exists :supersede) (with-safe-output (dolist (node nodes) (format o "~s~%" (list (getf node :public) (getf node :private))))))) (defun generated-directory (configuration) "For CONFIGURATION return a uniquely named relative directory for the network generation process" (let ((host (alexandria:assoc-value configuration :hostname)) (ip (alexandria:assoc-value configuration :ip)) (gossip-server-port (alexandria:assoc-value configuration :gossip-server-port)) (rest-server-port (alexandria:assoc-value configuration :rest-server-port)) (websocket-server-port (alexandria:assoc-value configuration :websocket-server-port))) (make-pathname :directory `(:relative ,(format nil "~{~a~^-~}" (list host ip gossip-server-port rest-server-port websocket-server-port)))))) (defun generate-gossip-node (&key root host eripa gossip-port public key-records) (ensure-directories-exist root) (write-gossip-conf root :eripa eripa :port gossip-port :public-key-or-keys public) (write-hosts-conf root key-records) root) (defun write-gossip-conf (directory &key eripa port public-key-or-keys) (let ((p (merge-pathnames emotiq/config:*local-machine-filename* directory))) (with-open-file (o p :direction :output :if-exists :supersede) (with-safe-output (format o "~s~&" `(:eripa ,eripa :gossip-port ,port :pubkeys ,public-key-or-keys)))))) (defun write-hosts-conf (directory records) (let ((p (merge-pathnames emotiq/config:*hosts-filename* directory))) (with-open-file (o p :direction :output :if-exists :supersede) (with-safe-output (dolist (record records) (format o "~s~&" `(,(getf record :ip) ,(getf record :gossip-server-port)))))))) (defun ensure-defaults (&key force (for-purely-local nil) (nodes-dns-ip *eg-config-zerotier*)) "Ensure that configuration will start up, even in the absence of explicit configuration With FORCE true, overwrite destination without warning. With FOR-PURELY-LOCAL, emits a purely local configuration for the local node." (let ((root (emotiq/fs:new-temporary-directory)) (destination (emotiq/fs:etc/))) (unless force (when (not (zerop (length (directory (make-pathname :name :wild :type :wild :defaults destination)))))) (warn "Refusing to overwrite existing '~a' with defaults. Use force to try again." destination) (return-from ensure-defaults (emotiq/config:settings))) (ensure-directories-exist root) (let ((directories (generate-network :root root :nodes-dns-ip nodes-dns-ip))) (uiop:run-program (format nil "rsync -avzP ~a ~a" (first directories) destination)) (when for-purely-local (uiop:run-program (format nil "cat /dev/null > ~a" (merge-pathnames emotiq/config:*hosts-filename* destination))) (let* ((keypairs (emotiq/config:get-keypairs)) (local-machine (emotiq/config:local-machine)) (eripa (getf local-machine :eripa)) (gossip-port (getf local-machine :gossip-port)) (result (write-gossip-conf destination :eripa eripa :port gossip-port :public-key-or-keys (mapcar 'first keypairs)))) (emotiq:note "Finished mangling configuration for purely local nodes~%~t~a" result))) (values (emotiq/config:settings) destination))))
9809825351de612f973a0246791ccb5646d6d7505f2a85a8a7a505bb4dc39397
finnishtransportagency/harja
johto_ja_hallintokorvaus_osio.cljs
(ns harja.views.urakka.suunnittelu.kustannussuunnitelma.johto-ja-hallintokorvaus-osio (:require [reagent.core :as r] [harja.tiedot.urakka.suunnittelu.mhu-kustannussuunnitelma :as t] [harja.ui.taulukko.grid :as grid] [harja.ui.yleiset :as yleiset] [harja.ui.kentat :as kentat] [harja.tyokalut.yleiset :as tyokalut] [harja.views.urakka.suunnittelu.kustannussuunnitelma.yhteiset :as ks-yhteiset :refer [e!]] [harja.tyokalut.tuck :as tuck-apurit] [harja.ui.taulukko.impl.solu :as solu] [harja.ui.taulukko.grid-pohjat :as g-pohjat] [harja.fmt :as fmt] [clojure.string :as clj-str] [harja.ui.modal :as modal] [harja.tiedot.urakka.urakka :as tila] [harja.pvm :as pvm] [harja.ui.grid :as vanha-grid] [harja.ui.taulukko.grid-osan-vaihtaminen :as gov] [harja.views.urakka.suunnittelu.kustannussuunnitelma.grid-apurit :as grid-apurit] [harja.domain.mhu :as mhu])) -- gridit -- (def toimistokulut-grid (partial grid-apurit/maarataulukko-grid "toimistokulut" [:yhteenvedot :johto-ja-hallintokorvaukset] {:tallennus-onnistui-event t/->TallennaToimistokulutOnnistui})) (defn- yhteenveto-grid-rajapinta-asetukset [toimenkuva maksukausi data-koskee-ennen-urakkaa?] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi) kuvaus (vec (concat [:toimenkuva :tunnit :tuntipalkka :yhteensa] (when-not (t/post-2022?) [:kk-v])))] {:rajapinta (keyword (str "yhteenveto" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :jarjestys [(with-meta kuvaus {:nimi :mapit})] :datan-kasittely (fn [yhteenveto] (mapv (fn [[_ v]] v) yhteenveto)) :tunnisteen-kasittely (fn [osat data] (second (reduce (fn [[loytynyt? tunnisteet] osa] (let [syote-osa? (instance? solu/Syote osa) osa (when syote-osa? (if loytynyt? :tuntipalkka :tunnit)) Note : Nämä tiedot valuvat jotenkin : aseta - jh - yhteenveto ! ;; jh-yhteenvetopaivitys -funktiolle parametreiksi. tunniste {:osa osa :toimenkuva toimenkuva :maksukausi maksukausi :data-koskee-ennen-urakkaa? data-koskee-ennen-urakkaa?}] [(or loytynyt? syote-osa?) (conj tunnisteet tunniste)])) [false []] (grid/hae-grid osat :lapset))))})) (defn- muokkausrivien-rajapinta-asetukset [nimi] {:rajapinta (keyword (str "yhteenveto-" nimi)) :solun-polun-pituus 1 :jarjestys [^{:nimi :mapit} [:toimenkuva :tunnit :tuntipalkka :yhteensa :maksukausi]] :datan-kasittely (fn [yhteenveto] (mapv (fn [[_ v]] v) yhteenveto)) :tunnisteen-kasittely (fn [_ _] (mapv (fn [index] (assoc (case index 0 {:osa :toimenkuva} 1 {:osa :tunnit} 2 {:osa :tuntipalkka} 3 {:osa :yhteensa} 4 {:osa :maksukausi}) :omanimi nimi)) (range 5)))}) (defn- blur-tallenna! ([tallenna-kaikki? etsittava-osa solu] (blur-tallenna! tallenna-kaikki? etsittava-osa solu nil)) ([tallenna-kaikki? etsittava-osa solu muutos] (if tallenna-kaikki? (e! (t/->TallennaJohtoJaHallintokorvaukset (mapv #(grid/solun-asia (get (grid/hae-grid % :lapset) 1) :tunniste-rajapinnan-dataan) (grid/hae-grid (get (grid/hae-grid (grid/etsi-osa (grid/root solu) etsittava-osa) :lapset) 1) :lapset)))) (e! (t/->TallennaJohtoJaHallintokorvaukset [(grid/solun-asia solu :tunniste-rajapinnan-dataan)]))))) (defn- nappia-painettu-tallenna! ([rivit-alla] (nappia-painettu-tallenna! rivit-alla nil)) ([rivit-alla muutos] (e! (t/->TallennaJohtoJaHallintokorvaukset (vec (keep (fn [rivi] (let [haettu-solu (grid/get-in-grid rivi [1]) piilotettu? (grid/piilotettu? rivi)] (when-not piilotettu? (grid/solun-asia haettu-solu :tunniste-rajapinnan-dataan)))) rivit-alla)))))) (defn- rividisable! [g index kuukausitasolla?] (ks-yhteiset/maara-solujen-disable! (grid/get-in-grid g [::g-pohjat/data index ::t/data-sisalto]) (not kuukausitasolla?)) (ks-yhteiset/maara-solujen-disable! (if-let [osa (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0 1])] osa (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 1])) kuukausitasolla?)) (defn- disable-osa-indexissa! [rivi indexit disabled?] (grid/paivita-grid! rivi :lapset (fn [osat] (vec (map-indexed (fn [index solu] (if (contains? indexit index) (if (grid/pudotusvalikko? solu) (assoc-in solu [:livi-pudotusvalikko-asetukset :disabled?] disabled?) (assoc-in solu [:parametrit :disabled?] disabled?)) solu)) osat))))) (defn johto-ja-hallintokorvaus-laskulla-grid [] (let [taulukon-id "johto-ja-hallintokorvaus-laskulla-taulukko" vakiorivit (mapv (fn [{:keys [toimenkuva maksukausi hoitokaudet] :as toimenkuva-kuvaus}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] (if (t/toimenpide-koskee-ennen-urakkaa? hoitokaudet) {:tyyppi :rivi :nimi ::t/data-yhteenveto :osat [{:tyyppi :teksti :luokat #{"table-default"}} (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! false nil)}) (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! false nil)}) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} {:tyyppi :teksti :luokat #{"table-default"} :fmt (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))}]} {:tyyppi :taulukko :nimi (str toimenkuva "-" maksukausi "-taulukko") :osat [{:tyyppi :rivi :nimi ::t/data-yhteenveto :osat [{:tyyppi :laajenna :aukaise-fn (fn [this auki?] (if auki? (ks-yhteiset/rivi-kuukausifiltterilla! this true (keyword (str "kuukausitasolla?" yksiloiva-nimen-paate)) [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? toimenkuva maksukausi] [:. ::t/yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false) [:. ::t/valinta] {:rajapinta (keyword (str "kuukausitasolla?" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :datan-kasittely (fn [kuukausitasolla?] [kuukausitasolla? nil nil nil])}) (do (ks-yhteiset/rivi-ilman-kuukausifiltteria! this [:.. ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false)) (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? toimenkuva maksukausi] false)))) (t/laajenna-solua-klikattu this auki? taulukon-id [::g-pohjat/data] {:sulkemis-polku [:.. :.. :.. 1]})) :auki-alussa? false :luokat #{"table-default"}} (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true (str toimenkuva "-" maksukausi "-taulukko"))}) (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true (str toimenkuva "-" maksukausi "-taulukko"))}) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} {:tyyppi :teksti :luokat #{"table-default"} :fmt (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))}]} {:tyyppi :taulukko :nimi ::t/data-sisalto :luokat #{"piilotettu"} :osat (vec (repeatedly (t/kk-v-toimenkuvan-kuvaukselle toimenkuva-kuvaus) (fn [] {:tyyppi :rivi :osat [{:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/aika-tekstilla-fmt} (ks-yhteiset/syote-solu {:nappi? true :fmt ks-yhteiset/summa-formatointi-uusi :paivitettava-asia :aseta-tunnit! :solun-index 1 :blur-tallenna! (partial blur-tallenna! false (str toimenkuva "-" maksukausi "-taulukko")) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) {:tyyppi :tyhja} {:tyyppi :tyhja} {:tyyppi :tyhja}]})))}]}))) (t/pohjadatan-versio)) muokattavat-rivit (mapv (fn [index] (let [rivin-nimi (t/jh-omienrivien-nimi index)] rivi ( sisältää alitaulukon ) {:tyyppi :taulukko :nimi rivin-nimi :osat [{:tyyppi :rivi :nimi ::t/data-yhteenveto ;; :oma = itselisätyn toimenkuvan nimi-solu :osat [{:tyyppi :oma :constructor (fn [_] (ks-yhteiset/laajenna-syote (fn [this auki?] (if auki? (ks-yhteiset/rivi-kuukausifiltterilla! this true (keyword (str "kuukausitasolla?-" rivin-nimi)) [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? rivin-nimi] [:. ::t/yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi) [:. ::t/valinta] {:rajapinta (keyword (str "kuukausitasolla?-" rivin-nimi)) :solun-polun-pituus 1 :datan-kasittely (fn [kuukausitasolla?] [kuukausitasolla? nil nil nil])}) (do (ks-yhteiset/rivi-ilman-kuukausifiltteria! this [:.. ::t/data-yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi)) (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? rivin-nimi] false)))) (t/laajenna-solua-klikattu this auki? taulukon-id [::g-pohjat/data] {:sulkemis-polku [:.. :.. :.. 1]})) false {:on-change (fn [arvo] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo arvo :solu solu/*this* :ajettavat-jarjestykset #{:mapit}} false)) :on-blur (fn [arvo] (let [arvo (if (= "" (clj-str/trim arvo)) nil arvo) solu solu/*this* paivita-ui! (fn [] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo arvo :solu solu :ajettavat-jarjestykset true :triggeroi-seuranta? true} true)) paivita-kanta! (fn [] (e! (t/->TallennaToimenkuva rivin-nimi))) paivita! (fn [] (paivita-ui!) (paivita-kanta!)) peruuta! (fn [vanha-arvo] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :yhteenveto rivin-nimi :toimenkuva] vanha-arvo)))] Jos custom toimenkuvan nimi pyyhitään , niin täytyy triggeröidä toimenkuvaan liittyvän datan poisto tietokannasta . (if (nil? arvo) (let [paivita-seuraavalla-tickilla! (fn [] (r/next-tick paivita!))] (e! (t/->PoistaOmaJHDdata :toimenkuva rivin-nimi Poistetaan data kaikilta maksukausilta modal/piilota! paivita-seuraavalla-tickilla! (fn [toimenkuva data-hoitokausittain poista! vanhat-arvot] (ks-yhteiset/poista-modal! :toimenkuva data-hoitokausittain poista! {:toimenkuva toimenkuva} (partial peruuta! (some :toimenkuva vanhat-arvot))))))) (paivita!)))) :on-key-down (fn [event] (when (= "Enter" (.. event -key)) (.. event -target blur)))} {:on-change [:eventin-arvo] :on-blur [:eventin-arvo]} {:class #{"input-default"} :placeholder "Kirjoita muu toimenkuva"} identity identity)) :auki-alussa? false :luokat #{"table-default"}} Tunnit - solu (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) ;; Tuntipalkka-solu (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) Yhteenveto - solu ( Yhteensä / kk ) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} ;; Pudotusvalikko-solu {:tyyppi :pudotusvalikko :data-cy "kk-v-valinnat" :valitse-fn (fn [maksukausi] (let [solu solu/*this* paivita-ui! (fn [] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo maksukausi :solu solu :ajettavat-jarjestykset true :triggeroi-seuranta? true} false))] NOTE : , että maksukausi on varmasti solu on käytössä tallenna - funktiossa . (if (= :molemmat maksukausi) (do (paivita-ui!) (blur-tallenna! true rivin-nimi solu)) (e! (t/->PoistaOmaJHDdata :maksukausi rivin-nimi maksukausi modal/piilota! #(r/next-tick paivita-ui!) (fn [toimenkuva data-hoitokausittain poista! _] (ks-yhteiset/poista-modal! :toimenkuva data-hoitokausittain poista! {:toimenkuva toimenkuva}))))))) :format-fn (fn [teksti] (str (mhu/maksukausi->kuukausien-lkm teksti))) :rivin-haku (fn [pudotusvalikko] (grid/osa-polusta pudotusvalikko [:.. :..])) :vayla-tyyli? true :vaihtoehdot t/kk-v-valinnat}]} {:tyyppi :taulukko :nimi ::t/data-sisalto :luokat #{"piilotettu"} :osat (vec (repeatedly 12 (fn [] {:tyyppi :rivi :osat [{:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/aika-tekstilla-fmt} (ks-yhteiset/syote-solu {:nappi? true :fmt ks-yhteiset/summa-formatointi-uusi :paivitettava-asia :aseta-tunnit! :solun-index 1 :blur-tallenna! (partial blur-tallenna! false rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) {:tyyppi :tyhja} {:tyyppi :tyhja} {:tyyppi :tyhja}]})))}]})) (range 1 (inc t/jh-korvausten-omiariveja-lkm))) g (g-pohjat/uusi-taulukko {:header [{:tyyppi :teksti :leveys 4 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 1 :luokat #{"table-default" "table-default-header" "lihavoitu"}}] :body (vec (concat vakiorivit muokattavat-rivit)) :taulukon-id taulukon-id :root-luokat #{"salli-ylipiirtaminen"} :root-asetus! (fn [g] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :grid] g))) :root-asetukset {:haku (fn [] (get-in @tila/suunnittelu-kustannussuunnitelma [:gridit :johto-ja-hallintokorvaukset :grid])) :paivita! (fn [f] (swap! tila/suunnittelu-kustannussuunnitelma (fn [tila] (update-in tila [:gridit :johto-ja-hallintokorvaukset :grid] f))))}}) [vakio-viimeinen-index vakiokasittelijat] (reduce (fn [[index grid-kasittelijat] {:keys [toimenkuva maksukausi hoitokaudet]}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] [(inc index) (merge grid-kasittelijat (if (t/toimenpide-koskee-ennen-urakkaa? hoitokaudet) {[::g-pohjat/data ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi true)} {[::g-pohjat/data index ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false) [::g-pohjat/data index ::t/data-sisalto] {:rajapinta (keyword (str "johto-ja-hallintokorvaus" yksiloiva-nimen-paate)) :solun-polun-pituus 2 :jarjestys [{:keyfn :aika :comp (fn [aika-1 aika-2] (pvm/ennen? aika-1 aika-2))} ^{:nimi :mapit} [:aika :tunnit :tuntipalkka :yhteensa :kk-v]] :datan-kasittely (fn [vuoden-jh-korvaukset] (mapv (fn [rivi] (mapv (fn [[_ v]] v) rivi)) vuoden-jh-korvaukset)) :tunnisteen-kasittely (fn [data-sisalto-grid data] (vec (map-indexed (fn [i rivi] (vec (map-indexed (fn [j osa] (when (instance? g-pohjat/SyoteTaytaAlas osa) {:osa :tunnit :osan-paikka [i j] :toimenkuva toimenkuva :maksukausi maksukausi})) (grid/hae-grid rivi :lapset)))) (grid/hae-grid data-sisalto-grid :lapset))))}}))])) [0 {}] (t/pohjadatan-versio)) muokkauskasittelijat (second (reduce (fn [[rivi-index grid-kasittelijat] nimi-index] (let [rivin-nimi (t/jh-omienrivien-nimi nimi-index)] [(inc rivi-index) (merge grid-kasittelijat {[::g-pohjat/data rivi-index ::t/data-yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi) [::g-pohjat/data rivi-index ::t/data-sisalto] {:rajapinta (keyword (str "johto-ja-hallintokorvaus-" rivin-nimi)) :solun-polun-pituus 2 :jarjestys [{:keyfn :aika :comp (fn [aika-1 aika-2] (pvm/ennen? aika-1 aika-2))} ^{:nimi :mapit} [:aika :tunnit :tuntipalkka :yhteensa :maksukausi]] :datan-kasittely (fn [vuoden-jh-korvaukset] (mapv (fn [rivi] (mapv (fn [[_ v]] v) rivi)) vuoden-jh-korvaukset)) :tunnisteen-kasittely (fn [data-sisalto-grid data] (vec (map-indexed (fn [i rivi] (vec (map (fn [j osa] (when (instance? g-pohjat/SyoteTaytaAlas osa) {:osa :tunnit :osan-paikka [i j] :omanimi rivin-nimi})) (range) (grid/hae-grid rivi :lapset)))) (grid/hae-grid data-sisalto-grid :lapset))))}})])) [vakio-viimeinen-index {}] (range 1 (inc t/jh-korvausten-omiariveja-lkm))))] --- Datan käsittelijän ja grid - käsittelijän yhdistäminen -- (grid/rajapinta-grid-yhdistaminen! g # # # Rajapinta t/johto-ja-hallintokorvaus-rajapinta # # # Datan käsittelijä (t/johto-ja-hallintokorvaus-dr) # # # Grid käsittelijä (merge {[::g-pohjat/otsikko] {:rajapinta :otsikot :solun-polun-pituus 1 :jarjestys [^{:nimi :mapit} [:toimenkuva :tunnit :tuntipalkka :yhteensa :kk-v]] :datan-kasittely (fn [otsikot] (mapv (fn [otsikko] otsikko) (vals otsikot)))}} vakiokasittelijat muokkauskasittelijat)) --- Grid --- (grid/grid-tapahtumat g tila/suunnittelu-kustannussuunnitelma (merge { Disabloi toimenkuvan :johto-ja-hallintokorvaukset-disablerivit {:polut [[:gridit :johto-ja-hallintokorvaukset :kuukausitasolla?]] :toiminto! (fn [g _ kuukausitasolla-kaikki-toimenkuvat] (doseq [[toimenkuva maksukaudet-kuukausitasolla?] kuukausitasolla-kaikki-toimenkuvat] , niin kyseessä on oma / itsetäytettävärivi (when-not (and (string? toimenkuva) (re-find #"\d$" toimenkuva)) (doseq [[maksukausi kuukausitasolla?] maksukaudet-kuukausitasolla? :let [index (first (keep-indexed (fn [index jh-pohjadata] (when (and (= toimenkuva (:toimenkuva jh-pohjadata)) (= maksukausi (:maksukausi jh-pohjadata))) index)) (t/pohjadatan-versio)))]] (rividisable! g index kuukausitasolla?)))))} " ennen urakkaa"-rivit . VHAR-3127 :nayta-tai-piilota-ennen-urakkaa-rivit {:polut [[:suodattimet :hoitokauden-numero]] :toiminto! (fn [g _ hoitovuoden-nro] FIXME : : : t / data - yhteenveto ennen on . on vain taulukossa , pitäisi olla , varsinkin rivejä ... Yritin muuttaa : : t / data - yhteevedosta muuksi , jälkeen , joten en vienyt asiaa eteenpäin . NOTE : : : g - pohjat / data täytyy olla polun alussa , koska taulukko on luotu " g - pohjat / uusi - taulukko"-apufunktion avulla . : : g - pohjat / data alle . (let [rivi (grid/get-in-grid g [::g-pohjat/data ::t/data-yhteenveto]) Piilotetaan " Ennen urakkaa"-rivi mikäli hoitovuosi ei ole ensimmäinen . VHAR-3127 piilotetaan? (not= hoitovuoden-nro 1)] (when (grid/rivi? rivi) (if piilotetaan? (grid/piilota! rivi) (grid/nayta! rivi)) (t/paivita-raidat! g))))} :lisaa-yhteenvetorivi {:polut (reduce (fn [polut jarjestysnumero] (let [nimi (t/jh-omienrivien-nimi jarjestysnumero)] (conj polut [:domain :johto-ja-hallintokorvaukset nimi]))) [] (range 1 (inc t/jh-korvausten-omiariveja-lkm))) :toiminto! (fn [_ data & oma-data] (let [omien-rivien-tiedot (transduce (comp (map ffirst) (map-indexed #(assoc %2 :jarjestysnumero (inc %1)))) conj [] oma-data) lisatyt-rivit (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] #{})] (doseq [{:keys [toimenkuva toimenkuva-id jarjestysnumero]} omien-rivien-tiedot] (cond (and (not (contains? lisatyt-rivit toimenkuva-id)) (not (empty? toimenkuva))) (let [omanimi (t/jh-omienrivien-nimi jarjestysnumero) lisattava-rivi (grid/aseta-nimi (grid/samanlainen-osa (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [::g-pohjat/data 0])) omanimi) rivin-paikka-index (count (grid/hae-grid (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [::g-pohjat/data]) :lapset))] (e! (tuck-apurit/->PaivitaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] (fn [lisatyt-rivit] (conj (or lisatyt-rivit #{}) toimenkuva-id)))) (grid/lisaa-rivi! (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) lisattava-rivi [1 rivin-paikka-index]) (grid/lisaa-uuden-osan-rajapintakasittelijat (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [1 rivin-paikka-index]) [:. ::t/yhteenveto] {:rajapinta (keyword (str "yhteenveto-" omanimi)) :solun-polun-pituus 1 :datan-kasittely identity}) (t/paivita-raidat! (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]))) ;; -- (and (contains? lisatyt-rivit toimenkuva-id) (empty? toimenkuva)) (let [omanimi (t/jh-omienrivien-nimi jarjestysnumero) g (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) poistettava-rivi (grid/get-in-grid g [::g-pohjat/data omanimi])] (e! (tuck-apurit/->PaivitaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] (fn [lisatyt-rivit] (disj (or lisatyt-rivit #{}) toimenkuva-id)))) (grid/poista-osan-rajapintakasittelijat poistettava-rivi) (grid/poista-rivi! g poistettava-rivi)) :else nil))))}} (reduce (fn [polut jarjestysnumero] (let [nimi (t/jh-omienrivien-nimi jarjestysnumero)] (merge polut {(keyword "piilota-itsetaytettyja-riveja-" nimi) {:polut [[:gridit :johto-ja-hallintokorvaukset :yhteenveto nimi :maksukausi]] :toiminto! (fn [g _ maksukausi] (let [naytettavat-kuukaudet (into #{} (mhu/maksukausi->kuukaudet-range maksukausi))] (doseq [rivi (grid/hae-grid (grid/get-in-grid (grid/etsi-osa g nimi) [1]) :lapset)] (let [aika (grid/solun-arvo (grid/get-in-grid rivi [0])) piilotetaan? (and aika (not (contains? naytettavat-kuukaudet (pvm/kuukausi aika))))] (if piilotetaan? (grid/piilota! rivi) (grid/nayta! rivi)))) (t/paivita-raidat! (grid/osa-polusta g [::g-pohjat/data]))))} (keyword "omarivi-disable-" nimi) {:polut [[:domain :johto-ja-hallintokorvaukset nimi] [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? nimi]] :toiminto! (fn [g tila oma-jh-korvausten-tila kuukausitasolla?] (let [hoitokauden-numero (get-in tila [:suodattimet :hoitokauden-numero]) toimenkuva (get-in oma-jh-korvausten-tila [(dec hoitokauden-numero) 0 :toimenkuva]) index (dec (+ (count (t/pohjadatan-versio)) jarjestysnumero)) yhteenvetorivi (if (grid/rivi? (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0])) (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0]) (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto]))] (if (empty? toimenkuva) (do (ks-yhteiset/maara-solujen-disable! (grid/get-in-grid g [::g-pohjat/data index ::t/data-sisalto]) true) (disable-osa-indexissa! yhteenvetorivi #{1 2 4} true)) (do (rividisable! g (dec (+ (count (t/pohjadatan-versio)) jarjestysnumero)) kuukausitasolla?) (disable-osa-indexissa! yhteenvetorivi #{2 4} false)))))}}))) {} (range 1 (inc t/jh-korvausten-omiariveja-lkm))))) --- Triggeröi gridin luomisen ---- (grid/triggeroi-tapahtuma! g :nayta-tai-piilota-ennen-urakkaa-rivit) (grid/triggeroi-tapahtuma! g :johto-ja-hallintokorvaukset-disablerivit) ;; --- Palauta aina grid --- g)) (defn johto-ja-hallintokorvaus-laskulla-yhteenveto-grid [] (let [taulukon-id "johto-ja-hallintokorvaus-yhteenveto-taulukko" g (g-pohjat/uusi-taulukko {:header (-> (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :leveys 5 :luokat #{"table-default" "table-default-header" "lihavoitu"}})) (assoc-in [0 :leveys] 10) (assoc-in [1 :leveys] 4)) :body (mapv (fn [_] {:tyyppi :taulukko :osat [{:tyyppi :rivi :nimi ::t/yhteenveto :osat (cond-> (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/summa-formatointi-uusi})) true (assoc-in [0 :fmt] nil) (not (t/post-2022?)) (assoc-in [1 :fmt] (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))))}]}) (t/pohjadatan-versio)) :footer (let [osat (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :luokat #{"table-default" "table-default-sum"} :fmt ks-yhteiset/yhteenveto-format}))] (if-not (t/post-2022?) (assoc osat 1 {:tyyppi :tyhja :luokat #{"table-default" "table-default-sum"}}) osat)) :taulukon-id taulukon-id :root-asetus! (fn [g] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid] g))) :root-asetukset {:haku (fn [] (get-in @tila/suunnittelu-kustannussuunnitelma [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid])) :paivita! (fn [f] (swap! tila/suunnittelu-kustannussuunnitelma (fn [tila] (update-in tila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid] f))))}}) g (grid/lisaa-rivi! g (grid/rivi {:osat (let [osat (vec (repeatedly (if (t/post-2022?) 6 7) (fn [] (solu/teksti {:parametrit {:class #{"table-default" "table-default-sum" "harmaa-teksti"}} :fmt ks-yhteiset/yhteenveto-format}))))] (if-not (t/post-2022?) (update-in osat [1] gov/teksti->tyhja #{"table-default" "table-default-sum" "harmaa-teksti"}) osat)) :koko {:seuraa {:seurattava ::g-pohjat/otsikko :sarakkeet :sama :rivit :sama}} :nimi ::t/indeksikorjattu} [{:sarakkeet [0 (if (t/post-2022?) 6 7)] :rivit [0 1]}]) [3])] (grid/rajapinta-grid-yhdistaminen! g t/johto-ja-hallintokorvaus-yhteenveto-rajapinta (t/johto-ja-hallintokorvaus-yhteenveto-dr) (let [kuvaus (vec (concat [:toimenkuva] (when-not (t/post-2022?) [:kk-v]) [:hoitovuosi-1 :hoitovuosi-2 :hoitovuosi-3 :hoitovuosi-4 :hoitovuosi-5]))] (merge {[::g-pohjat/otsikko] {:rajapinta :otsikot :solun-polun-pituus 1 :jarjestys [(with-meta kuvaus {:nimi :mapit})] :datan-kasittely (fn [otsikot] (mapv (fn [otsikko] otsikko) (vals otsikot)))} [::g-pohjat/yhteenveto] {:rajapinta :yhteensa :solun-polun-pituus 1 :datan-kasittely identity} [::t/indeksikorjattu] {:rajapinta :indeksikorjattu :solun-polun-pituus 1 :datan-kasittely identity}} (second (reduce (fn [[index grid-kasittelijat] {:keys [toimenkuva maksukausi]}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] [(inc index) (merge grid-kasittelijat {[::g-pohjat/data index ::t/yhteenveto] {:rajapinta (keyword (str "yhteenveto" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :datan-kasittely identity}})])) [0 {}] (t/pohjadatan-versio)))))))) ;; | -- Gridit päättyy ;; ----- -- osion apufunktiot -- (defn johto-ja-hallintokorvaukset-yhteensa "Laskee yhteen 'johto-ja-hallintokorvaukset' yhteenvedon summat (eli käytännössä tuntipalkat) ja 'toimistokulut' yhteenvedon summat. Laskee yhteissumman joko annetulle hoitovuodelle tai annettujen summavektorien jokaiselle hoitovuodelle. Jos hoitovuotta ei anneta, palauttaa vektorin, jossa on summa jokaisesssa elementissä." ([johto-ja-hallintokorvaukset-summat toimistokulut-summat] (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-summat toimistokulut-summat nil)) ([johto-ja-hallintokorvaukset-summat toimistokulut-summat hoitokausi] (assert (or (nil? hoitokausi) (number? hoitokausi)) "Hoitokausi ei ole numero!") (assert (vector? johto-ja-hallintokorvaukset-summat) "johto-ja-hallintokorvaukset-summat täytyy olla vektori.") (assert (vector? toimistokulut-summat) "toimistokulut-summat täytyy olla vektori.") (if hoitokausi (let [hoitokausi-idx (dec hoitokausi)] (+ (nth johto-ja-hallintokorvaukset-summat hoitokausi-idx) (nth toimistokulut-summat hoitokausi-idx))) (mapv (fn [jh tk] (+ jh tk)) johto-ja-hallintokorvaukset-summat toimistokulut-summat)))) (defn- johto-ja-hallintokorvaus-yhteenveto [johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-indeksikorjattu toimistokulut-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] (if (and indeksit kantahaku-valmis?) (let [hinnat (mapv (fn [summa] {:summa summa}) (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-summat toimistokulut-summat)) hinnat-indeksikorjattu (mapv (fn [summa] {:summa summa}) (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-indeksikorjattu toimistokulut-indeksikorjattu))] [:div.summa-ja-indeksilaskuri [ks-yhteiset/hintalaskuri {:otsikko nil :selite "Palkat + Toimisto- ja ICT-kulut, tiedotus, opastus, kokousten järj. jne. + Hoito- ja korjaustöiden pientarvikevarasto" :hinnat hinnat :data-cy "johto-ja-hallintokorvaus-hintalaskuri"} kuluva-hoitokausi] [ks-yhteiset/indeksilaskuri-ei-indeksikorjausta hinnat-indeksikorjattu indeksit {:data-cy "johto-ja-hallintokorvaus-indeksilaskuri"}]]) [yleiset/ajax-loader])) (defn- laske-vuoden-summa [hoitokauden-kuukausittaiset-summat] (let [summat-vuodelle (map #(-> % second :kuukausipalkka) hoitokauden-kuukausittaiset-summat)] (reduce + 0 summat-vuodelle))) (defn formatoi-kuukausi [vuosi kuukausi] (let [tanaan (pvm/nyt)] (str (get {1 "Tammikuu" 2 "Helmikuu" 3 "Maaliskuu" 4 "Huhtikuu" 5 "Toukokuu" 6 "Kesäkuu" 7 "Heinäkuu" 8 "Elokuu" 9 "Syyskuu" 10 "Lokakuu" 11 "Marraskuu" 12 "Joulukuu"} kuukausi) " " (if (> kuukausi 9) vuosi (inc vuosi)) (when (or (< (inc vuosi) (-> tanaan pvm/vuosi)) (and (= (inc vuosi) (-> tanaan pvm/vuosi)) (or (< kuukausi (-> tanaan pvm/kuukausi)) (< 9 kuukausi ))) (and (= vuosi (-> tanaan pvm/vuosi)) (and (< kuukausi (-> tanaan pvm/kuukausi)) (< 9 kuukausi)))) " (mennyt)")))) (defn- kun-erikseen-syotettava-checkbox-klikattu [checkbox-tila] @checkbox-tila) (defn- jaa-vuosipalkka-kuukausille [hoitokausi kopioi-tuleville? ennen-urakkaa? toimenkuvan-maarat vuosipalkka] (if ennen-urakkaa? ennen lokakuulle (let [kuukausipalkka (tyokalut/round2 2 (/ vuosipalkka 12)) viimeinen-kuukausi (if-not (= vuosipalkka (* 12 kuukausipalkka)) (tyokalut/round2 2 (- vuosipalkka (tyokalut/round2 2 (* 11 kuukausipalkka)))) kuukausipalkka) alkuvuosi (-> tila/yleiset deref :urakka :alkupvm pvm/vuosi) loppuvuosi (-> tila/yleiset deref :urakka :loppupvm pvm/vuosi) loppukausi (inc (if kopioi-tuleville? (- loppuvuosi alkuvuosi) hoitokausi)) kaudet (into [] (range hoitokausi loppukausi)) aseta-kuukausipalkka (map (fn [[kuukausi tiedot]] [kuukausi (assoc tiedot :kuukausipalkka (if (= 9 kuukausi) viimeinen-kuukausi kuukausipalkka))])) paivita-vuoden-tiedot (fn [kkt] (into {} aseta-kuukausipalkka kkt)) paivitysfunktiot (mapv #(fn [maarat] (update maarat % paivita-vuoden-tiedot)) kaudet) paivita (apply comp paivitysfunktiot)] (paivita toimenkuvan-maarat)))) (defn- tallenna-vuosipalkka [atomi {:keys [hoitokausi kopioi-tuleville?]} rivi] (let [toimenkuvan-maarat (get-in rivi [:maksuerat-per-hoitovuosi-per-kuukausi]) paivitetyt (jaa-vuosipalkka-kuukausille hoitokausi kopioi-tuleville? (:ennen-urakkaa? rivi) toimenkuvan-maarat (:vuosipalkka rivi)) rivi (assoc rivi :maksuerat-per-hoitovuosi-per-kuukausi paivitetyt) tiedot @atomi tiedot-muuttuneet? (not= (get tiedot (:tunniste rivi)) rivi) tiedot (assoc-in tiedot [(:tunniste rivi) :maksuerat-per-hoitovuosi-per-kuukausi] paivitetyt) _ (reset! atomi tiedot)] (when tiedot-muuttuneet? (e! (t/->TallennaJHOToimenkuvanVuosipalkka rivi))))) (defn- paivita-toimenkuvan-vuosiloota [hoitokausi [toimenkuva toimenkuvan-tiedot]] (let [vuoden-summa (laske-vuoden-summa (get-in toimenkuvan-tiedot [:maksuerat-per-hoitovuosi-per-kuukausi hoitokausi]))] [toimenkuva (assoc toimenkuvan-tiedot :vuosipalkka vuoden-summa)])) (defn- paivita-vuosilootat [tiedot hoitokausi] (into {} (map (r/partial paivita-toimenkuvan-vuosiloota hoitokausi)) tiedot)) (defn- tallenna-kuukausipalkka [tiedot-atom {:keys [alkuvuosi loppuvuosi hoitokausi kopioi-tuleville?]} rivi] (let [tiedot @tiedot-atom loppukausi (inc (if kopioi-tuleville? (- loppuvuosi alkuvuosi) hoitokausi)) kaudet (into [] (range hoitokausi loppukausi)) erat (get tiedot :maksuerat-per-hoitovuosi-per-kuukausi) paivitysfunktiot (mapv (fn [kausi] (fn [maarat] (assoc-in maarat [kausi (:kuukausi rivi) :kuukausipalkka] (:kuukausipalkka rivi)))) kaudet) vuosipalkka (reduce (fn [summa kuukauden-arvot] (if (not (nil? (:kuukausipalkka (second kuukauden-arvot)))) (+ summa (:kuukausipalkka (second kuukauden-arvot))) summa)) 0 (get erat hoitokausi)) paivita (apply comp paivitysfunktiot) paivitetyt (paivita erat) tiedot (assoc tiedot :vuosipalkka vuosipalkka) toimenkuvan-tiedot (assoc tiedot :maksuerat-per-hoitovuosi-per-kuukausi paivitetyt) _ (reset! tiedot-atom toimenkuvan-tiedot)] Atomin päivittämisessä menee joitakin millisekunteja . Siksi viive (e! (t/->TallennaJHOToimenkuvanVuosipalkka toimenkuvan-tiedot)))) (defn- jarjesta-hoitovuoden-jarjestykseen "Järjestys lokakuusta seuraavan vuoden syyskuuhun" [{:keys [kuukausi]}] (if (> kuukausi 9) (- kuukausi 12) kuukausi)) (defn- luo-kursori [atomi toimenkuva polku hoitokausi] (r/cursor atomi [toimenkuva polku hoitokausi])) (defn- kursorit-polulle [polku tiedot toimenkuva vuosien-erotus] (into {} (map (juxt identity (r/partial luo-kursori tiedot toimenkuva polku))) (range 1 vuosien-erotus))) (defn- palkkakentta-muokattava? [erikseen-syotettava? tiedot hoitokausi] (and @erikseen-syotettava? (or (and (:ennen-urakkaa? tiedot) (= 1 hoitokausi)) (false? (:ennen-urakkaa? tiedot))))) (defn- vetolaatikko-klikattu-fn [atomi tallenna-fn rivi-atom event] (let [valittu? (-> event .-target .-checked)] (when (and @atomi (not valittu?)) (tallenna-fn @rivi-atom)) (reset! atomi valittu?))) (defn- vetolaatikko-komponentti [tiedot-atomi polku {:keys [tunniste] :as rivi} tallenna-fn_ kuluva-hoitokausi_] (let [suodattimet (r/cursor tila/suunnittelu-kustannussuunnitelma [:suodattimet]) urakan-alkuvuosi (-> tila/yleiset deref :urakka :alkupvm pvm/vuosi) urakan-loppuvuosi (-> tila/yleiset deref :urakka :loppupvm pvm/vuosi) vuosien-erotus (- urakan-loppuvuosi urakan-alkuvuosi) kursorit (assoc {} :toimenkuva (r/cursor tiedot-atomi [tunniste]) :maksuerat (kursorit-polulle :maksuerat-per-hoitovuosi-per-kuukausi tiedot-atomi polku vuosien-erotus) :erikseen-syotettava? (kursorit-polulle :erikseen-syotettava? tiedot-atomi polku vuosien-erotus))] (fn [_ polku rivi tallenna-fn kuluva-hoitokausi] (let [{kopioi-tuleville? :kopioidaan-tuleville-vuosille?} @suodattimet valitun-hoitokauden-alkuvuosi (-> @tila/yleiset :urakka :alkupvm pvm/vuosi (+ (dec kuluva-hoitokausi))) maksuerat (get-in kursorit [:maksuerat kuluva-hoitokausi])] [:div [kentat/tee-kentta {:tyyppi :checkbox :teksti "Suunnittele maksuerät kuukausittain" :valitse! (partial vetolaatikko-klikattu-fn (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi]) tallenna-fn (get-in kursorit [:toimenkuva]))} (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi])] [:div.vetolaatikko-border {:style {:border-left "4px solid lightblue" :margin-top "16px" :padding-left "18px"}} [vanha-grid/muokkaus-grid {:id (str polku valitun-hoitokauden-alkuvuosi) :voi-poistaa? (constantly false) :voi-lisata? false :piilota-toiminnot? true :muokkauspaneeli? false :jarjesta jarjesta-hoitovuoden-jarjestykseen :piilota-table-header? true :on-rivi-blur (r/partial tallenna-kuukausipalkka (get kursorit :toimenkuva) {:hoitokausi kuluva-hoitokausi :kopioi-tuleville? kopioi-tuleville? :alkuvuosi urakan-alkuvuosi :loppuvuosi urakan-loppuvuosi}) :voi-kumota? false} [{:nimi :kuukausi :tyyppi :string :muokattava? (constantly false) :leveys "85%" :fmt (r/partial formatoi-kuukausi valitun-hoitokauden-alkuvuosi)} {:nimi :kuukausipalkka :tyyppi :numero :leveys "15%" :muokattava? #(palkkakentta-muokattava? (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi]) rivi kuluva-hoitokausi)}] maksuerat]]])))) (defn luo-vetolaatikot [atomi tallenna-fn kuluva-hoitokausi] (into {} (map (juxt first #(let [rivi (second %) polku (:tunniste rivi)] [vetolaatikko-komponentti atomi polku rivi tallenna-fn kuluva-hoitokausi]))) (into {} (filter #(let [data (second %)] (not (or (:ennen-urakkaa? data) (get (:hoitokaudet data) 0))))) @atomi))) (defn- kun-ei-syoteta-erikseen [hoitokausi tiedot] (and (not (get-in tiedot [:erikseen-syotettava? hoitokausi])) (or (and (:ennen-urakkaa? tiedot) (= 1 hoitokausi)) (false? (:ennen-urakkaa? tiedot))))) (defn tallenna-toimenkuvan-tiedot [data-atomi optiot rivin-tiedot] (when (:oma-toimenkuva? rivin-tiedot) (let [uusi-toimenkuva-nimi (:toimenkuva rivin-tiedot) rivin-nimi (:rivin-nimi rivin-tiedot)] , niin vaihdetaan se FIXME : , joten tätä . , koska ei ole . (when (not= uusi-toimenkuva-nimi rivin-nimi) (e! (t/->VaihdaOmanToimenkuvanNimi rivin-tiedot)) (e! (t/->TallennaToimenkuva (:tunniste rivin-tiedot)))))) (tallenna-vuosipalkka data-atomi optiot rivin-tiedot)) (defn taulukko-2022-eteenpain [app] (let [kaytetty-hoitokausi (r/atom (-> app :suodattimet :hoitokauden-numero)) data (t/konvertoi-jhk-data-taulukolle (get-in app [:domain :johto-ja-hallintokorvaukset]) @kaytetty-hoitokausi)] (fn [app] (let [kuluva-hoitokausi (-> app :suodattimet :hoitokauden-numero) kopioidaan-tuleville-vuosille? (-> app :suodattimet :kopioidaan-tuleville-vuosille?) tallenna-fn (r/partial tallenna-toimenkuvan-tiedot data {:hoitokausi kuluva-hoitokausi :kopioi-tuleville? kopioidaan-tuleville-vuosille?}) vetolaatikot (luo-vetolaatikot data tallenna-fn @kaytetty-hoitokausi)] (when-not (= kuluva-hoitokausi @kaytetty-hoitokausi) (swap! data paivita-vuosilootat kuluva-hoitokausi) (reset! kaytetty-hoitokausi kuluva-hoitokausi)) [:div Kaikille yhteiset toimenkuvat [vanha-grid/muokkaus-grid {:otsikko "Tuntimäärät ja -palkat" :id "toimenkuvat-taulukko" :luokat ["poista-bottom-margin"] :voi-lisata? false :voi-kumota? false :muutos (fn [g] (when-not (= @kaytetty-hoitokausi kuluva-hoitokausi) (vanha-grid/sulje-vetolaatikot! g))) :jarjesta :jarjestys :piilota-toiminnot? true :on-rivi-blur tallenna-fn :voi-poistaa? (constantly false) :piilota-rivi #(and (not (= kuluva-hoitokausi 1)) (:ennen-urakkaa? %)) :vetolaatikot vetolaatikot} [{:otsikko "Toimenkuva" :nimi :toimenkuva :tyyppi :string :muokattava? :oma-toimenkuva? :leveys "80%" :fmt clj-str/capitalize :placeholder "Kirjoita muu toimenkuva"} {:otsikko "" :tyyppi :vetolaatikon-tila :leveys "5%" :muokattava? (constantly false)} {:otsikko "Vuosipalkka, €" :nimi :vuosipalkka :desimaalien-maara 2 :tyyppi :numero :muokattava? (r/partial kun-ei-syoteta-erikseen kuluva-hoitokausi) :leveys "15%"}] data]])))) (defn- johto-ja-hallintokorvaus [app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [:<> [:h2 {:id (str (get t/hallinnollisten-idt :johto-ja-hallintokorvaus) "-osio")} "Johto- ja hallintokorvaus"] [johto-ja-hallintokorvaus-yhteenveto johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [:h3 "Tuntimäärät ja -palkat"] [:div {:data-cy "tuntimaarat-ja-palkat-taulukko-suodattimet"} [ks-yhteiset/yleis-suodatin suodattimet]] (cond (and johto-ja-hallintokorvaus-grid kantahaku-valmis? (not (t/post-2022?))) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra johto-ja-hallintokorvaus-grid]] (and (t/post-2022?) johto-ja-hallintokorvaus-grid kantahaku-valmis?) [:div.johto-ja-hallintokorvaukset {:class (when vahvistettu? "osio-vahvistettu")} [taulukko-2022-eteenpain app]] :else [yleiset/ajax-loader]) (if (and johto-ja-hallintokorvaus-yhteenveto-grid kantahaku-valmis?) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra johto-ja-hallintokorvaus-yhteenveto-grid]] [yleiset/ajax-loader]) Johto ja hallinto : Muut kulut -taulukko [:h3 {:id (str (get t/hallinnollisten-idt :toimistokulut) "-osio")} "Johto ja hallinto: muut kulut"] [:div {:data-cy "johto-ja-hallinto-muut-kulut-taulukko-suodattimet"} [ks-yhteiset/yleis-suodatin suodattimet]] Note : " Muut kulut " taulukko on hämäävästi toimistokulut - grid . " toimistokulut " , niin kannattaa harkita gridin . on vähän työlästä , gridin viitataan : toimistokulut - keywordillä . (if (and toimistokulut-grid kantahaku-valmis?) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra toimistokulut-grid]] [yleiset/ajax-loader]) [:span "Yhteenlaskettu kk-määrä: Toimisto- ja ICT-kulut, tiedotus, opastus, kokousten ja vierailujen järjestäminen sekä tarjoilukulut + Hoito- ja korjaustöiden pientarvikevarasto (työkalut, mutterit, lankut, naulat jne.)"]]) # # # Johto- ja hallintokorvaus osion pääkomponentti # # # FIXME : Arvojen tallentamisessa on jokin häikkä . Tallennus ei onnistu . ( ositustakin ) (defn osio [app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [johto-ja-hallintokorvaus app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?])
null
https://raw.githubusercontent.com/finnishtransportagency/harja/6170c269fefe11ce5bf93932e85b5c9a9edb4879/src/cljs/harja/views/urakka/suunnittelu/kustannussuunnitelma/johto_ja_hallintokorvaus_osio.cljs
clojure
jh-yhteenvetopaivitys -funktiolle parametreiksi. :oma = itselisätyn toimenkuvan nimi-solu Tuntipalkka-solu Pudotusvalikko-solu -- --- Palauta aina grid --- | -- Gridit päättyy -----
(ns harja.views.urakka.suunnittelu.kustannussuunnitelma.johto-ja-hallintokorvaus-osio (:require [reagent.core :as r] [harja.tiedot.urakka.suunnittelu.mhu-kustannussuunnitelma :as t] [harja.ui.taulukko.grid :as grid] [harja.ui.yleiset :as yleiset] [harja.ui.kentat :as kentat] [harja.tyokalut.yleiset :as tyokalut] [harja.views.urakka.suunnittelu.kustannussuunnitelma.yhteiset :as ks-yhteiset :refer [e!]] [harja.tyokalut.tuck :as tuck-apurit] [harja.ui.taulukko.impl.solu :as solu] [harja.ui.taulukko.grid-pohjat :as g-pohjat] [harja.fmt :as fmt] [clojure.string :as clj-str] [harja.ui.modal :as modal] [harja.tiedot.urakka.urakka :as tila] [harja.pvm :as pvm] [harja.ui.grid :as vanha-grid] [harja.ui.taulukko.grid-osan-vaihtaminen :as gov] [harja.views.urakka.suunnittelu.kustannussuunnitelma.grid-apurit :as grid-apurit] [harja.domain.mhu :as mhu])) -- gridit -- (def toimistokulut-grid (partial grid-apurit/maarataulukko-grid "toimistokulut" [:yhteenvedot :johto-ja-hallintokorvaukset] {:tallennus-onnistui-event t/->TallennaToimistokulutOnnistui})) (defn- yhteenveto-grid-rajapinta-asetukset [toimenkuva maksukausi data-koskee-ennen-urakkaa?] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi) kuvaus (vec (concat [:toimenkuva :tunnit :tuntipalkka :yhteensa] (when-not (t/post-2022?) [:kk-v])))] {:rajapinta (keyword (str "yhteenveto" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :jarjestys [(with-meta kuvaus {:nimi :mapit})] :datan-kasittely (fn [yhteenveto] (mapv (fn [[_ v]] v) yhteenveto)) :tunnisteen-kasittely (fn [osat data] (second (reduce (fn [[loytynyt? tunnisteet] osa] (let [syote-osa? (instance? solu/Syote osa) osa (when syote-osa? (if loytynyt? :tuntipalkka :tunnit)) Note : Nämä tiedot valuvat jotenkin : aseta - jh - yhteenveto ! tunniste {:osa osa :toimenkuva toimenkuva :maksukausi maksukausi :data-koskee-ennen-urakkaa? data-koskee-ennen-urakkaa?}] [(or loytynyt? syote-osa?) (conj tunnisteet tunniste)])) [false []] (grid/hae-grid osat :lapset))))})) (defn- muokkausrivien-rajapinta-asetukset [nimi] {:rajapinta (keyword (str "yhteenveto-" nimi)) :solun-polun-pituus 1 :jarjestys [^{:nimi :mapit} [:toimenkuva :tunnit :tuntipalkka :yhteensa :maksukausi]] :datan-kasittely (fn [yhteenveto] (mapv (fn [[_ v]] v) yhteenveto)) :tunnisteen-kasittely (fn [_ _] (mapv (fn [index] (assoc (case index 0 {:osa :toimenkuva} 1 {:osa :tunnit} 2 {:osa :tuntipalkka} 3 {:osa :yhteensa} 4 {:osa :maksukausi}) :omanimi nimi)) (range 5)))}) (defn- blur-tallenna! ([tallenna-kaikki? etsittava-osa solu] (blur-tallenna! tallenna-kaikki? etsittava-osa solu nil)) ([tallenna-kaikki? etsittava-osa solu muutos] (if tallenna-kaikki? (e! (t/->TallennaJohtoJaHallintokorvaukset (mapv #(grid/solun-asia (get (grid/hae-grid % :lapset) 1) :tunniste-rajapinnan-dataan) (grid/hae-grid (get (grid/hae-grid (grid/etsi-osa (grid/root solu) etsittava-osa) :lapset) 1) :lapset)))) (e! (t/->TallennaJohtoJaHallintokorvaukset [(grid/solun-asia solu :tunniste-rajapinnan-dataan)]))))) (defn- nappia-painettu-tallenna! ([rivit-alla] (nappia-painettu-tallenna! rivit-alla nil)) ([rivit-alla muutos] (e! (t/->TallennaJohtoJaHallintokorvaukset (vec (keep (fn [rivi] (let [haettu-solu (grid/get-in-grid rivi [1]) piilotettu? (grid/piilotettu? rivi)] (when-not piilotettu? (grid/solun-asia haettu-solu :tunniste-rajapinnan-dataan)))) rivit-alla)))))) (defn- rividisable! [g index kuukausitasolla?] (ks-yhteiset/maara-solujen-disable! (grid/get-in-grid g [::g-pohjat/data index ::t/data-sisalto]) (not kuukausitasolla?)) (ks-yhteiset/maara-solujen-disable! (if-let [osa (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0 1])] osa (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 1])) kuukausitasolla?)) (defn- disable-osa-indexissa! [rivi indexit disabled?] (grid/paivita-grid! rivi :lapset (fn [osat] (vec (map-indexed (fn [index solu] (if (contains? indexit index) (if (grid/pudotusvalikko? solu) (assoc-in solu [:livi-pudotusvalikko-asetukset :disabled?] disabled?) (assoc-in solu [:parametrit :disabled?] disabled?)) solu)) osat))))) (defn johto-ja-hallintokorvaus-laskulla-grid [] (let [taulukon-id "johto-ja-hallintokorvaus-laskulla-taulukko" vakiorivit (mapv (fn [{:keys [toimenkuva maksukausi hoitokaudet] :as toimenkuva-kuvaus}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] (if (t/toimenpide-koskee-ennen-urakkaa? hoitokaudet) {:tyyppi :rivi :nimi ::t/data-yhteenveto :osat [{:tyyppi :teksti :luokat #{"table-default"}} (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! false nil)}) (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! false nil)}) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} {:tyyppi :teksti :luokat #{"table-default"} :fmt (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))}]} {:tyyppi :taulukko :nimi (str toimenkuva "-" maksukausi "-taulukko") :osat [{:tyyppi :rivi :nimi ::t/data-yhteenveto :osat [{:tyyppi :laajenna :aukaise-fn (fn [this auki?] (if auki? (ks-yhteiset/rivi-kuukausifiltterilla! this true (keyword (str "kuukausitasolla?" yksiloiva-nimen-paate)) [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? toimenkuva maksukausi] [:. ::t/yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false) [:. ::t/valinta] {:rajapinta (keyword (str "kuukausitasolla?" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :datan-kasittely (fn [kuukausitasolla?] [kuukausitasolla? nil nil nil])}) (do (ks-yhteiset/rivi-ilman-kuukausifiltteria! this [:.. ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false)) (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? toimenkuva maksukausi] false)))) (t/laajenna-solua-klikattu this auki? taulukon-id [::g-pohjat/data] {:sulkemis-polku [:.. :.. :.. 1]})) :auki-alussa? false :luokat #{"table-default"}} (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true (str toimenkuva "-" maksukausi "-taulukko"))}) (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true (str toimenkuva "-" maksukausi "-taulukko"))}) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} {:tyyppi :teksti :luokat #{"table-default"} :fmt (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))}]} {:tyyppi :taulukko :nimi ::t/data-sisalto :luokat #{"piilotettu"} :osat (vec (repeatedly (t/kk-v-toimenkuvan-kuvaukselle toimenkuva-kuvaus) (fn [] {:tyyppi :rivi :osat [{:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/aika-tekstilla-fmt} (ks-yhteiset/syote-solu {:nappi? true :fmt ks-yhteiset/summa-formatointi-uusi :paivitettava-asia :aseta-tunnit! :solun-index 1 :blur-tallenna! (partial blur-tallenna! false (str toimenkuva "-" maksukausi "-taulukko")) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) {:tyyppi :tyhja} {:tyyppi :tyhja} {:tyyppi :tyhja}]})))}]}))) (t/pohjadatan-versio)) muokattavat-rivit (mapv (fn [index] (let [rivin-nimi (t/jh-omienrivien-nimi index)] rivi ( sisältää alitaulukon ) {:tyyppi :taulukko :nimi rivin-nimi :osat [{:tyyppi :rivi :nimi ::t/data-yhteenveto :osat [{:tyyppi :oma :constructor (fn [_] (ks-yhteiset/laajenna-syote (fn [this auki?] (if auki? (ks-yhteiset/rivi-kuukausifiltterilla! this true (keyword (str "kuukausitasolla?-" rivin-nimi)) [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? rivin-nimi] [:. ::t/yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi) [:. ::t/valinta] {:rajapinta (keyword (str "kuukausitasolla?-" rivin-nimi)) :solun-polun-pituus 1 :datan-kasittely (fn [kuukausitasolla?] [kuukausitasolla? nil nil nil])}) (do (ks-yhteiset/rivi-ilman-kuukausifiltteria! this [:.. ::t/data-yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi)) (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? rivin-nimi] false)))) (t/laajenna-solua-klikattu this auki? taulukon-id [::g-pohjat/data] {:sulkemis-polku [:.. :.. :.. 1]})) false {:on-change (fn [arvo] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo arvo :solu solu/*this* :ajettavat-jarjestykset #{:mapit}} false)) :on-blur (fn [arvo] (let [arvo (if (= "" (clj-str/trim arvo)) nil arvo) solu solu/*this* paivita-ui! (fn [] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo arvo :solu solu :ajettavat-jarjestykset true :triggeroi-seuranta? true} true)) paivita-kanta! (fn [] (e! (t/->TallennaToimenkuva rivin-nimi))) paivita! (fn [] (paivita-ui!) (paivita-kanta!)) peruuta! (fn [vanha-arvo] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :yhteenveto rivin-nimi :toimenkuva] vanha-arvo)))] Jos custom toimenkuvan nimi pyyhitään , niin täytyy triggeröidä toimenkuvaan liittyvän datan poisto tietokannasta . (if (nil? arvo) (let [paivita-seuraavalla-tickilla! (fn [] (r/next-tick paivita!))] (e! (t/->PoistaOmaJHDdata :toimenkuva rivin-nimi Poistetaan data kaikilta maksukausilta modal/piilota! paivita-seuraavalla-tickilla! (fn [toimenkuva data-hoitokausittain poista! vanhat-arvot] (ks-yhteiset/poista-modal! :toimenkuva data-hoitokausittain poista! {:toimenkuva toimenkuva} (partial peruuta! (some :toimenkuva vanhat-arvot))))))) (paivita!)))) :on-key-down (fn [event] (when (= "Enter" (.. event -key)) (.. event -target blur)))} {:on-change [:eventin-arvo] :on-blur [:eventin-arvo]} {:class #{"input-default"} :placeholder "Kirjoita muu toimenkuva"} identity identity)) :auki-alussa? false :luokat #{"table-default"}} Tunnit - solu (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) (ks-yhteiset/syote-solu {:nappi? false :fmt ks-yhteiset/yhteenveto-format :paivitettava-asia :aseta-jh-yhteenveto! :blur-tallenna! (partial blur-tallenna! true rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) Yhteenveto - solu ( Yhteensä / kk ) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/yhteenveto-format} {:tyyppi :pudotusvalikko :data-cy "kk-v-valinnat" :valitse-fn (fn [maksukausi] (let [solu solu/*this* paivita-ui! (fn [] (t/paivita-solun-arvo {:paivitettava-asia :aseta-jh-yhteenveto! :arvo maksukausi :solu solu :ajettavat-jarjestykset true :triggeroi-seuranta? true} false))] NOTE : , että maksukausi on varmasti solu on käytössä tallenna - funktiossa . (if (= :molemmat maksukausi) (do (paivita-ui!) (blur-tallenna! true rivin-nimi solu)) (e! (t/->PoistaOmaJHDdata :maksukausi rivin-nimi maksukausi modal/piilota! #(r/next-tick paivita-ui!) (fn [toimenkuva data-hoitokausittain poista! _] (ks-yhteiset/poista-modal! :toimenkuva data-hoitokausittain poista! {:toimenkuva toimenkuva}))))))) :format-fn (fn [teksti] (str (mhu/maksukausi->kuukausien-lkm teksti))) :rivin-haku (fn [pudotusvalikko] (grid/osa-polusta pudotusvalikko [:.. :..])) :vayla-tyyli? true :vaihtoehdot t/kk-v-valinnat}]} {:tyyppi :taulukko :nimi ::t/data-sisalto :luokat #{"piilotettu"} :osat (vec (repeatedly 12 (fn [] {:tyyppi :rivi :osat [{:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/aika-tekstilla-fmt} (ks-yhteiset/syote-solu {:nappi? true :fmt ks-yhteiset/summa-formatointi-uusi :paivitettava-asia :aseta-tunnit! :solun-index 1 :blur-tallenna! (partial blur-tallenna! false rivin-nimi) :nappia-painettu-tallenna! nappia-painettu-tallenna!}) {:tyyppi :tyhja} {:tyyppi :tyhja} {:tyyppi :tyhja}]})))}]})) (range 1 (inc t/jh-korvausten-omiariveja-lkm))) g (g-pohjat/uusi-taulukko {:header [{:tyyppi :teksti :leveys 4 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 3 :luokat #{"table-default" "table-default-header" "lihavoitu"}} {:tyyppi :teksti :leveys 1 :luokat #{"table-default" "table-default-header" "lihavoitu"}}] :body (vec (concat vakiorivit muokattavat-rivit)) :taulukon-id taulukon-id :root-luokat #{"salli-ylipiirtaminen"} :root-asetus! (fn [g] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset :grid] g))) :root-asetukset {:haku (fn [] (get-in @tila/suunnittelu-kustannussuunnitelma [:gridit :johto-ja-hallintokorvaukset :grid])) :paivita! (fn [f] (swap! tila/suunnittelu-kustannussuunnitelma (fn [tila] (update-in tila [:gridit :johto-ja-hallintokorvaukset :grid] f))))}}) [vakio-viimeinen-index vakiokasittelijat] (reduce (fn [[index grid-kasittelijat] {:keys [toimenkuva maksukausi hoitokaudet]}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] [(inc index) (merge grid-kasittelijat (if (t/toimenpide-koskee-ennen-urakkaa? hoitokaudet) {[::g-pohjat/data ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi true)} {[::g-pohjat/data index ::t/data-yhteenveto] (yhteenveto-grid-rajapinta-asetukset toimenkuva maksukausi false) [::g-pohjat/data index ::t/data-sisalto] {:rajapinta (keyword (str "johto-ja-hallintokorvaus" yksiloiva-nimen-paate)) :solun-polun-pituus 2 :jarjestys [{:keyfn :aika :comp (fn [aika-1 aika-2] (pvm/ennen? aika-1 aika-2))} ^{:nimi :mapit} [:aika :tunnit :tuntipalkka :yhteensa :kk-v]] :datan-kasittely (fn [vuoden-jh-korvaukset] (mapv (fn [rivi] (mapv (fn [[_ v]] v) rivi)) vuoden-jh-korvaukset)) :tunnisteen-kasittely (fn [data-sisalto-grid data] (vec (map-indexed (fn [i rivi] (vec (map-indexed (fn [j osa] (when (instance? g-pohjat/SyoteTaytaAlas osa) {:osa :tunnit :osan-paikka [i j] :toimenkuva toimenkuva :maksukausi maksukausi})) (grid/hae-grid rivi :lapset)))) (grid/hae-grid data-sisalto-grid :lapset))))}}))])) [0 {}] (t/pohjadatan-versio)) muokkauskasittelijat (second (reduce (fn [[rivi-index grid-kasittelijat] nimi-index] (let [rivin-nimi (t/jh-omienrivien-nimi nimi-index)] [(inc rivi-index) (merge grid-kasittelijat {[::g-pohjat/data rivi-index ::t/data-yhteenveto] (muokkausrivien-rajapinta-asetukset rivin-nimi) [::g-pohjat/data rivi-index ::t/data-sisalto] {:rajapinta (keyword (str "johto-ja-hallintokorvaus-" rivin-nimi)) :solun-polun-pituus 2 :jarjestys [{:keyfn :aika :comp (fn [aika-1 aika-2] (pvm/ennen? aika-1 aika-2))} ^{:nimi :mapit} [:aika :tunnit :tuntipalkka :yhteensa :maksukausi]] :datan-kasittely (fn [vuoden-jh-korvaukset] (mapv (fn [rivi] (mapv (fn [[_ v]] v) rivi)) vuoden-jh-korvaukset)) :tunnisteen-kasittely (fn [data-sisalto-grid data] (vec (map-indexed (fn [i rivi] (vec (map (fn [j osa] (when (instance? g-pohjat/SyoteTaytaAlas osa) {:osa :tunnit :osan-paikka [i j] :omanimi rivin-nimi})) (range) (grid/hae-grid rivi :lapset)))) (grid/hae-grid data-sisalto-grid :lapset))))}})])) [vakio-viimeinen-index {}] (range 1 (inc t/jh-korvausten-omiariveja-lkm))))] --- Datan käsittelijän ja grid - käsittelijän yhdistäminen -- (grid/rajapinta-grid-yhdistaminen! g # # # Rajapinta t/johto-ja-hallintokorvaus-rajapinta # # # Datan käsittelijä (t/johto-ja-hallintokorvaus-dr) # # # Grid käsittelijä (merge {[::g-pohjat/otsikko] {:rajapinta :otsikot :solun-polun-pituus 1 :jarjestys [^{:nimi :mapit} [:toimenkuva :tunnit :tuntipalkka :yhteensa :kk-v]] :datan-kasittely (fn [otsikot] (mapv (fn [otsikko] otsikko) (vals otsikot)))}} vakiokasittelijat muokkauskasittelijat)) --- Grid --- (grid/grid-tapahtumat g tila/suunnittelu-kustannussuunnitelma (merge { Disabloi toimenkuvan :johto-ja-hallintokorvaukset-disablerivit {:polut [[:gridit :johto-ja-hallintokorvaukset :kuukausitasolla?]] :toiminto! (fn [g _ kuukausitasolla-kaikki-toimenkuvat] (doseq [[toimenkuva maksukaudet-kuukausitasolla?] kuukausitasolla-kaikki-toimenkuvat] , niin kyseessä on oma / itsetäytettävärivi (when-not (and (string? toimenkuva) (re-find #"\d$" toimenkuva)) (doseq [[maksukausi kuukausitasolla?] maksukaudet-kuukausitasolla? :let [index (first (keep-indexed (fn [index jh-pohjadata] (when (and (= toimenkuva (:toimenkuva jh-pohjadata)) (= maksukausi (:maksukausi jh-pohjadata))) index)) (t/pohjadatan-versio)))]] (rividisable! g index kuukausitasolla?)))))} " ennen urakkaa"-rivit . VHAR-3127 :nayta-tai-piilota-ennen-urakkaa-rivit {:polut [[:suodattimet :hoitokauden-numero]] :toiminto! (fn [g _ hoitovuoden-nro] FIXME : : : t / data - yhteenveto ennen on . on vain taulukossa , pitäisi olla , varsinkin rivejä ... Yritin muuttaa : : t / data - yhteevedosta muuksi , jälkeen , joten en vienyt asiaa eteenpäin . NOTE : : : g - pohjat / data täytyy olla polun alussa , koska taulukko on luotu " g - pohjat / uusi - taulukko"-apufunktion avulla . : : g - pohjat / data alle . (let [rivi (grid/get-in-grid g [::g-pohjat/data ::t/data-yhteenveto]) Piilotetaan " Ennen urakkaa"-rivi mikäli hoitovuosi ei ole ensimmäinen . VHAR-3127 piilotetaan? (not= hoitovuoden-nro 1)] (when (grid/rivi? rivi) (if piilotetaan? (grid/piilota! rivi) (grid/nayta! rivi)) (t/paivita-raidat! g))))} :lisaa-yhteenvetorivi {:polut (reduce (fn [polut jarjestysnumero] (let [nimi (t/jh-omienrivien-nimi jarjestysnumero)] (conj polut [:domain :johto-ja-hallintokorvaukset nimi]))) [] (range 1 (inc t/jh-korvausten-omiariveja-lkm))) :toiminto! (fn [_ data & oma-data] (let [omien-rivien-tiedot (transduce (comp (map ffirst) (map-indexed #(assoc %2 :jarjestysnumero (inc %1)))) conj [] oma-data) lisatyt-rivit (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] #{})] (doseq [{:keys [toimenkuva toimenkuva-id jarjestysnumero]} omien-rivien-tiedot] (cond (and (not (contains? lisatyt-rivit toimenkuva-id)) (not (empty? toimenkuva))) (let [omanimi (t/jh-omienrivien-nimi jarjestysnumero) lisattava-rivi (grid/aseta-nimi (grid/samanlainen-osa (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [::g-pohjat/data 0])) omanimi) rivin-paikka-index (count (grid/hae-grid (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [::g-pohjat/data]) :lapset))] (e! (tuck-apurit/->PaivitaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] (fn [lisatyt-rivit] (conj (or lisatyt-rivit #{}) toimenkuva-id)))) (grid/lisaa-rivi! (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) lisattava-rivi [1 rivin-paikka-index]) (grid/lisaa-uuden-osan-rajapintakasittelijat (grid/get-in-grid (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) [1 rivin-paikka-index]) [:. ::t/yhteenveto] {:rajapinta (keyword (str "yhteenveto-" omanimi)) :solun-polun-pituus 1 :datan-kasittely identity}) (t/paivita-raidat! (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]))) (and (contains? lisatyt-rivit toimenkuva-id) (empty? toimenkuva)) (let [omanimi (t/jh-omienrivien-nimi jarjestysnumero) g (get-in data [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid]) poistettava-rivi (grid/get-in-grid g [::g-pohjat/data omanimi])] (e! (tuck-apurit/->PaivitaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :lisatyt-rivit] (fn [lisatyt-rivit] (disj (or lisatyt-rivit #{}) toimenkuva-id)))) (grid/poista-osan-rajapintakasittelijat poistettava-rivi) (grid/poista-rivi! g poistettava-rivi)) :else nil))))}} (reduce (fn [polut jarjestysnumero] (let [nimi (t/jh-omienrivien-nimi jarjestysnumero)] (merge polut {(keyword "piilota-itsetaytettyja-riveja-" nimi) {:polut [[:gridit :johto-ja-hallintokorvaukset :yhteenveto nimi :maksukausi]] :toiminto! (fn [g _ maksukausi] (let [naytettavat-kuukaudet (into #{} (mhu/maksukausi->kuukaudet-range maksukausi))] (doseq [rivi (grid/hae-grid (grid/get-in-grid (grid/etsi-osa g nimi) [1]) :lapset)] (let [aika (grid/solun-arvo (grid/get-in-grid rivi [0])) piilotetaan? (and aika (not (contains? naytettavat-kuukaudet (pvm/kuukausi aika))))] (if piilotetaan? (grid/piilota! rivi) (grid/nayta! rivi)))) (t/paivita-raidat! (grid/osa-polusta g [::g-pohjat/data]))))} (keyword "omarivi-disable-" nimi) {:polut [[:domain :johto-ja-hallintokorvaukset nimi] [:gridit :johto-ja-hallintokorvaukset :kuukausitasolla? nimi]] :toiminto! (fn [g tila oma-jh-korvausten-tila kuukausitasolla?] (let [hoitokauden-numero (get-in tila [:suodattimet :hoitokauden-numero]) toimenkuva (get-in oma-jh-korvausten-tila [(dec hoitokauden-numero) 0 :toimenkuva]) index (dec (+ (count (t/pohjadatan-versio)) jarjestysnumero)) yhteenvetorivi (if (grid/rivi? (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0])) (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto 0]) (grid/get-in-grid g [::g-pohjat/data index ::t/data-yhteenveto]))] (if (empty? toimenkuva) (do (ks-yhteiset/maara-solujen-disable! (grid/get-in-grid g [::g-pohjat/data index ::t/data-sisalto]) true) (disable-osa-indexissa! yhteenvetorivi #{1 2 4} true)) (do (rividisable! g (dec (+ (count (t/pohjadatan-versio)) jarjestysnumero)) kuukausitasolla?) (disable-osa-indexissa! yhteenvetorivi #{2 4} false)))))}}))) {} (range 1 (inc t/jh-korvausten-omiariveja-lkm))))) --- Triggeröi gridin luomisen ---- (grid/triggeroi-tapahtuma! g :nayta-tai-piilota-ennen-urakkaa-rivit) (grid/triggeroi-tapahtuma! g :johto-ja-hallintokorvaukset-disablerivit) g)) (defn johto-ja-hallintokorvaus-laskulla-yhteenveto-grid [] (let [taulukon-id "johto-ja-hallintokorvaus-yhteenveto-taulukko" g (g-pohjat/uusi-taulukko {:header (-> (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :leveys 5 :luokat #{"table-default" "table-default-header" "lihavoitu"}})) (assoc-in [0 :leveys] 10) (assoc-in [1 :leveys] 4)) :body (mapv (fn [_] {:tyyppi :taulukko :osat [{:tyyppi :rivi :nimi ::t/yhteenveto :osat (cond-> (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :luokat #{"table-default"} :fmt ks-yhteiset/summa-formatointi-uusi})) true (assoc-in [0 :fmt] nil) (not (t/post-2022?)) (assoc-in [1 :fmt] (fn [teksti] (if (nil? teksti) "" (let [sisaltaa-erottimen? (boolean (re-find #",|\." (str teksti)))] (if sisaltaa-erottimen? (fmt/desimaaliluku (clj-str/replace (str teksti) "," ".") 1 true) teksti))))))}]}) (t/pohjadatan-versio)) :footer (let [osat (vec (repeat (if (t/post-2022?) 6 7) {:tyyppi :teksti :luokat #{"table-default" "table-default-sum"} :fmt ks-yhteiset/yhteenveto-format}))] (if-not (t/post-2022?) (assoc osat 1 {:tyyppi :tyhja :luokat #{"table-default" "table-default-sum"}}) osat)) :taulukon-id taulukon-id :root-asetus! (fn [g] (e! (tuck-apurit/->MuutaTila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid] g))) :root-asetukset {:haku (fn [] (get-in @tila/suunnittelu-kustannussuunnitelma [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid])) :paivita! (fn [f] (swap! tila/suunnittelu-kustannussuunnitelma (fn [tila] (update-in tila [:gridit :johto-ja-hallintokorvaukset-yhteenveto :grid] f))))}}) g (grid/lisaa-rivi! g (grid/rivi {:osat (let [osat (vec (repeatedly (if (t/post-2022?) 6 7) (fn [] (solu/teksti {:parametrit {:class #{"table-default" "table-default-sum" "harmaa-teksti"}} :fmt ks-yhteiset/yhteenveto-format}))))] (if-not (t/post-2022?) (update-in osat [1] gov/teksti->tyhja #{"table-default" "table-default-sum" "harmaa-teksti"}) osat)) :koko {:seuraa {:seurattava ::g-pohjat/otsikko :sarakkeet :sama :rivit :sama}} :nimi ::t/indeksikorjattu} [{:sarakkeet [0 (if (t/post-2022?) 6 7)] :rivit [0 1]}]) [3])] (grid/rajapinta-grid-yhdistaminen! g t/johto-ja-hallintokorvaus-yhteenveto-rajapinta (t/johto-ja-hallintokorvaus-yhteenveto-dr) (let [kuvaus (vec (concat [:toimenkuva] (when-not (t/post-2022?) [:kk-v]) [:hoitovuosi-1 :hoitovuosi-2 :hoitovuosi-3 :hoitovuosi-4 :hoitovuosi-5]))] (merge {[::g-pohjat/otsikko] {:rajapinta :otsikot :solun-polun-pituus 1 :jarjestys [(with-meta kuvaus {:nimi :mapit})] :datan-kasittely (fn [otsikot] (mapv (fn [otsikko] otsikko) (vals otsikot)))} [::g-pohjat/yhteenveto] {:rajapinta :yhteensa :solun-polun-pituus 1 :datan-kasittely identity} [::t/indeksikorjattu] {:rajapinta :indeksikorjattu :solun-polun-pituus 1 :datan-kasittely identity}} (second (reduce (fn [[index grid-kasittelijat] {:keys [toimenkuva maksukausi]}] (let [yksiloiva-nimen-paate (str "-" toimenkuva "-" maksukausi)] [(inc index) (merge grid-kasittelijat {[::g-pohjat/data index ::t/yhteenveto] {:rajapinta (keyword (str "yhteenveto" yksiloiva-nimen-paate)) :solun-polun-pituus 1 :datan-kasittely identity}})])) [0 {}] (t/pohjadatan-versio)))))))) -- osion apufunktiot -- (defn johto-ja-hallintokorvaukset-yhteensa "Laskee yhteen 'johto-ja-hallintokorvaukset' yhteenvedon summat (eli käytännössä tuntipalkat) ja 'toimistokulut' yhteenvedon summat. Laskee yhteissumman joko annetulle hoitovuodelle tai annettujen summavektorien jokaiselle hoitovuodelle. Jos hoitovuotta ei anneta, palauttaa vektorin, jossa on summa jokaisesssa elementissä." ([johto-ja-hallintokorvaukset-summat toimistokulut-summat] (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-summat toimistokulut-summat nil)) ([johto-ja-hallintokorvaukset-summat toimistokulut-summat hoitokausi] (assert (or (nil? hoitokausi) (number? hoitokausi)) "Hoitokausi ei ole numero!") (assert (vector? johto-ja-hallintokorvaukset-summat) "johto-ja-hallintokorvaukset-summat täytyy olla vektori.") (assert (vector? toimistokulut-summat) "toimistokulut-summat täytyy olla vektori.") (if hoitokausi (let [hoitokausi-idx (dec hoitokausi)] (+ (nth johto-ja-hallintokorvaukset-summat hoitokausi-idx) (nth toimistokulut-summat hoitokausi-idx))) (mapv (fn [jh tk] (+ jh tk)) johto-ja-hallintokorvaukset-summat toimistokulut-summat)))) (defn- johto-ja-hallintokorvaus-yhteenveto [johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-indeksikorjattu toimistokulut-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] (if (and indeksit kantahaku-valmis?) (let [hinnat (mapv (fn [summa] {:summa summa}) (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-summat toimistokulut-summat)) hinnat-indeksikorjattu (mapv (fn [summa] {:summa summa}) (johto-ja-hallintokorvaukset-yhteensa johto-ja-hallintokorvaukset-indeksikorjattu toimistokulut-indeksikorjattu))] [:div.summa-ja-indeksilaskuri [ks-yhteiset/hintalaskuri {:otsikko nil :selite "Palkat + Toimisto- ja ICT-kulut, tiedotus, opastus, kokousten järj. jne. + Hoito- ja korjaustöiden pientarvikevarasto" :hinnat hinnat :data-cy "johto-ja-hallintokorvaus-hintalaskuri"} kuluva-hoitokausi] [ks-yhteiset/indeksilaskuri-ei-indeksikorjausta hinnat-indeksikorjattu indeksit {:data-cy "johto-ja-hallintokorvaus-indeksilaskuri"}]]) [yleiset/ajax-loader])) (defn- laske-vuoden-summa [hoitokauden-kuukausittaiset-summat] (let [summat-vuodelle (map #(-> % second :kuukausipalkka) hoitokauden-kuukausittaiset-summat)] (reduce + 0 summat-vuodelle))) (defn formatoi-kuukausi [vuosi kuukausi] (let [tanaan (pvm/nyt)] (str (get {1 "Tammikuu" 2 "Helmikuu" 3 "Maaliskuu" 4 "Huhtikuu" 5 "Toukokuu" 6 "Kesäkuu" 7 "Heinäkuu" 8 "Elokuu" 9 "Syyskuu" 10 "Lokakuu" 11 "Marraskuu" 12 "Joulukuu"} kuukausi) " " (if (> kuukausi 9) vuosi (inc vuosi)) (when (or (< (inc vuosi) (-> tanaan pvm/vuosi)) (and (= (inc vuosi) (-> tanaan pvm/vuosi)) (or (< kuukausi (-> tanaan pvm/kuukausi)) (< 9 kuukausi ))) (and (= vuosi (-> tanaan pvm/vuosi)) (and (< kuukausi (-> tanaan pvm/kuukausi)) (< 9 kuukausi)))) " (mennyt)")))) (defn- kun-erikseen-syotettava-checkbox-klikattu [checkbox-tila] @checkbox-tila) (defn- jaa-vuosipalkka-kuukausille [hoitokausi kopioi-tuleville? ennen-urakkaa? toimenkuvan-maarat vuosipalkka] (if ennen-urakkaa? ennen lokakuulle (let [kuukausipalkka (tyokalut/round2 2 (/ vuosipalkka 12)) viimeinen-kuukausi (if-not (= vuosipalkka (* 12 kuukausipalkka)) (tyokalut/round2 2 (- vuosipalkka (tyokalut/round2 2 (* 11 kuukausipalkka)))) kuukausipalkka) alkuvuosi (-> tila/yleiset deref :urakka :alkupvm pvm/vuosi) loppuvuosi (-> tila/yleiset deref :urakka :loppupvm pvm/vuosi) loppukausi (inc (if kopioi-tuleville? (- loppuvuosi alkuvuosi) hoitokausi)) kaudet (into [] (range hoitokausi loppukausi)) aseta-kuukausipalkka (map (fn [[kuukausi tiedot]] [kuukausi (assoc tiedot :kuukausipalkka (if (= 9 kuukausi) viimeinen-kuukausi kuukausipalkka))])) paivita-vuoden-tiedot (fn [kkt] (into {} aseta-kuukausipalkka kkt)) paivitysfunktiot (mapv #(fn [maarat] (update maarat % paivita-vuoden-tiedot)) kaudet) paivita (apply comp paivitysfunktiot)] (paivita toimenkuvan-maarat)))) (defn- tallenna-vuosipalkka [atomi {:keys [hoitokausi kopioi-tuleville?]} rivi] (let [toimenkuvan-maarat (get-in rivi [:maksuerat-per-hoitovuosi-per-kuukausi]) paivitetyt (jaa-vuosipalkka-kuukausille hoitokausi kopioi-tuleville? (:ennen-urakkaa? rivi) toimenkuvan-maarat (:vuosipalkka rivi)) rivi (assoc rivi :maksuerat-per-hoitovuosi-per-kuukausi paivitetyt) tiedot @atomi tiedot-muuttuneet? (not= (get tiedot (:tunniste rivi)) rivi) tiedot (assoc-in tiedot [(:tunniste rivi) :maksuerat-per-hoitovuosi-per-kuukausi] paivitetyt) _ (reset! atomi tiedot)] (when tiedot-muuttuneet? (e! (t/->TallennaJHOToimenkuvanVuosipalkka rivi))))) (defn- paivita-toimenkuvan-vuosiloota [hoitokausi [toimenkuva toimenkuvan-tiedot]] (let [vuoden-summa (laske-vuoden-summa (get-in toimenkuvan-tiedot [:maksuerat-per-hoitovuosi-per-kuukausi hoitokausi]))] [toimenkuva (assoc toimenkuvan-tiedot :vuosipalkka vuoden-summa)])) (defn- paivita-vuosilootat [tiedot hoitokausi] (into {} (map (r/partial paivita-toimenkuvan-vuosiloota hoitokausi)) tiedot)) (defn- tallenna-kuukausipalkka [tiedot-atom {:keys [alkuvuosi loppuvuosi hoitokausi kopioi-tuleville?]} rivi] (let [tiedot @tiedot-atom loppukausi (inc (if kopioi-tuleville? (- loppuvuosi alkuvuosi) hoitokausi)) kaudet (into [] (range hoitokausi loppukausi)) erat (get tiedot :maksuerat-per-hoitovuosi-per-kuukausi) paivitysfunktiot (mapv (fn [kausi] (fn [maarat] (assoc-in maarat [kausi (:kuukausi rivi) :kuukausipalkka] (:kuukausipalkka rivi)))) kaudet) vuosipalkka (reduce (fn [summa kuukauden-arvot] (if (not (nil? (:kuukausipalkka (second kuukauden-arvot)))) (+ summa (:kuukausipalkka (second kuukauden-arvot))) summa)) 0 (get erat hoitokausi)) paivita (apply comp paivitysfunktiot) paivitetyt (paivita erat) tiedot (assoc tiedot :vuosipalkka vuosipalkka) toimenkuvan-tiedot (assoc tiedot :maksuerat-per-hoitovuosi-per-kuukausi paivitetyt) _ (reset! tiedot-atom toimenkuvan-tiedot)] Atomin päivittämisessä menee joitakin millisekunteja . Siksi viive (e! (t/->TallennaJHOToimenkuvanVuosipalkka toimenkuvan-tiedot)))) (defn- jarjesta-hoitovuoden-jarjestykseen "Järjestys lokakuusta seuraavan vuoden syyskuuhun" [{:keys [kuukausi]}] (if (> kuukausi 9) (- kuukausi 12) kuukausi)) (defn- luo-kursori [atomi toimenkuva polku hoitokausi] (r/cursor atomi [toimenkuva polku hoitokausi])) (defn- kursorit-polulle [polku tiedot toimenkuva vuosien-erotus] (into {} (map (juxt identity (r/partial luo-kursori tiedot toimenkuva polku))) (range 1 vuosien-erotus))) (defn- palkkakentta-muokattava? [erikseen-syotettava? tiedot hoitokausi] (and @erikseen-syotettava? (or (and (:ennen-urakkaa? tiedot) (= 1 hoitokausi)) (false? (:ennen-urakkaa? tiedot))))) (defn- vetolaatikko-klikattu-fn [atomi tallenna-fn rivi-atom event] (let [valittu? (-> event .-target .-checked)] (when (and @atomi (not valittu?)) (tallenna-fn @rivi-atom)) (reset! atomi valittu?))) (defn- vetolaatikko-komponentti [tiedot-atomi polku {:keys [tunniste] :as rivi} tallenna-fn_ kuluva-hoitokausi_] (let [suodattimet (r/cursor tila/suunnittelu-kustannussuunnitelma [:suodattimet]) urakan-alkuvuosi (-> tila/yleiset deref :urakka :alkupvm pvm/vuosi) urakan-loppuvuosi (-> tila/yleiset deref :urakka :loppupvm pvm/vuosi) vuosien-erotus (- urakan-loppuvuosi urakan-alkuvuosi) kursorit (assoc {} :toimenkuva (r/cursor tiedot-atomi [tunniste]) :maksuerat (kursorit-polulle :maksuerat-per-hoitovuosi-per-kuukausi tiedot-atomi polku vuosien-erotus) :erikseen-syotettava? (kursorit-polulle :erikseen-syotettava? tiedot-atomi polku vuosien-erotus))] (fn [_ polku rivi tallenna-fn kuluva-hoitokausi] (let [{kopioi-tuleville? :kopioidaan-tuleville-vuosille?} @suodattimet valitun-hoitokauden-alkuvuosi (-> @tila/yleiset :urakka :alkupvm pvm/vuosi (+ (dec kuluva-hoitokausi))) maksuerat (get-in kursorit [:maksuerat kuluva-hoitokausi])] [:div [kentat/tee-kentta {:tyyppi :checkbox :teksti "Suunnittele maksuerät kuukausittain" :valitse! (partial vetolaatikko-klikattu-fn (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi]) tallenna-fn (get-in kursorit [:toimenkuva]))} (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi])] [:div.vetolaatikko-border {:style {:border-left "4px solid lightblue" :margin-top "16px" :padding-left "18px"}} [vanha-grid/muokkaus-grid {:id (str polku valitun-hoitokauden-alkuvuosi) :voi-poistaa? (constantly false) :voi-lisata? false :piilota-toiminnot? true :muokkauspaneeli? false :jarjesta jarjesta-hoitovuoden-jarjestykseen :piilota-table-header? true :on-rivi-blur (r/partial tallenna-kuukausipalkka (get kursorit :toimenkuva) {:hoitokausi kuluva-hoitokausi :kopioi-tuleville? kopioi-tuleville? :alkuvuosi urakan-alkuvuosi :loppuvuosi urakan-loppuvuosi}) :voi-kumota? false} [{:nimi :kuukausi :tyyppi :string :muokattava? (constantly false) :leveys "85%" :fmt (r/partial formatoi-kuukausi valitun-hoitokauden-alkuvuosi)} {:nimi :kuukausipalkka :tyyppi :numero :leveys "15%" :muokattava? #(palkkakentta-muokattava? (get-in kursorit [:erikseen-syotettava? kuluva-hoitokausi]) rivi kuluva-hoitokausi)}] maksuerat]]])))) (defn luo-vetolaatikot [atomi tallenna-fn kuluva-hoitokausi] (into {} (map (juxt first #(let [rivi (second %) polku (:tunniste rivi)] [vetolaatikko-komponentti atomi polku rivi tallenna-fn kuluva-hoitokausi]))) (into {} (filter #(let [data (second %)] (not (or (:ennen-urakkaa? data) (get (:hoitokaudet data) 0))))) @atomi))) (defn- kun-ei-syoteta-erikseen [hoitokausi tiedot] (and (not (get-in tiedot [:erikseen-syotettava? hoitokausi])) (or (and (:ennen-urakkaa? tiedot) (= 1 hoitokausi)) (false? (:ennen-urakkaa? tiedot))))) (defn tallenna-toimenkuvan-tiedot [data-atomi optiot rivin-tiedot] (when (:oma-toimenkuva? rivin-tiedot) (let [uusi-toimenkuva-nimi (:toimenkuva rivin-tiedot) rivin-nimi (:rivin-nimi rivin-tiedot)] , niin vaihdetaan se FIXME : , joten tätä . , koska ei ole . (when (not= uusi-toimenkuva-nimi rivin-nimi) (e! (t/->VaihdaOmanToimenkuvanNimi rivin-tiedot)) (e! (t/->TallennaToimenkuva (:tunniste rivin-tiedot)))))) (tallenna-vuosipalkka data-atomi optiot rivin-tiedot)) (defn taulukko-2022-eteenpain [app] (let [kaytetty-hoitokausi (r/atom (-> app :suodattimet :hoitokauden-numero)) data (t/konvertoi-jhk-data-taulukolle (get-in app [:domain :johto-ja-hallintokorvaukset]) @kaytetty-hoitokausi)] (fn [app] (let [kuluva-hoitokausi (-> app :suodattimet :hoitokauden-numero) kopioidaan-tuleville-vuosille? (-> app :suodattimet :kopioidaan-tuleville-vuosille?) tallenna-fn (r/partial tallenna-toimenkuvan-tiedot data {:hoitokausi kuluva-hoitokausi :kopioi-tuleville? kopioidaan-tuleville-vuosille?}) vetolaatikot (luo-vetolaatikot data tallenna-fn @kaytetty-hoitokausi)] (when-not (= kuluva-hoitokausi @kaytetty-hoitokausi) (swap! data paivita-vuosilootat kuluva-hoitokausi) (reset! kaytetty-hoitokausi kuluva-hoitokausi)) [:div Kaikille yhteiset toimenkuvat [vanha-grid/muokkaus-grid {:otsikko "Tuntimäärät ja -palkat" :id "toimenkuvat-taulukko" :luokat ["poista-bottom-margin"] :voi-lisata? false :voi-kumota? false :muutos (fn [g] (when-not (= @kaytetty-hoitokausi kuluva-hoitokausi) (vanha-grid/sulje-vetolaatikot! g))) :jarjesta :jarjestys :piilota-toiminnot? true :on-rivi-blur tallenna-fn :voi-poistaa? (constantly false) :piilota-rivi #(and (not (= kuluva-hoitokausi 1)) (:ennen-urakkaa? %)) :vetolaatikot vetolaatikot} [{:otsikko "Toimenkuva" :nimi :toimenkuva :tyyppi :string :muokattava? :oma-toimenkuva? :leveys "80%" :fmt clj-str/capitalize :placeholder "Kirjoita muu toimenkuva"} {:otsikko "" :tyyppi :vetolaatikon-tila :leveys "5%" :muokattava? (constantly false)} {:otsikko "Vuosipalkka, €" :nimi :vuosipalkka :desimaalien-maara 2 :tyyppi :numero :muokattava? (r/partial kun-ei-syoteta-erikseen kuluva-hoitokausi) :leveys "15%"}] data]])))) (defn- johto-ja-hallintokorvaus [app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [:<> [:h2 {:id (str (get t/hallinnollisten-idt :johto-ja-hallintokorvaus) "-osio")} "Johto- ja hallintokorvaus"] [johto-ja-hallintokorvaus-yhteenveto johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [:h3 "Tuntimäärät ja -palkat"] [:div {:data-cy "tuntimaarat-ja-palkat-taulukko-suodattimet"} [ks-yhteiset/yleis-suodatin suodattimet]] (cond (and johto-ja-hallintokorvaus-grid kantahaku-valmis? (not (t/post-2022?))) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra johto-ja-hallintokorvaus-grid]] (and (t/post-2022?) johto-ja-hallintokorvaus-grid kantahaku-valmis?) [:div.johto-ja-hallintokorvaukset {:class (when vahvistettu? "osio-vahvistettu")} [taulukko-2022-eteenpain app]] :else [yleiset/ajax-loader]) (if (and johto-ja-hallintokorvaus-yhteenveto-grid kantahaku-valmis?) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra johto-ja-hallintokorvaus-yhteenveto-grid]] [yleiset/ajax-loader]) Johto ja hallinto : Muut kulut -taulukko [:h3 {:id (str (get t/hallinnollisten-idt :toimistokulut) "-osio")} "Johto ja hallinto: muut kulut"] [:div {:data-cy "johto-ja-hallinto-muut-kulut-taulukko-suodattimet"} [ks-yhteiset/yleis-suodatin suodattimet]] Note : " Muut kulut " taulukko on hämäävästi toimistokulut - grid . " toimistokulut " , niin kannattaa harkita gridin . on vähän työlästä , gridin viitataan : toimistokulut - keywordillä . (if (and toimistokulut-grid kantahaku-valmis?) FIXME : " " luokka on väliaikainen hack , jolla osion input kunnes muutosten seuranta ehditään toteuttaa . [:div {:class (when vahvistettu? "osio-vahvistettu")} [grid/piirra toimistokulut-grid]] [yleiset/ajax-loader]) [:span "Yhteenlaskettu kk-määrä: Toimisto- ja ICT-kulut, tiedotus, opastus, kokousten ja vierailujen järjestäminen sekä tarjoilukulut + Hoito- ja korjaustöiden pientarvikevarasto (työkalut, mutterit, lankut, naulat jne.)"]]) # # # Johto- ja hallintokorvaus osion pääkomponentti # # # FIXME : Arvojen tallentamisessa on jokin häikkä . Tallennus ei onnistu . ( ositustakin ) (defn osio [app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?] [johto-ja-hallintokorvaus app vahvistettu? johto-ja-hallintokorvaus-grid johto-ja-hallintokorvaus-yhteenveto-grid toimistokulut-grid suodattimet johto-ja-hallintokorvaukset-summat toimistokulut-summat johto-ja-hallintokorvaukset-summat-indeksikorjattu toimistokulut-summat-indeksikorjattu kuluva-hoitokausi indeksit kantahaku-valmis?])
1935f49ad8a8d2a444f9e910c18a9f41e545adad1ce19bb93ca92bb371a56efb
parsimony-ide/parsimony
common_test.clj
(ns parsimony.common-test (:require [alanlcode.util.os :as os] [clojure.test :refer [is]])) (defmacro is-not [arg & args] `(is (not ~arg) ~@args)) (defn temp-db-file [] (-> (os/make-temp-file (os/temp-directory) "temp-rdag" ".db") (os/->file) (doto (.deleteOnExit))))
null
https://raw.githubusercontent.com/parsimony-ide/parsimony/1744e8b4a921a50dfbd0815499cf3af1059590c8/test/parsimony/common_test.clj
clojure
(ns parsimony.common-test (:require [alanlcode.util.os :as os] [clojure.test :refer [is]])) (defmacro is-not [arg & args] `(is (not ~arg) ~@args)) (defn temp-db-file [] (-> (os/make-temp-file (os/temp-directory) "temp-rdag" ".db") (os/->file) (doto (.deleteOnExit))))
b9123734c950038188844237a3da1f6b722ca01f7d66aa103f6661536f9cf96f
footprintanalytics/footprint-web
types.cljc
(ns metabase.types "The Metabase Hierarchical Type System (MHTS). This is a hierarchy where types derive from one or more parent types, which in turn derive from their own parents. This makes it possible to add new types without needing to add corresponding mappings in the frontend or other places. For example, a Database may want a type called something like `:type/CaseInsensitiveText`; we can add this type as a derivative of `:type/Text` and everywhere else can continue to treat it as such until further notice. There are a few different keyword hierarchies below: ### Data (Base/Effective) Types -- keys starting with `:type/` and deriving from `:type/*`, but not `:Semantic/*` or `:Relation/*` The 'base type' represents the actual data type of the column in the data warehouse. The 'effective type' is the data type we treat this column as; it may be the same as base type or something different if the column has a coercion strategy (see below). Example: a `VARCHAR` column might have a base type of `:type/Text`, but store ISO-8601 timestamps; we might choose to interpret this column as a timestamp column by giving it an effective type of `:type/DateTime` and the coercion strategy `:Coercion/ISO8601->DateTime` ### Coercion Strategies -- keys starting with `:Coercion/` These strategies tell us how to coerce a column from its base type to it effective type when the two differ. For example, `:Coercion/ISO8601->DateTime` can be used to tell us how to interpret a `VARCHAR` column (base type = `:type/Text`) as a `:type/DateTime` column (effective type). This depends of the database, but we might do something like using a `parse_timestamp()` function whenever we fetch this column. ### Semantic Types -- types starting with `:type/*` and deriving from `:Semantic/*` NOTE: In the near future we plan to rename the semantic types so they start with `:Semantic/` rather than `:type/`. These types represent the semantic meaning/interpretation/purpose of a column in the data warehouse, for example `:type/UpdatedTimestamp`. This affects things like how we display this column or how we generate Automagic Dashboards. How is this different from Base/Effective type? Suppose we have an `updated_at` `TIMESTAMP` column; its data type is `TIMESTAMP` and thus its base type would be `:type/DateTime`. There is no such thing as an `UPDATED_AT_TIMESTAMP` data type; the fact that this column is used to record update timestamps is purely a semantic one. :Semantic types descend from data type(s) that are allowed to have this semantic type. For example, `:type/UpdatedTimestamp` descends from `:type/DateTime`, which means a column with an effective type of `:type/DateTime` can have a semantic type of`:type/UpdatedTimestamp`; however a `:type/Boolean` cannot -- this would make no sense. (Unless maybe `false` meant `1970-01-01T00:00:00Z` and `true` meant `1970-01-01T00:00:01Z`, but I think we can agree that's dumb.) ### Relation Type -- types starting with `:type/*` and deriving from `:Relation/*` NOTE: As with Semantic types, in the near future we'll change the relation types so they all start with `:Relation/`. Types that have to do with whether this column is a primary key or foreign key. These are currently stored in the `semantic_type` column, but we'll split them out into a separate `relation_type` column in the future. ### Entity Types -- keys starting with `:entity/` These are used to record the semantic purpose of a Table." #?@(:clj [(:require [clojure.set :as set] [metabase.types.coercion-hierarchies :as coercion-hierarchies])] :cljs [(:require [clojure.set :as set] [metabase.shared.util :as shared.u] [metabase.types.coercion-hierarchies :as coercion-hierarchies])])) ;;; Table (entity) Types (derive :entity/GenericTable :entity/*) (derive :entity/UserTable :entity/GenericTable) (derive :entity/CompanyTable :entity/GenericTable) (derive :entity/TransactionTable :entity/GenericTable) (derive :entity/ProductTable :entity/GenericTable) (derive :entity/SubscriptionTable :entity/GenericTable) (derive :entity/EventTable :entity/GenericTable) (derive :entity/GoogleAnalyticsTable :entity/GenericTable) ;;; Numeric Types (derive :type/Number :type/*) (derive :type/Integer :type/Number) (derive :type/BigInteger :type/Integer) (derive :type/Quantity :Semantic/*) (derive :type/Quantity :type/Integer) ` : type / Float ` means any number with a decimal place ! It does n't explicitly mean a 32 - bit or 64 - bit floating - point ;; number. That's why there's no `:type/Double`. (derive :type/Float :type/Number) ` : type / Decimal ` means a column that is actually stored as an arbitrary - precision decimal type , e.g. ` BigDecimal ` or ` DECIMAL ` . For fixed - precision columns , just use ` : type / Float ` (derive :type/Decimal :type/Float) (derive :type/Share :Semantic/*) (derive :type/Share :type/Float) ;; `:type/Currency` -- an actual currency data type, for example Postgres `money`. ;; `:type/Currency` -- a column that should be interpreted as money. ;; ;; `money` (base type `:type/Currency`) columns will likely have a semantic type `:type/Currency` or a descendant ;; thereof like `:type/Income`, but other floating-point data type columns can be interpreted as currency as well; a ` DECIMAL ` ( base type ` : type / Decimal ` ) column can also have a semantic type ` : type / Currency ` . (derive :type/Currency :type/Decimal) (derive :type/Currency :Semantic/*) (derive :type/Income :type/Currency) (derive :type/Discount :type/Currency) (derive :type/Price :type/Currency) (derive :type/GrossMargin :type/Currency) (derive :type/Cost :type/Currency) ;; :type/Location -- anything having to do with a location, e.g. country, city, or coordinates. (derive :type/Location :Semantic/*) (derive :type/Coordinate :type/Location) (derive :type/Coordinate :type/Float) (derive :type/Latitude :type/Coordinate) (derive :type/Longitude :type/Coordinate) (derive :type/Score :Semantic/*) (derive :type/Score :type/Number) (derive :type/Duration :Semantic/*) (derive :type/Duration :type/Number) ;;; Text Types (derive :type/Text :type/*) (derive :type/UUID :type/Text) (derive :type/URL :Semantic/*) (derive :type/URL :type/Text) (derive :type/ImageURL :type/URL) (derive :type/AvatarURL :type/ImageURL) (derive :type/Email :Semantic/*) (derive :type/Email :type/Text) ;; Semantic types deriving from `:type/Category` should be marked as 'category' Fields during sync, i.e. they should have their FieldValues cached and synced . See ;; `metabase.sync.analyze.classifiers.category/field-should-be-category?` (derive :type/Category :Semantic/*) (derive :type/Enum :Semantic/*) (derive :type/Address :type/Location) (derive :type/City :type/Address) (derive :type/City :type/Category) (derive :type/City :type/Text) (derive :type/State :type/Address) (derive :type/State :type/Category) (derive :type/State :type/Text) (derive :type/Country :type/Address) (derive :type/Country :type/Category) (derive :type/Country :type/Text) (derive :type/ZipCode :type/Address) (derive :type/ZipCode :type/Text) (derive :type/Name :type/Category) (derive :type/Name :type/Text) (derive :type/Title :type/Category) (derive :type/Title :type/Text) (derive :type/Description :Semantic/*) (derive :type/Description :type/Text) (derive :type/Comment :Semantic/*) (derive :type/Comment :type/Text) (derive :type/PostgresEnum :type/Text) ;;; DateTime Types (derive :type/Temporal :type/*) (derive :type/Date :type/Temporal) You could have Dates with TZ info but it 's not supported by JSR-310 so we 'll not worry about that for now . (derive :type/Time :type/Temporal) (derive :type/TimeWithTZ :type/Time) (derive :type/TimeWithLocalTZ :type/TimeWithTZ) ; a column that is timezone-aware, but normalized to UTC or another offset at rest. (derive :type/TimeWithZoneOffset :type/TimeWithTZ) ; a column that stores its timezone offset (derive :type/DateTime :type/Temporal) (derive :type/DateTimeWithTZ :type/DateTime) (derive :type/DateTimeWithLocalTZ :type/DateTimeWithTZ) ; a column that is timezone-aware, but normalized to UTC or another offset at rest. a column that stores its timezone offset , e.g. ` -08:00 ` a column that stores its timezone ID , e.g. ` US / Pacific ` An ` Instant ` is a timestamp in ( milli-)seconds since the epoch , UTC . Since it does n't store TZ information , but is normalized to UTC , it is a DateTimeWithLocalTZ ;; ;; `Instant` if differentiated from other `DateTimeWithLocalTZ` columns in the same way `java.time.Instant` is ;; different from `java.time.OffsetDateTime`; (derive :type/Instant :type/DateTimeWithLocalTZ) TODO -- should n't we have a ` : type / LocalDateTime ` as well ? (derive :type/CreationTemporal :Semantic/*) (derive :type/CreationTimestamp :type/CreationTemporal) (derive :type/CreationTimestamp :type/DateTime) (derive :type/CreationTime :type/CreationTemporal) (derive :type/CreationTime :type/Time) (derive :type/CreationDate :type/CreationTemporal) (derive :type/CreationDate :type/Date) (derive :type/JoinTemporal :Semantic/*) (derive :type/JoinTimestamp :type/JoinTemporal) (derive :type/JoinTimestamp :type/DateTime) (derive :type/JoinTime :type/JoinTemporal) (derive :type/JoinTime :type/Time) (derive :type/JoinDate :type/JoinTemporal) (derive :type/JoinDate :type/Date) (derive :type/CancelationTemporal :Semantic/*) (derive :type/CancelationTimestamp :type/CancelationTemporal) (derive :type/CancelationTimestamp :type/DateTime) (derive :type/CancelationTime :type/CancelationTemporal) (derive :type/CancelationTime :type/Date) (derive :type/CancelationDate :type/CancelationTemporal) (derive :type/CancelationDate :type/Date) (derive :type/DeletionTemporal :Semantic/*) (derive :type/DeletionTimestamp :type/DeletionTemporal) (derive :type/DeletionTimestamp :type/DateTime) (derive :type/DeletionTime :type/DeletionTemporal) (derive :type/DeletionTime :type/Time) (derive :type/DeletionDate :type/DeletionTemporal) (derive :type/DeletionDate :type/Date) (derive :type/UpdatedTemporal :Semantic/*) (derive :type/UpdatedTimestamp :type/UpdatedTemporal) (derive :type/UpdatedTimestamp :type/DateTime) (derive :type/UpdatedTime :type/UpdatedTemporal) (derive :type/UpdatedTime :type/Time) (derive :type/UpdatedDate :type/UpdatedTemporal) (derive :type/UpdatedDate :type/Date) (derive :type/Birthdate :Semantic/*) (derive :type/Birthdate :type/Date) ;;; Other (derive :type/Boolean :type/*) (derive :type/DruidHyperUnique :type/*) ;;; Text-Like Types: Things that should be displayed as text for most purposes but that *shouldn't* support advanced ;;; filter options like starts with / contains (derive :type/TextLike :type/*) (derive :type/MongoBSONID :type/TextLike) ;; IP address can be either a data type e.g. Postgres `inet` or a semantic type e.g. a `text` column that has IP ;; addresses (derive :type/IPAddress :type/TextLike) (derive :type/IPAddress :Semantic/*) Structured / Collections (derive :type/Collection :type/*) (derive :type/Structured :type/*) (derive :type/Dictionary :type/Collection) (derive :type/Array :type/Collection) ;; `:type/JSON` currently means a column that is JSON data, e.g. a Postgres JSON column (derive :type/JSON :type/Structured) (derive :type/JSON :type/Collection) ;; `:type/XML` -- an actual native XML data column (derive :type/XML :type/Structured) (derive :type/XML :type/Collection) ;; `:type/Structured` columns are ones that are stored as text, but should be treated as a `:type/Collection` column ( e.g. JSON or XML ) . These should probably be coercion strategies instead , e.g. ;; ;; base type = :type/Text ;; coercion strategy = :Coercion/SerializedJSON ;; effective type = :type/JSON ;; ;; but for the time being we'll have to live with these being "weird" semantic types. (derive :type/Structured :Semantic/*) (derive :type/Structured :type/Text) (derive :type/SerializedJSON :type/Structured) (derive :type/XML :type/Structured) ;; Other (derive :type/User :Semantic/*) (derive :type/Author :type/User) (derive :type/Owner :type/User) (derive :type/Product :type/Category) (derive :type/Company :type/Category) (derive :type/Subscription :type/Category) (derive :type/Source :type/Category) ;;; Relation types (derive :type/FK :Relation/*) (derive :type/PK :Relation/*) ;;; Coercion strategies (derive :Coercion/String->Temporal :Coercion/*) (derive :Coercion/ISO8601->Temporal :Coercion/String->Temporal) (derive :Coercion/ISO8601->DateTime :Coercion/ISO8601->Temporal) (derive :Coercion/ISO8601->Time :Coercion/ISO8601->Temporal) (derive :Coercion/ISO8601->Date :Coercion/ISO8601->Temporal) (derive :Coercion/YYYYMMDDHHMMSSString->Temporal :Coercion/String->Temporal) (derive :Coercion/Bytes->Temporal :Coercion/*) (derive :Coercion/YYYYMMDDHHMMSSBytes->Temporal :Coercion/Bytes->Temporal) (derive :Coercion/Number->Temporal :Coercion/*) (derive :Coercion/UNIXTime->Temporal :Coercion/Number->Temporal) (derive :Coercion/UNIXSeconds->DateTime :Coercion/UNIXTime->Temporal) (derive :Coercion/UNIXMilliSeconds->DateTime :Coercion/UNIXTime->Temporal) (derive :Coercion/UNIXMicroSeconds->DateTime :Coercion/UNIXTime->Temporal) ;;; ---------------------------------------------------- Util Fns ---------------------------------------------------- (defn field-is-type? "True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value relating to a moment in time." [tyype {base-type :base_type, effective-type :effective_type}] (some #(isa? % tyype) [base-type effective-type])) (defn temporal-field? "True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value relating to a moment in time." [field] (field-is-type? :type/Temporal field)) #?(:cljs (defn ^:export isa "Is `x` the same as, or a descendant type of, `y`?" [x y] (isa? (keyword x) (keyword y)))) #?(:cljs (def ^:export TYPE "A map of Type name (as string, without `:type/` namespace) -> qualified type name as string {\"Temporal\" \"type/Temporal\", ...}" (clj->js (into {} (for [tyype (distinct (mapcat descendants [:type/* :Semantic/* :Relation/*]))] [(name tyype) (shared.u/qualified-name tyype)]))))) (coercion-hierarchies/define-types! :Coercion/UNIXMicroSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/UNIXMilliSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/UNIXSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/ISO8601->Date :type/Text :type/Date) (coercion-hierarchies/define-types! :Coercion/ISO8601->DateTime :type/Text :type/DateTime) (coercion-hierarchies/define-types! :Coercion/ISO8601->Time :type/Text :type/Time) (coercion-hierarchies/define-types! :Coercion/YYYYMMDDHHMMSSString->Temporal :type/Text :type/DateTime) (coercion-hierarchies/define-non-inheritable-type! :Coercion/YYYYMMDDHHMMSSBytes->Temporal :type/* :type/DateTime) (defn is-coercible-from? "Whether `coercion-strategy` is allowed for `base-type`." [coercion-strategy base-type] (or (isa? (coercion-hierarchies/base-type-hierarchy) base-type coercion-strategy) (boolean (some-> (coercion-hierarchies/non-descending-strategies) (get base-type) (contains? coercion-strategy))))) (defn is-coercible-to? "Whether `coercion-strategy` coerces to `effective-type` or some subtype thereof." [coercion-strategy effective-type] (isa? (coercion-hierarchies/effective-type-hierarchy) coercion-strategy effective-type)) (defn is-coercible? "Whether `coercion-strategy` is allowed for `base-type` and coerces to `effective-type` or some subtype thereof." [coercion-strategy base-type effective-type] (and (is-coercible-from? coercion-strategy base-type) (is-coercible-to? coercion-strategy effective-type))) (defn coercion-possibilities "Possible coercions for a base type, returned as a map of `effective-type -> #{coercion-strategy}`" [base-type] (let [base-type-hierarchy (coercion-hierarchies/base-type-hierarchy) effective-type-hierarchy (coercion-hierarchies/effective-type-hierarchy)] (->> (for [strategy (ancestors base-type-hierarchy base-type) :when (isa? strategy :Coercion/*) :let [effective-types (parents effective-type-hierarchy strategy)] effective-type effective-types :when (not (isa? effective-type :Coercion/*))] {effective-type #{strategy}}) (reduce (partial merge-with set/union) (select-keys (coercion-hierarchies/non-descending-strategies) [base-type])) not-empty))) (defn ^:export is_coerceable "Returns a boolean of whether a field base-type has any coercion strategies available." [base-type] (boolean (not-empty (coercion-possibilities (keyword base-type))))) (defn effective-type-for-coercion "The effective type resulting from a coercion." [coercion] (coercion-hierarchies/effective-type-for-strategy coercion)) (defn ^:export coercions_for_type "Coercions available for a type. In cljs will return a js array of strings like [\"Coercion/ISO8601->Time\" ...]. In clojure will return a sequence of keywords." [base-type] (let [applicable (into () (comp (distinct) cat) (vals (coercion-possibilities (keyword base-type))))] #?(:cljs (clj->js (map (fn [kw] (str (namespace kw) "/" (name kw))) applicable)) :clj applicable)))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/shared/src/metabase/types.cljc
clojure
we can add this type as a derivative of `:type/Text` and everywhere else can it may be the same as base type or something different if the column has a we might choose to interpret this column as a timestamp column by giving it an effective type its the fact that this column is used to record update timestamps is purely a semantic however a `:type/Boolean` cannot -- this Table (entity) Types Numeric Types number. That's why there's no `:type/Double`. `:type/Currency` -- an actual currency data type, for example Postgres `money`. `:type/Currency` -- a column that should be interpreted as money. `money` (base type `:type/Currency`) columns will likely have a semantic type `:type/Currency` or a descendant thereof like `:type/Income`, but other floating-point data type columns can be interpreted as currency as well; :type/Location -- anything having to do with a location, e.g. country, city, or coordinates. Text Types Semantic types deriving from `:type/Category` should be marked as 'category' Fields during sync, i.e. they `metabase.sync.analyze.classifiers.category/field-should-be-category?` DateTime Types a column that is timezone-aware, but normalized to UTC or another offset at rest. a column that stores its timezone offset a column that is timezone-aware, but normalized to UTC or another offset at rest. `Instant` if differentiated from other `DateTimeWithLocalTZ` columns in the same way `java.time.Instant` is different from `java.time.OffsetDateTime`; Other Text-Like Types: Things that should be displayed as text for most purposes but that *shouldn't* support advanced filter options like starts with / contains IP address can be either a data type e.g. Postgres `inet` or a semantic type e.g. a `text` column that has IP addresses `:type/JSON` currently means a column that is JSON data, e.g. a Postgres JSON column `:type/XML` -- an actual native XML data column `:type/Structured` columns are ones that are stored as text, but should be treated as a `:type/Collection` base type = :type/Text coercion strategy = :Coercion/SerializedJSON effective type = :type/JSON but for the time being we'll have to live with these being "weird" semantic types. Other Relation types Coercion strategies ---------------------------------------------------- Util Fns ----------------------------------------------------
(ns metabase.types "The Metabase Hierarchical Type System (MHTS). This is a hierarchy where types derive from one or more parent types, which in turn derive from their own parents. This makes it possible to add new types without needing to add corresponding mappings in the frontend or other places. For example, a Database may want a type called something continue to treat it as such until further notice. There are a few different keyword hierarchies below: ### Data (Base/Effective) Types -- keys starting with `:type/` and deriving from `:type/*`, but not `:Semantic/*` or `:Relation/*` The 'base type' represents the actual data type of the column in the data warehouse. The 'effective type' is the coercion strategy (see below). Example: a `VARCHAR` column might have a base type of `:type/Text`, but store of `:type/DateTime` and the coercion strategy `:Coercion/ISO8601->DateTime` ### Coercion Strategies -- keys starting with `:Coercion/` These strategies tell us how to coerce a column from its base type to it effective type when the two differ. For example, `:Coercion/ISO8601->DateTime` can be used to tell us how to interpret a `VARCHAR` column (base type = `:type/Text`) as a `:type/DateTime` column (effective type). This depends of the database, but we might do something like using a `parse_timestamp()` function whenever we fetch this column. ### Semantic Types -- types starting with `:type/*` and deriving from `:Semantic/*` NOTE: In the near future we plan to rename the semantic types so they start with `:Semantic/` rather than `:type/`. These types represent the semantic meaning/interpretation/purpose of a column in the data warehouse, for example `:type/UpdatedTimestamp`. This affects things like how we display this column or how we generate Automagic data type is `TIMESTAMP` and thus its base type would be `:type/DateTime`. There is no such thing as an one. :Semantic types descend from data type(s) that are allowed to have this semantic type. For example, `:type/UpdatedTimestamp` descends from `:type/DateTime`, which means a column with an effective type of would make no sense. (Unless maybe `false` meant `1970-01-01T00:00:00Z` and `true` meant `1970-01-01T00:00:01Z`, but I think we can agree that's dumb.) ### Relation Type -- types starting with `:type/*` and deriving from `:Relation/*` NOTE: As with Semantic types, in the near future we'll change the relation types so they all start with `:Relation/`. Types that have to do with whether this column is a primary key or foreign key. These are currently stored in the `semantic_type` column, but we'll split them out into a separate `relation_type` column in the future. ### Entity Types -- keys starting with `:entity/` These are used to record the semantic purpose of a Table." #?@(:clj [(:require [clojure.set :as set] [metabase.types.coercion-hierarchies :as coercion-hierarchies])] :cljs [(:require [clojure.set :as set] [metabase.shared.util :as shared.u] [metabase.types.coercion-hierarchies :as coercion-hierarchies])])) (derive :entity/GenericTable :entity/*) (derive :entity/UserTable :entity/GenericTable) (derive :entity/CompanyTable :entity/GenericTable) (derive :entity/TransactionTable :entity/GenericTable) (derive :entity/ProductTable :entity/GenericTable) (derive :entity/SubscriptionTable :entity/GenericTable) (derive :entity/EventTable :entity/GenericTable) (derive :entity/GoogleAnalyticsTable :entity/GenericTable) (derive :type/Number :type/*) (derive :type/Integer :type/Number) (derive :type/BigInteger :type/Integer) (derive :type/Quantity :Semantic/*) (derive :type/Quantity :type/Integer) ` : type / Float ` means any number with a decimal place ! It does n't explicitly mean a 32 - bit or 64 - bit floating - point (derive :type/Float :type/Number) ` : type / Decimal ` means a column that is actually stored as an arbitrary - precision decimal type , e.g. ` BigDecimal ` or ` DECIMAL ` . For fixed - precision columns , just use ` : type / Float ` (derive :type/Decimal :type/Float) (derive :type/Share :Semantic/*) (derive :type/Share :type/Float) a ` DECIMAL ` ( base type ` : type / Decimal ` ) column can also have a semantic type ` : type / Currency ` . (derive :type/Currency :type/Decimal) (derive :type/Currency :Semantic/*) (derive :type/Income :type/Currency) (derive :type/Discount :type/Currency) (derive :type/Price :type/Currency) (derive :type/GrossMargin :type/Currency) (derive :type/Cost :type/Currency) (derive :type/Location :Semantic/*) (derive :type/Coordinate :type/Location) (derive :type/Coordinate :type/Float) (derive :type/Latitude :type/Coordinate) (derive :type/Longitude :type/Coordinate) (derive :type/Score :Semantic/*) (derive :type/Score :type/Number) (derive :type/Duration :Semantic/*) (derive :type/Duration :type/Number) (derive :type/Text :type/*) (derive :type/UUID :type/Text) (derive :type/URL :Semantic/*) (derive :type/URL :type/Text) (derive :type/ImageURL :type/URL) (derive :type/AvatarURL :type/ImageURL) (derive :type/Email :Semantic/*) (derive :type/Email :type/Text) should have their FieldValues cached and synced . See (derive :type/Category :Semantic/*) (derive :type/Enum :Semantic/*) (derive :type/Address :type/Location) (derive :type/City :type/Address) (derive :type/City :type/Category) (derive :type/City :type/Text) (derive :type/State :type/Address) (derive :type/State :type/Category) (derive :type/State :type/Text) (derive :type/Country :type/Address) (derive :type/Country :type/Category) (derive :type/Country :type/Text) (derive :type/ZipCode :type/Address) (derive :type/ZipCode :type/Text) (derive :type/Name :type/Category) (derive :type/Name :type/Text) (derive :type/Title :type/Category) (derive :type/Title :type/Text) (derive :type/Description :Semantic/*) (derive :type/Description :type/Text) (derive :type/Comment :Semantic/*) (derive :type/Comment :type/Text) (derive :type/PostgresEnum :type/Text) (derive :type/Temporal :type/*) (derive :type/Date :type/Temporal) You could have Dates with TZ info but it 's not supported by JSR-310 so we 'll not worry about that for now . (derive :type/Time :type/Temporal) (derive :type/TimeWithTZ :type/Time) (derive :type/DateTime :type/Temporal) (derive :type/DateTimeWithTZ :type/DateTime) a column that stores its timezone offset , e.g. ` -08:00 ` a column that stores its timezone ID , e.g. ` US / Pacific ` An ` Instant ` is a timestamp in ( milli-)seconds since the epoch , UTC . Since it does n't store TZ information , but is normalized to UTC , it is a DateTimeWithLocalTZ (derive :type/Instant :type/DateTimeWithLocalTZ) TODO -- should n't we have a ` : type / LocalDateTime ` as well ? (derive :type/CreationTemporal :Semantic/*) (derive :type/CreationTimestamp :type/CreationTemporal) (derive :type/CreationTimestamp :type/DateTime) (derive :type/CreationTime :type/CreationTemporal) (derive :type/CreationTime :type/Time) (derive :type/CreationDate :type/CreationTemporal) (derive :type/CreationDate :type/Date) (derive :type/JoinTemporal :Semantic/*) (derive :type/JoinTimestamp :type/JoinTemporal) (derive :type/JoinTimestamp :type/DateTime) (derive :type/JoinTime :type/JoinTemporal) (derive :type/JoinTime :type/Time) (derive :type/JoinDate :type/JoinTemporal) (derive :type/JoinDate :type/Date) (derive :type/CancelationTemporal :Semantic/*) (derive :type/CancelationTimestamp :type/CancelationTemporal) (derive :type/CancelationTimestamp :type/DateTime) (derive :type/CancelationTime :type/CancelationTemporal) (derive :type/CancelationTime :type/Date) (derive :type/CancelationDate :type/CancelationTemporal) (derive :type/CancelationDate :type/Date) (derive :type/DeletionTemporal :Semantic/*) (derive :type/DeletionTimestamp :type/DeletionTemporal) (derive :type/DeletionTimestamp :type/DateTime) (derive :type/DeletionTime :type/DeletionTemporal) (derive :type/DeletionTime :type/Time) (derive :type/DeletionDate :type/DeletionTemporal) (derive :type/DeletionDate :type/Date) (derive :type/UpdatedTemporal :Semantic/*) (derive :type/UpdatedTimestamp :type/UpdatedTemporal) (derive :type/UpdatedTimestamp :type/DateTime) (derive :type/UpdatedTime :type/UpdatedTemporal) (derive :type/UpdatedTime :type/Time) (derive :type/UpdatedDate :type/UpdatedTemporal) (derive :type/UpdatedDate :type/Date) (derive :type/Birthdate :Semantic/*) (derive :type/Birthdate :type/Date) (derive :type/Boolean :type/*) (derive :type/DruidHyperUnique :type/*) (derive :type/TextLike :type/*) (derive :type/MongoBSONID :type/TextLike) (derive :type/IPAddress :type/TextLike) (derive :type/IPAddress :Semantic/*) Structured / Collections (derive :type/Collection :type/*) (derive :type/Structured :type/*) (derive :type/Dictionary :type/Collection) (derive :type/Array :type/Collection) (derive :type/JSON :type/Structured) (derive :type/JSON :type/Collection) (derive :type/XML :type/Structured) (derive :type/XML :type/Collection) column ( e.g. JSON or XML ) . These should probably be coercion strategies instead , e.g. (derive :type/Structured :Semantic/*) (derive :type/Structured :type/Text) (derive :type/SerializedJSON :type/Structured) (derive :type/XML :type/Structured) (derive :type/User :Semantic/*) (derive :type/Author :type/User) (derive :type/Owner :type/User) (derive :type/Product :type/Category) (derive :type/Company :type/Category) (derive :type/Subscription :type/Category) (derive :type/Source :type/Category) (derive :type/FK :Relation/*) (derive :type/PK :Relation/*) (derive :Coercion/String->Temporal :Coercion/*) (derive :Coercion/ISO8601->Temporal :Coercion/String->Temporal) (derive :Coercion/ISO8601->DateTime :Coercion/ISO8601->Temporal) (derive :Coercion/ISO8601->Time :Coercion/ISO8601->Temporal) (derive :Coercion/ISO8601->Date :Coercion/ISO8601->Temporal) (derive :Coercion/YYYYMMDDHHMMSSString->Temporal :Coercion/String->Temporal) (derive :Coercion/Bytes->Temporal :Coercion/*) (derive :Coercion/YYYYMMDDHHMMSSBytes->Temporal :Coercion/Bytes->Temporal) (derive :Coercion/Number->Temporal :Coercion/*) (derive :Coercion/UNIXTime->Temporal :Coercion/Number->Temporal) (derive :Coercion/UNIXSeconds->DateTime :Coercion/UNIXTime->Temporal) (derive :Coercion/UNIXMilliSeconds->DateTime :Coercion/UNIXTime->Temporal) (derive :Coercion/UNIXMicroSeconds->DateTime :Coercion/UNIXTime->Temporal) (defn field-is-type? "True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value relating to a moment in time." [tyype {base-type :base_type, effective-type :effective_type}] (some #(isa? % tyype) [base-type effective-type])) (defn temporal-field? "True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value relating to a moment in time." [field] (field-is-type? :type/Temporal field)) #?(:cljs (defn ^:export isa "Is `x` the same as, or a descendant type of, `y`?" [x y] (isa? (keyword x) (keyword y)))) #?(:cljs (def ^:export TYPE "A map of Type name (as string, without `:type/` namespace) -> qualified type name as string {\"Temporal\" \"type/Temporal\", ...}" (clj->js (into {} (for [tyype (distinct (mapcat descendants [:type/* :Semantic/* :Relation/*]))] [(name tyype) (shared.u/qualified-name tyype)]))))) (coercion-hierarchies/define-types! :Coercion/UNIXMicroSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/UNIXMilliSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/UNIXSeconds->DateTime #{:type/Integer :type/Decimal} :type/Instant) (coercion-hierarchies/define-types! :Coercion/ISO8601->Date :type/Text :type/Date) (coercion-hierarchies/define-types! :Coercion/ISO8601->DateTime :type/Text :type/DateTime) (coercion-hierarchies/define-types! :Coercion/ISO8601->Time :type/Text :type/Time) (coercion-hierarchies/define-types! :Coercion/YYYYMMDDHHMMSSString->Temporal :type/Text :type/DateTime) (coercion-hierarchies/define-non-inheritable-type! :Coercion/YYYYMMDDHHMMSSBytes->Temporal :type/* :type/DateTime) (defn is-coercible-from? "Whether `coercion-strategy` is allowed for `base-type`." [coercion-strategy base-type] (or (isa? (coercion-hierarchies/base-type-hierarchy) base-type coercion-strategy) (boolean (some-> (coercion-hierarchies/non-descending-strategies) (get base-type) (contains? coercion-strategy))))) (defn is-coercible-to? "Whether `coercion-strategy` coerces to `effective-type` or some subtype thereof." [coercion-strategy effective-type] (isa? (coercion-hierarchies/effective-type-hierarchy) coercion-strategy effective-type)) (defn is-coercible? "Whether `coercion-strategy` is allowed for `base-type` and coerces to `effective-type` or some subtype thereof." [coercion-strategy base-type effective-type] (and (is-coercible-from? coercion-strategy base-type) (is-coercible-to? coercion-strategy effective-type))) (defn coercion-possibilities "Possible coercions for a base type, returned as a map of `effective-type -> #{coercion-strategy}`" [base-type] (let [base-type-hierarchy (coercion-hierarchies/base-type-hierarchy) effective-type-hierarchy (coercion-hierarchies/effective-type-hierarchy)] (->> (for [strategy (ancestors base-type-hierarchy base-type) :when (isa? strategy :Coercion/*) :let [effective-types (parents effective-type-hierarchy strategy)] effective-type effective-types :when (not (isa? effective-type :Coercion/*))] {effective-type #{strategy}}) (reduce (partial merge-with set/union) (select-keys (coercion-hierarchies/non-descending-strategies) [base-type])) not-empty))) (defn ^:export is_coerceable "Returns a boolean of whether a field base-type has any coercion strategies available." [base-type] (boolean (not-empty (coercion-possibilities (keyword base-type))))) (defn effective-type-for-coercion "The effective type resulting from a coercion." [coercion] (coercion-hierarchies/effective-type-for-strategy coercion)) (defn ^:export coercions_for_type "Coercions available for a type. In cljs will return a js array of strings like [\"Coercion/ISO8601->Time\" ...]. In clojure will return a sequence of keywords." [base-type] (let [applicable (into () (comp (distinct) cat) (vals (coercion-possibilities (keyword base-type))))] #?(:cljs (clj->js (map (fn [kw] (str (namespace kw) "/" (name kw))) applicable)) :clj applicable)))
50e3df9b9df53582b4a131cb0e75a5bd373ce88d3141fd6c5f869eace7ac6cfe
gvolpe/haskell-book-exercises
intermission.hs
data TisAnInteger = TisAn Integer instance Eq TisAnInteger where (==) (TisAn v) (TisAn v') = v == v' data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two a b) (Two a' b') = a == a' && b == b' data StringOrInt = TisAnInt Int | TisAString String instance Eq StringOrInt where (==) (TisAnInt v) (TisAnInt v') = v == v' (==) (TisAString v) (TisAString v') = v == v' (==) (_) (_) = False data Pair a = Pair a a instance Eq a => Eq (Pair a) where (==) (Pair x y) (Pair x' y') = x == x' && y == y' data Tuple a b = Tuple a b instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple x y) (Tuple x' y') = x == x' && y == y' data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne x) (ThisOne x') = x == x' (==) (ThatOne x) (ThatOne x') = x == x' (==) (_) (_) = False data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello x) (Hello x') = x == x' (==) (Goodbye x) (Goodbye x') = x == x' (==) (_) (_) = False
null
https://raw.githubusercontent.com/gvolpe/haskell-book-exercises/5c1b9d8dc729ee5a90c8709b9c889cbacb30a2cb/chapter6/intermission.hs
haskell
data TisAnInteger = TisAn Integer instance Eq TisAnInteger where (==) (TisAn v) (TisAn v') = v == v' data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two a b) (Two a' b') = a == a' && b == b' data StringOrInt = TisAnInt Int | TisAString String instance Eq StringOrInt where (==) (TisAnInt v) (TisAnInt v') = v == v' (==) (TisAString v) (TisAString v') = v == v' (==) (_) (_) = False data Pair a = Pair a a instance Eq a => Eq (Pair a) where (==) (Pair x y) (Pair x' y') = x == x' && y == y' data Tuple a b = Tuple a b instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple x y) (Tuple x' y') = x == x' && y == y' data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne x) (ThisOne x') = x == x' (==) (ThatOne x) (ThatOne x') = x == x' (==) (_) (_) = False data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello x) (Hello x') = x == x' (==) (Goodbye x) (Goodbye x') = x == x' (==) (_) (_) = False
06efb291430ef5b4be5f92dd03676126677b2989bfdb8b29348a4c31c8923815
jaspervdj/tweetov
Markov.hs
-- | Generate tweets based on markov chains. -- {-# LANGUAGE OverloadedStrings #-} module Tweetov.Twitter.Markov ( markovTweet ) where import Data.Text (Text) import qualified Data.Text as T import Data.Char (isAlphaNum) import Tweetov.Twitter (Tweet (..)) import Tweetov.Data.Markov -- | Extract a 'Sample' from a tweet. -- sampleFromTweet :: Tweet -> Sample Text sampleFromTweet = Sample . filter (not . T.null) . map (T.filter (`notElem` "()\"")) . filter goodWord . tweetWords where goodWord = T.any isAlphaNum -- | Generate a random tweet -- markovTweet :: Text -- ^ Author -> [Tweet] -- ^ Tweet samples -> [Int] -- ^ Random pool -> Tweet -- ^ Result markovTweet author tweets seeds = let samples = map sampleFromTweet tweets model = fromSamples True samples in Tweet { tweetWords = sentence tooLarge model seeds , tweetAuthor = author } -- | Check if a tweet is already too large -- tooLarge :: [Text] -> Bool tooLarge ls = length ls + sum (map T.length ls) > 140
null
https://raw.githubusercontent.com/jaspervdj/tweetov/b310da0844ed9bfe8696ffba6f70ea0194dd6144/src/Tweetov/Twitter/Markov.hs
haskell
| Generate tweets based on markov chains. # LANGUAGE OverloadedStrings # | Extract a 'Sample' from a tweet. | Generate a random tweet ^ Author ^ Tweet samples ^ Random pool ^ Result | Check if a tweet is already too large
module Tweetov.Twitter.Markov ( markovTweet ) where import Data.Text (Text) import qualified Data.Text as T import Data.Char (isAlphaNum) import Tweetov.Twitter (Tweet (..)) import Tweetov.Data.Markov sampleFromTweet :: Tweet -> Sample Text sampleFromTweet = Sample . filter (not . T.null) . map (T.filter (`notElem` "()\"")) . filter goodWord . tweetWords where goodWord = T.any isAlphaNum markovTweet author tweets seeds = let samples = map sampleFromTweet tweets model = fromSamples True samples in Tweet { tweetWords = sentence tooLarge model seeds , tweetAuthor = author } tooLarge :: [Text] -> Bool tooLarge ls = length ls + sum (map T.length ls) > 140
8f68df0626151cf592e345f0cc21c6ebc253a65d77dbc9674a4735f3d1d2ea35
yzhs/ocamlllvm
misc.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : misc.ml 7909 2007 - 02 - 23 13:44:51Z ertai $ (* Errors *) exception Fatal_error let fatal_error msg = prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error (* Exceptions *) let try_finally f1 f2 = try let result = f1 () in f2 (); result with x -> f2 (); raise x ;; (* List functions *) let rec map_end f l1 l2 = match l1 with [] -> l2 | hd::tl -> f hd :: map_end f tl l2 let rec map_left_right f = function [] -> [] | hd::tl -> let res = f hd in res :: map_left_right f tl let rec for_all2 pred l1 l2 = match (l1, l2) with ([], []) -> true | (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2 | (_, _) -> false let rec replicate_list elem n = if n <= 0 then [] else elem :: replicate_list elem (n-1) let rec list_remove x = function [] -> [] | hd :: tl -> if hd = x then tl else hd :: list_remove x tl let rec split_last = function [] -> assert false | [x] -> ([], x) | hd :: tl -> let (lst, last) = split_last tl in (hd :: lst, last) let rec samelist pred l1 l2 = match (l1, l2) with | ([], []) -> true | (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2 | (_, _) -> false (* Options *) let may f = function Some x -> f x | None -> () let may_map f = function Some x -> Some (f x) | None -> None (* File functions *) let find_in_path path name = if not (Filename.is_implicit name) then if Sys.file_exists name then name else raise Not_found else begin let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path end let find_in_path_uncap path name = let uname = String.uncapitalize name in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name and ufullname = Filename.concat dir uname in if Sys.file_exists ufullname then ufullname else if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let remove_file filename = try Sys.remove filename with Sys_error msg -> () (* Expand a -I option: if it starts with +, make it relative to the standard library directory *) let expand_directory alt s = if String.length s > 0 && s.[0] = '+' then Filename.concat alt (String.sub s 1 (String.length s - 1)) else s (* Hashtable functions *) let create_hashtable size init = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl (* File copy *) let copy_file ic oc = let buff = String.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then () else (output oc buff 0 n; copy()) in copy() let copy_file_chunk ic oc len = let buff = String.create 0x1000 in let rec copy n = if n <= 0 then () else begin let r = input ic buff 0 (min n 0x1000) in if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r)) end in copy len Integer operations let rec log2 n = if n <= 1 then 0 else 1 + log2(n asr 1) let align n a = if n >= 0 then (n + a - 1) land (-a) else n land (-a) let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0 let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0 let no_overflow_lsl a = min_int asr 1 <= a && a <= max_int asr 1 (* String operations *) let chop_extension_if_any fname = try Filename.chop_extension fname with Invalid_argument _ -> fname let chop_extensions file = let dirname = Filename.dirname file and basename = Filename.basename file in try let pos = String.index basename '.' in let basename = String.sub basename 0 pos in if Filename.is_implicit file && dirname = Filename.current_dir_name then basename else Filename.concat dirname basename with Not_found -> file let search_substring pat str start = let rec search i j = if j >= String.length pat then i else if i + j >= String.length str then raise Not_found else if str.[i + j] = pat.[j] then search i (j+1) else search (i+1) 0 in search start 0 let rev_split_words s = let rec split1 res i = if i >= String.length s then res else begin match s.[i] with ' ' | '\t' | '\r' | '\n' -> split1 res (i+1) | _ -> split2 res i (i+1) end and split2 res i j = if j >= String.length s then String.sub s i (j-i) :: res else begin match s.[j] with ' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1) | _ -> split2 res i (j+1) end in split1 [] 0
null
https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/utils/misc.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* Errors Exceptions List functions Options File functions Expand a -I option: if it starts with +, make it relative to the standard library directory Hashtable functions File copy String operations
, 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 Q Public License version 1.0 . $ I d : misc.ml 7909 2007 - 02 - 23 13:44:51Z ertai $ exception Fatal_error let fatal_error msg = prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error let try_finally f1 f2 = try let result = f1 () in f2 (); result with x -> f2 (); raise x ;; let rec map_end f l1 l2 = match l1 with [] -> l2 | hd::tl -> f hd :: map_end f tl l2 let rec map_left_right f = function [] -> [] | hd::tl -> let res = f hd in res :: map_left_right f tl let rec for_all2 pred l1 l2 = match (l1, l2) with ([], []) -> true | (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2 | (_, _) -> false let rec replicate_list elem n = if n <= 0 then [] else elem :: replicate_list elem (n-1) let rec list_remove x = function [] -> [] | hd :: tl -> if hd = x then tl else hd :: list_remove x tl let rec split_last = function [] -> assert false | [x] -> ([], x) | hd :: tl -> let (lst, last) = split_last tl in (hd :: lst, last) let rec samelist pred l1 l2 = match (l1, l2) with | ([], []) -> true | (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2 | (_, _) -> false let may f = function Some x -> f x | None -> () let may_map f = function Some x -> Some (f x) | None -> None let find_in_path path name = if not (Filename.is_implicit name) then if Sys.file_exists name then name else raise Not_found else begin let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path end let find_in_path_uncap path name = let uname = String.uncapitalize name in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name and ufullname = Filename.concat dir uname in if Sys.file_exists ufullname then ufullname else if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let remove_file filename = try Sys.remove filename with Sys_error msg -> () let expand_directory alt s = if String.length s > 0 && s.[0] = '+' then Filename.concat alt (String.sub s 1 (String.length s - 1)) else s let create_hashtable size init = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl let copy_file ic oc = let buff = String.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then () else (output oc buff 0 n; copy()) in copy() let copy_file_chunk ic oc len = let buff = String.create 0x1000 in let rec copy n = if n <= 0 then () else begin let r = input ic buff 0 (min n 0x1000) in if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r)) end in copy len Integer operations let rec log2 n = if n <= 1 then 0 else 1 + log2(n asr 1) let align n a = if n >= 0 then (n + a - 1) land (-a) else n land (-a) let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0 let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0 let no_overflow_lsl a = min_int asr 1 <= a && a <= max_int asr 1 let chop_extension_if_any fname = try Filename.chop_extension fname with Invalid_argument _ -> fname let chop_extensions file = let dirname = Filename.dirname file and basename = Filename.basename file in try let pos = String.index basename '.' in let basename = String.sub basename 0 pos in if Filename.is_implicit file && dirname = Filename.current_dir_name then basename else Filename.concat dirname basename with Not_found -> file let search_substring pat str start = let rec search i j = if j >= String.length pat then i else if i + j >= String.length str then raise Not_found else if str.[i + j] = pat.[j] then search i (j+1) else search (i+1) 0 in search start 0 let rev_split_words s = let rec split1 res i = if i >= String.length s then res else begin match s.[i] with ' ' | '\t' | '\r' | '\n' -> split1 res (i+1) | _ -> split2 res i (i+1) end and split2 res i j = if j >= String.length s then String.sub s i (j-i) :: res else begin match s.[j] with ' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1) | _ -> split2 res i (j+1) end in split1 [] 0
6162862143be415b27513b59bceb01341529c46cea75a1dd97887bc924a1c238
parapluu/Concuerror
depend_4_2.erl
-module(depend_4_2). -export([result/0, procs/0, run/1]). result() -> io:format("20"). procs() -> io:format("6"). run(Procs) -> [S] = io_lib:format("~p",[Procs]), initial(), run_aux(S), block(). run_aux([]) -> ok; run_aux([P|R]) -> spawn(fun() -> proc(P) end), run_aux(R). block() -> receive after infinity -> never end. initial() -> ets:new(table, [public, named_table]), ets:insert(table, {x, 0}), ets:insert(table, {y, 0}), ets:insert(table, {z, 0}). proc($1) -> ets:insert(table, {z, 1}); proc($2) -> ets:insert(table, {x, 1}); proc($3) -> ets:insert(table, {y, 1}); proc($4) -> [{x, X}] = ets:lookup(table, x), case X of 1 -> [{y, Y}] = ets:lookup(table, y), case Y of 1 -> ets:lookup(table, z); _ -> ok end; _ -> ok end; proc($5) -> ets:lookup(table, y); proc($6) -> ets:insert(table, {x, 2}).
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/resources/perm_tests/src/depend_4_2.erl
erlang
-module(depend_4_2). -export([result/0, procs/0, run/1]). result() -> io:format("20"). procs() -> io:format("6"). run(Procs) -> [S] = io_lib:format("~p",[Procs]), initial(), run_aux(S), block(). run_aux([]) -> ok; run_aux([P|R]) -> spawn(fun() -> proc(P) end), run_aux(R). block() -> receive after infinity -> never end. initial() -> ets:new(table, [public, named_table]), ets:insert(table, {x, 0}), ets:insert(table, {y, 0}), ets:insert(table, {z, 0}). proc($1) -> ets:insert(table, {z, 1}); proc($2) -> ets:insert(table, {x, 1}); proc($3) -> ets:insert(table, {y, 1}); proc($4) -> [{x, X}] = ets:lookup(table, x), case X of 1 -> [{y, Y}] = ets:lookup(table, y), case Y of 1 -> ets:lookup(table, z); _ -> ok end; _ -> ok end; proc($5) -> ets:lookup(table, y); proc($6) -> ets:insert(table, {x, 2}).
46d46efcc8a1358a4e6742c750e6abdf13fbcbe69abd072455f252239551cded
mmzeeman/elli_websocket
elli_ws_request_adapter.erl
@author < > 2013 %% @doc . %% Copyright 2013 %% 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(elli_ws_request_adapter). -include_lib("elli/include/elli.hrl"). -export([ init/2, get/2, maybe_reply/2, ensure_response/2, upgrade_reply/3, parse_header/2, header/2, set_meta/3]). -export([ websocket_handler_init/3, websocket_handler_callback/5, websocket_handler_handle_event/5 ]). %% Helper function. -export([messages/1]). -export_type([req/0]). %% Request adapter record. -record(req_adapter, { req :: elli:req(), %% If set to true we check if we can compress. resp_compress = false :: boolean(), %% Headers to add to the response. resp_headers = [] :: elli:headers(), %% TODO: should become elli:headers(). %% sent_upgrade_reply = false :: boolean(), %% Possible meta values. websocket_version=undefined :: undefined | integer(), websocket_compress=false :: boolean() }). -type req() :: #req_adapter{}. %% %% %% % @doc Initialize the request helper % -spec init(Req :: elli:req(), RespCompress :: boolean()) -> req(). init(Req, RespCompress) -> #req_adapter{req=Req, resp_compress=RespCompress}. @doc Mimics cowboy_req : get/2 % -spec get(atom() | list(), req()) -> any() | list(). get(socket, ReqAdapter) -> Req = ReqAdapter#req_adapter.req, Req#req.socket; get(resp_compress, ReqAdapter) -> ReqAdapter#req_adapter.resp_compress; get(websocket_version, ReqAdapter) -> ReqAdapter#req_adapter.websocket_version; get(websocket_compress, ReqAdapter) -> ReqAdapter#req_adapter.websocket_compress; get(L, Req) when is_list(L) -> get(L, Req, []). get([], _Req, Acc) -> lists:reverse(Acc); get([H|T], Req, Acc) -> get(T, Req, [get(H, Req)|Acc]). % @doc Mimics cowboy_req:maybe_reply/2 % -spec maybe_reply(400, req()) -> ok. maybe_reply(400, ReqAdapter) -> case ReqAdapter#req_adapter.sent_upgrade_reply of true -> ok; false -> reply(400, ReqAdapter) end. % @doc Mimics cowboy_req:ensure_response/2 % -spec ensure_response(req(), 400) -> ok. ensure_response(ReqAdapter, 400) -> reply(400, ReqAdapter). %% %% Send an upgrade reply to the -spec upgrade_reply(101, elli:headers(), req()) -> {ok, req()}. upgrade_reply(101, Headers, #req_adapter{req=Req}=RA) -> UpgradeHeaders = [{<<"Connection">>, <<"Upgrade">>} | Headers], ok = elli_http:send_response(Req, 101, RA#req_adapter.resp_headers ++ UpgradeHeaders, <<>>), {ok, RA#req_adapter{sent_upgrade_reply=true}}. Note : The headers keys are already parsed by Erlang decode_packet . This %% means that all keys are capitalized. @doc Mimics cowboy_req : parse_header/3 { ok , ParsedHeaders , Req } % parse_header(<<"upgrade">>, #req_adapter{req=Req}=RA) -> %% case insensitive tokens. Values = get_header_values(<<"Upgrade">>, Req), {ok, elli_ws_http:tokens(Values), RA}; parse_header(<<"connection">>, #req_adapter{req=Req}=RA) -> Values = get_header_values(<<"Connection">>, Req), {ok, elli_ws_http:tokens(Values), RA}; parse_header(<<"sec-websocket-extensions">>, #req_adapter{req=Req}=RA) -> Values = get_header_values(<<"Sec-WebSocket-Extensions">>, Req), %% We only recognize x-webkit-deflate-frame, which has no args, %% skip the rest. Exts = elli_ws_http:tokens(Values), Extensions = [{E, []} || E <- Exts, E =:= <<"x-webkit-deflate-frame">>], {ok, Extensions, RA}. % @doc Mimics cowboy_req:header/2 % header(<<"sec-websocket-version">>, #req_adapter{req=Req}=RA) -> {get_header_value(<<"Sec-WebSocket-Version">>, Req), RA}; header(<<"sec-websocket-key">>, #req_adapter{req=Req}=RA) -> {get_header_value(<<"Sec-Websocket-Key">>, Req), RA}. % @doc Mimics cowboy_req:set_meta/3 % set_meta(websocket_version, Version, ReqAdapter) -> ReqAdapter#req_adapter{websocket_version = Version}; set_meta(websocket_compress, Bool, ReqAdapter) -> ReqAdapter#req_adapter{websocket_compress = Bool}. % @doc Call the websocket_init callback of the websocket handler. % calls websocket_init(Req , HandlerOpts ) - > % {ok, Headers, HandlerState} - We can upgrade, headers are added to the upgrade response. % {ok, Headers, hibernate, HandlerState} - We can upgrade, but this process will hibernate, headers % are added to the upgrade response % {ok, Headers, Timeout, HandlerState} - We can upgrade, we will timout, headers are added to the % upgrade respose. % {ok, Headers, hibernate, Timeout, HandlerState} - We can upgrade, set a timeout and hibernate. % Headers are added to the response. % {shutdown, Headers} - We can't upgrade, a bad request response will be sent to the client. % -spec websocket_handler_init(req(), Handler :: module(), HandlerState :: any()) -> {shutdown, req()} | {ok, req(), any()} | {ok, req(), any(), hibernate} | {ok, req(), any(), Timeout :: non_neg_integer()} | {ok, req(), any(), Timeout :: non_neg_integer(), hibernate}. websocket_handler_init(#req_adapter{req=Req}=RA, Handler, HandlerOpts) -> case Handler:websocket_init(Req, HandlerOpts) of {shutdown, Headers} -> {shutdown, RA#req_adapter{resp_headers=Headers}}; {ok, Headers, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState}; {ok, Headers, hibernate, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, hibernate}; {ok, Headers, Timeout, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, Timeout}; {ok, Headers, hibernate, Timeout, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, Timeout, hibernate} end. % @doc Calls websocket_info en websocket_handle callbacks. -spec websocket_handler_callback(req(), Handler :: module(), websocket_info | websocket_handle, Message :: any(), HandlerState :: any()) -> {ok, req(), any()} | {ok, req(), any(), hibernate} | {reply, binary() | iolist(), req(), any()} | {reply, binary() | iolist(), hibernate, req(), any()} | {shutdown, req(), any()}. websocket_handler_callback(#req_adapter{req=Req}=RA, Handler, Callback, Message, HandlerState) -> case Handler:Callback(Req, Message, HandlerState) of {ok, HandlerState1} -> {ok, RA, HandlerState1}; {ok, hibernate, HandlerState1} -> {ok, RA, HandlerState1, hibernate}; {reply, Payload, HandlerState1} -> {reply, Payload, RA, HandlerState1}; {reply, Payload, hibernate, HandlerState1} -> {reply, Payload, RA, HandlerState1, hibernate}; {shutdown, HandlerState1} -> {shutdown, RA, HandlerState1} end. % @doc Report an event... -spec websocket_handler_handle_event(req(), Handler :: module(), atom(), list(), any()) -> ok. websocket_handler_handle_event(#req_adapter{req=Req}, Handler, Name, EventArgs, HandlerOpts) -> try Handler:websocket_handle_event(Name, [Req|EventArgs], HandlerOpts) catch EvClass:EvError -> error_logger:error_msg("~p:handle_event/3 crashed ~p:~p~n~p", [Handler, EvClass, EvError, erlang:get_stacktrace()]) end. % @doc Atoms used to identify messages in {active, once | true} mode. -spec messages(RA :: req()) -> {tcp, tcp_closed, tcp_error} | {ssl, ssl_closed, ssl_error}. messages(#req_adapter{req=Req}) -> case Req#req.socket of undefined -> undefined; Socket -> socket_messages(Socket) end. -spec socket_messages(Socket :: elli_tcp:socket()) -> {tcp, tcp_closed, tcp_error} | {ssl, ssl_closed, ssl_error}. socket_messages({plain, _}) -> {tcp, tcp_closed, tcp_error}; socket_messages({ssl, _}) -> {ssl, ssl_closed, ssl_error}. %% %% Helpers %% % @doc Send a bad_request reply. % -spec reply(400, #req_adapter{}) -> ok. reply(400, #req_adapter{req=Req}) -> Body = <<"Bad request">>, Size = size(Body), ok = elli_http:send_response(Req, 400, [{"Connection", "close"}, {"Content-Length", Size}], Body). % @doc Get all header values for Key -spec get_header_values(binary(), elli:req()) -> [binary()]. get_header_values(Key, #req{headers=Headers}) -> elli_proplists:get_all_values_ci(Key, Headers). @doc Get the first value . -spec get_header_value(binary(), elli:req()) -> undefined | binary(). get_header_value(Key, #req{headers=Headers}) -> elli_proplists:get_value_ci(Key, Headers).
null
https://raw.githubusercontent.com/mmzeeman/elli_websocket/7545c031ef3d8cf67c2485121b369441ecb9d7c9/src/elli_ws_request_adapter.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. Helper function. Request adapter record. If set to true we check if we can compress. Headers to add to the response. TODO: should become elli:headers(). Possible meta values. @doc Initialize the request helper @doc Mimics cowboy_req:maybe_reply/2 @doc Mimics cowboy_req:ensure_response/2 Send an upgrade reply to the means that all keys are capitalized. case insensitive tokens. We only recognize x-webkit-deflate-frame, which has no args, skip the rest. @doc Mimics cowboy_req:header/2 @doc Mimics cowboy_req:set_meta/3 @doc Call the websocket_init callback of the websocket handler. {ok, Headers, HandlerState} - We can upgrade, headers are added to the upgrade response. {ok, Headers, hibernate, HandlerState} - We can upgrade, but this process will hibernate, headers are added to the upgrade response {ok, Headers, Timeout, HandlerState} - We can upgrade, we will timout, headers are added to the upgrade respose. {ok, Headers, hibernate, Timeout, HandlerState} - We can upgrade, set a timeout and hibernate. Headers are added to the response. {shutdown, Headers} - We can't upgrade, a bad request response will be sent to the client. @doc Calls websocket_info en websocket_handle callbacks. @doc Report an event... @doc Atoms used to identify messages in {active, once | true} mode. Helpers @doc Send a bad_request reply. @doc Get all header values for Key
@author < > 2013 @doc . Copyright 2013 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(elli_ws_request_adapter). -include_lib("elli/include/elli.hrl"). -export([ init/2, get/2, maybe_reply/2, ensure_response/2, upgrade_reply/3, parse_header/2, header/2, set_meta/3]). -export([ websocket_handler_init/3, websocket_handler_callback/5, websocket_handler_handle_event/5 ]). -export([messages/1]). -export_type([req/0]). -record(req_adapter, { req :: elli:req(), resp_compress = false :: boolean(), sent_upgrade_reply = false :: boolean(), websocket_version=undefined :: undefined | integer(), websocket_compress=false :: boolean() }). -type req() :: #req_adapter{}. -spec init(Req :: elli:req(), RespCompress :: boolean()) -> req(). init(Req, RespCompress) -> #req_adapter{req=Req, resp_compress=RespCompress}. @doc Mimics cowboy_req : get/2 -spec get(atom() | list(), req()) -> any() | list(). get(socket, ReqAdapter) -> Req = ReqAdapter#req_adapter.req, Req#req.socket; get(resp_compress, ReqAdapter) -> ReqAdapter#req_adapter.resp_compress; get(websocket_version, ReqAdapter) -> ReqAdapter#req_adapter.websocket_version; get(websocket_compress, ReqAdapter) -> ReqAdapter#req_adapter.websocket_compress; get(L, Req) when is_list(L) -> get(L, Req, []). get([], _Req, Acc) -> lists:reverse(Acc); get([H|T], Req, Acc) -> get(T, Req, [get(H, Req)|Acc]). -spec maybe_reply(400, req()) -> ok. maybe_reply(400, ReqAdapter) -> case ReqAdapter#req_adapter.sent_upgrade_reply of true -> ok; false -> reply(400, ReqAdapter) end. -spec ensure_response(req(), 400) -> ok. ensure_response(ReqAdapter, 400) -> reply(400, ReqAdapter). -spec upgrade_reply(101, elli:headers(), req()) -> {ok, req()}. upgrade_reply(101, Headers, #req_adapter{req=Req}=RA) -> UpgradeHeaders = [{<<"Connection">>, <<"Upgrade">>} | Headers], ok = elli_http:send_response(Req, 101, RA#req_adapter.resp_headers ++ UpgradeHeaders, <<>>), {ok, RA#req_adapter{sent_upgrade_reply=true}}. Note : The headers keys are already parsed by Erlang decode_packet . This @doc Mimics cowboy_req : parse_header/3 { ok , ParsedHeaders , Req } parse_header(<<"upgrade">>, #req_adapter{req=Req}=RA) -> Values = get_header_values(<<"Upgrade">>, Req), {ok, elli_ws_http:tokens(Values), RA}; parse_header(<<"connection">>, #req_adapter{req=Req}=RA) -> Values = get_header_values(<<"Connection">>, Req), {ok, elli_ws_http:tokens(Values), RA}; parse_header(<<"sec-websocket-extensions">>, #req_adapter{req=Req}=RA) -> Values = get_header_values(<<"Sec-WebSocket-Extensions">>, Req), Exts = elli_ws_http:tokens(Values), Extensions = [{E, []} || E <- Exts, E =:= <<"x-webkit-deflate-frame">>], {ok, Extensions, RA}. header(<<"sec-websocket-version">>, #req_adapter{req=Req}=RA) -> {get_header_value(<<"Sec-WebSocket-Version">>, Req), RA}; header(<<"sec-websocket-key">>, #req_adapter{req=Req}=RA) -> {get_header_value(<<"Sec-Websocket-Key">>, Req), RA}. set_meta(websocket_version, Version, ReqAdapter) -> ReqAdapter#req_adapter{websocket_version = Version}; set_meta(websocket_compress, Bool, ReqAdapter) -> ReqAdapter#req_adapter{websocket_compress = Bool}. calls websocket_init(Req , HandlerOpts ) - > -spec websocket_handler_init(req(), Handler :: module(), HandlerState :: any()) -> {shutdown, req()} | {ok, req(), any()} | {ok, req(), any(), hibernate} | {ok, req(), any(), Timeout :: non_neg_integer()} | {ok, req(), any(), Timeout :: non_neg_integer(), hibernate}. websocket_handler_init(#req_adapter{req=Req}=RA, Handler, HandlerOpts) -> case Handler:websocket_init(Req, HandlerOpts) of {shutdown, Headers} -> {shutdown, RA#req_adapter{resp_headers=Headers}}; {ok, Headers, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState}; {ok, Headers, hibernate, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, hibernate}; {ok, Headers, Timeout, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, Timeout}; {ok, Headers, hibernate, Timeout, HandlerState} -> {ok, RA#req_adapter{resp_headers=Headers}, HandlerState, Timeout, hibernate} end. -spec websocket_handler_callback(req(), Handler :: module(), websocket_info | websocket_handle, Message :: any(), HandlerState :: any()) -> {ok, req(), any()} | {ok, req(), any(), hibernate} | {reply, binary() | iolist(), req(), any()} | {reply, binary() | iolist(), hibernate, req(), any()} | {shutdown, req(), any()}. websocket_handler_callback(#req_adapter{req=Req}=RA, Handler, Callback, Message, HandlerState) -> case Handler:Callback(Req, Message, HandlerState) of {ok, HandlerState1} -> {ok, RA, HandlerState1}; {ok, hibernate, HandlerState1} -> {ok, RA, HandlerState1, hibernate}; {reply, Payload, HandlerState1} -> {reply, Payload, RA, HandlerState1}; {reply, Payload, hibernate, HandlerState1} -> {reply, Payload, RA, HandlerState1, hibernate}; {shutdown, HandlerState1} -> {shutdown, RA, HandlerState1} end. -spec websocket_handler_handle_event(req(), Handler :: module(), atom(), list(), any()) -> ok. websocket_handler_handle_event(#req_adapter{req=Req}, Handler, Name, EventArgs, HandlerOpts) -> try Handler:websocket_handle_event(Name, [Req|EventArgs], HandlerOpts) catch EvClass:EvError -> error_logger:error_msg("~p:handle_event/3 crashed ~p:~p~n~p", [Handler, EvClass, EvError, erlang:get_stacktrace()]) end. -spec messages(RA :: req()) -> {tcp, tcp_closed, tcp_error} | {ssl, ssl_closed, ssl_error}. messages(#req_adapter{req=Req}) -> case Req#req.socket of undefined -> undefined; Socket -> socket_messages(Socket) end. -spec socket_messages(Socket :: elli_tcp:socket()) -> {tcp, tcp_closed, tcp_error} | {ssl, ssl_closed, ssl_error}. socket_messages({plain, _}) -> {tcp, tcp_closed, tcp_error}; socket_messages({ssl, _}) -> {ssl, ssl_closed, ssl_error}. -spec reply(400, #req_adapter{}) -> ok. reply(400, #req_adapter{req=Req}) -> Body = <<"Bad request">>, Size = size(Body), ok = elli_http:send_response(Req, 400, [{"Connection", "close"}, {"Content-Length", Size}], Body). -spec get_header_values(binary(), elli:req()) -> [binary()]. get_header_values(Key, #req{headers=Headers}) -> elli_proplists:get_all_values_ci(Key, Headers). @doc Get the first value . -spec get_header_value(binary(), elli:req()) -> undefined | binary(). get_header_value(Key, #req{headers=Headers}) -> elli_proplists:get_value_ci(Key, Headers).
bad4f0aaad9847d9d95a2be77f7597557272c7f7a45d4ca8697c36a824f03477
nikomatsakis/a-mir-formality
implied-bounds--supertraits.rkt
#lang racket (require redex/reduction-semantics "../../util.rkt" "../grammar.rkt" "../prove.rkt" ) (module+ test (redex-let* formality-rust [(Rust/Program (term ([(crate C { (trait PartialEq[] where [] {}) (trait Eq[] where [(Self : PartialEq[])] {}) (trait Debug[] where [] {}) })] C)))] (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : PartialEq[])] (T : Eq[])))) #f)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : PartialEq[])))) #t)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : Eq[])))) #t)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : Debug[])))) #f)) ) )
null
https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/71be4d5c4bd5e91d326277eaedd19a7abe3ac76a/racket-src/rust/test/implied-bounds--supertraits.rkt
racket
#lang racket (require redex/reduction-semantics "../../util.rkt" "../grammar.rkt" "../prove.rkt" ) (module+ test (redex-let* formality-rust [(Rust/Program (term ([(crate C { (trait PartialEq[] where [] {}) (trait Eq[] where [(Self : PartialEq[])] {}) (trait Debug[] where [] {}) })] C)))] (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : PartialEq[])] (T : Eq[])))) #f)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : PartialEq[])))) #t)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : Eq[])))) #t)) (traced '() (test-equal (term (rust:can-prove-where-clause-in-program Rust/Program (∀ [(type T)] where [(T : Eq[])] (T : Debug[])))) #f)) ) )
bffc85b7b5b83ed8a1f97d4ed0dece84e629b4790137b23e1d5a7cd431c00685
webyrd/wreckto-verseo
absento-tests.scm
Tests for general absento , where the first argument is n't a ground atom . (test "test 0" (run* (q) (absento q q)) '()) (test "test 1" (run* (q) (fresh (a b c) (== a b) (absento b c) (== c b) (== `(,a ,b ,c) q))) '()) (test "test 2" (run* (q) (fresh (a) (absento q a) (absento `((,q ,q) 3 (,q ,q)) `(,a 3 ,a)))) '(_.0)) (test "test 3" (run* (q) (fresh (a b) (absento q a) (absento `(3 ,a) `(,b ,a)) (== 3 b))) '()) (test "test 4" (run* (q) (fresh (a b) (absento q a) (absento `(3 ,a) `(,q ,a)) (== 3 b))) '((_.0 (=/= ((_.0 3)))))) (test "test 5" (run* (q) (fresh (a b) (numbero a) (numbero b) (absento '(3 3) `(,a ,b)) (=/= a b) (== `(,a ,b) q))) '(((_.0 _.1) (=/= ((_.0 _.1))) (num _.0 _.1)))) (test "test 6" (run* (q) (fresh (a) (absento q a) (== q a))) '()) (test "test 7" (run* (q) (fresh (a b c) (absento '(3 . 4) c) (== `(,a . ,b) c) (== q `(,a . ,b)))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (absento ((3 . 4) _.0) ((3 . 4) _.1))))) (test "test 8" (run* (q) (fresh (a b) (absento 5 a) (symbolo b) (== `(,q ,b) a))) '((_.0 (absento (5 _.0))))) (test "test 9" (run* (q) (fresh (a b) (absento 5 a) (== `(,q ,b) a))) '((_.0 (absento (5 _.0))))) (test "test 10" (run* (q) (fresh (a) (absento `(3 . ,a) q) (absento q `(3 . ,a)))) '((_.0 (=/= ((_.0 3)))))) (test "test 11" (run* (q) (fresh (a b c d e f) (absento `(,a . ,b) q) (absento q `(,a . ,b)) (== `(,c . ,d) a) (== `(3 . ,e) c) (== `(,f . 4) d))) '((_.0 (=/= ((_.0 3)) ((_.0 4)))))) (test "test 12" (run* (q) (fresh (a b c) (absento `(,3 . ,a) `(,b . ,c)) (numbero b) (== `(,a ,b ,c) q))) '(((_.0 _.1 _.2) (=/= ((_.0 _.2) (_.1 3))) (num _.1) (absento ((3 . _.0) _.2))))) (test "test 13" (run* (q) (fresh (a b c) (== `(,a . ,b) q) (absento '(3 . 4) q) (numbero a) (numbero b))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (num _.0 _.1)))) (test "test 14" (run* (q) (fresh (a b) (absento '(3 . 4) `(,a . ,b)) (== `(,a . ,b) q))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (absento ((3 . 4) _.0) ((3 . 4) _.1))))) (test "test 15" (run* (q) (absento q `(3 . (4 . 5)))) '((_.0 (=/= ((_.0 3)) ((_.0 4)) ((_.0 5)) ((_.0 (3 . (4 . 5)))) ((_.0 (4 . 5))))))) (test "test 16" (run* (q) (fresh (a b x) (absento a b) (symbolo a) (numbero x) (== x b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 19" (run* (q) (absento 5 q) (absento 5 q)) '((_.0 (absento (5 _.0))))) (test "test 20" (run* (q) (absento 5 q) (absento 6 q)) '((_.0 (absento (5 _.0) (6 _.0))))) (test "test 21" (run* (q) (absento 5 q) (symbolo q)) '((_.0 (sym _.0)))) (test "test 22" (run* (q) (numbero q) (absento 'tag q)) '((_.0 (num _.0)))) (test "test 23" (run* (q) (absento 'tag q) (numbero q)) '((_.0 (num _.0)))) (test "test 24" (run* (q) (== 5 q) (absento 5 q)) '()) (test "test 25" (run* (q) (== q `(5 6)) (absento 5 q)) '()) (test "test 25b" (run* (q) (absento 5 q) (== q `(5 6))) '()) (test "test 26" (run* (q) (absento 5 q) (== 5 q)) '()) (test "test 27" (run* (q) (absento 'tag1 q) (absento 'tag2 q)) '((_.0 (absento (tag1 _.0) (tag2 _.0))))) (test "test 28" (run* (q) (absento 'tag q) (numbero q)) '((_.0 (num _.0)))) (test "test 29" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 30" (run* (q) (fresh (a b) (absento b a) (absento a b) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 31" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 32" (run* (q) (fresh (a b) (absento 5 a) (absento 5 b) (== `(,a . ,b) q))) '(((_.0 . _.1) (absento (5 _.0) (5 _.1))))) (test "test 33" (run* (q) (fresh (a b c) (== `(,a ,b) c) (== `(,c ,c) q) (symbolo b) (numbero c))) '()) (test "test 34" (run* (q) (absento 'tag q) (symbolo q)) '((_.0 (=/= ((_.0 tag))) (sym _.0)))) (test "test 35" (run* (q) (absento 5 q) (numbero q)) '((_.0 (=/= ((_.0 5))) (num _.0)))) (test "test 36" (run* (q) (fresh (a) (== 5 a) (absento a q))) '((_.0 (absento (5 _.0))))) (test "test 37" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 38" (run* (q) (absento '() q)) '((_.0 (absento (() _.0))))) (test "test 39" (run* (q) (absento `(3 4) q)) '((_.0 (absento ((3 4) _.0))))) (test "test 40" (run* (q) (fresh (d a c) (== `(3 . ,d) q) (=/= `(,c . ,a) q) (== '(3 . 4) d))) '((3 3 . 4))) (test "test 41" (run* (q) (fresh (a) (== `(,a . ,a) q))) '((_.0 . _.0))) (test "test 42" (run* (q) (fresh (a b) (== `((3 4) (5 6)) q) (absento `(3 4) q))) '()) (test "test 43" (run* (q) (absento q 3)) '((_.0 (=/= ((_.0 3)))))) (test "test 44" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 45" (run* (q) (fresh (a b) (absento `(,a . ,b) q) (== q `(3 . (,b . ,b))))) '((3 _.0 . _.0))) (test "test 45b" (run* (q) (fresh (a b) (absento `(,a . ,b) q) (== q `(,a 3 . (,b . ,b))))) '(((_.0 3 _.1 . _.1) (=/= ((_.0 _.1)))))) (test "test 46" (run* (q) (fresh (a) (absento a q) (absento q a))) '(_.0)) (test "test 47" (run* (q) (fresh (a) (absento `(,a . 3) q))) '(_.0)) (test "test 48" (run* (q) (fresh (a) (absento `(,a . 3) q))) '(_.0)) (test "test 49" (run* (q) (fresh (a b c d e) (absento `((3 4 ,a) (4 ,b) ((,c)) ,d ,e) q))) '(_.0)) (test "test 50" (run* (q) (fresh (a) (absento a q) (== 5 a))) '((_.0 (absento (5 _.0))))) (test "test 51" (run* (q) (fresh (a b c d) (== a 5) (== a b) (== b c) (absento d q) (== c d))) '((_.0 (absento (5 _.0))))) (test "test 52" (run* (q) (fresh (a b c d) (== a b) (== b c) (absento a q) (== c d) (== d 5))) '((_.0 (absento (5 _.0))))) (test "test 53" (run* (q) (fresh (t1 t2 a) (== `(,a . 3) t1) (== `(,a . (4 . 3)) t2) (== `(,t1 ,t2) q) (absento t1 t2))) '((((_.0 . 3) (_.0 4 . 3)) (=/= ((_.0 4)))))) (test "test 54" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . (4 . 3))))) '(((_.0 . 3) (=/= ((_.0 4)))))) (test "test 55" (run* (q) (fresh (a d c) (== '(3 . 4) d) (absento `(3 . 4) q) (== `(3 . ,d) q))) '()) (test "test 56" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 57" (run* (q) (numbero q) (absento q 3)) '((_.0 (=/= ((_.0 3))) (num _.0)))) (test "test 58" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . (4 . (,a . 3)))))) '()) (test "test 59" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . ((,a . 3) . (,a . 4)))))) '()) (test "test 60" (run* (q) (fresh (a d c) (== `(3 . ,d) q) (== '(3 . 4) d) (absento `(3 . 4) q))) '()) (test "test 61" (run* (q) (fresh (a b c) (symbolo b) (absento `(,3 . ,a) `(,b . ,c)) (== `(,a ,b ,c) q))) '(((_.0 _.1 _.2) (sym _.1) (absento ((3 . _.0) _.2))))) (test "test 62" (run* (q) (fresh (a b c) (absento a b) (absento b c) (absento c q) (symbolo a))) '(_.0)) (test "test 63" (run* (q) (fresh (a b c) (=/= a b) (=/= b c) (=/= c q) (symbolo a))) '(_.0)) (test "test 64" (run* (q) (symbolo q) (== 'tag q)) '(tag)) (test "test 65" (run* (q) (fresh (b) (absento '(3 4) `(,q ,b)))) '((_.0 (absento ((3 4) _.0))))) (test "test 66" (run* (q) (absento 6 5)) '(_.0)) (test "test 67" (run* (q) (fresh (a b) (=/= a b) (symbolo a) (numbero b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 68" (run* (q) (fresh (a b c d) (=/= `(,a ,b) `(,c ,d)) (symbolo a) (numbero c) (symbolo b) (numbero c) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (num _.2) (sym _.0 _.1)))) (test "test 69" (run* (q) (fresh (a b) (=/= `(,a . 3) `(,b . 3)) (symbolo a) (numbero b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 70" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 70b" (run* (q) (fresh (a b) (symbolo a) (numbero b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 71" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 72" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 73" (run* (q) (fresh (a b) (== `(,a ,b) q) (absento b a) (absento a b) (== a '(1 . 2)))) '((((1 . 2) _.0) (=/= ((_.0 1)) ((_.0 2))) (absento ((1 . 2) _.0))))) (test "test 74" (run* (q) (fresh (a b c) (absento a q) (absento q a) (== `(,b . ,c) a) (== '(1 . 2) b) (== '(3 . 4) c))) '((_.0 (=/= ((_.0 1)) ((_.0 2)) ((_.0 3)) ((_.0 4)) ((_.0 (1 . 2))) ((_.0 (3 . 4)))) (absento (((1 . 2) 3 . 4) _.0))))) (test "test 75" (run* (q) (fresh (a b c d e f g) (absento a q) (absento q a) (== `(,b . ,c) a) (== `(,d . ,e) b) (== `(,f . ,g) c) (== '(1 . 2) d) (== '(3 . 4) e) (== '(5 . 6) f) (== '(7 . 8) g))) '((_.0 (=/= ((_.0 1)) ((_.0 2)) ((_.0 3)) ((_.0 4)) ((_.0 5)) ((_.0 6)) ((_.0 7)) ((_.0 8)) ((_.0 (1 . 2))) ((_.0 (3 . 4))) ((_.0 (5 . 6))) ((_.0 (7 . 8))) ((_.0 ((1 . 2) 3 . 4))) ((_.0 ((5 . 6) 7 . 8)))) (absento ((((1 . 2) 3 . 4) (5 . 6) 7 . 8) _.0))))) (test "test 76" (run* (q) (absento 3 q) (absento '(3 4) q)) '((_.0 (absento (3 _.0))))) (test "test 77" (run* (q) (fresh (x a b) (== x `(,a ,b)) (absento '(3 4) x) (absento 3 a) (absento 4 b) (== q `(,a 2)))) '(((_.0 2) (absento (3 _.0))))) (test "test 78" (run* (q) (fresh (d) (== `(3 . ,d) q) (absento `(3 . 4) q) (== '(3 . 4) d))) '()) (test "test 79" (run* (q) (fresh (d) (absento `(3 . 4) q) (== `(3 . ,d) q) (== '(3 . 4) d))) '()) (test "test 80" (run* (q) (fresh (d a c) (== `(3 . ,d) q) (absento `(3 . ,a) q) (== c d) (== `(3 . ,a) c))) '()) (test "test 81" (run* (q) (fresh (a b) (absento `(3 . ,a) `(,b . 4)) (== `(,a . ,b) q))) '(((_.0 . _.1) (=/= ((_.0 4) (_.1 3))) (absento ((3 . _.0) _.1))))) (test "test 82" (run* (q) (fresh (d) (== `(3 . ,d) q) (absento `(3 . 4) q))) '(((3 . _.0) (=/= ((_.0 4))) (absento ((3 . 4) _.0))))) (test "test 83" (run* (q) (fresh (d) (== `(3 . ,d) q) (== '(3 . 4) d)) (absento `(3 . 4) q)) '()) (test "test 84" (run* (q) (fresh (a b c d) (=/= `(,a . ,b) `(,c . ,d)) (absento a c) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (absento (_.0 _.2))))) (test "test 84 b" (run* (q) (fresh (a b c d) (=/= `(,a . ,b) `(,c . ,d)) (absento c a) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (absento (_.2 _.0))))) (test "test 85 a" (run* (q) (fresh (a b) (=/= a b) (absento a b) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1))))) (test "test 85 b" (run* (q) (fresh (a b) (absento a b) (=/= a b) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1))))) (test "test 86 absento-occurs-check" (run* (q) (fresh (x y z) (== (list x y z) q) (absento (list x y z) x))) '((_.0 _.1 _.2))) (test "test 87 absento-symbolo-numbero-together-drop-superfluous" (run* (q) (fresh (x y z) (== (list x y z) q) (absento x (cons y z)) (symbolo x) (numbero y))) '(((_.0 _.1 _.2) (num _.1) (sym _.0) (absento (_.0 _.2)))) ) (test "null, pair, and atomic types order correctly in absento reification" (run 1 (q) (absento '(a . b) q) (absento '() q) (absento 5 q)) '((_.0 (absento (5 _.0) (() _.0) ((a . b) _.0)))))
null
https://raw.githubusercontent.com/webyrd/wreckto-verseo/45ce27643a18ff7d6a8080f37a3e5d2ec984b051/faster-minikanren/absento-tests.scm
scheme
Tests for general absento , where the first argument is n't a ground atom . (test "test 0" (run* (q) (absento q q)) '()) (test "test 1" (run* (q) (fresh (a b c) (== a b) (absento b c) (== c b) (== `(,a ,b ,c) q))) '()) (test "test 2" (run* (q) (fresh (a) (absento q a) (absento `((,q ,q) 3 (,q ,q)) `(,a 3 ,a)))) '(_.0)) (test "test 3" (run* (q) (fresh (a b) (absento q a) (absento `(3 ,a) `(,b ,a)) (== 3 b))) '()) (test "test 4" (run* (q) (fresh (a b) (absento q a) (absento `(3 ,a) `(,q ,a)) (== 3 b))) '((_.0 (=/= ((_.0 3)))))) (test "test 5" (run* (q) (fresh (a b) (numbero a) (numbero b) (absento '(3 3) `(,a ,b)) (=/= a b) (== `(,a ,b) q))) '(((_.0 _.1) (=/= ((_.0 _.1))) (num _.0 _.1)))) (test "test 6" (run* (q) (fresh (a) (absento q a) (== q a))) '()) (test "test 7" (run* (q) (fresh (a b c) (absento '(3 . 4) c) (== `(,a . ,b) c) (== q `(,a . ,b)))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (absento ((3 . 4) _.0) ((3 . 4) _.1))))) (test "test 8" (run* (q) (fresh (a b) (absento 5 a) (symbolo b) (== `(,q ,b) a))) '((_.0 (absento (5 _.0))))) (test "test 9" (run* (q) (fresh (a b) (absento 5 a) (== `(,q ,b) a))) '((_.0 (absento (5 _.0))))) (test "test 10" (run* (q) (fresh (a) (absento `(3 . ,a) q) (absento q `(3 . ,a)))) '((_.0 (=/= ((_.0 3)))))) (test "test 11" (run* (q) (fresh (a b c d e f) (absento `(,a . ,b) q) (absento q `(,a . ,b)) (== `(,c . ,d) a) (== `(3 . ,e) c) (== `(,f . 4) d))) '((_.0 (=/= ((_.0 3)) ((_.0 4)))))) (test "test 12" (run* (q) (fresh (a b c) (absento `(,3 . ,a) `(,b . ,c)) (numbero b) (== `(,a ,b ,c) q))) '(((_.0 _.1 _.2) (=/= ((_.0 _.2) (_.1 3))) (num _.1) (absento ((3 . _.0) _.2))))) (test "test 13" (run* (q) (fresh (a b c) (== `(,a . ,b) q) (absento '(3 . 4) q) (numbero a) (numbero b))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (num _.0 _.1)))) (test "test 14" (run* (q) (fresh (a b) (absento '(3 . 4) `(,a . ,b)) (== `(,a . ,b) q))) '(((_.0 . _.1) (=/= ((_.0 3) (_.1 4))) (absento ((3 . 4) _.0) ((3 . 4) _.1))))) (test "test 15" (run* (q) (absento q `(3 . (4 . 5)))) '((_.0 (=/= ((_.0 3)) ((_.0 4)) ((_.0 5)) ((_.0 (3 . (4 . 5)))) ((_.0 (4 . 5))))))) (test "test 16" (run* (q) (fresh (a b x) (absento a b) (symbolo a) (numbero x) (== x b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 19" (run* (q) (absento 5 q) (absento 5 q)) '((_.0 (absento (5 _.0))))) (test "test 20" (run* (q) (absento 5 q) (absento 6 q)) '((_.0 (absento (5 _.0) (6 _.0))))) (test "test 21" (run* (q) (absento 5 q) (symbolo q)) '((_.0 (sym _.0)))) (test "test 22" (run* (q) (numbero q) (absento 'tag q)) '((_.0 (num _.0)))) (test "test 23" (run* (q) (absento 'tag q) (numbero q)) '((_.0 (num _.0)))) (test "test 24" (run* (q) (== 5 q) (absento 5 q)) '()) (test "test 25" (run* (q) (== q `(5 6)) (absento 5 q)) '()) (test "test 25b" (run* (q) (absento 5 q) (== q `(5 6))) '()) (test "test 26" (run* (q) (absento 5 q) (== 5 q)) '()) (test "test 27" (run* (q) (absento 'tag1 q) (absento 'tag2 q)) '((_.0 (absento (tag1 _.0) (tag2 _.0))))) (test "test 28" (run* (q) (absento 'tag q) (numbero q)) '((_.0 (num _.0)))) (test "test 29" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 30" (run* (q) (fresh (a b) (absento b a) (absento a b) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 31" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 32" (run* (q) (fresh (a b) (absento 5 a) (absento 5 b) (== `(,a . ,b) q))) '(((_.0 . _.1) (absento (5 _.0) (5 _.1))))) (test "test 33" (run* (q) (fresh (a b c) (== `(,a ,b) c) (== `(,c ,c) q) (symbolo b) (numbero c))) '()) (test "test 34" (run* (q) (absento 'tag q) (symbolo q)) '((_.0 (=/= ((_.0 tag))) (sym _.0)))) (test "test 35" (run* (q) (absento 5 q) (numbero q)) '((_.0 (=/= ((_.0 5))) (num _.0)))) (test "test 36" (run* (q) (fresh (a) (== 5 a) (absento a q))) '((_.0 (absento (5 _.0))))) (test "test 37" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 38" (run* (q) (absento '() q)) '((_.0 (absento (() _.0))))) (test "test 39" (run* (q) (absento `(3 4) q)) '((_.0 (absento ((3 4) _.0))))) (test "test 40" (run* (q) (fresh (d a c) (== `(3 . ,d) q) (=/= `(,c . ,a) q) (== '(3 . 4) d))) '((3 3 . 4))) (test "test 41" (run* (q) (fresh (a) (== `(,a . ,a) q))) '((_.0 . _.0))) (test "test 42" (run* (q) (fresh (a b) (== `((3 4) (5 6)) q) (absento `(3 4) q))) '()) (test "test 43" (run* (q) (absento q 3)) '((_.0 (=/= ((_.0 3)))))) (test "test 44" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 45" (run* (q) (fresh (a b) (absento `(,a . ,b) q) (== q `(3 . (,b . ,b))))) '((3 _.0 . _.0))) (test "test 45b" (run* (q) (fresh (a b) (absento `(,a . ,b) q) (== q `(,a 3 . (,b . ,b))))) '(((_.0 3 _.1 . _.1) (=/= ((_.0 _.1)))))) (test "test 46" (run* (q) (fresh (a) (absento a q) (absento q a))) '(_.0)) (test "test 47" (run* (q) (fresh (a) (absento `(,a . 3) q))) '(_.0)) (test "test 48" (run* (q) (fresh (a) (absento `(,a . 3) q))) '(_.0)) (test "test 49" (run* (q) (fresh (a b c d e) (absento `((3 4 ,a) (4 ,b) ((,c)) ,d ,e) q))) '(_.0)) (test "test 50" (run* (q) (fresh (a) (absento a q) (== 5 a))) '((_.0 (absento (5 _.0))))) (test "test 51" (run* (q) (fresh (a b c d) (== a 5) (== a b) (== b c) (absento d q) (== c d))) '((_.0 (absento (5 _.0))))) (test "test 52" (run* (q) (fresh (a b c d) (== a b) (== b c) (absento a q) (== c d) (== d 5))) '((_.0 (absento (5 _.0))))) (test "test 53" (run* (q) (fresh (t1 t2 a) (== `(,a . 3) t1) (== `(,a . (4 . 3)) t2) (== `(,t1 ,t2) q) (absento t1 t2))) '((((_.0 . 3) (_.0 4 . 3)) (=/= ((_.0 4)))))) (test "test 54" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . (4 . 3))))) '(((_.0 . 3) (=/= ((_.0 4)))))) (test "test 55" (run* (q) (fresh (a d c) (== '(3 . 4) d) (absento `(3 . 4) q) (== `(3 . ,d) q))) '()) (test "test 56" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 57" (run* (q) (numbero q) (absento q 3)) '((_.0 (=/= ((_.0 3))) (num _.0)))) (test "test 58" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . (4 . (,a . 3)))))) '()) (test "test 59" (run* (q) (fresh (a) (== `(,a . 3) q) (absento q `(,a . ((,a . 3) . (,a . 4)))))) '()) (test "test 60" (run* (q) (fresh (a d c) (== `(3 . ,d) q) (== '(3 . 4) d) (absento `(3 . 4) q))) '()) (test "test 61" (run* (q) (fresh (a b c) (symbolo b) (absento `(,3 . ,a) `(,b . ,c)) (== `(,a ,b ,c) q))) '(((_.0 _.1 _.2) (sym _.1) (absento ((3 . _.0) _.2))))) (test "test 62" (run* (q) (fresh (a b c) (absento a b) (absento b c) (absento c q) (symbolo a))) '(_.0)) (test "test 63" (run* (q) (fresh (a b c) (=/= a b) (=/= b c) (=/= c q) (symbolo a))) '(_.0)) (test "test 64" (run* (q) (symbolo q) (== 'tag q)) '(tag)) (test "test 65" (run* (q) (fresh (b) (absento '(3 4) `(,q ,b)))) '((_.0 (absento ((3 4) _.0))))) (test "test 66" (run* (q) (absento 6 5)) '(_.0)) (test "test 67" (run* (q) (fresh (a b) (=/= a b) (symbolo a) (numbero b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 68" (run* (q) (fresh (a b c d) (=/= `(,a ,b) `(,c ,d)) (symbolo a) (numbero c) (symbolo b) (numbero c) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (num _.2) (sym _.0 _.1)))) (test "test 69" (run* (q) (fresh (a b) (=/= `(,a . 3) `(,b . 3)) (symbolo a) (numbero b) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 70" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (numbero b))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 70b" (run* (q) (fresh (a b) (symbolo a) (numbero b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (num _.1) (sym _.0)))) (test "test 71" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q) (symbolo a) (symbolo b))) '(((_.0 _.1) (=/= ((_.0 _.1))) (sym _.0 _.1)))) (test "test 72" (run* (q) (fresh (a b) (absento a b) (absento b a) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1) (_.1 _.0))))) (test "test 73" (run* (q) (fresh (a b) (== `(,a ,b) q) (absento b a) (absento a b) (== a '(1 . 2)))) '((((1 . 2) _.0) (=/= ((_.0 1)) ((_.0 2))) (absento ((1 . 2) _.0))))) (test "test 74" (run* (q) (fresh (a b c) (absento a q) (absento q a) (== `(,b . ,c) a) (== '(1 . 2) b) (== '(3 . 4) c))) '((_.0 (=/= ((_.0 1)) ((_.0 2)) ((_.0 3)) ((_.0 4)) ((_.0 (1 . 2))) ((_.0 (3 . 4)))) (absento (((1 . 2) 3 . 4) _.0))))) (test "test 75" (run* (q) (fresh (a b c d e f g) (absento a q) (absento q a) (== `(,b . ,c) a) (== `(,d . ,e) b) (== `(,f . ,g) c) (== '(1 . 2) d) (== '(3 . 4) e) (== '(5 . 6) f) (== '(7 . 8) g))) '((_.0 (=/= ((_.0 1)) ((_.0 2)) ((_.0 3)) ((_.0 4)) ((_.0 5)) ((_.0 6)) ((_.0 7)) ((_.0 8)) ((_.0 (1 . 2))) ((_.0 (3 . 4))) ((_.0 (5 . 6))) ((_.0 (7 . 8))) ((_.0 ((1 . 2) 3 . 4))) ((_.0 ((5 . 6) 7 . 8)))) (absento ((((1 . 2) 3 . 4) (5 . 6) 7 . 8) _.0))))) (test "test 76" (run* (q) (absento 3 q) (absento '(3 4) q)) '((_.0 (absento (3 _.0))))) (test "test 77" (run* (q) (fresh (x a b) (== x `(,a ,b)) (absento '(3 4) x) (absento 3 a) (absento 4 b) (== q `(,a 2)))) '(((_.0 2) (absento (3 _.0))))) (test "test 78" (run* (q) (fresh (d) (== `(3 . ,d) q) (absento `(3 . 4) q) (== '(3 . 4) d))) '()) (test "test 79" (run* (q) (fresh (d) (absento `(3 . 4) q) (== `(3 . ,d) q) (== '(3 . 4) d))) '()) (test "test 80" (run* (q) (fresh (d a c) (== `(3 . ,d) q) (absento `(3 . ,a) q) (== c d) (== `(3 . ,a) c))) '()) (test "test 81" (run* (q) (fresh (a b) (absento `(3 . ,a) `(,b . 4)) (== `(,a . ,b) q))) '(((_.0 . _.1) (=/= ((_.0 4) (_.1 3))) (absento ((3 . _.0) _.1))))) (test "test 82" (run* (q) (fresh (d) (== `(3 . ,d) q) (absento `(3 . 4) q))) '(((3 . _.0) (=/= ((_.0 4))) (absento ((3 . 4) _.0))))) (test "test 83" (run* (q) (fresh (d) (== `(3 . ,d) q) (== '(3 . 4) d)) (absento `(3 . 4) q)) '()) (test "test 84" (run* (q) (fresh (a b c d) (=/= `(,a . ,b) `(,c . ,d)) (absento a c) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (absento (_.0 _.2))))) (test "test 84 b" (run* (q) (fresh (a b c d) (=/= `(,a . ,b) `(,c . ,d)) (absento c a) (== `(,a ,b ,c ,d) q))) '(((_.0 _.1 _.2 _.3) (absento (_.2 _.0))))) (test "test 85 a" (run* (q) (fresh (a b) (=/= a b) (absento a b) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1))))) (test "test 85 b" (run* (q) (fresh (a b) (absento a b) (=/= a b) (== `(,a ,b) q))) '(((_.0 _.1) (absento (_.0 _.1))))) (test "test 86 absento-occurs-check" (run* (q) (fresh (x y z) (== (list x y z) q) (absento (list x y z) x))) '((_.0 _.1 _.2))) (test "test 87 absento-symbolo-numbero-together-drop-superfluous" (run* (q) (fresh (x y z) (== (list x y z) q) (absento x (cons y z)) (symbolo x) (numbero y))) '(((_.0 _.1 _.2) (num _.1) (sym _.0) (absento (_.0 _.2)))) ) (test "null, pair, and atomic types order correctly in absento reification" (run 1 (q) (absento '(a . b) q) (absento '() q) (absento 5 q)) '((_.0 (absento (5 _.0) (() _.0) ((a . b) _.0)))))
b7de3429f4105c693b1096381683057809ecec7f822b01892f543cae7806a78f
zack-bitcoin/verkle
unit_tests.erl
-module(unit_tests). -export([doit/1]). doit(0) -> S = success, io:fwrite("leaf\n"), S = leaf:test(1), io:fwrite("stem\n"), S = stem2:test(1), io:fwrite("get\n"), S = get2:test(1), lists:map(fun(N) -> io:fwrite("fr "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = fr:test(N) end, [2,3,5,6,10,11,17,19,20,21,22]), lists:map(fun(N) -> io:fwrite("ed "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = ed:test(N) end, [1,2,4,5,7,8,9,10,11,12]), lists:map(fun(N) -> io:fwrite("poly "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = poly2:test(N) end, [2,3]), lists:map(fun(N) -> io:fwrite("multi exponent "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = multi_exponent:test(N) end, [0,1,5,6,7,8]), S = store2:test(1), lists:map(fun(N) -> S = ipa2:test(N) end, [1,3,5,7]), S = verify2:test(), {prove, _, verify, _} = multiproof2:test(7), S.
null
https://raw.githubusercontent.com/zack-bitcoin/verkle/da9a014779decb3744aef197efcf972de80adccc/src/unit_tests.erl
erlang
-module(unit_tests). -export([doit/1]). doit(0) -> S = success, io:fwrite("leaf\n"), S = leaf:test(1), io:fwrite("stem\n"), S = stem2:test(1), io:fwrite("get\n"), S = get2:test(1), lists:map(fun(N) -> io:fwrite("fr "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = fr:test(N) end, [2,3,5,6,10,11,17,19,20,21,22]), lists:map(fun(N) -> io:fwrite("ed "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = ed:test(N) end, [1,2,4,5,7,8,9,10,11,12]), lists:map(fun(N) -> io:fwrite("poly "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = poly2:test(N) end, [2,3]), lists:map(fun(N) -> io:fwrite("multi exponent "), io:fwrite(integer_to_list(N)), io:fwrite("\n"), S = multi_exponent:test(N) end, [0,1,5,6,7,8]), S = store2:test(1), lists:map(fun(N) -> S = ipa2:test(N) end, [1,3,5,7]), S = verify2:test(), {prove, _, verify, _} = multiproof2:test(7), S.
2e8c4dda7e7658448303974ffa5057a73267888999938c23cf960dc8dc91fe0f
anwarmamat/cmsc330fall18-public
student.ml
open P3.Nfa open P3.Regexp open TestUtils open OUnit2 let m1 = { qs = [0; 1; 2; 3]; sigma = ['a'; 'b']; delta = [(0, Some 'a', 1); (0, Some 'a', 2); (2, Some 'b', 3)]; q0 = 0; fs = [1; 3] } let test_nfa_new_states ctxt = assert_set_set_eq [[]; []] (new_states m1 []); assert_set_set_eq [[1; 2]; []] (new_states m1 [0]); assert_set_set_eq [[1; 2]; [3]] (new_states m1 [0; 2]); assert_set_set_eq [[1; 2]; [3]] (new_states m1 [0; 1; 2; 3]) let test_nfa_new_trans ctxt = assert_trans_eq [([0], Some 'a', [1; 2]); ([0], Some 'b', [])] (new_trans m1 [0]); assert_trans_eq [([0; 2], Some 'a', [1; 2]); ([0; 2], Some 'b', [3])] (new_trans m1 [0; 2]) let test_nfa_new_finals ctxt = assert_set_set_eq [] (new_finals m1 [0; 2]); assert_set_set_eq [[1]] (new_finals m1 [1]); assert_set_set_eq [[1; 3]] (new_finals m1 [1; 3]) let suite = "student" >::: [ "nfa_new_states" >:: test_nfa_new_states; "nfa_new_trans" >:: test_nfa_new_trans; "nfa_new_finals" >:: test_nfa_new_finals ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/anwarmamat/cmsc330fall18-public/12585d98d45f954f75e2f78df3062444f5f97cf6/p3/test/student.ml
ocaml
open P3.Nfa open P3.Regexp open TestUtils open OUnit2 let m1 = { qs = [0; 1; 2; 3]; sigma = ['a'; 'b']; delta = [(0, Some 'a', 1); (0, Some 'a', 2); (2, Some 'b', 3)]; q0 = 0; fs = [1; 3] } let test_nfa_new_states ctxt = assert_set_set_eq [[]; []] (new_states m1 []); assert_set_set_eq [[1; 2]; []] (new_states m1 [0]); assert_set_set_eq [[1; 2]; [3]] (new_states m1 [0; 2]); assert_set_set_eq [[1; 2]; [3]] (new_states m1 [0; 1; 2; 3]) let test_nfa_new_trans ctxt = assert_trans_eq [([0], Some 'a', [1; 2]); ([0], Some 'b', [])] (new_trans m1 [0]); assert_trans_eq [([0; 2], Some 'a', [1; 2]); ([0; 2], Some 'b', [3])] (new_trans m1 [0; 2]) let test_nfa_new_finals ctxt = assert_set_set_eq [] (new_finals m1 [0; 2]); assert_set_set_eq [[1]] (new_finals m1 [1]); assert_set_set_eq [[1; 3]] (new_finals m1 [1; 3]) let suite = "student" >::: [ "nfa_new_states" >:: test_nfa_new_states; "nfa_new_trans" >:: test_nfa_new_trans; "nfa_new_finals" >:: test_nfa_new_finals ] let _ = run_test_tt_main suite
d534b87a3721f76f47d7f1f93936cf7adc95d6249a00b54cd98efdd166da4c44
avsm/platform
zed_edit.ml
* zed_edit.ml * ----------- * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_edit.ml * ----------- * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) open CamomileLibraryDefault.Camomile open React module CaseMap = CaseMap.Make(Zed_rope.Text_core) (* +-----------------------------------------------------------------+ | Types | +-----------------------------------------------------------------+ *) type clipboard = { clipboard_get : unit -> Zed_rope.t; clipboard_set : Zed_rope.t -> unit; } type 'a t = { mutable data : 'a option; (* Custom data attached to the engine. *) mutable text : Zed_rope.t; (* The contents of the engine. *) mutable lines : Zed_lines.t; (* The set of line position of [text]. *) changes : Zed_cursor.changes event; send_changes : Zed_cursor.changes -> unit; (* Changes of the contents. *) erase_mode : bool signal; set_erase_mode : bool -> unit; (* The current erase mode. *) editable : int -> int -> bool; (* The editable function of the engine. *) clipboard : clipboard; (* The clipboard for this engine. *) mutable mark : Zed_cursor.t; (* The cursor that points to the mark. *) selection : bool signal; set_selection : bool -> unit; (* The current selection state. *) match_word : Zed_rope.t -> int -> int option; (* The function for matching words. *) locale : string option signal; (* The buffer's locale. *) undo : (Zed_rope.t * Zed_lines.t * int * int * int * int * int * int) array; The undo buffer . It is an array of element of the form [ ( text , lines , pos , new_pos , added , removed , added_width , removed_width ) ] . lines, pos, new_pos, added, removed, added_width, removed_width)]. *) undo_size : int; (* Size of the undo buffer. *) mutable undo_start : int; (* Position of the first used cell in the undo buffer. *) mutable undo_index : int; (* Position of the next available cell in the undo buffer. *) mutable undo_count : int; (* Number of used cell in the undo buffer. *) } (* +-----------------------------------------------------------------+ | Creation | +-----------------------------------------------------------------+ *) let dummy_cursor = Zed_cursor.create 0 E.never (fun () -> Zed_lines.empty) 0 0 let match_by_regexp_core re rope idx = match Zed_re.Core.regexp_match ~sem:`Longest re rope idx with | None -> None | Some arr -> match arr.(0) with | Some(_zip1, zip2) -> Some(Zed_rope.Zip.offset zip2) | None -> None let match_by_regexp_raw re rope idx = match Zed_re.Raw.regexp_match ~sem:`Longest re rope idx with | None -> None | Some arr -> match arr.(0) with | Some(_zip1, zip2) -> Some(Zed_rope.Zip_raw.offset zip2) | None -> None let regexp_word_core = let set = UCharInfo.load_property_set `Alphabetic in let set = List.fold_left (fun set ch -> USet.add (UChar.of_char ch) set) set ['0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'] in Zed_re.Core.compile (`Repn(`Set set, 1, None)) let regexp_word_raw = let set = UCharInfo.load_property_set `Alphabetic in let set = List.fold_left (fun set ch -> USet.add (UChar.of_char ch) set) set ['0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'] in Zed_re.Raw.compile (`Repn(`Set set, 1, None)) let new_clipboard () = let r = ref (Zed_rope.empty ()) in { clipboard_get = (fun () -> !r); clipboard_set = (fun x -> r := x) } let create ?(editable=fun _pos _len -> true) ?(move = (+)) ?clipboard ?(match_word = match_by_regexp_core regexp_word_core) ?(locale = S.const None) ?(undo_size = 1000) () = (* I'm not sure how to disable the unused warning with ocaml.warning and the argument can't be removed as it's part of the interface *) let _ = move in let changes, send_changes = E.create () in let erase_mode, set_erase_mode = S.create false in let selection, set_selection = S.create false in let clipboard = match clipboard with | Some clipboard -> clipboard | None -> new_clipboard () in let edit = { data = None; text = Zed_rope.empty (); lines = Zed_lines.empty; changes; send_changes; erase_mode; set_erase_mode; editable; clipboard; mark = dummy_cursor; selection; set_selection; match_word; locale; undo = Array.make undo_size (Zed_rope.empty (), Zed_lines.empty, 0, 0, 0, 0, 0, 0); undo_size; undo_start = 0; undo_index = 0; undo_count = 0; } in edit.mark <- Zed_cursor.create 0 changes (fun () -> edit.lines) 0 0; edit (* +-----------------------------------------------------------------+ | State | +-----------------------------------------------------------------+ *) let get_data engine = match engine.data with | Some data -> data | None -> raise Not_found let set_data engine data = engine.data <- Some data let clear_data engine = engine.data <- None let text engine = engine.text let lines engine = engine.lines let changes engine = engine.changes let erase_mode engine = engine.erase_mode let get_erase_mode engine = S.value engine.erase_mode let set_erase_mode engine state = engine.set_erase_mode state let mark engine = engine.mark let selection engine = engine.selection let get_selection engine = S.value engine.selection let set_selection engine state = engine.set_selection state let get_line e i = let txt = text e in let lines = lines e in let start = Zed_lines.line_start lines i in let stop = Zed_lines.line_stop lines i in Zed_rope.sub txt start (stop - start) let update engine cursors = E.select ( E.stamp engine.changes () :: E.stamp (S.changes engine.selection) () :: E.stamp (S.changes (Zed_cursor.position engine.mark)) () :: List.map (fun cursor -> E.stamp (S.changes (Zed_cursor.position cursor)) ()) cursors ) (* +-----------------------------------------------------------------+ | Cursors | +-----------------------------------------------------------------+ *) let new_cursor engine = Zed_cursor.create (Zed_rope.length engine.text) engine.changes (fun () -> engine.lines) 0 0 (* +-----------------------------------------------------------------+ | Actions | +-----------------------------------------------------------------+ *) exception Cannot_edit type 'a context = { edit : 'a t; cursor : Zed_cursor.t; check : bool; } let context ?(check=true) edit cursor = { edit; cursor; check } let edit ctx = ctx.edit let cursor ctx = ctx.cursor let check ctx = ctx.check let with_check check ctx = { ctx with check } let goto ctx ?set_wanted_column new_position = Zed_cursor.goto ctx.cursor ?set_wanted_column new_position let move ctx ?set_wanted_column delta = Zed_cursor.move ctx.cursor ?set_wanted_column delta let next_line_n ctx n = let index = Zed_cursor.get_line ctx.cursor in if index + n > Zed_lines.count ctx.edit.lines then goto ctx ~set_wanted_column:false (Zed_rope.length ctx.edit.text) else begin let start = Zed_lines.line_start ctx.edit.lines (index + n) in let stop = if index + n = Zed_lines.count ctx.edit.lines then Zed_rope.length ctx.edit.text else Zed_lines.line_start ctx.edit.lines (index + n + 1) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let prev_line_n ctx n = let index = Zed_cursor.get_line ctx.cursor in if index - n < 0 then begin goto ctx ~set_wanted_column:false 0 end else begin let start = Zed_lines.line_start ctx.edit.lines (index - n) in let stop = Zed_lines.line_start ctx.edit.lines (index - (n - 1)) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let move_line ctx delta = match delta with | _ when delta < 0 -> prev_line_n ctx (-delta) | _ when delta > 0 -> next_line_n ctx delta | _ -> () let position ctx = Zed_cursor.get_position ctx.cursor let line ctx = Zed_cursor.get_line ctx.cursor let column ctx = Zed_cursor.get_column ctx.cursor let column_display ctx = Zed_cursor.get_column_display ctx.cursor let at_bol ctx = Zed_cursor.get_column ctx.cursor = 0 let at_eol ctx = let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then position = Zed_rope.length ctx.edit.text else position = Zed_lines.line_start ctx.edit.lines (index + 1) - 1 let at_bot ctx = Zed_cursor.get_position ctx.cursor = 0 let at_eot ctx = Zed_cursor.get_position ctx.cursor = Zed_rope.length ctx.edit.text let modify { edit ; _ } text lines position new_position added removed added_width removed_width= if edit.undo_size > 0 then begin edit.undo.(edit.undo_index) <- (text, lines, position, new_position, added, removed, added_width, removed_width); edit.undo_index <- (edit.undo_index + 1) mod edit.undo_size; if edit.undo_count = edit.undo_size then edit.undo_start <- (edit.undo_start + 1) mod edit.undo_size else edit.undo_count <- edit.undo_count + 1 end; edit.send_changes {position; added; removed; added_width; removed_width } let insert ctx rope = let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let len = Zed_rope.length rope in let text = ctx.edit.text and lines = ctx.edit.lines in if S.value ctx.edit.erase_mode then begin let text_len = Zed_rope.length ctx.edit.text in if position + len > text_len then begin let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position (text_len-position))))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position (text_len - position) rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position (text_len - position) (Zed_lines.of_rope rope); modify ctx text lines position position len (text_len - position) curr_width orig_width end else begin let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position len rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position len (Zed_lines.of_rope rope); modify ctx text lines position position len len curr_width orig_width; end; move ctx len end else begin let width_add= Zed_string.aval_width (Zed_string.width (Zed_rope.to_string rope)) in ctx.edit.text <- Zed_rope.insert ctx.edit.text position rope; ctx.edit.lines <- Zed_lines.insert ctx.edit.lines position (Zed_lines.of_rope rope); modify ctx text lines position position len 0 width_add 0; move ctx len end end else raise Cannot_edit let insert_char ctx ch = if Zed_char.is_combining_mark ch then let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let text = ctx.edit.text and lines = ctx.edit.lines in try ctx.edit.text <- Zed_rope.insert_uChar ctx.edit.text position ch; modify ctx text lines position position 1 1 0 0; move ctx 0; next_line_n ctx 0; with _-> () end else raise Cannot_edit else insert ctx (Zed_rope.of_string (fst (Zed_string.of_uChars [ch]))) let insert_no_erase ctx rope = let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let len = Zed_rope.length rope and text = ctx.edit.text and lines = ctx.edit.lines in let width_add= Zed_string.aval_width (Zed_string.width (Zed_rope.to_string rope)) in ctx.edit.text <- Zed_rope.insert text position rope; ctx.edit.lines <- Zed_lines.insert ctx.edit.lines position (Zed_lines.of_rope rope); modify ctx text lines position position len 0 width_add 0; move ctx len end else raise Cannot_edit let remove_next ctx len = let position = Zed_cursor.get_position ctx.cursor in let text_len = Zed_rope.length ctx.edit.text in let len = if position + len > text_len then text_len - position else len in if not ctx.check || ctx.edit.editable position len then begin let text = ctx.edit.text and lines = ctx.edit.lines in let width_remove= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in ctx.edit.text <- Zed_rope.remove text position len; ctx.edit.lines <- Zed_lines.remove ctx.edit.lines position len; modify ctx text lines position position 0 len 0 width_remove; end else raise Cannot_edit let remove_prev ctx len = let position = Zed_cursor.get_position ctx.cursor in let len = min position len in if not ctx.check || ctx.edit.editable (position - len) len then begin let text = ctx.edit.text and lines = ctx.edit.lines in let width_remove= Zed_string.(aval_width (width Zed_rope.(to_string (sub text (position-len) len)))) in ctx.edit.text <- Zed_rope.remove text (position - len) len; ctx.edit.lines <- Zed_lines.remove ctx.edit.lines (position - len) len; modify ctx text lines (position - len) position 0 len 0 width_remove; end else raise Cannot_edit let remove = remove_next let replace ctx len rope = let position = Zed_cursor.get_position ctx.cursor in let text_len = Zed_rope.length ctx.edit.text in let len = if position + len > text_len then text_len - position else len in if not ctx.check || ctx.edit.editable position len then begin let rope_len = Zed_rope.length rope and text = ctx.edit.text and lines = ctx.edit.lines in let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position len rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position len (Zed_lines.of_rope rope); modify ctx text lines position position rope_len len curr_width orig_width; move ctx rope_len end else raise Cannot_edit let newline_rope = Zed_rope.singleton (Zed_char.unsafe_of_char '\n') let newline ctx = insert ctx newline_rope let next_char ctx = if not (at_eot ctx) then move ctx 1 let prev_char ctx = if not (at_bot ctx) then move ctx (-1) let next_line ctx = let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then goto ctx ~set_wanted_column:false (Zed_rope.length ctx.edit.text) else begin let start = Zed_lines.line_start ctx.edit.lines (index + 1) in let stop = if index + 1 = Zed_lines.count ctx.edit.lines then Zed_rope.length ctx.edit.text else Zed_lines.line_start ctx.edit.lines (index + 2) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let prev_line ctx = let index = Zed_cursor.get_line ctx.cursor in if index = 0 then begin goto ctx ~set_wanted_column:false 0 end else begin let start = Zed_lines.line_start ctx.edit.lines (index - 1) in let stop = Zed_lines.line_start ctx.edit.lines index - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let goto_bol ctx = goto ctx (Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor)) let goto_eol ctx = let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then goto ctx (Zed_rope.length ctx.edit.text) else goto ctx (Zed_lines.line_start ctx.edit.lines (index + 1) - 1) let goto_bot ctx = goto ctx 0 let goto_eot ctx = goto ctx (Zed_rope.length ctx.edit.text) let delete_next_char ctx = if not (at_eot ctx) then begin ctx.edit.set_selection false; remove_next ctx 1 end let delete_prev_char ctx = if not (at_bot ctx) then begin ctx.edit.set_selection false; remove_prev ctx 1 end let delete_next_line ctx = ctx.edit.set_selection false; let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then remove_next ctx (Zed_rope.length ctx.edit.text - position) else remove_next ctx (Zed_lines.line_start ctx.edit.lines (index + 1) - position) let delete_prev_line ctx = ctx.edit.set_selection false; let position = Zed_cursor.get_position ctx.cursor in let start = Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor) in remove_prev ctx (position - start) let kill_next_line ctx = let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then begin ctx.edit.clipboard.clipboard_set (Zed_rope.after ctx.edit.text position); ctx.edit.set_selection false; remove ctx (Zed_rope.length ctx.edit.text - position) end else begin let len = Zed_lines.line_start ctx.edit.lines (index + 1) - position in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text position len); ctx.edit.set_selection false; remove ctx len end let kill_prev_line ctx = let position = Zed_cursor.get_position ctx.cursor in let start = Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor) in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text start (position - start)); ctx.edit.set_selection false; remove_prev ctx (position - start) let switch_erase_mode ctx = ctx.edit.set_erase_mode (not (S.value ctx.edit.erase_mode)) let set_mark ctx = Zed_cursor.goto ctx.edit.mark (Zed_cursor.get_position ctx.cursor); ctx.edit.set_selection true let goto_mark ctx = goto ctx (Zed_cursor.get_position ctx.edit.mark) let copy ctx = if S.value ctx.edit.selection then begin let a = Zed_cursor.get_position ctx.cursor and b = Zed_cursor.get_position ctx.edit.mark in let a = min a b and b = max a b in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text a (b - a)); ctx.edit.set_selection false end let kill ctx = if S.value ctx.edit.selection then begin let a = Zed_cursor.get_position ctx.cursor and b = Zed_cursor.get_position ctx.edit.mark in let a = min a b and b = max a b in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text a (b - a)); ctx.edit.set_selection false; goto ctx a; let a = Zed_cursor.get_position ctx.cursor in if a <= b then remove ctx (b - a) end let yank ctx = ctx.edit.set_selection false; insert ctx (ctx.edit.clipboard.clipboard_get ()) let search_word_forward ctx = let len = Zed_rope.length ctx.edit.text in let rec loop idx = if idx = len then None else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> Some(idx, idx') | None -> loop (idx + 1) in loop (Zed_cursor.get_position ctx.cursor) let search_word_backward ctx = let rec loop idx = if idx = -1 then None else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> loop2 (idx - 1) (idx, idx') | None -> loop (idx - 1) and loop2 idx result = if idx = -1 then Some result else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> loop2 (idx - 1) (idx, idx') | None -> Some result in loop (Zed_cursor.get_position ctx.cursor - 1) let capitalize_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 && idx1 < idx2 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in let ch, str' = Zed_rope.break str 1 in replace ctx (Zed_rope.length str) (Zed_rope.append (CaseMap.uppercase ?locale:(S.value ctx.edit.locale) ch) (CaseMap.lowercase ?locale:(S.value ctx.edit.locale) str')) end | None -> () let lowercase_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in replace ctx (Zed_rope.length str) (CaseMap.lowercase ?locale:(S.value ctx.edit.locale) str) end | None -> () let uppercase_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in replace ctx (Zed_rope.length str) (CaseMap.uppercase ?locale:(S.value ctx.edit.locale) str) end | None -> () let next_word ctx = match search_word_forward ctx with | Some(_idx1, idx2) -> goto ctx idx2 | None -> goto ctx (Zed_rope.length ctx.edit.text) let prev_word ctx = match search_word_backward ctx with | Some(idx1, _idx2) -> goto ctx idx1 | None -> goto ctx 0 let delete_next_word ctx = let position = Zed_cursor.get_position ctx.cursor in let word_end = match search_word_forward ctx with | Some(_idx1, idx2) -> idx2 | None -> Zed_rope.length ctx.edit.text in remove ctx (word_end - position) let delete_prev_word ctx = let position = Zed_cursor.get_position ctx.cursor in let start = match search_word_backward ctx with | Some(idx1, _idx2) -> idx1 | None -> 0 in remove_prev ctx (position - start) let kill_next_word ctx = let position = Zed_cursor.get_position ctx.cursor in let word_end = match search_word_forward ctx with | Some(_idx1, idx2) -> idx2 | None -> Zed_rope.length ctx.edit.text in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text position (word_end - position)); ctx.edit.set_selection false; remove ctx (word_end - position) let kill_prev_word ctx = let position = Zed_cursor.get_position ctx.cursor in let start = match search_word_backward ctx with | Some(idx1, _idx2) -> idx1 | None -> 0 in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text start (position - start)); ctx.edit.set_selection false; remove_prev ctx (position - start) let undo { check; edit; cursor } = if edit.undo_count > 0 then begin let index = if edit.undo_index = 0 then edit.undo_size - 1 else edit.undo_index - 1 in let text, lines, pos, new_pos, added, removed, added_width, removed_width = edit.undo.(index) in if not check || edit.editable pos added then begin edit.undo_count <- edit.undo_count - 1; edit.undo_index <- index; edit.text <- text; edit.lines <- lines; edit.send_changes {position= pos; removed; added; added_width; removed_width }; Zed_cursor.goto cursor new_pos end else raise Cannot_edit end (* +-----------------------------------------------------------------+ | Action by names | +-----------------------------------------------------------------+ *) type action = | Insert of Zed_char.t | Newline | Next_char | Prev_char | Next_line | Prev_line | Goto_bol | Goto_eol | Goto_bot | Goto_eot | Delete_next_char | Delete_prev_char | Delete_next_line | Delete_prev_line | Kill_next_line | Kill_prev_line | Switch_erase_mode | Set_mark | Goto_mark | Copy | Kill | Yank | Capitalize_word | Lowercase_word | Uppercase_word | Next_word | Prev_word | Delete_next_word | Delete_prev_word | Kill_next_word | Kill_prev_word | Undo let get_action = function | Insert ch -> (fun ctx -> if Zed_char.length ch = 1 then insert_char ctx (Zed_char.core ch) else insert ctx (Zed_rope.singleton ch)) | Newline -> newline | Next_char -> next_char | Prev_char -> prev_char | Next_line -> next_line | Prev_line -> prev_line | Goto_bol -> goto_bol | Goto_eol -> goto_eol | Goto_bot -> goto_bot | Goto_eot -> goto_eot | Delete_next_char -> delete_next_char | Delete_prev_char -> delete_prev_char | Delete_next_line -> delete_next_line | Delete_prev_line -> delete_prev_line | Kill_next_line -> kill_next_line | Kill_prev_line -> kill_prev_line | Switch_erase_mode -> switch_erase_mode | Set_mark -> set_mark | Goto_mark -> goto_mark | Copy -> copy | Kill -> kill | Yank -> yank | Capitalize_word -> capitalize_word | Lowercase_word -> lowercase_word | Uppercase_word -> uppercase_word | Next_word -> next_word | Prev_word -> prev_word | Delete_next_word -> delete_next_word | Delete_prev_word -> delete_prev_word | Kill_next_word -> kill_next_word | Kill_prev_word -> kill_prev_word | Undo -> undo let doc_of_action = function | Insert _ -> "insert the given character." | Newline -> "insert a newline character." | Next_char -> "move the cursor to the next character." | Prev_char -> "move the cursor to the previous character." | Next_line -> "move the cursor to the next line." | Prev_line -> "move the cursor to the previous line." | Goto_bol -> "move the cursor to the beginning of the current line." | Goto_eol -> "move the cursor to the end of the current line." | Goto_bot -> "move the cursor to the beginning of the text." | Goto_eot -> "move the cursor to the end of the text." | Delete_next_char -> "delete the character after the cursor." | Delete_prev_char -> "delete the character before the cursor." | Delete_next_line -> "delete everything until the end of the current line." | Delete_prev_line -> "delete everything until the beginning of the current line." | Kill_next_line -> "cut everything until the end of the current line." | Kill_prev_line -> "cut everything until the beginning of the current line." | Switch_erase_mode -> "switch the current erasing mode." | Set_mark -> "set the mark to the current position." | Goto_mark -> "move the cursor to the mark." | Copy -> "copy the current region to the clipboard." | Kill -> "cut the current region to the clipboard." | Yank -> "paste the contents of the clipboard at current position." | Capitalize_word -> "capitalize the first word after the cursor." | Lowercase_word -> "convert the first word after the cursor to lowercase." | Uppercase_word -> "convert the first word after the cursor to uppercase." | Next_word -> "move the cursor to the end of the next word." | Prev_word -> "move the cursor to the beginning of the previous word." | Delete_next_word -> "delete up until the next non-word character." | Delete_prev_word -> "delete the word behind the cursor." | Kill_next_word -> "cut up until the next non-word character." | Kill_prev_word -> "cut the word behind the cursor." | Undo -> "revert the last action." let actions = [ Newline, "newline"; Next_char, "next-char"; Prev_char, "prev-char"; Next_line, "next-line"; Prev_line, "prev-line"; Goto_bol, "goto-bol"; Goto_eol, "goto-eol"; Goto_bot, "goto-bot"; Goto_eot, "goto-eot"; Delete_next_char, "delete-next-char"; Delete_prev_char, "delete-prev-char"; Delete_next_line, "delete-next-line"; Delete_prev_line, "delete-prev-line"; Kill_next_line, "kill-next-line"; Kill_prev_line, "kill-prev-line"; Switch_erase_mode, "switch-erase-mode"; Set_mark, "set-mark"; Goto_mark, "goto-mark"; Copy, "copy"; Kill, "kill"; Yank, "yank"; Capitalize_word, "capitalize-word"; Lowercase_word, "lowercase-word"; Uppercase_word, "uppercase-word"; Next_word, "next-word"; Prev_word, "prev-word"; Delete_next_word, "delete-next-word"; Delete_prev_word, "delete-prev-word"; Kill_next_word, "kill-next-word"; Kill_prev_word, "kill-prev-word"; Undo, "undo"; ] let actions_to_names = Array.of_list (List.sort (fun (a1, _) (a2, _) -> compare a1 a2) actions) let names_to_actions = Array.of_list (List.sort (fun (_, n1) (_, n2) -> compare n1 n2) actions) let parse_insert x = if Zed_utf8.starts_with x "insert(" && Zed_utf8.ends_with x ")" then begin let str = String.sub x 7 (String.length x - 8) in if String.length str = 1 && Char.code str.[0] < 128 then Insert(Zed_char.unsafe_of_uChar (UChar.of_char str.[0])) else if String.length str > 2 && str.[0] = 'U' && str.[1] = '+' then let acc = ref 0 in for i = 2 to String.length str - 1 do let ch = str.[i] in acc := !acc * 16 + (match ch with | '0' .. '9' -> Char.code ch - Char.code '0' | 'a' .. 'f' -> Char.code ch - Char.code 'a' + 10 | 'A' .. 'F' -> Char.code ch - Char.code 'A' + 10 | _ -> raise Not_found) done; try Insert(Zed_char.unsafe_of_uChar (UChar.of_int !acc)) with _ -> raise Not_found else raise Not_found end else raise Not_found let action_of_name x = let rec loop a b = if a = b then parse_insert x else let c = (a + b) / 2 in let action, name = Array.unsafe_get names_to_actions c in match compare x name with | d when d < 0 -> loop a c | d when d > 0 -> loop (c + 1) b | _ -> action in loop 0 (Array.length names_to_actions) let name_of_action x = let rec loop a b = if a = b then raise Not_found else let c = (a + b) / 2 in let action, name = Array.unsafe_get actions_to_names c in match compare x action with | d when d < 0 -> loop a c | d when d > 0 -> loop (c + 1) b | _ -> name in match x with | Insert ch -> let code = UChar.code (Zed_char.core ch) in if code <= 255 then let ch = Char.chr (UChar.code (Zed_char.core ch)) in match ch with | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' -> Printf.sprintf "insert(%c)" ch | _ -> Printf.sprintf "insert(U+%02x)" code else if code <= 0xffff then Printf.sprintf "insert(U+%04x)" code else Printf.sprintf "insert(U+%06x)" code | _ -> loop 0 (Array.length actions_to_names)
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/zed.2.0.3/src/zed_edit.ml
ocaml
+-----------------------------------------------------------------+ | Types | +-----------------------------------------------------------------+ Custom data attached to the engine. The contents of the engine. The set of line position of [text]. Changes of the contents. The current erase mode. The editable function of the engine. The clipboard for this engine. The cursor that points to the mark. The current selection state. The function for matching words. The buffer's locale. Size of the undo buffer. Position of the first used cell in the undo buffer. Position of the next available cell in the undo buffer. Number of used cell in the undo buffer. +-----------------------------------------------------------------+ | Creation | +-----------------------------------------------------------------+ I'm not sure how to disable the unused warning with ocaml.warning and the argument can't be removed as it's part of the interface +-----------------------------------------------------------------+ | State | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Cursors | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Actions | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Action by names | +-----------------------------------------------------------------+
* zed_edit.ml * ----------- * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_edit.ml * ----------- * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) open CamomileLibraryDefault.Camomile open React module CaseMap = CaseMap.Make(Zed_rope.Text_core) type clipboard = { clipboard_get : unit -> Zed_rope.t; clipboard_set : Zed_rope.t -> unit; } type 'a t = { mutable data : 'a option; mutable text : Zed_rope.t; mutable lines : Zed_lines.t; changes : Zed_cursor.changes event; send_changes : Zed_cursor.changes -> unit; erase_mode : bool signal; set_erase_mode : bool -> unit; editable : int -> int -> bool; clipboard : clipboard; mutable mark : Zed_cursor.t; selection : bool signal; set_selection : bool -> unit; match_word : Zed_rope.t -> int -> int option; locale : string option signal; undo : (Zed_rope.t * Zed_lines.t * int * int * int * int * int * int) array; The undo buffer . It is an array of element of the form [ ( text , lines , pos , new_pos , added , removed , added_width , removed_width ) ] . lines, pos, new_pos, added, removed, added_width, removed_width)]. *) undo_size : int; mutable undo_start : int; mutable undo_index : int; mutable undo_count : int; } let dummy_cursor = Zed_cursor.create 0 E.never (fun () -> Zed_lines.empty) 0 0 let match_by_regexp_core re rope idx = match Zed_re.Core.regexp_match ~sem:`Longest re rope idx with | None -> None | Some arr -> match arr.(0) with | Some(_zip1, zip2) -> Some(Zed_rope.Zip.offset zip2) | None -> None let match_by_regexp_raw re rope idx = match Zed_re.Raw.regexp_match ~sem:`Longest re rope idx with | None -> None | Some arr -> match arr.(0) with | Some(_zip1, zip2) -> Some(Zed_rope.Zip_raw.offset zip2) | None -> None let regexp_word_core = let set = UCharInfo.load_property_set `Alphabetic in let set = List.fold_left (fun set ch -> USet.add (UChar.of_char ch) set) set ['0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'] in Zed_re.Core.compile (`Repn(`Set set, 1, None)) let regexp_word_raw = let set = UCharInfo.load_property_set `Alphabetic in let set = List.fold_left (fun set ch -> USet.add (UChar.of_char ch) set) set ['0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'] in Zed_re.Raw.compile (`Repn(`Set set, 1, None)) let new_clipboard () = let r = ref (Zed_rope.empty ()) in { clipboard_get = (fun () -> !r); clipboard_set = (fun x -> r := x) } let create ?(editable=fun _pos _len -> true) ?(move = (+)) ?clipboard ?(match_word = match_by_regexp_core regexp_word_core) ?(locale = S.const None) ?(undo_size = 1000) () = let _ = move in let changes, send_changes = E.create () in let erase_mode, set_erase_mode = S.create false in let selection, set_selection = S.create false in let clipboard = match clipboard with | Some clipboard -> clipboard | None -> new_clipboard () in let edit = { data = None; text = Zed_rope.empty (); lines = Zed_lines.empty; changes; send_changes; erase_mode; set_erase_mode; editable; clipboard; mark = dummy_cursor; selection; set_selection; match_word; locale; undo = Array.make undo_size (Zed_rope.empty (), Zed_lines.empty, 0, 0, 0, 0, 0, 0); undo_size; undo_start = 0; undo_index = 0; undo_count = 0; } in edit.mark <- Zed_cursor.create 0 changes (fun () -> edit.lines) 0 0; edit let get_data engine = match engine.data with | Some data -> data | None -> raise Not_found let set_data engine data = engine.data <- Some data let clear_data engine = engine.data <- None let text engine = engine.text let lines engine = engine.lines let changes engine = engine.changes let erase_mode engine = engine.erase_mode let get_erase_mode engine = S.value engine.erase_mode let set_erase_mode engine state = engine.set_erase_mode state let mark engine = engine.mark let selection engine = engine.selection let get_selection engine = S.value engine.selection let set_selection engine state = engine.set_selection state let get_line e i = let txt = text e in let lines = lines e in let start = Zed_lines.line_start lines i in let stop = Zed_lines.line_stop lines i in Zed_rope.sub txt start (stop - start) let update engine cursors = E.select ( E.stamp engine.changes () :: E.stamp (S.changes engine.selection) () :: E.stamp (S.changes (Zed_cursor.position engine.mark)) () :: List.map (fun cursor -> E.stamp (S.changes (Zed_cursor.position cursor)) ()) cursors ) let new_cursor engine = Zed_cursor.create (Zed_rope.length engine.text) engine.changes (fun () -> engine.lines) 0 0 exception Cannot_edit type 'a context = { edit : 'a t; cursor : Zed_cursor.t; check : bool; } let context ?(check=true) edit cursor = { edit; cursor; check } let edit ctx = ctx.edit let cursor ctx = ctx.cursor let check ctx = ctx.check let with_check check ctx = { ctx with check } let goto ctx ?set_wanted_column new_position = Zed_cursor.goto ctx.cursor ?set_wanted_column new_position let move ctx ?set_wanted_column delta = Zed_cursor.move ctx.cursor ?set_wanted_column delta let next_line_n ctx n = let index = Zed_cursor.get_line ctx.cursor in if index + n > Zed_lines.count ctx.edit.lines then goto ctx ~set_wanted_column:false (Zed_rope.length ctx.edit.text) else begin let start = Zed_lines.line_start ctx.edit.lines (index + n) in let stop = if index + n = Zed_lines.count ctx.edit.lines then Zed_rope.length ctx.edit.text else Zed_lines.line_start ctx.edit.lines (index + n + 1) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let prev_line_n ctx n = let index = Zed_cursor.get_line ctx.cursor in if index - n < 0 then begin goto ctx ~set_wanted_column:false 0 end else begin let start = Zed_lines.line_start ctx.edit.lines (index - n) in let stop = Zed_lines.line_start ctx.edit.lines (index - (n - 1)) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let move_line ctx delta = match delta with | _ when delta < 0 -> prev_line_n ctx (-delta) | _ when delta > 0 -> next_line_n ctx delta | _ -> () let position ctx = Zed_cursor.get_position ctx.cursor let line ctx = Zed_cursor.get_line ctx.cursor let column ctx = Zed_cursor.get_column ctx.cursor let column_display ctx = Zed_cursor.get_column_display ctx.cursor let at_bol ctx = Zed_cursor.get_column ctx.cursor = 0 let at_eol ctx = let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then position = Zed_rope.length ctx.edit.text else position = Zed_lines.line_start ctx.edit.lines (index + 1) - 1 let at_bot ctx = Zed_cursor.get_position ctx.cursor = 0 let at_eot ctx = Zed_cursor.get_position ctx.cursor = Zed_rope.length ctx.edit.text let modify { edit ; _ } text lines position new_position added removed added_width removed_width= if edit.undo_size > 0 then begin edit.undo.(edit.undo_index) <- (text, lines, position, new_position, added, removed, added_width, removed_width); edit.undo_index <- (edit.undo_index + 1) mod edit.undo_size; if edit.undo_count = edit.undo_size then edit.undo_start <- (edit.undo_start + 1) mod edit.undo_size else edit.undo_count <- edit.undo_count + 1 end; edit.send_changes {position; added; removed; added_width; removed_width } let insert ctx rope = let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let len = Zed_rope.length rope in let text = ctx.edit.text and lines = ctx.edit.lines in if S.value ctx.edit.erase_mode then begin let text_len = Zed_rope.length ctx.edit.text in if position + len > text_len then begin let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position (text_len-position))))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position (text_len - position) rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position (text_len - position) (Zed_lines.of_rope rope); modify ctx text lines position position len (text_len - position) curr_width orig_width end else begin let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position len rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position len (Zed_lines.of_rope rope); modify ctx text lines position position len len curr_width orig_width; end; move ctx len end else begin let width_add= Zed_string.aval_width (Zed_string.width (Zed_rope.to_string rope)) in ctx.edit.text <- Zed_rope.insert ctx.edit.text position rope; ctx.edit.lines <- Zed_lines.insert ctx.edit.lines position (Zed_lines.of_rope rope); modify ctx text lines position position len 0 width_add 0; move ctx len end end else raise Cannot_edit let insert_char ctx ch = if Zed_char.is_combining_mark ch then let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let text = ctx.edit.text and lines = ctx.edit.lines in try ctx.edit.text <- Zed_rope.insert_uChar ctx.edit.text position ch; modify ctx text lines position position 1 1 0 0; move ctx 0; next_line_n ctx 0; with _-> () end else raise Cannot_edit else insert ctx (Zed_rope.of_string (fst (Zed_string.of_uChars [ch]))) let insert_no_erase ctx rope = let position = Zed_cursor.get_position ctx.cursor in if not ctx.check || ctx.edit.editable position 0 then begin let len = Zed_rope.length rope and text = ctx.edit.text and lines = ctx.edit.lines in let width_add= Zed_string.aval_width (Zed_string.width (Zed_rope.to_string rope)) in ctx.edit.text <- Zed_rope.insert text position rope; ctx.edit.lines <- Zed_lines.insert ctx.edit.lines position (Zed_lines.of_rope rope); modify ctx text lines position position len 0 width_add 0; move ctx len end else raise Cannot_edit let remove_next ctx len = let position = Zed_cursor.get_position ctx.cursor in let text_len = Zed_rope.length ctx.edit.text in let len = if position + len > text_len then text_len - position else len in if not ctx.check || ctx.edit.editable position len then begin let text = ctx.edit.text and lines = ctx.edit.lines in let width_remove= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in ctx.edit.text <- Zed_rope.remove text position len; ctx.edit.lines <- Zed_lines.remove ctx.edit.lines position len; modify ctx text lines position position 0 len 0 width_remove; end else raise Cannot_edit let remove_prev ctx len = let position = Zed_cursor.get_position ctx.cursor in let len = min position len in if not ctx.check || ctx.edit.editable (position - len) len then begin let text = ctx.edit.text and lines = ctx.edit.lines in let width_remove= Zed_string.(aval_width (width Zed_rope.(to_string (sub text (position-len) len)))) in ctx.edit.text <- Zed_rope.remove text (position - len) len; ctx.edit.lines <- Zed_lines.remove ctx.edit.lines (position - len) len; modify ctx text lines (position - len) position 0 len 0 width_remove; end else raise Cannot_edit let remove = remove_next let replace ctx len rope = let position = Zed_cursor.get_position ctx.cursor in let text_len = Zed_rope.length ctx.edit.text in let len = if position + len > text_len then text_len - position else len in if not ctx.check || ctx.edit.editable position len then begin let rope_len = Zed_rope.length rope and text = ctx.edit.text and lines = ctx.edit.lines in let orig_width= Zed_string.(aval_width (width Zed_rope.(to_string (sub text position len)))) in let curr_width= Zed_string.(aval_width (width Zed_rope.(to_string rope))) in ctx.edit.text <- Zed_rope.replace text position len rope; ctx.edit.lines <- Zed_lines.replace ctx.edit.lines position len (Zed_lines.of_rope rope); modify ctx text lines position position rope_len len curr_width orig_width; move ctx rope_len end else raise Cannot_edit let newline_rope = Zed_rope.singleton (Zed_char.unsafe_of_char '\n') let newline ctx = insert ctx newline_rope let next_char ctx = if not (at_eot ctx) then move ctx 1 let prev_char ctx = if not (at_bot ctx) then move ctx (-1) let next_line ctx = let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then goto ctx ~set_wanted_column:false (Zed_rope.length ctx.edit.text) else begin let start = Zed_lines.line_start ctx.edit.lines (index + 1) in let stop = if index + 1 = Zed_lines.count ctx.edit.lines then Zed_rope.length ctx.edit.text else Zed_lines.line_start ctx.edit.lines (index + 2) - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let prev_line ctx = let index = Zed_cursor.get_line ctx.cursor in if index = 0 then begin goto ctx ~set_wanted_column:false 0 end else begin let start = Zed_lines.line_start ctx.edit.lines (index - 1) in let stop = Zed_lines.line_start ctx.edit.lines index - 1 in goto ctx ~set_wanted_column:false (start + min (Zed_cursor.get_wanted_column ctx.cursor) (stop - start)) end let goto_bol ctx = goto ctx (Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor)) let goto_eol ctx = let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then goto ctx (Zed_rope.length ctx.edit.text) else goto ctx (Zed_lines.line_start ctx.edit.lines (index + 1) - 1) let goto_bot ctx = goto ctx 0 let goto_eot ctx = goto ctx (Zed_rope.length ctx.edit.text) let delete_next_char ctx = if not (at_eot ctx) then begin ctx.edit.set_selection false; remove_next ctx 1 end let delete_prev_char ctx = if not (at_bot ctx) then begin ctx.edit.set_selection false; remove_prev ctx 1 end let delete_next_line ctx = ctx.edit.set_selection false; let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then remove_next ctx (Zed_rope.length ctx.edit.text - position) else remove_next ctx (Zed_lines.line_start ctx.edit.lines (index + 1) - position) let delete_prev_line ctx = ctx.edit.set_selection false; let position = Zed_cursor.get_position ctx.cursor in let start = Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor) in remove_prev ctx (position - start) let kill_next_line ctx = let position = Zed_cursor.get_position ctx.cursor in let index = Zed_cursor.get_line ctx.cursor in if index = Zed_lines.count ctx.edit.lines then begin ctx.edit.clipboard.clipboard_set (Zed_rope.after ctx.edit.text position); ctx.edit.set_selection false; remove ctx (Zed_rope.length ctx.edit.text - position) end else begin let len = Zed_lines.line_start ctx.edit.lines (index + 1) - position in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text position len); ctx.edit.set_selection false; remove ctx len end let kill_prev_line ctx = let position = Zed_cursor.get_position ctx.cursor in let start = Zed_lines.line_start ctx.edit.lines (Zed_cursor.get_line ctx.cursor) in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text start (position - start)); ctx.edit.set_selection false; remove_prev ctx (position - start) let switch_erase_mode ctx = ctx.edit.set_erase_mode (not (S.value ctx.edit.erase_mode)) let set_mark ctx = Zed_cursor.goto ctx.edit.mark (Zed_cursor.get_position ctx.cursor); ctx.edit.set_selection true let goto_mark ctx = goto ctx (Zed_cursor.get_position ctx.edit.mark) let copy ctx = if S.value ctx.edit.selection then begin let a = Zed_cursor.get_position ctx.cursor and b = Zed_cursor.get_position ctx.edit.mark in let a = min a b and b = max a b in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text a (b - a)); ctx.edit.set_selection false end let kill ctx = if S.value ctx.edit.selection then begin let a = Zed_cursor.get_position ctx.cursor and b = Zed_cursor.get_position ctx.edit.mark in let a = min a b and b = max a b in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text a (b - a)); ctx.edit.set_selection false; goto ctx a; let a = Zed_cursor.get_position ctx.cursor in if a <= b then remove ctx (b - a) end let yank ctx = ctx.edit.set_selection false; insert ctx (ctx.edit.clipboard.clipboard_get ()) let search_word_forward ctx = let len = Zed_rope.length ctx.edit.text in let rec loop idx = if idx = len then None else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> Some(idx, idx') | None -> loop (idx + 1) in loop (Zed_cursor.get_position ctx.cursor) let search_word_backward ctx = let rec loop idx = if idx = -1 then None else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> loop2 (idx - 1) (idx, idx') | None -> loop (idx - 1) and loop2 idx result = if idx = -1 then Some result else match ctx.edit.match_word ctx.edit.text idx with | Some idx' -> loop2 (idx - 1) (idx, idx') | None -> Some result in loop (Zed_cursor.get_position ctx.cursor - 1) let capitalize_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 && idx1 < idx2 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in let ch, str' = Zed_rope.break str 1 in replace ctx (Zed_rope.length str) (Zed_rope.append (CaseMap.uppercase ?locale:(S.value ctx.edit.locale) ch) (CaseMap.lowercase ?locale:(S.value ctx.edit.locale) str')) end | None -> () let lowercase_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in replace ctx (Zed_rope.length str) (CaseMap.lowercase ?locale:(S.value ctx.edit.locale) str) end | None -> () let uppercase_word ctx = match search_word_forward ctx with | Some(idx1, idx2) -> goto ctx idx1; if Zed_cursor.get_position ctx.cursor = idx1 then begin let str = Zed_rope.sub ctx.edit.text idx1 (idx2 - idx1) in replace ctx (Zed_rope.length str) (CaseMap.uppercase ?locale:(S.value ctx.edit.locale) str) end | None -> () let next_word ctx = match search_word_forward ctx with | Some(_idx1, idx2) -> goto ctx idx2 | None -> goto ctx (Zed_rope.length ctx.edit.text) let prev_word ctx = match search_word_backward ctx with | Some(idx1, _idx2) -> goto ctx idx1 | None -> goto ctx 0 let delete_next_word ctx = let position = Zed_cursor.get_position ctx.cursor in let word_end = match search_word_forward ctx with | Some(_idx1, idx2) -> idx2 | None -> Zed_rope.length ctx.edit.text in remove ctx (word_end - position) let delete_prev_word ctx = let position = Zed_cursor.get_position ctx.cursor in let start = match search_word_backward ctx with | Some(idx1, _idx2) -> idx1 | None -> 0 in remove_prev ctx (position - start) let kill_next_word ctx = let position = Zed_cursor.get_position ctx.cursor in let word_end = match search_word_forward ctx with | Some(_idx1, idx2) -> idx2 | None -> Zed_rope.length ctx.edit.text in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text position (word_end - position)); ctx.edit.set_selection false; remove ctx (word_end - position) let kill_prev_word ctx = let position = Zed_cursor.get_position ctx.cursor in let start = match search_word_backward ctx with | Some(idx1, _idx2) -> idx1 | None -> 0 in ctx.edit.clipboard.clipboard_set (Zed_rope.sub ctx.edit.text start (position - start)); ctx.edit.set_selection false; remove_prev ctx (position - start) let undo { check; edit; cursor } = if edit.undo_count > 0 then begin let index = if edit.undo_index = 0 then edit.undo_size - 1 else edit.undo_index - 1 in let text, lines, pos, new_pos, added, removed, added_width, removed_width = edit.undo.(index) in if not check || edit.editable pos added then begin edit.undo_count <- edit.undo_count - 1; edit.undo_index <- index; edit.text <- text; edit.lines <- lines; edit.send_changes {position= pos; removed; added; added_width; removed_width }; Zed_cursor.goto cursor new_pos end else raise Cannot_edit end type action = | Insert of Zed_char.t | Newline | Next_char | Prev_char | Next_line | Prev_line | Goto_bol | Goto_eol | Goto_bot | Goto_eot | Delete_next_char | Delete_prev_char | Delete_next_line | Delete_prev_line | Kill_next_line | Kill_prev_line | Switch_erase_mode | Set_mark | Goto_mark | Copy | Kill | Yank | Capitalize_word | Lowercase_word | Uppercase_word | Next_word | Prev_word | Delete_next_word | Delete_prev_word | Kill_next_word | Kill_prev_word | Undo let get_action = function | Insert ch -> (fun ctx -> if Zed_char.length ch = 1 then insert_char ctx (Zed_char.core ch) else insert ctx (Zed_rope.singleton ch)) | Newline -> newline | Next_char -> next_char | Prev_char -> prev_char | Next_line -> next_line | Prev_line -> prev_line | Goto_bol -> goto_bol | Goto_eol -> goto_eol | Goto_bot -> goto_bot | Goto_eot -> goto_eot | Delete_next_char -> delete_next_char | Delete_prev_char -> delete_prev_char | Delete_next_line -> delete_next_line | Delete_prev_line -> delete_prev_line | Kill_next_line -> kill_next_line | Kill_prev_line -> kill_prev_line | Switch_erase_mode -> switch_erase_mode | Set_mark -> set_mark | Goto_mark -> goto_mark | Copy -> copy | Kill -> kill | Yank -> yank | Capitalize_word -> capitalize_word | Lowercase_word -> lowercase_word | Uppercase_word -> uppercase_word | Next_word -> next_word | Prev_word -> prev_word | Delete_next_word -> delete_next_word | Delete_prev_word -> delete_prev_word | Kill_next_word -> kill_next_word | Kill_prev_word -> kill_prev_word | Undo -> undo let doc_of_action = function | Insert _ -> "insert the given character." | Newline -> "insert a newline character." | Next_char -> "move the cursor to the next character." | Prev_char -> "move the cursor to the previous character." | Next_line -> "move the cursor to the next line." | Prev_line -> "move the cursor to the previous line." | Goto_bol -> "move the cursor to the beginning of the current line." | Goto_eol -> "move the cursor to the end of the current line." | Goto_bot -> "move the cursor to the beginning of the text." | Goto_eot -> "move the cursor to the end of the text." | Delete_next_char -> "delete the character after the cursor." | Delete_prev_char -> "delete the character before the cursor." | Delete_next_line -> "delete everything until the end of the current line." | Delete_prev_line -> "delete everything until the beginning of the current line." | Kill_next_line -> "cut everything until the end of the current line." | Kill_prev_line -> "cut everything until the beginning of the current line." | Switch_erase_mode -> "switch the current erasing mode." | Set_mark -> "set the mark to the current position." | Goto_mark -> "move the cursor to the mark." | Copy -> "copy the current region to the clipboard." | Kill -> "cut the current region to the clipboard." | Yank -> "paste the contents of the clipboard at current position." | Capitalize_word -> "capitalize the first word after the cursor." | Lowercase_word -> "convert the first word after the cursor to lowercase." | Uppercase_word -> "convert the first word after the cursor to uppercase." | Next_word -> "move the cursor to the end of the next word." | Prev_word -> "move the cursor to the beginning of the previous word." | Delete_next_word -> "delete up until the next non-word character." | Delete_prev_word -> "delete the word behind the cursor." | Kill_next_word -> "cut up until the next non-word character." | Kill_prev_word -> "cut the word behind the cursor." | Undo -> "revert the last action." let actions = [ Newline, "newline"; Next_char, "next-char"; Prev_char, "prev-char"; Next_line, "next-line"; Prev_line, "prev-line"; Goto_bol, "goto-bol"; Goto_eol, "goto-eol"; Goto_bot, "goto-bot"; Goto_eot, "goto-eot"; Delete_next_char, "delete-next-char"; Delete_prev_char, "delete-prev-char"; Delete_next_line, "delete-next-line"; Delete_prev_line, "delete-prev-line"; Kill_next_line, "kill-next-line"; Kill_prev_line, "kill-prev-line"; Switch_erase_mode, "switch-erase-mode"; Set_mark, "set-mark"; Goto_mark, "goto-mark"; Copy, "copy"; Kill, "kill"; Yank, "yank"; Capitalize_word, "capitalize-word"; Lowercase_word, "lowercase-word"; Uppercase_word, "uppercase-word"; Next_word, "next-word"; Prev_word, "prev-word"; Delete_next_word, "delete-next-word"; Delete_prev_word, "delete-prev-word"; Kill_next_word, "kill-next-word"; Kill_prev_word, "kill-prev-word"; Undo, "undo"; ] let actions_to_names = Array.of_list (List.sort (fun (a1, _) (a2, _) -> compare a1 a2) actions) let names_to_actions = Array.of_list (List.sort (fun (_, n1) (_, n2) -> compare n1 n2) actions) let parse_insert x = if Zed_utf8.starts_with x "insert(" && Zed_utf8.ends_with x ")" then begin let str = String.sub x 7 (String.length x - 8) in if String.length str = 1 && Char.code str.[0] < 128 then Insert(Zed_char.unsafe_of_uChar (UChar.of_char str.[0])) else if String.length str > 2 && str.[0] = 'U' && str.[1] = '+' then let acc = ref 0 in for i = 2 to String.length str - 1 do let ch = str.[i] in acc := !acc * 16 + (match ch with | '0' .. '9' -> Char.code ch - Char.code '0' | 'a' .. 'f' -> Char.code ch - Char.code 'a' + 10 | 'A' .. 'F' -> Char.code ch - Char.code 'A' + 10 | _ -> raise Not_found) done; try Insert(Zed_char.unsafe_of_uChar (UChar.of_int !acc)) with _ -> raise Not_found else raise Not_found end else raise Not_found let action_of_name x = let rec loop a b = if a = b then parse_insert x else let c = (a + b) / 2 in let action, name = Array.unsafe_get names_to_actions c in match compare x name with | d when d < 0 -> loop a c | d when d > 0 -> loop (c + 1) b | _ -> action in loop 0 (Array.length names_to_actions) let name_of_action x = let rec loop a b = if a = b then raise Not_found else let c = (a + b) / 2 in let action, name = Array.unsafe_get actions_to_names c in match compare x action with | d when d < 0 -> loop a c | d when d > 0 -> loop (c + 1) b | _ -> name in match x with | Insert ch -> let code = UChar.code (Zed_char.core ch) in if code <= 255 then let ch = Char.chr (UChar.code (Zed_char.core ch)) in match ch with | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' -> Printf.sprintf "insert(%c)" ch | _ -> Printf.sprintf "insert(U+%02x)" code else if code <= 0xffff then Printf.sprintf "insert(U+%04x)" code else Printf.sprintf "insert(U+%06x)" code | _ -> loop 0 (Array.length actions_to_names)
194fbdb493926025f0fe0ced8ea6ae317c9afc88fcad33845b86d72543b94930
joneshf/purty
Span.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} # LANGUAGE NoImplicitPrelude # module Span ( Span (..), adoBlock, betweenSourceRanges, betweenSourceTokens, binder, caseOf, comment, constraint, dataCtor, dataMembers, declaration, delimitedNonEmpty, doBlock, doStatement, export, expr, foreign', guarded, guardedExpr, ifThenElse, import', importDecl, instance', instanceBinding, instanceHead, label, labeled, lambda, lineFeed, letBinding, letIn, name, oneOrDelimited, patternGuard, qualifiedName, recordAccessor, recordLabeled, recordUpdate, row, separated, sourceRange, sourceToken, type', typeVarBinding, valueBindingFields, where', wrapped, ) where import qualified "purescript-cst" Language.PureScript.CST.Positions import qualified "purescript-cst" Language.PureScript.CST.Types import "rio" RIO import qualified "rio" RIO.Text import qualified "purs-tool-cst" SourceRange data Span = MultipleLines | SingleLine deriving (Show) instance Semigroup Span where span1 <> span2 = case (span1, span2) of (MultipleLines, MultipleLines) -> MultipleLines (MultipleLines, SingleLine) -> MultipleLines (SingleLine, MultipleLines) -> MultipleLines (SingleLine, SingleLine) -> SingleLine instance Monoid Span where mempty = SingleLine adoBlock :: Language.PureScript.CST.Types.AdoBlock a -> Span adoBlock = sourceRange . SourceRange.adoBlock betweenSourceRanges :: Language.PureScript.CST.Types.SourceRange -> Language.PureScript.CST.Types.SourceRange -> Span betweenSourceRanges start end = sourceRange (Language.PureScript.CST.Positions.widen start end) betweenSourceTokens :: Language.PureScript.CST.Types.SourceToken -> Language.PureScript.CST.Types.SourceToken -> Span betweenSourceTokens start end = sourceRange (Language.PureScript.CST.Positions.toSourceRange (start, end)) binder :: Language.PureScript.CST.Types.Binder a -> Span binder = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.binderRange caseOf :: Language.PureScript.CST.Types.CaseOf a -> Span caseOf = sourceRange . SourceRange.caseOf comment :: (a -> Span) -> Language.PureScript.CST.Types.Comment a -> Span comment f comment'' = case comment'' of Language.PureScript.CST.Types.Comment comment' -> case RIO.Text.find (== '\n') comment' of Nothing -> Span.SingleLine Just _ -> Span.MultipleLines Language.PureScript.CST.Types.Line a -> f a Language.PureScript.CST.Types.Space _ -> Span.SingleLine constraint :: Language.PureScript.CST.Types.Constraint a -> Span constraint = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.constraintRange dataCtor :: Language.PureScript.CST.Types.DataCtor a -> Span dataCtor = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.dataCtorRange dataMembers :: Language.PureScript.CST.Types.DataMembers a -> Span dataMembers = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.dataMembersRange declaration :: Language.PureScript.CST.Types.Declaration a -> Span declaration = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.declRange delimitedNonEmpty :: Language.PureScript.CST.Types.DelimitedNonEmpty a -> Span delimitedNonEmpty = sourceRange . SourceRange.wrapped doBlock :: Language.PureScript.CST.Types.DoBlock a -> Span doBlock = sourceRange . SourceRange.doBlock doStatement :: Language.PureScript.CST.Types.DoStatement a -> Span doStatement = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.doStatementRange export :: Language.PureScript.CST.Types.Export a -> Span export = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.exportRange expr :: Language.PureScript.CST.Types.Expr a -> Span expr = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.exprRange foreign' :: Language.PureScript.CST.Types.Foreign a -> Span foreign' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.foreignRange guarded :: Language.PureScript.CST.Types.Guarded a -> Span guarded = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.guardedRange guardedExpr :: Language.PureScript.CST.Types.GuardedExpr a -> Span guardedExpr = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.guardedExprRange ifThenElse :: Language.PureScript.CST.Types.IfThenElse a -> Span ifThenElse = sourceRange . SourceRange.ifThenElse import' :: Language.PureScript.CST.Types.Import a -> Span import' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.importRange importDecl :: Language.PureScript.CST.Types.ImportDecl a -> Span importDecl = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.importDeclRange instance' :: Language.PureScript.CST.Types.Instance a -> Span instance' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceRange instanceBinding :: Language.PureScript.CST.Types.InstanceBinding a -> Span instanceBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceBindingRange instanceHead :: Language.PureScript.CST.Types.InstanceHead a -> Span instanceHead = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceHeadRange label :: Language.PureScript.CST.Types.Label -> Span label = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.labelRange labeled :: (a -> Language.PureScript.CST.Types.SourceRange) -> (b -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.Labeled a b -> Span labeled f g labeled' = case labeled' of Language.PureScript.CST.Types.Labeled a _ b -> sourceRange (Language.PureScript.CST.Positions.widen (f a) (g b)) lambda :: Language.PureScript.CST.Types.Lambda a -> Span lambda = sourceRange . SourceRange.lambda linesBetween :: Language.PureScript.CST.Types.SourcePos -> Language.PureScript.CST.Types.SourcePos -> Int linesBetween start end = case (start, end) of (Language.PureScript.CST.Types.SourcePos line _, Language.PureScript.CST.Types.SourcePos line' _) -> line - line' lineFeed :: Language.PureScript.CST.Types.LineFeed -> Span lineFeed lineFeed' = case lineFeed' of Language.PureScript.CST.Types.LF -> Span.SingleLine Language.PureScript.CST.Types.CRLF -> Span.SingleLine letBinding :: Language.PureScript.CST.Types.LetBinding a -> Span letBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.letBindingRange letIn :: Language.PureScript.CST.Types.LetIn a -> Span letIn = sourceRange . SourceRange.letIn name :: Language.PureScript.CST.Types.Name a -> Span name = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.nameRange oneOrDelimited :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.OneOrDelimited a -> Span oneOrDelimited f = sourceRange . SourceRange.oneOrDelimited f patternGuard :: Language.PureScript.CST.Types.PatternGuard a -> Span patternGuard = sourceRange . SourceRange.patternGuard qualifiedName :: Language.PureScript.CST.Types.QualifiedName a -> Span qualifiedName = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.qualRange recordAccessor :: Language.PureScript.CST.Types.RecordAccessor a -> Span recordAccessor = sourceRange . SourceRange.recordAccessor recordLabeled :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.RecordLabeled a -> Span recordLabeled f recordLabeled' = case recordLabeled' of Language.PureScript.CST.Types.RecordPun name' -> name name' Language.PureScript.CST.Types.RecordField label' _ a -> sourceRange ( Language.PureScript.CST.Positions.widen (SourceRange.label label') (f a) ) recordUpdate :: Language.PureScript.CST.Types.RecordUpdate a -> Span recordUpdate = sourceRange . SourceRange.recordUpdate row :: Language.PureScript.CST.Types.Row a -> Span row row' = case row' of Language.PureScript.CST.Types.Row labels' tail -> case (labels', tail) of (Just labels, Just (_, type'')) -> sourceRange ( Language.PureScript.CST.Positions.widen ( SourceRange.separated (SourceRange.labeled SourceRange.label SourceRange.type') labels ) (SourceRange.type' type'') ) (Just labels, Nothing) -> separated (SourceRange.labeled SourceRange.label SourceRange.type') labels (Nothing, Just (_, type'')) -> type' type'' (Nothing, Nothing) -> SingleLine separated :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.Separated a -> Span separated f = sourceRange . SourceRange.separated f sourceToken :: Language.PureScript.CST.Types.SourceToken -> Span sourceToken = sourceRange . Language.PureScript.CST.Positions.srcRange sourceRange :: Language.PureScript.CST.Types.SourceRange -> Span sourceRange sourceRange' = case sourceRange' of Language.PureScript.CST.Types.SourceRange start end -> case linesBetween start end of 0 -> SingleLine _ -> MultipleLines type' :: Language.PureScript.CST.Types.Type a -> Span type' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.typeRange typeVarBinding :: Language.PureScript.CST.Types.TypeVarBinding a -> Span typeVarBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.typeVarBindingRange valueBindingFields :: Language.PureScript.CST.Types.ValueBindingFields a -> Span valueBindingFields = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.valueBindingFieldsRange where' :: Language.PureScript.CST.Types.Where a -> Span where' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.whereRange wrapped :: Language.PureScript.CST.Types.Wrapped a -> Span wrapped = sourceRange . SourceRange.wrapped
null
https://raw.githubusercontent.com/joneshf/purty/a3bd72646b3b6237e185ab4d10a1c4b50987faee/internal/format/Span.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE PackageImports #
# LANGUAGE NoImplicitPrelude # module Span ( Span (..), adoBlock, betweenSourceRanges, betweenSourceTokens, binder, caseOf, comment, constraint, dataCtor, dataMembers, declaration, delimitedNonEmpty, doBlock, doStatement, export, expr, foreign', guarded, guardedExpr, ifThenElse, import', importDecl, instance', instanceBinding, instanceHead, label, labeled, lambda, lineFeed, letBinding, letIn, name, oneOrDelimited, patternGuard, qualifiedName, recordAccessor, recordLabeled, recordUpdate, row, separated, sourceRange, sourceToken, type', typeVarBinding, valueBindingFields, where', wrapped, ) where import qualified "purescript-cst" Language.PureScript.CST.Positions import qualified "purescript-cst" Language.PureScript.CST.Types import "rio" RIO import qualified "rio" RIO.Text import qualified "purs-tool-cst" SourceRange data Span = MultipleLines | SingleLine deriving (Show) instance Semigroup Span where span1 <> span2 = case (span1, span2) of (MultipleLines, MultipleLines) -> MultipleLines (MultipleLines, SingleLine) -> MultipleLines (SingleLine, MultipleLines) -> MultipleLines (SingleLine, SingleLine) -> SingleLine instance Monoid Span where mempty = SingleLine adoBlock :: Language.PureScript.CST.Types.AdoBlock a -> Span adoBlock = sourceRange . SourceRange.adoBlock betweenSourceRanges :: Language.PureScript.CST.Types.SourceRange -> Language.PureScript.CST.Types.SourceRange -> Span betweenSourceRanges start end = sourceRange (Language.PureScript.CST.Positions.widen start end) betweenSourceTokens :: Language.PureScript.CST.Types.SourceToken -> Language.PureScript.CST.Types.SourceToken -> Span betweenSourceTokens start end = sourceRange (Language.PureScript.CST.Positions.toSourceRange (start, end)) binder :: Language.PureScript.CST.Types.Binder a -> Span binder = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.binderRange caseOf :: Language.PureScript.CST.Types.CaseOf a -> Span caseOf = sourceRange . SourceRange.caseOf comment :: (a -> Span) -> Language.PureScript.CST.Types.Comment a -> Span comment f comment'' = case comment'' of Language.PureScript.CST.Types.Comment comment' -> case RIO.Text.find (== '\n') comment' of Nothing -> Span.SingleLine Just _ -> Span.MultipleLines Language.PureScript.CST.Types.Line a -> f a Language.PureScript.CST.Types.Space _ -> Span.SingleLine constraint :: Language.PureScript.CST.Types.Constraint a -> Span constraint = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.constraintRange dataCtor :: Language.PureScript.CST.Types.DataCtor a -> Span dataCtor = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.dataCtorRange dataMembers :: Language.PureScript.CST.Types.DataMembers a -> Span dataMembers = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.dataMembersRange declaration :: Language.PureScript.CST.Types.Declaration a -> Span declaration = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.declRange delimitedNonEmpty :: Language.PureScript.CST.Types.DelimitedNonEmpty a -> Span delimitedNonEmpty = sourceRange . SourceRange.wrapped doBlock :: Language.PureScript.CST.Types.DoBlock a -> Span doBlock = sourceRange . SourceRange.doBlock doStatement :: Language.PureScript.CST.Types.DoStatement a -> Span doStatement = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.doStatementRange export :: Language.PureScript.CST.Types.Export a -> Span export = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.exportRange expr :: Language.PureScript.CST.Types.Expr a -> Span expr = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.exprRange foreign' :: Language.PureScript.CST.Types.Foreign a -> Span foreign' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.foreignRange guarded :: Language.PureScript.CST.Types.Guarded a -> Span guarded = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.guardedRange guardedExpr :: Language.PureScript.CST.Types.GuardedExpr a -> Span guardedExpr = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.guardedExprRange ifThenElse :: Language.PureScript.CST.Types.IfThenElse a -> Span ifThenElse = sourceRange . SourceRange.ifThenElse import' :: Language.PureScript.CST.Types.Import a -> Span import' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.importRange importDecl :: Language.PureScript.CST.Types.ImportDecl a -> Span importDecl = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.importDeclRange instance' :: Language.PureScript.CST.Types.Instance a -> Span instance' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceRange instanceBinding :: Language.PureScript.CST.Types.InstanceBinding a -> Span instanceBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceBindingRange instanceHead :: Language.PureScript.CST.Types.InstanceHead a -> Span instanceHead = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.instanceHeadRange label :: Language.PureScript.CST.Types.Label -> Span label = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.labelRange labeled :: (a -> Language.PureScript.CST.Types.SourceRange) -> (b -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.Labeled a b -> Span labeled f g labeled' = case labeled' of Language.PureScript.CST.Types.Labeled a _ b -> sourceRange (Language.PureScript.CST.Positions.widen (f a) (g b)) lambda :: Language.PureScript.CST.Types.Lambda a -> Span lambda = sourceRange . SourceRange.lambda linesBetween :: Language.PureScript.CST.Types.SourcePos -> Language.PureScript.CST.Types.SourcePos -> Int linesBetween start end = case (start, end) of (Language.PureScript.CST.Types.SourcePos line _, Language.PureScript.CST.Types.SourcePos line' _) -> line - line' lineFeed :: Language.PureScript.CST.Types.LineFeed -> Span lineFeed lineFeed' = case lineFeed' of Language.PureScript.CST.Types.LF -> Span.SingleLine Language.PureScript.CST.Types.CRLF -> Span.SingleLine letBinding :: Language.PureScript.CST.Types.LetBinding a -> Span letBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.letBindingRange letIn :: Language.PureScript.CST.Types.LetIn a -> Span letIn = sourceRange . SourceRange.letIn name :: Language.PureScript.CST.Types.Name a -> Span name = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.nameRange oneOrDelimited :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.OneOrDelimited a -> Span oneOrDelimited f = sourceRange . SourceRange.oneOrDelimited f patternGuard :: Language.PureScript.CST.Types.PatternGuard a -> Span patternGuard = sourceRange . SourceRange.patternGuard qualifiedName :: Language.PureScript.CST.Types.QualifiedName a -> Span qualifiedName = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.qualRange recordAccessor :: Language.PureScript.CST.Types.RecordAccessor a -> Span recordAccessor = sourceRange . SourceRange.recordAccessor recordLabeled :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.RecordLabeled a -> Span recordLabeled f recordLabeled' = case recordLabeled' of Language.PureScript.CST.Types.RecordPun name' -> name name' Language.PureScript.CST.Types.RecordField label' _ a -> sourceRange ( Language.PureScript.CST.Positions.widen (SourceRange.label label') (f a) ) recordUpdate :: Language.PureScript.CST.Types.RecordUpdate a -> Span recordUpdate = sourceRange . SourceRange.recordUpdate row :: Language.PureScript.CST.Types.Row a -> Span row row' = case row' of Language.PureScript.CST.Types.Row labels' tail -> case (labels', tail) of (Just labels, Just (_, type'')) -> sourceRange ( Language.PureScript.CST.Positions.widen ( SourceRange.separated (SourceRange.labeled SourceRange.label SourceRange.type') labels ) (SourceRange.type' type'') ) (Just labels, Nothing) -> separated (SourceRange.labeled SourceRange.label SourceRange.type') labels (Nothing, Just (_, type'')) -> type' type'' (Nothing, Nothing) -> SingleLine separated :: (a -> Language.PureScript.CST.Types.SourceRange) -> Language.PureScript.CST.Types.Separated a -> Span separated f = sourceRange . SourceRange.separated f sourceToken :: Language.PureScript.CST.Types.SourceToken -> Span sourceToken = sourceRange . Language.PureScript.CST.Positions.srcRange sourceRange :: Language.PureScript.CST.Types.SourceRange -> Span sourceRange sourceRange' = case sourceRange' of Language.PureScript.CST.Types.SourceRange start end -> case linesBetween start end of 0 -> SingleLine _ -> MultipleLines type' :: Language.PureScript.CST.Types.Type a -> Span type' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.typeRange typeVarBinding :: Language.PureScript.CST.Types.TypeVarBinding a -> Span typeVarBinding = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.typeVarBindingRange valueBindingFields :: Language.PureScript.CST.Types.ValueBindingFields a -> Span valueBindingFields = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.valueBindingFieldsRange where' :: Language.PureScript.CST.Types.Where a -> Span where' = sourceRange . Language.PureScript.CST.Positions.toSourceRange . Language.PureScript.CST.Positions.whereRange wrapped :: Language.PureScript.CST.Types.Wrapped a -> Span wrapped = sourceRange . SourceRange.wrapped
c5a07b13a25a588d9e391b300d09c3bf2d971b0c39f0b55c7d14efd2829c1adb
phylogeography/spread
subscriptions.cljs
(ns ui.subscriptions (:require [clojure.string :as string] [re-frame.core :as re-frame])) (re-frame/reg-sub ::config (fn [db _] (get db :config))) (re-frame/reg-sub ::users (fn [db _] (-> db :users (dissoc :authorized-user)))) (re-frame/reg-sub ::authorized-user (fn [db _] (-> db :users :authorized-user))) (re-frame/reg-sub ::search (fn [db] (:search db))) (re-frame/reg-sub ::analysis (fn [db] (-> db :analysis))) (re-frame/reg-sub ::sorted-analysis :<- [::analysis] (fn [analysis] (sort-by :created-on (-> analysis vals vec)))) (re-frame/reg-sub ::analysis-results :<- [::analysis] (fn [analysis [_ id]] (get analysis id))) (re-frame/reg-sub ::ongoing-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"UPLOADED" "ATTRIBUTES_PARSED" "ARGUMENTS_SET"} (:status elem))) analysis))) (re-frame/reg-sub ::completed-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"ERROR" "SUCCEEDED"} (:status elem))) analysis))) (re-frame/reg-sub ::completed-analysis-search :<- [::completed-analysis] :<- [::search] (fn [[completed-analysis search-term]] (if search-term (filter (fn [elem] (let [readable-name (-> elem :readable-name)] (when readable-name (string/includes? (string/lower-case readable-name) (string/lower-case search-term))))) completed-analysis) completed-analysis))) (re-frame/reg-sub ::new-completed-analysis :<- [::completed-analysis] (fn [completed-analysis] (filter (fn [elem] (:new? elem)) completed-analysis))) (re-frame/reg-sub ::queued-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"QUEUED""RUNNING"} (:status elem))) analysis))) (re-frame/reg-sub ::continuous-mcc-tree (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :continuous-mcc-tree]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::discrete-mcc-tree (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :discrete-mcc-tree]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::bayes-factor (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :bayes-factor]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::pastebin (fn [db _] (get db :pastebin))) (comment @(re-frame/subscribe [::authorized-user]) @(re-frame/subscribe [::discrete-tree-parsers]) @(re-frame/subscribe [::discrete-tree-parser "60b08880-03e6-4a3f-a170-29f3c75cb43f"]))
null
https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljs/ui/subscriptions.cljs
clojure
(ns ui.subscriptions (:require [clojure.string :as string] [re-frame.core :as re-frame])) (re-frame/reg-sub ::config (fn [db _] (get db :config))) (re-frame/reg-sub ::users (fn [db _] (-> db :users (dissoc :authorized-user)))) (re-frame/reg-sub ::authorized-user (fn [db _] (-> db :users :authorized-user))) (re-frame/reg-sub ::search (fn [db] (:search db))) (re-frame/reg-sub ::analysis (fn [db] (-> db :analysis))) (re-frame/reg-sub ::sorted-analysis :<- [::analysis] (fn [analysis] (sort-by :created-on (-> analysis vals vec)))) (re-frame/reg-sub ::analysis-results :<- [::analysis] (fn [analysis [_ id]] (get analysis id))) (re-frame/reg-sub ::ongoing-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"UPLOADED" "ATTRIBUTES_PARSED" "ARGUMENTS_SET"} (:status elem))) analysis))) (re-frame/reg-sub ::completed-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"ERROR" "SUCCEEDED"} (:status elem))) analysis))) (re-frame/reg-sub ::completed-analysis-search :<- [::completed-analysis] :<- [::search] (fn [[completed-analysis search-term]] (if search-term (filter (fn [elem] (let [readable-name (-> elem :readable-name)] (when readable-name (string/includes? (string/lower-case readable-name) (string/lower-case search-term))))) completed-analysis) completed-analysis))) (re-frame/reg-sub ::new-completed-analysis :<- [::completed-analysis] (fn [completed-analysis] (filter (fn [elem] (:new? elem)) completed-analysis))) (re-frame/reg-sub ::queued-analysis :<- [::sorted-analysis] (fn [analysis] (filter (fn [elem] (#{"QUEUED""RUNNING"} (:status elem))) analysis))) (re-frame/reg-sub ::continuous-mcc-tree (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :continuous-mcc-tree]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::discrete-mcc-tree (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :discrete-mcc-tree]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::bayes-factor (fn [db] (let [ongoing-analysis (get-in db [:new-analysis :bayes-factor]) id (:id ongoing-analysis)] (merge ongoing-analysis (get-in db [:analysis id]))))) (re-frame/reg-sub ::pastebin (fn [db _] (get db :pastebin))) (comment @(re-frame/subscribe [::authorized-user]) @(re-frame/subscribe [::discrete-tree-parsers]) @(re-frame/subscribe [::discrete-tree-parser "60b08880-03e6-4a3f-a170-29f3c75cb43f"]))
1fbfc19632b94b73995c5c76ccd59221a4c0c5bfc79681dd57609ef3fcc6acd8
igorhvr/bedlam
jndi.scm
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in compliance with ;;; the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " basis , ;;; WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License ;;; for the specific language governing rights and limitations under the ;;; License. ;;; The Original Code is SISCweb . ;;; The Initial Developer of the Original Code is . Portions created by the Initial Developer are Copyright ( C ) 2005 . All Rights Reserved . ;;; ;;; Contributor(s): ;;; ;;; Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later ( the " GPL " ) , or the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) , ;;; in which case the provisions of the GPL or the LGPL are applicable instead ;;; of those above. If you wish to allow use of your version of this file only ;;; under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL , indicate your ;;; decision by deleting the provisions above and replace them with the notice ;;; and other provisions required by the GPL or the LGPL. If you do not delete ;;; the provisions above, a recipient may use your version of this file under the terms of any one of the MPL , the GPL or the LGPL . (module util/jndi (jndi/lookup) (import s2j) (define-java-classes (<initial-context> |javax.naming.InitialContext|)) (define-generic-java-methods lookup) (define (jndi/lookup name) (with/fc (lambda (m e) #f) (lambda () (lookup (java-new <initial-context>) (->jstring name))))) )
null
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/siscweb/siscweb-src-0.5/scm/util/jndi.scm
scheme
you may not use this file except in compliance with the License. You may obtain a copy of the License at / WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Contributor(s): Alternatively, the contents of this file may be used under the terms of in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under
The contents of this file are subject to the Mozilla Public License Version Software distributed under the License is distributed on an " AS IS " basis , The Original Code is SISCweb . The Initial Developer of the Original Code is . Portions created by the Initial Developer are Copyright ( C ) 2005 . All Rights Reserved . either the GNU General Public License Version 2 or later ( the " GPL " ) , or the GNU Lesser General Public License Version 2.1 or later ( the " LGPL " ) , use your version of this file under the terms of the MPL , indicate your the terms of any one of the MPL , the GPL or the LGPL . (module util/jndi (jndi/lookup) (import s2j) (define-java-classes (<initial-context> |javax.naming.InitialContext|)) (define-generic-java-methods lookup) (define (jndi/lookup name) (with/fc (lambda (m e) #f) (lambda () (lookup (java-new <initial-context>) (->jstring name))))) )
e48f2f8bdca318f2d60cb8f30eb0eddc5a84149c0bf0911ad0845d459a5735d4
ucsd-progsys/nate
main.ml
(*************************************************************************) (* *) (* Objective Caml LablTk library *) (* *) , Kyoto University RIMS (* *) Copyright 1999 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library (* General Public License, with the special exception on linking *) (* described in file ../../../LICENSE. *) (* *) (*************************************************************************) $ I d : main.ml , v 1.34 2006/04/16 23:28:21 doligez Exp $ open StdLabels module Unix = UnixLabels open Tk let fatal_error text = let top = openTk ~clas:"OCamlBrowser" () in let mw = Message.create top ~text ~padx:20 ~pady:10 ~width:400 ~justify:`Left ~aspect:400 ~anchor:`W and b = Button.create top ~text:"OK" ~command:(fun () -> destroy top) in pack [mw] ~side:`Top ~fill:`Both; pack [b] ~side:`Bottom; mainLoop (); exit 0 let rec get_incr key = function [] -> raise Not_found | (k, c, d) :: rem -> if k = key then match c with Arg.Set _ | Arg.Clear _ | Arg.Unit _ -> false | _ -> true else get_incr key rem let check ~spec argv = let i = ref 1 in while !i < Array.length argv do try let a = get_incr argv.(!i) spec in incr i; if a then incr i with Not_found -> i := Array.length argv + 1 done; !i = Array.length argv open Printf let print_version () = printf "The Objective Caml browser, version %s\n" Sys.ocaml_version; exit 0; ;; let usage ~spec errmsg = let b = Buffer.create 1024 in bprintf b "%s\n" errmsg; List.iter (function (key, _, doc) -> bprintf b " %s %s\n" key doc) spec; Buffer.contents b let _ = let is_win32 = Sys.os_type = "Win32" in if is_win32 then Format.pp_set_formatter_output_functions Format.err_formatter (fun _ _ _ -> ()) (fun _ -> ()); let path = ref [] in let st = ref true in let spec = [ "-I", Arg.String (fun s -> path := s :: !path), "<dir> Add <dir> to the list of include directories"; "-labels", Arg.Clear Clflags.classic, " <obsolete>"; "-nolabels", Arg.Set Clflags.classic, " Ignore non-optional labels in types"; "-oldui", Arg.Clear st, " Revert back to old UI"; "-pp", Arg.String (fun s -> Clflags.preprocessor := Some s), "<command> Pipe sources through preprocessor <command>"; "-rectypes", Arg.Set Clflags.recursive_types, " Allow arbitrary recursive types"; "-version", Arg.Unit print_version, " Print version and exit"; "-w", Arg.String (fun s -> Shell.warnings := s), "<flags> Enable or disable warnings according to <flags>:\n\ \032 A/a enable/disable all warnings\n\ \032 C/c enable/disable suspicious comment\n\ \032 D/d enable/disable deprecated features\n\ \032 E/e enable/disable fragile match\n\ \032 F/f enable/disable partially applied function\n\ \032 L/l enable/disable labels omitted in application\n\ \032 M/m enable/disable overriden method\n\ \032 P/p enable/disable partial match\n\ \032 S/s enable/disable non-unit statement\n\ \032 U/u enable/disable unused match case\n\ \032 V/v enable/disable hidden instance variable\n\ \032 X/x enable/disable all other warnings\n\ \032 default setting is \"Ale\"\n\ \032 (all warnings but labels and fragile match enabled)"; ] and errmsg = "Command line: ocamlbrowser <options>" in if not (check ~spec Sys.argv) then fatal_error (usage ~spec errmsg); Arg.parse spec (fun name -> raise(Arg.Bad("don't know what to do with " ^ name))) errmsg; Config.load_path := Sys.getcwd () :: List.rev_map ~f:(Misc.expand_directory Config.standard_library) !path @ [Config.standard_library]; Warnings.parse_options false !Shell.warnings; Unix.putenv "TERM" "noterminal"; begin try Searchid.start_env := Env.open_pers_signature "Pervasives" Env.initial with _ -> fatal_error (Printf.sprintf "%s\nPlease check that %s %s\nCurrent value is `%s'" "Couldn't initialize environment." (if is_win32 then "%OCAMLLIB%" else "$OCAMLLIB") "points to the Objective Caml library." Config.standard_library) end; Searchpos.view_defined_ref := (fun s ~env -> Viewer.view_defined s ~env); Searchpos.editor_ref := Editor.f; let top = openTk ~clas:"OCamlBrowser" () in Jg_config.init (); (* bind top ~events:[`Destroy] ~action:(fun _ -> exit 0); *) at_exit Shell.kill_all; if !st then Viewer.st_viewer ~on:top () else Viewer.f ~on:top (); while true do try if is_win32 then mainLoop () else Printexc.print mainLoop () with Protocol.TkError _ -> if not is_win32 then flush stderr done
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/browser/main.ml
ocaml
*********************************************************************** Objective Caml LablTk library General Public License, with the special exception on linking described in file ../../../LICENSE. *********************************************************************** bind top ~events:[`Destroy] ~action:(fun _ -> exit 0);
, Kyoto University RIMS Copyright 1999 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library $ I d : main.ml , v 1.34 2006/04/16 23:28:21 doligez Exp $ open StdLabels module Unix = UnixLabels open Tk let fatal_error text = let top = openTk ~clas:"OCamlBrowser" () in let mw = Message.create top ~text ~padx:20 ~pady:10 ~width:400 ~justify:`Left ~aspect:400 ~anchor:`W and b = Button.create top ~text:"OK" ~command:(fun () -> destroy top) in pack [mw] ~side:`Top ~fill:`Both; pack [b] ~side:`Bottom; mainLoop (); exit 0 let rec get_incr key = function [] -> raise Not_found | (k, c, d) :: rem -> if k = key then match c with Arg.Set _ | Arg.Clear _ | Arg.Unit _ -> false | _ -> true else get_incr key rem let check ~spec argv = let i = ref 1 in while !i < Array.length argv do try let a = get_incr argv.(!i) spec in incr i; if a then incr i with Not_found -> i := Array.length argv + 1 done; !i = Array.length argv open Printf let print_version () = printf "The Objective Caml browser, version %s\n" Sys.ocaml_version; exit 0; ;; let usage ~spec errmsg = let b = Buffer.create 1024 in bprintf b "%s\n" errmsg; List.iter (function (key, _, doc) -> bprintf b " %s %s\n" key doc) spec; Buffer.contents b let _ = let is_win32 = Sys.os_type = "Win32" in if is_win32 then Format.pp_set_formatter_output_functions Format.err_formatter (fun _ _ _ -> ()) (fun _ -> ()); let path = ref [] in let st = ref true in let spec = [ "-I", Arg.String (fun s -> path := s :: !path), "<dir> Add <dir> to the list of include directories"; "-labels", Arg.Clear Clflags.classic, " <obsolete>"; "-nolabels", Arg.Set Clflags.classic, " Ignore non-optional labels in types"; "-oldui", Arg.Clear st, " Revert back to old UI"; "-pp", Arg.String (fun s -> Clflags.preprocessor := Some s), "<command> Pipe sources through preprocessor <command>"; "-rectypes", Arg.Set Clflags.recursive_types, " Allow arbitrary recursive types"; "-version", Arg.Unit print_version, " Print version and exit"; "-w", Arg.String (fun s -> Shell.warnings := s), "<flags> Enable or disable warnings according to <flags>:\n\ \032 A/a enable/disable all warnings\n\ \032 C/c enable/disable suspicious comment\n\ \032 D/d enable/disable deprecated features\n\ \032 E/e enable/disable fragile match\n\ \032 F/f enable/disable partially applied function\n\ \032 L/l enable/disable labels omitted in application\n\ \032 M/m enable/disable overriden method\n\ \032 P/p enable/disable partial match\n\ \032 S/s enable/disable non-unit statement\n\ \032 U/u enable/disable unused match case\n\ \032 V/v enable/disable hidden instance variable\n\ \032 X/x enable/disable all other warnings\n\ \032 default setting is \"Ale\"\n\ \032 (all warnings but labels and fragile match enabled)"; ] and errmsg = "Command line: ocamlbrowser <options>" in if not (check ~spec Sys.argv) then fatal_error (usage ~spec errmsg); Arg.parse spec (fun name -> raise(Arg.Bad("don't know what to do with " ^ name))) errmsg; Config.load_path := Sys.getcwd () :: List.rev_map ~f:(Misc.expand_directory Config.standard_library) !path @ [Config.standard_library]; Warnings.parse_options false !Shell.warnings; Unix.putenv "TERM" "noterminal"; begin try Searchid.start_env := Env.open_pers_signature "Pervasives" Env.initial with _ -> fatal_error (Printf.sprintf "%s\nPlease check that %s %s\nCurrent value is `%s'" "Couldn't initialize environment." (if is_win32 then "%OCAMLLIB%" else "$OCAMLLIB") "points to the Objective Caml library." Config.standard_library) end; Searchpos.view_defined_ref := (fun s ~env -> Viewer.view_defined s ~env); Searchpos.editor_ref := Editor.f; let top = openTk ~clas:"OCamlBrowser" () in Jg_config.init (); at_exit Shell.kill_all; if !st then Viewer.st_viewer ~on:top () else Viewer.f ~on:top (); while true do try if is_win32 then mainLoop () else Printexc.print mainLoop () with Protocol.TkError _ -> if not is_win32 then flush stderr done
760ea7e16f9a5fd9043e46c6c586b82327532ad7c59a343dcdc09ca89121dcd7
LaurentMazare/ocaml-arrow
table.ml
open Core_kernel open Arrow_c_api let%expect_test _ = let table = List.init 3 ~f:(fun i -> let cols = [ Wrapper.Writer.utf8 [| "v1"; "v2"; "v3" |] ~name:"foo" ; Wrapper.Writer.int [| i; 5 * i; 10 * i |] ~name:"bar" ; Wrapper.Writer.int_opt [| Some ((i * 2) + 1); None; None |] ~name:"baz" ] in Wrapper.Writer.create_table ~cols) |> Wrapper.Table.concatenate in let foo = Wrapper.Column.read_utf8 table ~column:(`Name "foo") in let bar = Wrapper.Column.read_int table ~column:(`Name "bar") in let baz = Wrapper.Column.read_int_opt table ~column:(`Name "baz") in Array.iter foo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter bar ~f:(Stdio.printf "%d "); Stdio.printf "\n"; Array.iter baz ~f:(fun v -> Option.value_map v ~f:Int.to_string ~default:"none" |> Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| v1 v2 v3 v1 v2 v3 v1 v2 v3 0 0 0 1 5 10 2 10 20 1 none none 3 none none 5 none none |}] let%expect_test _ = let table = List.init 3 ~f:(fun i -> let f = Float.of_int i in let cols = [ Table.col [| "v1"; "v2"; "v3" |] Utf8 ~name:"foo" ; Table.col [| f; 5. *. f; 0.5 *. f |] Float ~name:"bar" ; Table.col_opt [| Some ((f *. 2.) +. 0.1); None; None |] Float ~name:"baz" ] in Wrapper.Writer.create_table ~cols) |> Wrapper.Table.concatenate in let foo = Table.read table Utf8 ~column:(`Name "foo") in let bar = Table.read table Float ~column:(`Name "bar") in let baz = Table.read_opt table Float ~column:(`Name "baz") in Array.iter foo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter bar ~f:(Stdio.printf "%f "); Stdio.printf "\n"; Array.iter baz ~f:(fun v -> Option.value_map v ~f:Float.to_string ~default:"none" |> Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| v1 v2 v3 v1 v2 v3 v1 v2 v3 0.000000 0.000000 0.000000 1.000000 5.000000 0.500000 2.000000 10.000000 1.000000 0.1 none none 2.1 none none 4.1 none none |}]; let col_foo = Wrapper.Table.get_column table "foo" in let col_bar = Wrapper.Table.get_column table "bar" in let table2 = let cols = [ Table.col (Array.init 9 ~f:(Printf.sprintf "w%d")) Utf8 ~name:"woo" ] in Wrapper.Writer.create_table ~cols in let table3 = Table.add_column table2 "foo2" col_foo in let table3 = Table.add_column table3 "foo3" col_foo in let table3 = Table.add_column table3 "barbar" col_bar in let foo3 = Table.read table3 Utf8 ~column:(`Name "foo3") in let woo = Table.read table3 Utf8 ~column:(`Name "woo") in Array.iter woo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter foo3 ~f:(Stdio.printf "%s "); Stdio.printf "\n"; let table = Table.add_all_columns table table3 in let foo3 = Table.read table Utf8 ~column:(`Name "foo3") in let woo = Table.read table Utf8 ~column:(`Name "woo") in Array.iter woo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter foo3 ~f:(Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| w0 w1 w2 w3 w4 w5 w6 w7 w8 v1 v2 v3 v1 v2 v3 v1 v2 v3 w0 w1 w2 w3 w4 w5 w6 w7 w8 v1 v2 v3 v1 v2 v3 v1 v2 v3 |}]
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-arrow/f7adb7593974fd955ad82b8324d5626c6dded8ce/tests/table.ml
ocaml
open Core_kernel open Arrow_c_api let%expect_test _ = let table = List.init 3 ~f:(fun i -> let cols = [ Wrapper.Writer.utf8 [| "v1"; "v2"; "v3" |] ~name:"foo" ; Wrapper.Writer.int [| i; 5 * i; 10 * i |] ~name:"bar" ; Wrapper.Writer.int_opt [| Some ((i * 2) + 1); None; None |] ~name:"baz" ] in Wrapper.Writer.create_table ~cols) |> Wrapper.Table.concatenate in let foo = Wrapper.Column.read_utf8 table ~column:(`Name "foo") in let bar = Wrapper.Column.read_int table ~column:(`Name "bar") in let baz = Wrapper.Column.read_int_opt table ~column:(`Name "baz") in Array.iter foo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter bar ~f:(Stdio.printf "%d "); Stdio.printf "\n"; Array.iter baz ~f:(fun v -> Option.value_map v ~f:Int.to_string ~default:"none" |> Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| v1 v2 v3 v1 v2 v3 v1 v2 v3 0 0 0 1 5 10 2 10 20 1 none none 3 none none 5 none none |}] let%expect_test _ = let table = List.init 3 ~f:(fun i -> let f = Float.of_int i in let cols = [ Table.col [| "v1"; "v2"; "v3" |] Utf8 ~name:"foo" ; Table.col [| f; 5. *. f; 0.5 *. f |] Float ~name:"bar" ; Table.col_opt [| Some ((f *. 2.) +. 0.1); None; None |] Float ~name:"baz" ] in Wrapper.Writer.create_table ~cols) |> Wrapper.Table.concatenate in let foo = Table.read table Utf8 ~column:(`Name "foo") in let bar = Table.read table Float ~column:(`Name "bar") in let baz = Table.read_opt table Float ~column:(`Name "baz") in Array.iter foo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter bar ~f:(Stdio.printf "%f "); Stdio.printf "\n"; Array.iter baz ~f:(fun v -> Option.value_map v ~f:Float.to_string ~default:"none" |> Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| v1 v2 v3 v1 v2 v3 v1 v2 v3 0.000000 0.000000 0.000000 1.000000 5.000000 0.500000 2.000000 10.000000 1.000000 0.1 none none 2.1 none none 4.1 none none |}]; let col_foo = Wrapper.Table.get_column table "foo" in let col_bar = Wrapper.Table.get_column table "bar" in let table2 = let cols = [ Table.col (Array.init 9 ~f:(Printf.sprintf "w%d")) Utf8 ~name:"woo" ] in Wrapper.Writer.create_table ~cols in let table3 = Table.add_column table2 "foo2" col_foo in let table3 = Table.add_column table3 "foo3" col_foo in let table3 = Table.add_column table3 "barbar" col_bar in let foo3 = Table.read table3 Utf8 ~column:(`Name "foo3") in let woo = Table.read table3 Utf8 ~column:(`Name "woo") in Array.iter woo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter foo3 ~f:(Stdio.printf "%s "); Stdio.printf "\n"; let table = Table.add_all_columns table table3 in let foo3 = Table.read table Utf8 ~column:(`Name "foo3") in let woo = Table.read table Utf8 ~column:(`Name "woo") in Array.iter woo ~f:(Stdio.printf "%s "); Stdio.printf "\n"; Array.iter foo3 ~f:(Stdio.printf "%s "); Stdio.printf "\n"; [%expect {| w0 w1 w2 w3 w4 w5 w6 w7 w8 v1 v2 v3 v1 v2 v3 v1 v2 v3 w0 w1 w2 w3 w4 w5 w6 w7 w8 v1 v2 v3 v1 v2 v3 v1 v2 v3 |}]
25fbf2573fa2935e036829357b93d50f0356f29e0c4d753b893556d92c15a6e8
tjammer/olox
ast.ml
type unop = Not | Neg [@@deriving show] type binop = | Less | Less_equal | Greater | Greater_equal | Equal_equal | Plus | Minus | Star | Slash [@@deriving show] type logicop = And | Or [@@deriving show] type callable = { callable : string; call : value list -> value } and method' = value option -> callable and class' = { cl_name : string; methods : (string * method') list; super : class' option; } and value = | Number of float | String of string | Identifier of string | Bool of bool | Nil | Fun of callable | Method of method' | Class of (class'[@printer fun fmt c -> Format.fprintf fmt "\"%s\"" c.cl_name]) | Instance of ((string * value Environment.t ref * class') [@printer fun fmt (s, _, _) -> Format.fprintf fmt "\"%s\"" s]) (* We make the env opaque to since we don't really care about the content *) (* The env is a reference to make it easier to set values *) | This | Super of string [@@deriving show { with_path = false }] and primary = Value of value | Grouping of expr and expr = | Primary of primary | Unary of { op : unop; expr : expr } | Binary of { left : expr; op : binop; right : expr } | Assign of expr * expr | Logical of logicop * expr * expr | Call of expr * expr list | Class_get of expr * string and statement = | Expr of expr | Print of expr | Block of decl list | If of expr * statement * statement option | While of expr * statement | Return of expr option and decl = | Var_decl of string * expr option | Stmt of statement | Fun_decl of func | Class_decl of string * func list * string option and func = { name : string; parameters : string list; body : statement } let parenthesize str = "(" ^ String.concat " " str ^ ")" let rec show_expr = function | Primary (Value lit) -> show_value lit | Primary (Grouping expr) -> parenthesize [ "group"; show_expr expr ] | Unary { op; expr } -> parenthesize [ show_unop op; show_expr expr ] | Binary { left; op; right } -> parenthesize [ show_binop op; show_expr left; show_expr right ] | Assign (id, expr) -> parenthesize [ "assign"; show_expr id; show_expr expr ] | Logical (op, left, right) -> parenthesize [ show_logicop op; show_expr left; show_expr right ] | Call (func, parameters) -> parenthesize [ show_expr func; List.map show_expr parameters |> String.concat ", " ] | Class_get (expr, field) -> parenthesize [ "get"; show_expr expr; field ] exception Error let make_lvalue = function | Primary (Value (Identifier id)) -> id | Class_get (instance, field) -> Printf.printf "%s, %s\n%!" (show_expr instance) field; "nil" | _ -> raise Error
null
https://raw.githubusercontent.com/tjammer/olox/f8febbbec5ecd1a7bd4955b0cd51da02a705e72f/lib/ast.ml
ocaml
We make the env opaque to since we don't really care about the content The env is a reference to make it easier to set values
type unop = Not | Neg [@@deriving show] type binop = | Less | Less_equal | Greater | Greater_equal | Equal_equal | Plus | Minus | Star | Slash [@@deriving show] type logicop = And | Or [@@deriving show] type callable = { callable : string; call : value list -> value } and method' = value option -> callable and class' = { cl_name : string; methods : (string * method') list; super : class' option; } and value = | Number of float | String of string | Identifier of string | Bool of bool | Nil | Fun of callable | Method of method' | Class of (class'[@printer fun fmt c -> Format.fprintf fmt "\"%s\"" c.cl_name]) | Instance of ((string * value Environment.t ref * class') [@printer fun fmt (s, _, _) -> Format.fprintf fmt "\"%s\"" s]) | This | Super of string [@@deriving show { with_path = false }] and primary = Value of value | Grouping of expr and expr = | Primary of primary | Unary of { op : unop; expr : expr } | Binary of { left : expr; op : binop; right : expr } | Assign of expr * expr | Logical of logicop * expr * expr | Call of expr * expr list | Class_get of expr * string and statement = | Expr of expr | Print of expr | Block of decl list | If of expr * statement * statement option | While of expr * statement | Return of expr option and decl = | Var_decl of string * expr option | Stmt of statement | Fun_decl of func | Class_decl of string * func list * string option and func = { name : string; parameters : string list; body : statement } let parenthesize str = "(" ^ String.concat " " str ^ ")" let rec show_expr = function | Primary (Value lit) -> show_value lit | Primary (Grouping expr) -> parenthesize [ "group"; show_expr expr ] | Unary { op; expr } -> parenthesize [ show_unop op; show_expr expr ] | Binary { left; op; right } -> parenthesize [ show_binop op; show_expr left; show_expr right ] | Assign (id, expr) -> parenthesize [ "assign"; show_expr id; show_expr expr ] | Logical (op, left, right) -> parenthesize [ show_logicop op; show_expr left; show_expr right ] | Call (func, parameters) -> parenthesize [ show_expr func; List.map show_expr parameters |> String.concat ", " ] | Class_get (expr, field) -> parenthesize [ "get"; show_expr expr; field ] exception Error let make_lvalue = function | Primary (Value (Identifier id)) -> id | Class_get (instance, field) -> Printf.printf "%s, %s\n%!" (show_expr instance) field; "nil" | _ -> raise Error
af28903338ee8760b967b2efe077e8d643880a3a1cff1446ffc45c99f1d95497
effectai/effect-network
swap.cljs
(ns e2e.swap (:require [eos-cljs.core :as eos] e2e.token [e2e.util :as util] ["@cityofzion/neon-js" :refer [rpc tx] :as Neon] [clojure.string :as string] (clojure.pprint :refer [pprint]) [cljs.test :refer-macros [deftest is testing run-tests async use-fixtures]] )) (def swap-acc (eos/random-account "efx")) (def token-acc e2e.token/account) (def owner-acc e2e.token/owner-acc) (def bk-acc (eos/random-account "jbk")) ;; define a new token for the swap test (def sym "SWP") (def total-amount "650000000.0000") (def total-supply (str total-amount " " sym)) (def tx1-raw "d10153081027000000000000141b00234a5dcafb17ae645c203617f709450e8c5b141b00234a5dcafb17ae645c203617f709450e8c5b53c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcac000000000000000003201b00234a5dcafb17ae645c203617f709450e8c5bf0096c617572656e732e78f00d31353533353036343939313139000001414088b6a244963ae20183dba549b38affc4255c0f20d5ffccf94f00ad9e1ba0063f33ef9a0be05799e7c3a7f191e6d7e57b896179f49f4246af3f03d0d99368c43c2321023c626ad1b80d7d7bf4620fe15ff43eea073a1ccb707d786942a68546a89fee7eac") (def tx2-raw "d1015c08307c97389c000000149bd53e0aa2df30567ef559a8c61520010ea6cc46145ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb953c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcacf1660682ba9ce83307000000000000000001205ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb90000014140ebfadb9335a01a0753d046954e2bfee843565d98b5aee080be7f6e57216307af73114d6b2bf84dc271a895e1095df908855325300d9d3899ff974683dda89f842321035b5d8d4824b495e5a9c0bb0523c8c72cc6cb826d8cb8edaf0da68cd2f044ee65ac") (def tx3-raw "d1015c08600badec31050000142fb9bf175c31d76d6e1fdbf7cb39c39795a58ff9145ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb953c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcacf16606426384930657000000000000000001205ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb90000") (def tx1 (.deserialize Neon/tx.Transaction tx1-raw)) (def tx2 (.deserialize Neon/tx.Transaction tx2-raw)) (def tx3 (.deserialize Neon/tx.Transaction tx3-raw)) (def tx-hash (.reverseHex Neon/u (.-hash tx1))) (def tx-parsed (util/parse-nep5 tx1)) (use-fixtures :once {:before (fn [] (async done (-> (eos/create-account owner-acc swap-acc) (.then #(eos/create-account owner-acc bk-acc)) (.then #(println (str "> Created SWAP account " swap-acc))) (.then #(eos/deploy swap-acc "contracts/swap/swap")) (.catch prn) (.then #(eos/update-auth swap-acc "active" [{:permission {:actor swap-acc :permission "eosio.code"} :weight 1} {:permission {:actor owner-acc :permission "active"} :weight 1}])) (.then #(eos/transact token-acc "create" {:issuer swap-acc :maximum_supply total-supply})) (.catch prn) (.then done)))) :after (fn [])}) (defn do-posttx "Helper for the posttx action" ([] (do-posttx bk-acc)) ([bk-acc] (do-posttx bk-acc [{:actor bk-acc :permission "active"}])) ([bk-acc permission] (eos/transact [{:account swap-acc :name "posttx" :authorization permission :data {:bookkeeper bk-acc :rawtx (.serialize tx1 false) :asset_hash (:script-hash tx-parsed) :value (:value tx-parsed) :to owner-acc}}]))) (def init-config {:token_contract token-acc :token_symbol sym :tx_max_age 100000000 :min_tx_value 1 :max_tx_value "10000000000" :global_swap_limit 100000 :limit_reset_time_sec 3}) (def update-config (select-keys init-config [:tx_max_age :min_tx_value :max_tx_value :global_swap_limit :limit_reset_time_sec])) (deftest update-bofore-init (async done (-> ;; needs swap account authority (eos/transact swap-acc "update" update-config [{:actor bk-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "only swap account can update") ;; cant update before init (.then #(eos/transact swap-acc "update" update-config)) (util/should-fail-with "not initialized" "cant call update before init") (.then done)))) (deftest initialize (async done (-> ;; cant issue before init (eos/transact swap-acc "issue" {:txid tx-hash} [{:actor bk-acc :permission "active"}]) (util/should-fail-with "not initialized" "cant call issue before without init") ;; needs swap account authority (.then #(eos/transact swap-acc "init" init-config [{:actor bk-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " swap-acc) "only swap account can init") ;; cant init with invalid name (.then #(eos/transact swap-acc "init" (assoc init-config :token_contract "noaccount"))) (util/should-fail-with "token contract does not exsist") ;; can set config (.then #(eos/transact swap-acc "init" init-config)) (util/should-succeed "can perform init") (.then #(eos/get-table-rows swap-acc swap-acc "config")) (.then #(is (= (vals (first %)) (vals init-config)) "config incorrect")) eos/wait-block ;; cant set config twice (.then #(eos/transact swap-acc "init" init-config)) (util/should-fail-with "already initialized" "can only initialize once") (.then done)))) (deftest update-after-init (async done (let [new-update-config (update-in update-config [:tx_max_age] inc) new-config (update-in init-config [:tx_max_age] inc)] (-> ;; can perform update (eos/transact swap-acc "update" new-update-config) (util/should-succeed "can perform update") (.then #(eos/get-table-rows swap-acc swap-acc "config")) ;; compare (.then #(do (is (not (= (vals (first %)) (vals init-config))) "config incorrect") (is (= (vals (first %)) (vals new-config)) "config incorrect") )) (.then done))))) (deftest bookkeeper-add (async done (.then (.all js/Promise #js [(-> ;; can add bookkeeper (eos/transact swap-acc "mkbookkeeper" {:account bk-acc} [{:actor swap-acc :permission "owner"}]) eos/wait-block (.then #(eos/get-table-rows swap-acc swap-acc "bookkeeper")) (.then #(is (> (count %) 0) "there is 1 bookkeeper"))) (-> ;; needs contract permission (eos/transact swap-acc "mkbookkeeper" {:account owner-acc} [{:actor token-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "adding a bookkeeper requires owner permission")) (-> ;; cant add same bookkeeper twice (eos/transact swap-acc "mkbookkeeper" {:account token-acc} [{:actor swap-acc :permission "owner"}]) eos/wait-block (.then #(eos/transact swap-acc "mkbookkeeper" {:account token-acc} [{:actor swap-acc :permission "owner"}])) (util/should-fail-with "assertion failure with message: already registered" "cant add existing bookkeeper"))]) done))) (deftest bookkeeper-remove (async done (.then (.all js/Promise #js [(-> ;; can remove bookkeeper (eos/transact swap-acc "rmbookkeeper" {:account token-acc} [{:actor swap-acc :permission "active"}]) eos/wait-block (.then #(eos/get-table-rows swap-acc swap-acc "bookkeeper")) (.then #(is (= (count %) 1) "bookkeeper is removed"))) (-> ;; needs contact permission (eos/transact swap-acc "rmbookkeeper" {:account owner-acc} [{:actor token-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "removing a bookkeeper requires owner permission")) (-> ;; cant remove non-existing bookkeeper (eos/transact swap-acc "rmbookkeeper" {:account "acc4"} [{:actor swap-acc :permission "active"}]) (util/should-fail-with "registered" "cant remove non exisinting bookkeeper"))]) done))) (deftest posttx (async done (-> create tx (do-posttx) (.then (fn [tx] (let [console-out (eos/tx-get-console tx)] (is (string/starts-with? console-out "inserted")) console-out))) (.then #(let [id (re-find #"\d+" %)] (is (= (int? id))) (eos/get-table-row swap-acc swap-acc "nep5" id))) (.then (fn [row] (testing "nep5 tx is correct" (is (= (get row "txid") tx-hash)) (is (= (get row "value") (:value tx-parsed)))))) ca nt create same tx twice eos/wait-block (.then #(do-posttx)) (util/should-fail-with "tx already posted") ;; requires bookkeeper and signature (.then #(do-posttx owner-acc)) (util/should-fail-with "not a bookkeeper" "require registered bookkeeper") (.then #(do-posttx bk-acc [{:actor owner-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " bk-acc) "require bookkeeper signature") (.then done)))) (defn do-posttx-n ([t] (do-posttx-n t (:value tx-parsed))) ([t v] (eos/transact swap-acc "posttx" {:bookkeeper bk-acc :rawtx (.serialize t false) :asset_hash (:script-hash tx-parsed) :value v :to owner-acc} [{:actor bk-acc :permission "active"}]))) (deftest cleartx (async done (-> ;; tx must exist (eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor swap-acc :permission "owner"}]) (util/should-fail-with "tx does not exist") (.then #(do-posttx-n tx2)) ;; requires contract auth (.then #(eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor bk-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " swap-acc)) ;; success (.then #(eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor swap-acc :permission "owner"}])) (util/should-succeed "can clear tx") (.then done)))) (deftest swap-limits (async done (-> (eos/get-table-rows swap-acc swap-acc "global") (.then (fn [[{swap-total "swap_total" last-reset "last_limit_resert"}]] (is (= swap-total (* 2 (:value tx-parsed))) "correct swap total") ;; post a new tx and see that it updates (-> (do-posttx-n tx2) (.then #(eos/get-table-rows swap-acc swap-acc "global")) (.then #(is (= (get-in % [0 "swap_total"]) (+ swap-total (:value tx-parsed))) "swap total do update")) (.then #(do-posttx-n tx3 (dec (:global_swap_limit init-config)))) (util/should-fail-with "global swap limit reached") ;; wait until limit reset (eos/wait-block (* 2 (:limit_reset_time_sec init-config))) ;; can post txs again (.then #(do-posttx-n tx3 (:global_swap_limit init-config))) util/should-succeed ;; limits should have updated (.then #(eos/get-table-rows swap-acc swap-acc "global")) (.then #(do (is (= (get-in % [0 "swap_total"]) (:global_swap_limit init-config)) "swap total updated") (is (not (= (get-in % [0 "last_limit_reset"]) last-reset "limit reset time is updated")))))))) (.then done)))) (deftest issue-success (async done (-> (eos/transact swap-acc "issue" {:txid tx-hash}) ( .then # ( do ( prn ( eos / tx - get - console % ) ) % ) ) (.then (fn [res] (testing "swap transaction exists" (is (not (nil? res)))) (let [inner-act (aget res "processed" "action_traces" 0 "inline_traces" 0 "inline_traces" 0 "inline_traces" 0)] (testing "issue result is correct" (is (= (aget inner-act "receipt" "receiver") swap-acc)) (is (= (aget inner-act "act" "name") "transfer")) (is (= (aget inner-act "act" "data" "to") owner-acc)) (is (= (aget inner-act "act" "data" "from") swap-acc)) (is (= (aget inner-act "act" "data" "quantity") (str "1.0000 " sym))))))) (.catch #(is (= (.-message %) "failed processing transaction"))) eos/wait-block (.then done)))) (deftest issue-fail (async done (-> (eos/transact swap-acc "issue" {:txid (.reverseHex Neon/u (.-hash tx1))}) (.then #(testing "transaction not made" (is (nil? %)))) (util/should-fail-with "tx already issued" "cant issue tokens twice") (.then done)))) (defn -main [] (run-tests))
null
https://raw.githubusercontent.com/effectai/effect-network/17af92f491458fee8f1e0a3eb602f7be3d6384c4/tests/e2e/swap.cljs
clojure
define a new token for the swap test needs swap account authority cant update before init cant issue before init needs swap account authority cant init with invalid name can set config cant set config twice can perform update compare can add bookkeeper needs contract permission cant add same bookkeeper twice can remove bookkeeper needs contact permission cant remove non-existing bookkeeper requires bookkeeper and signature tx must exist requires contract auth success post a new tx and see that it updates wait until limit reset can post txs again limits should have updated
(ns e2e.swap (:require [eos-cljs.core :as eos] e2e.token [e2e.util :as util] ["@cityofzion/neon-js" :refer [rpc tx] :as Neon] [clojure.string :as string] (clojure.pprint :refer [pprint]) [cljs.test :refer-macros [deftest is testing run-tests async use-fixtures]] )) (def swap-acc (eos/random-account "efx")) (def token-acc e2e.token/account) (def owner-acc e2e.token/owner-acc) (def bk-acc (eos/random-account "jbk")) (def sym "SWP") (def total-amount "650000000.0000") (def total-supply (str total-amount " " sym)) (def tx1-raw "d10153081027000000000000141b00234a5dcafb17ae645c203617f709450e8c5b141b00234a5dcafb17ae645c203617f709450e8c5b53c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcac000000000000000003201b00234a5dcafb17ae645c203617f709450e8c5bf0096c617572656e732e78f00d31353533353036343939313139000001414088b6a244963ae20183dba549b38affc4255c0f20d5ffccf94f00ad9e1ba0063f33ef9a0be05799e7c3a7f191e6d7e57b896179f49f4246af3f03d0d99368c43c2321023c626ad1b80d7d7bf4620fe15ff43eea073a1ccb707d786942a68546a89fee7eac") (def tx2-raw "d1015c08307c97389c000000149bd53e0aa2df30567ef559a8c61520010ea6cc46145ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb953c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcacf1660682ba9ce83307000000000000000001205ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb90000014140ebfadb9335a01a0753d046954e2bfee843565d98b5aee080be7f6e57216307af73114d6b2bf84dc271a895e1095df908855325300d9d3899ff974683dda89f842321035b5d8d4824b495e5a9c0bb0523c8c72cc6cb826d8cb8edaf0da68cd2f044ee65ac") (def tx3-raw "d1015c08600badec31050000142fb9bf175c31d76d6e1fdbf7cb39c39795a58ff9145ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb953c1087472616e7366657267f9e6e770af783d809bd1a65e1bb5b6042953bcacf16606426384930657000000000000000001205ad9ffcd1e2a0e4d8388e00a1dc028203f7b2bb90000") (def tx1 (.deserialize Neon/tx.Transaction tx1-raw)) (def tx2 (.deserialize Neon/tx.Transaction tx2-raw)) (def tx3 (.deserialize Neon/tx.Transaction tx3-raw)) (def tx-hash (.reverseHex Neon/u (.-hash tx1))) (def tx-parsed (util/parse-nep5 tx1)) (use-fixtures :once {:before (fn [] (async done (-> (eos/create-account owner-acc swap-acc) (.then #(eos/create-account owner-acc bk-acc)) (.then #(println (str "> Created SWAP account " swap-acc))) (.then #(eos/deploy swap-acc "contracts/swap/swap")) (.catch prn) (.then #(eos/update-auth swap-acc "active" [{:permission {:actor swap-acc :permission "eosio.code"} :weight 1} {:permission {:actor owner-acc :permission "active"} :weight 1}])) (.then #(eos/transact token-acc "create" {:issuer swap-acc :maximum_supply total-supply})) (.catch prn) (.then done)))) :after (fn [])}) (defn do-posttx "Helper for the posttx action" ([] (do-posttx bk-acc)) ([bk-acc] (do-posttx bk-acc [{:actor bk-acc :permission "active"}])) ([bk-acc permission] (eos/transact [{:account swap-acc :name "posttx" :authorization permission :data {:bookkeeper bk-acc :rawtx (.serialize tx1 false) :asset_hash (:script-hash tx-parsed) :value (:value tx-parsed) :to owner-acc}}]))) (def init-config {:token_contract token-acc :token_symbol sym :tx_max_age 100000000 :min_tx_value 1 :max_tx_value "10000000000" :global_swap_limit 100000 :limit_reset_time_sec 3}) (def update-config (select-keys init-config [:tx_max_age :min_tx_value :max_tx_value :global_swap_limit :limit_reset_time_sec])) (deftest update-bofore-init (async done (-> (eos/transact swap-acc "update" update-config [{:actor bk-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "only swap account can update") (.then #(eos/transact swap-acc "update" update-config)) (util/should-fail-with "not initialized" "cant call update before init") (.then done)))) (deftest initialize (async done (-> (eos/transact swap-acc "issue" {:txid tx-hash} [{:actor bk-acc :permission "active"}]) (util/should-fail-with "not initialized" "cant call issue before without init") (.then #(eos/transact swap-acc "init" init-config [{:actor bk-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " swap-acc) "only swap account can init") (.then #(eos/transact swap-acc "init" (assoc init-config :token_contract "noaccount"))) (util/should-fail-with "token contract does not exsist") (.then #(eos/transact swap-acc "init" init-config)) (util/should-succeed "can perform init") (.then #(eos/get-table-rows swap-acc swap-acc "config")) (.then #(is (= (vals (first %)) (vals init-config)) "config incorrect")) eos/wait-block (.then #(eos/transact swap-acc "init" init-config)) (util/should-fail-with "already initialized" "can only initialize once") (.then done)))) (deftest update-after-init (async done (let [new-update-config (update-in update-config [:tx_max_age] inc) new-config (update-in init-config [:tx_max_age] inc)] (-> (eos/transact swap-acc "update" new-update-config) (util/should-succeed "can perform update") (.then #(eos/get-table-rows swap-acc swap-acc "config")) (.then #(do (is (not (= (vals (first %)) (vals init-config))) "config incorrect") (is (= (vals (first %)) (vals new-config)) "config incorrect") )) (.then done))))) (deftest bookkeeper-add (async done (.then (.all js/Promise #js [(-> (eos/transact swap-acc "mkbookkeeper" {:account bk-acc} [{:actor swap-acc :permission "owner"}]) eos/wait-block (.then #(eos/get-table-rows swap-acc swap-acc "bookkeeper")) (.then #(is (> (count %) 0) "there is 1 bookkeeper"))) (-> (eos/transact swap-acc "mkbookkeeper" {:account owner-acc} [{:actor token-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "adding a bookkeeper requires owner permission")) (-> (eos/transact swap-acc "mkbookkeeper" {:account token-acc} [{:actor swap-acc :permission "owner"}]) eos/wait-block (.then #(eos/transact swap-acc "mkbookkeeper" {:account token-acc} [{:actor swap-acc :permission "owner"}])) (util/should-fail-with "assertion failure with message: already registered" "cant add existing bookkeeper"))]) done))) (deftest bookkeeper-remove (async done (.then (.all js/Promise #js [(-> (eos/transact swap-acc "rmbookkeeper" {:account token-acc} [{:actor swap-acc :permission "active"}]) eos/wait-block (.then #(eos/get-table-rows swap-acc swap-acc "bookkeeper")) (.then #(is (= (count %) 1) "bookkeeper is removed"))) (-> (eos/transact swap-acc "rmbookkeeper" {:account owner-acc} [{:actor token-acc :permission "active"}]) (util/should-fail-with (str "missing authority of " swap-acc) "removing a bookkeeper requires owner permission")) (-> (eos/transact swap-acc "rmbookkeeper" {:account "acc4"} [{:actor swap-acc :permission "active"}]) (util/should-fail-with "registered" "cant remove non exisinting bookkeeper"))]) done))) (deftest posttx (async done (-> create tx (do-posttx) (.then (fn [tx] (let [console-out (eos/tx-get-console tx)] (is (string/starts-with? console-out "inserted")) console-out))) (.then #(let [id (re-find #"\d+" %)] (is (= (int? id))) (eos/get-table-row swap-acc swap-acc "nep5" id))) (.then (fn [row] (testing "nep5 tx is correct" (is (= (get row "txid") tx-hash)) (is (= (get row "value") (:value tx-parsed)))))) ca nt create same tx twice eos/wait-block (.then #(do-posttx)) (util/should-fail-with "tx already posted") (.then #(do-posttx owner-acc)) (util/should-fail-with "not a bookkeeper" "require registered bookkeeper") (.then #(do-posttx bk-acc [{:actor owner-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " bk-acc) "require bookkeeper signature") (.then done)))) (defn do-posttx-n ([t] (do-posttx-n t (:value tx-parsed))) ([t v] (eos/transact swap-acc "posttx" {:bookkeeper bk-acc :rawtx (.serialize t false) :asset_hash (:script-hash tx-parsed) :value v :to owner-acc} [{:actor bk-acc :permission "active"}]))) (deftest cleartx (async done (-> (eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor swap-acc :permission "owner"}]) (util/should-fail-with "tx does not exist") (.then #(do-posttx-n tx2)) (.then #(eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor bk-acc :permission "active"}])) (util/should-fail-with (str "missing authority of " swap-acc)) (.then #(eos/transact swap-acc "cleartx" {:txid (.reverseHex Neon/u (.-hash tx2))} [{:actor swap-acc :permission "owner"}])) (util/should-succeed "can clear tx") (.then done)))) (deftest swap-limits (async done (-> (eos/get-table-rows swap-acc swap-acc "global") (.then (fn [[{swap-total "swap_total" last-reset "last_limit_resert"}]] (is (= swap-total (* 2 (:value tx-parsed))) "correct swap total") (-> (do-posttx-n tx2) (.then #(eos/get-table-rows swap-acc swap-acc "global")) (.then #(is (= (get-in % [0 "swap_total"]) (+ swap-total (:value tx-parsed))) "swap total do update")) (.then #(do-posttx-n tx3 (dec (:global_swap_limit init-config)))) (util/should-fail-with "global swap limit reached") (eos/wait-block (* 2 (:limit_reset_time_sec init-config))) (.then #(do-posttx-n tx3 (:global_swap_limit init-config))) util/should-succeed (.then #(eos/get-table-rows swap-acc swap-acc "global")) (.then #(do (is (= (get-in % [0 "swap_total"]) (:global_swap_limit init-config)) "swap total updated") (is (not (= (get-in % [0 "last_limit_reset"]) last-reset "limit reset time is updated")))))))) (.then done)))) (deftest issue-success (async done (-> (eos/transact swap-acc "issue" {:txid tx-hash}) ( .then # ( do ( prn ( eos / tx - get - console % ) ) % ) ) (.then (fn [res] (testing "swap transaction exists" (is (not (nil? res)))) (let [inner-act (aget res "processed" "action_traces" 0 "inline_traces" 0 "inline_traces" 0 "inline_traces" 0)] (testing "issue result is correct" (is (= (aget inner-act "receipt" "receiver") swap-acc)) (is (= (aget inner-act "act" "name") "transfer")) (is (= (aget inner-act "act" "data" "to") owner-acc)) (is (= (aget inner-act "act" "data" "from") swap-acc)) (is (= (aget inner-act "act" "data" "quantity") (str "1.0000 " sym))))))) (.catch #(is (= (.-message %) "failed processing transaction"))) eos/wait-block (.then done)))) (deftest issue-fail (async done (-> (eos/transact swap-acc "issue" {:txid (.reverseHex Neon/u (.-hash tx1))}) (.then #(testing "transaction not made" (is (nil? %)))) (util/should-fail-with "tx already issued" "cant issue tokens twice") (.then done)))) (defn -main [] (run-tests))
18a3a539c061c708c2dbbfb43bb995c078e1bb6503e2faa5af630519e03f6fd8
2600hz/kazoo
kzd_task.erl
%%%----------------------------------------------------------------------------- ( C ) 2016 - 2020 , 2600Hz @doc Task document @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kzd_task). -export([fetch/2]). -export([account_id/1 ,action/1 ,auth_account_id/1 ,category/1 ,end_timestamp/1 ,failure_count/1 ,file_name/1 ,id/1 ,node/1 ,start_timestamp/1 ,status/1 ,success_count/1 ,total_count/1 ,type/0 ]). -include("kz_documents.hrl"). -include_lib("kazoo_tasks/include/tasks.hrl"). -include_lib("kazoo_tasks/include/task_fields.hrl"). -type doc() :: kz_json:object(). %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec fetch(kz_term:ne_binary(), kz_tasks:id()) -> {ok, kz_json:object()} | {error, any()}. fetch(Account, TaskId) -> View = ?KZ_TASKS_BY_ACCOUNT, ViewOptions = [{'key', [kzs_util:format_account_id(Account), TaskId]}], case kz_datamgr:get_single_result(?KZ_TASKS_DB, View, ViewOptions) of {'error', _}=E -> E; {'ok', JObj} -> kz_json:get_value(<<"value">>, JObj) end. %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec id(doc()) -> kz_term:ne_binary(). id(JObj) -> kz_doc:id(JObj). %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec type() -> kz_term:ne_binary(). type() -> <<"task">>. -spec node(doc()) -> kz_term:ne_binary() | 'undefined'. node(Doc) -> kz_json:get_ne_binary_value(?PVT_WORKER_NODE, Doc). -spec account_id(doc()) -> kz_term:ne_binary(). account_id(Doc) -> kz_json:get_ne_binary_value(?PVT_ACCOUNT_ID, Doc). -spec auth_account_id(doc()) -> kz_term:ne_binary(). auth_account_id(Doc) -> kz_json:get_ne_binary_value(?PVT_AUTH_ACCOUNT_ID, Doc). -spec category(doc()) -> kz_term:ne_binary(). category(Doc) -> kz_json:get_ne_binary_value(?PVT_CATEGORY, Doc). -spec action(doc()) -> kz_term:ne_binary(). action(Doc) -> kz_json:get_ne_binary_value(?PVT_ACTION, Doc). -spec status(doc()) -> kz_term:ne_binary(). status(Doc) -> kz_json:get_ne_binary_value(?PVT_STATUS, Doc). -spec file_name(doc()) -> kz_term:ne_binary(). file_name(Doc) -> kz_json:get_ne_binary_value(?PVT_FILENAME, Doc). -spec start_timestamp(doc()) -> kz_time:api_seconds(). start_timestamp(Doc) -> kz_json:get_integer_value(?PVT_STARTED_AT, Doc). -spec end_timestamp(doc()) -> kz_time:api_seconds(). end_timestamp(Doc) -> kz_json:get_integer_value(?PVT_FINISHED_AT, Doc). -spec total_count(doc()) -> kz_term:api_pos_integer(). total_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS, Doc). -spec failure_count(doc()) -> kz_term:api_non_neg_integer(). failure_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS_FAILED, Doc). -spec success_count(doc()) -> kz_term:api_non_neg_integer(). success_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS_SUCCEEDED, Doc).
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_task.erl
erlang
----------------------------------------------------------------------------- @end ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------
( C ) 2016 - 2020 , 2600Hz @doc Task document @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(kzd_task). -export([fetch/2]). -export([account_id/1 ,action/1 ,auth_account_id/1 ,category/1 ,end_timestamp/1 ,failure_count/1 ,file_name/1 ,id/1 ,node/1 ,start_timestamp/1 ,status/1 ,success_count/1 ,total_count/1 ,type/0 ]). -include("kz_documents.hrl"). -include_lib("kazoo_tasks/include/tasks.hrl"). -include_lib("kazoo_tasks/include/task_fields.hrl"). -type doc() :: kz_json:object(). -spec fetch(kz_term:ne_binary(), kz_tasks:id()) -> {ok, kz_json:object()} | {error, any()}. fetch(Account, TaskId) -> View = ?KZ_TASKS_BY_ACCOUNT, ViewOptions = [{'key', [kzs_util:format_account_id(Account), TaskId]}], case kz_datamgr:get_single_result(?KZ_TASKS_DB, View, ViewOptions) of {'error', _}=E -> E; {'ok', JObj} -> kz_json:get_value(<<"value">>, JObj) end. -spec id(doc()) -> kz_term:ne_binary(). id(JObj) -> kz_doc:id(JObj). -spec type() -> kz_term:ne_binary(). type() -> <<"task">>. -spec node(doc()) -> kz_term:ne_binary() | 'undefined'. node(Doc) -> kz_json:get_ne_binary_value(?PVT_WORKER_NODE, Doc). -spec account_id(doc()) -> kz_term:ne_binary(). account_id(Doc) -> kz_json:get_ne_binary_value(?PVT_ACCOUNT_ID, Doc). -spec auth_account_id(doc()) -> kz_term:ne_binary(). auth_account_id(Doc) -> kz_json:get_ne_binary_value(?PVT_AUTH_ACCOUNT_ID, Doc). -spec category(doc()) -> kz_term:ne_binary(). category(Doc) -> kz_json:get_ne_binary_value(?PVT_CATEGORY, Doc). -spec action(doc()) -> kz_term:ne_binary(). action(Doc) -> kz_json:get_ne_binary_value(?PVT_ACTION, Doc). -spec status(doc()) -> kz_term:ne_binary(). status(Doc) -> kz_json:get_ne_binary_value(?PVT_STATUS, Doc). -spec file_name(doc()) -> kz_term:ne_binary(). file_name(Doc) -> kz_json:get_ne_binary_value(?PVT_FILENAME, Doc). -spec start_timestamp(doc()) -> kz_time:api_seconds(). start_timestamp(Doc) -> kz_json:get_integer_value(?PVT_STARTED_AT, Doc). -spec end_timestamp(doc()) -> kz_time:api_seconds(). end_timestamp(Doc) -> kz_json:get_integer_value(?PVT_FINISHED_AT, Doc). -spec total_count(doc()) -> kz_term:api_pos_integer(). total_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS, Doc). -spec failure_count(doc()) -> kz_term:api_non_neg_integer(). failure_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS_FAILED, Doc). -spec success_count(doc()) -> kz_term:api_non_neg_integer(). success_count(Doc) -> kz_json:get_integer_value(?PVT_TOTAL_ROWS_SUCCEEDED, Doc).
69b7291ca95eaa1b72f69e0deb7a020f74e1ccf647fb60820c5e8ed6888fd3e3
SimulaVR/godot-haskell
NavigationMesh.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.NavigationMesh (Godot.Core.NavigationMesh._SAMPLE_PARTITION_LAYERS, Godot.Core.NavigationMesh._SAMPLE_PARTITION_WATERSHED, Godot.Core.NavigationMesh._SAMPLE_PARTITION_MONOTONE, Godot.Core.NavigationMesh._PARSED_GEOMETRY_BOTH, Godot.Core.NavigationMesh._PARSED_GEOMETRY_MESH_INSTANCES, Godot.Core.NavigationMesh._PARSED_GEOMETRY_STATIC_COLLIDERS, Godot.Core.NavigationMesh._get_polygons, Godot.Core.NavigationMesh._set_polygons, Godot.Core.NavigationMesh.add_polygon, Godot.Core.NavigationMesh.clear_polygons, Godot.Core.NavigationMesh.create_from_mesh, Godot.Core.NavigationMesh.get_agent_height, Godot.Core.NavigationMesh.get_agent_max_climb, Godot.Core.NavigationMesh.get_agent_max_slope, Godot.Core.NavigationMesh.get_agent_radius, Godot.Core.NavigationMesh.get_cell_height, Godot.Core.NavigationMesh.get_cell_size, Godot.Core.NavigationMesh.get_collision_mask, Godot.Core.NavigationMesh.get_collision_mask_bit, Godot.Core.NavigationMesh.get_detail_sample_distance, Godot.Core.NavigationMesh.get_detail_sample_max_error, Godot.Core.NavigationMesh.get_edge_max_error, Godot.Core.NavigationMesh.get_edge_max_length, Godot.Core.NavigationMesh.get_filter_ledge_spans, Godot.Core.NavigationMesh.get_filter_low_hanging_obstacles, Godot.Core.NavigationMesh.get_filter_walkable_low_height_spans, Godot.Core.NavigationMesh.get_parsed_geometry_type, Godot.Core.NavigationMesh.get_polygon, Godot.Core.NavigationMesh.get_polygon_count, Godot.Core.NavigationMesh.get_region_merge_size, Godot.Core.NavigationMesh.get_region_min_size, Godot.Core.NavigationMesh.get_sample_partition_type, Godot.Core.NavigationMesh.get_source_geometry_mode, Godot.Core.NavigationMesh.get_source_group_name, Godot.Core.NavigationMesh.get_vertices, Godot.Core.NavigationMesh.get_verts_per_poly, Godot.Core.NavigationMesh.set_agent_height, Godot.Core.NavigationMesh.set_agent_max_climb, Godot.Core.NavigationMesh.set_agent_max_slope, Godot.Core.NavigationMesh.set_agent_radius, Godot.Core.NavigationMesh.set_cell_height, Godot.Core.NavigationMesh.set_cell_size, Godot.Core.NavigationMesh.set_collision_mask, Godot.Core.NavigationMesh.set_collision_mask_bit, Godot.Core.NavigationMesh.set_detail_sample_distance, Godot.Core.NavigationMesh.set_detail_sample_max_error, Godot.Core.NavigationMesh.set_edge_max_error, Godot.Core.NavigationMesh.set_edge_max_length, Godot.Core.NavigationMesh.set_filter_ledge_spans, Godot.Core.NavigationMesh.set_filter_low_hanging_obstacles, Godot.Core.NavigationMesh.set_filter_walkable_low_height_spans, Godot.Core.NavigationMesh.set_parsed_geometry_type, Godot.Core.NavigationMesh.set_region_merge_size, Godot.Core.NavigationMesh.set_region_min_size, Godot.Core.NavigationMesh.set_sample_partition_type, Godot.Core.NavigationMesh.set_source_geometry_mode, Godot.Core.NavigationMesh.set_source_group_name, Godot.Core.NavigationMesh.set_vertices, Godot.Core.NavigationMesh.set_verts_per_poly) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Resource() _SAMPLE_PARTITION_LAYERS :: Int _SAMPLE_PARTITION_LAYERS = 2 _SAMPLE_PARTITION_WATERSHED :: Int _SAMPLE_PARTITION_WATERSHED = 0 _SAMPLE_PARTITION_MONOTONE :: Int _SAMPLE_PARTITION_MONOTONE = 1 _PARSED_GEOMETRY_BOTH :: Int _PARSED_GEOMETRY_BOTH = 2 _PARSED_GEOMETRY_MESH_INSTANCES :: Int _PARSED_GEOMETRY_MESH_INSTANCES = 0 _PARSED_GEOMETRY_STATIC_COLLIDERS :: Int _PARSED_GEOMETRY_STATIC_COLLIDERS = 1 instance NodeProperty NavigationMesh "agent/height" Float 'False where nodeProperty = (get_agent_height, wrapDroppingSetter set_agent_height, Nothing) instance NodeProperty NavigationMesh "agent/max_climb" Float 'False where nodeProperty = (get_agent_max_climb, wrapDroppingSetter set_agent_max_climb, Nothing) instance NodeProperty NavigationMesh "agent/max_slope" Float 'False where nodeProperty = (get_agent_max_slope, wrapDroppingSetter set_agent_max_slope, Nothing) instance NodeProperty NavigationMesh "agent/radius" Float 'False where nodeProperty = (get_agent_radius, wrapDroppingSetter set_agent_radius, Nothing) instance NodeProperty NavigationMesh "cell/height" Float 'False where nodeProperty = (get_cell_height, wrapDroppingSetter set_cell_height, Nothing) instance NodeProperty NavigationMesh "cell/size" Float 'False where nodeProperty = (get_cell_size, wrapDroppingSetter set_cell_size, Nothing) instance NodeProperty NavigationMesh "detail/sample_distance" Float 'False where nodeProperty = (get_detail_sample_distance, wrapDroppingSetter set_detail_sample_distance, Nothing) instance NodeProperty NavigationMesh "detail/sample_max_error" Float 'False where nodeProperty = (get_detail_sample_max_error, wrapDroppingSetter set_detail_sample_max_error, Nothing) instance NodeProperty NavigationMesh "edge/max_error" Float 'False where nodeProperty = (get_edge_max_error, wrapDroppingSetter set_edge_max_error, Nothing) instance NodeProperty NavigationMesh "edge/max_length" Float 'False where nodeProperty = (get_edge_max_length, wrapDroppingSetter set_edge_max_length, Nothing) instance NodeProperty NavigationMesh "filter/filter_walkable_low_height_spans" Bool 'False where nodeProperty = (get_filter_walkable_low_height_spans, wrapDroppingSetter set_filter_walkable_low_height_spans, Nothing) instance NodeProperty NavigationMesh "filter/ledge_spans" Bool 'False where nodeProperty = (get_filter_ledge_spans, wrapDroppingSetter set_filter_ledge_spans, Nothing) instance NodeProperty NavigationMesh "filter/low_hanging_obstacles" Bool 'False where nodeProperty = (get_filter_low_hanging_obstacles, wrapDroppingSetter set_filter_low_hanging_obstacles, Nothing) instance NodeProperty NavigationMesh "geometry/collision_mask" Int 'False where nodeProperty = (get_collision_mask, wrapDroppingSetter set_collision_mask, Nothing) instance NodeProperty NavigationMesh "geometry/parsed_geometry_type" Int 'False where nodeProperty = (get_parsed_geometry_type, wrapDroppingSetter set_parsed_geometry_type, Nothing) instance NodeProperty NavigationMesh "geometry/source_geometry_mode" Int 'False where nodeProperty = (get_source_geometry_mode, wrapDroppingSetter set_source_geometry_mode, Nothing) instance NodeProperty NavigationMesh "geometry/source_group_name" GodotString 'False where nodeProperty = (get_source_group_name, wrapDroppingSetter set_source_group_name, Nothing) instance NodeProperty NavigationMesh "polygon/verts_per_poly" Float 'False where nodeProperty = (get_verts_per_poly, wrapDroppingSetter set_verts_per_poly, Nothing) instance NodeProperty NavigationMesh "polygons" Array 'False where nodeProperty = (_get_polygons, wrapDroppingSetter _set_polygons, Nothing) instance NodeProperty NavigationMesh "region/merge_size" Float 'False where nodeProperty = (get_region_merge_size, wrapDroppingSetter set_region_merge_size, Nothing) instance NodeProperty NavigationMesh "region/min_size" Float 'False where nodeProperty = (get_region_min_size, wrapDroppingSetter set_region_min_size, Nothing) instance NodeProperty NavigationMesh "sample_partition_type/sample_partition_type" Int 'False where nodeProperty = (get_sample_partition_type, wrapDroppingSetter set_sample_partition_type, Nothing) instance NodeProperty NavigationMesh "vertices" PoolVector3Array 'False where nodeProperty = (get_vertices, wrapDroppingSetter set_vertices, Nothing) # NOINLINE bindNavigationMesh__get_polygons # bindNavigationMesh__get_polygons :: MethodBind bindNavigationMesh__get_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "_get_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _get_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Array _get_polygons cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh__get_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "_get_polygons" '[] (IO Array) where nodeMethod = Godot.Core.NavigationMesh._get_polygons # NOINLINE bindNavigationMesh__set_polygons # bindNavigationMesh__set_polygons :: MethodBind bindNavigationMesh__set_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "_set_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _set_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> Array -> IO () _set_polygons cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh__set_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "_set_polygons" '[Array] (IO ()) where nodeMethod = Godot.Core.NavigationMesh._set_polygons # NOINLINE bindNavigationMesh_add_polygon # bindNavigationMesh_add_polygon :: MethodBind bindNavigationMesh_add_polygon = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "add_polygon" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr add_polygon :: (NavigationMesh :< cls, Object :< cls) => cls -> PoolIntArray -> IO () add_polygon cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_add_polygon (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "add_polygon" '[PoolIntArray] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.add_polygon # NOINLINE bindNavigationMesh_clear_polygons # bindNavigationMesh_clear_polygons :: MethodBind bindNavigationMesh_clear_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "clear_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr clear_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> IO () clear_polygons cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_clear_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "clear_polygons" '[] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.clear_polygons # NOINLINE bindNavigationMesh_create_from_mesh # bindNavigationMesh_create_from_mesh :: MethodBind bindNavigationMesh_create_from_mesh = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "create_from_mesh" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr create_from_mesh :: (NavigationMesh :< cls, Object :< cls) => cls -> Mesh -> IO () create_from_mesh cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_create_from_mesh (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "create_from_mesh" '[Mesh] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.create_from_mesh # NOINLINE bindNavigationMesh_get_agent_height # bindNavigationMesh_get_agent_height :: MethodBind bindNavigationMesh_get_agent_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_height :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_height" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_height # NOINLINE bindNavigationMesh_get_agent_max_climb # bindNavigationMesh_get_agent_max_climb :: MethodBind bindNavigationMesh_get_agent_max_climb = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_max_climb" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_max_climb :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_max_climb cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_max_climb (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_max_climb" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_max_climb {-# NOINLINE bindNavigationMesh_get_agent_max_slope #-} bindNavigationMesh_get_agent_max_slope :: MethodBind bindNavigationMesh_get_agent_max_slope = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_max_slope" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_max_slope :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_max_slope cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_max_slope (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_max_slope" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_max_slope # NOINLINE bindNavigationMesh_get_agent_radius # bindNavigationMesh_get_agent_radius :: MethodBind bindNavigationMesh_get_agent_radius = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_radius" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_radius :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_radius cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_radius (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_radius" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_radius # NOINLINE bindNavigationMesh_get_cell_height # bindNavigationMesh_get_cell_height :: MethodBind bindNavigationMesh_get_cell_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_cell_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_cell_height :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_cell_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_cell_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_cell_height" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_cell_height # NOINLINE bindNavigationMesh_get_cell_size # bindNavigationMesh_get_cell_size :: MethodBind bindNavigationMesh_get_cell_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_cell_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_cell_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_cell_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_cell_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_cell_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_cell_size # NOINLINE bindNavigationMesh_get_collision_mask # bindNavigationMesh_get_collision_mask :: MethodBind bindNavigationMesh_get_collision_mask = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_collision_mask" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_collision_mask :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_collision_mask cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_collision_mask (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_collision_mask" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_collision_mask # NOINLINE bindNavigationMesh_get_collision_mask_bit # bindNavigationMesh_get_collision_mask_bit :: MethodBind bindNavigationMesh_get_collision_mask_bit = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_collision_mask_bit" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_collision_mask_bit :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO Bool get_collision_mask_bit cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_collision_mask_bit (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_collision_mask_bit" '[Int] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_collision_mask_bit # NOINLINE bindNavigationMesh_get_detail_sample_distance # bindNavigationMesh_get_detail_sample_distance :: MethodBind bindNavigationMesh_get_detail_sample_distance = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_detail_sample_distance" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_detail_sample_distance :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_detail_sample_distance cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_detail_sample_distance (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_detail_sample_distance" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_detail_sample_distance # NOINLINE bindNavigationMesh_get_detail_sample_max_error # bindNavigationMesh_get_detail_sample_max_error :: MethodBind bindNavigationMesh_get_detail_sample_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_detail_sample_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_detail_sample_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_detail_sample_max_error cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_detail_sample_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_detail_sample_max_error" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_detail_sample_max_error # NOINLINE bindNavigationMesh_get_edge_max_error # bindNavigationMesh_get_edge_max_error :: MethodBind bindNavigationMesh_get_edge_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_edge_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_edge_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_edge_max_error cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_edge_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_edge_max_error" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_edge_max_error # NOINLINE bindNavigationMesh_get_edge_max_length # bindNavigationMesh_get_edge_max_length :: MethodBind bindNavigationMesh_get_edge_max_length = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_edge_max_length" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_edge_max_length :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_edge_max_length cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_edge_max_length (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_edge_max_length" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_edge_max_length {-# NOINLINE bindNavigationMesh_get_filter_ledge_spans #-} bindNavigationMesh_get_filter_ledge_spans :: MethodBind bindNavigationMesh_get_filter_ledge_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_ledge_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_ledge_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_ledge_spans cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_ledge_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_ledge_spans" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_ledge_spans # NOINLINE bindNavigationMesh_get_filter_low_hanging_obstacles # #-} bindNavigationMesh_get_filter_low_hanging_obstacles :: MethodBind bindNavigationMesh_get_filter_low_hanging_obstacles = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_low_hanging_obstacles" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_low_hanging_obstacles :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_low_hanging_obstacles cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_low_hanging_obstacles (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_low_hanging_obstacles" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_low_hanging_obstacles # NOINLINE bindNavigationMesh_get_filter_walkable_low_height_spans # #-} bindNavigationMesh_get_filter_walkable_low_height_spans :: MethodBind bindNavigationMesh_get_filter_walkable_low_height_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_walkable_low_height_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_walkable_low_height_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_walkable_low_height_spans cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_walkable_low_height_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_walkable_low_height_spans" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_walkable_low_height_spans {-# NOINLINE bindNavigationMesh_get_parsed_geometry_type #-} bindNavigationMesh_get_parsed_geometry_type :: MethodBind bindNavigationMesh_get_parsed_geometry_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_parsed_geometry_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_parsed_geometry_type :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_parsed_geometry_type cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_parsed_geometry_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_parsed_geometry_type" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_parsed_geometry_type # NOINLINE bindNavigationMesh_get_polygon # bindNavigationMesh_get_polygon :: MethodBind bindNavigationMesh_get_polygon = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_polygon" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_polygon :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO PoolIntArray get_polygon cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_polygon (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_polygon" '[Int] (IO PoolIntArray) where nodeMethod = Godot.Core.NavigationMesh.get_polygon # NOINLINE bindNavigationMesh_get_polygon_count # bindNavigationMesh_get_polygon_count :: MethodBind bindNavigationMesh_get_polygon_count = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_polygon_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_polygon_count :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_polygon_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_polygon_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_polygon_count" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_polygon_count # NOINLINE bindNavigationMesh_get_region_merge_size # bindNavigationMesh_get_region_merge_size :: MethodBind bindNavigationMesh_get_region_merge_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_region_merge_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_region_merge_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_region_merge_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_region_merge_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_region_merge_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_region_merge_size # NOINLINE bindNavigationMesh_get_region_min_size # bindNavigationMesh_get_region_min_size :: MethodBind bindNavigationMesh_get_region_min_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_region_min_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_region_min_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_region_min_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_region_min_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_region_min_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_region_min_size # NOINLINE bindNavigationMesh_get_sample_partition_type # bindNavigationMesh_get_sample_partition_type :: MethodBind bindNavigationMesh_get_sample_partition_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_sample_partition_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_sample_partition_type :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_sample_partition_type cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_sample_partition_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_sample_partition_type" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_sample_partition_type # NOINLINE bindNavigationMesh_get_source_geometry_mode # bindNavigationMesh_get_source_geometry_mode :: MethodBind bindNavigationMesh_get_source_geometry_mode = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_source_geometry_mode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_source_geometry_mode :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_source_geometry_mode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_source_geometry_mode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_source_geometry_mode" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_source_geometry_mode # NOINLINE bindNavigationMesh_get_source_group_name # bindNavigationMesh_get_source_group_name :: MethodBind bindNavigationMesh_get_source_group_name = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_source_group_name" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_source_group_name :: (NavigationMesh :< cls, Object :< cls) => cls -> IO GodotString get_source_group_name cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_source_group_name (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_source_group_name" '[] (IO GodotString) where nodeMethod = Godot.Core.NavigationMesh.get_source_group_name # NOINLINE bindNavigationMesh_get_vertices # bindNavigationMesh_get_vertices :: MethodBind bindNavigationMesh_get_vertices = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_vertices" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_vertices :: (NavigationMesh :< cls, Object :< cls) => cls -> IO PoolVector3Array get_vertices cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_vertices (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_vertices" '[] (IO PoolVector3Array) where nodeMethod = Godot.Core.NavigationMesh.get_vertices # NOINLINE bindNavigationMesh_get_verts_per_poly # bindNavigationMesh_get_verts_per_poly :: MethodBind bindNavigationMesh_get_verts_per_poly = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_verts_per_poly" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_verts_per_poly :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_verts_per_poly cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_verts_per_poly (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_verts_per_poly" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_verts_per_poly {-# NOINLINE bindNavigationMesh_set_agent_height #-} bindNavigationMesh_set_agent_height :: MethodBind bindNavigationMesh_set_agent_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_height :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_height cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_height" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_height # NOINLINE bindNavigationMesh_set_agent_max_climb # bindNavigationMesh_set_agent_max_climb :: MethodBind bindNavigationMesh_set_agent_max_climb = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_max_climb" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_max_climb :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_max_climb cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_max_climb (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_max_climb" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_max_climb # NOINLINE bindNavigationMesh_set_agent_max_slope # bindNavigationMesh_set_agent_max_slope :: MethodBind bindNavigationMesh_set_agent_max_slope = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_max_slope" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_max_slope :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_max_slope cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_max_slope (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_max_slope" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_max_slope # NOINLINE bindNavigationMesh_set_agent_radius # bindNavigationMesh_set_agent_radius :: MethodBind bindNavigationMesh_set_agent_radius = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_radius" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_radius :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_radius cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_radius (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_radius" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_radius # NOINLINE bindNavigationMesh_set_cell_height # bindNavigationMesh_set_cell_height :: MethodBind bindNavigationMesh_set_cell_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_cell_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_cell_height :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_cell_height cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_cell_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_cell_height" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_cell_height # NOINLINE bindNavigationMesh_set_cell_size # bindNavigationMesh_set_cell_size :: MethodBind bindNavigationMesh_set_cell_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_cell_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_cell_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_cell_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_cell_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_cell_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_cell_size {-# NOINLINE bindNavigationMesh_set_collision_mask #-} bindNavigationMesh_set_collision_mask :: MethodBind bindNavigationMesh_set_collision_mask = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_collision_mask" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_collision_mask :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_collision_mask cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_collision_mask (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_collision_mask" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_collision_mask # NOINLINE bindNavigationMesh_set_collision_mask_bit # bindNavigationMesh_set_collision_mask_bit :: MethodBind bindNavigationMesh_set_collision_mask_bit = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_collision_mask_bit" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_collision_mask_bit :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> Bool -> IO () set_collision_mask_bit cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_collision_mask_bit (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_collision_mask_bit" '[Int, Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_collision_mask_bit # NOINLINE bindNavigationMesh_set_detail_sample_distance # bindNavigationMesh_set_detail_sample_distance :: MethodBind bindNavigationMesh_set_detail_sample_distance = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_detail_sample_distance" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_detail_sample_distance :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_detail_sample_distance cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_detail_sample_distance (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_detail_sample_distance" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_detail_sample_distance # NOINLINE bindNavigationMesh_set_detail_sample_max_error # bindNavigationMesh_set_detail_sample_max_error :: MethodBind bindNavigationMesh_set_detail_sample_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_detail_sample_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_detail_sample_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_detail_sample_max_error cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_detail_sample_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_detail_sample_max_error" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_detail_sample_max_error # NOINLINE bindNavigationMesh_set_edge_max_error # bindNavigationMesh_set_edge_max_error :: MethodBind bindNavigationMesh_set_edge_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_edge_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_edge_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_edge_max_error cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_edge_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_edge_max_error" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_edge_max_error # NOINLINE bindNavigationMesh_set_edge_max_length # bindNavigationMesh_set_edge_max_length :: MethodBind bindNavigationMesh_set_edge_max_length = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_edge_max_length" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_edge_max_length :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_edge_max_length cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_edge_max_length (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_edge_max_length" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_edge_max_length # NOINLINE bindNavigationMesh_set_filter_ledge_spans # bindNavigationMesh_set_filter_ledge_spans :: MethodBind bindNavigationMesh_set_filter_ledge_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_ledge_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_ledge_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_ledge_spans cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_ledge_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_ledge_spans" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_ledge_spans # NOINLINE bindNavigationMesh_set_filter_low_hanging_obstacles # #-} bindNavigationMesh_set_filter_low_hanging_obstacles :: MethodBind bindNavigationMesh_set_filter_low_hanging_obstacles = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_low_hanging_obstacles" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_low_hanging_obstacles :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_low_hanging_obstacles cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_low_hanging_obstacles (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_low_hanging_obstacles" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_low_hanging_obstacles # NOINLINE bindNavigationMesh_set_filter_walkable_low_height_spans # #-} bindNavigationMesh_set_filter_walkable_low_height_spans :: MethodBind bindNavigationMesh_set_filter_walkable_low_height_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_walkable_low_height_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_walkable_low_height_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_walkable_low_height_spans cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_walkable_low_height_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_walkable_low_height_spans" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_walkable_low_height_spans # NOINLINE bindNavigationMesh_set_parsed_geometry_type # bindNavigationMesh_set_parsed_geometry_type :: MethodBind bindNavigationMesh_set_parsed_geometry_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_parsed_geometry_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_parsed_geometry_type :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_parsed_geometry_type cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_parsed_geometry_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_parsed_geometry_type" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_parsed_geometry_type # NOINLINE bindNavigationMesh_set_region_merge_size # bindNavigationMesh_set_region_merge_size :: MethodBind bindNavigationMesh_set_region_merge_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_region_merge_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_region_merge_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_region_merge_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_region_merge_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_region_merge_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_region_merge_size # NOINLINE bindNavigationMesh_set_region_min_size # bindNavigationMesh_set_region_min_size :: MethodBind bindNavigationMesh_set_region_min_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_region_min_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_region_min_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_region_min_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_region_min_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_region_min_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_region_min_size {-# NOINLINE bindNavigationMesh_set_sample_partition_type #-} bindNavigationMesh_set_sample_partition_type :: MethodBind bindNavigationMesh_set_sample_partition_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_sample_partition_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_sample_partition_type :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_sample_partition_type cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_sample_partition_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_sample_partition_type" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_sample_partition_type # NOINLINE bindNavigationMesh_set_source_geometry_mode # bindNavigationMesh_set_source_geometry_mode :: MethodBind bindNavigationMesh_set_source_geometry_mode = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_source_geometry_mode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_source_geometry_mode :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_source_geometry_mode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_source_geometry_mode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_source_geometry_mode" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_source_geometry_mode # NOINLINE bindNavigationMesh_set_source_group_name # bindNavigationMesh_set_source_group_name :: MethodBind bindNavigationMesh_set_source_group_name = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_source_group_name" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_source_group_name :: (NavigationMesh :< cls, Object :< cls) => cls -> GodotString -> IO () set_source_group_name cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_source_group_name (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_source_group_name" '[GodotString] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_source_group_name # NOINLINE bindNavigationMesh_set_vertices # bindNavigationMesh_set_vertices :: MethodBind bindNavigationMesh_set_vertices = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_vertices" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_vertices :: (NavigationMesh :< cls, Object :< cls) => cls -> PoolVector3Array -> IO () set_vertices cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_vertices (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_vertices" '[PoolVector3Array] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_vertices # NOINLINE bindNavigationMesh_set_verts_per_poly # bindNavigationMesh_set_verts_per_poly :: MethodBind bindNavigationMesh_set_verts_per_poly = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_verts_per_poly" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_verts_per_poly :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_verts_per_poly cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_verts_per_poly (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_verts_per_poly" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_verts_per_poly
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/NavigationMesh.hs
haskell
# NOINLINE bindNavigationMesh_get_agent_max_slope # # NOINLINE bindNavigationMesh_get_filter_ledge_spans # # NOINLINE bindNavigationMesh_get_parsed_geometry_type # # NOINLINE bindNavigationMesh_set_agent_height # # NOINLINE bindNavigationMesh_set_collision_mask # # NOINLINE bindNavigationMesh_set_sample_partition_type #
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.NavigationMesh (Godot.Core.NavigationMesh._SAMPLE_PARTITION_LAYERS, Godot.Core.NavigationMesh._SAMPLE_PARTITION_WATERSHED, Godot.Core.NavigationMesh._SAMPLE_PARTITION_MONOTONE, Godot.Core.NavigationMesh._PARSED_GEOMETRY_BOTH, Godot.Core.NavigationMesh._PARSED_GEOMETRY_MESH_INSTANCES, Godot.Core.NavigationMesh._PARSED_GEOMETRY_STATIC_COLLIDERS, Godot.Core.NavigationMesh._get_polygons, Godot.Core.NavigationMesh._set_polygons, Godot.Core.NavigationMesh.add_polygon, Godot.Core.NavigationMesh.clear_polygons, Godot.Core.NavigationMesh.create_from_mesh, Godot.Core.NavigationMesh.get_agent_height, Godot.Core.NavigationMesh.get_agent_max_climb, Godot.Core.NavigationMesh.get_agent_max_slope, Godot.Core.NavigationMesh.get_agent_radius, Godot.Core.NavigationMesh.get_cell_height, Godot.Core.NavigationMesh.get_cell_size, Godot.Core.NavigationMesh.get_collision_mask, Godot.Core.NavigationMesh.get_collision_mask_bit, Godot.Core.NavigationMesh.get_detail_sample_distance, Godot.Core.NavigationMesh.get_detail_sample_max_error, Godot.Core.NavigationMesh.get_edge_max_error, Godot.Core.NavigationMesh.get_edge_max_length, Godot.Core.NavigationMesh.get_filter_ledge_spans, Godot.Core.NavigationMesh.get_filter_low_hanging_obstacles, Godot.Core.NavigationMesh.get_filter_walkable_low_height_spans, Godot.Core.NavigationMesh.get_parsed_geometry_type, Godot.Core.NavigationMesh.get_polygon, Godot.Core.NavigationMesh.get_polygon_count, Godot.Core.NavigationMesh.get_region_merge_size, Godot.Core.NavigationMesh.get_region_min_size, Godot.Core.NavigationMesh.get_sample_partition_type, Godot.Core.NavigationMesh.get_source_geometry_mode, Godot.Core.NavigationMesh.get_source_group_name, Godot.Core.NavigationMesh.get_vertices, Godot.Core.NavigationMesh.get_verts_per_poly, Godot.Core.NavigationMesh.set_agent_height, Godot.Core.NavigationMesh.set_agent_max_climb, Godot.Core.NavigationMesh.set_agent_max_slope, Godot.Core.NavigationMesh.set_agent_radius, Godot.Core.NavigationMesh.set_cell_height, Godot.Core.NavigationMesh.set_cell_size, Godot.Core.NavigationMesh.set_collision_mask, Godot.Core.NavigationMesh.set_collision_mask_bit, Godot.Core.NavigationMesh.set_detail_sample_distance, Godot.Core.NavigationMesh.set_detail_sample_max_error, Godot.Core.NavigationMesh.set_edge_max_error, Godot.Core.NavigationMesh.set_edge_max_length, Godot.Core.NavigationMesh.set_filter_ledge_spans, Godot.Core.NavigationMesh.set_filter_low_hanging_obstacles, Godot.Core.NavigationMesh.set_filter_walkable_low_height_spans, Godot.Core.NavigationMesh.set_parsed_geometry_type, Godot.Core.NavigationMesh.set_region_merge_size, Godot.Core.NavigationMesh.set_region_min_size, Godot.Core.NavigationMesh.set_sample_partition_type, Godot.Core.NavigationMesh.set_source_geometry_mode, Godot.Core.NavigationMesh.set_source_group_name, Godot.Core.NavigationMesh.set_vertices, Godot.Core.NavigationMesh.set_verts_per_poly) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Resource() _SAMPLE_PARTITION_LAYERS :: Int _SAMPLE_PARTITION_LAYERS = 2 _SAMPLE_PARTITION_WATERSHED :: Int _SAMPLE_PARTITION_WATERSHED = 0 _SAMPLE_PARTITION_MONOTONE :: Int _SAMPLE_PARTITION_MONOTONE = 1 _PARSED_GEOMETRY_BOTH :: Int _PARSED_GEOMETRY_BOTH = 2 _PARSED_GEOMETRY_MESH_INSTANCES :: Int _PARSED_GEOMETRY_MESH_INSTANCES = 0 _PARSED_GEOMETRY_STATIC_COLLIDERS :: Int _PARSED_GEOMETRY_STATIC_COLLIDERS = 1 instance NodeProperty NavigationMesh "agent/height" Float 'False where nodeProperty = (get_agent_height, wrapDroppingSetter set_agent_height, Nothing) instance NodeProperty NavigationMesh "agent/max_climb" Float 'False where nodeProperty = (get_agent_max_climb, wrapDroppingSetter set_agent_max_climb, Nothing) instance NodeProperty NavigationMesh "agent/max_slope" Float 'False where nodeProperty = (get_agent_max_slope, wrapDroppingSetter set_agent_max_slope, Nothing) instance NodeProperty NavigationMesh "agent/radius" Float 'False where nodeProperty = (get_agent_radius, wrapDroppingSetter set_agent_radius, Nothing) instance NodeProperty NavigationMesh "cell/height" Float 'False where nodeProperty = (get_cell_height, wrapDroppingSetter set_cell_height, Nothing) instance NodeProperty NavigationMesh "cell/size" Float 'False where nodeProperty = (get_cell_size, wrapDroppingSetter set_cell_size, Nothing) instance NodeProperty NavigationMesh "detail/sample_distance" Float 'False where nodeProperty = (get_detail_sample_distance, wrapDroppingSetter set_detail_sample_distance, Nothing) instance NodeProperty NavigationMesh "detail/sample_max_error" Float 'False where nodeProperty = (get_detail_sample_max_error, wrapDroppingSetter set_detail_sample_max_error, Nothing) instance NodeProperty NavigationMesh "edge/max_error" Float 'False where nodeProperty = (get_edge_max_error, wrapDroppingSetter set_edge_max_error, Nothing) instance NodeProperty NavigationMesh "edge/max_length" Float 'False where nodeProperty = (get_edge_max_length, wrapDroppingSetter set_edge_max_length, Nothing) instance NodeProperty NavigationMesh "filter/filter_walkable_low_height_spans" Bool 'False where nodeProperty = (get_filter_walkable_low_height_spans, wrapDroppingSetter set_filter_walkable_low_height_spans, Nothing) instance NodeProperty NavigationMesh "filter/ledge_spans" Bool 'False where nodeProperty = (get_filter_ledge_spans, wrapDroppingSetter set_filter_ledge_spans, Nothing) instance NodeProperty NavigationMesh "filter/low_hanging_obstacles" Bool 'False where nodeProperty = (get_filter_low_hanging_obstacles, wrapDroppingSetter set_filter_low_hanging_obstacles, Nothing) instance NodeProperty NavigationMesh "geometry/collision_mask" Int 'False where nodeProperty = (get_collision_mask, wrapDroppingSetter set_collision_mask, Nothing) instance NodeProperty NavigationMesh "geometry/parsed_geometry_type" Int 'False where nodeProperty = (get_parsed_geometry_type, wrapDroppingSetter set_parsed_geometry_type, Nothing) instance NodeProperty NavigationMesh "geometry/source_geometry_mode" Int 'False where nodeProperty = (get_source_geometry_mode, wrapDroppingSetter set_source_geometry_mode, Nothing) instance NodeProperty NavigationMesh "geometry/source_group_name" GodotString 'False where nodeProperty = (get_source_group_name, wrapDroppingSetter set_source_group_name, Nothing) instance NodeProperty NavigationMesh "polygon/verts_per_poly" Float 'False where nodeProperty = (get_verts_per_poly, wrapDroppingSetter set_verts_per_poly, Nothing) instance NodeProperty NavigationMesh "polygons" Array 'False where nodeProperty = (_get_polygons, wrapDroppingSetter _set_polygons, Nothing) instance NodeProperty NavigationMesh "region/merge_size" Float 'False where nodeProperty = (get_region_merge_size, wrapDroppingSetter set_region_merge_size, Nothing) instance NodeProperty NavigationMesh "region/min_size" Float 'False where nodeProperty = (get_region_min_size, wrapDroppingSetter set_region_min_size, Nothing) instance NodeProperty NavigationMesh "sample_partition_type/sample_partition_type" Int 'False where nodeProperty = (get_sample_partition_type, wrapDroppingSetter set_sample_partition_type, Nothing) instance NodeProperty NavigationMesh "vertices" PoolVector3Array 'False where nodeProperty = (get_vertices, wrapDroppingSetter set_vertices, Nothing) # NOINLINE bindNavigationMesh__get_polygons # bindNavigationMesh__get_polygons :: MethodBind bindNavigationMesh__get_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "_get_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _get_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Array _get_polygons cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh__get_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "_get_polygons" '[] (IO Array) where nodeMethod = Godot.Core.NavigationMesh._get_polygons # NOINLINE bindNavigationMesh__set_polygons # bindNavigationMesh__set_polygons :: MethodBind bindNavigationMesh__set_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "_set_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _set_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> Array -> IO () _set_polygons cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh__set_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "_set_polygons" '[Array] (IO ()) where nodeMethod = Godot.Core.NavigationMesh._set_polygons # NOINLINE bindNavigationMesh_add_polygon # bindNavigationMesh_add_polygon :: MethodBind bindNavigationMesh_add_polygon = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "add_polygon" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr add_polygon :: (NavigationMesh :< cls, Object :< cls) => cls -> PoolIntArray -> IO () add_polygon cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_add_polygon (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "add_polygon" '[PoolIntArray] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.add_polygon # NOINLINE bindNavigationMesh_clear_polygons # bindNavigationMesh_clear_polygons :: MethodBind bindNavigationMesh_clear_polygons = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "clear_polygons" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr clear_polygons :: (NavigationMesh :< cls, Object :< cls) => cls -> IO () clear_polygons cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_clear_polygons (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "clear_polygons" '[] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.clear_polygons # NOINLINE bindNavigationMesh_create_from_mesh # bindNavigationMesh_create_from_mesh :: MethodBind bindNavigationMesh_create_from_mesh = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "create_from_mesh" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr create_from_mesh :: (NavigationMesh :< cls, Object :< cls) => cls -> Mesh -> IO () create_from_mesh cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_create_from_mesh (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "create_from_mesh" '[Mesh] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.create_from_mesh # NOINLINE bindNavigationMesh_get_agent_height # bindNavigationMesh_get_agent_height :: MethodBind bindNavigationMesh_get_agent_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_height :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_height" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_height # NOINLINE bindNavigationMesh_get_agent_max_climb # bindNavigationMesh_get_agent_max_climb :: MethodBind bindNavigationMesh_get_agent_max_climb = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_max_climb" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_max_climb :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_max_climb cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_max_climb (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_max_climb" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_max_climb bindNavigationMesh_get_agent_max_slope :: MethodBind bindNavigationMesh_get_agent_max_slope = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_max_slope" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_max_slope :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_max_slope cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_max_slope (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_max_slope" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_max_slope # NOINLINE bindNavigationMesh_get_agent_radius # bindNavigationMesh_get_agent_radius :: MethodBind bindNavigationMesh_get_agent_radius = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_agent_radius" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_agent_radius :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_agent_radius cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_agent_radius (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_agent_radius" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_agent_radius # NOINLINE bindNavigationMesh_get_cell_height # bindNavigationMesh_get_cell_height :: MethodBind bindNavigationMesh_get_cell_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_cell_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_cell_height :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_cell_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_cell_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_cell_height" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_cell_height # NOINLINE bindNavigationMesh_get_cell_size # bindNavigationMesh_get_cell_size :: MethodBind bindNavigationMesh_get_cell_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_cell_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_cell_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_cell_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_cell_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_cell_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_cell_size # NOINLINE bindNavigationMesh_get_collision_mask # bindNavigationMesh_get_collision_mask :: MethodBind bindNavigationMesh_get_collision_mask = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_collision_mask" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_collision_mask :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_collision_mask cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_collision_mask (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_collision_mask" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_collision_mask # NOINLINE bindNavigationMesh_get_collision_mask_bit # bindNavigationMesh_get_collision_mask_bit :: MethodBind bindNavigationMesh_get_collision_mask_bit = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_collision_mask_bit" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_collision_mask_bit :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO Bool get_collision_mask_bit cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_collision_mask_bit (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_collision_mask_bit" '[Int] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_collision_mask_bit # NOINLINE bindNavigationMesh_get_detail_sample_distance # bindNavigationMesh_get_detail_sample_distance :: MethodBind bindNavigationMesh_get_detail_sample_distance = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_detail_sample_distance" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_detail_sample_distance :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_detail_sample_distance cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_detail_sample_distance (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_detail_sample_distance" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_detail_sample_distance # NOINLINE bindNavigationMesh_get_detail_sample_max_error # bindNavigationMesh_get_detail_sample_max_error :: MethodBind bindNavigationMesh_get_detail_sample_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_detail_sample_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_detail_sample_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_detail_sample_max_error cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_detail_sample_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_detail_sample_max_error" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_detail_sample_max_error # NOINLINE bindNavigationMesh_get_edge_max_error # bindNavigationMesh_get_edge_max_error :: MethodBind bindNavigationMesh_get_edge_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_edge_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_edge_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_edge_max_error cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_edge_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_edge_max_error" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_edge_max_error # NOINLINE bindNavigationMesh_get_edge_max_length # bindNavigationMesh_get_edge_max_length :: MethodBind bindNavigationMesh_get_edge_max_length = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_edge_max_length" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_edge_max_length :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_edge_max_length cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_edge_max_length (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_edge_max_length" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_edge_max_length bindNavigationMesh_get_filter_ledge_spans :: MethodBind bindNavigationMesh_get_filter_ledge_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_ledge_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_ledge_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_ledge_spans cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_ledge_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_ledge_spans" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_ledge_spans # NOINLINE bindNavigationMesh_get_filter_low_hanging_obstacles # #-} bindNavigationMesh_get_filter_low_hanging_obstacles :: MethodBind bindNavigationMesh_get_filter_low_hanging_obstacles = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_low_hanging_obstacles" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_low_hanging_obstacles :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_low_hanging_obstacles cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_low_hanging_obstacles (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_low_hanging_obstacles" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_low_hanging_obstacles # NOINLINE bindNavigationMesh_get_filter_walkable_low_height_spans # #-} bindNavigationMesh_get_filter_walkable_low_height_spans :: MethodBind bindNavigationMesh_get_filter_walkable_low_height_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_filter_walkable_low_height_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_filter_walkable_low_height_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Bool get_filter_walkable_low_height_spans cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_filter_walkable_low_height_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_filter_walkable_low_height_spans" '[] (IO Bool) where nodeMethod = Godot.Core.NavigationMesh.get_filter_walkable_low_height_spans bindNavigationMesh_get_parsed_geometry_type :: MethodBind bindNavigationMesh_get_parsed_geometry_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_parsed_geometry_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_parsed_geometry_type :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_parsed_geometry_type cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_parsed_geometry_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_parsed_geometry_type" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_parsed_geometry_type # NOINLINE bindNavigationMesh_get_polygon # bindNavigationMesh_get_polygon :: MethodBind bindNavigationMesh_get_polygon = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_polygon" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_polygon :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO PoolIntArray get_polygon cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_polygon (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_polygon" '[Int] (IO PoolIntArray) where nodeMethod = Godot.Core.NavigationMesh.get_polygon # NOINLINE bindNavigationMesh_get_polygon_count # bindNavigationMesh_get_polygon_count :: MethodBind bindNavigationMesh_get_polygon_count = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_polygon_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_polygon_count :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_polygon_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_polygon_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_polygon_count" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_polygon_count # NOINLINE bindNavigationMesh_get_region_merge_size # bindNavigationMesh_get_region_merge_size :: MethodBind bindNavigationMesh_get_region_merge_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_region_merge_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_region_merge_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_region_merge_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_region_merge_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_region_merge_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_region_merge_size # NOINLINE bindNavigationMesh_get_region_min_size # bindNavigationMesh_get_region_min_size :: MethodBind bindNavigationMesh_get_region_min_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_region_min_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_region_min_size :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_region_min_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_region_min_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_region_min_size" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_region_min_size # NOINLINE bindNavigationMesh_get_sample_partition_type # bindNavigationMesh_get_sample_partition_type :: MethodBind bindNavigationMesh_get_sample_partition_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_sample_partition_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_sample_partition_type :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_sample_partition_type cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_sample_partition_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_sample_partition_type" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_sample_partition_type # NOINLINE bindNavigationMesh_get_source_geometry_mode # bindNavigationMesh_get_source_geometry_mode :: MethodBind bindNavigationMesh_get_source_geometry_mode = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_source_geometry_mode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_source_geometry_mode :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Int get_source_geometry_mode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_source_geometry_mode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_source_geometry_mode" '[] (IO Int) where nodeMethod = Godot.Core.NavigationMesh.get_source_geometry_mode # NOINLINE bindNavigationMesh_get_source_group_name # bindNavigationMesh_get_source_group_name :: MethodBind bindNavigationMesh_get_source_group_name = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_source_group_name" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_source_group_name :: (NavigationMesh :< cls, Object :< cls) => cls -> IO GodotString get_source_group_name cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_source_group_name (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_source_group_name" '[] (IO GodotString) where nodeMethod = Godot.Core.NavigationMesh.get_source_group_name # NOINLINE bindNavigationMesh_get_vertices # bindNavigationMesh_get_vertices :: MethodBind bindNavigationMesh_get_vertices = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_vertices" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_vertices :: (NavigationMesh :< cls, Object :< cls) => cls -> IO PoolVector3Array get_vertices cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_vertices (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_vertices" '[] (IO PoolVector3Array) where nodeMethod = Godot.Core.NavigationMesh.get_vertices # NOINLINE bindNavigationMesh_get_verts_per_poly # bindNavigationMesh_get_verts_per_poly :: MethodBind bindNavigationMesh_get_verts_per_poly = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "get_verts_per_poly" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_verts_per_poly :: (NavigationMesh :< cls, Object :< cls) => cls -> IO Float get_verts_per_poly cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_get_verts_per_poly (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "get_verts_per_poly" '[] (IO Float) where nodeMethod = Godot.Core.NavigationMesh.get_verts_per_poly bindNavigationMesh_set_agent_height :: MethodBind bindNavigationMesh_set_agent_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_height :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_height cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_height" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_height # NOINLINE bindNavigationMesh_set_agent_max_climb # bindNavigationMesh_set_agent_max_climb :: MethodBind bindNavigationMesh_set_agent_max_climb = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_max_climb" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_max_climb :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_max_climb cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_max_climb (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_max_climb" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_max_climb # NOINLINE bindNavigationMesh_set_agent_max_slope # bindNavigationMesh_set_agent_max_slope :: MethodBind bindNavigationMesh_set_agent_max_slope = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_max_slope" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_max_slope :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_max_slope cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_max_slope (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_max_slope" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_max_slope # NOINLINE bindNavigationMesh_set_agent_radius # bindNavigationMesh_set_agent_radius :: MethodBind bindNavigationMesh_set_agent_radius = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_agent_radius" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_agent_radius :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_agent_radius cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_agent_radius (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_agent_radius" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_agent_radius # NOINLINE bindNavigationMesh_set_cell_height # bindNavigationMesh_set_cell_height :: MethodBind bindNavigationMesh_set_cell_height = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_cell_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_cell_height :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_cell_height cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_cell_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_cell_height" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_cell_height # NOINLINE bindNavigationMesh_set_cell_size # bindNavigationMesh_set_cell_size :: MethodBind bindNavigationMesh_set_cell_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_cell_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_cell_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_cell_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_cell_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_cell_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_cell_size bindNavigationMesh_set_collision_mask :: MethodBind bindNavigationMesh_set_collision_mask = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_collision_mask" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_collision_mask :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_collision_mask cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_collision_mask (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_collision_mask" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_collision_mask # NOINLINE bindNavigationMesh_set_collision_mask_bit # bindNavigationMesh_set_collision_mask_bit :: MethodBind bindNavigationMesh_set_collision_mask_bit = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_collision_mask_bit" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_collision_mask_bit :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> Bool -> IO () set_collision_mask_bit cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_collision_mask_bit (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_collision_mask_bit" '[Int, Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_collision_mask_bit # NOINLINE bindNavigationMesh_set_detail_sample_distance # bindNavigationMesh_set_detail_sample_distance :: MethodBind bindNavigationMesh_set_detail_sample_distance = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_detail_sample_distance" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_detail_sample_distance :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_detail_sample_distance cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_detail_sample_distance (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_detail_sample_distance" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_detail_sample_distance # NOINLINE bindNavigationMesh_set_detail_sample_max_error # bindNavigationMesh_set_detail_sample_max_error :: MethodBind bindNavigationMesh_set_detail_sample_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_detail_sample_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_detail_sample_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_detail_sample_max_error cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_detail_sample_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_detail_sample_max_error" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_detail_sample_max_error # NOINLINE bindNavigationMesh_set_edge_max_error # bindNavigationMesh_set_edge_max_error :: MethodBind bindNavigationMesh_set_edge_max_error = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_edge_max_error" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_edge_max_error :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_edge_max_error cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_edge_max_error (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_edge_max_error" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_edge_max_error # NOINLINE bindNavigationMesh_set_edge_max_length # bindNavigationMesh_set_edge_max_length :: MethodBind bindNavigationMesh_set_edge_max_length = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_edge_max_length" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_edge_max_length :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_edge_max_length cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_edge_max_length (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_edge_max_length" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_edge_max_length # NOINLINE bindNavigationMesh_set_filter_ledge_spans # bindNavigationMesh_set_filter_ledge_spans :: MethodBind bindNavigationMesh_set_filter_ledge_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_ledge_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_ledge_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_ledge_spans cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_ledge_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_ledge_spans" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_ledge_spans # NOINLINE bindNavigationMesh_set_filter_low_hanging_obstacles # #-} bindNavigationMesh_set_filter_low_hanging_obstacles :: MethodBind bindNavigationMesh_set_filter_low_hanging_obstacles = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_low_hanging_obstacles" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_low_hanging_obstacles :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_low_hanging_obstacles cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_low_hanging_obstacles (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_low_hanging_obstacles" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_low_hanging_obstacles # NOINLINE bindNavigationMesh_set_filter_walkable_low_height_spans # #-} bindNavigationMesh_set_filter_walkable_low_height_spans :: MethodBind bindNavigationMesh_set_filter_walkable_low_height_spans = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_filter_walkable_low_height_spans" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_filter_walkable_low_height_spans :: (NavigationMesh :< cls, Object :< cls) => cls -> Bool -> IO () set_filter_walkable_low_height_spans cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_filter_walkable_low_height_spans (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_filter_walkable_low_height_spans" '[Bool] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_filter_walkable_low_height_spans # NOINLINE bindNavigationMesh_set_parsed_geometry_type # bindNavigationMesh_set_parsed_geometry_type :: MethodBind bindNavigationMesh_set_parsed_geometry_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_parsed_geometry_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_parsed_geometry_type :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_parsed_geometry_type cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_parsed_geometry_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_parsed_geometry_type" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_parsed_geometry_type # NOINLINE bindNavigationMesh_set_region_merge_size # bindNavigationMesh_set_region_merge_size :: MethodBind bindNavigationMesh_set_region_merge_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_region_merge_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_region_merge_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_region_merge_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_region_merge_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_region_merge_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_region_merge_size # NOINLINE bindNavigationMesh_set_region_min_size # bindNavigationMesh_set_region_min_size :: MethodBind bindNavigationMesh_set_region_min_size = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_region_min_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_region_min_size :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_region_min_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_region_min_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_region_min_size" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_region_min_size bindNavigationMesh_set_sample_partition_type :: MethodBind bindNavigationMesh_set_sample_partition_type = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_sample_partition_type" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_sample_partition_type :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_sample_partition_type cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_sample_partition_type (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_sample_partition_type" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_sample_partition_type # NOINLINE bindNavigationMesh_set_source_geometry_mode # bindNavigationMesh_set_source_geometry_mode :: MethodBind bindNavigationMesh_set_source_geometry_mode = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_source_geometry_mode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_source_geometry_mode :: (NavigationMesh :< cls, Object :< cls) => cls -> Int -> IO () set_source_geometry_mode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_source_geometry_mode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_source_geometry_mode" '[Int] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_source_geometry_mode # NOINLINE bindNavigationMesh_set_source_group_name # bindNavigationMesh_set_source_group_name :: MethodBind bindNavigationMesh_set_source_group_name = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_source_group_name" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_source_group_name :: (NavigationMesh :< cls, Object :< cls) => cls -> GodotString -> IO () set_source_group_name cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_source_group_name (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_source_group_name" '[GodotString] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_source_group_name # NOINLINE bindNavigationMesh_set_vertices # bindNavigationMesh_set_vertices :: MethodBind bindNavigationMesh_set_vertices = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_vertices" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_vertices :: (NavigationMesh :< cls, Object :< cls) => cls -> PoolVector3Array -> IO () set_vertices cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_vertices (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_vertices" '[PoolVector3Array] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_vertices # NOINLINE bindNavigationMesh_set_verts_per_poly # bindNavigationMesh_set_verts_per_poly :: MethodBind bindNavigationMesh_set_verts_per_poly = unsafePerformIO $ withCString "NavigationMesh" $ \ clsNamePtr -> withCString "set_verts_per_poly" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_verts_per_poly :: (NavigationMesh :< cls, Object :< cls) => cls -> Float -> IO () set_verts_per_poly cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindNavigationMesh_set_verts_per_poly (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod NavigationMesh "set_verts_per_poly" '[Float] (IO ()) where nodeMethod = Godot.Core.NavigationMesh.set_verts_per_poly
efa95eba737126bf6317c5abe5ab80019a9924f3b6522018b4006cfc1707d760
gpwwjr/LISA
terminal-node.lisp
This file is part of LISA , the Lisp - based Intelligent Software ;;; Agents platform. Copyright ( C ) 2000 ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License ;;; along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . ;;; File: terminal-node.lisp ;;; Description: $ I d : terminal - node.lisp , v 1.12 2004/09/13 19:27:53 youngde Exp $ (in-package :lisa) (defclass terminal-node () ((rule :initarg :rule :initform nil :reader terminal-node-rule))) (defmethod accept-token ((self terminal-node) (tokens add-token)) (let* ((rule (terminal-node-rule self)) (activation (make-activation rule tokens))) (add-activation (rule-engine rule) activation) (bind-rule-activation rule activation tokens) t)) (defmethod accept-token ((self terminal-node) (tokens remove-token)) (let* ((rule (terminal-node-rule self)) (activation (find-activation-binding rule tokens))) (unless (null activation) (disable-activation (rule-engine rule) activation) (unbind-rule-activation rule tokens)) t)) (defmethod accept-token ((self terminal-node) (token reset-token)) (clear-activation-bindings (terminal-node-rule self)) t) (defmethod print-object ((self terminal-node) strm) (print-unreadable-object (self strm :type t) (format strm "~A" (rule-name (terminal-node-rule self))))) (defun make-terminal-node (rule) (make-instance 'terminal-node :rule rule))
null
https://raw.githubusercontent.com/gpwwjr/LISA/bc7f54b3a9b901d5648d7e9de358e29d3b794c78/src/rete/reference/terminal-node.lisp
lisp
Agents platform. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License either version 2.1 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this library; if not, write to the Free Software File: terminal-node.lisp Description:
This file is part of LISA , the Lisp - based Intelligent Software Copyright ( C ) 2000 of the License , or ( at your option ) any later version . GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . $ I d : terminal - node.lisp , v 1.12 2004/09/13 19:27:53 youngde Exp $ (in-package :lisa) (defclass terminal-node () ((rule :initarg :rule :initform nil :reader terminal-node-rule))) (defmethod accept-token ((self terminal-node) (tokens add-token)) (let* ((rule (terminal-node-rule self)) (activation (make-activation rule tokens))) (add-activation (rule-engine rule) activation) (bind-rule-activation rule activation tokens) t)) (defmethod accept-token ((self terminal-node) (tokens remove-token)) (let* ((rule (terminal-node-rule self)) (activation (find-activation-binding rule tokens))) (unless (null activation) (disable-activation (rule-engine rule) activation) (unbind-rule-activation rule tokens)) t)) (defmethod accept-token ((self terminal-node) (token reset-token)) (clear-activation-bindings (terminal-node-rule self)) t) (defmethod print-object ((self terminal-node) strm) (print-unreadable-object (self strm :type t) (format strm "~A" (rule-name (terminal-node-rule self))))) (defun make-terminal-node (rule) (make-instance 'terminal-node :rule rule))
193e6ddb77b43370f8c38d8f5778ad2fc0e141bcda8964d197a80fac118616c9
replikativ/datahike-server
json_utils.clj
(ns datahike-server.json-utils (:require [clojure.string :as string] [clojure.walk :as walk] [datahike.schema :as s])) (def edn-fmt "application/edn") (def json-fmt "application/json") (def number-re #"\d+(\.\d+)?") (def number-format-instance (java.text.NumberFormat/getInstance)) (defn- filter-value-type-attrs [valtypes schema] (into #{} (filter #(-> % schema :db/valueType valtypes) (keys schema)))) (def ^:private filter-kw-attrs (partial filter-value-type-attrs #{:db.type/keyword :db.type/value :db.type/cardinality :db.type/unique})) (def keyword-valued-schema-attrs (filter-kw-attrs s/implicit-schema-spec)) (defn- int-obj-to-long [i] (if (some? i) (.longValue (java.lang.Integer. i)) (throw (ex-info "Cannot store nil as a value")))) (defn- xf-val [f v] (if (vector? v) (map f v) (f v))) (declare handle-id-or-av-pair) (defn- xf-ref-val [v valtype-attrs-map db] (if (vector? v) (walk/prewalk #(handle-id-or-av-pair % valtype-attrs-map db) v) v)) (defn keywordize-string [s] (if (string? s) (keyword s) s)) (defn ident-for [db a] (if (and (number? a) (some? db)) (.-ident-for db a) a)) (defn cond-xf-val [a-ident v {:keys [ref-attrs long-attrs keyword-attrs symbol-attrs] :as valtype-attrs-map} db] (cond (contains? ref-attrs a-ident) (xf-ref-val v valtype-attrs-map db) (contains? long-attrs a-ident) (xf-val int-obj-to-long v) (contains? keyword-attrs a-ident) (xf-val keyword v) (contains? symbol-attrs a-ident) (xf-val symbol v) :else v)) (defn handle-id-or-av-pair ([v valtype-attrs-map] (handle-id-or-av-pair v valtype-attrs-map nil)) ([v valtype-attrs-map db] (if (and (vector? v) (= (count v) 2)) (let [a (keywordize-string (first v))] [a (cond-xf-val (ident-for db a) (nth v 1) valtype-attrs-map db)]) v))) (defn- xf-tx-data-map [m valtype-attrs-map db] (into {} (map (fn [[a v]] [a (if (= :db/id a) (handle-id-or-av-pair [a v] valtype-attrs-map db) (cond-xf-val a v valtype-attrs-map db))]) m))) (defn- xf-tx-data-vec [tx-vec valtype-attrs-map db] (let [op (first tx-vec) [e a v] (rest tx-vec) a (keywordize-string a)] (vec (filter some? (list (keyword op) (handle-id-or-av-pair e valtype-attrs-map db) a (cond-xf-val (ident-for db a) v valtype-attrs-map db)))))) (defn get-valtype-attrs-map [schema] (let [ref-valued-attrs (filter-value-type-attrs #{:db.type/ref} schema) long-valued-attrs (filter-value-type-attrs #{:db.type/long} schema) kw-valued-attrs (clojure.set/union keyword-valued-schema-attrs (filter-kw-attrs schema)) sym-valued-attrs (filter-value-type-attrs #{:db.type/symbol} schema)] {:ref-attrs ref-valued-attrs :long-attrs long-valued-attrs :keyword-attrs kw-valued-attrs :symbol-attrs sym-valued-attrs})) (defn xf-data-for-tx [tx-data db] (let [valtype-attrs-map (get-valtype-attrs-map (:schema db))] (map #(let [xf-fn (cond (map? %) xf-tx-data-map (vector? %) xf-tx-data-vec ; Q: Is this error appropriate? :else (throw (ex-info "Only maps and vectors allowed in :tx-data and :tx-meta" {:event :handlers/transact :data tx-data})))] (xf-fn % valtype-attrs-map db)) tx-data))) (defn- component-index [c index components] (let [c-index (string/index-of index c)] (if (> (count components) c-index) c-index nil))) (defn xf-datoms-components [index components db] (let [e-index (component-index \e index components) a-index (component-index \a index components) valtype-attrs-map (when (or (> (count components) 2) (some? e-index)) (get-valtype-attrs-map (:schema db))) a (when (some? a-index) (keywordize-string (nth components a-index)))] (cond-> components (some? e-index) (update e-index #(handle-id-or-av-pair % valtype-attrs-map db)) (some? a-index) (assoc a-index a) (> (count components) 2) (update 2 #(cond-xf-val (ident-for db a) % valtype-attrs-map db))))) (defn- strip [s] (subs s 1 (- (count s) 1))) (defn first-char-str [s] (subs s 0 1)) (defn- first-char-is? [s cstr] (= cstr (first-char-str s))) (defn- last-char-str [s] (subs s (- (count s) 1) (count s))) (defn- last-char-is? [s cstr] (= cstr (last-char-str s))) (defn- symbol-or-string [c1 s] (if (and (> (count s) 1) (= c1 (subs s 1 2))) (subs s 1) (symbol s))) (defn- handle-non-singleton-char [s char-str f] (if (> (count s) 1) (cond-> (subs s 1) (not= char-str (subs s 1 2)) f) (throw (ex-info (str "Illegal use of \"" char-str "\" as " s))))) (defn- clojurize-string [s] (let [first-char (subs s 0 1)] (case first-char ":" (handle-non-singleton-char s ":" keyword) "?" (symbol-or-string "?" s) "$" (symbol-or-string "$" s) "." (if (#{"." "..."} s) (symbol s) s) ("+" "-" "*" "/" "_" "%") (if (= (count s) 1) (symbol s) s) ; Q: Or should this be escaped by doubling, for consistency with other special chars? "&" (handle-non-singleton-char s "&" symbol) "n" (if (= s "nil") nil s) s))) (defn clojurize [c] (walk/prewalk #(cond (string? %) (clojurize-string %) (sequential? %) (if (= "!list" (first %)) (apply list (rest %)) %) :else %) c)) (defn clojurize-coll-str [s] (into [] (comp (map #(if (and (first-char-is? % "\"") (last-char-is? % "\"")) (strip %) %)) (map #(if (re-matches number-re %) (.parse number-format-instance %) %))) (string/split (strip s) #" ")))
null
https://raw.githubusercontent.com/replikativ/datahike-server/ec87469832e017bfaff98e86046de85f8e365817/src/clj/datahike_server/json_utils.clj
clojure
Q: Is this error appropriate? Q: Or should this be escaped by doubling, for consistency with other special chars?
(ns datahike-server.json-utils (:require [clojure.string :as string] [clojure.walk :as walk] [datahike.schema :as s])) (def edn-fmt "application/edn") (def json-fmt "application/json") (def number-re #"\d+(\.\d+)?") (def number-format-instance (java.text.NumberFormat/getInstance)) (defn- filter-value-type-attrs [valtypes schema] (into #{} (filter #(-> % schema :db/valueType valtypes) (keys schema)))) (def ^:private filter-kw-attrs (partial filter-value-type-attrs #{:db.type/keyword :db.type/value :db.type/cardinality :db.type/unique})) (def keyword-valued-schema-attrs (filter-kw-attrs s/implicit-schema-spec)) (defn- int-obj-to-long [i] (if (some? i) (.longValue (java.lang.Integer. i)) (throw (ex-info "Cannot store nil as a value")))) (defn- xf-val [f v] (if (vector? v) (map f v) (f v))) (declare handle-id-or-av-pair) (defn- xf-ref-val [v valtype-attrs-map db] (if (vector? v) (walk/prewalk #(handle-id-or-av-pair % valtype-attrs-map db) v) v)) (defn keywordize-string [s] (if (string? s) (keyword s) s)) (defn ident-for [db a] (if (and (number? a) (some? db)) (.-ident-for db a) a)) (defn cond-xf-val [a-ident v {:keys [ref-attrs long-attrs keyword-attrs symbol-attrs] :as valtype-attrs-map} db] (cond (contains? ref-attrs a-ident) (xf-ref-val v valtype-attrs-map db) (contains? long-attrs a-ident) (xf-val int-obj-to-long v) (contains? keyword-attrs a-ident) (xf-val keyword v) (contains? symbol-attrs a-ident) (xf-val symbol v) :else v)) (defn handle-id-or-av-pair ([v valtype-attrs-map] (handle-id-or-av-pair v valtype-attrs-map nil)) ([v valtype-attrs-map db] (if (and (vector? v) (= (count v) 2)) (let [a (keywordize-string (first v))] [a (cond-xf-val (ident-for db a) (nth v 1) valtype-attrs-map db)]) v))) (defn- xf-tx-data-map [m valtype-attrs-map db] (into {} (map (fn [[a v]] [a (if (= :db/id a) (handle-id-or-av-pair [a v] valtype-attrs-map db) (cond-xf-val a v valtype-attrs-map db))]) m))) (defn- xf-tx-data-vec [tx-vec valtype-attrs-map db] (let [op (first tx-vec) [e a v] (rest tx-vec) a (keywordize-string a)] (vec (filter some? (list (keyword op) (handle-id-or-av-pair e valtype-attrs-map db) a (cond-xf-val (ident-for db a) v valtype-attrs-map db)))))) (defn get-valtype-attrs-map [schema] (let [ref-valued-attrs (filter-value-type-attrs #{:db.type/ref} schema) long-valued-attrs (filter-value-type-attrs #{:db.type/long} schema) kw-valued-attrs (clojure.set/union keyword-valued-schema-attrs (filter-kw-attrs schema)) sym-valued-attrs (filter-value-type-attrs #{:db.type/symbol} schema)] {:ref-attrs ref-valued-attrs :long-attrs long-valued-attrs :keyword-attrs kw-valued-attrs :symbol-attrs sym-valued-attrs})) (defn xf-data-for-tx [tx-data db] (let [valtype-attrs-map (get-valtype-attrs-map (:schema db))] (map #(let [xf-fn (cond (map? %) xf-tx-data-map (vector? %) xf-tx-data-vec :else (throw (ex-info "Only maps and vectors allowed in :tx-data and :tx-meta" {:event :handlers/transact :data tx-data})))] (xf-fn % valtype-attrs-map db)) tx-data))) (defn- component-index [c index components] (let [c-index (string/index-of index c)] (if (> (count components) c-index) c-index nil))) (defn xf-datoms-components [index components db] (let [e-index (component-index \e index components) a-index (component-index \a index components) valtype-attrs-map (when (or (> (count components) 2) (some? e-index)) (get-valtype-attrs-map (:schema db))) a (when (some? a-index) (keywordize-string (nth components a-index)))] (cond-> components (some? e-index) (update e-index #(handle-id-or-av-pair % valtype-attrs-map db)) (some? a-index) (assoc a-index a) (> (count components) 2) (update 2 #(cond-xf-val (ident-for db a) % valtype-attrs-map db))))) (defn- strip [s] (subs s 1 (- (count s) 1))) (defn first-char-str [s] (subs s 0 1)) (defn- first-char-is? [s cstr] (= cstr (first-char-str s))) (defn- last-char-str [s] (subs s (- (count s) 1) (count s))) (defn- last-char-is? [s cstr] (= cstr (last-char-str s))) (defn- symbol-or-string [c1 s] (if (and (> (count s) 1) (= c1 (subs s 1 2))) (subs s 1) (symbol s))) (defn- handle-non-singleton-char [s char-str f] (if (> (count s) 1) (cond-> (subs s 1) (not= char-str (subs s 1 2)) f) (throw (ex-info (str "Illegal use of \"" char-str "\" as " s))))) (defn- clojurize-string [s] (let [first-char (subs s 0 1)] (case first-char ":" (handle-non-singleton-char s ":" keyword) "?" (symbol-or-string "?" s) "$" (symbol-or-string "$" s) "." (if (#{"." "..."} s) (symbol s) s) ("+" "-" "*" "/" "_" "%") (if (= (count s) 1) (symbol s) "&" (handle-non-singleton-char s "&" symbol) "n" (if (= s "nil") nil s) s))) (defn clojurize [c] (walk/prewalk #(cond (string? %) (clojurize-string %) (sequential? %) (if (= "!list" (first %)) (apply list (rest %)) %) :else %) c)) (defn clojurize-coll-str [s] (into [] (comp (map #(if (and (first-char-is? % "\"") (last-char-is? % "\"")) (strip %) %)) (map #(if (re-matches number-re %) (.parse number-format-instance %) %))) (string/split (strip s) #" ")))
5693229b51c16910b25b45c2fb5c2acb0160ea0b590119f10ebbcdc5719cae55
KingoftheHomeless/Cofree-Traversable-Functors
Cofree.hs
# LANGUAGE DataKinds , DeriveTraversable , GADTs # # LANGUAGE RankNTypes , ScopedTypeVariables , StandaloneDeriving # module Data.Traversable.Cofree ( module Data.Nat, module Data.Fin, module Data.Vec, module Data.Traversable, Cotra(..), unit, counit, hoist, fromTraversal ) where import Data.Batch import Data.Nat import Data.Fin import Data.Vec import Data.Traversable | The representational encoding of . -- Members of this type are representational triples. data Cotra f a where Cotra :: SNat n -> f (Fin n) -> Vec n a -> Cotra f a deriving instance Functor (Cotra f) deriving instance Foldable (Cotra f) deriving instance Traversable (Cotra f) -- | Calculates the characterization of any traversable container, -- effectively decoupling the elements of the container from -- its shape. unit :: Traversable t => t a -> Cotra t a unit = fromTraversal traverse -- | Integrates the elements into the shape, creating a container of the base functor. counit :: Functor f => Cotra f a -> f a counit (Cotra _ s l) = fmap (index l) s -- | Applies the natural transformation to the shape of a triple. hoist :: (forall x. f x -> g x) -> Cotra f a -> Cotra g a hoist nat (Cotra n s l) = Cotra n (nat s) l -- | Like 'unit', but the traversal under which the characterization -- is calculated is provided explicitly. fromTraversal :: forall s f a. ( forall x. (a -> Batch a x x) -> s -> Batch a x (f x) ) -> s -> Cotra f a fromTraversal tr s = let g :: forall x. Batch a x (f x) g = tr batch s in case g of P h -> Cotra SZ h End r :*: a -> case makeElems r (SomeNEVec (a :- End)) of SomeNEVec (elems :: Vec ('S n) a) -> let sz :: SNat n SS sz = vecToSNat elems shape :: f (Fin ('S n)) shape = makeShape (toFin sz) g in Cotra (SS sz) shape elems where makeElems :: Batch a b c -> SomeNEVec a -> SomeNEVec a makeElems (r :*: a) (SomeNEVec v) = makeElems r (SomeNEVec (a :- v)) makeElems _ v = v makeShape :: Fin ('S n) -> Batch a (Fin ('S n)) c -> c makeShape FZ (P l :*: _) = l FZ makeShape (FS n) (r :*: _) = makeShape (raise n) r (FS n) makeShape _ _ = error "Impossible: elements of g dependent on type"
null
https://raw.githubusercontent.com/KingoftheHomeless/Cofree-Traversable-Functors/40289b1f5ec151da10ab625102527432e84d6743/src/Data/Traversable/Cofree.hs
haskell
Members of this type are representational triples. | Calculates the characterization of any traversable container, effectively decoupling the elements of the container from its shape. | Integrates the elements into the shape, creating a container of the base functor. | Applies the natural transformation to the shape of a triple. | Like 'unit', but the traversal under which the characterization is calculated is provided explicitly.
# LANGUAGE DataKinds , DeriveTraversable , GADTs # # LANGUAGE RankNTypes , ScopedTypeVariables , StandaloneDeriving # module Data.Traversable.Cofree ( module Data.Nat, module Data.Fin, module Data.Vec, module Data.Traversable, Cotra(..), unit, counit, hoist, fromTraversal ) where import Data.Batch import Data.Nat import Data.Fin import Data.Vec import Data.Traversable | The representational encoding of . data Cotra f a where Cotra :: SNat n -> f (Fin n) -> Vec n a -> Cotra f a deriving instance Functor (Cotra f) deriving instance Foldable (Cotra f) deriving instance Traversable (Cotra f) unit :: Traversable t => t a -> Cotra t a unit = fromTraversal traverse counit :: Functor f => Cotra f a -> f a counit (Cotra _ s l) = fmap (index l) s hoist :: (forall x. f x -> g x) -> Cotra f a -> Cotra g a hoist nat (Cotra n s l) = Cotra n (nat s) l fromTraversal :: forall s f a. ( forall x. (a -> Batch a x x) -> s -> Batch a x (f x) ) -> s -> Cotra f a fromTraversal tr s = let g :: forall x. Batch a x (f x) g = tr batch s in case g of P h -> Cotra SZ h End r :*: a -> case makeElems r (SomeNEVec (a :- End)) of SomeNEVec (elems :: Vec ('S n) a) -> let sz :: SNat n SS sz = vecToSNat elems shape :: f (Fin ('S n)) shape = makeShape (toFin sz) g in Cotra (SS sz) shape elems where makeElems :: Batch a b c -> SomeNEVec a -> SomeNEVec a makeElems (r :*: a) (SomeNEVec v) = makeElems r (SomeNEVec (a :- v)) makeElems _ v = v makeShape :: Fin ('S n) -> Batch a (Fin ('S n)) c -> c makeShape FZ (P l :*: _) = l FZ makeShape (FS n) (r :*: _) = makeShape (raise n) r (FS n) makeShape _ _ = error "Impossible: elements of g dependent on type"
b8eb61b50f26ec19b3c28bf5906e4113914b37b820f96b90f45eda7e6bfdade3
OCamlPro/OCamlPro-OCaml-Branch
kb.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : 2553 1999 - 11 - 17 18:59:06Z xleroy $ open Terms open Equations (****************** Critical pairs *********************) All ( u , subst ) such that N / u ( & var ) unifies with M , with principal unifier subst with principal unifier subst *) let rec super m = function Term(_,sons) as n -> let rec collate n = function [] -> [] | son::rest -> List.map (fun (u, subst) -> (n::u, subst)) (super m son) @ collate (n+1) rest in let insides = collate 1 sons in begin try ([], unify m n) :: insides with Failure _ -> insides end | _ -> [] Ex : let ( m , _ ) = < < F(A , B ) > > and ( n , _ ) = < < H(F(A , x),F(x , y ) ) > > in super m n = = > [ [ 1],[2,Term ( " B " , [ ] ) ] ; x < - B [ 2],[2,Term ( " A " , [ ] ) ; 1,Term ( " B " , [ ] ) ] ] x < - A y < - B let (m,_) = <<F(A,B)>> and (n,_) = <<H(F(A,x),F(x,y))>> in super m n ==> [[1],[2,Term ("B",[])]; x <- B [2],[2,Term ("A",[]); 1,Term ("B",[])]] x <- A y <- B *) All ( u , subst ) , u & [ ] , such that n / u unifies with m let super_strict m = function Term(_,sons) -> let rec collate n = function [] -> [] | son::rest -> List.map (fun (u, subst) -> (n::u, subst)) (super m son) @ collate (n+1) rest in collate 1 sons | _ -> [] (* Critical pairs of l1=r1 with l2=r2 *) (* critical_pairs : term_pair -> term_pair -> term_pair list *) let critical_pairs (l1,r1) (l2,r2) = let mk_pair (u,subst) = substitute subst (replace l2 u r1), substitute subst r2 in List.map mk_pair (super l1 l2) (* Strict critical pairs of l1=r1 with l2=r2 *) strict_critical_pairs : term_pair - > term_pair - > term_pair list let strict_critical_pairs (l1,r1) (l2,r2) = let mk_pair (u,subst) = substitute subst (replace l2 u r1), substitute subst r2 in List.map mk_pair (super_strict l1 l2) All critical pairs of eq1 with eq2 let mutual_critical_pairs eq1 eq2 = (strict_critical_pairs eq1 eq2) @ (critical_pairs eq2 eq1) (* Renaming of variables *) let rename n (t1,t2) = let rec ren_rec = function Var k -> Var(k+n) | Term(op,sons) -> Term(op, List.map ren_rec sons) in (ren_rec t1, ren_rec t2) (************************ Completion ******************************) let deletion_message rule = print_string "Rule ";print_int rule.number; print_string " deleted"; print_newline() (* Generate failure message *) let non_orientable (m,n) = pretty_term m; print_string " = "; pretty_term n; print_newline() let rec partition p = function [] -> ([], []) | x::l -> let (l1, l2) = partition p l in if p x then (x::l1, l2) else (l1, x::l2) let rec get_rule n = function [] -> raise Not_found | r::l -> if n = r.number then r else get_rule n l Improved Knuth - Bendix completion procedure let kb_completion greater = let rec kbrec j rules = let rec process failures (k,l) eqs = * * * print_string " * * * kb_completion " ; print_int j ; print_newline ( ) ; pretty_rules rules ; List.iter non_orientable failures ; print_int k ; print_string " " ; print_int l ; print_newline ( ) ; List.iter non_orientable eqs ; * * print_string "***kb_completion "; print_int j; print_newline(); pretty_rules rules; List.iter non_orientable failures; print_int k; print_string " "; print_int l; print_newline(); List.iter non_orientable eqs; ***) match eqs with [] -> if k<l then next_criticals failures (k+1,l) else if l<j then next_criticals failures (1,l+1) else begin match failures with [] -> rules (* successful completion *) | _ -> print_string "Non-orientable equations :"; print_newline(); List.iter non_orientable failures; failwith "kb_completion" end | (m,n)::eqs -> let m' = mrewrite_all rules m and n' = mrewrite_all rules n and enter_rule(left,right) = let new_rule = mk_rule (j+1) left right in pretty_rule new_rule; let left_reducible rule = reducible left rule.lhs in let (redl,irredl) = partition left_reducible rules in List.iter deletion_message redl; let right_reduce rule = mk_rule rule.number rule.lhs (mrewrite_all (new_rule::rules) rule.rhs) in let irreds = List.map right_reduce irredl in let eqs' = List.map (fun rule -> (rule.lhs, rule.rhs)) redl in kbrec (j+1) (new_rule::irreds) [] (k,l) (eqs @ eqs' @ failures) in (*** print_string "--- Considering "; non_orientable (m', n'); ***) if m' = n' then process failures (k,l) eqs else if greater(m',n') then enter_rule(m',n') else if greater(n',m') then enter_rule(n',m') else process ((m',n')::failures) (k,l) eqs and next_criticals failures (k,l) = * * * print_string " * * * next_criticals " ; print_int k ; print_string " " ; print_int l ; print_newline ( ) ; * * * print_string "***next_criticals "; print_int k; print_string " "; print_int l ; print_newline(); ****) try let rl = get_rule l rules in let el = (rl.lhs, rl.rhs) in if k=l then process failures (k,l) (strict_critical_pairs el (rename rl.numvars el)) else try let rk = get_rule k rules in let ek = (rk.lhs, rk.rhs) in process failures (k,l) (mutual_critical_pairs el (rename rl.numvars ek)) with Not_found -> next_criticals failures (k+1,l) with Not_found -> next_criticals failures (1,l+1) in process in kbrec complete_rules is assumed locally confluent , and checked with ordering greater , rules is any list of rules ordering greater, rules is any list of rules *) let kb_complete greater complete_rules rules = let n = check_rules complete_rules and eqs = List.map (fun rule -> (rule.lhs, rule.rhs)) rules in let completed_rules = kb_completion greater n complete_rules [] (n,n) eqs in print_string "Canonical set found :"; print_newline(); pretty_rules (List.rev completed_rules)
null
https://raw.githubusercontent.com/OCamlPro/OCamlPro-OCaml-Branch/3a522985649389f89dac73e655d562c54f0456a5/inline-more/testsuite/tests/misc-kb/kb.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* ***************** Critical pairs ******************** Critical pairs of l1=r1 with l2=r2 critical_pairs : term_pair -> term_pair -> term_pair list Strict critical pairs of l1=r1 with l2=r2 Renaming of variables *********************** Completion ***************************** Generate failure message successful completion ** print_string "--- Considering "; non_orientable (m', n'); **
, 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 Q Public License version 1.0 . $ I d : 2553 1999 - 11 - 17 18:59:06Z xleroy $ open Terms open Equations All ( u , subst ) such that N / u ( & var ) unifies with M , with principal unifier subst with principal unifier subst *) let rec super m = function Term(_,sons) as n -> let rec collate n = function [] -> [] | son::rest -> List.map (fun (u, subst) -> (n::u, subst)) (super m son) @ collate (n+1) rest in let insides = collate 1 sons in begin try ([], unify m n) :: insides with Failure _ -> insides end | _ -> [] Ex : let ( m , _ ) = < < F(A , B ) > > and ( n , _ ) = < < H(F(A , x),F(x , y ) ) > > in super m n = = > [ [ 1],[2,Term ( " B " , [ ] ) ] ; x < - B [ 2],[2,Term ( " A " , [ ] ) ; 1,Term ( " B " , [ ] ) ] ] x < - A y < - B let (m,_) = <<F(A,B)>> and (n,_) = <<H(F(A,x),F(x,y))>> in super m n ==> [[1],[2,Term ("B",[])]; x <- B [2],[2,Term ("A",[]); 1,Term ("B",[])]] x <- A y <- B *) All ( u , subst ) , u & [ ] , such that n / u unifies with m let super_strict m = function Term(_,sons) -> let rec collate n = function [] -> [] | son::rest -> List.map (fun (u, subst) -> (n::u, subst)) (super m son) @ collate (n+1) rest in collate 1 sons | _ -> [] let critical_pairs (l1,r1) (l2,r2) = let mk_pair (u,subst) = substitute subst (replace l2 u r1), substitute subst r2 in List.map mk_pair (super l1 l2) strict_critical_pairs : term_pair - > term_pair - > term_pair list let strict_critical_pairs (l1,r1) (l2,r2) = let mk_pair (u,subst) = substitute subst (replace l2 u r1), substitute subst r2 in List.map mk_pair (super_strict l1 l2) All critical pairs of eq1 with eq2 let mutual_critical_pairs eq1 eq2 = (strict_critical_pairs eq1 eq2) @ (critical_pairs eq2 eq1) let rename n (t1,t2) = let rec ren_rec = function Var k -> Var(k+n) | Term(op,sons) -> Term(op, List.map ren_rec sons) in (ren_rec t1, ren_rec t2) let deletion_message rule = print_string "Rule ";print_int rule.number; print_string " deleted"; print_newline() let non_orientable (m,n) = pretty_term m; print_string " = "; pretty_term n; print_newline() let rec partition p = function [] -> ([], []) | x::l -> let (l1, l2) = partition p l in if p x then (x::l1, l2) else (l1, x::l2) let rec get_rule n = function [] -> raise Not_found | r::l -> if n = r.number then r else get_rule n l Improved Knuth - Bendix completion procedure let kb_completion greater = let rec kbrec j rules = let rec process failures (k,l) eqs = * * * print_string " * * * kb_completion " ; print_int j ; print_newline ( ) ; pretty_rules rules ; List.iter non_orientable failures ; print_int k ; print_string " " ; print_int l ; print_newline ( ) ; List.iter non_orientable eqs ; * * print_string "***kb_completion "; print_int j; print_newline(); pretty_rules rules; List.iter non_orientable failures; print_int k; print_string " "; print_int l; print_newline(); List.iter non_orientable eqs; ***) match eqs with [] -> if k<l then next_criticals failures (k+1,l) else if l<j then next_criticals failures (1,l+1) else begin match failures with | _ -> print_string "Non-orientable equations :"; print_newline(); List.iter non_orientable failures; failwith "kb_completion" end | (m,n)::eqs -> let m' = mrewrite_all rules m and n' = mrewrite_all rules n and enter_rule(left,right) = let new_rule = mk_rule (j+1) left right in pretty_rule new_rule; let left_reducible rule = reducible left rule.lhs in let (redl,irredl) = partition left_reducible rules in List.iter deletion_message redl; let right_reduce rule = mk_rule rule.number rule.lhs (mrewrite_all (new_rule::rules) rule.rhs) in let irreds = List.map right_reduce irredl in let eqs' = List.map (fun rule -> (rule.lhs, rule.rhs)) redl in kbrec (j+1) (new_rule::irreds) [] (k,l) (eqs @ eqs' @ failures) in if m' = n' then process failures (k,l) eqs else if greater(m',n') then enter_rule(m',n') else if greater(n',m') then enter_rule(n',m') else process ((m',n')::failures) (k,l) eqs and next_criticals failures (k,l) = * * * print_string " * * * next_criticals " ; print_int k ; print_string " " ; print_int l ; print_newline ( ) ; * * * print_string "***next_criticals "; print_int k; print_string " "; print_int l ; print_newline(); ****) try let rl = get_rule l rules in let el = (rl.lhs, rl.rhs) in if k=l then process failures (k,l) (strict_critical_pairs el (rename rl.numvars el)) else try let rk = get_rule k rules in let ek = (rk.lhs, rk.rhs) in process failures (k,l) (mutual_critical_pairs el (rename rl.numvars ek)) with Not_found -> next_criticals failures (k+1,l) with Not_found -> next_criticals failures (1,l+1) in process in kbrec complete_rules is assumed locally confluent , and checked with ordering greater , rules is any list of rules ordering greater, rules is any list of rules *) let kb_complete greater complete_rules rules = let n = check_rules complete_rules and eqs = List.map (fun rule -> (rule.lhs, rule.rhs)) rules in let completed_rules = kb_completion greater n complete_rules [] (n,n) eqs in print_string "Canonical set found :"; print_newline(); pretty_rules (List.rev completed_rules)
b5aa2f113067e49a56a3cbfba4df052e50411bcd65e9dfa9c092150246d8c2c6
nasa/Common-Metadata-Repository
core.clj
(ns cmr.exchange.common.components.core (:require [cmr.exchange.common.components.config :as config] [cmr.exchange.common.components.logging :as logging] [com.stuartsierra.component :as component])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Common Configuration Components ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def cfg {:config (config/create-component)}) (def log {:logging (component/using (logging/create-component) [:config])}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Component Initializations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn initialize-without-logging [] (component/map->SystemMap cfg)) (defn initialize [] (component/map->SystemMap (merge cfg log))) (def init-lookup {:no-logging #'initialize-without-logging :main #'initialize}) (defn init ([] (init :main)) ([mode] ((mode init-lookup))))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/exchange-common/src/cmr/exchange/common/components/core.clj
clojure
Common Configuration Components ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Component Initializations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cmr.exchange.common.components.core (:require [cmr.exchange.common.components.config :as config] [cmr.exchange.common.components.logging :as logging] [com.stuartsierra.component :as component])) (def cfg {:config (config/create-component)}) (def log {:logging (component/using (logging/create-component) [:config])}) (defn initialize-without-logging [] (component/map->SystemMap cfg)) (defn initialize [] (component/map->SystemMap (merge cfg log))) (def init-lookup {:no-logging #'initialize-without-logging :main #'initialize}) (defn init ([] (init :main)) ([mode] ((mode init-lookup))))
733a1d7f755bdcb7417c775397bca586d7c10af26f43f156e732b9a062de0e1f
vert-x/mod-lang-clojure
config_to_eb.clj
Copyright 2013 the original author or authors . ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns deployments.config-to-eb (:require [vertx.core :as core] [vertx.http :as http])) (println "TC: LOADED") (let [cfg (core/config)] (-> (http/server) (http/on-request (fn [req] (-> (http/server-response req) (http/end (pr-str cfg))))) (http/listen (:port cfg))))
null
https://raw.githubusercontent.com/vert-x/mod-lang-clojure/dcf713460b8f46c08d0db6e7bf8537f1dd91f297/lang-module/src/test/resources/embed/config_to_eb.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2013 the original author or authors . distributed under the License is distributed on an " AS IS " BASIS , (ns deployments.config-to-eb (:require [vertx.core :as core] [vertx.http :as http])) (println "TC: LOADED") (let [cfg (core/config)] (-> (http/server) (http/on-request (fn [req] (-> (http/server-response req) (http/end (pr-str cfg))))) (http/listen (:port cfg))))
9e09dbe5e1d02ce80c90843ae8a59f53b6d50b5f73ea94fd2c2d8a5cb5a21e51
bhauman/advent-of-clojure
day12.clj
(ns advent-2015.day12 (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.walk :refer [prewalk]])) (def prob12 (slurp (io/resource "2015/prob12"))) part 1 #_(reduce + (map read-string (re-seq #"[-]{0,1}\d+" prob12))) part 2 (defn has-red? [m] (some (fn [me] ((set me) "red")) m)) #_(as-> prob12 a (string/replace a ":" " ") (read-string a) (prewalk #(cond (and (map? %) (has-red? %)) nil (map? %) (seq %) :else %) a) (flatten a) (filter integer? a) (reduce + a))
null
https://raw.githubusercontent.com/bhauman/advent-of-clojure/856763baf45bf7bf452ffd304dc1b89f9bc879a6/src/advent-2015/day12.clj
clojure
(ns advent-2015.day12 (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.walk :refer [prewalk]])) (def prob12 (slurp (io/resource "2015/prob12"))) part 1 #_(reduce + (map read-string (re-seq #"[-]{0,1}\d+" prob12))) part 2 (defn has-red? [m] (some (fn [me] ((set me) "red")) m)) #_(as-> prob12 a (string/replace a ":" " ") (read-string a) (prewalk #(cond (and (map? %) (has-red? %)) nil (map? %) (seq %) :else %) a) (flatten a) (filter integer? a) (reduce + a))
19c57d2d4b9fea6f0b2b6f2f2b6521fdb37bbff054b6b14b7c0c0eaf5c87e0ac
nodename/clevolution
imagefunctions.clj
(ns clevolution.app.imagefunctions (:require [seesaw.core :as seesaw] [seesaw.widget-options :refer [widget-option-provider]] [mikera.image.core :as img] [clevolution.file-input :refer [read-image-from-file]]) (:import [mikera.gui JIcon] [java.awt Dimension] [java.awt.image BufferedImage])) (defonce PENDING-IMAGE (read-image-from-file "resources/Pending.png")) (defonce ERROR-IMAGE (read-image-from-file "resources/Error.png")) Make JIcon play nice with seesaw : (widget-option-provider mikera.gui.JIcon seesaw/default-options) (defn to-display-size [^BufferedImage bi ^long size] (let [factor (/ size (.getWidth bi))] (img/zoom bi factor))) (defn make-image-icon [image size] (doto (JIcon. ^BufferedImage (to-display-size image size)) (.setMinimumSize (Dimension. size size)) (.setMaximumSize (Dimension. size size))))
null
https://raw.githubusercontent.com/nodename/clevolution/e0302d788826d6408076471a724fbe6352dddd82/src/clj/clevolution/app/imagefunctions.clj
clojure
(ns clevolution.app.imagefunctions (:require [seesaw.core :as seesaw] [seesaw.widget-options :refer [widget-option-provider]] [mikera.image.core :as img] [clevolution.file-input :refer [read-image-from-file]]) (:import [mikera.gui JIcon] [java.awt Dimension] [java.awt.image BufferedImage])) (defonce PENDING-IMAGE (read-image-from-file "resources/Pending.png")) (defonce ERROR-IMAGE (read-image-from-file "resources/Error.png")) Make JIcon play nice with seesaw : (widget-option-provider mikera.gui.JIcon seesaw/default-options) (defn to-display-size [^BufferedImage bi ^long size] (let [factor (/ size (.getWidth bi))] (img/zoom bi factor))) (defn make-image-icon [image size] (doto (JIcon. ^BufferedImage (to-display-size image size)) (.setMinimumSize (Dimension. size size)) (.setMaximumSize (Dimension. size size))))
30b273bfb6e0e6d8193a5451a39d2a8bd3b6c0b138af584e0a17d3574f723717
alexbecker/formal-morality
Morality.hs
module Morality where import Data.Maybe import Data.List import Control.Applicative import Preorder import ProbDist import Norm type WorldState = String type PossibleState = ProbDist WorldState type MoralTheory = PreorderFamily PossibleState invert :: (Eq a) => (a -> a) -> [a] -> a -> a invert f domain x = fromJust $ find ((== x) . f) domain -- infer a moral theory from adjacency lists approximating each preorder -- and functions from your own states to those of others inferMoralTheory :: [AdjacencyList PossibleState] -> [WorldState -> WorldState] -> MoralTheory inferMoralTheory adjLists fs = isoSubFamily $ map (\n -> (fromAdjListNormed $ adjLists !! n, map (\m -> fmap $ (fs !! m) . invert (fs !! n) domain) [0..maxind])) [0..maxind] where maxind = length adjLists - 1 domain = concat $ map getEvents $ map fst $ head adjLists -- randomize a list of possible states across the moral community veil :: MoralTheory -> PossibleState -> PossibleState veil theory state = scale (1.0 / fromIntegral (length theory)) $ foldr1 add $ (snd $ head theory) <*> return state -- same as above, but ignore self (assumes self's preferences have index 0) veilMinusSelf :: MoralTheory -> PossibleState -> PossibleState veilMinusSelf theory state = scale (1.0 / fromIntegral (length theory - 1)) $ foldr1 add $ (tail $ snd $ head theory) <*> return state -- judges which state is Just (punnyness >9000), or Nothing judge :: MoralTheory -> PossibleState -> PossibleState -> Maybe PossibleState judge theory state1 state2 = case (comp (veil theory state1) (veil theory state2), comp (veilMinusSelf theory state1) (veilMinusSelf theory state2)) of (PGT, PGT) -> Just state1 (PLT, PLT) -> Just state2 _ -> Nothing where comp = pCompare $ fst $ head theory
null
https://raw.githubusercontent.com/alexbecker/formal-morality/64d1751924a6f06834c8cd1a287b22a814e43e4a/Morality.hs
haskell
infer a moral theory from adjacency lists approximating each preorder and functions from your own states to those of others randomize a list of possible states across the moral community same as above, but ignore self (assumes self's preferences have index 0) judges which state is Just (punnyness >9000), or Nothing
module Morality where import Data.Maybe import Data.List import Control.Applicative import Preorder import ProbDist import Norm type WorldState = String type PossibleState = ProbDist WorldState type MoralTheory = PreorderFamily PossibleState invert :: (Eq a) => (a -> a) -> [a] -> a -> a invert f domain x = fromJust $ find ((== x) . f) domain inferMoralTheory :: [AdjacencyList PossibleState] -> [WorldState -> WorldState] -> MoralTheory inferMoralTheory adjLists fs = isoSubFamily $ map (\n -> (fromAdjListNormed $ adjLists !! n, map (\m -> fmap $ (fs !! m) . invert (fs !! n) domain) [0..maxind])) [0..maxind] where maxind = length adjLists - 1 domain = concat $ map getEvents $ map fst $ head adjLists veil :: MoralTheory -> PossibleState -> PossibleState veil theory state = scale (1.0 / fromIntegral (length theory)) $ foldr1 add $ (snd $ head theory) <*> return state veilMinusSelf :: MoralTheory -> PossibleState -> PossibleState veilMinusSelf theory state = scale (1.0 / fromIntegral (length theory - 1)) $ foldr1 add $ (tail $ snd $ head theory) <*> return state judge :: MoralTheory -> PossibleState -> PossibleState -> Maybe PossibleState judge theory state1 state2 = case (comp (veil theory state1) (veil theory state2), comp (veilMinusSelf theory state1) (veilMinusSelf theory state2)) of (PGT, PGT) -> Just state1 (PLT, PLT) -> Just state2 _ -> Nothing where comp = pCompare $ fst $ head theory
336bd87bd30da640419a46ca49d97b88128d1bfca0715d0a9a38a21eee3e017c
vehicle-lang/vehicle
AnnotationRestrictions.hs
module Vehicle.Compile.Type.Subsystem.Polarity.AnnotationRestrictions ( assertUnquantifiedPolarity, checkNetworkType, ) where import Vehicle.Compile.Error import Vehicle.Compile.Normalise.Quote (Quote (..)) import Vehicle.Compile.Prelude import Vehicle.Compile.Type.Core import Vehicle.Compile.Type.Monad import Vehicle.Compile.Type.Subsystem.Polarity.Core import Vehicle.Expr.Normalised checkNetworkType :: forall m. MonadTypeChecker PolarityType m => DeclProvenance -> GluedType PolarityType -> m (CheckedType PolarityType) checkNetworkType (_, p) networkType = case normalised networkType of -- \|Decomposes the Pi types in a network type signature, checking that the -- binders are explicit and their types are equal. Returns a function that prepends the linearity constraint . VPi binder result -> do inputPol <- quote mempty 0 (typeOf binder) outputPol <- quote mempty 0 result createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) inputPol createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) outputPol return $ unnormalised networkType _ -> compilerDeveloperError "Invalid network type should have been caught by the main type system" assertUnquantifiedPolarity :: MonadTypeChecker PolarityType m => DeclProvenance -> GluedType PolarityType -> m (CheckedType PolarityType) assertUnquantifiedPolarity (_, p) t = do createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) (unnormalised t) return $ unnormalised t
null
https://raw.githubusercontent.com/vehicle-lang/vehicle/3a3548f9b48c3969212ccb51e954d4d4556ea815/vehicle/src/Vehicle/Compile/Type/Subsystem/Polarity/AnnotationRestrictions.hs
haskell
\|Decomposes the Pi types in a network type signature, checking that the binders are explicit and their types are equal. Returns a function that
module Vehicle.Compile.Type.Subsystem.Polarity.AnnotationRestrictions ( assertUnquantifiedPolarity, checkNetworkType, ) where import Vehicle.Compile.Error import Vehicle.Compile.Normalise.Quote (Quote (..)) import Vehicle.Compile.Prelude import Vehicle.Compile.Type.Core import Vehicle.Compile.Type.Monad import Vehicle.Compile.Type.Subsystem.Polarity.Core import Vehicle.Expr.Normalised checkNetworkType :: forall m. MonadTypeChecker PolarityType m => DeclProvenance -> GluedType PolarityType -> m (CheckedType PolarityType) checkNetworkType (_, p) networkType = case normalised networkType of prepends the linearity constraint . VPi binder result -> do inputPol <- quote mempty 0 (typeOf binder) outputPol <- quote mempty 0 result createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) inputPol createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) outputPol return $ unnormalised networkType _ -> compilerDeveloperError "Invalid network type should have been caught by the main type system" assertUnquantifiedPolarity :: MonadTypeChecker PolarityType m => DeclProvenance -> GluedType PolarityType -> m (CheckedType PolarityType) assertUnquantifiedPolarity (_, p) t = do createFreshUnificationConstraint p mempty CheckingAuxiliary (PolarityExpr p Unquantified) (unnormalised t) return $ unnormalised t
944057d9d090566739afbf774d9b8783a5bbe2a234ceb73075f8bcbe13ec23f6
binsec/haunted
infos.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2019 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 ) . (* *) (**************************************************************************) type instruction_kinds = Dba.Instr.t list type widening_delay = int module BoundThreshold = struct type t = { los : int array; his : int array; } let default = { los = [| |]; his = [| |]; } let mk_from_list (los: int list) (his : int list) : t = { los = Array.of_list los; his = Array.of_list his; } let is_unspecified bthreshold = Array.length bthreshold.los = 0 && Array.length bthreshold.his = 0 end module WideningThreshold = struct type t = { signed : BoundThreshold.t; unsigned : BoundThreshold.t; } let mk signed unsigned = { signed; unsigned; } let default = { signed = BoundThreshold.default; unsigned = BoundThreshold.default ; } let is_unspecified (wthreshold : t) = BoundThreshold.is_unspecified wthreshold.signed && BoundThreshold.is_unspecified wthreshold.unsigned (* Translation function to legacy structure *) let flatten_to_arrays_tuple wthreshold = let open BoundThreshold in wthreshold.signed.his, wthreshold.signed.los, wthreshold.unsigned.his, wthreshold.unsigned.los end let default_global_widening_thresholds = WideningThreshold.default and default_global_widening_delay = 0 type t = { entry_points : Virtual_address.Set.t; jumps : Dba.addresses Dba_types.Caddress.Map.t ; allowed_jumpzones : (Dba.address * Dba.address) list ; stops : Dba_types.Caddress.Set.t ; prepend_stubs : instruction_kinds Dba_types.Caddress.Map.t ; substitute_stubs : Dba_types.instruction_sequence Dba_types.Caddress.Map.t ; linear_addresses : (Virtual_address.t * Virtual_address.t) list ; global_widening : WideningThreshold.t * widening_delay ; local_widening_thresholds : WideningThreshold.t Dba_types.Caddress.Map.t ; local_widening_delays : widening_delay Dba_types.Caddress.Map.t ; } let default = { entry_points = Virtual_address.Set.empty; jumps = Dba_types.Caddress.Map.empty; allowed_jumpzones = []; stops = Dba_types.Caddress.Set.empty; substitute_stubs = Dba_types.Caddress.Map.empty; prepend_stubs = Dba_types.Caddress.Map.empty; linear_addresses = []; global_widening = default_global_widening_thresholds, default_global_widening_delay; local_widening_thresholds = Dba_types.Caddress.Map.empty; local_widening_delays = Dba_types.Caddress.Map.empty; } let empty = default let has_entry_points p = not (Virtual_address.Set.is_empty p.entry_points) let has_stops p = not (Dba_types.Caddress.Set.is_empty p.stops) let has_jumps p = not (Dba_types.Caddress.Map.is_empty p.jumps) let has_allowed_jumpzones p = not (List_utils.is_empty p.allowed_jumpzones) let has_prepend_stubs p = not (Dba_types.Caddress.Map.is_empty p.prepend_stubs) let has_substitute_stubs p = not (Dba_types.Caddress.Map.is_empty p.substitute_stubs) let has_linear_addresses p = not (List_utils.is_empty p.linear_addresses) FIXME : in the next 2 functions * If those values are set to default values in the parameter file , the user * will be allowed to make another declaration in the same file * If those values are set to default values in the parameter file, the user * will be allowed to make another declaration in the same file *) let has_global_widening_delay p = (snd p.global_widening) <> default_global_widening_delay let has_global_widening_thresholds p = not (WideningThreshold.is_unspecified (fst p.global_widening)) let _has_local_widening_thresholds p = not (Dba_types.Caddress.Map.is_empty p.local_widening_thresholds) let _has_local_widening_delays p = not (Dba_types.Caddress.Map.is_empty p.local_widening_delays) let set_if_not err_p err_msg do_action parameters = if err_p parameters then failwith err_msg else do_action parameters let set_entry_points addrs parameters = Kernel_options.Logger.debug "@[Setting %d entry points...@]" (Virtual_address.Set.cardinal addrs); set_if_not has_entry_points "Entry points already set" (fun p -> { p with entry_points = addrs }) parameters let set_jumps addr_map parameters = set_if_not has_jumps "Jumps already set" (fun p -> { p with jumps = addr_map }) parameters let set_stops addresses parameters = set_if_not has_stops "Stops already set" (fun p -> { p with stops = addresses }) parameters let set_prepend_stubs addr_map parameters = set_if_not has_prepend_stubs "Prepend stubs already set" (fun p -> { p with prepend_stubs = addr_map }) parameters let set_substitute_stubs addr_map parameters = set_if_not has_substitute_stubs "Susbstitute stubs already set" (fun p -> { p with substitute_stubs = addr_map }) parameters let set_allowed_jumpzones addrs parameters = set_if_not has_allowed_jumpzones "Allowed jumps areas already set" (fun p -> { p with allowed_jumpzones = addrs }) parameters let set_linear_addresses addr_intervals parameters = let linear_addresses = List.map (fun (start, _end) -> let open Dba_types.Caddress in (to_virtual_address start, to_virtual_address _end)) addr_intervals in set_if_not has_linear_addresses "Linear addresses already set" (fun p -> { p with linear_addresses }) parameters let set_global_widening_delay widening_delay parameters = set_if_not has_global_widening_delay "Global widening delay already set" (fun p -> { p with global_widening = (fst p.global_widening, widening_delay) }) parameters let set_global_widening_thresholds widening_thresholds parameters = set_if_not has_global_widening_thresholds "Global widening thresholds already set" (fun p -> { p with global_widening = (widening_thresholds, snd p.global_widening) }) parameters
null
https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/parser/infos.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ Translation function to legacy structure
This file is part of BINSEC . Copyright ( C ) 2016 - 2019 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 ) . type instruction_kinds = Dba.Instr.t list type widening_delay = int module BoundThreshold = struct type t = { los : int array; his : int array; } let default = { los = [| |]; his = [| |]; } let mk_from_list (los: int list) (his : int list) : t = { los = Array.of_list los; his = Array.of_list his; } let is_unspecified bthreshold = Array.length bthreshold.los = 0 && Array.length bthreshold.his = 0 end module WideningThreshold = struct type t = { signed : BoundThreshold.t; unsigned : BoundThreshold.t; } let mk signed unsigned = { signed; unsigned; } let default = { signed = BoundThreshold.default; unsigned = BoundThreshold.default ; } let is_unspecified (wthreshold : t) = BoundThreshold.is_unspecified wthreshold.signed && BoundThreshold.is_unspecified wthreshold.unsigned let flatten_to_arrays_tuple wthreshold = let open BoundThreshold in wthreshold.signed.his, wthreshold.signed.los, wthreshold.unsigned.his, wthreshold.unsigned.los end let default_global_widening_thresholds = WideningThreshold.default and default_global_widening_delay = 0 type t = { entry_points : Virtual_address.Set.t; jumps : Dba.addresses Dba_types.Caddress.Map.t ; allowed_jumpzones : (Dba.address * Dba.address) list ; stops : Dba_types.Caddress.Set.t ; prepend_stubs : instruction_kinds Dba_types.Caddress.Map.t ; substitute_stubs : Dba_types.instruction_sequence Dba_types.Caddress.Map.t ; linear_addresses : (Virtual_address.t * Virtual_address.t) list ; global_widening : WideningThreshold.t * widening_delay ; local_widening_thresholds : WideningThreshold.t Dba_types.Caddress.Map.t ; local_widening_delays : widening_delay Dba_types.Caddress.Map.t ; } let default = { entry_points = Virtual_address.Set.empty; jumps = Dba_types.Caddress.Map.empty; allowed_jumpzones = []; stops = Dba_types.Caddress.Set.empty; substitute_stubs = Dba_types.Caddress.Map.empty; prepend_stubs = Dba_types.Caddress.Map.empty; linear_addresses = []; global_widening = default_global_widening_thresholds, default_global_widening_delay; local_widening_thresholds = Dba_types.Caddress.Map.empty; local_widening_delays = Dba_types.Caddress.Map.empty; } let empty = default let has_entry_points p = not (Virtual_address.Set.is_empty p.entry_points) let has_stops p = not (Dba_types.Caddress.Set.is_empty p.stops) let has_jumps p = not (Dba_types.Caddress.Map.is_empty p.jumps) let has_allowed_jumpzones p = not (List_utils.is_empty p.allowed_jumpzones) let has_prepend_stubs p = not (Dba_types.Caddress.Map.is_empty p.prepend_stubs) let has_substitute_stubs p = not (Dba_types.Caddress.Map.is_empty p.substitute_stubs) let has_linear_addresses p = not (List_utils.is_empty p.linear_addresses) FIXME : in the next 2 functions * If those values are set to default values in the parameter file , the user * will be allowed to make another declaration in the same file * If those values are set to default values in the parameter file, the user * will be allowed to make another declaration in the same file *) let has_global_widening_delay p = (snd p.global_widening) <> default_global_widening_delay let has_global_widening_thresholds p = not (WideningThreshold.is_unspecified (fst p.global_widening)) let _has_local_widening_thresholds p = not (Dba_types.Caddress.Map.is_empty p.local_widening_thresholds) let _has_local_widening_delays p = not (Dba_types.Caddress.Map.is_empty p.local_widening_delays) let set_if_not err_p err_msg do_action parameters = if err_p parameters then failwith err_msg else do_action parameters let set_entry_points addrs parameters = Kernel_options.Logger.debug "@[Setting %d entry points...@]" (Virtual_address.Set.cardinal addrs); set_if_not has_entry_points "Entry points already set" (fun p -> { p with entry_points = addrs }) parameters let set_jumps addr_map parameters = set_if_not has_jumps "Jumps already set" (fun p -> { p with jumps = addr_map }) parameters let set_stops addresses parameters = set_if_not has_stops "Stops already set" (fun p -> { p with stops = addresses }) parameters let set_prepend_stubs addr_map parameters = set_if_not has_prepend_stubs "Prepend stubs already set" (fun p -> { p with prepend_stubs = addr_map }) parameters let set_substitute_stubs addr_map parameters = set_if_not has_substitute_stubs "Susbstitute stubs already set" (fun p -> { p with substitute_stubs = addr_map }) parameters let set_allowed_jumpzones addrs parameters = set_if_not has_allowed_jumpzones "Allowed jumps areas already set" (fun p -> { p with allowed_jumpzones = addrs }) parameters let set_linear_addresses addr_intervals parameters = let linear_addresses = List.map (fun (start, _end) -> let open Dba_types.Caddress in (to_virtual_address start, to_virtual_address _end)) addr_intervals in set_if_not has_linear_addresses "Linear addresses already set" (fun p -> { p with linear_addresses }) parameters let set_global_widening_delay widening_delay parameters = set_if_not has_global_widening_delay "Global widening delay already set" (fun p -> { p with global_widening = (fst p.global_widening, widening_delay) }) parameters let set_global_widening_thresholds widening_thresholds parameters = set_if_not has_global_widening_thresholds "Global widening thresholds already set" (fun p -> { p with global_widening = (widening_thresholds, snd p.global_widening) }) parameters
591cdbaf231f421a2a1e53fc70b2607207324e4f53e808bf4123f5a60f21e0f7
HugoPeters1024/hs-sleuth
Stream.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE MagicHash #-} -- | -- Module : Data.List.Stream Copyright : ( c ) 2007 ( c ) 2007 - 2013 -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : portable -- A reimplementation of the standard list library to take advantage of stream fusion , and new GHC optimisations . The fusion mechanism is -- based on stream fusion for sequences. Described in: -- -- * /Stream Fusion: From Lists to Streams to Nothing at All/, by , and , ICFP 2007 . -- </~dons/papers/CLS07.html> -- * /Rewriting Haskell Strings/ , by , and Roman Leshchinskiy , Practical Aspects of Declarative Languages 8th International Symposium , PADL 2007 , 2007 . -- </~dons/papers/CSL06.html> -- -- See the source for the complete story: -- -- * </~dons/code/streams/list/Data/Stream.hs> -- -- This library is a drop in replacement for "Data.List". -- module Data.List.Stream ( $ fusion_intro -- * Basic interface (++), -- :: [a] -> [a] -> [a] head, -- :: [a] -> a last, -- :: [a] -> a tail, -- :: [a] -> [a] init, -- :: [a] -> [a] null, -- :: [a] -> Bool length, -- :: [a] -> Int -- * List transformations map, -- :: (a -> b) -> [a] -> [b] reverse, -- :: [a] -> [a] intersperse, -- :: a -> [a] -> [a] intercalate, -- :: [a] -> [[a]] -> [a] transpose, -- :: [[a]] -> [[a]] -- * Reducing lists (folds) foldl, -- :: (a -> b -> a) -> a -> [b] -> a foldl', -- :: (a -> b -> a) -> a -> [b] -> a foldl1, -- :: (a -> a -> a) -> [a] -> a foldl1', -- :: (a -> a -> a) -> [a] -> a foldr, -- :: (a -> b -> b) -> b -> [a] -> b foldr1, -- :: (a -> a -> a) -> [a] -> a -- ** Special folds concat, -- :: [[a]] -> [a] concatMap, -- :: (a -> [b]) -> [a] -> [b] and, -- :: [Bool] -> Bool or, -- :: [Bool] -> Bool any, -- :: (a -> Bool) -> [a] -> Bool all, -- :: (a -> Bool) -> [a] -> Bool : : a = > [ a ] - > a : : a = > [ a ] - > a : : a = > [ a ] - > a : : a = > [ a ] - > a -- * Building lists -- ** Scans scanl, -- :: (a -> b -> a) -> a -> [b] -> [a] scanl1, -- :: (a -> a -> a) -> [a] -> [a] scanr, -- :: (a -> b -> b) -> b -> [a] -> [b] scanr1, -- :: (a -> a -> a) -> [a] -> [a] -- ** Accumulating maps : : ( acc - > x - > ( acc , y ) ) - > acc - > [ x ] - > ( acc , [ y ] ) : : ( acc - > x - > ( acc , y ) ) - > acc - > [ x ] - > ( acc , [ y ] ) -- ** Infinite lists iterate, -- :: (a -> a) -> a -> [a] repeat, -- :: a -> [a] replicate, -- :: Int -> a -> [a] cycle, -- :: [a] -> [a] -- ** Unfolding unfoldr, -- :: (b -> Maybe (a, b)) -> b -> [a] -- * Sublists -- ** Extracting sublists take, -- :: Int -> [a] -> [a] drop, -- :: Int -> [a] -> [a] splitAt, -- :: Int -> [a] -> ([a], [a]) takeWhile, -- :: (a -> Bool) -> [a] -> [a] dropWhile, -- :: (a -> Bool) -> [a] -> [a] span, -- :: (a -> Bool) -> [a] -> ([a], [a]) break, -- :: (a -> Bool) -> [a] -> ([a], [a]) group, -- :: Eq a => [a] -> [[a]] inits, -- :: [a] -> [[a]] tails, -- :: [a] -> [[a]] -- * Predicates isPrefixOf, -- :: Eq a => [a] -> [a] -> Bool isSuffixOf, -- :: Eq a => [a] -> [a] -> Bool isInfixOf, -- :: Eq a => [a] -> [a] -> Bool -- * Searching lists -- ** Searching by equality elem, -- :: Eq a => a -> [a] -> Bool notElem, -- :: Eq a => a -> [a] -> Bool lookup, -- :: Eq a => a -> [(a, b)] -> Maybe b -- ** Searching with a predicate find, -- :: (a -> Bool) -> [a] -> Maybe a filter, -- :: (a -> Bool) -> [a] -> [a] partition, -- :: (a -> Bool) -> [a] -> ([a], [a]) -- * Indexing lists -- | These functions treat a list @xs@ as a indexed collection, -- with indices ranging from 0 to @'length' xs - 1@. (!!), -- :: [a] -> Int -> a elemIndex, -- :: Eq a => a -> [a] -> Maybe Int elemIndices, -- :: Eq a => a -> [a] -> [Int] findIndex, -- :: (a -> Bool) -> [a] -> Maybe Int findIndices, -- :: (a -> Bool) -> [a] -> [Int] -- * Zipping and unzipping lists zip, -- :: [a] -> [b] -> [(a, b)] zip3, -- :: [a] -> [b] -> [c] -> [(a, b, c)] zip4, zip5, zip6, zip7, | The zipWith family generalises the zip family by zipping with the function given as the first argument , instead of a tupling function . zipWith, -- :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith3, -- :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] zipWith4, zipWith5, zipWith6, zipWith7, unzip, -- :: [(a, b)] -> ([a], [b]) unzip3, -- :: [(a, b, c)] -> ([a], [b], [c]) unzip4, unzip5, unzip6, unzip7, -- * Special lists -- ** Functions on strings lines, -- :: String -> [String] words, -- :: String -> [String] unlines, -- :: [String] -> String unwords, -- :: [String] -> String -- ** \"Set\" operations nub, -- :: Eq a => [a] -> [a] delete, -- :: Eq a => a -> [a] -> [a] (\\), -- :: Eq a => [a] -> [a] -> [a] union, -- :: Eq a => [a] -> [a] -> [a] intersect, -- :: Eq a => [a] -> [a] -> [a] -- ** Ordered lists : : a = > [ a ] - > [ a ] : : a = > a - > [ a ] - > [ a ] -- * Generalized functions -- ** The \"By\" operations -- | By convention, overloaded functions have a non-overloaded -- counterpart whose name is suffixed with \`@By@\'. -- -- It is often convenient to use these functions together with -- 'Data.Function.on', for instance @'sortBy' ('compare' -- \`on\` 'fst')@. * * * User - supplied equality ( replacing an Eq context ) -- | The predicate is assumed to define an equivalence. nubBy, -- :: (a -> a -> Bool) -> [a] -> [a] deleteBy, -- :: (a -> a -> Bool) -> a -> [a] -> [a] deleteFirstsBy, -- :: (a -> a -> Bool) -> [a] -> [a] -> [a] unionBy, -- :: (a -> a -> Bool) -> [a] -> [a] -> [a] intersectBy, -- :: (a -> a -> Bool) -> [a] -> [a] -> [a] groupBy, -- :: (a -> a -> Bool) -> [a] -> [[a]] * * * User - supplied comparison ( replacing an context ) sortBy, -- :: (a -> a -> Ordering) -> [a] -> [a] insertBy, -- :: (a -> a -> Ordering) -> a -> [a] -> [a] maximumBy, -- :: (a -> a -> Ordering) -> [a] -> a minimumBy, -- :: (a -> a -> Ordering) -> [a] -> a -- * The \"generic\" operations -- | The prefix \`@generic@\' indicates an overloaded function that is a generalized version of a " Prelude " function . : : i = > [ b ] - > i genericTake, -- :: Integral i => i -> [a] -> [a] genericDrop, -- :: Integral i => i -> [a] -> [a] genericSplitAt, -- :: Integral i => i -> [a] -> ([a], [a]) genericIndex, -- :: Integral a => [b] -> a -> b genericReplicate, -- :: Integral i => i -> a -> [a] helper for GHC.List errorEmptyList -- :: String -> a ) where #ifndef EXTERNAL_PACKAGE import {-# SOURCE #-} GHC.Err ( error ) import {-# SOURCE #-} GHC.Real (Integral) import {-# SOURCE #-} GHC.Num (Num(..)) import {-# SOURCE #-} GHC.Unicode (isSpace) import GHC.Base (Int, Eq(..), Ord(..), Ordering(..), Bool(..), not, Ordering(..), seq, otherwise, flip, Monad(..), Char, String, Int(I#), Int#, (+#), -- we just reuse these: foldr, (++), map ) import Data.Maybe (Maybe(..)) #else import GHC.Exts (Int(I#), Int#, (+#)) import Prelude (Int, Integral, Num(..), Eq(..), Ord(..), Ordering(..), Bool(..), not, Maybe(..), Char, String, error, seq, otherwise, flip) import Data.Char (isSpace) #endif import qualified Data.Stream as Stream import Data.Stream (stream ,unstream) -- ----------------------------------------------------------------------------- #ifdef EXTERNAL_PACKAGE infixr 5 ++ #endif comment to fool infixl 9 !! infix 4 `elem`, `notElem` -- ----------------------------------------------------------------------------- $ fusion_intro -- -- The functions in this library marked with /fusion/ are -- (transparently) rewritten by the compiler to stream functions, using the fusion framework described in /Rewriting Haskell Strings/. -- -- For example: -- -- > map f xs -- -- is transformed via rewrite rules to: -- > ( unstream . mapS f . ) xs -- -- The 'unstream' and 'stream' functions identify the allocation points -- for each function. -- When two or more fusible functions are in close proximity ( i.e. -- directly composed, or with only intermediate lets and cases), the -- fusion rule will fire, removing the intermediate structures. -- -- Consider: -- > map f . map -- -- The rewrite engine will transform this code to: -- > unstream . mapS f . . unstream . . stream -- -- The fusion rule will then fire: -- > unstream . mapS f . . stream -- -- Removing the intermeidate list that is allocated. The compiler then -- optimises the result. -- -- Functions that fail to fuse are not left in stream form. In the final -- simplifier phase any remaining unfused functions of the form: -- -- > unstream . g . stream -- -- Will be transformed back to their original list implementation. -- -- Notes on simplifer phasing -- -- * api functions should be rewritten to fusible forms as soon as possble * This implies a NOINLINE [ 1 ] on the top level functions , so if ghc wants -- to inline them they'll only have their bodies inlined at the end. -- * These rewrite rules can then fire in any but the last phase: -- "++ -> fusible" [~1] forall xs ys. -- * Finally, if we reach the final phase, rewrite back to best effort [a] forms: " + + - > unfused " [ 1 ] forall xs ys . -- * And then inline the result. -- -- If fusion occurs though, hang on to those 'stream' and 'unstream' pairs: -- {-# INLINE [0] unstream #-} -- hmm? -- -- Todo: notes on the phasing of Streams -- -- ----------------------------------------------------------------------------- -- Fusion for the constructors: -- -- We do not enable fusion for (:), as it leads to a massive massive -- slow down in compilation time. -- RULES " (: ) - > fusible " [ ~1 ] forall x xs . x : xs = unstream ( Stream.cons x ( stream xs ) ) " (: ) - > unfused " [ 1 ] forall x xs . unstream ( Stream.cons x ( stream xs ) ) = x : xs "(:) -> fusible" [~1] forall x xs. x : xs = unstream (Stream.cons x (stream xs)) "(:) -> unfused" [1] forall x xs. unstream (Stream.cons x (stream xs)) = x : xs -} -- ----------------------------------------------------------------------------- -- Basic interface | /O(n)/ , /fusion/. Append two lists , i.e. , -- -- > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] -- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] -- If the first list is not finite , the result is the first list . The spine of the first list argument must be copied . #ifdef EXTERNAL_PACKAGE (++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys # NOINLINE [ 1 ] ( + + ) # #endif -- NOTE: This is quite subtle as we do not want to copy the last list in -- -- xs1 ++ xs2 ++ ... ++ xsn -- -- Indeed, we don't really want to fuse the above at all unless at least -- one of the arguments has the form (unstream s) or the result of the -- concatenation is streamed. The rules below do precisely that. Note they -- really fuse instead of just rewriting things into a fusible form so there -- is no need to rewrite back. # RULES " + + - > fused on 1st arg " [ ~1 ] forall xs ys . unstream xs + + ys = " + + - > fused on 2nd arg " [ ~1 ] forall xs ys . ( unstream ys ) = unstream ( Stream.append xs ys ) " + + - > fused ( 1 ) " [ ~1 ] forall xs ys . stream ( xs + + ys ) = Stream.append ( stream xs ) ( stream ys ) " + + - > fused ( 2 ) " [ ~1 ] forall xs ys . stream ( ) = Stream.append xs ( stream ys ) " + + - > 1st arg empty " forall xs . [ ] + + xs = xs " + + - > 2nd arg empty " forall xs . xs + + [ ] = xs " + + / : " forall x xs ys . ( x : xs ) + + ys = x : ( xs + + ys ) # "++ -> fused on 1st arg" [~1] forall xs ys. unstream xs ++ ys = Stream.append1 xs ys "++ -> fused on 2nd arg" [~1] forall xs ys. Stream.append1 xs (unstream ys) = unstream (Stream.append xs ys) "++ -> fused (1)" [~1] forall xs ys. stream (xs ++ ys) = Stream.append (stream xs) (stream ys) "++ -> fused (2)" [~1] forall xs ys. stream (Stream.append1 xs ys) = Stream.append xs (stream ys) "++ -> 1st arg empty" forall xs. [] ++ xs = xs "++ -> 2nd arg empty" forall xs. xs ++ [] = xs "++ / :" forall x xs ys. (x:xs) ++ ys = x : (xs ++ ys) #-} | /O(1)/ , /fusion/. Extract the first element of a list , which must be -- non-empty. head :: [a] -> a head (x:_) = x head [] = errorEmptyList "head" # NOINLINE [ 1 ] head # # RULES " head - > fusible " [ ~1 ] forall xs . head xs = Stream.head ( stream xs ) --"head - > unfused " [ 1 ] forall xs . -- Stream.head ( stream xs ) = head xs # "head -> fusible" [~1] forall xs. head xs = Stream.head (stream xs) --"head -> unfused" [1] forall xs. -- Stream.head (stream xs) = head xs #-} -- | /O(n)/, /fusion/. Extract the last element of a list, which must be finite -- and non-empty. last :: [a] -> a last [] = errorEmptyList "last" last (x:xs) = last' x xs where last' y [] = y last' _ (y:ys) = last' y ys # NOINLINE [ 1 ] last # # RULES " last - > fusible " [ ~1 ] forall xs . last xs = Stream.last ( stream xs ) --"last - > unfused " [ 1 ] forall xs . -- Stream.last ( stream xs ) = last xs # "last -> fusible" [~1] forall xs. last xs = Stream.last (stream xs) --"last -> unfused" [1] forall xs. -- Stream.last (stream xs) = last xs #-} -- | /O(1)/, /fusion/. Extract the elements after the head of a list, which -- must be non-empty. tail :: [a] -> [a] tail (_:xs) = xs tail [] = errorEmptyList "tail" # NOINLINE [ 1 ] tail # # RULES " tail - > fusible " [ ~1 ] forall xs . tail xs = unstream ( Stream.tail ( stream xs ) ) --"tail - > unfused " [ 1 ] forall xs . -- unstream ( Stream.tail ( stream xs ) ) = tail xs # "tail -> fusible" [~1] forall xs. tail xs = unstream (Stream.tail (stream xs)) --"tail -> unfused" [1] forall xs. -- unstream (Stream.tail (stream xs)) = tail xs #-} -- | /O(n)/, /fusion/. Return all the elements of a list except the last one. -- The list must be finite and non-empty. init :: [a] -> [a] init [] = errorEmptyList "init" init (x:xs) = init' x xs where init' _ [] = [] init' y (z:zs) = y : init' z zs # NOINLINE [ 1 ] init # # RULES " init - > fusible " [ ~1 ] forall xs . init xs = unstream ( Stream.init ( stream xs ) ) --"init - > unfused " [ 1 ] forall xs . -- unstream ( Stream.init ( stream xs ) ) = init xs # "init -> fusible" [~1] forall xs. init xs = unstream (Stream.init (stream xs)) --"init -> unfused" [1] forall xs. -- unstream (Stream.init (stream xs)) = init xs #-} -- | /O(1)/, /fusion/. Test whether a list is empty. null :: [a] -> Bool null [] = True null (_:_) = False # NOINLINE [ 1 ] null # # RULES " null - > fusible " [ ~1 ] forall xs . null xs = Stream.null ( stream xs ) --"null - > unfused " [ 1 ] forall xs . -- Stream.null ( stream xs ) = null xs # "null -> fusible" [~1] forall xs. null xs = Stream.null (stream xs) --"null -> unfused" [1] forall xs. -- Stream.null (stream xs) = null xs #-} -- | /O(n)/, /fusion/. 'length' returns the length of a finite list as an 'Int'. -- It is an instance of the more general 'Data.List.genericLength', -- the result type of which may be any kind of number. length :: [a] -> Int length xs0 = len xs0 0# #ifndef __HADDOCK__ where len :: [a] -> Int# -> Int len [] a# = I# a# len (_:xs) a# = len xs (a# +# 1#) #endif # NOINLINE [ 1 ] length # # RULES " length - > fusible " [ ~1 ] forall xs . length xs = Stream.length ( stream xs ) " length - > unfused " [ 1 ] forall xs . Stream.length ( stream xs ) = length xs # "length -> fusible" [~1] forall xs. length xs = Stream.length (stream xs) "length -> unfused" [1] forall xs. Stream.length (stream xs) = length xs #-} -- --------------------------------------------------------------------- -- List transformations | /O(n)/ , /fusion/. ' map ' is the list obtained by applying @f@ to each element of @xs@ , i.e. , -- -- > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] -- > map f [x1, x2, ...] == [f x1, f x2, ...] -- -- Properties: -- > map f . map = map ( f . ) -- > map f (repeat x) = repeat (f x) -- > map f (replicate n x) = replicate n (f x) #ifdef EXTERNAL_PACKAGE map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = f x : map f xs # NOINLINE [ 1 ] map # #endif # RULES " map - > fusible " [ ~1 ] forall f xs . map f xs = unstream ( Stream.map f ( stream xs ) ) --"map - > unfused " [ 1 ] forall f xs . -- unstream ( Stream.map f ( stream xs ) ) = map f xs # "map -> fusible" [~1] forall f xs. map f xs = unstream (Stream.map f (stream xs)) --"map -> unfused" [1] forall f xs. -- unstream (Stream.map f (stream xs)) = map f xs #-} -- | /O(n)/, /fusion/. 'reverse' @xs@ returns the elements of @xs@ in reverse order. -- @xs@ must be finite. Will fuse as a consumer only. reverse :: [a] -> [a] reverse = foldl' (flip (:)) [] # INLINE reverse # {- reverse l = rev l [] where rev [] a = a rev (x:xs) a = rev xs (x:a) -} --TODO : I 'm sure there are some cunning things we can do with optimising -- reverse . Of course if we try and fuse we may need to still force the -- sping of the list : eg reverse . reverse = forceSpine forceSpine : : [ a ] - > [ a ] forceSpine xs = forceSpine ' xs ` seq ` xs { - # INLINE forceSpine # --TODO: I'm sure there are some cunning things we can do with optimising -- reverse. Of course if we try and fuse we may need to still force the -- sping of the list: eg reverse . reverse = forceSpine forceSpine :: [a] -> [a] forceSpine xs = forceSpine' xs `seq` xs {-# INLINE forceSpine #-} -- The idea of this slightly odd construction is that we inline the above form -- and in the context we may then be able to use xs directly and just keep -- around the fact that xs must be forced at some point. Remember, seq does not -- imply any evaluation order. forceSpine' :: [a] -> () forceSpine' [] = () forceSpine' (_:xs') = forceSpine' xs' # NOINLINE forceSpine ' # -} -- | /O(n)/, /fusion/. The 'intersperse' function takes an element and a list and ' that element between the elements of the list . -- For example, -- -- > intersperse ',' "abcde" == "a,b,c,d,e" -- intersperse :: a -> [a] -> [a] intersperse _ [] = [] intersperse sep (x0:xs0) = x0 : go xs0 where go [] = [] go (x:xs) = sep : x : go xs # NOINLINE [ 1 ] intersperse # RULES " intersperse - > fusible " [ ~1 ] forall x xs . intersperse x xs = unstream ( Stream.intersperse x ( stream xs ) ) " intersperse - > unfused " [ 1 ] forall x xs . unstream ( Stream.intersperse x ( stream xs ) ) = intersperse x xs "intersperse -> fusible" [~1] forall x xs. intersperse x xs = unstream (Stream.intersperse x (stream xs)) "intersperse -> unfused" [1] forall x xs. unstream (Stream.intersperse x (stream xs)) = intersperse x xs -} | /O(n)/ , /fusion/. ' intercalate ' @xs xss@ is equivalent to @('concat ' ( ' intersperse ' xs xss))@. -- It inserts the list @xs@ in between the lists in @xss@ and concatenates the -- result. -- -- > intercalate = concat . intersperse -- intercalate :: [a] -> [[a]] -> [a] intercalate sep xss = go (intersperse sep xss) where go [] = [] go (y:ys) = y ++ go ys # NOINLINE [ 1 ] intercalate # intercalate _ [ ] = [ ] intercalate sep ( xs0 : ) = go xs0 where go [ ] xss = to xss go ( x : xs ) xss = x : go xs xss to [ ] = [ ] to ( xs : xss ) = go ' sep xs xss go ' [ ] xs xss = go xs xss go ' ( s : ss ) xs xss = s : go ' ss xs xss { - # NOINLINE [ 1 ] intercalate # intercalate _ [] = [] intercalate sep (xs0:xss0) = go xs0 xss0 where go [] xss = to xss go (x:xs) xss = x : go xs xss to [] = [] to (xs:xss) = go' sep xs xss go' [] xs xss = go xs xss go' (s:ss) xs xss = s : go' ss xs xss {-# NOINLINE [1] intercalate #-} -} -- fusion rule based on: -- intercalate = concat . intersperse -- RULES " intercalate - > fusible " [ ~1 ] forall x xs . intercalate x xs = Stream.concat ( Stream.intersperse x ( stream xs ) ) " intercalate - > unfused " [ 1 ] forall x xs . Stream.concat ( Stream.intersperse x ( stream xs ) ) = intercalate x xs "intercalate -> fusible" [~1] forall x xs. intercalate x xs = Stream.concat (Stream.intersperse x (stream xs)) "intercalate -> unfused" [1] forall x xs. Stream.concat (Stream.intersperse x (stream xs)) = intercalate x xs -} -- | The 'transpose' function transposes the rows and columns of its argument. -- For example, -- -- > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]] -- transpose :: [[a]] -> [[a]] transpose [] = [] transpose ([] : xss) = transpose xss transpose ((x:xs) : xss) = (x : [h | (h:_t) <- xss]) : transpose (xs : [ t | (_h:t) <- xss]) TODO fuse -- --------------------------------------------------------------------- -- Reducing lists (folds) -- | /O(n)/, /fusion/. 'foldl', applied to a binary operator, a starting value (typically -- the left-identity of the operator), and a list, reduces the list -- using the binary operator, from left to right: -- -- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn -- -- The list must be finite. -- foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z0 xs0 = go z0 xs0 where go z [] = z go z (x:xs) = go (f z x) xs # INLINE [ 1 ] foldl # # RULES " foldl - > fusible " [ ~1 ] forall f z xs . foldl f z xs = Stream.foldl f z ( stream xs ) --"foldl - > unfused " [ 1 ] forall f z xs . -- Stream.foldl f z ( stream xs ) = foldl f z xs # "foldl -> fusible" [~1] forall f z xs. foldl f z xs = Stream.foldl f z (stream xs) --"foldl -> unfused" [1] forall f z xs. -- Stream.foldl f z (stream xs) = foldl f z xs #-} -- | /O(n)/, /fusion/. A strict version of 'foldl'. foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f z0 xs0 = go z0 xs0 #ifndef __HADDOCK__ where go !z [] = z go !z (x:xs) = go (f z x) xs #endif # INLINE [ 1 ] foldl ' # # RULES " foldl ' - > fusible " [ ~1 ] forall f z xs . foldl ' f z xs = Stream.foldl ' f z ( stream xs ) --"foldl ' - > unfused " [ 1 ] forall f z xs . -- Stream.foldl ' f z ( stream xs ) = foldl ' f z xs # "foldl' -> fusible" [~1] forall f z xs. foldl' f z xs = Stream.foldl' f z (stream xs) --"foldl' -> unfused" [1] forall f z xs. -- Stream.foldl' f z (stream xs) = foldl' f z xs #-} | /O(n)/ , /fusion/. ' foldl1 ' is a variant of ' foldl ' that has no starting value argument , -- and thus must be applied to non-empty lists. foldl1 :: (a -> a -> a) -> [a] -> a foldl1 _ [] = errorEmptyList "foldl1" foldl1 f (x0:xs0) = go x0 xs0 where go z [] = z go z (x:xs) = go (f z x) xs # INLINE [ 1 ] foldl1 # # RULES " foldl1 - > fusible " [ ~1 ] forall f xs . foldl1 f xs = Stream.foldl1 f ( stream xs ) --"foldl1 - > unfused " [ 1 ] forall f xs . -- Stream.foldl1 f ( stream xs ) = foldl1 f xs # "foldl1 -> fusible" [~1] forall f xs. foldl1 f xs = Stream.foldl1 f (stream xs) --"foldl1 -> unfused" [1] forall f xs. -- Stream.foldl1 f (stream xs) = foldl1 f xs #-} | /O(n)/ , /fusion/. A strict version of ' foldl1 ' foldl1' :: (a -> a -> a) -> [a] -> a foldl1' _ [] = errorEmptyList "foldl1'" foldl1' f (x0:xs0) = go x0 xs0 #ifndef __HADDOCK__ where go !z [] = z go !z (x:xs) = go (f z x) xs #endif # INLINE [ 1 ] foldl1 ' # # RULES " foldl1 ' - > fusible " [ ~1 ] forall f xs . foldl1 ' f xs = Stream.foldl1 ' f ( stream xs ) --"foldl1 - > unfused " [ 1 ] forall f xs . -- Stream.foldl1 ' f ( stream xs ) = foldl1 ' f xs # "foldl1' -> fusible" [~1] forall f xs. foldl1' f xs = Stream.foldl1' f (stream xs) --"foldl1 -> unfused" [1] forall f xs. -- Stream.foldl1' f (stream xs) = foldl1' f xs #-} -- | /O(n)/, /fusion/. 'foldr', applied to a binary operator, a starting value (typically -- the right-identity of the operator), and a list, reduces the list -- using the binary operator, from right to left: -- -- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) #ifdef EXTERNAL_PACKAGE foldr :: (a -> b -> b) -> b -> [a] -> b foldr k z xs = go xs where go [] = z go (y:ys) = y `k` go ys {-# INLINE [0] foldr #-} #endif # RULES " foldr - > fusible " [ ~1 ] forall f z xs . foldr f z xs = Stream.foldr f z ( stream xs ) --"foldr - > unfused " [ 1 ] forall f z xs . -- Stream.foldr f z ( stream xs ) = foldr f z xs # "foldr -> fusible" [~1] forall f z xs. foldr f z xs = Stream.foldr f z (stream xs) --"foldr -> unfused" [1] forall f z xs. -- Stream.foldr f z (stream xs) = foldr f z xs #-} | /O(n)/ , /fusion/. ' ' is a variant of ' foldr ' that has no starting value argument , -- and thus must be applied to non-empty lists. foldr1 :: (a -> a -> a) -> [a] -> a foldr1 _ [] = errorEmptyList "foldr1" foldr1 k (x0:xs0) = go x0 xs0 where go x [] = x go x (x':xs) = k x (go x' xs) {-# INLINE [1] foldr1 #-} # RULES " foldr1 - > fusible " [ ~1 ] forall f xs . foldr1 f xs = Stream.foldr1 f ( stream xs ) --"foldr1 - > unfused " [ 1 ] forall f xs . -- Stream.foldr1 f ( stream xs ) = foldr1 f xs # "foldr1 -> fusible" [~1] forall f xs. foldr1 f xs = Stream.foldr1 f (stream xs) --"foldr1 -> unfused" [1] forall f xs. -- Stream.foldr1 f (stream xs) = foldr1 f xs #-} -- --------------------------------------------------------------------- -- Special folds | /O(n)/ , /fusion/. a list of lists . concat :: [[a]] -> [a] concat xss0 = to xss0 where go [] xss = to xss go (x:xs) xss = x : go xs xss to [] = [] to (xs:xss) = go xs xss -- hmm, this is slower than the old concat? # NOINLINE [ 1 ] concat # -- -- fuse via concatMap, as the Stream (Stream a) is too hard to construct -- -- or via foldr (++) ? -- # RULES " concat - > fused " [ ~1 ] forall xs . concat xs = Stream.concat ( stream xs ) --"concat - > unfused " [ 1 ] forall xs . -- Stream.concat ( stream xs ) = concat xs # "concat -> fused" [~1] forall xs. concat xs = Stream.concat (stream xs) --"concat -> unfused" [1] forall xs. -- Stream.concat (stream xs) = concat xs #-} -- | /O(n)/, /fusion/. Map a function over a list and concatenate the results. concatMap :: (a -> [b]) -> [a] -> [b] concatMap f = foldr (\x y -> f x ++ y) [] -- at least it will fuse. # INLINE concatMap # concatMap f as0 = to as0 where go [ ] as = to as go ( b : bs ) as = b : go bs as to [ ] = [ ] to ( a : as ) = go ( f a ) as { - # NOINLINE [ 1 ] concatMap # concatMap f as0 = to as0 where go [] as = to as go (b:bs) as = b : go bs as to [] = [] to (a:as) = go (f a) as {-# NOINLINE [1] concatMap #-} -} RULES " concatMap - > fusible " [ ~1 ] forall f xs . concatMap f xs = Stream.concatMap f ( stream xs ) " concatMap - > unfused " [ 1 ] forall f xs . Stream.concatMap f ( stream xs ) = concatMap f xs "concatMap -> fusible" [~1] forall f xs. concatMap f xs = Stream.concatMap f (stream xs) "concatMap -> unfused" [1] forall f xs. Stream.concatMap f (stream xs) = concatMap f xs -} | /O(n)/ , /fusion/. ' and ' returns the conjunction of a Boolean list . For the result to be -- 'True', the list must be finite; 'False', however, results from a 'False' -- value at a finite index of a finite or infinite list. -- and :: [Bool] -> Bool and [] = True and (False:_ ) = False and (_ :xs) = and xs # NOINLINE [ 1 ] and # # RULES " and - > fused " [ ~1 ] forall xs . and xs = Stream.and ( stream xs ) --"and - > unfused " [ 1 ] forall xs . -- Stream.and ( stream xs ) = and xs # "and -> fused" [~1] forall xs. and xs = Stream.and (stream xs) --"and -> unfused" [1] forall xs. -- Stream.and (stream xs) = and xs #-} | /O(n)/ , /fusion/. ' or ' returns the disjunction of a Boolean list . For the result to be -- 'False', the list must be finite; 'True', however, results from a 'True' -- value at a finite index of a finite or infinite list. or :: [Bool] -> Bool or [] = False or (True:_ ) = True or (_ :xs) = or xs # NOINLINE [ 1 ] or # # RULES " or - > fused " [ ~1 ] forall xs . or xs = Stream.or ( stream xs ) --"or - > unfused " [ 1 ] forall xs . -- Stream.or ( stream xs ) = or xs # "or -> fused" [~1] forall xs. or xs = Stream.or (stream xs) --"or -> unfused" [1] forall xs. -- Stream.or (stream xs) = or xs #-} -- | /O(n)/, /fusion/. Applied to a predicate and a list, 'any' determines if any element -- of the list satisfies the predicate. any :: (a -> Bool) -> [a] -> Bool any p xs0 = go xs0 where go [] = False go (x:xs) = case p x of True -> True False -> go xs # NOINLINE [ 1 ] any # TODO : check if being lazy in p is a cost , should we do [ ] as a special case and then strictly evaluate p ? # RULES " any - > fusible " [ ~1 ] forall f xs . any f xs = Stream.any f ( stream xs ) --"any - > unfused " [ 1 ] forall f xs . -- Stream.any f ( stream xs ) = any f xs # "any -> fusible" [~1] forall f xs. any f xs = Stream.any f (stream xs) --"any -> unfused" [1] forall f xs. -- Stream.any f (stream xs) = any f xs #-} -- | Applied to a predicate and a list, 'all' determines if all elements -- of the list satisfy the predicate. all :: (a -> Bool) -> [a] -> Bool all p xs0 = go xs0 where go [] = True go (x:xs) = case p x of True -> go xs False -> False # NOINLINE [ 1 ] all # # RULES " all - > fusible " [ ~1 ] forall f xs . all f xs = Stream.all f ( stream xs ) --"all - > unfused " [ 1 ] forall f xs . -- Stream.all f ( stream xs ) = all f xs # "all -> fusible" [~1] forall f xs. all f xs = Stream.all f (stream xs) --"all -> unfused" [1] forall f xs. -- Stream.all f (stream xs) = all f xs #-} -- | /O(n)/, /fusion/. The 'sum' function computes the sum of a finite list of numbers. sum :: Num a => [a] -> a sum l = sum' l 0 #ifndef __HADDOCK__ where sum' [] a = a sum' (x:xs) a = sum' xs (a+x) #endif # NOINLINE [ 1 ] sum # sumInt :: [Int] -> Int sumInt l = sum' l 0 #ifndef __HADDOCK__ where sum' [] a = a sum' (x:xs) !a = sum' xs (a+x) #endif # NOINLINE [ 1 ] sumInt # {-# RULES "sum spec Int" sum = sumInt :: [Int] -> Int #-} # RULES " sum - > fusible " [ ~1 ] forall xs . sum xs = Stream.sum ( stream xs ) --"sum - > unfused " [ 1 ] forall xs . -- Stream.sum ( stream xs ) = sum xs # "sum -> fusible" [~1] forall xs. sum xs = Stream.sum (stream xs) --"sum -> unfused" [1] forall xs. -- Stream.sum (stream xs) = sum xs #-} # RULES " sumInt - > fusible " [ ~1 ] forall ( xs : : [ Int ] ) . sumInt xs = Stream.sum ( stream xs ) --"sumInt - > unfused " [ 1 ] forall ( xs : : [ Int ] ) . -- Stream.sum ( stream xs ) = sumInt xs # "sumInt -> fusible" [~1] forall (xs :: [Int]). sumInt xs = Stream.sum (stream xs) --"sumInt -> unfused" [1] forall (xs :: [Int]). -- Stream.sum (stream xs) = sumInt xs #-} -- | /O(n)/,/fusion/. The 'product' function computes the product of a finite list of numbers. product :: Num a => [a] -> a product l = prod l 1 #ifndef __HADDOCK__ where prod [] a = a prod (x:xs) a = prod xs (a*x) #endif # NOINLINE [ 1 ] product # productInt :: [Int] -> Int productInt l = product' l 0 #ifndef __HADDOCK__ where product' [] a = a product' (x:xs) !a = product' xs (a*x) #endif # NOINLINE [ 1 ] productInt # {-# RULES "product spec Int" product = productInt :: [Int] -> Int #-} # RULES " product - > fused " [ ~1 ] forall xs . product xs = Stream.product ( stream xs ) --"product - > unfused " [ 1 ] forall xs . -- ( stream xs ) = product xs # "product -> fused" [~1] forall xs. product xs = Stream.product (stream xs) --"product -> unfused" [1] forall xs. -- Stream.product (stream xs) = product xs #-} # RULES " productInt - > fusible " [ ~1 ] forall ( xs : : [ Int ] ) . productInt xs = Stream.product ( stream xs ) --"productInt - > unfused " [ 1 ] forall ( xs : : [ Int ] ) . -- ( stream xs ) = productInt xs # "productInt -> fusible" [~1] forall (xs :: [Int]). productInt xs = Stream.product (stream xs) --"productInt -> unfused" [1] forall (xs :: [Int]). -- Stream.product (stream xs) = productInt xs #-} -- | /O(n)/,/fusion/. 'maximum' returns the maximum value from a list, -- which must be non-empty, finite, and of an ordered type. -- It is a special case of 'Data.List.maximumBy', which allows the -- programmer to supply their own comparison function. maximum :: Ord a => [a] -> a maximum [] = errorEmptyList "maximum" maximum xs = foldl1 max xs # NOINLINE [ 1 ] maximum # # RULES " maximum - > fused " [ ~1 ] forall xs . maximum xs = Stream.maximum ( stream xs ) --"maximum - > unfused " [ 1 ] forall xs . -- Stream.maximum ( stream xs ) = maximum xs # "maximum -> fused" [~1] forall xs. maximum xs = Stream.maximum (stream xs) --"maximum -> unfused" [1] forall xs. -- Stream.maximum (stream xs) = maximum xs #-} -- We can't make the overloaded version of maximum strict without changing its semantics ( might not be strict ) , but we can for -- the version specialised to 'Int'. # RULES " maximumInt " maximum = ( strictMaximum : : [ Int ] - > Int ) ; " maximumChar " maximum = ( strictMaximum : : [ ) # "maximumInt" maximum = (strictMaximum :: [Int] -> Int); "maximumChar" maximum = (strictMaximum :: [Char] -> Char) #-} strictMaximum :: (Ord a) => [a] -> a strictMaximum [] = errorEmptyList "maximum" strictMaximum xs = foldl1' max xs # NOINLINE [ 1 ] strictMaximum # # RULES " strictMaximum - > fused " [ ~1 ] forall xs . strictMaximum xs = Stream.strictMaximum ( stream xs ) --"strictMaximum - > unfused " [ 1 ] forall xs . -- Stream.strictMaximum ( stream xs ) = strictMaximum xs # "strictMaximum -> fused" [~1] forall xs. strictMaximum xs = Stream.strictMaximum (stream xs) --"strictMaximum -> unfused" [1] forall xs. -- Stream.strictMaximum (stream xs) = strictMaximum xs #-} -- | /O(n)/,/fusion/. 'minimum' returns the minimum value from a list, -- which must be non-empty, finite, and of an ordered type. -- It is a special case of 'Data.List.minimumBy', which allows the -- programmer to supply their own comparison function. minimum :: Ord a => [a] -> a minimum [] = errorEmptyList "minimum" minimum xs = foldl1 min xs # NOINLINE [ 1 ] minimum # # RULES " minimum - > fused " [ ~1 ] forall xs . minimum xs = Stream.minimum ( stream xs ) --"minimum - > unfused " [ 1 ] forall xs . -- Stream.minimum ( stream xs ) = minimum xs # "minimum -> fused" [~1] forall xs. minimum xs = Stream.minimum (stream xs) --"minimum -> unfused" [1] forall xs. -- Stream.minimum (stream xs) = minimum xs #-} # RULES " minimumInt " minimum = ( strictMinimum : : [ Int ] - > Int ) ; " minimumChar " minimum = ( strictMinimum : : [ ) # "minimumInt" minimum = (strictMinimum :: [Int] -> Int); "minimumChar" minimum = (strictMinimum :: [Char] -> Char) #-} strictMinimum :: (Ord a) => [a] -> a strictMinimum [] = errorEmptyList "maximum" strictMinimum xs = foldl1' min xs # NOINLINE [ 1 ] strictMinimum # # RULES " strictMinimum - > fused " [ ~1 ] forall xs . strictMinimum xs = Stream.strictMinimum ( stream xs ) --"strictMinimum - > unfused " [ 1 ] forall xs . -- Stream.strictMinimum ( stream xs ) = strictMinimum xs # "strictMinimum -> fused" [~1] forall xs. strictMinimum xs = Stream.strictMinimum (stream xs) --"strictMinimum -> unfused" [1] forall xs. -- Stream.strictMinimum (stream xs) = strictMinimum xs #-} -- --------------------------------------------------------------------- -- * Building lists -- ** Scans | /O(n)/ , /fusion/. ' ' is similar to ' foldl ' , but returns a list of successive -- reduced values from the left: -- > f z [ x1 , x2 , ... ] = = [ z , z ` f ` x1 , ( z ` f ` x1 ) ` f ` x2 , ... ] -- -- Properties: -- > last ( f z xs ) = = foldl f z x -- scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q ls = q : case ls of [] -> [] x:xs -> scanl f (f q x) xs # INLINE [ 1 ] scanl # or perhaps : f q xs0 = q : go q xs0 where go q [ ] = [ ] go q ( x : xs ) = let q ' = f q x in q ' : go q ' xs scanl f q xs0 = q : go q xs0 where go q [] = [] go q (x:xs) = let q' = f q x in q' : go q' xs -} -- note : 's ' scan ' is a bit weird , as it always puts the initial -- state as a prefix. this complicates the rules. -- # RULES " - > fusible " [ ~1 ] forall f z xs . f z xs = unstream ( Stream.scanl f z ( Stream.snoc ( stream xs ) bottom ) ) --"scanl - > unfused " [ 1 ] forall f z xs . -- unstream ( Stream.scanl f z ( Stream.snoc ( stream xs ) bottom ) ) = f z xs # "scanl -> fusible" [~1] forall f z xs. scanl f z xs = unstream (Stream.scanl f z (Stream.snoc (stream xs) bottom)) --"scanl -> unfused" [1] forall f z xs. -- unstream (Stream.scanl f z (Stream.snoc (stream xs) bottom)) = scanl f z xs #-} | /O(n)/,/fusion/. ' ' is a variant of ' ' that has no starting value argument : -- > f [ x1 , x2 , ... ] = = [ x1 , x1 ` f ` x2 , ... ] -- scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 f (x:xs) = scanl f x xs scanl1 _ [] = [] {-# INLINE [1] scanl1 #-} # RULES " scanl1 - > fusible " [ ~1 ] forall f xs . scanl1 f xs = unstream ( Stream.scanl1 f ( Stream.snoc ( stream xs ) bottom ) ) --"scanl1 - > unfused " [ 1 ] forall f xs . -- unstream ( Stream.scanl1 f ( Stream.snoc ( stream xs ) bottom ) ) = scanl1 f xs # "scanl1 -> fusible" [~1] forall f xs. scanl1 f xs = unstream (Stream.scanl1 f (Stream.snoc (stream xs) bottom)) --"scanl1 -> unfused" [1] forall f xs. -- unstream (Stream.scanl1 f (Stream.snoc (stream xs) bottom)) = scanl1 f xs #-} | /O(n)/. ' scanr ' is the right - to - left dual of ' ' . -- Properties: -- > head ( scanr f z xs ) = = foldr f z xs -- scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr _ q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs # INLINE [ 1 ] scanr # RULES " scanr - > fusible " [ ~1 ] forall f z xs . scanr f z xs = unstream ( Stream.scanr f z ( Stream.cons bottom ( stream xs ) ) ) " scanr - > unfused " [ 1 ] forall f z xs . unstream ( Stream.scanr f z ( Stream.cons bottom ( stream xs ) ) ) = scanr f z xs "scanr -> fusible" [~1] forall f z xs. scanr f z xs = unstream (Stream.scanr f z (Stream.cons bottom (stream xs))) "scanr -> unfused" [1] forall f z xs. unstream (Stream.scanr f z (Stream.cons bottom (stream xs))) = scanr f z xs -} | ' ' is a variant of ' scanr ' that has no starting value argument . scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 _ [] = [] scanr1 _ [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs TODO fuse -- --------------------------------------------------------------------- -- ** Accumulating maps -- | The 'mapAccumL' function behaves like a combination of 'map' and -- 'foldl'; it applies a function to each element of a list, passing -- an accumulating parameter from left to right, and returning a final -- value of this accumulator together with the new list. -- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) mapAccumL _ s [] = (s, []) mapAccumL f s (x:xs) = (s'',y:ys) where (s', y ) = f s x (s'',ys) = mapAccumL f s' xs TODO fuse -- | The 'mapAccumR' function behaves like a combination of 'map' and -- 'foldr'; it applies a function to each element of a list, passing -- an accumulating parameter from right to left, and returning a final -- value of this accumulator together with the new list. -- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) mapAccumR _ s [] = (s, []) mapAccumR f s (x:xs) = (s'', y:ys) where (s'',y ) = f s' x (s', ys) = mapAccumR f s xs TODO fuse ------------------------------------------------------------------------ -- ** Infinite lists | /fusion/. ' iterate ' @f returns an infinite list of repeated applications of to @x@ : -- -- > iterate f x == [x, f x, f (f x), ...] iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) # NOINLINE [ 1 ] iterate # # RULES " iterate - > fusible " [ ~1 ] forall f x. iterate f x = unstream ( Stream.iterate f x ) --"iterate - > unfused " [ 1 ] forall f x. -- unstream ( Stream.iterate f x ) = iterate f x # "iterate -> fusible" [~1] forall f x. iterate f x = unstream (Stream.iterate f x) --"iterate -> unfused" [1] forall f x. -- unstream (Stream.iterate f x) = iterate f x #-} -- | /fusion/. 'repeat' @x@ is an infinite list, with @x@ the value of every element. repeat :: a -> [a] repeat x = xs where xs = x : xs # INLINE [ 1 ] repeat # # RULES " repeat - > fusible " [ ~1 ] forall x. repeat x = unstream ( Stream.repeat x ) --"repeat - > unfused " [ 1 ] forall x. -- unstream ( Stream.repeat x ) = repeat x # "repeat -> fusible" [~1] forall x. repeat x = unstream (Stream.repeat x) --"repeat -> unfused" [1] forall x. -- unstream (Stream.repeat x) = repeat x #-} | /O(n)/ , /fusion/. ' replicate ' @n is a list of length @n@ with @x@ the value of -- every element. It is an instance of the more general ' Data . List.genericReplicate ' , in which @n@ may be of any integral type . -- replicate :: Int -> a -> [a] replicate n0 _ | n0 <= 0 = [] replicate n0 x = go n0 where go 0 = [] go n = x : go (n-1) # NOINLINE [ 1 ] replicate # # RULES " replicate - > fusible " [ ~1 ] replicate = - > unstream ( Stream.replicate n x ) --"replicate - > unfused " [ 1 ] forall n x. -- unstream ( Stream.replicate n x ) = replicate n x # "replicate -> fusible" [~1] replicate = \n x -> unstream (Stream.replicate n x) --"replicate -> unfused" [1] forall n x. -- unstream (Stream.replicate n x) = replicate n x #-} -- | /fusion/. 'cycle' ties a finite list into a circular one, or equivalently, -- the infinite repetition of the original list. It is the identity -- on infinite lists. -- cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs0 = go xs0 where go [] = go xs0 go (x:xs) = x : go xs # NOINLINE [ 1 ] cycle # # RULES " cycle - > fusible " [ ~1 ] forall xs . cycle xs = unstream ( Stream.cycle ( stream xs ) ) --"cycle - > unfused " [ 1 ] forall xs . -- unstream ( Stream.cycle ( stream xs ) ) = cycle xs # "cycle -> fusible" [~1] forall xs. cycle xs = unstream (Stream.cycle (stream xs)) --"cycle -> unfused" [1] forall xs. -- unstream (Stream.cycle (stream xs)) = cycle xs #-} -- --------------------------------------------------------------------- -- ** Unfolding -- | /fusion/. The 'unfoldr' function is a \`dual\' to 'foldr': while 'foldr' -- reduces a list to a summary value, 'unfoldr' builds a list from -- a seed value. The function takes the element and returns 'Nothing' -- if it is done producing the list or returns 'Just' @(a,b)@, in which case , @a@ is a prepended to the list and @b@ is used as the next -- element in a recursive call. For example, -- > iterate f = = unfoldr ( \x - > Just ( x , f x ) ) -- -- In some cases, 'unfoldr' can undo a 'foldr' operation: -- -- > unfoldr f' (foldr f z xs) == xs -- -- if the following holds: -- -- > f' (f x y) = Just (x,y) -- > f' z = Nothing -- -- A simple use of unfoldr: -- > unfoldr ( \b - > if b = = 0 then Nothing else Just ( b , b-1 ) ) 10 -- > [10,9,8,7,6,5,4,3,2,1] -- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] unfoldr f b0 = unfold b0 where unfold b = case f b of Just (a,b') -> a : unfold b' Nothing -> [] # INLINE [ 1 ] unfoldr # # RULES " unfoldr - > fusible " [ ~1 ] forall f x. unfoldr f x = unstream ( Stream.unfoldr f x ) --"unfoldr - > unfused " [ 1 ] forall f x. -- unstream ( Stream.unfoldr f x ) = unfoldr f x # "unfoldr -> fusible" [~1] forall f x. unfoldr f x = unstream (Stream.unfoldr f x) --"unfoldr -> unfused" [1] forall f x. -- unstream (Stream.unfoldr f x) = unfoldr f x #-} ------------------------------------------------------------------------ -- * Sublists -- ** Extracting sublists -- | /O(n)/,/fusion/. 'take' @n@, applied to a list @xs@, returns the prefix of @xs@ of length @n@ , or @xs@ itself if @n > ' length ' xs@ : -- > take 5 " Hello World ! " = = " Hello " > take 3 [ 1,2,3,4,5 ] = = [ 1,2,3 ] > take 3 [ 1,2 ] = = [ 1,2 ] > take 3 [ ] = = [ ] -- > take (-1) [1,2] == [] > take 0 [ 1,2 ] = = [ ] -- It is an instance of the more general ' Data . List.genericTake ' , in which @n@ may be of any integral type . -- take :: Int -> [a] -> [a] take i _ | i <= 0 = [] take i ls = take' i ls where take' :: Int -> [a] -> [a] take' 0 _ = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs # NOINLINE [ 1 ] take # # RULES " take - > fusible " [ ~1 ] forall n x. take n x = unstream ( Stream.take n ( stream x ) ) --"take - > unfused " [ 1 ] forall n x. -- unstream ( Stream.take n ( stream x ) ) = take n x # "take -> fusible" [~1] forall n x. take n x = unstream (Stream.take n (stream x)) --"take -> unfused" [1] forall n x. -- unstream (Stream.take n (stream x)) = take n x #-} take : : Int - > [ a ] - > [ a ] take ( I # n # ) xs = takeUInt n # xs takeUInt : : Int # - > [ b ] - > [ b ] takeUInt n xs | n > = # 0 # = take_unsafe_UInt n xs | otherwise = [ ] take_unsafe_UInt : : Int # - > [ b ] - > [ b ] take_unsafe_UInt 0 # _ = [ ] take_unsafe_UInt m ls = case ls of [ ] - > [ ] ( x : xs ) - > x : take_unsafe_UInt ( m - # 1 # ) xs take :: Int -> [a] -> [a] take (I# n#) xs = takeUInt n# xs takeUInt :: Int# -> [b] -> [b] takeUInt n xs | n >=# 0# = take_unsafe_UInt n xs | otherwise = [] take_unsafe_UInt :: Int# -> [b] -> [b] take_unsafe_UInt 0# _ = [] take_unsafe_UInt m ls = case ls of [] -> [] (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs -} | /O(n)/,/fusion/. ' drop ' @n returns the suffix of @xs@ after the first @n@ elements , or @[]@ if @n > ' length ' xs@ : -- > drop 6 " Hello World ! " = = " World ! " > drop 3 [ 1,2,3,4,5 ] = = [ 4,5 ] > drop 3 [ 1,2 ] = = [ ] > drop 3 [ ] = = [ ] -- > drop (-1) [1,2] == [1,2] > drop 0 [ 1,2 ] = = [ 1,2 ] -- -- It is an instance of the more general 'Data.List.genericDrop', in which @n@ may be of any integral type . -- drop :: Int -> [a] -> [a] drop n ls | n < 0 = ls | otherwise = drop' n ls where drop' :: Int -> [a] -> [a] drop' 0 xs = xs drop' _ xs@[] = xs drop' m (_:xs) = drop' (m-1) xs # NOINLINE [ 1 ] drop # # RULES " drop - > fusible " [ ~1 ] forall n x. drop n x = unstream ( Stream.drop n ( stream x ) ) --"drop - > unfused " [ 1 ] forall n x. -- unstream ( Stream.drop n ( stream x ) ) = drop n x # "drop -> fusible" [~1] forall n x. drop n x = unstream (Stream.drop n (stream x)) --"drop -> unfused" [1] forall n x. -- unstream (Stream.drop n (stream x)) = drop n x #-} | ' splitAt ' @n returns a tuple where first element is @xs@ prefix of length @n@ and second element is the remainder of the list : -- > splitAt 6 " Hello World ! " = = ( " Hello " , " World ! " ) > splitAt 3 [ 1,2,3,4,5 ] = = ( [ 1,2,3],[4,5 ] ) > splitAt 1 [ 1,2,3 ] = = ( [ 1],[2,3 ] ) > splitAt 3 [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) > splitAt 4 [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) -- > splitAt 0 [1,2,3] == ([],[1,2,3]) -- > splitAt (-1) [1,2,3] == ([],[1,2,3]) -- -- It is equivalent to @('take' n xs, 'drop' n xs)@. -- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt', in which @n@ may be of any integral type . -- splitAt :: Int -> [a] -> ([a], [a]) splitAt n ls | n < 0 = ([], ls) | otherwise = splitAt' n ls where splitAt' :: Int -> [a] -> ([a], [a]) splitAt' 0 xs = ([], xs) splitAt' _ xs@[] = (xs, xs) splitAt' m (x:xs) = (x:xs', xs'') where (xs', xs'') = splitAt' (m-1) xs # NOINLINE [ 1 ] splitAt # {- splitAt n xs | n <= 0 = ([], xs) splitAt _ [] = ([], []) splitAt n (x:xs) = (x:xs', xs'') where (xs', xs'') = splitAt (n-1) xs -} # RULES " splitAt - > fusible " [ ~1 ] forall n xs . splitAt n xs = Stream.splitAt n ( stream xs ) --"splitAt - > unfused " [ 1 ] forall n xs . -- Stream.splitAt n ( stream xs ) = splitAt n xs # "splitAt -> fusible" [~1] forall n xs. splitAt n xs = Stream.splitAt n (stream xs) --"splitAt -> unfused" [1] forall n xs. -- Stream.splitAt n (stream xs) = splitAt n xs #-} -- | /O(n)/,/fusion/. 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the -- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@: -- > ( < 3 ) [ 1,2,3,4,1,2,3,4 ] = = [ 1,2 ] > ( < 9 ) [ 1,2,3 ] = = [ 1,2,3 ] > ( < 0 ) [ 1,2,3 ] = = [ ] -- takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p xs0 = go xs0 where go [] = [] go (x:xs) | p x = x : go xs | otherwise = [] # NOINLINE [ 1 ] takeWhile # # RULES " takeWhile - > fusible " [ ~1 ] forall f xs . takeWhile f xs = unstream ( Stream.takeWhile f ( stream xs ) ) --"takeWhile - > unfused " [ 1 ] forall f xs . -- unstream ( Stream.takeWhile f ( stream xs ) ) = takeWhile f xs # "takeWhile -> fusible" [~1] forall f xs. takeWhile f xs = unstream (Stream.takeWhile f (stream xs)) --"takeWhile -> unfused" [1] forall f xs. -- unstream (Stream.takeWhile f (stream xs)) = takeWhile f xs #-} | /O(n)/,/fusion/. ' dropWhile ' @p xs@ returns the suffix remaining after ' takeWhile ' @p xs@ : -- > dropWhile ( < 3 ) [ 1,2,3,4,5,1,2,3 ] = = [ 3,4,5,1,2,3 ] > dropWhile ( < 9 ) [ 1,2,3 ] = = [ ] -- > dropWhile (< 0) [1,2,3] == [1,2,3] -- dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p xs0 = go xs0 where go [] = [] go xs@(x:xs') | p x = go xs' | otherwise = xs # NOINLINE [ 1 ] dropWhile # # RULES " dropWhile - > fusible " [ ~1 ] forall f xs . dropWhile f xs = unstream ( Stream.dropWhile f ( stream xs ) ) --"dropWhile - > unfused " [ 1 ] forall f xs . -- unstream ( Stream.dropWhile f ( stream xs ) ) = dropWhile f xs # "dropWhile -> fusible" [~1] forall f xs. dropWhile f xs = unstream (Stream.dropWhile f (stream xs)) --"dropWhile -> unfused" [1] forall f xs. -- unstream (Stream.dropWhile f (stream xs)) = dropWhile f xs #-} -- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where first element is longest prefix ( possibly empty ) of @xs@ of elements that satisfy @p@ and second element is the remainder of the list : -- > span ( < 3 ) [ 1,2,3,4,1,2,3,4 ] = = ( [ 1,2],[3,4,1,2,3,4 ] ) > span ( < 9 ) [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) -- > span (< 0) [1,2,3] == ([],[1,2,3]) -- ' span ' @p xs@ is equivalent to @('takeWhile ' p xs , ' dropWhile ' p xs)@ span :: (a -> Bool) -> [a] -> ([a], [a]) span _ [] = ([], []) span p xs0 = go xs0 where go [] = ([], []) go xs@(x:xs') | p x = let (ys,zs) = go xs' in (x:ys,zs) | otherwise = ([],xs) TODO fuse -- Hmm, these do a lot of sharing, but is it worth it? -- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where first element is longest prefix ( possibly empty ) of @xs@ of elements that /do not satisfy/ @p@ and second element is the remainder of the list : -- > break ( > 3 ) [ 1,2,3,4,1,2,3,4 ] = = ( [ 1,2,3],[4,1,2,3,4 ] ) > break ( < 9 ) [ 1,2,3 ] = = ( [ ] , [ 1,2,3 ] ) > break ( > 9 ) [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) -- ' break ' @p@ is equivalent to @'span ' ( ' not ' . p)@. -- break :: (a -> Bool) -> [a] -> ([a], [a]) break _ [] = ([], []) break p xs0 = go xs0 where go [] = ([], []) go xs@(x:xs') | p x = ([],xs) | otherwise = let (ys,zs) = go xs' in (x:ys,zs) TODO fuse -- | The 'group' function takes a list and returns a list of lists such -- that the concatenation of the result is equal to the argument. Moreover, -- each sublist in the result contains only equal elements. For example, -- > group " Mississippi " = [ " M","i","ss","i","ss","i","pp","i " ] -- -- It is a special case of 'groupBy', which allows the programmer to supply -- their own equality test. group :: Eq a => [a] -> [[a]] group [] = [] group (x:xs) = (x:ys) : group zs where (ys,zs) = span (x ==) xs TODO fuse -- | The 'inits' function returns all initial segments of the argument, shortest first . For example , -- > inits " abc " = = [ " " , " a","ab","abc " ] -- inits :: [a] -> [[a]] inits [] = [] : [] inits (x:xs) = [] : map (x:) (inits xs) TODO fuse -- | The 'tails' function returns all final segments of the argument, -- longest first. For example, -- > tails " abc " = = [ " abc " , " bc " , " c " , " " ] -- tails :: [a] -> [[a]] tails [] = [] : [] tails xxs@(_:xs) = xxs : tails xs TODO fuse ------------------------------------------------------------------------ -- * Predicates | /O(n)/,/fusion/. The ' isPrefixOf ' function takes two lists and returns ' True ' iff the first list is a prefix of the second . -- isPrefixOf :: Eq a => [a] -> [a] -> Bool isPrefixOf [] _ = True isPrefixOf _ [] = False isPrefixOf (x:xs) (y:ys) | x == y = isPrefixOf xs ys | otherwise = False # NOINLINE [ 1 ] isPrefixOf # # RULES " isPrefixOf - > fusible " [ ~1 ] forall xs ys . isPrefixOf xs ys = Stream.isPrefixOf ( stream xs ) ( stream ys ) --"isPrefixOf - > unfused " [ 1 ] forall xs ys . -- Stream.isPrefixOf ( stream xs ) ( stream ys ) = # "isPrefixOf -> fusible" [~1] forall xs ys. isPrefixOf xs ys = Stream.isPrefixOf (stream xs) (stream ys) --"isPrefixOf -> unfused" [1] forall xs ys. -- Stream.isPrefixOf (stream xs) (stream ys) = isPrefixOf xs ys #-} | The ' isSuffixOf ' function takes two lists and returns ' True ' iff the first list is a suffix of the second . -- Both lists must be finite. isSuffixOf :: Eq a => [a] -> [a] -> Bool isSuffixOf x y = reverse x `isPrefixOf` reverse y TODO fuse | The ' isInfixOf ' function takes two lists and returns ' True ' iff the first list is contained , wholly and intact , anywhere within the second . -- -- Example: -- > isInfixOf " Haskell " " I really like . " - > True > isInfixOf " Ial " " I really like . " - > False -- isInfixOf :: Eq a => [a] -> [a] -> Bool isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack) TODO fuse -- --------------------------------------------------------------------- -- * Searching lists -- ** Searching by equality -- | /O(n)/, /fusion/. 'elem' is the list membership predicate, usually written -- in infix form, e.g., @x `elem` xs@. -- elem :: Eq a => a -> [a] -> Bool elem _ [] = False elem x (y:ys) | x == y = True | otherwise = elem x ys # NOINLINE [ 1 ] elem # # RULES " elem - > fusible " [ ~1 ] forall x xs . elem x xs = Stream.elem x ( stream xs ) --"elem - > unfused " [ 1 ] forall x xs . -- Stream.elem x ( stream xs ) = elem x xs # "elem -> fusible" [~1] forall x xs. elem x xs = Stream.elem x (stream xs) --"elem -> unfused" [1] forall x xs. -- Stream.elem x (stream xs) = elem x xs #-} -- | /O(n)/, /fusion/. 'notElem' is the negation of 'elem'. notElem :: Eq a => a -> [a] -> Bool notElem x xs = not (elem x xs) # INLINE notElem # RULES -- We do n't provide an expicilty fusible version , since not . elem is -- just as good . " notElem - > fusible " [ ~1 ] forall x xs . notElem x xs = Stream.notElem x ( stream xs ) " notElem - > unfused " [ 1 ] forall x xs . Stream.notElem x ( stream xs ) = notElem x xs -- We don't provide an expicilty fusible version, since not . elem is -- just as good. "notElem -> fusible" [~1] forall x xs. notElem x xs = Stream.notElem x (stream xs) "notElem -> unfused" [1] forall x xs. Stream.notElem x (stream xs) = notElem x xs -} -- | /O(n)/,/fusion/. 'lookup' @key assocs@ looks up a key in an association list. lookup :: Eq a => a -> [(a, b)] -> Maybe b lookup _ [] = Nothing lookup key xys0 = go xys0 where go [] = Nothing go ((x,y):xys) | key == x = Just y | otherwise = lookup key xys # NOINLINE [ 1 ] lookup # # RULES " lookup - > fusible " [ ~1 ] forall x xs . lookup x xs = Stream.lookup x ( stream xs ) --"lookup - > unfused " [ 1 ] forall x xs . -- Stream.lookup x ( stream xs ) = lookup x xs # "lookup -> fusible" [~1] forall x xs. lookup x xs = Stream.lookup x (stream xs) --"lookup -> unfused" [1] forall x xs. -- Stream.lookup x (stream xs) = lookup x xs #-} -- | /O(n)/,/fusion/. 'filter', applied to a predicate and a list, returns the list of -- those elements that satisfy the predicate; i.e., -- -- > filter p xs = [ x | x <- xs, p x] -- -- Properties: -- > filter p ( filter q s ) = filter ( \x - > q x & & p x ) s -- filter :: (a -> Bool) -> [a] -> [a] filter _ [] = [] filter p xs0 = go xs0 where go [] = [] go (x:xs) | p x = x : go xs | otherwise = go xs # NOINLINE [ 1 ] filter # # RULES " filter - > fusible " [ ~1 ] forall f xs . filter f xs = unstream ( Stream.filter f ( stream xs ) ) --"filter - > unfused " [ 1 ] forall f xs . -- unstream ( Stream.filter f ( stream xs ) ) = filter f xs # "filter -> fusible" [~1] forall f xs. filter f xs = unstream (Stream.filter f (stream xs)) --"filter -> unfused" [1] forall f xs. -- unstream (Stream.filter f (stream xs)) = filter f xs #-} ------------------------------------------------------------------------ -- ** Searching with a predicate -- | /O(n)/,/fusion/. The 'find' function takes a predicate and a list and returns the first element in the list matching the predicate , or ' Nothing ' if -- there is no such element. find :: (a -> Bool) -> [a] -> Maybe a find _ [] = Nothing find p xs0 = go xs0 where go [] = Nothing go (x:xs) | p x = Just x | otherwise = go xs # NOINLINE [ 1 ] find # # RULES " find - > fusible " [ ~1 ] forall f xs . find f xs = Stream.find f ( stream xs ) --"find - > unfused " [ 1 ] forall f xs . -- Stream.find f ( stream xs ) = find f xs # "find -> fusible" [~1] forall f xs. find f xs = Stream.find f (stream xs) --"find -> unfused" [1] forall f xs. -- Stream.find f (stream xs) = find f xs #-} -- | The 'partition' function takes a predicate a list and returns -- the pair of lists of elements which do and do not satisfy the -- predicate, respectively; i.e., -- -- > partition p xs == (filter p xs, filter (not . p) xs) partition :: (a -> Bool) -> [a] -> ([a], [a]) partition p xs = foldr (select p) ([],[]) xs # INLINE partition # TODO fuse select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a]) select p x ~(ts,fs) | p x = (x:ts,fs) | otherwise = (ts, x:fs) ------------------------------------------------------------------------ -- * Indexing lists -- | /O(n)/,/fusion/. List index (subscript) operator, starting from 0. -- It is an instance of the more general 'Data.List.genericIndex', -- which takes an index of any integral type. (!!) :: [a] -> Int -> a xs0 !! n0 | n0 < 0 = error "Prelude.(!!): negative index" | otherwise = index xs0 n0 #ifndef __HADDOCK__ where index [] _ = error "Prelude.(!!): index too large" index (y:ys) n = if n == 0 then y else index ys (n-1) #endif # NOINLINE [ 1 ] ( ! ! ) # # RULES " ! ! - > fusible " [ ~1 ] forall xs n. xs ! ! n = Stream.index ( stream xs ) n -- " ! ! - > unfused " [ 1 ] forall -- Stream.index ( stream xs ) n = xs ! ! n # "!! -> fusible" [~1] forall xs n. xs !! n = Stream.index (stream xs) n -- "!! -> unfused" [1] forall xs n. -- Stream.index (stream xs) n = xs !! n #-} | The ' elemIndex ' function returns the index of the first element -- in the given list which is equal (by '==') to the query element, -- or 'Nothing' if there is no such element. -- -- Properties: -- -- > elemIndex x xs = listToMaybe [ n | (n,a) <- zip [0..] xs, a == x ] -- > elemIndex x xs = findIndex (x==) xs -- elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex x = findIndex (x==) {-# INLINE elemIndex #-} elemIndex : : Eq a = > a - > [ a ] - > Maybe Int elemIndex y xs0 = loop_elemIndex xs0 0 # ifndef _ _ HADDOCK _ _ where loop_elemIndex [ ] ! _ = Nothing loop_elemIndex ( x : xs ) ! n | p x = Just n | otherwise = loop_elemIndex xs ( n + 1 ) p = ( y = { - # NOINLINE [ 1 ] elemIndex # elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex y xs0 = loop_elemIndex xs0 0 #ifndef __HADDOCK__ where loop_elemIndex [] !_ = Nothing loop_elemIndex (x:xs) !n | p x = Just n | otherwise = loop_elemIndex xs (n + 1) p = (y ==) #endif {-# NOINLINE [1] elemIndex #-} -} RULES " elemIndex - > fusible " [ ~1 ] forall x xs . elemIndex x xs = Stream.elemIndex x ( stream xs ) " elemIndex - > unfused " [ 1 ] forall x xs . Stream.elemIndex x ( stream xs ) = elemIndex x xs "elemIndex -> fusible" [~1] forall x xs. elemIndex x xs = Stream.elemIndex x (stream xs) "elemIndex -> unfused" [1] forall x xs. Stream.elemIndex x (stream xs) = elemIndex x xs -} -- | /O(n)/,/fusion/. The 'elemIndices' function extends 'elemIndex', by -- returning the indices of all elements equal to the query element, in -- ascending order. -- -- Properties: -- > length ( filter (= = a ) xs ) = length ( elemIndices a xs ) -- elemIndices :: Eq a => a -> [a] -> [Int] elemIndices x = findIndices (x==) # INLINE elemIndices # elemIndices : : Eq a = > a - > [ a ] - > [ Int ] elemIndices y xs0 = loop_elemIndices xs0 0 # ifndef _ _ HADDOCK _ _ where loop_elemIndices [ ] ! _ = [ ] loop_elemIndices ( x : xs ) ! n | p x = n : loop_elemIndices xs ( n + 1 ) | otherwise = loop_elemIndices xs ( n + 1 ) p = ( y = { - # NOINLINE [ 1 ] elemIndices # elemIndices :: Eq a => a -> [a] -> [Int] elemIndices y xs0 = loop_elemIndices xs0 0 #ifndef __HADDOCK__ where loop_elemIndices [] !_ = [] loop_elemIndices (x:xs) !n | p x = n : loop_elemIndices xs (n + 1) | otherwise = loop_elemIndices xs (n + 1) p = (y ==) #endif {-# NOINLINE [1] elemIndices #-} -} RULES " elemIndices - > fusible " [ ~1 ] forall x xs . elemIndices x xs = unstream ( Stream.elemIndices x ( stream xs ) ) " elemIndices - > unfused " [ 1 ] forall x xs . unstream ( Stream.elemIndices x ( stream xs ) ) = elemIndices x xs "elemIndices -> fusible" [~1] forall x xs. elemIndices x xs = unstream (Stream.elemIndices x (stream xs)) "elemIndices -> unfused" [1] forall x xs. unstream (Stream.elemIndices x (stream xs)) = elemIndices x xs -} -- | The 'findIndex' function takes a predicate and a list and returns the index of the first element in the list satisfying the predicate , -- or 'Nothing' if there is no such element. -- -- Properties: -- -- > findIndex p xs = listToMaybe [ n | (n,x) <- zip [0..] xs, p x ] -- findIndex :: (a -> Bool) -> [a] -> Maybe Int findIndex p ls = loop_findIndex ls 0# where loop_findIndex [] _ = Nothing loop_findIndex (x:xs) n | p x = Just (I# n) | otherwise = loop_findIndex xs (n +# 1#) # NOINLINE [ 1 ] findIndex # # RULES " findIndex - > fusible " [ ~1 ] forall f xs . findIndex f xs = Stream.findIndex f ( stream xs ) -- " findIndex - > unfused " [ 1 ] forall f xs . -- Stream.findIndex f ( stream xs ) = findIndex f xs # "findIndex -> fusible" [~1] forall f xs. findIndex f xs = Stream.findIndex f (stream xs) -- "findIndex -> unfused" [1] forall f xs. -- Stream.findIndex f (stream xs) = findIndex f xs #-} -- | /O(n)/,/fusion/. The 'findIndices' function extends 'findIndex', by -- returning the indices of all elements satisfying the predicate, in -- ascending order. -- -- Properties: -- > length ( filter p xs ) = length ( findIndices p xs ) -- findIndices :: (a -> Bool) -> [a] -> [Int] findIndices p ls = loop_findIndices ls 0# where loop_findIndices [] _ = [] loop_findIndices (x:xs) n | p x = I# n : loop_findIndices xs (n +# 1#) | otherwise = loop_findIndices xs (n +# 1#) # NOINLINE [ 1 ] findIndices # # RULES " findIndices - > fusible " [ ~1 ] forall p xs . findIndices p xs = unstream ( Stream.findIndices p ( stream xs ) ) -- " findIndices - > unfused " [ 1 ] forall p xs . -- unstream ( Stream.findIndices p ( stream xs ) ) = findIndices p xs # "findIndices -> fusible" [~1] forall p xs. findIndices p xs = unstream (Stream.findIndices p (stream xs)) -- "findIndices -> unfused" [1] forall p xs. -- unstream (Stream.findIndices p (stream xs)) = findIndices p xs #-} ------------------------------------------------------------------------ -- * Zipping and unzipping lists | /O(n)/,/fusion/. ' zip ' takes two lists and returns a list of corresponding pairs . If one input list is short , excess elements of -- the longer list are discarded. -- -- Properties: -- -- > zip a b = zipWith (,) a b -- zip :: [a] -> [b] -> [(a, b)] zip (a:as) (b:bs) = (a,b) : zip as bs zip _ _ = [] # NOINLINE [ 1 ] zip # # RULES " zip - > fusible " [ ~1 ] forall xs ys . zip xs ys = unstream ( Stream.zip ( stream xs ) ( stream ys ) ) -- " zip - > unfused " [ 1 ] forall xs ys . -- unstream ( Stream.zip ( stream xs ) ( stream ys ) ) = zip xs ys # "zip -> fusible" [~1] forall xs ys. zip xs ys = unstream (Stream.zip (stream xs) (stream ys)) -- "zip -> unfused" [1] forall xs ys. -- unstream (Stream.zip (stream xs) (stream ys)) = zip xs ys #-} | /O(n)/,/fusion/. ' zip3 ' takes three lists and returns a list of -- triples, analogous to 'zip'. -- -- Properties: -- -- > zip3 a b c = zipWith (,,) a b c -- zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs zip3 _ _ _ = [] # NOINLINE [ 1 ] zip3 # # RULES " zip3 - > fusible " [ ~1 ] forall xs ys zs . = unstream ( Stream.zipWith3 ( , , ) ( stream xs ) ( stream ys ) ( stream zs ) ) -- " zip3 - > unfused " [ 1 ] forall xs ys zs . -- unstream ( Stream.zipWith3 ( , , ) ( stream xs ) ( stream ys ) ( stream zs ) ) = zip3 xs ys zs # "zip3 -> fusible" [~1] forall xs ys zs. zip3 xs ys zs = unstream (Stream.zipWith3 (,,) (stream xs) (stream ys) (stream zs)) -- "zip3 -> unfused" [1] forall xs ys zs. -- unstream (Stream.zipWith3 (,,) (stream xs) (stream ys) (stream zs)) = zip3 xs ys zs #-} | /O(n)/,/fusion/. The ' zip4 ' function takes four lists and returns a list of -- quadruples, analogous to 'zip'. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] zip4 = zipWith4 (,,,) # INLINE zip4 # | The ' zip5 ' function takes five lists and returns a list of five - tuples , analogous to ' zip ' . zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] zip5 = zipWith5 (,,,,) | The ' ' function takes six lists and returns a list of six - tuples , -- analogous to 'zip'. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] zip6 = zipWith6 (,,,,,) | The ' zip7 ' function takes seven lists and returns a list of seven - tuples , analogous to ' zip ' . zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] zip7 = zipWith7 (,,,,,,) -- | /O(n)/,/fusion/. 'zipWith' generalises 'zip' by zipping with the function given as the first argument , instead of a tupling function . For example , @'zipWith ' ( + ) @ is applied to two lists to produce the -- list of corresponding sums. -- Properties: -- -- > zipWith (,) = zip -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith f (a:as) (b:bs) = f a b : zipWith f as bs zipWith _ _ _ = [] # INLINE [ 1 ] zipWith # FIXME : If we change the above INLINE to NOINLINE then ghc goes into -- a loop, why? Do we have some dodgy recursive rules somewhere? # RULES " zipWith - > fusible " [ ~1 ] forall f xs ys . zipWith f xs ys = unstream ( Stream.zipWith f ( stream xs ) ( stream ys ) ) -- " zipWith - > unfused " [ 1 ] forall f xs ys . -- unstream ( Stream.zipWith f ( stream xs ) ( stream ys ) ) = zipWith f xs ys # "zipWith -> fusible" [~1] forall f xs ys. zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys)) -- "zipWith -> unfused" [1] forall f xs ys. -- unstream (Stream.zipWith f (stream xs) (stream ys)) = zipWith f xs ys #-} -- | /O(n)/,/fusion/. The 'zipWith3' function takes a function which combines three elements , as well as three lists and returns a list of -- their point-wise combination, analogous to 'zipWith'. -- -- Properties: -- -- > zipWith3 (,,) = zip3 -- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] zipWith3 z (a:as) (b:bs) (c:cs) = z a b c : zipWith3 z as bs cs zipWith3 _ _ _ _ = [] # NOINLINE [ 1 ] zipWith3 # # RULES " zipWith3 - > fusible " [ ~1 ] forall f xs ys zs . zipWith3 f xs ys zs = unstream ( Stream.zipWith3 f ( stream xs ) ( stream ys ) ( stream zs ) ) -- " zipWith3 - > unfused " [ 1 ] forall f xs ys zs . -- unstream ( Stream.zipWith3 f ( stream xs ) ( stream ys ) ( stream zs ) ) = zipWith3 f xs ys zs # "zipWith3 -> fusible" [~1] forall f xs ys zs. zipWith3 f xs ys zs = unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs)) -- "zipWith3 -> unfused" [1] forall f xs ys zs. -- unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs)) = zipWith3 f xs ys zs #-} | /O(n)/,/fusion/. The ' zipWith4 ' function takes a function which combines four elements , as well as four lists and returns a list of their point - wise -- combination, analogous to 'zipWith'. zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] zipWith4 z (a:as) (b:bs) (c:cs) (d:ds) = z a b c d : zipWith4 z as bs cs ds zipWith4 _ _ _ _ _ = [] # NOINLINE [ 1 ] zipWith4 # # RULES " zipWith4 - > fusible " [ ~1 ] forall f ws xs ys zs . zipWith4 f ws xs ys zs = unstream ( Stream.zipWith4 f ( stream ws ) ( stream xs ) ( stream ys ) ( stream zs ) ) -- " zipWith4 - > unfused " [ 1 ] forall f ws xs ys zs . -- unstream ( Stream.zipWith4 f ( stream ws ) ( stream xs ) ( stream ys ) ( stream zs ) ) = # "zipWith4 -> fusible" [~1] forall f ws xs ys zs. zipWith4 f ws xs ys zs = unstream (Stream.zipWith4 f (stream ws) (stream xs) (stream ys) (stream zs)) -- "zipWith4 -> unfused" [1] forall f ws xs ys zs. -- unstream (Stream.zipWith4 f (stream ws) (stream xs) (stream ys) (stream zs)) = zipWith4 f ws xs ys zs #-} | The ' zipWith5 ' function takes a function which combines five elements , as well as five lists and returns a list of their point - wise -- combination, analogous to 'zipWith'. zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) = z a b c d e : zipWith5 z as bs cs ds es zipWith5 _ _ _ _ _ _ = [] TODO fuse | The ' zipWith6 ' function takes a function which combines six elements , as well as six lists and returns a list of their point - wise -- combination, analogous to 'zipWith'. zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) = z a b c d e f : zipWith6 z as bs cs ds es fs zipWith6 _ _ _ _ _ _ _ = [] TODO fuse | The ' zipWith7 ' function takes a function which combines seven elements , as well as seven lists and returns a list of their point - wise -- combination, analogous to 'zipWith'. zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) = z a b c d e f g : zipWith7 z as bs cs ds es fs gs zipWith7 _ _ _ _ _ _ _ _ = [] TODO fuse ------------------------------------------------------------------------ -- unzips | ' unzip ' transforms a list of pairs into a list of first components and a list of second components . unzip :: [(a, b)] -> ([a], [b]) unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[]) TODO fuse | The ' unzip3 ' function takes a list of triples and returns three -- lists, analogous to 'unzip'. unzip3 :: [(a, b, c)] -> ([a], [b], [c]) unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs)) ([],[],[]) TODO fuse | The ' ' function takes a list of quadruples and returns four -- lists, analogous to 'unzip'. unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d]) unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) -> (a:as,b:bs,c:cs,d:ds)) ([],[],[],[]) TODO fuse | The ' ' function takes a list of five - tuples and returns five -- lists, analogous to 'unzip'. unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) -> (a:as,b:bs,c:cs,d:ds,e:es)) ([],[],[],[],[]) TODO fuse | The ' unzip6 ' function takes a list of six - tuples and returns six -- lists, analogous to 'unzip'. unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) -> (a:as,b:bs,c:cs,d:ds,e:es,f:fs)) ([],[],[],[],[],[]) TODO fuse | The ' ' function takes a list of seven - tuples and returns seven lists , analogous to ' unzip ' . unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) -> (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs)) ([],[],[],[],[],[],[]) TODO fuse ------------------------------------------------------------------------ -- * Special lists -- ** Functions on strings -- | /O(O)/,/fusion/. 'lines' breaks a string up into a list of strings -- at newline characters. The resulting strings do not contain -- newlines. lines :: String -> [String] lines [] = [] lines s = let (l, s') = break (== '\n') s in l : case s' of [] -> [] (_:s'') -> lines s'' --TODO: can we do better than this and preserve the same strictness? {- -- This implementation is fast but too strict :-( -- it doesn't yield each line until it has seen the ending '\n' lines :: String -> [String] lines [] = [] lines cs0 = go [] cs0 where go l [] = reverse l : [] go l ('\n':cs) = reverse l : case cs of [] -> [] _ -> go [] cs go l ( c :cs) = go (c:l) cs -} # INLINE [ 1 ] lines # RULES " lines - > fusible " [ ~1 ] forall xs . lines xs = unstream ( Stream.lines ( stream xs ) ) " lines - > unfused " [ 1 ] forall xs . unstream ( Stream.lines ( stream xs ) ) = lines xs "lines -> fusible" [~1] forall xs. lines xs = unstream (Stream.lines (stream xs)) "lines -> unfused" [1] forall xs. unstream (Stream.lines (stream xs)) = lines xs -} -- | 'words' breaks a string up into a list of words, which were delimited -- by white space. words :: String -> [String] words s = case dropWhile isSpace s of "" -> [] s' -> w : words s'' where (w, s'') = break isSpace s' TODO fuse --TODO: can we do better than this and preserve the same strictness? {- -- This implementation is fast but too strict :-( -- it doesn't yield each word until it has seen the ending space words cs0 = dropSpaces cs0 where dropSpaces :: String -> [String] dropSpaces [] = [] dropSpaces (c:cs) | isSpace c = dropSpaces cs | otherwise = munchWord [c] cs munchWord :: String -> String -> [String] munchWord w [] = reverse w : [] munchWord w (c:cs) | isSpace c = reverse w : dropSpaces cs | otherwise = munchWord (c:w) cs -} -- | /O(n)/,/fusion/. 'unlines' is an inverse operation to 'lines'. -- It joins lines, after appending a terminating newline to each. -- -- > unlines xs = concatMap (++"\n") -- unlines :: [String] -> String unlines css0 = to css0 where go [] css = '\n' : to css go (c:cs) css = c : go cs css to [] = [] to (cs:css) = go cs css # NOINLINE [ 1 ] unlines # -- -- fuse via: -- unlines xs = concatMap (snoc xs '\n') -- RULES " unlines - > fusible " [ ~1 ] forall xs . unlines xs = unstream ( Stream.concatMap ( \x - > Stream.snoc ( stream x ) ' \n ' ) ( stream xs ) ) " unlines - > unfused " [ 1 ] forall xs . unstream ( Stream.concatMap ( \x - > Stream.snoc ( stream x ) ' \n ' ) ( stream xs ) ) = unlines xs "unlines -> fusible" [~1] forall xs. unlines xs = unstream (Stream.concatMap (\x -> Stream.snoc (stream x) '\n') (stream xs)) "unlines -> unfused" [1] forall xs. unstream (Stream.concatMap (\x -> Stream.snoc (stream x) '\n') (stream xs)) = unlines xs -} -- | 'unwords' is an inverse operation to 'words'. -- It joins words with separating spaces. unwords :: [String] -> String unwords [] = [] unwords (cs0:css0) = go cs0 css0 where go [] css = to css go (c:cs) css = c : go cs css to [] = [] to (cs:ccs) = ' ' : go cs ccs TODO fuse ------------------------------------------------------------------------ -- ** \"Set\" operations -- | The 'nub' function removes duplicate elements from a list. In particular , it keeps only the first occurrence of each element . ( The name ' nub ' means \`essence\ ' . ) -- It is a special case of 'nubBy', which allows the programmer to supply -- their own equality test. -- nub :: Eq a => [a] -> [a] nub l = nub' l [] where nub' [] _ = [] nub' (x:xs) ls | x `elem` ls = nub' xs ls | otherwise = x : nub' xs (x:ls) {- RULES -- ndm's optimisation "sort/nub" forall xs. sort (nub xs) = map head (group (sort xs)) -} TODO fuse | ' delete ' @x@ removes the first occurrence of @x@ from its list argument . -- For example, -- > delete ' a ' " banana " = = " " -- -- It is a special case of 'deleteBy', which allows the programmer to -- supply their own equality test. -- delete :: Eq a => a -> [a] -> [a] delete = deleteBy (==) TODO fuse -- | The '\\' function is list difference ((non-associative). In the result of @xs@ ' \\ ' @ys@ , the first occurrence of each element of -- @ys@ in turn (if any) has been removed from @xs@. Thus -- -- > (xs ++ ys) \\ xs == ys. -- -- It is a special case of 'deleteFirstsBy', which allows the programmer -- to supply their own equality test. (\\) :: Eq a => [a] -> [a] -> [a] (\\) = foldl (flip delete) | The ' union ' function returns the list union of the two lists . -- For example, -- -- > "dog" `union` "cow" == "dogcw" -- Duplicates , and elements of the first list , are removed from the the second list , but if the first list contains duplicates , so will -- the result. -- It is a special case of 'unionBy', which allows the programmer to supply -- their own equality test. -- union :: Eq a => [a] -> [a] -> [a] union = unionBy (==) TODO fuse | The ' intersect ' function takes the list intersection of two lists . -- For example, -- > [ 1,2,3,4 ] ` intersect ` [ 2,4,6,8 ] = = [ 2,4 ] -- If the first list contains duplicates , so will the result . -- It is a special case of 'intersectBy', which allows the programmer to -- supply their own equality test. -- intersect :: Eq a => [a] -> [a] -> [a] intersect = intersectBy (==) TODO fuse ------------------------------------------------------------------------ -- ** Ordered lists TODO stuff in Ord can use Map / IntMap , an Ord constraint ! we could use a better structure . -- | The 'sort' function implements a stable sorting algorithm. -- It is a special case of 'sortBy', which allows the programmer to supply -- their own comparison function. -- -- Properties: -- -- > not (null x) ==> (head . sort) x = minimum x -- > not (null x) ==> (last . sort) x = maximum x -- sort :: Ord a => [a] -> [a] sort l = mergesort compare l TODO fuse , we have an Ord constraint ! -- | /O(n)/,/fusion/. The 'insert' function takes an element and a list and inserts the -- element into the list at the last position where it is still less -- than or equal to the next element. In particular, if the list -- is sorted before the call, the result will also be sorted. -- It is a special case of 'insertBy', which allows the programmer to -- supply their own comparison function. -- insert :: Ord a => a -> [a] -> [a] insert e ls = insertBy (compare) e ls # INLINE insert # ------------------------------------------------------------------------ -- * Generalized functions -- ** The \"By\" operations * * * User - supplied equality ( replacing an Eq context ) -- | The 'nubBy' function behaves just like 'nub', except it uses a -- user-supplied equality predicate instead of the overloaded '==' -- function. nubBy :: (a -> a -> Bool) -> [a] -> [a] nubBy eq l = nubBy' l [] where nubBy' [] _ = [] nubBy' (y:ys) xs | elem_by eq y xs = nubBy' ys xs | otherwise = y : nubBy' ys (y:xs) TODO fuse -- Not exported: -- Note that we keep the call to `eq` with arguments in the -- same order as in the reference implementation -- 'xs' is the list of things we've seen so far, -- 'y' is the potential new element -- elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool elem_by _ _ [] = False elem_by eq y (x:xs) = if x `eq` y then True else elem_by eq y xs -- | The 'deleteBy' function behaves like 'delete', but takes a -- user-supplied equality predicate. deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] deleteBy _ _ [] = [] deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys TODO fuse deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] deleteFirstsBy eq = foldl (flip (deleteBy eq)) -- | The 'unionBy' function is the non-overloaded version of 'union'. unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs TODO fuse -- | The 'intersectBy' function is the non-overloaded version of 'intersect'. intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] intersectBy eq xs ys = [x | x <- xs, any (eq x) ys] TODO fuse -- | The 'groupBy' function is the non-overloaded version of 'group'. groupBy :: (a -> a -> Bool) -> [a] -> [[a]] groupBy _ [] = [] groupBy eq (x:xs) = (x:ys) : groupBy eq zs where (ys,zs) = span (eq x) xs TODO fuse ------------------------------------------------------------------------ * * * User - supplied comparison ( replacing an context ) -- | The 'sortBy' function is the non-overloaded version of 'sort'. sortBy :: (a -> a -> Ordering) -> [a] -> [a] sortBy cmp l = mergesort cmp l TODO fuse mergesort :: (a -> a -> Ordering) -> [a] -> [a] mergesort cmp xs = mergesort' cmp (map wrap xs) mergesort' :: (a -> a -> Ordering) -> [[a]] -> [a] mergesort' _ [] = [] mergesort' _ [xs] = xs mergesort' cmp xss = mergesort' cmp (merge_pairs cmp xss) merge_pairs :: (a -> a -> Ordering) -> [[a]] -> [[a]] merge_pairs _ [] = [] merge_pairs _ [xs] = [xs] merge_pairs cmp (xs:ys:xss) = merge cmp xs ys : merge_pairs cmp xss merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a] merge _ xs [] = xs merge _ [] ys = ys merge cmp (x:xs) (y:ys) = case x `cmp` y of GT -> y : merge cmp (x:xs) ys _ -> x : merge cmp xs (y:ys) wrap :: a -> [a] wrap x = [x] -- | /O(n)/,/fusion/. The non-overloaded version of 'insert'. insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a] insertBy _ x [] = [x] insertBy cmp x ys@(y:ys') = case cmp x y of GT -> y : insertBy cmp x ys' _ -> x : ys # NOINLINE [ 1 ] insertBy # # RULES " insertBy - > fusible " [ ~1 ] forall f x xs . insertBy f x xs = unstream ( Stream.insertBy f x ( stream xs ) ) -- " insertBy - > unfused " [ 1 ] forall f x xs . -- unstream ( Stream.insertBy f x ( stream xs ) ) = insertBy f x xs # "insertBy -> fusible" [~1] forall f x xs. insertBy f x xs = unstream (Stream.insertBy f x (stream xs)) -- "insertBy -> unfused" [1] forall f x xs. -- unstream (Stream.insertBy f x (stream xs)) = insertBy f x xs #-} -- | /O(n)/,/fusion/. The 'maximumBy' function takes a comparison function and a list -- and returns the greatest element of the list by the comparison function. -- The list must be finite and non-empty. -- maximumBy :: (a -> a -> Ordering) -> [a] -> a maximumBy _ [] = error "List.maximumBy: empty list" maximumBy cmp xs = foldl1 max' xs where max' x y = case cmp x y of GT -> x _ -> y # NOINLINE [ 1 ] maximumBy # # RULES " maximumBy - > fused " [ ~1 ] forall p xs . ( stream xs ) -- " maximumBy - > unfused " [ 1 ] forall p xs . -- Stream.maximumBy p ( stream xs ) = xs # "maximumBy -> fused" [~1] forall p xs. maximumBy p xs = Stream.maximumBy p (stream xs) -- "maximumBy -> unfused" [1] forall p xs. -- Stream.maximumBy p (stream xs) = maximumBy p xs #-} -- | /O(n)/,/fusion/. The 'minimumBy' function takes a comparison function and a list -- and returns the least element of the list by the comparison function. -- The list must be finite and non-empty. minimumBy :: (a -> a -> Ordering) -> [a] -> a minimumBy _ [] = error "List.minimumBy: empty list" minimumBy cmp xs = foldl1 min' xs where min' x y = case cmp x y of GT -> y _ -> x # NOINLINE [ 1 ] minimumBy # # RULES " minimumBy - > fused " [ ~1 ] forall p xs . minimumBy p xs = ( stream xs ) -- " minimumBy - > unfused " [ 1 ] forall p xs . -- ( stream xs ) = minimumBy p xs # "minimumBy -> fused" [~1] forall p xs. minimumBy p xs = Stream.minimumBy p (stream xs) -- "minimumBy -> unfused" [1] forall p xs. -- Stream.minimumBy p (stream xs) = minimumBy p xs #-} ------------------------------------------------------------------------ -- * The \"generic\" operations | The ' genericLength ' function is an overloaded version of ' length ' . In -- particular, instead of returning an 'Int', it returns any type which is an instance of ' ' . It is , however , less efficient than ' length ' . -- genericLength :: Num i => [b] -> i genericLength [] = 0 genericLength (_:l) = 1 + genericLength l # NOINLINE [ 1 ] genericLength # # RULES " genericLength - > fusible " [ ~1 ] forall xs . genericLength xs = Stream.genericLength ( stream xs ) -- " genericLength - > unfused " [ 1 ] forall xs . -- Stream.genericLength ( stream xs ) = genericLength xs # "genericLength -> fusible" [~1] forall xs. genericLength xs = Stream.genericLength (stream xs) -- "genericLength -> unfused" [1] forall xs. -- Stream.genericLength (stream xs) = genericLength xs #-} # RULES " genericLength - > length / Int " genericLength = length : : [ a ] - > Int # "genericLength -> length/Int" genericLength = length :: [a] -> Int #-} -- | /O(n)/,/fusion/. The 'genericTake' function is an overloaded version of 'take', which -- accepts any 'Integral' value as the number of elements to take. genericTake :: Integral i => i -> [a] -> [a] genericTake 0 _ = [] genericTake _ [] = [] genericTake n (x:xs) | n > 0 = x : genericTake (n-1) xs | otherwise = error "List.genericTake: negative argument" # NOINLINE [ 1 ] genericTake # # RULES " genericTake - > fusible " [ ~1 ] forall xs n. genericTake n xs = unstream ( Stream.genericTake n ( stream xs ) ) -- " genericTake - > unfused " [ 1 ] forall -- unstream ( Stream.genericTake n ( stream xs ) ) = genericTake n xs # "genericTake -> fusible" [~1] forall xs n. genericTake n xs = unstream (Stream.genericTake n (stream xs)) -- "genericTake -> unfused" [1] forall xs n. -- unstream (Stream.genericTake n (stream xs)) = genericTake n xs #-} {-# RULES "genericTake -> take/Int" genericTake = take :: Int -> [a] -> [a] #-} -- | /O(n)/,/fusion/. The 'genericDrop' function is an overloaded version of 'drop', which -- accepts any 'Integral' value as the number of elements to drop. genericDrop :: Integral i => i -> [a] -> [a] genericDrop 0 xs = xs genericDrop _ [] = [] genericDrop n (_:xs) | n > 0 = genericDrop (n-1) xs genericDrop _ _ = error "List.genericDrop: negative argument" # NOINLINE [ 1 ] genericDrop # # RULES " genericDrop - > fusible " [ ~1 ] forall xs n. genericDrop n xs = unstream ( Stream.genericDrop n ( stream xs ) ) -- " genericDrop - > unfused " [ 1 ] forall -- unstream ( Stream.genericDrop n ( stream xs ) ) = genericDrop n xs # "genericDrop -> fusible" [~1] forall xs n. genericDrop n xs = unstream (Stream.genericDrop n (stream xs)) -- "genericDrop -> unfused" [1] forall xs n. -- unstream (Stream.genericDrop n (stream xs)) = genericDrop n xs #-} {-# RULES "genericDrop -> drop/Int" genericDrop = drop :: Int -> [a] -> [a] #-} -- | /O(n)/,/fusion/. The 'genericIndex' function is an overloaded version of '!!', which -- accepts any 'Integral' value as the index. genericIndex :: Integral a => [b] -> a -> b genericIndex (x:_) 0 = x genericIndex (_:xs) n | n > 0 = genericIndex xs (n-1) | otherwise = error "List.genericIndex: negative argument." genericIndex _ _ = error "List.genericIndex: index too large." # NOINLINE [ 1 ] genericIndex # -- can we pull the n > 0 test out and do it just once? -- probably not since we don't know what n-1 does!! -- can only specialise it for sane Integral instances :-( # RULES " genericIndex - > fusible " [ ~1 ] forall xs n. genericIndex xs n = Stream.genericIndex ( stream xs ) n -- " genericIndex - > unfused " [ 1 ] forall -- ( stream xs ) n = genericIndex n xs # "genericIndex -> fusible" [~1] forall xs n. genericIndex xs n = Stream.genericIndex (stream xs) n -- "genericIndex -> unfused" [1] forall xs n. -- Stream.genericIndex (stream xs) n = genericIndex n xs #-} {-# RULES "genericIndex -> index/Int" genericIndex = (!!) :: [a] -> Int -> a #-} -- | /O(n)/,/fusion/. The 'genericSplitAt' function is an overloaded -- version of 'splitAt', which accepts any 'Integral' value as the -- position at which to split. -- genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) genericSplitAt 0 xs = ([],xs) genericSplitAt _ [] = ([],[]) genericSplitAt n (x:xs) | n > 0 = (x:xs',xs'') where (xs',xs'') = genericSplitAt (n-1) xs genericSplitAt _ _ = error "List.genericSplitAt: negative argument" # RULES " genericSplitAt - > fusible " [ ~1 ] forall xs n. genericSplitAt n xs = Stream.genericSplitAt n ( stream xs ) -- " genericSplitAt - > unfused " [ 1 ] forall -- Stream.genericSplitAt n ( stream xs ) = genericSplitAt n xs # "genericSplitAt -> fusible" [~1] forall xs n. genericSplitAt n xs = Stream.genericSplitAt n (stream xs) -- "genericSplitAt -> unfused" [1] forall xs n. -- Stream.genericSplitAt n (stream xs) = genericSplitAt n xs #-} {-# RULES "genericSplitAt -> splitAt/Int" genericSplitAt = splitAt :: Int -> [a] -> ([a], [a]) #-} -- | /O(n)/,/fusion/. The 'genericReplicate' function is an overloaded version of 'replicate', -- which accepts any 'Integral' value as the number of repetitions to make. -- genericReplicate :: Integral i => i -> a -> [a] genericReplicate n x = genericTake n (repeat x) # INLINE genericReplicate # # RULES " genericReplicate - > replicate / Int " genericReplicate = replicate : : Int - > a - > [ a ] # "genericReplicate -> replicate/Int" genericReplicate = replicate :: Int -> a -> [a] #-} -- --------------------------------------------------------------------- Internal utilities -- Common up near identical calls to `error' to reduce the number -- constant strings created when compiled: errorEmptyList :: String -> a errorEmptyList fun = moduleError fun "empty list" # NOINLINE errorEmptyList # moduleError :: String -> String -> a moduleError fun msg = error ("Data.List." ++ fun ++ ':':' ':msg) # NOINLINE moduleError # bottom :: a bottom = error "Data.List.Stream: bottom" # NOINLINE bottom #
null
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/8ea5efc614b23692fd208c611f749b788f09f596/test-project/stream-fusion/Data/List/Stream.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE MagicHash # | Module : Data.List.Stream License : BSD-style Maintainer : Stability : experimental Portability : portable based on stream fusion for sequences. Described in: * /Stream Fusion: From Lists to Streams to Nothing at All/, by </~dons/papers/CLS07.html> </~dons/papers/CSL06.html> See the source for the complete story: * </~dons/code/streams/list/Data/Stream.hs> This library is a drop in replacement for "Data.List". * Basic interface :: [a] -> [a] -> [a] :: [a] -> a :: [a] -> a :: [a] -> [a] :: [a] -> [a] :: [a] -> Bool :: [a] -> Int * List transformations :: (a -> b) -> [a] -> [b] :: [a] -> [a] :: a -> [a] -> [a] :: [a] -> [[a]] -> [a] :: [[a]] -> [[a]] * Reducing lists (folds) :: (a -> b -> a) -> a -> [b] -> a :: (a -> b -> a) -> a -> [b] -> a :: (a -> a -> a) -> [a] -> a :: (a -> a -> a) -> [a] -> a :: (a -> b -> b) -> b -> [a] -> b :: (a -> a -> a) -> [a] -> a ** Special folds :: [[a]] -> [a] :: (a -> [b]) -> [a] -> [b] :: [Bool] -> Bool :: [Bool] -> Bool :: (a -> Bool) -> [a] -> Bool :: (a -> Bool) -> [a] -> Bool * Building lists ** Scans :: (a -> b -> a) -> a -> [b] -> [a] :: (a -> a -> a) -> [a] -> [a] :: (a -> b -> b) -> b -> [a] -> [b] :: (a -> a -> a) -> [a] -> [a] ** Accumulating maps ** Infinite lists :: (a -> a) -> a -> [a] :: a -> [a] :: Int -> a -> [a] :: [a] -> [a] ** Unfolding :: (b -> Maybe (a, b)) -> b -> [a] * Sublists ** Extracting sublists :: Int -> [a] -> [a] :: Int -> [a] -> [a] :: Int -> [a] -> ([a], [a]) :: (a -> Bool) -> [a] -> [a] :: (a -> Bool) -> [a] -> [a] :: (a -> Bool) -> [a] -> ([a], [a]) :: (a -> Bool) -> [a] -> ([a], [a]) :: Eq a => [a] -> [[a]] :: [a] -> [[a]] :: [a] -> [[a]] * Predicates :: Eq a => [a] -> [a] -> Bool :: Eq a => [a] -> [a] -> Bool :: Eq a => [a] -> [a] -> Bool * Searching lists ** Searching by equality :: Eq a => a -> [a] -> Bool :: Eq a => a -> [a] -> Bool :: Eq a => a -> [(a, b)] -> Maybe b ** Searching with a predicate :: (a -> Bool) -> [a] -> Maybe a :: (a -> Bool) -> [a] -> [a] :: (a -> Bool) -> [a] -> ([a], [a]) * Indexing lists | These functions treat a list @xs@ as a indexed collection, with indices ranging from 0 to @'length' xs - 1@. :: [a] -> Int -> a :: Eq a => a -> [a] -> Maybe Int :: Eq a => a -> [a] -> [Int] :: (a -> Bool) -> [a] -> Maybe Int :: (a -> Bool) -> [a] -> [Int] * Zipping and unzipping lists :: [a] -> [b] -> [(a, b)] :: [a] -> [b] -> [c] -> [(a, b, c)] :: (a -> b -> c) -> [a] -> [b] -> [c] :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] :: [(a, b)] -> ([a], [b]) :: [(a, b, c)] -> ([a], [b], [c]) * Special lists ** Functions on strings :: String -> [String] :: String -> [String] :: [String] -> String :: [String] -> String ** \"Set\" operations :: Eq a => [a] -> [a] :: Eq a => a -> [a] -> [a] :: Eq a => [a] -> [a] -> [a] :: Eq a => [a] -> [a] -> [a] :: Eq a => [a] -> [a] -> [a] ** Ordered lists * Generalized functions ** The \"By\" operations | By convention, overloaded functions have a non-overloaded counterpart whose name is suffixed with \`@By@\'. It is often convenient to use these functions together with 'Data.Function.on', for instance @'sortBy' ('compare' \`on\` 'fst')@. | The predicate is assumed to define an equivalence. :: (a -> a -> Bool) -> [a] -> [a] :: (a -> a -> Bool) -> a -> [a] -> [a] :: (a -> a -> Bool) -> [a] -> [a] -> [a] :: (a -> a -> Bool) -> [a] -> [a] -> [a] :: (a -> a -> Bool) -> [a] -> [a] -> [a] :: (a -> a -> Bool) -> [a] -> [[a]] :: (a -> a -> Ordering) -> [a] -> [a] :: (a -> a -> Ordering) -> a -> [a] -> [a] :: (a -> a -> Ordering) -> [a] -> a :: (a -> a -> Ordering) -> [a] -> a * The \"generic\" operations | The prefix \`@generic@\' indicates an overloaded function that :: Integral i => i -> [a] -> [a] :: Integral i => i -> [a] -> [a] :: Integral i => i -> [a] -> ([a], [a]) :: Integral a => [b] -> a -> b :: Integral i => i -> a -> [a] :: String -> a # SOURCE # # SOURCE # # SOURCE # # SOURCE # we just reuse these: ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- The functions in this library marked with /fusion/ are (transparently) rewritten by the compiler to stream functions, using For example: > map f xs is transformed via rewrite rules to: The 'unstream' and 'stream' functions identify the allocation points for each function. directly composed, or with only intermediate lets and cases), the fusion rule will fire, removing the intermediate structures. Consider: The rewrite engine will transform this code to: The fusion rule will then fire: Removing the intermeidate list that is allocated. The compiler then optimises the result. Functions that fail to fuse are not left in stream form. In the final simplifier phase any remaining unfused functions of the form: > unstream . g . stream Will be transformed back to their original list implementation. * api functions should be rewritten to fusible forms as soon as possble to inline them they'll only have their bodies inlined at the end. * These rewrite rules can then fire in any but the last phase: "++ -> fusible" [~1] forall xs ys. * Finally, if we reach the final phase, rewrite back to best effort [a] forms: * And then inline the result. If fusion occurs though, hang on to those 'stream' and 'unstream' pairs: {-# INLINE [0] unstream #-} -- hmm? Todo: notes on the phasing of Streams ----------------------------------------------------------------------------- Fusion for the constructors: We do not enable fusion for (:), as it leads to a massive massive slow down in compilation time. ----------------------------------------------------------------------------- Basic interface > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...] NOTE: This is quite subtle as we do not want to copy the last list in xs1 ++ xs2 ++ ... ++ xsn Indeed, we don't really want to fuse the above at all unless at least one of the arguments has the form (unstream s) or the result of the concatenation is streamed. The rules below do precisely that. Note they really fuse instead of just rewriting things into a fusible form so there is no need to rewrite back. non-empty. "head - > unfused " [ 1 ] forall xs . Stream.head ( stream xs ) = head xs "head -> unfused" [1] forall xs. Stream.head (stream xs) = head xs | /O(n)/, /fusion/. Extract the last element of a list, which must be finite and non-empty. "last - > unfused " [ 1 ] forall xs . Stream.last ( stream xs ) = last xs "last -> unfused" [1] forall xs. Stream.last (stream xs) = last xs | /O(1)/, /fusion/. Extract the elements after the head of a list, which must be non-empty. "tail - > unfused " [ 1 ] forall xs . unstream ( Stream.tail ( stream xs ) ) = tail xs "tail -> unfused" [1] forall xs. unstream (Stream.tail (stream xs)) = tail xs | /O(n)/, /fusion/. Return all the elements of a list except the last one. The list must be finite and non-empty. "init - > unfused " [ 1 ] forall xs . unstream ( Stream.init ( stream xs ) ) = init xs "init -> unfused" [1] forall xs. unstream (Stream.init (stream xs)) = init xs | /O(1)/, /fusion/. Test whether a list is empty. "null - > unfused " [ 1 ] forall xs . Stream.null ( stream xs ) = null xs "null -> unfused" [1] forall xs. Stream.null (stream xs) = null xs | /O(n)/, /fusion/. 'length' returns the length of a finite list as an 'Int'. It is an instance of the more general 'Data.List.genericLength', the result type of which may be any kind of number. --------------------------------------------------------------------- List transformations > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] > map f [x1, x2, ...] == [f x1, f x2, ...] Properties: > map f (repeat x) = repeat (f x) > map f (replicate n x) = replicate n (f x) "map - > unfused " [ 1 ] forall f xs . unstream ( Stream.map f ( stream xs ) ) = map f xs "map -> unfused" [1] forall f xs. unstream (Stream.map f (stream xs)) = map f xs | /O(n)/, /fusion/. 'reverse' @xs@ returns the elements of @xs@ in reverse order. @xs@ must be finite. Will fuse as a consumer only. reverse l = rev l [] where rev [] a = a rev (x:xs) a = rev xs (x:a) TODO : I 'm sure there are some cunning things we can do with optimising reverse . Of course if we try and fuse we may need to still force the sping of the list : eg reverse . reverse = forceSpine TODO: I'm sure there are some cunning things we can do with optimising reverse. Of course if we try and fuse we may need to still force the sping of the list: eg reverse . reverse = forceSpine # INLINE forceSpine # The idea of this slightly odd construction is that we inline the above form and in the context we may then be able to use xs directly and just keep around the fact that xs must be forced at some point. Remember, seq does not imply any evaluation order. | /O(n)/, /fusion/. The 'intersperse' function takes an element and a list and For example, > intersperse ',' "abcde" == "a,b,c,d,e" It inserts the list @xs@ in between the lists in @xss@ and concatenates the result. > intercalate = concat . intersperse # NOINLINE [1] intercalate # fusion rule based on: intercalate = concat . intersperse | The 'transpose' function transposes the rows and columns of its argument. For example, > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]] --------------------------------------------------------------------- Reducing lists (folds) | /O(n)/, /fusion/. 'foldl', applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right: > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn The list must be finite. "foldl - > unfused " [ 1 ] forall f z xs . Stream.foldl f z ( stream xs ) = foldl f z xs "foldl -> unfused" [1] forall f z xs. Stream.foldl f z (stream xs) = foldl f z xs | /O(n)/, /fusion/. A strict version of 'foldl'. "foldl ' - > unfused " [ 1 ] forall f z xs . Stream.foldl ' f z ( stream xs ) = foldl ' f z xs "foldl' -> unfused" [1] forall f z xs. Stream.foldl' f z (stream xs) = foldl' f z xs and thus must be applied to non-empty lists. "foldl1 - > unfused " [ 1 ] forall f xs . Stream.foldl1 f ( stream xs ) = foldl1 f xs "foldl1 -> unfused" [1] forall f xs. Stream.foldl1 f (stream xs) = foldl1 f xs "foldl1 - > unfused " [ 1 ] forall f xs . Stream.foldl1 ' f ( stream xs ) = foldl1 ' f xs "foldl1 -> unfused" [1] forall f xs. Stream.foldl1' f (stream xs) = foldl1' f xs | /O(n)/, /fusion/. 'foldr', applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left: > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) # INLINE [0] foldr # "foldr - > unfused " [ 1 ] forall f z xs . Stream.foldr f z ( stream xs ) = foldr f z xs "foldr -> unfused" [1] forall f z xs. Stream.foldr f z (stream xs) = foldr f z xs and thus must be applied to non-empty lists. # INLINE [1] foldr1 # "foldr1 - > unfused " [ 1 ] forall f xs . Stream.foldr1 f ( stream xs ) = foldr1 f xs "foldr1 -> unfused" [1] forall f xs. Stream.foldr1 f (stream xs) = foldr1 f xs --------------------------------------------------------------------- Special folds hmm, this is slower than the old concat? fuse via concatMap, as the Stream (Stream a) is too hard to construct or via foldr (++) ? "concat - > unfused " [ 1 ] forall xs . Stream.concat ( stream xs ) = concat xs "concat -> unfused" [1] forall xs. Stream.concat (stream xs) = concat xs | /O(n)/, /fusion/. Map a function over a list and concatenate the results. at least it will fuse. # NOINLINE [1] concatMap # 'True', the list must be finite; 'False', however, results from a 'False' value at a finite index of a finite or infinite list. "and - > unfused " [ 1 ] forall xs . Stream.and ( stream xs ) = and xs "and -> unfused" [1] forall xs. Stream.and (stream xs) = and xs 'False', the list must be finite; 'True', however, results from a 'True' value at a finite index of a finite or infinite list. "or - > unfused " [ 1 ] forall xs . Stream.or ( stream xs ) = or xs "or -> unfused" [1] forall xs. Stream.or (stream xs) = or xs | /O(n)/, /fusion/. Applied to a predicate and a list, 'any' determines if any element of the list satisfies the predicate. "any - > unfused " [ 1 ] forall f xs . Stream.any f ( stream xs ) = any f xs "any -> unfused" [1] forall f xs. Stream.any f (stream xs) = any f xs | Applied to a predicate and a list, 'all' determines if all elements of the list satisfy the predicate. "all - > unfused " [ 1 ] forall f xs . Stream.all f ( stream xs ) = all f xs "all -> unfused" [1] forall f xs. Stream.all f (stream xs) = all f xs | /O(n)/, /fusion/. The 'sum' function computes the sum of a finite list of numbers. # RULES "sum spec Int" sum = sumInt :: [Int] -> Int # "sum - > unfused " [ 1 ] forall xs . Stream.sum ( stream xs ) = sum xs "sum -> unfused" [1] forall xs. Stream.sum (stream xs) = sum xs "sumInt - > unfused " [ 1 ] forall ( xs : : [ Int ] ) . Stream.sum ( stream xs ) = sumInt xs "sumInt -> unfused" [1] forall (xs :: [Int]). Stream.sum (stream xs) = sumInt xs | /O(n)/,/fusion/. The 'product' function computes the product of a finite list of numbers. # RULES "product spec Int" product = productInt :: [Int] -> Int # "product - > unfused " [ 1 ] forall xs . ( stream xs ) = product xs "product -> unfused" [1] forall xs. Stream.product (stream xs) = product xs "productInt - > unfused " [ 1 ] forall ( xs : : [ Int ] ) . ( stream xs ) = productInt xs "productInt -> unfused" [1] forall (xs :: [Int]). Stream.product (stream xs) = productInt xs | /O(n)/,/fusion/. 'maximum' returns the maximum value from a list, which must be non-empty, finite, and of an ordered type. It is a special case of 'Data.List.maximumBy', which allows the programmer to supply their own comparison function. "maximum - > unfused " [ 1 ] forall xs . Stream.maximum ( stream xs ) = maximum xs "maximum -> unfused" [1] forall xs. Stream.maximum (stream xs) = maximum xs We can't make the overloaded version of maximum strict without the version specialised to 'Int'. "strictMaximum - > unfused " [ 1 ] forall xs . Stream.strictMaximum ( stream xs ) = strictMaximum xs "strictMaximum -> unfused" [1] forall xs. Stream.strictMaximum (stream xs) = strictMaximum xs | /O(n)/,/fusion/. 'minimum' returns the minimum value from a list, which must be non-empty, finite, and of an ordered type. It is a special case of 'Data.List.minimumBy', which allows the programmer to supply their own comparison function. "minimum - > unfused " [ 1 ] forall xs . Stream.minimum ( stream xs ) = minimum xs "minimum -> unfused" [1] forall xs. Stream.minimum (stream xs) = minimum xs "strictMinimum - > unfused " [ 1 ] forall xs . Stream.strictMinimum ( stream xs ) = strictMinimum xs "strictMinimum -> unfused" [1] forall xs. Stream.strictMinimum (stream xs) = strictMinimum xs --------------------------------------------------------------------- * Building lists ** Scans reduced values from the left: Properties: state as a prefix. this complicates the rules. "scanl - > unfused " [ 1 ] forall f z xs . unstream ( Stream.scanl f z ( Stream.snoc ( stream xs ) bottom ) ) = f z xs "scanl -> unfused" [1] forall f z xs. unstream (Stream.scanl f z (Stream.snoc (stream xs) bottom)) = scanl f z xs # INLINE [1] scanl1 # "scanl1 - > unfused " [ 1 ] forall f xs . unstream ( Stream.scanl1 f ( Stream.snoc ( stream xs ) bottom ) ) = scanl1 f xs "scanl1 -> unfused" [1] forall f xs. unstream (Stream.scanl1 f (Stream.snoc (stream xs) bottom)) = scanl1 f xs Properties: --------------------------------------------------------------------- ** Accumulating maps | The 'mapAccumL' function behaves like a combination of 'map' and 'foldl'; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list. | The 'mapAccumR' function behaves like a combination of 'map' and 'foldr'; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list. ---------------------------------------------------------------------- ** Infinite lists > iterate f x == [x, f x, f (f x), ...] "iterate - > unfused " [ 1 ] forall f x. unstream ( Stream.iterate f x ) = iterate f x "iterate -> unfused" [1] forall f x. unstream (Stream.iterate f x) = iterate f x | /fusion/. 'repeat' @x@ is an infinite list, with @x@ the value of every element. "repeat - > unfused " [ 1 ] forall x. unstream ( Stream.repeat x ) = repeat x "repeat -> unfused" [1] forall x. unstream (Stream.repeat x) = repeat x every element. "replicate - > unfused " [ 1 ] forall n x. unstream ( Stream.replicate n x ) = replicate n x "replicate -> unfused" [1] forall n x. unstream (Stream.replicate n x) = replicate n x | /fusion/. 'cycle' ties a finite list into a circular one, or equivalently, the infinite repetition of the original list. It is the identity on infinite lists. "cycle - > unfused " [ 1 ] forall xs . unstream ( Stream.cycle ( stream xs ) ) = cycle xs "cycle -> unfused" [1] forall xs. unstream (Stream.cycle (stream xs)) = cycle xs --------------------------------------------------------------------- ** Unfolding | /fusion/. The 'unfoldr' function is a \`dual\' to 'foldr': while 'foldr' reduces a list to a summary value, 'unfoldr' builds a list from a seed value. The function takes the element and returns 'Nothing' if it is done producing the list or returns 'Just' @(a,b)@, in which element in a recursive call. For example, In some cases, 'unfoldr' can undo a 'foldr' operation: > unfoldr f' (foldr f z xs) == xs if the following holds: > f' (f x y) = Just (x,y) > f' z = Nothing A simple use of unfoldr: > [10,9,8,7,6,5,4,3,2,1] "unfoldr - > unfused " [ 1 ] forall f x. unstream ( Stream.unfoldr f x ) = unfoldr f x "unfoldr -> unfused" [1] forall f x. unstream (Stream.unfoldr f x) = unfoldr f x ---------------------------------------------------------------------- * Sublists ** Extracting sublists | /O(n)/,/fusion/. 'take' @n@, applied to a list @xs@, returns the prefix of @xs@ > take (-1) [1,2] == [] "take - > unfused " [ 1 ] forall n x. unstream ( Stream.take n ( stream x ) ) = take n x "take -> unfused" [1] forall n x. unstream (Stream.take n (stream x)) = take n x > drop (-1) [1,2] == [1,2] It is an instance of the more general 'Data.List.genericDrop', "drop - > unfused " [ 1 ] forall n x. unstream ( Stream.drop n ( stream x ) ) = drop n x "drop -> unfused" [1] forall n x. unstream (Stream.drop n (stream x)) = drop n x > splitAt 0 [1,2,3] == ([],[1,2,3]) > splitAt (-1) [1,2,3] == ([],[1,2,3]) It is equivalent to @('take' n xs, 'drop' n xs)@. 'splitAt' is an instance of the more general 'Data.List.genericSplitAt', splitAt n xs | n <= 0 = ([], xs) splitAt _ [] = ([], []) splitAt n (x:xs) = (x:xs', xs'') where (xs', xs'') = splitAt (n-1) xs "splitAt - > unfused " [ 1 ] forall n xs . Stream.splitAt n ( stream xs ) = splitAt n xs "splitAt -> unfused" [1] forall n xs. Stream.splitAt n (stream xs) = splitAt n xs | /O(n)/,/fusion/. 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the longest prefix (possibly empty) of @xs@ of elements that satisfy @p@: "takeWhile - > unfused " [ 1 ] forall f xs . unstream ( Stream.takeWhile f ( stream xs ) ) = takeWhile f xs "takeWhile -> unfused" [1] forall f xs. unstream (Stream.takeWhile f (stream xs)) = takeWhile f xs > dropWhile (< 0) [1,2,3] == [1,2,3] "dropWhile - > unfused " [ 1 ] forall f xs . unstream ( Stream.dropWhile f ( stream xs ) ) = dropWhile f xs "dropWhile -> unfused" [1] forall f xs. unstream (Stream.dropWhile f (stream xs)) = dropWhile f xs | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where > span (< 0) [1,2,3] == ([],[1,2,3]) Hmm, these do a lot of sharing, but is it worth it? | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where | The 'group' function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. For example, It is a special case of 'groupBy', which allows the programmer to supply their own equality test. | The 'inits' function returns all initial segments of the argument, | The 'tails' function returns all final segments of the argument, longest first. For example, ---------------------------------------------------------------------- * Predicates "isPrefixOf - > unfused " [ 1 ] forall xs ys . Stream.isPrefixOf ( stream xs ) ( stream ys ) = # "isPrefixOf -> unfused" [1] forall xs ys. Stream.isPrefixOf (stream xs) (stream ys) = isPrefixOf xs ys Both lists must be finite. Example: --------------------------------------------------------------------- * Searching lists ** Searching by equality | /O(n)/, /fusion/. 'elem' is the list membership predicate, usually written in infix form, e.g., @x `elem` xs@. "elem - > unfused " [ 1 ] forall x xs . Stream.elem x ( stream xs ) = elem x xs "elem -> unfused" [1] forall x xs. Stream.elem x (stream xs) = elem x xs | /O(n)/, /fusion/. 'notElem' is the negation of 'elem'. We do n't provide an expicilty fusible version , since not . elem is just as good . We don't provide an expicilty fusible version, since not . elem is just as good. | /O(n)/,/fusion/. 'lookup' @key assocs@ looks up a key in an association list. "lookup - > unfused " [ 1 ] forall x xs . Stream.lookup x ( stream xs ) = lookup x xs "lookup -> unfused" [1] forall x xs. Stream.lookup x (stream xs) = lookup x xs | /O(n)/,/fusion/. 'filter', applied to a predicate and a list, returns the list of those elements that satisfy the predicate; i.e., > filter p xs = [ x | x <- xs, p x] Properties: "filter - > unfused " [ 1 ] forall f xs . unstream ( Stream.filter f ( stream xs ) ) = filter f xs "filter -> unfused" [1] forall f xs. unstream (Stream.filter f (stream xs)) = filter f xs ---------------------------------------------------------------------- ** Searching with a predicate | /O(n)/,/fusion/. The 'find' function takes a predicate and a list and returns the there is no such element. "find - > unfused " [ 1 ] forall f xs . Stream.find f ( stream xs ) = find f xs "find -> unfused" [1] forall f xs. Stream.find f (stream xs) = find f xs | The 'partition' function takes a predicate a list and returns the pair of lists of elements which do and do not satisfy the predicate, respectively; i.e., > partition p xs == (filter p xs, filter (not . p) xs) ---------------------------------------------------------------------- * Indexing lists | /O(n)/,/fusion/. List index (subscript) operator, starting from 0. It is an instance of the more general 'Data.List.genericIndex', which takes an index of any integral type. " ! ! - > unfused " [ 1 ] forall -- Stream.index ( stream xs ) n = xs ! ! n "!! -> unfused" [1] forall xs n. Stream.index (stream xs) n = xs !! n in the given list which is equal (by '==') to the query element, or 'Nothing' if there is no such element. Properties: > elemIndex x xs = listToMaybe [ n | (n,a) <- zip [0..] xs, a == x ] > elemIndex x xs = findIndex (x==) xs # INLINE elemIndex # # NOINLINE [1] elemIndex # | /O(n)/,/fusion/. The 'elemIndices' function extends 'elemIndex', by returning the indices of all elements equal to the query element, in ascending order. Properties: # NOINLINE [1] elemIndices # | The 'findIndex' function takes a predicate and a list and returns or 'Nothing' if there is no such element. Properties: > findIndex p xs = listToMaybe [ n | (n,x) <- zip [0..] xs, p x ] " findIndex - > unfused " [ 1 ] forall f xs . Stream.findIndex f ( stream xs ) = findIndex f xs "findIndex -> unfused" [1] forall f xs. Stream.findIndex f (stream xs) = findIndex f xs | /O(n)/,/fusion/. The 'findIndices' function extends 'findIndex', by returning the indices of all elements satisfying the predicate, in ascending order. Properties: " findIndices - > unfused " [ 1 ] forall p xs . unstream ( Stream.findIndices p ( stream xs ) ) = findIndices p xs "findIndices -> unfused" [1] forall p xs. unstream (Stream.findIndices p (stream xs)) = findIndices p xs ---------------------------------------------------------------------- * Zipping and unzipping lists the longer list are discarded. Properties: > zip a b = zipWith (,) a b " zip - > unfused " [ 1 ] forall xs ys . unstream ( Stream.zip ( stream xs ) ( stream ys ) ) = zip xs ys "zip -> unfused" [1] forall xs ys. unstream (Stream.zip (stream xs) (stream ys)) = zip xs ys triples, analogous to 'zip'. Properties: > zip3 a b c = zipWith (,,) a b c " zip3 - > unfused " [ 1 ] forall xs ys zs . unstream ( Stream.zipWith3 ( , , ) ( stream xs ) ( stream ys ) ( stream zs ) ) = zip3 xs ys zs "zip3 -> unfused" [1] forall xs ys zs. unstream (Stream.zipWith3 (,,) (stream xs) (stream ys) (stream zs)) = zip3 xs ys zs quadruples, analogous to 'zip'. analogous to 'zip'. | /O(n)/,/fusion/. 'zipWith' generalises 'zip' by zipping with the list of corresponding sums. Properties: > zipWith (,) = zip a loop, why? Do we have some dodgy recursive rules somewhere? " zipWith - > unfused " [ 1 ] forall f xs ys . unstream ( Stream.zipWith f ( stream xs ) ( stream ys ) ) = zipWith f xs ys "zipWith -> unfused" [1] forall f xs ys. unstream (Stream.zipWith f (stream xs) (stream ys)) = zipWith f xs ys | /O(n)/,/fusion/. The 'zipWith3' function takes a function which their point-wise combination, analogous to 'zipWith'. Properties: > zipWith3 (,,) = zip3 " zipWith3 - > unfused " [ 1 ] forall f xs ys zs . unstream ( Stream.zipWith3 f ( stream xs ) ( stream ys ) ( stream zs ) ) = zipWith3 f xs ys zs "zipWith3 -> unfused" [1] forall f xs ys zs. unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs)) = zipWith3 f xs ys zs combination, analogous to 'zipWith'. " zipWith4 - > unfused " [ 1 ] forall f ws xs ys zs . unstream ( Stream.zipWith4 f ( stream ws ) ( stream xs ) ( stream ys ) ( stream zs ) ) = "zipWith4 -> unfused" [1] forall f ws xs ys zs. unstream (Stream.zipWith4 f (stream ws) (stream xs) (stream ys) (stream zs)) = zipWith4 f ws xs ys zs combination, analogous to 'zipWith'. combination, analogous to 'zipWith'. combination, analogous to 'zipWith'. ---------------------------------------------------------------------- unzips lists, analogous to 'unzip'. lists, analogous to 'unzip'. lists, analogous to 'unzip'. lists, analogous to 'unzip'. ---------------------------------------------------------------------- * Special lists ** Functions on strings | /O(O)/,/fusion/. 'lines' breaks a string up into a list of strings at newline characters. The resulting strings do not contain newlines. TODO: can we do better than this and preserve the same strictness? -- This implementation is fast but too strict :-( -- it doesn't yield each line until it has seen the ending '\n' lines :: String -> [String] lines [] = [] lines cs0 = go [] cs0 where go l [] = reverse l : [] go l ('\n':cs) = reverse l : case cs of [] -> [] _ -> go [] cs go l ( c :cs) = go (c:l) cs | 'words' breaks a string up into a list of words, which were delimited by white space. TODO: can we do better than this and preserve the same strictness? -- This implementation is fast but too strict :-( -- it doesn't yield each word until it has seen the ending space words cs0 = dropSpaces cs0 where dropSpaces :: String -> [String] dropSpaces [] = [] dropSpaces (c:cs) | isSpace c = dropSpaces cs | otherwise = munchWord [c] cs munchWord :: String -> String -> [String] munchWord w [] = reverse w : [] munchWord w (c:cs) | isSpace c = reverse w : dropSpaces cs | otherwise = munchWord (c:w) cs | /O(n)/,/fusion/. 'unlines' is an inverse operation to 'lines'. It joins lines, after appending a terminating newline to each. > unlines xs = concatMap (++"\n") fuse via: unlines xs = concatMap (snoc xs '\n') | 'unwords' is an inverse operation to 'words'. It joins words with separating spaces. ---------------------------------------------------------------------- ** \"Set\" operations | The 'nub' function removes duplicate elements from a list. It is a special case of 'nubBy', which allows the programmer to supply their own equality test. RULES -- ndm's optimisation "sort/nub" forall xs. sort (nub xs) = map head (group (sort xs)) For example, It is a special case of 'deleteBy', which allows the programmer to supply their own equality test. | The '\\' function is list difference ((non-associative). @ys@ in turn (if any) has been removed from @xs@. Thus > (xs ++ ys) \\ xs == ys. It is a special case of 'deleteFirstsBy', which allows the programmer to supply their own equality test. For example, > "dog" `union` "cow" == "dogcw" the result. It is a special case of 'unionBy', which allows the programmer to supply their own equality test. For example, It is a special case of 'intersectBy', which allows the programmer to supply their own equality test. ---------------------------------------------------------------------- ** Ordered lists | The 'sort' function implements a stable sorting algorithm. It is a special case of 'sortBy', which allows the programmer to supply their own comparison function. Properties: > not (null x) ==> (head . sort) x = minimum x > not (null x) ==> (last . sort) x = maximum x | /O(n)/,/fusion/. The 'insert' function takes an element and a list and inserts the element into the list at the last position where it is still less than or equal to the next element. In particular, if the list is sorted before the call, the result will also be sorted. It is a special case of 'insertBy', which allows the programmer to supply their own comparison function. ---------------------------------------------------------------------- * Generalized functions ** The \"By\" operations | The 'nubBy' function behaves just like 'nub', except it uses a user-supplied equality predicate instead of the overloaded '==' function. Not exported: Note that we keep the call to `eq` with arguments in the same order as in the reference implementation 'xs' is the list of things we've seen so far, 'y' is the potential new element | The 'deleteBy' function behaves like 'delete', but takes a user-supplied equality predicate. | The 'unionBy' function is the non-overloaded version of 'union'. | The 'intersectBy' function is the non-overloaded version of 'intersect'. | The 'groupBy' function is the non-overloaded version of 'group'. ---------------------------------------------------------------------- | The 'sortBy' function is the non-overloaded version of 'sort'. | /O(n)/,/fusion/. The non-overloaded version of 'insert'. " insertBy - > unfused " [ 1 ] forall f x xs . unstream ( Stream.insertBy f x ( stream xs ) ) = insertBy f x xs "insertBy -> unfused" [1] forall f x xs. unstream (Stream.insertBy f x (stream xs)) = insertBy f x xs | /O(n)/,/fusion/. The 'maximumBy' function takes a comparison function and a list and returns the greatest element of the list by the comparison function. The list must be finite and non-empty. " maximumBy - > unfused " [ 1 ] forall p xs . Stream.maximumBy p ( stream xs ) = xs "maximumBy -> unfused" [1] forall p xs. Stream.maximumBy p (stream xs) = maximumBy p xs | /O(n)/,/fusion/. The 'minimumBy' function takes a comparison function and a list and returns the least element of the list by the comparison function. The list must be finite and non-empty. " minimumBy - > unfused " [ 1 ] forall p xs . ( stream xs ) = minimumBy p xs "minimumBy -> unfused" [1] forall p xs. Stream.minimumBy p (stream xs) = minimumBy p xs ---------------------------------------------------------------------- * The \"generic\" operations particular, instead of returning an 'Int', it returns any type which is " genericLength - > unfused " [ 1 ] forall xs . Stream.genericLength ( stream xs ) = genericLength xs "genericLength -> unfused" [1] forall xs. Stream.genericLength (stream xs) = genericLength xs | /O(n)/,/fusion/. The 'genericTake' function is an overloaded version of 'take', which accepts any 'Integral' value as the number of elements to take. " genericTake - > unfused " [ 1 ] forall -- unstream ( Stream.genericTake n ( stream xs ) ) = genericTake n xs "genericTake -> unfused" [1] forall xs n. unstream (Stream.genericTake n (stream xs)) = genericTake n xs # RULES "genericTake -> take/Int" genericTake = take :: Int -> [a] -> [a] # | /O(n)/,/fusion/. The 'genericDrop' function is an overloaded version of 'drop', which accepts any 'Integral' value as the number of elements to drop. " genericDrop - > unfused " [ 1 ] forall -- unstream ( Stream.genericDrop n ( stream xs ) ) = genericDrop n xs "genericDrop -> unfused" [1] forall xs n. unstream (Stream.genericDrop n (stream xs)) = genericDrop n xs # RULES "genericDrop -> drop/Int" genericDrop = drop :: Int -> [a] -> [a] # | /O(n)/,/fusion/. The 'genericIndex' function is an overloaded version of '!!', which accepts any 'Integral' value as the index. can we pull the n > 0 test out and do it just once? probably not since we don't know what n-1 does!! can only specialise it for sane Integral instances :-( " genericIndex - > unfused " [ 1 ] forall -- ( stream xs ) n = genericIndex n xs "genericIndex -> unfused" [1] forall xs n. Stream.genericIndex (stream xs) n = genericIndex n xs # RULES "genericIndex -> index/Int" genericIndex = (!!) :: [a] -> Int -> a # | /O(n)/,/fusion/. The 'genericSplitAt' function is an overloaded version of 'splitAt', which accepts any 'Integral' value as the position at which to split. " genericSplitAt - > unfused " [ 1 ] forall -- Stream.genericSplitAt n ( stream xs ) = genericSplitAt n xs "genericSplitAt -> unfused" [1] forall xs n. Stream.genericSplitAt n (stream xs) = genericSplitAt n xs # RULES "genericSplitAt -> splitAt/Int" genericSplitAt = splitAt :: Int -> [a] -> ([a], [a]) # | /O(n)/,/fusion/. The 'genericReplicate' function is an overloaded version of 'replicate', which accepts any 'Integral' value as the number of repetitions to make. --------------------------------------------------------------------- Common up near identical calls to `error' to reduce the number constant strings created when compiled:
Copyright : ( c ) 2007 ( c ) 2007 - 2013 A reimplementation of the standard list library to take advantage of stream fusion , and new GHC optimisations . The fusion mechanism is , and , ICFP 2007 . * /Rewriting Haskell Strings/ , by , and Roman Leshchinskiy , Practical Aspects of Declarative Languages 8th International Symposium , PADL 2007 , 2007 . module Data.List.Stream ( $ fusion_intro : : a = > [ a ] - > a : : a = > [ a ] - > a : : a = > [ a ] - > a : : a = > [ a ] - > a : : ( acc - > x - > ( acc , y ) ) - > acc - > [ x ] - > ( acc , [ y ] ) : : ( acc - > x - > ( acc , y ) ) - > acc - > [ x ] - > ( acc , [ y ] ) zip4, zip5, zip6, zip7, | The zipWith family generalises the zip family by zipping with the function given as the first argument , instead of a tupling function . zipWith4, zipWith5, zipWith6, zipWith7, unzip4, unzip5, unzip6, unzip7, : : a = > [ a ] - > [ a ] : : a = > a - > [ a ] - > [ a ] * * * User - supplied equality ( replacing an Eq context ) * * * User - supplied comparison ( replacing an context ) is a generalized version of a " Prelude " function . : : i = > [ b ] - > i helper for GHC.List ) where #ifndef EXTERNAL_PACKAGE import GHC.Base (Int, Eq(..), Ord(..), Ordering(..), Bool(..), not, Ordering(..), seq, otherwise, flip, Monad(..), Char, String, Int(I#), Int#, (+#), foldr, (++), map ) import Data.Maybe (Maybe(..)) #else import GHC.Exts (Int(I#), Int#, (+#)) import Prelude (Int, Integral, Num(..), Eq(..), Ord(..), Ordering(..), Bool(..), not, Maybe(..), Char, String, error, seq, otherwise, flip) import Data.Char (isSpace) #endif import qualified Data.Stream as Stream import Data.Stream (stream ,unstream) #ifdef EXTERNAL_PACKAGE infixr 5 ++ #endif comment to fool infixl 9 !! infix 4 `elem`, `notElem` $ fusion_intro the fusion framework described in /Rewriting Haskell Strings/. > ( unstream . mapS f . ) xs When two or more fusible functions are in close proximity ( i.e. > map f . map > unstream . mapS f . . unstream . . stream > unstream . mapS f . . stream Notes on simplifer phasing * This implies a NOINLINE [ 1 ] on the top level functions , so if ghc wants " + + - > unfused " [ 1 ] forall xs ys . RULES " (: ) - > fusible " [ ~1 ] forall x xs . x : xs = unstream ( Stream.cons x ( stream xs ) ) " (: ) - > unfused " [ 1 ] forall x xs . unstream ( Stream.cons x ( stream xs ) ) = x : xs "(:) -> fusible" [~1] forall x xs. x : xs = unstream (Stream.cons x (stream xs)) "(:) -> unfused" [1] forall x xs. unstream (Stream.cons x (stream xs)) = x : xs -} | /O(n)/ , /fusion/. Append two lists , i.e. , If the first list is not finite , the result is the first list . The spine of the first list argument must be copied . #ifdef EXTERNAL_PACKAGE (++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys # NOINLINE [ 1 ] ( + + ) # #endif # RULES " + + - > fused on 1st arg " [ ~1 ] forall xs ys . unstream xs + + ys = " + + - > fused on 2nd arg " [ ~1 ] forall xs ys . ( unstream ys ) = unstream ( Stream.append xs ys ) " + + - > fused ( 1 ) " [ ~1 ] forall xs ys . stream ( xs + + ys ) = Stream.append ( stream xs ) ( stream ys ) " + + - > fused ( 2 ) " [ ~1 ] forall xs ys . stream ( ) = Stream.append xs ( stream ys ) " + + - > 1st arg empty " forall xs . [ ] + + xs = xs " + + - > 2nd arg empty " forall xs . xs + + [ ] = xs " + + / : " forall x xs ys . ( x : xs ) + + ys = x : ( xs + + ys ) # "++ -> fused on 1st arg" [~1] forall xs ys. unstream xs ++ ys = Stream.append1 xs ys "++ -> fused on 2nd arg" [~1] forall xs ys. Stream.append1 xs (unstream ys) = unstream (Stream.append xs ys) "++ -> fused (1)" [~1] forall xs ys. stream (xs ++ ys) = Stream.append (stream xs) (stream ys) "++ -> fused (2)" [~1] forall xs ys. stream (Stream.append1 xs ys) = Stream.append xs (stream ys) "++ -> 1st arg empty" forall xs. [] ++ xs = xs "++ -> 2nd arg empty" forall xs. xs ++ [] = xs "++ / :" forall x xs ys. (x:xs) ++ ys = x : (xs ++ ys) #-} | /O(1)/ , /fusion/. Extract the first element of a list , which must be head :: [a] -> a head (x:_) = x head [] = errorEmptyList "head" # NOINLINE [ 1 ] head # # RULES " head - > fusible " [ ~1 ] forall xs . head xs = Stream.head ( stream xs ) # "head -> fusible" [~1] forall xs. head xs = Stream.head (stream xs) #-} last :: [a] -> a last [] = errorEmptyList "last" last (x:xs) = last' x xs where last' y [] = y last' _ (y:ys) = last' y ys # NOINLINE [ 1 ] last # # RULES " last - > fusible " [ ~1 ] forall xs . last xs = Stream.last ( stream xs ) # "last -> fusible" [~1] forall xs. last xs = Stream.last (stream xs) #-} tail :: [a] -> [a] tail (_:xs) = xs tail [] = errorEmptyList "tail" # NOINLINE [ 1 ] tail # # RULES " tail - > fusible " [ ~1 ] forall xs . tail xs = unstream ( Stream.tail ( stream xs ) ) # "tail -> fusible" [~1] forall xs. tail xs = unstream (Stream.tail (stream xs)) #-} init :: [a] -> [a] init [] = errorEmptyList "init" init (x:xs) = init' x xs where init' _ [] = [] init' y (z:zs) = y : init' z zs # NOINLINE [ 1 ] init # # RULES " init - > fusible " [ ~1 ] forall xs . init xs = unstream ( Stream.init ( stream xs ) ) # "init -> fusible" [~1] forall xs. init xs = unstream (Stream.init (stream xs)) #-} null :: [a] -> Bool null [] = True null (_:_) = False # NOINLINE [ 1 ] null # # RULES " null - > fusible " [ ~1 ] forall xs . null xs = Stream.null ( stream xs ) # "null -> fusible" [~1] forall xs. null xs = Stream.null (stream xs) #-} length :: [a] -> Int length xs0 = len xs0 0# #ifndef __HADDOCK__ where len :: [a] -> Int# -> Int len [] a# = I# a# len (_:xs) a# = len xs (a# +# 1#) #endif # NOINLINE [ 1 ] length # # RULES " length - > fusible " [ ~1 ] forall xs . length xs = Stream.length ( stream xs ) " length - > unfused " [ 1 ] forall xs . Stream.length ( stream xs ) = length xs # "length -> fusible" [~1] forall xs. length xs = Stream.length (stream xs) "length -> unfused" [1] forall xs. Stream.length (stream xs) = length xs #-} | /O(n)/ , /fusion/. ' map ' is the list obtained by applying @f@ to each element of @xs@ , i.e. , > map f . map = map ( f . ) #ifdef EXTERNAL_PACKAGE map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = f x : map f xs # NOINLINE [ 1 ] map # #endif # RULES " map - > fusible " [ ~1 ] forall f xs . map f xs = unstream ( Stream.map f ( stream xs ) ) # "map -> fusible" [~1] forall f xs. map f xs = unstream (Stream.map f (stream xs)) #-} reverse :: [a] -> [a] reverse = foldl' (flip (:)) [] # INLINE reverse # forceSpine : : [ a ] - > [ a ] forceSpine xs = forceSpine ' xs ` seq ` xs { - # INLINE forceSpine # forceSpine :: [a] -> [a] forceSpine xs = forceSpine' xs `seq` xs forceSpine' :: [a] -> () forceSpine' [] = () forceSpine' (_:xs') = forceSpine' xs' # NOINLINE forceSpine ' # -} ' that element between the elements of the list . intersperse :: a -> [a] -> [a] intersperse _ [] = [] intersperse sep (x0:xs0) = x0 : go xs0 where go [] = [] go (x:xs) = sep : x : go xs # NOINLINE [ 1 ] intersperse # RULES " intersperse - > fusible " [ ~1 ] forall x xs . intersperse x xs = unstream ( Stream.intersperse x ( stream xs ) ) " intersperse - > unfused " [ 1 ] forall x xs . unstream ( Stream.intersperse x ( stream xs ) ) = intersperse x xs "intersperse -> fusible" [~1] forall x xs. intersperse x xs = unstream (Stream.intersperse x (stream xs)) "intersperse -> unfused" [1] forall x xs. unstream (Stream.intersperse x (stream xs)) = intersperse x xs -} | /O(n)/ , /fusion/. ' intercalate ' @xs xss@ is equivalent to @('concat ' ( ' intersperse ' xs xss))@. intercalate :: [a] -> [[a]] -> [a] intercalate sep xss = go (intersperse sep xss) where go [] = [] go (y:ys) = y ++ go ys # NOINLINE [ 1 ] intercalate # intercalate _ [ ] = [ ] intercalate sep ( xs0 : ) = go xs0 where go [ ] xss = to xss go ( x : xs ) xss = x : go xs xss to [ ] = [ ] to ( xs : xss ) = go ' sep xs xss go ' [ ] xs xss = go xs xss go ' ( s : ss ) xs xss = s : go ' ss xs xss { - # NOINLINE [ 1 ] intercalate # intercalate _ [] = [] intercalate sep (xs0:xss0) = go xs0 xss0 where go [] xss = to xss go (x:xs) xss = x : go xs xss to [] = [] to (xs:xss) = go' sep xs xss go' [] xs xss = go xs xss go' (s:ss) xs xss = s : go' ss xs xss -} RULES " intercalate - > fusible " [ ~1 ] forall x xs . intercalate x xs = Stream.concat ( Stream.intersperse x ( stream xs ) ) " intercalate - > unfused " [ 1 ] forall x xs . Stream.concat ( Stream.intersperse x ( stream xs ) ) = intercalate x xs "intercalate -> fusible" [~1] forall x xs. intercalate x xs = Stream.concat (Stream.intersperse x (stream xs)) "intercalate -> unfused" [1] forall x xs. Stream.concat (Stream.intersperse x (stream xs)) = intercalate x xs -} transpose :: [[a]] -> [[a]] transpose [] = [] transpose ([] : xss) = transpose xss transpose ((x:xs) : xss) = (x : [h | (h:_t) <- xss]) : transpose (xs : [ t | (_h:t) <- xss]) TODO fuse foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z0 xs0 = go z0 xs0 where go z [] = z go z (x:xs) = go (f z x) xs # INLINE [ 1 ] foldl # # RULES " foldl - > fusible " [ ~1 ] forall f z xs . foldl f z xs = Stream.foldl f z ( stream xs ) # "foldl -> fusible" [~1] forall f z xs. foldl f z xs = Stream.foldl f z (stream xs) #-} foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f z0 xs0 = go z0 xs0 #ifndef __HADDOCK__ where go !z [] = z go !z (x:xs) = go (f z x) xs #endif # INLINE [ 1 ] foldl ' # # RULES " foldl ' - > fusible " [ ~1 ] forall f z xs . foldl ' f z xs = Stream.foldl ' f z ( stream xs ) # "foldl' -> fusible" [~1] forall f z xs. foldl' f z xs = Stream.foldl' f z (stream xs) #-} | /O(n)/ , /fusion/. ' foldl1 ' is a variant of ' foldl ' that has no starting value argument , foldl1 :: (a -> a -> a) -> [a] -> a foldl1 _ [] = errorEmptyList "foldl1" foldl1 f (x0:xs0) = go x0 xs0 where go z [] = z go z (x:xs) = go (f z x) xs # INLINE [ 1 ] foldl1 # # RULES " foldl1 - > fusible " [ ~1 ] forall f xs . foldl1 f xs = Stream.foldl1 f ( stream xs ) # "foldl1 -> fusible" [~1] forall f xs. foldl1 f xs = Stream.foldl1 f (stream xs) #-} | /O(n)/ , /fusion/. A strict version of ' foldl1 ' foldl1' :: (a -> a -> a) -> [a] -> a foldl1' _ [] = errorEmptyList "foldl1'" foldl1' f (x0:xs0) = go x0 xs0 #ifndef __HADDOCK__ where go !z [] = z go !z (x:xs) = go (f z x) xs #endif # INLINE [ 1 ] foldl1 ' # # RULES " foldl1 ' - > fusible " [ ~1 ] forall f xs . foldl1 ' f xs = Stream.foldl1 ' f ( stream xs ) # "foldl1' -> fusible" [~1] forall f xs. foldl1' f xs = Stream.foldl1' f (stream xs) #-} #ifdef EXTERNAL_PACKAGE foldr :: (a -> b -> b) -> b -> [a] -> b foldr k z xs = go xs where go [] = z go (y:ys) = y `k` go ys #endif # RULES " foldr - > fusible " [ ~1 ] forall f z xs . foldr f z xs = Stream.foldr f z ( stream xs ) # "foldr -> fusible" [~1] forall f z xs. foldr f z xs = Stream.foldr f z (stream xs) #-} | /O(n)/ , /fusion/. ' ' is a variant of ' foldr ' that has no starting value argument , foldr1 :: (a -> a -> a) -> [a] -> a foldr1 _ [] = errorEmptyList "foldr1" foldr1 k (x0:xs0) = go x0 xs0 where go x [] = x go x (x':xs) = k x (go x' xs) # RULES " foldr1 - > fusible " [ ~1 ] forall f xs . foldr1 f xs = Stream.foldr1 f ( stream xs ) # "foldr1 -> fusible" [~1] forall f xs. foldr1 f xs = Stream.foldr1 f (stream xs) #-} | /O(n)/ , /fusion/. a list of lists . concat :: [[a]] -> [a] concat xss0 = to xss0 where go [] xss = to xss go (x:xs) xss = x : go xs xss to [] = [] # NOINLINE [ 1 ] concat # # RULES " concat - > fused " [ ~1 ] forall xs . concat xs = Stream.concat ( stream xs ) # "concat -> fused" [~1] forall xs. concat xs = Stream.concat (stream xs) #-} concatMap :: (a -> [b]) -> [a] -> [b] # INLINE concatMap # concatMap f as0 = to as0 where go [ ] as = to as go ( b : bs ) as = b : go bs as to [ ] = [ ] to ( a : as ) = go ( f a ) as { - # NOINLINE [ 1 ] concatMap # concatMap f as0 = to as0 where go [] as = to as go (b:bs) as = b : go bs as to [] = [] to (a:as) = go (f a) as -} RULES " concatMap - > fusible " [ ~1 ] forall f xs . concatMap f xs = Stream.concatMap f ( stream xs ) " concatMap - > unfused " [ 1 ] forall f xs . Stream.concatMap f ( stream xs ) = concatMap f xs "concatMap -> fusible" [~1] forall f xs. concatMap f xs = Stream.concatMap f (stream xs) "concatMap -> unfused" [1] forall f xs. Stream.concatMap f (stream xs) = concatMap f xs -} | /O(n)/ , /fusion/. ' and ' returns the conjunction of a Boolean list . For the result to be and :: [Bool] -> Bool and [] = True and (False:_ ) = False and (_ :xs) = and xs # NOINLINE [ 1 ] and # # RULES " and - > fused " [ ~1 ] forall xs . and xs = Stream.and ( stream xs ) # "and -> fused" [~1] forall xs. and xs = Stream.and (stream xs) #-} | /O(n)/ , /fusion/. ' or ' returns the disjunction of a Boolean list . For the result to be or :: [Bool] -> Bool or [] = False or (True:_ ) = True or (_ :xs) = or xs # NOINLINE [ 1 ] or # # RULES " or - > fused " [ ~1 ] forall xs . or xs = Stream.or ( stream xs ) # "or -> fused" [~1] forall xs. or xs = Stream.or (stream xs) #-} any :: (a -> Bool) -> [a] -> Bool any p xs0 = go xs0 where go [] = False go (x:xs) = case p x of True -> True False -> go xs # NOINLINE [ 1 ] any # TODO : check if being lazy in p is a cost , should we do [ ] as a special case and then strictly evaluate p ? # RULES " any - > fusible " [ ~1 ] forall f xs . any f xs = Stream.any f ( stream xs ) # "any -> fusible" [~1] forall f xs. any f xs = Stream.any f (stream xs) #-} all :: (a -> Bool) -> [a] -> Bool all p xs0 = go xs0 where go [] = True go (x:xs) = case p x of True -> go xs False -> False # NOINLINE [ 1 ] all # # RULES " all - > fusible " [ ~1 ] forall f xs . all f xs = Stream.all f ( stream xs ) # "all -> fusible" [~1] forall f xs. all f xs = Stream.all f (stream xs) #-} sum :: Num a => [a] -> a sum l = sum' l 0 #ifndef __HADDOCK__ where sum' [] a = a sum' (x:xs) a = sum' xs (a+x) #endif # NOINLINE [ 1 ] sum # sumInt :: [Int] -> Int sumInt l = sum' l 0 #ifndef __HADDOCK__ where sum' [] a = a sum' (x:xs) !a = sum' xs (a+x) #endif # NOINLINE [ 1 ] sumInt # # RULES " sum - > fusible " [ ~1 ] forall xs . sum xs = Stream.sum ( stream xs ) # "sum -> fusible" [~1] forall xs. sum xs = Stream.sum (stream xs) #-} # RULES " sumInt - > fusible " [ ~1 ] forall ( xs : : [ Int ] ) . sumInt xs = Stream.sum ( stream xs ) # "sumInt -> fusible" [~1] forall (xs :: [Int]). sumInt xs = Stream.sum (stream xs) #-} product :: Num a => [a] -> a product l = prod l 1 #ifndef __HADDOCK__ where prod [] a = a prod (x:xs) a = prod xs (a*x) #endif # NOINLINE [ 1 ] product # productInt :: [Int] -> Int productInt l = product' l 0 #ifndef __HADDOCK__ where product' [] a = a product' (x:xs) !a = product' xs (a*x) #endif # NOINLINE [ 1 ] productInt # # RULES " product - > fused " [ ~1 ] forall xs . product xs = Stream.product ( stream xs ) # "product -> fused" [~1] forall xs. product xs = Stream.product (stream xs) #-} # RULES " productInt - > fusible " [ ~1 ] forall ( xs : : [ Int ] ) . productInt xs = Stream.product ( stream xs ) # "productInt -> fusible" [~1] forall (xs :: [Int]). productInt xs = Stream.product (stream xs) #-} maximum :: Ord a => [a] -> a maximum [] = errorEmptyList "maximum" maximum xs = foldl1 max xs # NOINLINE [ 1 ] maximum # # RULES " maximum - > fused " [ ~1 ] forall xs . maximum xs = Stream.maximum ( stream xs ) # "maximum -> fused" [~1] forall xs. maximum xs = Stream.maximum (stream xs) #-} changing its semantics ( might not be strict ) , but we can for # RULES " maximumInt " maximum = ( strictMaximum : : [ Int ] - > Int ) ; " maximumChar " maximum = ( strictMaximum : : [ ) # "maximumInt" maximum = (strictMaximum :: [Int] -> Int); "maximumChar" maximum = (strictMaximum :: [Char] -> Char) #-} strictMaximum :: (Ord a) => [a] -> a strictMaximum [] = errorEmptyList "maximum" strictMaximum xs = foldl1' max xs # NOINLINE [ 1 ] strictMaximum # # RULES " strictMaximum - > fused " [ ~1 ] forall xs . strictMaximum xs = Stream.strictMaximum ( stream xs ) # "strictMaximum -> fused" [~1] forall xs. strictMaximum xs = Stream.strictMaximum (stream xs) #-} minimum :: Ord a => [a] -> a minimum [] = errorEmptyList "minimum" minimum xs = foldl1 min xs # NOINLINE [ 1 ] minimum # # RULES " minimum - > fused " [ ~1 ] forall xs . minimum xs = Stream.minimum ( stream xs ) # "minimum -> fused" [~1] forall xs. minimum xs = Stream.minimum (stream xs) #-} # RULES " minimumInt " minimum = ( strictMinimum : : [ Int ] - > Int ) ; " minimumChar " minimum = ( strictMinimum : : [ ) # "minimumInt" minimum = (strictMinimum :: [Int] -> Int); "minimumChar" minimum = (strictMinimum :: [Char] -> Char) #-} strictMinimum :: (Ord a) => [a] -> a strictMinimum [] = errorEmptyList "maximum" strictMinimum xs = foldl1' min xs # NOINLINE [ 1 ] strictMinimum # # RULES " strictMinimum - > fused " [ ~1 ] forall xs . strictMinimum xs = Stream.strictMinimum ( stream xs ) # "strictMinimum -> fused" [~1] forall xs. strictMinimum xs = Stream.strictMinimum (stream xs) #-} | /O(n)/ , /fusion/. ' ' is similar to ' foldl ' , but returns a list of successive > f z [ x1 , x2 , ... ] = = [ z , z ` f ` x1 , ( z ` f ` x1 ) ` f ` x2 , ... ] > last ( f z xs ) = = foldl f z x scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q ls = q : case ls of [] -> [] x:xs -> scanl f (f q x) xs # INLINE [ 1 ] scanl # or perhaps : f q xs0 = q : go q xs0 where go q [ ] = [ ] go q ( x : xs ) = let q ' = f q x in q ' : go q ' xs scanl f q xs0 = q : go q xs0 where go q [] = [] go q (x:xs) = let q' = f q x in q' : go q' xs -} note : 's ' scan ' is a bit weird , as it always puts the initial # RULES " - > fusible " [ ~1 ] forall f z xs . f z xs = unstream ( Stream.scanl f z ( Stream.snoc ( stream xs ) bottom ) ) # "scanl -> fusible" [~1] forall f z xs. scanl f z xs = unstream (Stream.scanl f z (Stream.snoc (stream xs) bottom)) #-} | /O(n)/,/fusion/. ' ' is a variant of ' ' that has no starting value argument : > f [ x1 , x2 , ... ] = = [ x1 , x1 ` f ` x2 , ... ] scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 f (x:xs) = scanl f x xs scanl1 _ [] = [] # RULES " scanl1 - > fusible " [ ~1 ] forall f xs . scanl1 f xs = unstream ( Stream.scanl1 f ( Stream.snoc ( stream xs ) bottom ) ) # "scanl1 -> fusible" [~1] forall f xs. scanl1 f xs = unstream (Stream.scanl1 f (Stream.snoc (stream xs) bottom)) #-} | /O(n)/. ' scanr ' is the right - to - left dual of ' ' . > head ( scanr f z xs ) = = foldr f z xs scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr _ q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs # INLINE [ 1 ] scanr # RULES " scanr - > fusible " [ ~1 ] forall f z xs . scanr f z xs = unstream ( Stream.scanr f z ( Stream.cons bottom ( stream xs ) ) ) " scanr - > unfused " [ 1 ] forall f z xs . unstream ( Stream.scanr f z ( Stream.cons bottom ( stream xs ) ) ) = scanr f z xs "scanr -> fusible" [~1] forall f z xs. scanr f z xs = unstream (Stream.scanr f z (Stream.cons bottom (stream xs))) "scanr -> unfused" [1] forall f z xs. unstream (Stream.scanr f z (Stream.cons bottom (stream xs))) = scanr f z xs -} | ' ' is a variant of ' scanr ' that has no starting value argument . scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 _ [] = [] scanr1 _ [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs TODO fuse mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) mapAccumL _ s [] = (s, []) mapAccumL f s (x:xs) = (s'',y:ys) where (s', y ) = f s x (s'',ys) = mapAccumL f s' xs TODO fuse mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) mapAccumR _ s [] = (s, []) mapAccumR f s (x:xs) = (s'', y:ys) where (s'',y ) = f s' x (s', ys) = mapAccumR f s xs TODO fuse | /fusion/. ' iterate ' @f returns an infinite list of repeated applications of to @x@ : iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) # NOINLINE [ 1 ] iterate # # RULES " iterate - > fusible " [ ~1 ] forall f x. iterate f x = unstream ( Stream.iterate f x ) # "iterate -> fusible" [~1] forall f x. iterate f x = unstream (Stream.iterate f x) #-} repeat :: a -> [a] repeat x = xs where xs = x : xs # INLINE [ 1 ] repeat # # RULES " repeat - > fusible " [ ~1 ] forall x. repeat x = unstream ( Stream.repeat x ) # "repeat -> fusible" [~1] forall x. repeat x = unstream (Stream.repeat x) #-} | /O(n)/ , /fusion/. ' replicate ' @n is a list of length @n@ with @x@ the value of It is an instance of the more general ' Data . List.genericReplicate ' , in which @n@ may be of any integral type . replicate :: Int -> a -> [a] replicate n0 _ | n0 <= 0 = [] replicate n0 x = go n0 where go 0 = [] go n = x : go (n-1) # NOINLINE [ 1 ] replicate # # RULES " replicate - > fusible " [ ~1 ] replicate = - > unstream ( Stream.replicate n x ) # "replicate -> fusible" [~1] replicate = \n x -> unstream (Stream.replicate n x) #-} cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs0 = go xs0 where go [] = go xs0 go (x:xs) = x : go xs # NOINLINE [ 1 ] cycle # # RULES " cycle - > fusible " [ ~1 ] forall xs . cycle xs = unstream ( Stream.cycle ( stream xs ) ) # "cycle -> fusible" [~1] forall xs. cycle xs = unstream (Stream.cycle (stream xs)) #-} case , @a@ is a prepended to the list and @b@ is used as the next > iterate f = = unfoldr ( \x - > Just ( x , f x ) ) > unfoldr ( \b - > if b = = 0 then Nothing else Just ( b , b-1 ) ) 10 unfoldr :: (b -> Maybe (a, b)) -> b -> [a] unfoldr f b0 = unfold b0 where unfold b = case f b of Just (a,b') -> a : unfold b' Nothing -> [] # INLINE [ 1 ] unfoldr # # RULES " unfoldr - > fusible " [ ~1 ] forall f x. unfoldr f x = unstream ( Stream.unfoldr f x ) # "unfoldr -> fusible" [~1] forall f x. unfoldr f x = unstream (Stream.unfoldr f x) #-} of length @n@ , or @xs@ itself if @n > ' length ' xs@ : > take 5 " Hello World ! " = = " Hello " > take 3 [ 1,2,3,4,5 ] = = [ 1,2,3 ] > take 3 [ 1,2 ] = = [ 1,2 ] > take 3 [ ] = = [ ] > take 0 [ 1,2 ] = = [ ] It is an instance of the more general ' Data . List.genericTake ' , in which @n@ may be of any integral type . take :: Int -> [a] -> [a] take i _ | i <= 0 = [] take i ls = take' i ls where take' :: Int -> [a] -> [a] take' 0 _ = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs # NOINLINE [ 1 ] take # # RULES " take - > fusible " [ ~1 ] forall n x. take n x = unstream ( Stream.take n ( stream x ) ) # "take -> fusible" [~1] forall n x. take n x = unstream (Stream.take n (stream x)) #-} take : : Int - > [ a ] - > [ a ] take ( I # n # ) xs = takeUInt n # xs takeUInt : : Int # - > [ b ] - > [ b ] takeUInt n xs | n > = # 0 # = take_unsafe_UInt n xs | otherwise = [ ] take_unsafe_UInt : : Int # - > [ b ] - > [ b ] take_unsafe_UInt 0 # _ = [ ] take_unsafe_UInt m ls = case ls of [ ] - > [ ] ( x : xs ) - > x : take_unsafe_UInt ( m - # 1 # ) xs take :: Int -> [a] -> [a] take (I# n#) xs = takeUInt n# xs takeUInt :: Int# -> [b] -> [b] takeUInt n xs | n >=# 0# = take_unsafe_UInt n xs | otherwise = [] take_unsafe_UInt :: Int# -> [b] -> [b] take_unsafe_UInt 0# _ = [] take_unsafe_UInt m ls = case ls of [] -> [] (x:xs) -> x : take_unsafe_UInt (m -# 1#) xs -} | /O(n)/,/fusion/. ' drop ' @n returns the suffix of @xs@ after the first @n@ elements , or @[]@ if @n > ' length ' xs@ : > drop 6 " Hello World ! " = = " World ! " > drop 3 [ 1,2,3,4,5 ] = = [ 4,5 ] > drop 3 [ 1,2 ] = = [ ] > drop 3 [ ] = = [ ] > drop 0 [ 1,2 ] = = [ 1,2 ] in which @n@ may be of any integral type . drop :: Int -> [a] -> [a] drop n ls | n < 0 = ls | otherwise = drop' n ls where drop' :: Int -> [a] -> [a] drop' 0 xs = xs drop' _ xs@[] = xs drop' m (_:xs) = drop' (m-1) xs # NOINLINE [ 1 ] drop # # RULES " drop - > fusible " [ ~1 ] forall n x. drop n x = unstream ( Stream.drop n ( stream x ) ) # "drop -> fusible" [~1] forall n x. drop n x = unstream (Stream.drop n (stream x)) #-} | ' splitAt ' @n returns a tuple where first element is @xs@ prefix of length @n@ and second element is the remainder of the list : > splitAt 6 " Hello World ! " = = ( " Hello " , " World ! " ) > splitAt 3 [ 1,2,3,4,5 ] = = ( [ 1,2,3],[4,5 ] ) > splitAt 1 [ 1,2,3 ] = = ( [ 1],[2,3 ] ) > splitAt 3 [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) > splitAt 4 [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) in which @n@ may be of any integral type . splitAt :: Int -> [a] -> ([a], [a]) splitAt n ls | n < 0 = ([], ls) | otherwise = splitAt' n ls where splitAt' :: Int -> [a] -> ([a], [a]) splitAt' 0 xs = ([], xs) splitAt' _ xs@[] = (xs, xs) splitAt' m (x:xs) = (x:xs', xs'') where (xs', xs'') = splitAt' (m-1) xs # NOINLINE [ 1 ] splitAt # # RULES " splitAt - > fusible " [ ~1 ] forall n xs . splitAt n xs = Stream.splitAt n ( stream xs ) # "splitAt -> fusible" [~1] forall n xs. splitAt n xs = Stream.splitAt n (stream xs) #-} > ( < 3 ) [ 1,2,3,4,1,2,3,4 ] = = [ 1,2 ] > ( < 9 ) [ 1,2,3 ] = = [ 1,2,3 ] > ( < 0 ) [ 1,2,3 ] = = [ ] takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p xs0 = go xs0 where go [] = [] go (x:xs) | p x = x : go xs | otherwise = [] # NOINLINE [ 1 ] takeWhile # # RULES " takeWhile - > fusible " [ ~1 ] forall f xs . takeWhile f xs = unstream ( Stream.takeWhile f ( stream xs ) ) # "takeWhile -> fusible" [~1] forall f xs. takeWhile f xs = unstream (Stream.takeWhile f (stream xs)) #-} | /O(n)/,/fusion/. ' dropWhile ' @p xs@ returns the suffix remaining after ' takeWhile ' @p xs@ : > dropWhile ( < 3 ) [ 1,2,3,4,5,1,2,3 ] = = [ 3,4,5,1,2,3 ] > dropWhile ( < 9 ) [ 1,2,3 ] = = [ ] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p xs0 = go xs0 where go [] = [] go xs@(x:xs') | p x = go xs' | otherwise = xs # NOINLINE [ 1 ] dropWhile # # RULES " dropWhile - > fusible " [ ~1 ] forall f xs . dropWhile f xs = unstream ( Stream.dropWhile f ( stream xs ) ) # "dropWhile -> fusible" [~1] forall f xs. dropWhile f xs = unstream (Stream.dropWhile f (stream xs)) #-} first element is longest prefix ( possibly empty ) of @xs@ of elements that satisfy @p@ and second element is the remainder of the list : > span ( < 3 ) [ 1,2,3,4,1,2,3,4 ] = = ( [ 1,2],[3,4,1,2,3,4 ] ) > span ( < 9 ) [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) ' span ' @p xs@ is equivalent to @('takeWhile ' p xs , ' dropWhile ' p xs)@ span :: (a -> Bool) -> [a] -> ([a], [a]) span _ [] = ([], []) span p xs0 = go xs0 where go [] = ([], []) go xs@(x:xs') | p x = let (ys,zs) = go xs' in (x:ys,zs) | otherwise = ([],xs) TODO fuse first element is longest prefix ( possibly empty ) of @xs@ of elements that /do not satisfy/ @p@ and second element is the remainder of the list : > break ( > 3 ) [ 1,2,3,4,1,2,3,4 ] = = ( [ 1,2,3],[4,1,2,3,4 ] ) > break ( < 9 ) [ 1,2,3 ] = = ( [ ] , [ 1,2,3 ] ) > break ( > 9 ) [ 1,2,3 ] = = ( [ 1,2,3 ] , [ ] ) ' break ' @p@ is equivalent to @'span ' ( ' not ' . p)@. break :: (a -> Bool) -> [a] -> ([a], [a]) break _ [] = ([], []) break p xs0 = go xs0 where go [] = ([], []) go xs@(x:xs') | p x = ([],xs) | otherwise = let (ys,zs) = go xs' in (x:ys,zs) TODO fuse > group " Mississippi " = [ " M","i","ss","i","ss","i","pp","i " ] group :: Eq a => [a] -> [[a]] group [] = [] group (x:xs) = (x:ys) : group zs where (ys,zs) = span (x ==) xs TODO fuse shortest first . For example , > inits " abc " = = [ " " , " a","ab","abc " ] inits :: [a] -> [[a]] inits [] = [] : [] inits (x:xs) = [] : map (x:) (inits xs) TODO fuse > tails " abc " = = [ " abc " , " bc " , " c " , " " ] tails :: [a] -> [[a]] tails [] = [] : [] tails xxs@(_:xs) = xxs : tails xs TODO fuse | /O(n)/,/fusion/. The ' isPrefixOf ' function takes two lists and returns ' True ' iff the first list is a prefix of the second . isPrefixOf :: Eq a => [a] -> [a] -> Bool isPrefixOf [] _ = True isPrefixOf _ [] = False isPrefixOf (x:xs) (y:ys) | x == y = isPrefixOf xs ys | otherwise = False # NOINLINE [ 1 ] isPrefixOf # # RULES " isPrefixOf - > fusible " [ ~1 ] forall xs ys . isPrefixOf xs ys = Stream.isPrefixOf ( stream xs ) ( stream ys ) "isPrefixOf -> fusible" [~1] forall xs ys. isPrefixOf xs ys = Stream.isPrefixOf (stream xs) (stream ys) #-} | The ' isSuffixOf ' function takes two lists and returns ' True ' iff the first list is a suffix of the second . isSuffixOf :: Eq a => [a] -> [a] -> Bool isSuffixOf x y = reverse x `isPrefixOf` reverse y TODO fuse | The ' isInfixOf ' function takes two lists and returns ' True ' iff the first list is contained , wholly and intact , anywhere within the second . > isInfixOf " Haskell " " I really like . " - > True > isInfixOf " Ial " " I really like . " - > False isInfixOf :: Eq a => [a] -> [a] -> Bool isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack) TODO fuse elem :: Eq a => a -> [a] -> Bool elem _ [] = False elem x (y:ys) | x == y = True | otherwise = elem x ys # NOINLINE [ 1 ] elem # # RULES " elem - > fusible " [ ~1 ] forall x xs . elem x xs = Stream.elem x ( stream xs ) # "elem -> fusible" [~1] forall x xs. elem x xs = Stream.elem x (stream xs) #-} notElem :: Eq a => a -> [a] -> Bool notElem x xs = not (elem x xs) # INLINE notElem # RULES " notElem - > fusible " [ ~1 ] forall x xs . notElem x xs = Stream.notElem x ( stream xs ) " notElem - > unfused " [ 1 ] forall x xs . Stream.notElem x ( stream xs ) = notElem x xs "notElem -> fusible" [~1] forall x xs. notElem x xs = Stream.notElem x (stream xs) "notElem -> unfused" [1] forall x xs. Stream.notElem x (stream xs) = notElem x xs -} lookup :: Eq a => a -> [(a, b)] -> Maybe b lookup _ [] = Nothing lookup key xys0 = go xys0 where go [] = Nothing go ((x,y):xys) | key == x = Just y | otherwise = lookup key xys # NOINLINE [ 1 ] lookup # # RULES " lookup - > fusible " [ ~1 ] forall x xs . lookup x xs = Stream.lookup x ( stream xs ) # "lookup -> fusible" [~1] forall x xs. lookup x xs = Stream.lookup x (stream xs) #-} > filter p ( filter q s ) = filter ( \x - > q x & & p x ) s filter :: (a -> Bool) -> [a] -> [a] filter _ [] = [] filter p xs0 = go xs0 where go [] = [] go (x:xs) | p x = x : go xs | otherwise = go xs # NOINLINE [ 1 ] filter # # RULES " filter - > fusible " [ ~1 ] forall f xs . filter f xs = unstream ( Stream.filter f ( stream xs ) ) # "filter -> fusible" [~1] forall f xs. filter f xs = unstream (Stream.filter f (stream xs)) #-} first element in the list matching the predicate , or ' Nothing ' if find :: (a -> Bool) -> [a] -> Maybe a find _ [] = Nothing find p xs0 = go xs0 where go [] = Nothing go (x:xs) | p x = Just x | otherwise = go xs # NOINLINE [ 1 ] find # # RULES " find - > fusible " [ ~1 ] forall f xs . find f xs = Stream.find f ( stream xs ) # "find -> fusible" [~1] forall f xs. find f xs = Stream.find f (stream xs) #-} partition :: (a -> Bool) -> [a] -> ([a], [a]) partition p xs = foldr (select p) ([],[]) xs # INLINE partition # TODO fuse select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a]) select p x ~(ts,fs) | p x = (x:ts,fs) | otherwise = (ts, x:fs) (!!) :: [a] -> Int -> a xs0 !! n0 | n0 < 0 = error "Prelude.(!!): negative index" | otherwise = index xs0 n0 #ifndef __HADDOCK__ where index [] _ = error "Prelude.(!!): index too large" index (y:ys) n = if n == 0 then y else index ys (n-1) #endif # NOINLINE [ 1 ] ( ! ! ) # # RULES " ! ! - > fusible " [ ~1 ] forall xs n. xs ! ! n = Stream.index ( stream xs ) n # "!! -> fusible" [~1] forall xs n. xs !! n = Stream.index (stream xs) n #-} | The ' elemIndex ' function returns the index of the first element elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex x = findIndex (x==) elemIndex : : Eq a = > a - > [ a ] - > Maybe Int elemIndex y xs0 = loop_elemIndex xs0 0 # ifndef _ _ HADDOCK _ _ where loop_elemIndex [ ] ! _ = Nothing loop_elemIndex ( x : xs ) ! n | p x = Just n | otherwise = loop_elemIndex xs ( n + 1 ) p = ( y = { - # NOINLINE [ 1 ] elemIndex # elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex y xs0 = loop_elemIndex xs0 0 #ifndef __HADDOCK__ where loop_elemIndex [] !_ = Nothing loop_elemIndex (x:xs) !n | p x = Just n | otherwise = loop_elemIndex xs (n + 1) p = (y ==) #endif -} RULES " elemIndex - > fusible " [ ~1 ] forall x xs . elemIndex x xs = Stream.elemIndex x ( stream xs ) " elemIndex - > unfused " [ 1 ] forall x xs . Stream.elemIndex x ( stream xs ) = elemIndex x xs "elemIndex -> fusible" [~1] forall x xs. elemIndex x xs = Stream.elemIndex x (stream xs) "elemIndex -> unfused" [1] forall x xs. Stream.elemIndex x (stream xs) = elemIndex x xs -} > length ( filter (= = a ) xs ) = length ( elemIndices a xs ) elemIndices :: Eq a => a -> [a] -> [Int] elemIndices x = findIndices (x==) # INLINE elemIndices # elemIndices : : Eq a = > a - > [ a ] - > [ Int ] elemIndices y xs0 = loop_elemIndices xs0 0 # ifndef _ _ HADDOCK _ _ where loop_elemIndices [ ] ! _ = [ ] loop_elemIndices ( x : xs ) ! n | p x = n : loop_elemIndices xs ( n + 1 ) | otherwise = loop_elemIndices xs ( n + 1 ) p = ( y = { - # NOINLINE [ 1 ] elemIndices # elemIndices :: Eq a => a -> [a] -> [Int] elemIndices y xs0 = loop_elemIndices xs0 0 #ifndef __HADDOCK__ where loop_elemIndices [] !_ = [] loop_elemIndices (x:xs) !n | p x = n : loop_elemIndices xs (n + 1) | otherwise = loop_elemIndices xs (n + 1) p = (y ==) #endif -} RULES " elemIndices - > fusible " [ ~1 ] forall x xs . elemIndices x xs = unstream ( Stream.elemIndices x ( stream xs ) ) " elemIndices - > unfused " [ 1 ] forall x xs . unstream ( Stream.elemIndices x ( stream xs ) ) = elemIndices x xs "elemIndices -> fusible" [~1] forall x xs. elemIndices x xs = unstream (Stream.elemIndices x (stream xs)) "elemIndices -> unfused" [1] forall x xs. unstream (Stream.elemIndices x (stream xs)) = elemIndices x xs -} the index of the first element in the list satisfying the predicate , findIndex :: (a -> Bool) -> [a] -> Maybe Int findIndex p ls = loop_findIndex ls 0# where loop_findIndex [] _ = Nothing loop_findIndex (x:xs) n | p x = Just (I# n) | otherwise = loop_findIndex xs (n +# 1#) # NOINLINE [ 1 ] findIndex # # RULES " findIndex - > fusible " [ ~1 ] forall f xs . findIndex f xs = Stream.findIndex f ( stream xs ) # "findIndex -> fusible" [~1] forall f xs. findIndex f xs = Stream.findIndex f (stream xs) #-} > length ( filter p xs ) = length ( findIndices p xs ) findIndices :: (a -> Bool) -> [a] -> [Int] findIndices p ls = loop_findIndices ls 0# where loop_findIndices [] _ = [] loop_findIndices (x:xs) n | p x = I# n : loop_findIndices xs (n +# 1#) | otherwise = loop_findIndices xs (n +# 1#) # NOINLINE [ 1 ] findIndices # # RULES " findIndices - > fusible " [ ~1 ] forall p xs . findIndices p xs = unstream ( Stream.findIndices p ( stream xs ) ) # "findIndices -> fusible" [~1] forall p xs. findIndices p xs = unstream (Stream.findIndices p (stream xs)) #-} | /O(n)/,/fusion/. ' zip ' takes two lists and returns a list of corresponding pairs . If one input list is short , excess elements of zip :: [a] -> [b] -> [(a, b)] zip (a:as) (b:bs) = (a,b) : zip as bs zip _ _ = [] # NOINLINE [ 1 ] zip # # RULES " zip - > fusible " [ ~1 ] forall xs ys . zip xs ys = unstream ( Stream.zip ( stream xs ) ( stream ys ) ) # "zip -> fusible" [~1] forall xs ys. zip xs ys = unstream (Stream.zip (stream xs) (stream ys)) #-} | /O(n)/,/fusion/. ' zip3 ' takes three lists and returns a list of zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs zip3 _ _ _ = [] # NOINLINE [ 1 ] zip3 # # RULES " zip3 - > fusible " [ ~1 ] forall xs ys zs . = unstream ( Stream.zipWith3 ( , , ) ( stream xs ) ( stream ys ) ( stream zs ) ) # "zip3 -> fusible" [~1] forall xs ys zs. zip3 xs ys zs = unstream (Stream.zipWith3 (,,) (stream xs) (stream ys) (stream zs)) #-} | /O(n)/,/fusion/. The ' zip4 ' function takes four lists and returns a list of zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)] zip4 = zipWith4 (,,,) # INLINE zip4 # | The ' zip5 ' function takes five lists and returns a list of five - tuples , analogous to ' zip ' . zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)] zip5 = zipWith5 (,,,,) | The ' ' function takes six lists and returns a list of six - tuples , zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)] zip6 = zipWith6 (,,,,,) | The ' zip7 ' function takes seven lists and returns a list of seven - tuples , analogous to ' zip ' . zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)] zip7 = zipWith7 (,,,,,,) function given as the first argument , instead of a tupling function . For example , @'zipWith ' ( + ) @ is applied to two lists to produce the zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith f (a:as) (b:bs) = f a b : zipWith f as bs zipWith _ _ _ = [] # INLINE [ 1 ] zipWith # FIXME : If we change the above INLINE to NOINLINE then ghc goes into # RULES " zipWith - > fusible " [ ~1 ] forall f xs ys . zipWith f xs ys = unstream ( Stream.zipWith f ( stream xs ) ( stream ys ) ) # "zipWith -> fusible" [~1] forall f xs ys. zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys)) #-} combines three elements , as well as three lists and returns a list of zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] zipWith3 z (a:as) (b:bs) (c:cs) = z a b c : zipWith3 z as bs cs zipWith3 _ _ _ _ = [] # NOINLINE [ 1 ] zipWith3 # # RULES " zipWith3 - > fusible " [ ~1 ] forall f xs ys zs . zipWith3 f xs ys zs = unstream ( Stream.zipWith3 f ( stream xs ) ( stream ys ) ( stream zs ) ) # "zipWith3 -> fusible" [~1] forall f xs ys zs. zipWith3 f xs ys zs = unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs)) #-} | /O(n)/,/fusion/. The ' zipWith4 ' function takes a function which combines four elements , as well as four lists and returns a list of their point - wise zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e] zipWith4 z (a:as) (b:bs) (c:cs) (d:ds) = z a b c d : zipWith4 z as bs cs ds zipWith4 _ _ _ _ _ = [] # NOINLINE [ 1 ] zipWith4 # # RULES " zipWith4 - > fusible " [ ~1 ] forall f ws xs ys zs . zipWith4 f ws xs ys zs = unstream ( Stream.zipWith4 f ( stream ws ) ( stream xs ) ( stream ys ) ( stream zs ) ) # "zipWith4 -> fusible" [~1] forall f ws xs ys zs. zipWith4 f ws xs ys zs = unstream (Stream.zipWith4 f (stream ws) (stream xs) (stream ys) (stream zs)) #-} | The ' zipWith5 ' function takes a function which combines five elements , as well as five lists and returns a list of their point - wise zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) = z a b c d e : zipWith5 z as bs cs ds es zipWith5 _ _ _ _ _ _ = [] TODO fuse | The ' zipWith6 ' function takes a function which combines six elements , as well as six lists and returns a list of their point - wise zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) = z a b c d e f : zipWith6 z as bs cs ds es fs zipWith6 _ _ _ _ _ _ _ = [] TODO fuse | The ' zipWith7 ' function takes a function which combines seven elements , as well as seven lists and returns a list of their point - wise zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) = z a b c d e f g : zipWith7 z as bs cs ds es fs gs zipWith7 _ _ _ _ _ _ _ _ = [] TODO fuse | ' unzip ' transforms a list of pairs into a list of first components and a list of second components . unzip :: [(a, b)] -> ([a], [b]) unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[]) TODO fuse | The ' unzip3 ' function takes a list of triples and returns three unzip3 :: [(a, b, c)] -> ([a], [b], [c]) unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs)) ([],[],[]) TODO fuse | The ' ' function takes a list of quadruples and returns four unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d]) unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) -> (a:as,b:bs,c:cs,d:ds)) ([],[],[],[]) TODO fuse | The ' ' function takes a list of five - tuples and returns five unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e]) unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) -> (a:as,b:bs,c:cs,d:ds,e:es)) ([],[],[],[],[]) TODO fuse | The ' unzip6 ' function takes a list of six - tuples and returns six unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) -> (a:as,b:bs,c:cs,d:ds,e:es,f:fs)) ([],[],[],[],[],[]) TODO fuse | The ' ' function takes a list of seven - tuples and returns seven lists , analogous to ' unzip ' . unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g]) unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) -> (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs)) ([],[],[],[],[],[],[]) TODO fuse lines :: String -> [String] lines [] = [] lines s = let (l, s') = break (== '\n') s in l : case s' of [] -> [] (_:s'') -> lines s'' # INLINE [ 1 ] lines # RULES " lines - > fusible " [ ~1 ] forall xs . lines xs = unstream ( Stream.lines ( stream xs ) ) " lines - > unfused " [ 1 ] forall xs . unstream ( Stream.lines ( stream xs ) ) = lines xs "lines -> fusible" [~1] forall xs. lines xs = unstream (Stream.lines (stream xs)) "lines -> unfused" [1] forall xs. unstream (Stream.lines (stream xs)) = lines xs -} words :: String -> [String] words s = case dropWhile isSpace s of "" -> [] s' -> w : words s'' where (w, s'') = break isSpace s' TODO fuse unlines :: [String] -> String unlines css0 = to css0 where go [] css = '\n' : to css go (c:cs) css = c : go cs css to [] = [] to (cs:css) = go cs css # NOINLINE [ 1 ] unlines # RULES " unlines - > fusible " [ ~1 ] forall xs . unlines xs = unstream ( Stream.concatMap ( \x - > Stream.snoc ( stream x ) ' \n ' ) ( stream xs ) ) " unlines - > unfused " [ 1 ] forall xs . unstream ( Stream.concatMap ( \x - > Stream.snoc ( stream x ) ' \n ' ) ( stream xs ) ) = unlines xs "unlines -> fusible" [~1] forall xs. unlines xs = unstream (Stream.concatMap (\x -> Stream.snoc (stream x) '\n') (stream xs)) "unlines -> unfused" [1] forall xs. unstream (Stream.concatMap (\x -> Stream.snoc (stream x) '\n') (stream xs)) = unlines xs -} unwords :: [String] -> String unwords [] = [] unwords (cs0:css0) = go cs0 css0 where go [] css = to css go (c:cs) css = c : go cs css to [] = [] to (cs:ccs) = ' ' : go cs ccs TODO fuse In particular , it keeps only the first occurrence of each element . ( The name ' nub ' means \`essence\ ' . ) nub :: Eq a => [a] -> [a] nub l = nub' l [] where nub' [] _ = [] nub' (x:xs) ls | x `elem` ls = nub' xs ls | otherwise = x : nub' xs (x:ls) TODO fuse | ' delete ' @x@ removes the first occurrence of @x@ from its list argument . > delete ' a ' " banana " = = " " delete :: Eq a => a -> [a] -> [a] delete = deleteBy (==) TODO fuse In the result of @xs@ ' \\ ' @ys@ , the first occurrence of each element of (\\) :: Eq a => [a] -> [a] -> [a] (\\) = foldl (flip delete) | The ' union ' function returns the list union of the two lists . Duplicates , and elements of the first list , are removed from the the second list , but if the first list contains duplicates , so will union :: Eq a => [a] -> [a] -> [a] union = unionBy (==) TODO fuse | The ' intersect ' function takes the list intersection of two lists . > [ 1,2,3,4 ] ` intersect ` [ 2,4,6,8 ] = = [ 2,4 ] If the first list contains duplicates , so will the result . intersect :: Eq a => [a] -> [a] -> [a] intersect = intersectBy (==) TODO fuse TODO stuff in Ord can use Map / IntMap , an Ord constraint ! we could use a better structure . sort :: Ord a => [a] -> [a] sort l = mergesort compare l TODO fuse , we have an Ord constraint ! insert :: Ord a => a -> [a] -> [a] insert e ls = insertBy (compare) e ls # INLINE insert # * * * User - supplied equality ( replacing an Eq context ) nubBy :: (a -> a -> Bool) -> [a] -> [a] nubBy eq l = nubBy' l [] where nubBy' [] _ = [] nubBy' (y:ys) xs | elem_by eq y xs = nubBy' ys xs | otherwise = y : nubBy' ys (y:xs) TODO fuse elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool elem_by _ _ [] = False elem_by eq y (x:xs) = if x `eq` y then True else elem_by eq y xs deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] deleteBy _ _ [] = [] deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys TODO fuse deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] deleteFirstsBy eq = foldl (flip (deleteBy eq)) unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs TODO fuse intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] intersectBy eq xs ys = [x | x <- xs, any (eq x) ys] TODO fuse groupBy :: (a -> a -> Bool) -> [a] -> [[a]] groupBy _ [] = [] groupBy eq (x:xs) = (x:ys) : groupBy eq zs where (ys,zs) = span (eq x) xs TODO fuse * * * User - supplied comparison ( replacing an context ) sortBy :: (a -> a -> Ordering) -> [a] -> [a] sortBy cmp l = mergesort cmp l TODO fuse mergesort :: (a -> a -> Ordering) -> [a] -> [a] mergesort cmp xs = mergesort' cmp (map wrap xs) mergesort' :: (a -> a -> Ordering) -> [[a]] -> [a] mergesort' _ [] = [] mergesort' _ [xs] = xs mergesort' cmp xss = mergesort' cmp (merge_pairs cmp xss) merge_pairs :: (a -> a -> Ordering) -> [[a]] -> [[a]] merge_pairs _ [] = [] merge_pairs _ [xs] = [xs] merge_pairs cmp (xs:ys:xss) = merge cmp xs ys : merge_pairs cmp xss merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a] merge _ xs [] = xs merge _ [] ys = ys merge cmp (x:xs) (y:ys) = case x `cmp` y of GT -> y : merge cmp (x:xs) ys _ -> x : merge cmp xs (y:ys) wrap :: a -> [a] wrap x = [x] insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a] insertBy _ x [] = [x] insertBy cmp x ys@(y:ys') = case cmp x y of GT -> y : insertBy cmp x ys' _ -> x : ys # NOINLINE [ 1 ] insertBy # # RULES " insertBy - > fusible " [ ~1 ] forall f x xs . insertBy f x xs = unstream ( Stream.insertBy f x ( stream xs ) ) # "insertBy -> fusible" [~1] forall f x xs. insertBy f x xs = unstream (Stream.insertBy f x (stream xs)) #-} maximumBy :: (a -> a -> Ordering) -> [a] -> a maximumBy _ [] = error "List.maximumBy: empty list" maximumBy cmp xs = foldl1 max' xs where max' x y = case cmp x y of GT -> x _ -> y # NOINLINE [ 1 ] maximumBy # # RULES " maximumBy - > fused " [ ~1 ] forall p xs . ( stream xs ) # "maximumBy -> fused" [~1] forall p xs. maximumBy p xs = Stream.maximumBy p (stream xs) #-} minimumBy :: (a -> a -> Ordering) -> [a] -> a minimumBy _ [] = error "List.minimumBy: empty list" minimumBy cmp xs = foldl1 min' xs where min' x y = case cmp x y of GT -> y _ -> x # NOINLINE [ 1 ] minimumBy # # RULES " minimumBy - > fused " [ ~1 ] forall p xs . minimumBy p xs = ( stream xs ) # "minimumBy -> fused" [~1] forall p xs. minimumBy p xs = Stream.minimumBy p (stream xs) #-} | The ' genericLength ' function is an overloaded version of ' length ' . In an instance of ' ' . It is , however , less efficient than ' length ' . genericLength :: Num i => [b] -> i genericLength [] = 0 genericLength (_:l) = 1 + genericLength l # NOINLINE [ 1 ] genericLength # # RULES " genericLength - > fusible " [ ~1 ] forall xs . genericLength xs = Stream.genericLength ( stream xs ) # "genericLength -> fusible" [~1] forall xs. genericLength xs = Stream.genericLength (stream xs) #-} # RULES " genericLength - > length / Int " genericLength = length : : [ a ] - > Int # "genericLength -> length/Int" genericLength = length :: [a] -> Int #-} genericTake :: Integral i => i -> [a] -> [a] genericTake 0 _ = [] genericTake _ [] = [] genericTake n (x:xs) | n > 0 = x : genericTake (n-1) xs | otherwise = error "List.genericTake: negative argument" # NOINLINE [ 1 ] genericTake # # RULES " genericTake - > fusible " [ ~1 ] forall xs n. genericTake n xs = unstream ( Stream.genericTake n ( stream xs ) ) # "genericTake -> fusible" [~1] forall xs n. genericTake n xs = unstream (Stream.genericTake n (stream xs)) #-} genericDrop :: Integral i => i -> [a] -> [a] genericDrop 0 xs = xs genericDrop _ [] = [] genericDrop n (_:xs) | n > 0 = genericDrop (n-1) xs genericDrop _ _ = error "List.genericDrop: negative argument" # NOINLINE [ 1 ] genericDrop # # RULES " genericDrop - > fusible " [ ~1 ] forall xs n. genericDrop n xs = unstream ( Stream.genericDrop n ( stream xs ) ) # "genericDrop -> fusible" [~1] forall xs n. genericDrop n xs = unstream (Stream.genericDrop n (stream xs)) #-} genericIndex :: Integral a => [b] -> a -> b genericIndex (x:_) 0 = x genericIndex (_:xs) n | n > 0 = genericIndex xs (n-1) | otherwise = error "List.genericIndex: negative argument." genericIndex _ _ = error "List.genericIndex: index too large." # NOINLINE [ 1 ] genericIndex # # RULES " genericIndex - > fusible " [ ~1 ] forall xs n. genericIndex xs n = Stream.genericIndex ( stream xs ) n # "genericIndex -> fusible" [~1] forall xs n. genericIndex xs n = Stream.genericIndex (stream xs) n #-} genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) genericSplitAt 0 xs = ([],xs) genericSplitAt _ [] = ([],[]) genericSplitAt n (x:xs) | n > 0 = (x:xs',xs'') where (xs',xs'') = genericSplitAt (n-1) xs genericSplitAt _ _ = error "List.genericSplitAt: negative argument" # RULES " genericSplitAt - > fusible " [ ~1 ] forall xs n. genericSplitAt n xs = Stream.genericSplitAt n ( stream xs ) # "genericSplitAt -> fusible" [~1] forall xs n. genericSplitAt n xs = Stream.genericSplitAt n (stream xs) #-} genericReplicate :: Integral i => i -> a -> [a] genericReplicate n x = genericTake n (repeat x) # INLINE genericReplicate # # RULES " genericReplicate - > replicate / Int " genericReplicate = replicate : : Int - > a - > [ a ] # "genericReplicate -> replicate/Int" genericReplicate = replicate :: Int -> a -> [a] #-} Internal utilities errorEmptyList :: String -> a errorEmptyList fun = moduleError fun "empty list" # NOINLINE errorEmptyList # moduleError :: String -> String -> a moduleError fun msg = error ("Data.List." ++ fun ++ ':':' ':msg) # NOINLINE moduleError # bottom :: a bottom = error "Data.List.Stream: bottom" # NOINLINE bottom #
422b8b74f9d3ad7fe5d7665177af69a9334857de53b6ed4a7edd937c59328869
chetmurthy/pa_ppx
unreachable.ml
let%expect_test _ = if false then [%expect.unreachable]
null
https://raw.githubusercontent.com/chetmurthy/pa_ppx/7c662fcf4897c978ae8a5ea230af0e8b2fa5858b/tests-inline/unreachable.ml
ocaml
let%expect_test _ = if false then [%expect.unreachable]
88c4ce6d5aa5bd8ce04028426c5b2a0884085a70ce3c93e2d7f28a25d9afc0af
inconvergent/weir
simplify-path.lisp
(in-package :simplify-path) (deftype pos-int (&optional (bits 31)) `(unsigned-byte ,bits)) (deftype int-vector () `(vector pos-int)) (deftype vec-simple () `(simple-array vec:vec)) ;note: it would be better if we could avoid using an adjustable vector. (defun -simplify (pts lim &key left right) (declare #.*opt-settings* (double-float lim) (vec-simple pts) (pos-int left right)) (let ((res (make-adjustable-vector :type 'pos-int)) (dmax -1d0) (index 0)) (declare (int-vector res) (pos-int index) (double-float dmax)) (loop with seg of-type list = (list (aref pts left) (aref pts right)) for i of-type pos-int from (1+ left) below right do (let ((d (vec:segdst seg (aref pts i)))) (declare (double-float d)) (when (> d dmax) (setf dmax d index i)))) (if (> dmax lim) (progn (loop with ps of-type int-vector = (-simplify pts lim :left left :right index) for i from 0 below (1- (length ps)) do (vextend (aref ps i) res)) (loop for i across (-simplify pts lim :left index :right right) do (vextend i res))) (progn (vextend left res) (vextend right res))) (sort res #'<))) ; :8338 (defun simplify (pts &key (lim 1d0)) (declare #.*opt-settings* (vec-simple pts) (double-float lim)) (loop for i of-type pos-int across (-simplify pts lim :left 0 :right (1- (length pts))) collect (aref pts i) of-type vec:vec))
null
https://raw.githubusercontent.com/inconvergent/weir/3c364e3a0e15526f0d6985f08a57b312b5c35f7d/src/math/simplify-path.lisp
lisp
note: it would be better if we could avoid using an adjustable vector. :8338
(in-package :simplify-path) (deftype pos-int (&optional (bits 31)) `(unsigned-byte ,bits)) (deftype int-vector () `(vector pos-int)) (deftype vec-simple () `(simple-array vec:vec)) (defun -simplify (pts lim &key left right) (declare #.*opt-settings* (double-float lim) (vec-simple pts) (pos-int left right)) (let ((res (make-adjustable-vector :type 'pos-int)) (dmax -1d0) (index 0)) (declare (int-vector res) (pos-int index) (double-float dmax)) (loop with seg of-type list = (list (aref pts left) (aref pts right)) for i of-type pos-int from (1+ left) below right do (let ((d (vec:segdst seg (aref pts i)))) (declare (double-float d)) (when (> d dmax) (setf dmax d index i)))) (if (> dmax lim) (progn (loop with ps of-type int-vector = (-simplify pts lim :left left :right index) for i from 0 below (1- (length ps)) do (vextend (aref ps i) res)) (loop for i across (-simplify pts lim :left index :right right) do (vextend i res))) (progn (vextend left res) (vextend right res))) (sort res #'<))) (defun simplify (pts &key (lim 1d0)) (declare #.*opt-settings* (vec-simple pts) (double-float lim)) (loop for i of-type pos-int across (-simplify pts lim :left 0 :right (1- (length pts))) collect (aref pts i) of-type vec:vec))
a6d00babd62d065bd09e5054ce02b78f4ad11f7d94011240db3ce6050c673362
sol/http-kit
HeaderSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Network.HTTP.Toolkit.HeaderSpec (main, spec) where import Helper import qualified Data.ByteString.Char8 as B import Network.HTTP.Toolkit.Error import Network.HTTP.Toolkit.Header main :: IO () main = hspec spec spec :: Spec spec = do describe "readMessageHeader" $ do it "reads message header" $ do c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo: 23\r\nbar: 42\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldReturn` ("HTTP/1.1 200 OK", [("foo", "23"), ("bar", "42")]) context "when start-line is missing" $ do it "throws InvalidHeader" $ do c <- mkInputStream ["\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== InvalidHeader) context "when header is malformed" $ do it "throws InvalidHeader" $ do c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== InvalidHeader) context "when attacker sends infinite header" $ do it "throws HeaderTooLarge" $ do c <- mkInputStream ("GET / HTTP/1.1" : repeat "foo: 23\r\n") readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== HeaderTooLarge) context "when input chunk exceeds defaultHeaderSizeLimit" $ do regression test for # 2 c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo: 23\r\nbar: 42\r\n\r\n" <> mconcat (replicate 1000000 "foo")] readMessageHeader defaultHeaderSizeLimit c `shouldReturn` ("HTTP/1.1 200 OK", [("foo", "23"), ("bar", "42")]) describe "combineHeaderLines" $ do it "strips trailing whitespace" $ do combineHeaderLines ["foo\r", "bar\t", "baz \t\r"] `shouldBe` ["foo", "bar", "baz"] context "when a header line starts with whitespace" $ do it "combines that line with the previous line" $ do combineHeaderLines ["foo", "bar", " baz"] `shouldBe` ["foo", "bar baz"] context "when multiple header lines start with whitespace" $ do it "combines consecutive lines" $ do combineHeaderLines ["foo", " bar \r", " baz"] `shouldBe` ["foo bar baz"] describe "readHeaderLines" $ do it "reads header lines" $ do property $ \n -> do c <- mkInputStream (slice n "foo\r\nbar\r\nbaz\r\n\r\n") readHeaderLines defaultHeaderSizeLimit c `shouldReturn` ["foo", "bar", "baz"] it "reads *arbitrary* header lines" $ do property $ \xs n -> do let ys = filter ((&&) <$> not . B.null <*> B.notElem '\n') xs c <- mkInputStream (slice n $ B.intercalate "\r\n" ys `B.append` "\r\n\r\n") readHeaderLines maxBound c `shouldReturn` ys describe "parseHeaderFields" $ do it "reads headers" $ do parseHeaderFields ["foo: 23", "bar: 42"] `shouldBe` Just [("foo", "23"), ("bar", "42")] it "ignores empty header lines" $ do parseHeaderFields ["foo: 23", " ", "bar: 42"] `shouldBe` Just [("foo", "23 "), ("bar", "42")] context "when header line starts with whitespace" $ do it "combines that line with the previous line" $ do parseHeaderFields ["foo: bar,", " baz"] `shouldBe` Just [("foo", "bar, baz")] context "when a header line does not contain a colon" $ do it "returns Nothing" $ do parseHeaderFields ["foo"] `shouldBe` Nothing
null
https://raw.githubusercontent.com/sol/http-kit/cc7eb6f1cb3ad6044c822286ad1352e26c112c69/test/Network/HTTP/Toolkit/HeaderSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module Network.HTTP.Toolkit.HeaderSpec (main, spec) where import Helper import qualified Data.ByteString.Char8 as B import Network.HTTP.Toolkit.Error import Network.HTTP.Toolkit.Header main :: IO () main = hspec spec spec :: Spec spec = do describe "readMessageHeader" $ do it "reads message header" $ do c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo: 23\r\nbar: 42\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldReturn` ("HTTP/1.1 200 OK", [("foo", "23"), ("bar", "42")]) context "when start-line is missing" $ do it "throws InvalidHeader" $ do c <- mkInputStream ["\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== InvalidHeader) context "when header is malformed" $ do it "throws InvalidHeader" $ do c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo\r\n\r\n"] readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== InvalidHeader) context "when attacker sends infinite header" $ do it "throws HeaderTooLarge" $ do c <- mkInputStream ("GET / HTTP/1.1" : repeat "foo: 23\r\n") readMessageHeader defaultHeaderSizeLimit c `shouldThrow` (== HeaderTooLarge) context "when input chunk exceeds defaultHeaderSizeLimit" $ do regression test for # 2 c <- mkInputStream ["HTTP/1.1 200 OK\r\nfoo: 23\r\nbar: 42\r\n\r\n" <> mconcat (replicate 1000000 "foo")] readMessageHeader defaultHeaderSizeLimit c `shouldReturn` ("HTTP/1.1 200 OK", [("foo", "23"), ("bar", "42")]) describe "combineHeaderLines" $ do it "strips trailing whitespace" $ do combineHeaderLines ["foo\r", "bar\t", "baz \t\r"] `shouldBe` ["foo", "bar", "baz"] context "when a header line starts with whitespace" $ do it "combines that line with the previous line" $ do combineHeaderLines ["foo", "bar", " baz"] `shouldBe` ["foo", "bar baz"] context "when multiple header lines start with whitespace" $ do it "combines consecutive lines" $ do combineHeaderLines ["foo", " bar \r", " baz"] `shouldBe` ["foo bar baz"] describe "readHeaderLines" $ do it "reads header lines" $ do property $ \n -> do c <- mkInputStream (slice n "foo\r\nbar\r\nbaz\r\n\r\n") readHeaderLines defaultHeaderSizeLimit c `shouldReturn` ["foo", "bar", "baz"] it "reads *arbitrary* header lines" $ do property $ \xs n -> do let ys = filter ((&&) <$> not . B.null <*> B.notElem '\n') xs c <- mkInputStream (slice n $ B.intercalate "\r\n" ys `B.append` "\r\n\r\n") readHeaderLines maxBound c `shouldReturn` ys describe "parseHeaderFields" $ do it "reads headers" $ do parseHeaderFields ["foo: 23", "bar: 42"] `shouldBe` Just [("foo", "23"), ("bar", "42")] it "ignores empty header lines" $ do parseHeaderFields ["foo: 23", " ", "bar: 42"] `shouldBe` Just [("foo", "23 "), ("bar", "42")] context "when header line starts with whitespace" $ do it "combines that line with the previous line" $ do parseHeaderFields ["foo: bar,", " baz"] `shouldBe` Just [("foo", "bar, baz")] context "when a header line does not contain a colon" $ do it "returns Nothing" $ do parseHeaderFields ["foo"] `shouldBe` Nothing
31a6c3d0d80a390c4112de3cbd69fc800773458e5f19c4609aec19e61f937d40
LdBeth/CLFSWM
menu-def.lisp
;;; -------------------------------------------------------------------------- ;;; CLFSWM - FullScreen Window Manager ;;; ;;; -------------------------------------------------------------------------- ;;; Documentation: Menu definitions ;;; Note : Mod-1 is the Alt or Meta key , Mod-2 is the key . ;;; -------------------------------------------------------------------------- ;;; ( C ) 2005 - 2015 < > ;;; ;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License ;;; along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . ;;; ;;; -------------------------------------------------------------------------- (in-package :clfswm) (format t "Updating menus...") (force-output) (init-menu) ;;; Here is a small example of menu manipulation: ( add - menu - key ' main " a " ' help - on - second - mode ) ;;(add-menu-key 'main "c" 'help-on-clfswm) ;; ;;(add-sub-menu 'main "p" 'plop "A sub menu") ;; ;;(add-menu-key 'plop "a" 'help-on-clfswm) ( add - menu - key ' plop " b " ' help - on - second - mode ) ( add - menu - key ' plop " d " ' help - on - second - mode ) ;;(del-menu-key 'main "p") ;;(del-menu-value 'plop 'help-on-main-mode) ;;(del-sub-menu 'main 'plop) ( define - second - key ( " a " ) ' open - menu ) (add-sub-menu 'main "F1" 'help-menu "Help menu") (add-sub-menu 'main "d" 'standard-menu "Standard menu") (add-sub-menu 'main "c" 'child-menu "Child menu") (add-sub-menu 'main "r" 'root-menu "Root menu") (add-sub-menu 'main "f" 'frame-menu "Frame menu") (add-sub-menu 'main "w" 'window-menu "Window menu") (add-sub-menu 'main "s" 'selection-menu "Selection menu") (add-sub-menu 'main "n" 'action-by-name-menu "Action by name menu") (add-sub-menu 'main "u" 'action-by-number-menu "Action by number menu") (add-sub-menu 'main "y" 'utility-menu "Utility menu") (add-sub-menu 'main "o" 'configuration-menu "Configuration menu") (add-sub-menu 'main "m" 'clfswm-menu "CLFSWM menu") (update-menus (find-menu 'standard-menu)) (add-menu-key 'help-menu "a" 'show-first-aid-kit) (add-menu-key 'help-menu "h" 'show-global-key-binding) (add-menu-key 'help-menu "b" 'show-main-mode-key-binding) (add-menu-key 'help-menu "s" 'show-second-mode-key-binding) (add-menu-key 'help-menu "r" 'show-circulate-mode-key-binding) (add-menu-key 'help-menu "e" 'show-expose-window-mode-key-binding) (add-menu-key 'help-menu "c" 'show-corner-help) (add-menu-key 'help-menu "g" 'show-config-variable) (add-menu-key 'help-menu "d" 'show-date) (add-menu-key 'help-menu "p" 'show-cpu-proc) (add-menu-key 'help-menu "m" 'show-mem-proc) (add-menu-key 'help-menu "v" 'show-version) (add-menu-key 'child-menu "r" 'rename-current-child) (add-menu-key 'child-menu "b" 'bury-current-child) (add-menu-key 'child-menu "f" 'bury-first-child) (add-menu-key 'child-menu "t" 'set-current-child-transparency) (add-menu-key 'child-menu "o" 'set-current-child-border-size) (add-menu-key 'child-menu "e" 'ensure-unique-name) (add-menu-key 'child-menu "n" 'ensure-unique-number) (add-menu-key 'child-menu "Delete" 'delete-current-child) (add-menu-key 'child-menu "X" 'remove-current-child) (add-menu-key 'child-menu "R" 'retrieve-existing-window) (add-menu-key 'child-menu "h" 'hide-current-child) (add-menu-key 'child-menu "u" 'unhide-a-child) (add-menu-key 'child-menu "F" 'unhide-a-child-from-all-frames) (add-menu-key 'child-menu "a" 'unhide-all-children) (add-menu-key 'child-menu "Page_Up" 'frame-lower-child) (add-menu-key 'child-menu "Page_Down" 'frame-raise-child) (add-menu-key 'root-menu "n" 'select-next-root-restart-menu) (add-menu-key 'root-menu "p" 'select-previous-root-restart-menu) (add-menu-key 'root-menu "g" 'rotate-root-geometry-next-restart-menu) (add-menu-key 'root-menu "f" 'rotate-root-geometry-previous-restart-menu) (add-menu-key 'root-menu "x" 'exchange-root-geometry-with-mouse) (add-menu-key 'root-menu "r" 'change-current-root-geometry) (add-sub-menu 'frame-menu "a" 'frame-adding-menu "Adding frame menu") (add-sub-menu 'frame-menu "l" 'frame-layout-menu "Frame layout menu") (add-sub-menu 'frame-menu "n" 'frame-nw-hook-menu "Frame new window hook menu") (add-sub-menu 'frame-menu "m" 'frame-movement-menu "Frame movement menu") (add-sub-menu 'frame-menu "f" 'frame-focus-policy "Frame focus policy menu") (add-sub-menu 'frame-menu "w" 'frame-managed-window-menu "Managed window type menu") (add-sub-menu 'frame-menu "u" 'frame-unmanaged-window-menu "Unmanaged window behaviour") (add-sub-menu 'frame-menu "s" 'frame-miscellaneous-menu "Frame miscallenous menu") (add-menu-key 'frame-menu "x" 'frame-toggle-maximize) (add-menu-key 'frame-adding-menu "a" 'add-default-frame) (add-menu-key 'frame-adding-menu "p" 'add-placed-frame) (add-sub-menu 'frame-movement-menu "p" 'frame-pack-menu "Frame pack menu") (add-sub-menu 'frame-movement-menu "f" 'frame-fill-menu "Frame fill menu") (add-sub-menu 'frame-movement-menu "r" 'frame-resize-menu "Frame resize menu") (add-menu-key 'frame-movement-menu "c" 'center-current-frame) (add-menu-key 'frame-movement-menu "R" 'with-movement-select-next-brother) (add-menu-key 'frame-movement-menu "L" 'with-movement-select-previous-brother) (add-menu-key 'frame-movement-menu "U" 'with-movement-select-next-level) (add-menu-key 'frame-movement-menu "D" 'with-movement-select-previous-level) (add-menu-key 'frame-movement-menu "T" 'with-movement-select-next-child) (add-menu-key 'frame-pack-menu "u" 'current-frame-pack-up) (add-menu-key 'frame-pack-menu "d" 'current-frame-pack-down) (add-menu-key 'frame-pack-menu "l" 'current-frame-pack-left) (add-menu-key 'frame-pack-menu "r" 'current-frame-pack-right) (add-menu-key 'frame-fill-menu "u" 'current-frame-fill-up) (add-menu-key 'frame-fill-menu "d" 'current-frame-fill-down) (add-menu-key 'frame-fill-menu "l" 'current-frame-fill-left) (add-menu-key 'frame-fill-menu "r" 'current-frame-fill-right) (add-menu-key 'frame-fill-menu "a" 'current-frame-fill-all-dir) (add-menu-key 'frame-fill-menu "v" 'current-frame-fill-vertical) (add-menu-key 'frame-fill-menu "h" 'current-frame-fill-horizontal) (add-menu-key 'frame-resize-menu "u" 'current-frame-resize-up) (add-menu-key 'frame-resize-menu "d" 'current-frame-resize-down) (add-menu-key 'frame-resize-menu "l" 'current-frame-resize-left) (add-menu-key 'frame-resize-menu "r" 'current-frame-resize-right) (add-menu-key 'frame-resize-menu "a" 'current-frame-resize-all-dir) (add-menu-key 'frame-resize-menu "m" 'current-frame-resize-all-dir-minimal) (add-menu-comment 'frame-focus-policy "-=- For the current frame -=-") (add-menu-key 'frame-focus-policy "a" 'current-frame-set-click-focus-policy) (add-menu-key 'frame-focus-policy "b" 'current-frame-set-sloppy-focus-policy) (add-menu-key 'frame-focus-policy "c" 'current-frame-set-sloppy-strict-focus-policy) (add-menu-key 'frame-focus-policy "d" 'current-frame-set-sloppy-select-policy) (add-menu-key 'frame-focus-policy "e" 'current-frame-set-sloppy-select-window-policy) (add-menu-comment 'frame-focus-policy "-=- For all frames -=-") (add-menu-key 'frame-focus-policy "f" 'all-frames-set-click-focus-policy) (add-menu-key 'frame-focus-policy "g" 'all-frames-set-sloppy-focus-policy) (add-menu-key 'frame-focus-policy "h" 'all-frames-set-sloppy-strict-focus-policy) (add-menu-key 'frame-focus-policy "i" 'all-frames-set-sloppy-select-policy) (add-menu-key 'frame-focus-policy "j" 'all-frames-set-sloppy-select-window-policy) (add-menu-key 'frame-managed-window-menu "m" 'current-frame-manage-window-type) (add-menu-key 'frame-managed-window-menu "a" 'current-frame-manage-all-window-type) (add-menu-key 'frame-managed-window-menu "n" 'current-frame-manage-only-normal-window-type) (add-menu-key 'frame-managed-window-menu "u" 'current-frame-manage-no-window-type) (add-menu-key 'frame-unmanaged-window-menu "s" 'set-show-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "h" 'set-hide-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "d" 'set-default-hide-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "w" 'set-globally-show-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "i" 'set-globally-hide-unmanaged-window) (add-menu-key 'frame-miscellaneous-menu "s" 'show-all-frames-info) (add-menu-key 'frame-miscellaneous-menu "a" 'hide-all-frames-info) (add-menu-key 'frame-miscellaneous-menu "h" 'hide-current-frame-window) (add-menu-key 'frame-miscellaneous-menu "w" 'show-current-frame-window) (add-menu-key 'frame-miscellaneous-menu "u" 'renumber-current-frame) (add-menu-key 'frame-miscellaneous-menu "x" 'explode-current-frame) (add-menu-key 'frame-miscellaneous-menu "i" 'implode-current-frame) (add-menu-key 'window-menu "i" 'display-current-window-info) (add-menu-key 'window-menu "t" 'set-current-window-transparency) (add-menu-key 'window-menu "f" 'force-window-in-frame) (add-menu-key 'window-menu "c" 'force-window-center-in-frame) (add-menu-key 'window-menu "m" 'manage-current-window) (add-menu-key 'window-menu "u" 'unmanage-current-window) (add-menu-key 'window-menu "a" 'adapt-current-frame-to-window-hints) (add-menu-key 'window-menu "w" 'adapt-current-frame-to-window-width-hint) (add-menu-key 'window-menu "h" 'adapt-current-frame-to-window-height-hint) (add-menu-key 'selection-menu "x" 'cut-current-child) (add-menu-key 'selection-menu "c" 'copy-current-child) (add-menu-key 'selection-menu "v" 'paste-selection) (add-menu-key 'selection-menu "p" 'paste-selection-no-clear) (add-menu-key 'selection-menu "Delete" 'remove-current-child) (add-menu-key 'selection-menu "z" 'clear-selection) (add-menu-key 'action-by-name-menu "f" 'focus-frame-by-name) (add-menu-key 'action-by-name-menu "o" 'open-frame-by-name) (add-menu-key 'action-by-name-menu "d" 'delete-frame-by-name) (add-menu-key 'action-by-name-menu "m" 'move-current-child-by-name) (add-menu-key 'action-by-name-menu "c" 'copy-current-child-by-name) (add-menu-key 'action-by-number-menu "f" 'focus-frame-by-number) (add-menu-key 'action-by-number-menu "o" 'open-frame-by-number) (add-menu-key 'action-by-number-menu "d" 'delete-frame-by-number) (add-menu-key 'action-by-number-menu "m" 'move-current-child-by-number) (add-menu-key 'action-by-number-menu "c" 'copy-current-child-by-number) (add-menu-key 'utility-menu "i" 'identify-key) (add-menu-key 'utility-menu "colon" 'eval-from-query-string) (add-menu-key 'utility-menu "exclam" 'run-program-from-query-string) (add-sub-menu 'utility-menu "o" 'other-window-manager-menu "Other window manager menu") (add-menu-key 'other-window-manager-menu "x" 'run-xterm) (add-menu-key 'other-window-manager-menu "t" 'run-twm) (add-menu-key 'other-window-manager-menu "i" 'run-icewm) (add-menu-key 'other-window-manager-menu "g" 'run-gnome-session) (add-menu-key 'other-window-manager-menu "k" 'run-startkde) (add-menu-key 'other-window-manager-menu "c" 'run-xfce4-session) (add-menu-key 'other-window-manager-menu "l" 'run-lxde) (add-menu-key 'other-window-manager-menu "p" 'run-prompt-wm) (add-menu-key 'clfswm-menu "r" 'reset-clfswm) (add-menu-key 'clfswm-menu "l" 'reload-clfswm) (add-menu-key 'clfswm-menu "x" 'exit-clfswm) (format t " Done.~%") (force-output)
null
https://raw.githubusercontent.com/LdBeth/CLFSWM/4e936552d1388718d2947a5f6ca3eada19643e75/src/menu-def.lisp
lisp
-------------------------------------------------------------------------- CLFSWM - FullScreen Window Manager -------------------------------------------------------------------------- Documentation: Menu definitions -------------------------------------------------------------------------- This program is free software; you can redistribute it and/or modify either version 3 of the License , or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software -------------------------------------------------------------------------- Here is a small example of menu manipulation: (add-menu-key 'main "c" 'help-on-clfswm) (add-sub-menu 'main "p" 'plop "A sub menu") (add-menu-key 'plop "a" 'help-on-clfswm) (del-menu-key 'main "p") (del-menu-value 'plop 'help-on-main-mode) (del-sub-menu 'main 'plop)
Note : Mod-1 is the Alt or Meta key , Mod-2 is the key . ( C ) 2005 - 2015 < > it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . (in-package :clfswm) (format t "Updating menus...") (force-output) (init-menu) ( add - menu - key ' main " a " ' help - on - second - mode ) ( add - menu - key ' plop " b " ' help - on - second - mode ) ( add - menu - key ' plop " d " ' help - on - second - mode ) ( define - second - key ( " a " ) ' open - menu ) (add-sub-menu 'main "F1" 'help-menu "Help menu") (add-sub-menu 'main "d" 'standard-menu "Standard menu") (add-sub-menu 'main "c" 'child-menu "Child menu") (add-sub-menu 'main "r" 'root-menu "Root menu") (add-sub-menu 'main "f" 'frame-menu "Frame menu") (add-sub-menu 'main "w" 'window-menu "Window menu") (add-sub-menu 'main "s" 'selection-menu "Selection menu") (add-sub-menu 'main "n" 'action-by-name-menu "Action by name menu") (add-sub-menu 'main "u" 'action-by-number-menu "Action by number menu") (add-sub-menu 'main "y" 'utility-menu "Utility menu") (add-sub-menu 'main "o" 'configuration-menu "Configuration menu") (add-sub-menu 'main "m" 'clfswm-menu "CLFSWM menu") (update-menus (find-menu 'standard-menu)) (add-menu-key 'help-menu "a" 'show-first-aid-kit) (add-menu-key 'help-menu "h" 'show-global-key-binding) (add-menu-key 'help-menu "b" 'show-main-mode-key-binding) (add-menu-key 'help-menu "s" 'show-second-mode-key-binding) (add-menu-key 'help-menu "r" 'show-circulate-mode-key-binding) (add-menu-key 'help-menu "e" 'show-expose-window-mode-key-binding) (add-menu-key 'help-menu "c" 'show-corner-help) (add-menu-key 'help-menu "g" 'show-config-variable) (add-menu-key 'help-menu "d" 'show-date) (add-menu-key 'help-menu "p" 'show-cpu-proc) (add-menu-key 'help-menu "m" 'show-mem-proc) (add-menu-key 'help-menu "v" 'show-version) (add-menu-key 'child-menu "r" 'rename-current-child) (add-menu-key 'child-menu "b" 'bury-current-child) (add-menu-key 'child-menu "f" 'bury-first-child) (add-menu-key 'child-menu "t" 'set-current-child-transparency) (add-menu-key 'child-menu "o" 'set-current-child-border-size) (add-menu-key 'child-menu "e" 'ensure-unique-name) (add-menu-key 'child-menu "n" 'ensure-unique-number) (add-menu-key 'child-menu "Delete" 'delete-current-child) (add-menu-key 'child-menu "X" 'remove-current-child) (add-menu-key 'child-menu "R" 'retrieve-existing-window) (add-menu-key 'child-menu "h" 'hide-current-child) (add-menu-key 'child-menu "u" 'unhide-a-child) (add-menu-key 'child-menu "F" 'unhide-a-child-from-all-frames) (add-menu-key 'child-menu "a" 'unhide-all-children) (add-menu-key 'child-menu "Page_Up" 'frame-lower-child) (add-menu-key 'child-menu "Page_Down" 'frame-raise-child) (add-menu-key 'root-menu "n" 'select-next-root-restart-menu) (add-menu-key 'root-menu "p" 'select-previous-root-restart-menu) (add-menu-key 'root-menu "g" 'rotate-root-geometry-next-restart-menu) (add-menu-key 'root-menu "f" 'rotate-root-geometry-previous-restart-menu) (add-menu-key 'root-menu "x" 'exchange-root-geometry-with-mouse) (add-menu-key 'root-menu "r" 'change-current-root-geometry) (add-sub-menu 'frame-menu "a" 'frame-adding-menu "Adding frame menu") (add-sub-menu 'frame-menu "l" 'frame-layout-menu "Frame layout menu") (add-sub-menu 'frame-menu "n" 'frame-nw-hook-menu "Frame new window hook menu") (add-sub-menu 'frame-menu "m" 'frame-movement-menu "Frame movement menu") (add-sub-menu 'frame-menu "f" 'frame-focus-policy "Frame focus policy menu") (add-sub-menu 'frame-menu "w" 'frame-managed-window-menu "Managed window type menu") (add-sub-menu 'frame-menu "u" 'frame-unmanaged-window-menu "Unmanaged window behaviour") (add-sub-menu 'frame-menu "s" 'frame-miscellaneous-menu "Frame miscallenous menu") (add-menu-key 'frame-menu "x" 'frame-toggle-maximize) (add-menu-key 'frame-adding-menu "a" 'add-default-frame) (add-menu-key 'frame-adding-menu "p" 'add-placed-frame) (add-sub-menu 'frame-movement-menu "p" 'frame-pack-menu "Frame pack menu") (add-sub-menu 'frame-movement-menu "f" 'frame-fill-menu "Frame fill menu") (add-sub-menu 'frame-movement-menu "r" 'frame-resize-menu "Frame resize menu") (add-menu-key 'frame-movement-menu "c" 'center-current-frame) (add-menu-key 'frame-movement-menu "R" 'with-movement-select-next-brother) (add-menu-key 'frame-movement-menu "L" 'with-movement-select-previous-brother) (add-menu-key 'frame-movement-menu "U" 'with-movement-select-next-level) (add-menu-key 'frame-movement-menu "D" 'with-movement-select-previous-level) (add-menu-key 'frame-movement-menu "T" 'with-movement-select-next-child) (add-menu-key 'frame-pack-menu "u" 'current-frame-pack-up) (add-menu-key 'frame-pack-menu "d" 'current-frame-pack-down) (add-menu-key 'frame-pack-menu "l" 'current-frame-pack-left) (add-menu-key 'frame-pack-menu "r" 'current-frame-pack-right) (add-menu-key 'frame-fill-menu "u" 'current-frame-fill-up) (add-menu-key 'frame-fill-menu "d" 'current-frame-fill-down) (add-menu-key 'frame-fill-menu "l" 'current-frame-fill-left) (add-menu-key 'frame-fill-menu "r" 'current-frame-fill-right) (add-menu-key 'frame-fill-menu "a" 'current-frame-fill-all-dir) (add-menu-key 'frame-fill-menu "v" 'current-frame-fill-vertical) (add-menu-key 'frame-fill-menu "h" 'current-frame-fill-horizontal) (add-menu-key 'frame-resize-menu "u" 'current-frame-resize-up) (add-menu-key 'frame-resize-menu "d" 'current-frame-resize-down) (add-menu-key 'frame-resize-menu "l" 'current-frame-resize-left) (add-menu-key 'frame-resize-menu "r" 'current-frame-resize-right) (add-menu-key 'frame-resize-menu "a" 'current-frame-resize-all-dir) (add-menu-key 'frame-resize-menu "m" 'current-frame-resize-all-dir-minimal) (add-menu-comment 'frame-focus-policy "-=- For the current frame -=-") (add-menu-key 'frame-focus-policy "a" 'current-frame-set-click-focus-policy) (add-menu-key 'frame-focus-policy "b" 'current-frame-set-sloppy-focus-policy) (add-menu-key 'frame-focus-policy "c" 'current-frame-set-sloppy-strict-focus-policy) (add-menu-key 'frame-focus-policy "d" 'current-frame-set-sloppy-select-policy) (add-menu-key 'frame-focus-policy "e" 'current-frame-set-sloppy-select-window-policy) (add-menu-comment 'frame-focus-policy "-=- For all frames -=-") (add-menu-key 'frame-focus-policy "f" 'all-frames-set-click-focus-policy) (add-menu-key 'frame-focus-policy "g" 'all-frames-set-sloppy-focus-policy) (add-menu-key 'frame-focus-policy "h" 'all-frames-set-sloppy-strict-focus-policy) (add-menu-key 'frame-focus-policy "i" 'all-frames-set-sloppy-select-policy) (add-menu-key 'frame-focus-policy "j" 'all-frames-set-sloppy-select-window-policy) (add-menu-key 'frame-managed-window-menu "m" 'current-frame-manage-window-type) (add-menu-key 'frame-managed-window-menu "a" 'current-frame-manage-all-window-type) (add-menu-key 'frame-managed-window-menu "n" 'current-frame-manage-only-normal-window-type) (add-menu-key 'frame-managed-window-menu "u" 'current-frame-manage-no-window-type) (add-menu-key 'frame-unmanaged-window-menu "s" 'set-show-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "h" 'set-hide-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "d" 'set-default-hide-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "w" 'set-globally-show-unmanaged-window) (add-menu-key 'frame-unmanaged-window-menu "i" 'set-globally-hide-unmanaged-window) (add-menu-key 'frame-miscellaneous-menu "s" 'show-all-frames-info) (add-menu-key 'frame-miscellaneous-menu "a" 'hide-all-frames-info) (add-menu-key 'frame-miscellaneous-menu "h" 'hide-current-frame-window) (add-menu-key 'frame-miscellaneous-menu "w" 'show-current-frame-window) (add-menu-key 'frame-miscellaneous-menu "u" 'renumber-current-frame) (add-menu-key 'frame-miscellaneous-menu "x" 'explode-current-frame) (add-menu-key 'frame-miscellaneous-menu "i" 'implode-current-frame) (add-menu-key 'window-menu "i" 'display-current-window-info) (add-menu-key 'window-menu "t" 'set-current-window-transparency) (add-menu-key 'window-menu "f" 'force-window-in-frame) (add-menu-key 'window-menu "c" 'force-window-center-in-frame) (add-menu-key 'window-menu "m" 'manage-current-window) (add-menu-key 'window-menu "u" 'unmanage-current-window) (add-menu-key 'window-menu "a" 'adapt-current-frame-to-window-hints) (add-menu-key 'window-menu "w" 'adapt-current-frame-to-window-width-hint) (add-menu-key 'window-menu "h" 'adapt-current-frame-to-window-height-hint) (add-menu-key 'selection-menu "x" 'cut-current-child) (add-menu-key 'selection-menu "c" 'copy-current-child) (add-menu-key 'selection-menu "v" 'paste-selection) (add-menu-key 'selection-menu "p" 'paste-selection-no-clear) (add-menu-key 'selection-menu "Delete" 'remove-current-child) (add-menu-key 'selection-menu "z" 'clear-selection) (add-menu-key 'action-by-name-menu "f" 'focus-frame-by-name) (add-menu-key 'action-by-name-menu "o" 'open-frame-by-name) (add-menu-key 'action-by-name-menu "d" 'delete-frame-by-name) (add-menu-key 'action-by-name-menu "m" 'move-current-child-by-name) (add-menu-key 'action-by-name-menu "c" 'copy-current-child-by-name) (add-menu-key 'action-by-number-menu "f" 'focus-frame-by-number) (add-menu-key 'action-by-number-menu "o" 'open-frame-by-number) (add-menu-key 'action-by-number-menu "d" 'delete-frame-by-number) (add-menu-key 'action-by-number-menu "m" 'move-current-child-by-number) (add-menu-key 'action-by-number-menu "c" 'copy-current-child-by-number) (add-menu-key 'utility-menu "i" 'identify-key) (add-menu-key 'utility-menu "colon" 'eval-from-query-string) (add-menu-key 'utility-menu "exclam" 'run-program-from-query-string) (add-sub-menu 'utility-menu "o" 'other-window-manager-menu "Other window manager menu") (add-menu-key 'other-window-manager-menu "x" 'run-xterm) (add-menu-key 'other-window-manager-menu "t" 'run-twm) (add-menu-key 'other-window-manager-menu "i" 'run-icewm) (add-menu-key 'other-window-manager-menu "g" 'run-gnome-session) (add-menu-key 'other-window-manager-menu "k" 'run-startkde) (add-menu-key 'other-window-manager-menu "c" 'run-xfce4-session) (add-menu-key 'other-window-manager-menu "l" 'run-lxde) (add-menu-key 'other-window-manager-menu "p" 'run-prompt-wm) (add-menu-key 'clfswm-menu "r" 'reset-clfswm) (add-menu-key 'clfswm-menu "l" 'reload-clfswm) (add-menu-key 'clfswm-menu "x" 'exit-clfswm) (format t " Done.~%") (force-output)
379e485fd1416ec8800325e9cc0a9bee9e447faf5ab787f18ad309ab827ac9f4
chrislloyd/kepler
name.clj
(ns kepler.systems.name (:require [kepler.component :refer [update-component-val]])) (defn name-system [state action] (if (= (:type action) :name) (map (fn [component] (if (and (= (:entity action) (:entity component)) (= (:type component) :name)) (update-component-val (constantly (:name action)) component) component)) state) state))
null
https://raw.githubusercontent.com/chrislloyd/kepler/bd6f30c20ff9e5ad6749bab0d3589d9ccce6f14f/src/kepler/systems/name.clj
clojure
(ns kepler.systems.name (:require [kepler.component :refer [update-component-val]])) (defn name-system [state action] (if (= (:type action) :name) (map (fn [component] (if (and (= (:entity action) (:entity component)) (= (:type component) :name)) (update-component-val (constantly (:name action)) component) component)) state) state))
01599b787f11060d61e44b077a533033c9cdf74882f1ecc3c58a2bfa2f567026
bjpop/blip
Utils.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # {-# LANGUAGE MagicHash #-} module Blip.Interpreter.HashTable.Utils ( whichBucket , nextBestPrime , bumpSize , shiftL , shiftRL , iShiftL , iShiftRL , nextHighestPowerOf2 , log2 , highestBitMask , wordSize , cacheLineSize , numElemsInCacheLine , cacheLineIntMask , cacheLineIntBits , forceSameType ) where import Data.Bits hiding (shiftL) import Blip.Interpreter.HashTable.IntArray (Elem) import Data.Vector (Vector) import qualified Data.Vector as V #if __GLASGOW_HASKELL__ >= 503 import GHC.Exts #else import qualified Data.Bits import Data.Word #endif ------------------------------------------------------------------------------ wordSize :: Int wordSize = bitSize (0::Int) cacheLineSize :: Int cacheLineSize = 64 numElemsInCacheLine :: Int numElemsInCacheLine = z where !z = cacheLineSize `div` (bitSize (0::Elem) `div` 8) -- | What you have to mask an integer index by to tell if it's -- cacheline-aligned cacheLineIntMask :: Int cacheLineIntMask = z where !z = numElemsInCacheLine - 1 cacheLineIntBits :: Int cacheLineIntBits = log2 $ toEnum numElemsInCacheLine ------------------------------------------------------------------------------ # INLINE whichBucket # whichBucket :: Int -> Int -> Int whichBucket !h !sz = o where !o = h `mod` sz ------------------------------------------------------------------------------ binarySearch :: (Ord e) => Vector e -> e -> Int binarySearch = binarySearchBy compare # INLINE binarySearch # ------------------------------------------------------------------------------ binarySearchBy :: (e -> e -> Ordering) -> Vector e -> e -> Int binarySearchBy cmp vec e = binarySearchByBounds cmp vec e 0 (V.length vec) # INLINE binarySearchBy # ------------------------------------------------------------------------------ binarySearchByBounds :: (e -> e -> Ordering) -> Vector e -> e -> Int -> Int -> Int binarySearchByBounds cmp vec e = loop where loop !l !u | u <= l = l | otherwise = let e' = V.unsafeIndex vec k in case cmp e' e of LT -> loop (k+1) u EQ -> k GT -> loop l k where k = (u + l) `shiftR` 1 # INLINE binarySearchByBounds # ------------------------------------------------------------------------------ primeSizes :: Vector Integer primeSizes = V.fromList [ 19 , 31 , 37 , 43 , 47 , 53 , 61 , 67 , 79 , 89 , 97 , 107 , 113 , 127 , 137 , 149 , 157 , 167 , 181 , 193 , 211 , 233 , 257 , 281 , 307 , 331 , 353 , 389 , 409 , 421 , 443 , 467 , 503 , 523 , 563 , 593 , 631 , 653 , 673 , 701 , 733 , 769 , 811 , 877 , 937 , 1039 , 1117 , 1229 , 1367 , 1543 , 1637 , 1747 , 1873 , 2003 , 2153 , 2311 , 2503 , 2777 , 3079 , 3343 , 3697 , 5281 , 6151 , 7411 , 9901 , 12289 , 18397 , 24593 , 34651 , 49157 , 66569 , 73009 , 98317 , 118081 , 151051 , 196613 , 246011 , 393241 , 600011 , 786433 , 1050013 , 1572869 , 2203657 , 3145739 , 4000813 , 6291469 , 7801379 , 10004947 , 12582917 , 19004989 , 22752641 , 25165843 , 39351667 , 50331653 , 69004951 , 83004629 , 100663319 , 133004881 , 173850851 , 201326611 , 293954587 , 402653189 , 550001761 , 702952391 , 805306457 , 1102951999 , 1402951337 , 1610612741 , 1902802801 , 2147483647 , 3002954501 , 3902954959 , 4294967291 , 5002902979 , 6402754181 , 8589934583 , 17179869143 , 34359738337 , 68719476731 , 137438953447 , 274877906899 ] ------------------------------------------------------------------------------ nextBestPrime :: Int -> Int nextBestPrime x = fromEnum yi where xi = toEnum x idx = binarySearch primeSizes xi yi = V.unsafeIndex primeSizes idx ------------------------------------------------------------------------------ bumpSize :: Double -> Int -> Int bumpSize !maxLoad !s = nextBestPrime $! ceiling (fromIntegral s / maxLoad) ------------------------------------------------------------------------------ shiftL :: Word -> Int -> Word shiftRL :: Word -> Int -> Word iShiftL :: Int -> Int -> Int iShiftRL :: Int -> Int -> Int #if __GLASGOW_HASKELL__ ------------------------------------------------------------------- GHC : use unboxing to get @shiftRL@ inlined . ------------------------------------------------------------------- GHC: use unboxing to get @shiftRL@ inlined. --------------------------------------------------------------------} # INLINE shiftL # shiftL (W# x) (I# i) = W# (shiftL# x i) # INLINE shiftRL # shiftRL (W# x) (I# i) = W# (shiftRL# x i) # INLINE iShiftL # iShiftL (I# x) (I# i) = I# (iShiftL# x i) # INLINE iShiftRL # iShiftRL (I# x) (I# i) = I# (iShiftRL# x i) #else shiftL x i = Data.Bits.shiftL x i shiftRL x i = shiftR x i iShiftL x i = shiftL x i iShiftRL x i = shiftRL x i #endif ------------------------------------------------------------------------------ # INLINE nextHighestPowerOf2 # nextHighestPowerOf2 :: Word -> Word nextHighestPowerOf2 w = highestBitMask (w-1) + 1 ------------------------------------------------------------------------------ log2 :: Word -> Int log2 w = go (nextHighestPowerOf2 w) 0 where go 0 !i = i-1 go !n !i = go (shiftRL n 1) (i+1) ------------------------------------------------------------------------------ # INLINE highestBitMask # highestBitMask :: Word -> Word highestBitMask !x0 = case (x0 .|. shiftRL x0 1) of x1 -> case (x1 .|. shiftRL x1 2) of x2 -> case (x2 .|. shiftRL x2 4) of x3 -> case (x3 .|. shiftRL x3 8) of x4 -> case (x4 .|. shiftRL x4 16) of x5 -> x5 .|. shiftRL x5 32 ------------------------------------------------------------------------------ forceSameType :: Monad m => a -> a -> m () forceSameType _ _ = return () # INLINE forceSameType #
null
https://raw.githubusercontent.com/bjpop/blip/3d9105a44d1afb7bd007da3742fb19dc69372e10/blipinterpreter/src/Blip/Interpreter/HashTable/Utils.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE MagicHash # ---------------------------------------------------------------------------- | What you have to mask an integer index by to tell if it's cacheline-aligned ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- ------------------------------------------------------------------} ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------------------
# LANGUAGE CPP # module Blip.Interpreter.HashTable.Utils ( whichBucket , nextBestPrime , bumpSize , shiftL , shiftRL , iShiftL , iShiftRL , nextHighestPowerOf2 , log2 , highestBitMask , wordSize , cacheLineSize , numElemsInCacheLine , cacheLineIntMask , cacheLineIntBits , forceSameType ) where import Data.Bits hiding (shiftL) import Blip.Interpreter.HashTable.IntArray (Elem) import Data.Vector (Vector) import qualified Data.Vector as V #if __GLASGOW_HASKELL__ >= 503 import GHC.Exts #else import qualified Data.Bits import Data.Word #endif wordSize :: Int wordSize = bitSize (0::Int) cacheLineSize :: Int cacheLineSize = 64 numElemsInCacheLine :: Int numElemsInCacheLine = z where !z = cacheLineSize `div` (bitSize (0::Elem) `div` 8) cacheLineIntMask :: Int cacheLineIntMask = z where !z = numElemsInCacheLine - 1 cacheLineIntBits :: Int cacheLineIntBits = log2 $ toEnum numElemsInCacheLine # INLINE whichBucket # whichBucket :: Int -> Int -> Int whichBucket !h !sz = o where !o = h `mod` sz binarySearch :: (Ord e) => Vector e -> e -> Int binarySearch = binarySearchBy compare # INLINE binarySearch # binarySearchBy :: (e -> e -> Ordering) -> Vector e -> e -> Int binarySearchBy cmp vec e = binarySearchByBounds cmp vec e 0 (V.length vec) # INLINE binarySearchBy # binarySearchByBounds :: (e -> e -> Ordering) -> Vector e -> e -> Int -> Int -> Int binarySearchByBounds cmp vec e = loop where loop !l !u | u <= l = l | otherwise = let e' = V.unsafeIndex vec k in case cmp e' e of LT -> loop (k+1) u EQ -> k GT -> loop l k where k = (u + l) `shiftR` 1 # INLINE binarySearchByBounds # primeSizes :: Vector Integer primeSizes = V.fromList [ 19 , 31 , 37 , 43 , 47 , 53 , 61 , 67 , 79 , 89 , 97 , 107 , 113 , 127 , 137 , 149 , 157 , 167 , 181 , 193 , 211 , 233 , 257 , 281 , 307 , 331 , 353 , 389 , 409 , 421 , 443 , 467 , 503 , 523 , 563 , 593 , 631 , 653 , 673 , 701 , 733 , 769 , 811 , 877 , 937 , 1039 , 1117 , 1229 , 1367 , 1543 , 1637 , 1747 , 1873 , 2003 , 2153 , 2311 , 2503 , 2777 , 3079 , 3343 , 3697 , 5281 , 6151 , 7411 , 9901 , 12289 , 18397 , 24593 , 34651 , 49157 , 66569 , 73009 , 98317 , 118081 , 151051 , 196613 , 246011 , 393241 , 600011 , 786433 , 1050013 , 1572869 , 2203657 , 3145739 , 4000813 , 6291469 , 7801379 , 10004947 , 12582917 , 19004989 , 22752641 , 25165843 , 39351667 , 50331653 , 69004951 , 83004629 , 100663319 , 133004881 , 173850851 , 201326611 , 293954587 , 402653189 , 550001761 , 702952391 , 805306457 , 1102951999 , 1402951337 , 1610612741 , 1902802801 , 2147483647 , 3002954501 , 3902954959 , 4294967291 , 5002902979 , 6402754181 , 8589934583 , 17179869143 , 34359738337 , 68719476731 , 137438953447 , 274877906899 ] nextBestPrime :: Int -> Int nextBestPrime x = fromEnum yi where xi = toEnum x idx = binarySearch primeSizes xi yi = V.unsafeIndex primeSizes idx bumpSize :: Double -> Int -> Int bumpSize !maxLoad !s = nextBestPrime $! ceiling (fromIntegral s / maxLoad) shiftL :: Word -> Int -> Word shiftRL :: Word -> Int -> Word iShiftL :: Int -> Int -> Int iShiftRL :: Int -> Int -> Int #if __GLASGOW_HASKELL__ GHC : use unboxing to get @shiftRL@ inlined . GHC: use unboxing to get @shiftRL@ inlined. # INLINE shiftL # shiftL (W# x) (I# i) = W# (shiftL# x i) # INLINE shiftRL # shiftRL (W# x) (I# i) = W# (shiftRL# x i) # INLINE iShiftL # iShiftL (I# x) (I# i) = I# (iShiftL# x i) # INLINE iShiftRL # iShiftRL (I# x) (I# i) = I# (iShiftRL# x i) #else shiftL x i = Data.Bits.shiftL x i shiftRL x i = shiftR x i iShiftL x i = shiftL x i iShiftRL x i = shiftRL x i #endif # INLINE nextHighestPowerOf2 # nextHighestPowerOf2 :: Word -> Word nextHighestPowerOf2 w = highestBitMask (w-1) + 1 log2 :: Word -> Int log2 w = go (nextHighestPowerOf2 w) 0 where go 0 !i = i-1 go !n !i = go (shiftRL n 1) (i+1) # INLINE highestBitMask # highestBitMask :: Word -> Word highestBitMask !x0 = case (x0 .|. shiftRL x0 1) of x1 -> case (x1 .|. shiftRL x1 2) of x2 -> case (x2 .|. shiftRL x2 4) of x3 -> case (x3 .|. shiftRL x3 8) of x4 -> case (x4 .|. shiftRL x4 16) of x5 -> x5 .|. shiftRL x5 32 forceSameType :: Monad m => a -> a -> m () forceSameType _ _ = return () # INLINE forceSameType #
80793525b410dd757e4cd4e9241cf152ef34748da805d9c16543c3a6d1c08d69
Mattiemus/LaneWars
Tests.hs
module Main where import Test.Hspec import Test.QuickCheck import FRP.Yampa as Yampa import FRP.Yampa.Geometry import Game.Shared.Types import Game.Shared.Physics import Game.Shared.Arrows import Game.Shared.Object import Data.Maybe import Control.Exception (evaluate) testObjects :: [GameObject] testObjects = [basicGameObject { goId = 1, goTeam = Neutral, goType = Player }, basicGameObject { goId = 2, goTeam = Red, goType = Minion }, basicGameObject { goId = 3, goTeam = Red, goType = Turret }] testRangedObjects :: [GameObject] testRangedObjects = [basicGameObject { goId = 1, goPos = vector2 0 0, goSize = vector2 10 10 }, basicGameObject { goId = 2, goPos = vector2 20 20, goSize = vector2 10 5 }, basicGameObject { goId = 3, goPos = vector2 5 5, goSize = vector2 2 2 }] main :: IO () main = hspec $ do describe "Game.Shared.Object.findObjById" $ do it "can find an object by its id" $ do findObjById 1 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 1) findObjById 2 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 2) findObjById 3 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 3) it "returns Nothing when no game object is found" $ do findObjById 0 testObjects `shouldSatisfy` isNothing findObjById 4 testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findObjByTeam" $ do it "can find an object by its team" $ do findObjByTeam Neutral testObjects `shouldSatisfy` (\(Just val) -> (goTeam val) == Neutral) findObjByTeam Red testObjects `shouldSatisfy` (\(Just val) -> (goTeam val) == Red) it "returns Nothing when no game object is found" $ do findObjByTeam Blue testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findObjByType" $ do it "can find an object by its type" $ do findObjByType Player testObjects `shouldSatisfy` (\(Just val) -> (goType val) == Player) findObjByType Turret testObjects `shouldSatisfy` (\(Just val) -> (goType val) == Turret) it "returns Nothing when no game object is found" $ do findObjByType TurretProjectile testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findCollisions" $ do it "finds colliding pairs of objects" $ do findCollisions testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 0, testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOf" $ do it "finds objects within a specific range" $ do findWithinRangeOf (testRangedObjects !! 2) 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOfId" $ do it "finds objects within a specific range" $ do findWithinRangeofId 3 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOfPoint" $ do it "finds objects within a specific range" $ do findWithinRangeOfPoint (vector2 5 5) 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.filterObjByType" $ do it "returns no objects when no types specified" $ do filterObjByType [] testObjects `shouldBe` [] it "can filter by single type" $ do filterObjByType [Player] testObjects `shouldSatisfy` (\xs -> (length xs) == 1) it "can filter by multiple types" $ do filterObjByType [Player, Minion] testObjects `shouldSatisfy` (\xs -> (length xs) == 2) describe "Game.Shared.Object.filterObjByTeam" $ do it "can filter by team" $ do filterObjByTeam Neutral testObjects `shouldSatisfy` (\xs -> (length xs) == 1) describe "Game.Shared.Object.sortByDistanceFrom" $ do it "sort objects correctly" $ do sortByDistanceFrom (testRangedObjects !! 0) testRangedObjects `shouldSatisfy` (\(x1:x2:x3:[]) -> x1 == (testRangedObjects !! 0) describe "Game.Shared.Object.sortByDistanceFromPoint" $ do it "sort objects correctly" $ do sortByDistanceFromPoint (zeroVector) testRangedObjects `shouldSatisfy` (\(x1:x2:x3:[]) -> x1 == (testRangedObjects !! 0) describe "Game.Shared.Types.tagMaybe" $ do it "returns NoEvent when no event is used with any value" $ do tagMaybe Yampa.NoEvent Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) tagMaybe Yampa.NoEvent (Just 5) `shouldSatisfy` (isNoEvent :: Num a => Event a -> Bool) it "returns NoEvent when any event is used with Nothing" $ do tagMaybe (Yampa.Event 5) Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) tagMaybe (Yampa.Event True) Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) it "returns an event tagged with the specified value" $ do tagMaybe (Yampa.Event 5) (Just "Hi") `shouldBe` (Yampa.Event "Hi") tagMaybe (Yampa.Event True) (Just 5.5) `shouldBe` (Yampa.Event 5.5) describe "Game.Shared.Types.tagUsing" $ do it "returns NoEvent when no event is used as the input" $ do tagUsing Yampa.NoEvent (+5) `shouldSatisfy` (isNoEvent :: Num a => Event a -> Bool) tagUsing Yampa.NoEvent (++"Hi") `shouldSatisfy` (isNoEvent :: Event String -> Bool) it "transforms an input event by a given function" $ do tagUsing (Yampa.Event 5) (+5) `shouldBe` (Yampa.Event 10) tagUsing (Yampa.Event "Hello") (++", world!") `shouldBe` (Yampa.Event "Hello, world!") describe "Game.Shared.Types.vectorDistance" $ do it "returns distance between two vectors" $ do vectorDistance (vector2 0 0) (vector2 1 1) `shouldBe` (sqrt 2) vectorDistance (vector2 0 0) (vector2 0 1) `shouldBe` 1 vectorDistance (vector2 0 0) (vector2 1 0) `shouldBe` 1 describe "Game.Shared.Types.vectorComponents" $ do it "first value is equal to X" $ do fst (vectorComponents (vector2 1 2)) `shouldBe` 1 it "second value is equal to Y" $ do snd (vectorComponents (vector2 1 2)) `shouldBe` 2 describe "Game.Shared.Types.vectorRoundedComponents" $ do it "rounds values above to x.5 up" $ do vectorRoundedComponents (vector2 0.51 0.51) `shouldBe` (1, 1) it "rounds values below or equal x.5 down" $ do vectorRoundedComponents (vector2 0.5 0.5) `shouldBe` (0, 0) describe "Game.Shared.Types.lerpV" $ do it "returns start value when percent is 0.0" $ do lerpV (vector2 0 0) (vector2 1 1) 0 `shouldBe` (vector2 0 0) it "returns end value when percent is 1.0" $ do lerpV (vector2 0 0) (vector2 1 1) 1 `shouldBe` (vector2 1 1) it "returns half way value when percent is 0.5" $ do lerpV (vector2 0 0) (vector2 1 1) 0.5 `shouldBe` (vector2 0.5 0.5) describe "Game.Shared.Physics.withinRange" $ do it "returns False when outside range" $ do withinRange 0 1 2 `shouldBe` False withinRange 3 1 2 `shouldBe` False it "returns True when within range" $ withinRange 2 1 3 `shouldBe` True it "returns True when equal to upper or lowwer bound" $ do withinRange 1 1 3 `shouldBe` True withinRange 3 1 3 `shouldBe` True
null
https://raw.githubusercontent.com/Mattiemus/LaneWars/4c4a0a11f49cbd9ff722aedf3e0f352e49b140fe/Tests.hs
haskell
module Main where import Test.Hspec import Test.QuickCheck import FRP.Yampa as Yampa import FRP.Yampa.Geometry import Game.Shared.Types import Game.Shared.Physics import Game.Shared.Arrows import Game.Shared.Object import Data.Maybe import Control.Exception (evaluate) testObjects :: [GameObject] testObjects = [basicGameObject { goId = 1, goTeam = Neutral, goType = Player }, basicGameObject { goId = 2, goTeam = Red, goType = Minion }, basicGameObject { goId = 3, goTeam = Red, goType = Turret }] testRangedObjects :: [GameObject] testRangedObjects = [basicGameObject { goId = 1, goPos = vector2 0 0, goSize = vector2 10 10 }, basicGameObject { goId = 2, goPos = vector2 20 20, goSize = vector2 10 5 }, basicGameObject { goId = 3, goPos = vector2 5 5, goSize = vector2 2 2 }] main :: IO () main = hspec $ do describe "Game.Shared.Object.findObjById" $ do it "can find an object by its id" $ do findObjById 1 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 1) findObjById 2 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 2) findObjById 3 testObjects `shouldSatisfy` (\(Just val) -> (goId val) == 3) it "returns Nothing when no game object is found" $ do findObjById 0 testObjects `shouldSatisfy` isNothing findObjById 4 testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findObjByTeam" $ do it "can find an object by its team" $ do findObjByTeam Neutral testObjects `shouldSatisfy` (\(Just val) -> (goTeam val) == Neutral) findObjByTeam Red testObjects `shouldSatisfy` (\(Just val) -> (goTeam val) == Red) it "returns Nothing when no game object is found" $ do findObjByTeam Blue testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findObjByType" $ do it "can find an object by its type" $ do findObjByType Player testObjects `shouldSatisfy` (\(Just val) -> (goType val) == Player) findObjByType Turret testObjects `shouldSatisfy` (\(Just val) -> (goType val) == Turret) it "returns Nothing when no game object is found" $ do findObjByType TurretProjectile testObjects `shouldSatisfy` isNothing describe "Game.Shared.Object.findCollisions" $ do it "finds colliding pairs of objects" $ do findCollisions testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 0, testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOf" $ do it "finds objects within a specific range" $ do findWithinRangeOf (testRangedObjects !! 2) 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOfId" $ do it "finds objects within a specific range" $ do findWithinRangeofId 3 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.findWithinRangeOfPoint" $ do it "finds objects within a specific range" $ do findWithinRangeOfPoint (vector2 5 5) 10 testRangedObjects `shouldSatisfy` (elem (testRangedObjects !! 2)) describe "Game.Shared.Object.filterObjByType" $ do it "returns no objects when no types specified" $ do filterObjByType [] testObjects `shouldBe` [] it "can filter by single type" $ do filterObjByType [Player] testObjects `shouldSatisfy` (\xs -> (length xs) == 1) it "can filter by multiple types" $ do filterObjByType [Player, Minion] testObjects `shouldSatisfy` (\xs -> (length xs) == 2) describe "Game.Shared.Object.filterObjByTeam" $ do it "can filter by team" $ do filterObjByTeam Neutral testObjects `shouldSatisfy` (\xs -> (length xs) == 1) describe "Game.Shared.Object.sortByDistanceFrom" $ do it "sort objects correctly" $ do sortByDistanceFrom (testRangedObjects !! 0) testRangedObjects `shouldSatisfy` (\(x1:x2:x3:[]) -> x1 == (testRangedObjects !! 0) describe "Game.Shared.Object.sortByDistanceFromPoint" $ do it "sort objects correctly" $ do sortByDistanceFromPoint (zeroVector) testRangedObjects `shouldSatisfy` (\(x1:x2:x3:[]) -> x1 == (testRangedObjects !! 0) describe "Game.Shared.Types.tagMaybe" $ do it "returns NoEvent when no event is used with any value" $ do tagMaybe Yampa.NoEvent Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) tagMaybe Yampa.NoEvent (Just 5) `shouldSatisfy` (isNoEvent :: Num a => Event a -> Bool) it "returns NoEvent when any event is used with Nothing" $ do tagMaybe (Yampa.Event 5) Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) tagMaybe (Yampa.Event True) Nothing `shouldSatisfy` (isNoEvent :: Event () -> Bool) it "returns an event tagged with the specified value" $ do tagMaybe (Yampa.Event 5) (Just "Hi") `shouldBe` (Yampa.Event "Hi") tagMaybe (Yampa.Event True) (Just 5.5) `shouldBe` (Yampa.Event 5.5) describe "Game.Shared.Types.tagUsing" $ do it "returns NoEvent when no event is used as the input" $ do tagUsing Yampa.NoEvent (+5) `shouldSatisfy` (isNoEvent :: Num a => Event a -> Bool) tagUsing Yampa.NoEvent (++"Hi") `shouldSatisfy` (isNoEvent :: Event String -> Bool) it "transforms an input event by a given function" $ do tagUsing (Yampa.Event 5) (+5) `shouldBe` (Yampa.Event 10) tagUsing (Yampa.Event "Hello") (++", world!") `shouldBe` (Yampa.Event "Hello, world!") describe "Game.Shared.Types.vectorDistance" $ do it "returns distance between two vectors" $ do vectorDistance (vector2 0 0) (vector2 1 1) `shouldBe` (sqrt 2) vectorDistance (vector2 0 0) (vector2 0 1) `shouldBe` 1 vectorDistance (vector2 0 0) (vector2 1 0) `shouldBe` 1 describe "Game.Shared.Types.vectorComponents" $ do it "first value is equal to X" $ do fst (vectorComponents (vector2 1 2)) `shouldBe` 1 it "second value is equal to Y" $ do snd (vectorComponents (vector2 1 2)) `shouldBe` 2 describe "Game.Shared.Types.vectorRoundedComponents" $ do it "rounds values above to x.5 up" $ do vectorRoundedComponents (vector2 0.51 0.51) `shouldBe` (1, 1) it "rounds values below or equal x.5 down" $ do vectorRoundedComponents (vector2 0.5 0.5) `shouldBe` (0, 0) describe "Game.Shared.Types.lerpV" $ do it "returns start value when percent is 0.0" $ do lerpV (vector2 0 0) (vector2 1 1) 0 `shouldBe` (vector2 0 0) it "returns end value when percent is 1.0" $ do lerpV (vector2 0 0) (vector2 1 1) 1 `shouldBe` (vector2 1 1) it "returns half way value when percent is 0.5" $ do lerpV (vector2 0 0) (vector2 1 1) 0.5 `shouldBe` (vector2 0.5 0.5) describe "Game.Shared.Physics.withinRange" $ do it "returns False when outside range" $ do withinRange 0 1 2 `shouldBe` False withinRange 3 1 2 `shouldBe` False it "returns True when within range" $ withinRange 2 1 3 `shouldBe` True it "returns True when equal to upper or lowwer bound" $ do withinRange 1 1 3 `shouldBe` True withinRange 3 1 3 `shouldBe` True
ee6bd703bf86a6b500adc0367fdb517931f83511b87621a14bea661fc2fc772f
alsonkemp/turbinado
Common.hs
module Turbinado.Database.ORM.Common where import Data.Char import Data.List import qualified Data.Map as M import Database.HDBC import Turbinado.Database.ORM.Types --------------------------------------------------------------------------- -- Utility functions -- --------------------------------------------------------------------------- cols :: Columns -> String cols cs = unwords $ intersperse "," $ map (\s -> "\\\"" ++ s ++ "\\\"") $ M.keys cs columnToFieldLabel :: (String, (SqlColDesc, ForeignKeyReferences, HasDefault)) -> String columnToFieldLabel cd@(name, (desc, _, _)) = " " ++ toFunction name ++ " :: " ++ maybeColumnLabel cd ++ getHaskellTypeString (colType desc) maybeColumnLabel :: (String, (SqlColDesc, ForeignKeyReferences, HasDefault)) -> String maybeColumnLabel (_, (_, _, True)) = "Maybe " -- Does the column have a default maybeColumnLabel (_, (desc, _, _)) = if ((colNullable desc) == Just True) then "Maybe " else "" Derived from hdbc - postgresql / Database / PostgreSQL / Statement.hs and hdbc / Database / HDBC / SqlValue.hs getHaskellTypeString :: SqlTypeId -> String getHaskellTypeString SqlCharT = "String" getHaskellTypeString SqlVarCharT = "String" getHaskellTypeString SqlLongVarCharT = "String" getHaskellTypeString SqlWCharT = "String" getHaskellTypeString SqlWVarCharT = "String" getHaskellTypeString SqlWLongVarCharT = "String" getHaskellTypeString SqlDecimalT = "Rational" getHaskellTypeString SqlNumericT = "Rational" getHaskellTypeString SqlTinyIntT = "Int32" getHaskellTypeString SqlSmallIntT ="Int32" getHaskellTypeString SqlIntegerT = "Int32" getHaskellTypeString SqlBigIntT = "Integer" getHaskellTypeString SqlRealT = "Double" getHaskellTypeString SqlFloatT = "Double" getHaskellTypeString SqlDoubleT = "Double" getHaskellTypeString SqlBitT = "Bool" getHaskellTypeString SqlDateT = "Day" getHaskellTypeString SqlTimestampWithZoneT = "ZonedTime" getHaskellTypeString SqlTimestampT = "UTCTime" getHaskellTypeString SqlUTCDateTimeT = "UTCTime" getHaskellTypeString SqlTimeT = "TimeOfDay" getHaskellTypeString SqlUTCTimeT = "TimeOfDay" getHaskellTypeString SqlTimeWithZoneT = error "Turbinado ORM Generator: SqlTimeWithZoneT is not supported" getHaskellTypeString SqlBinaryT = "B.ByteString" getHaskellTypeString SqlVarBinaryT = "B.ByteString" getHaskellTypeString SqlLongVarBinaryT = "B.ByteString" getHaskellTypeString t = error "Turbinado ORM Generator: Don't know how to translate this SqlTypeId (" ++ show t ++ " to a Haskell Type" | Used for safety . Lowercases the first letter to -- make a valid function. toFunction [] = error "toFunction passed an empty string" toFunction (firstLetter:letters) = (Data.Char.toLower firstLetter) : letters | Used for safety . Uppercases the first letter to -- make a valid type. toType [] = error "toType passed an empty string" toType (firstLetter:letters) = (Data.Char.toUpper firstLetter) : letters
null
https://raw.githubusercontent.com/alsonkemp/turbinado/da2ba7c3443ddf6a51d1ec5b05cb45a85efc0809/Turbinado/Database/ORM/Common.hs
haskell
------------------------------------------------------------------------- Utility functions -- ------------------------------------------------------------------------- Does the column have a default make a valid function. make a valid type.
module Turbinado.Database.ORM.Common where import Data.Char import Data.List import qualified Data.Map as M import Database.HDBC import Turbinado.Database.ORM.Types cols :: Columns -> String cols cs = unwords $ intersperse "," $ map (\s -> "\\\"" ++ s ++ "\\\"") $ M.keys cs columnToFieldLabel :: (String, (SqlColDesc, ForeignKeyReferences, HasDefault)) -> String columnToFieldLabel cd@(name, (desc, _, _)) = " " ++ toFunction name ++ " :: " ++ maybeColumnLabel cd ++ getHaskellTypeString (colType desc) maybeColumnLabel :: (String, (SqlColDesc, ForeignKeyReferences, HasDefault)) -> String maybeColumnLabel (_, (desc, _, _)) = if ((colNullable desc) == Just True) then "Maybe " else "" Derived from hdbc - postgresql / Database / PostgreSQL / Statement.hs and hdbc / Database / HDBC / SqlValue.hs getHaskellTypeString :: SqlTypeId -> String getHaskellTypeString SqlCharT = "String" getHaskellTypeString SqlVarCharT = "String" getHaskellTypeString SqlLongVarCharT = "String" getHaskellTypeString SqlWCharT = "String" getHaskellTypeString SqlWVarCharT = "String" getHaskellTypeString SqlWLongVarCharT = "String" getHaskellTypeString SqlDecimalT = "Rational" getHaskellTypeString SqlNumericT = "Rational" getHaskellTypeString SqlTinyIntT = "Int32" getHaskellTypeString SqlSmallIntT ="Int32" getHaskellTypeString SqlIntegerT = "Int32" getHaskellTypeString SqlBigIntT = "Integer" getHaskellTypeString SqlRealT = "Double" getHaskellTypeString SqlFloatT = "Double" getHaskellTypeString SqlDoubleT = "Double" getHaskellTypeString SqlBitT = "Bool" getHaskellTypeString SqlDateT = "Day" getHaskellTypeString SqlTimestampWithZoneT = "ZonedTime" getHaskellTypeString SqlTimestampT = "UTCTime" getHaskellTypeString SqlUTCDateTimeT = "UTCTime" getHaskellTypeString SqlTimeT = "TimeOfDay" getHaskellTypeString SqlUTCTimeT = "TimeOfDay" getHaskellTypeString SqlTimeWithZoneT = error "Turbinado ORM Generator: SqlTimeWithZoneT is not supported" getHaskellTypeString SqlBinaryT = "B.ByteString" getHaskellTypeString SqlVarBinaryT = "B.ByteString" getHaskellTypeString SqlLongVarBinaryT = "B.ByteString" getHaskellTypeString t = error "Turbinado ORM Generator: Don't know how to translate this SqlTypeId (" ++ show t ++ " to a Haskell Type" | Used for safety . Lowercases the first letter to toFunction [] = error "toFunction passed an empty string" toFunction (firstLetter:letters) = (Data.Char.toLower firstLetter) : letters | Used for safety . Uppercases the first letter to toType [] = error "toType passed an empty string" toType (firstLetter:letters) = (Data.Char.toUpper firstLetter) : letters
6728bbf9b32e1efdb2c5062a6dc5819258ef69264bfeb82b2c4116ff7201d1f2
jrclogic/SMCDEL
Cheryl.hs
module SMCDEL.Examples.Cheryl where import Data.HasCacBDD (Bdd,con,disSet) import Data.List import SMCDEL.Language import SMCDEL.Symbolic.S5 import SMCDEL.Internal.Help (powerset) type Possibility = (Int, String) possibilities :: [Possibility] possibilities = [ (15,"May"), (16,"May"), (19,"May") , (17,"June"), (18,"June") , (14,"July"), (16,"July") , (14,"August"), (15,"August"), (17,"August") ] dayIs :: Int -> Prp dayIs = P monthIs :: String -> Prp monthIs "May" = P 5 monthIs "June" = P 6 monthIs "July" = P 7 monthIs "August" = P 8 monthIs _ = undefined thisPos :: Possibility -> Form thisPos (d,m) = Conj $ (PrpF (dayIs d) : [ Neg (PrpF $ dayIs d') | d' <- nub (map fst possibilities) \\ [d] ]) ++ (PrpF (monthIs m) : [ Neg (PrpF $ monthIs m') | m' <- nub (map snd possibilities) \\ [m] ]) knWhich :: Agent -> Form knWhich i = Disj [ K i (thisPos pos) | pos <- possibilities ] start :: KnowStruct start = KnS allprops statelaw obs where allprops = sort $ nub $ map (dayIs . fst) possibilities ++ map (monthIs . snd) possibilities statelaw = boolBddOf $ Conj [ Disj (map thisPos possibilities) , Conj [ Neg $ Conj [thisPos p1, thisPos p2] | p1 <- possibilities, p2 <- possibilities, p1 /= p2 ] ] obs = [ ("Albert" , nub $ map (monthIs . snd) possibilities) , ("Bernard", nub $ map (dayIs . fst) possibilities) ] round1,round2,round3 :: KnowStruct round1 = update start (Conj [Neg $ knWhich "Albert", K "Albert" $ Neg (knWhich "Bernard")]) round2 = update round1 (knWhich "Bernard") round3 = update round2 (knWhich "Albert") cherylsBirthday :: String cherylsBirthday = m ++ " " ++ show d ++ "th" where [(d,m)] = filter (\(d',m') -> [monthIs m', dayIs d'] `elem` statesOf round3) possibilities newtype Variable = Var [Prp] deriving (Eq,Ord,Show) bitsOf :: Int -> [Int] bitsOf 0 = [] bitsOf n = k : bitsOf (n - 2^k) where k :: Int k = floor (logBase 2 (fromIntegral n) :: Double) -- alternative to: booloutofForm (powerset props !! n) props is :: Variable -> Int -> Form is (Var props) n = Conj [ (if i `elem` bitsOf n then id else Neg) (PrpF k) | (k,i) <- zip props [(0::Int)..] ] isBdd :: Variable -> Int -> Bdd isBdd v = boolBddOf . is v -- inverse of "is": valueIn :: Variable -> State -> Int valueIn (Var props) s = sum [ 2^i | (k,i) <- zip props [(0::Int)..], k `elem` s ] explainState :: [Variable] -> State -> [Int] explainState vs s = map (`valueIn` s) vs -- an agent knows the value iff they know-whether all bits kv :: Agent -> Variable -> Form kv i (Var props) = Conj [ Kw i (PrpF k) | k <- props ] : I have two younger brothers . The product of all our ages is 144 . allStates :: [(Int,Int,Int)] allStates = [ (c,b1,b2) | c <- [1..144] , b1 <- [1..(c-1)] , b2 <- [1..(c-1)] , c * b1 * b2 == 144 ] cheryl, broOne :: Variable cheryl = Var [P (2*k ) | k <- [0..7] ] broOne = Var [P (2*k +1) | k <- [0..7] ] ageKnsStart :: KnowStruct ageKnsStart = KnS allprops statelaw obs where allprops = let (Var cs, Var bs) = (cheryl, broOne) in sort $ cs ++ bs statelaw = disSet [ con (cheryl `isBdd` c) (broOne `isBdd` b) | (c,b,_) <- allStates ] obs = [("albernard",[])] step1,step2,step3,step4,step5 :: KnowStruct : We still do n't know your age . What other hints can you give us ? step1 = ageKnsStart `update` Neg (kv "albernard" cheryl) : The sum of all our ages is the bus number of this bus that we are on . step2 = step1 `update` revealTransformer -- For this we need a way to reveal the sum, hence we use a knowledge transformer revealTransformer :: KnowTransformer revealTransformer = noChange KnTrf addProps addLaw addObs where addProps = map P [1001..1008] -- 8 bits to label all sums addLaw = simplify $ Conj [ Disj [ label (c + b + a) | (c,b,a) <- allStates ] , Conj [ sumIs s `Equi` label s | s <- [1..144] ] ] where label s = booloutofForm (powerset (map P [1001..1008]) !! s) (map P [1001..1008]) sumIs n = Disj [ Conj [ cheryl `is` c, broOne `is` b ] | (c,b,a) <- allStates, c + b + a == n ] addObs = [("albernard",addProps)] -- Bernard: Of course we know the bus number, but we still don't know your age. step3 = step2 `update` Neg (kv "albernard" cheryl) : Oh , I forgot to tell you that my brothers have the same age . step4 = step3 `update` sameAge where sameAge = Disj [ Conj [cheryl `is` c, broOne `is` b ] | (c,b,a) <- allStates , b == a ] and : Oh , now we know your age . step5 = step4 `update` kv "albernard" cheryl
null
https://raw.githubusercontent.com/jrclogic/SMCDEL/10bd5ba2f1f3cc85e4b0f23d5eddbb26f05df5bf/src/SMCDEL/Examples/Cheryl.hs
haskell
alternative to: booloutofForm (powerset props !! n) props inverse of "is": an agent knows the value iff they know-whether all bits For this we need a way to reveal the sum, hence we use a knowledge transformer 8 bits to label all sums Bernard: Of course we know the bus number, but we still don't know your age.
module SMCDEL.Examples.Cheryl where import Data.HasCacBDD (Bdd,con,disSet) import Data.List import SMCDEL.Language import SMCDEL.Symbolic.S5 import SMCDEL.Internal.Help (powerset) type Possibility = (Int, String) possibilities :: [Possibility] possibilities = [ (15,"May"), (16,"May"), (19,"May") , (17,"June"), (18,"June") , (14,"July"), (16,"July") , (14,"August"), (15,"August"), (17,"August") ] dayIs :: Int -> Prp dayIs = P monthIs :: String -> Prp monthIs "May" = P 5 monthIs "June" = P 6 monthIs "July" = P 7 monthIs "August" = P 8 monthIs _ = undefined thisPos :: Possibility -> Form thisPos (d,m) = Conj $ (PrpF (dayIs d) : [ Neg (PrpF $ dayIs d') | d' <- nub (map fst possibilities) \\ [d] ]) ++ (PrpF (monthIs m) : [ Neg (PrpF $ monthIs m') | m' <- nub (map snd possibilities) \\ [m] ]) knWhich :: Agent -> Form knWhich i = Disj [ K i (thisPos pos) | pos <- possibilities ] start :: KnowStruct start = KnS allprops statelaw obs where allprops = sort $ nub $ map (dayIs . fst) possibilities ++ map (monthIs . snd) possibilities statelaw = boolBddOf $ Conj [ Disj (map thisPos possibilities) , Conj [ Neg $ Conj [thisPos p1, thisPos p2] | p1 <- possibilities, p2 <- possibilities, p1 /= p2 ] ] obs = [ ("Albert" , nub $ map (monthIs . snd) possibilities) , ("Bernard", nub $ map (dayIs . fst) possibilities) ] round1,round2,round3 :: KnowStruct round1 = update start (Conj [Neg $ knWhich "Albert", K "Albert" $ Neg (knWhich "Bernard")]) round2 = update round1 (knWhich "Bernard") round3 = update round2 (knWhich "Albert") cherylsBirthday :: String cherylsBirthday = m ++ " " ++ show d ++ "th" where [(d,m)] = filter (\(d',m') -> [monthIs m', dayIs d'] `elem` statesOf round3) possibilities newtype Variable = Var [Prp] deriving (Eq,Ord,Show) bitsOf :: Int -> [Int] bitsOf 0 = [] bitsOf n = k : bitsOf (n - 2^k) where k :: Int k = floor (logBase 2 (fromIntegral n) :: Double) is :: Variable -> Int -> Form is (Var props) n = Conj [ (if i `elem` bitsOf n then id else Neg) (PrpF k) | (k,i) <- zip props [(0::Int)..] ] isBdd :: Variable -> Int -> Bdd isBdd v = boolBddOf . is v valueIn :: Variable -> State -> Int valueIn (Var props) s = sum [ 2^i | (k,i) <- zip props [(0::Int)..], k `elem` s ] explainState :: [Variable] -> State -> [Int] explainState vs s = map (`valueIn` s) vs kv :: Agent -> Variable -> Form kv i (Var props) = Conj [ Kw i (PrpF k) | k <- props ] : I have two younger brothers . The product of all our ages is 144 . allStates :: [(Int,Int,Int)] allStates = [ (c,b1,b2) | c <- [1..144] , b1 <- [1..(c-1)] , b2 <- [1..(c-1)] , c * b1 * b2 == 144 ] cheryl, broOne :: Variable cheryl = Var [P (2*k ) | k <- [0..7] ] broOne = Var [P (2*k +1) | k <- [0..7] ] ageKnsStart :: KnowStruct ageKnsStart = KnS allprops statelaw obs where allprops = let (Var cs, Var bs) = (cheryl, broOne) in sort $ cs ++ bs statelaw = disSet [ con (cheryl `isBdd` c) (broOne `isBdd` b) | (c,b,_) <- allStates ] obs = [("albernard",[])] step1,step2,step3,step4,step5 :: KnowStruct : We still do n't know your age . What other hints can you give us ? step1 = ageKnsStart `update` Neg (kv "albernard" cheryl) : The sum of all our ages is the bus number of this bus that we are on . step2 = step1 `update` revealTransformer revealTransformer :: KnowTransformer revealTransformer = noChange KnTrf addProps addLaw addObs where addLaw = simplify $ Conj [ Disj [ label (c + b + a) | (c,b,a) <- allStates ] , Conj [ sumIs s `Equi` label s | s <- [1..144] ] ] where label s = booloutofForm (powerset (map P [1001..1008]) !! s) (map P [1001..1008]) sumIs n = Disj [ Conj [ cheryl `is` c, broOne `is` b ] | (c,b,a) <- allStates, c + b + a == n ] addObs = [("albernard",addProps)] step3 = step2 `update` Neg (kv "albernard" cheryl) : Oh , I forgot to tell you that my brothers have the same age . step4 = step3 `update` sameAge where sameAge = Disj [ Conj [cheryl `is` c, broOne `is` b ] | (c,b,a) <- allStates , b == a ] and : Oh , now we know your age . step5 = step4 `update` kv "albernard" cheryl
4c7945a31bf8ed1869e7edcd0aa75dcb2878af99da1b970c14da18db7a52f5a8
ragkousism/Guix-on-Hurd
utils.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 , 2013 < > 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 (guix import utils) #:use-module (guix base32) #:use-module ((guix build download) #:prefix build:) #:use-module (guix hash) #:use-module (guix http-client) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix utils) #:use-module (ice-9 match) #:use-module (ice-9 regex) #:use-module (srfi srfi-1) #:export (factorize-uri hash-table->alist flatten assoc-ref* url-fetch guix-hash-url maybe-inputs maybe-native-inputs package->definition spdx-string->license license->symbol snake-case beautify-description)) (define (factorize-uri uri version) "Factorize URI, a package tarball URI as a string, such that any occurrences of the string VERSION is replaced by the symbol 'version." (let ((version-rx (make-regexp (regexp-quote version)))) (match (regexp-exec version-rx uri) (#f uri) (_ (let ((indices (fold-matches version-rx uri '((0)) (lambda (m result) (match result (((start) rest ...) `((,(match:end m)) (,start . ,(match:start m)) ,@rest))))))) (fold (lambda (index result) (match index ((start) (cons (substring uri start) result)) ((start . end) (cons* (substring uri start end) 'version result)))) '() indices)))))) (define (hash-table->alist table) "Return an alist represenation of TABLE." (map (match-lambda ((key . (lst ...)) (cons key (map (lambda (x) (if (hash-table? x) (hash-table->alist x) x)) lst))) ((key . (? hash-table? table)) (cons key (hash-table->alist table))) (pair pair)) (hash-map->list cons table))) (define (flatten lst) "Return a list that recursively concatenates all sub-lists of LST." (fold-right (match-lambda* (((sub-list ...) memo) (append (flatten sub-list) memo)) ((elem memo) (cons elem memo))) '() lst)) (define (assoc-ref* alist key . rest) "Return the value for KEY from ALIST. For each additional key specified, recursively apply the procedure to the sub-list." (if (null? rest) (assoc-ref alist key) (apply assoc-ref* (assoc-ref alist key) rest))) (define (url-fetch url file-name) "Save the contents of URL to FILE-NAME. Return #f on failure." (parameterize ((current-output-port (current-error-port))) (build:url-fetch url file-name))) (define (guix-hash-url filename) "Return the hash of FILENAME in nix-base32 format." (bytevector->nix-base32-string (file-sha256 filename))) (define (spdx-string->license str) "Convert STR, a SPDX formatted license identifier, to a license object. Return #f if STR does not match any known identifiers." ;; / ;; The psfl, gfl1.0, nmap, repoze licenses does n't have SPDX identifiers (match str ("AGPL-1.0" 'license:agpl-1.0) ("AGPL-3.0" 'license:agpl-3.0) ("Apache-1.1" 'license:asl1.1) ("Apache-2.0" 'license:asl2.0) ("BSL-1.0" 'license:boost1.0) ("BSD-2-Clause-FreeBSD" 'license:bsd-2) ("BSD-3-Clause" 'license:bsd-3) ("BSD-4-Clause" 'license:bsd-4) ("CC0-1.0" 'license:cc0) ("CC-BY-2.0" 'license:cc-by2.0) ("CC-BY-3.0" 'license:cc-by3.0) ("CC-BY-SA-2.0" 'license:cc-by-sa2.0) ("CC-BY-SA-3.0" 'license:cc-by-sa3.0) ("CC-BY-SA-4.0" 'license:cc-by-sa4.0) ("CDDL-1.0" 'license:cddl1.0) ("CECILL-C" 'license:cecill-c) ("Artistic-2.0" 'license:artistic2.0) ("ClArtistic" 'license:clarified-artistic) ("CPL-1.0" 'license:cpl1.0) ("EPL-1.0" 'license:epl1.0) ("MIT" 'license:expat) ("FTL" 'license:freetype) ("GFDL-1.1" 'license:fdl1.1+) ("GFDL-1.2" 'license:fdl1.2+) ("GFDL-1.3" 'license:fdl1.3+) ("Giftware" 'license:giftware) ("GPL-1.0" 'license:gpl1) ("GPL-1.0+" 'license:gpl1+) ("GPL-2.0" 'license:gpl2) ("GPL-2.0+" 'license:gpl2+) ("GPL-3.0" 'license:gpl3) ("GPL-3.0+" 'license:gpl3+) ("ISC" 'license:isc) ("IJG" 'license:ijg) ("Imlib2" 'license:imlib2) ("IPA" 'license:ipa) ("IPL-1.0" 'license:ibmpl1.0) ("LGPL-2.0" 'license:lgpl2.0) ("LGPL-2.0+" 'license:lgpl2.0+) ("LGPL-2.1" 'license:lgpl2.1) ("LGPL-2.1+" 'license:lgpl2.1+) ("LGPL-3.0" 'license:lgpl3.0) ("LGPL-3.0+" 'license:lgpl3.0+) ("MPL-1.0" 'license:mpl1.0) ("MPL-1.1" 'license:mpl1.1) ("MPL-2.0" 'license:mpl2.0) ("MS-PL" 'license:ms-pl) ("NCSA" 'license:ncsa) ("OpenSSL" 'license:openssl) ("OLDAP-2.8" 'license:openldap2.8) ("CUA-OPL-1.0" 'license:opl1.0) ("QPL-1.0" 'license:qpl) ("Ruby" 'license:ruby) ("SGI-B-2.0" 'license:sgifreeb2.0) ("OFL-1.1" 'license:silofl1.1) ("Sleepycat" 'license:sleepycat) ("TCL" 'license:tcl/tk) ("Unlicense" 'license:unlicense) ("Vim" 'license:vim) ("X11" 'license:x11) ("ZPL-2.1" 'license:zpl2.1) ("Zlib" 'license:zlib) (_ #f))) (define (license->symbol license) "Convert license to a symbol representing the variable the object is bound to in the (guix licenses) module, or #f if there is no such known license." (define licenses (module-map (lambda (sym var) `(,(variable-ref var) . ,sym)) (resolve-interface '(guix licenses) #:prefix 'license:))) (assoc-ref licenses license)) (define (snake-case str) "Return a downcased version of the string STR where underscores are replaced with dashes." (string-join (string-split (string-downcase str) #\_) "-")) (define (beautify-description description) "Improve the package DESCRIPTION by turning a beginning sentence fragment into a proper sentence and by using two spaces between sentences." (let ((cleaned (if (string-prefix? "A " description) (string-append "This package provides a" (substring description 1)) description))) ;; Use double spacing between sentences (regexp-substitute/global #f "\\. \\b" cleaned 'pre ". " 'post))) (define* (package-names->package-inputs names #:optional (output #f)) (map (lambda (input) (cons* input (list 'unquote (string->symbol input)) (or (and output (list output)) '()))) names)) (define* (maybe-inputs package-names #:optional (output #f)) "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a package definition." (match (package-names->package-inputs package-names output) (() '()) ((package-inputs ...) `((inputs (,'quasiquote ,package-inputs)))))) (define* (maybe-native-inputs package-names #:optional (output #f)) "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a package definition." (match (package-names->package-inputs package-names output) (() '()) ((package-inputs ...) `((native-inputs (,'quasiquote ,package-inputs)))))) (define (package->definition guix-package) (match guix-package (('package ('name (? string? name)) _ ...) `(define-public ,(string->symbol name) ,guix-package))))
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/import/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. / The psfl, gfl1.0, nmap, repoze Use double spacing between sentences
Copyright © 2012 , 2013 < > 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 (guix import utils) #:use-module (guix base32) #:use-module ((guix build download) #:prefix build:) #:use-module (guix hash) #:use-module (guix http-client) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix utils) #:use-module (ice-9 match) #:use-module (ice-9 regex) #:use-module (srfi srfi-1) #:export (factorize-uri hash-table->alist flatten assoc-ref* url-fetch guix-hash-url maybe-inputs maybe-native-inputs package->definition spdx-string->license license->symbol snake-case beautify-description)) (define (factorize-uri uri version) "Factorize URI, a package tarball URI as a string, such that any occurrences of the string VERSION is replaced by the symbol 'version." (let ((version-rx (make-regexp (regexp-quote version)))) (match (regexp-exec version-rx uri) (#f uri) (_ (let ((indices (fold-matches version-rx uri '((0)) (lambda (m result) (match result (((start) rest ...) `((,(match:end m)) (,start . ,(match:start m)) ,@rest))))))) (fold (lambda (index result) (match index ((start) (cons (substring uri start) result)) ((start . end) (cons* (substring uri start end) 'version result)))) '() indices)))))) (define (hash-table->alist table) "Return an alist represenation of TABLE." (map (match-lambda ((key . (lst ...)) (cons key (map (lambda (x) (if (hash-table? x) (hash-table->alist x) x)) lst))) ((key . (? hash-table? table)) (cons key (hash-table->alist table))) (pair pair)) (hash-map->list cons table))) (define (flatten lst) "Return a list that recursively concatenates all sub-lists of LST." (fold-right (match-lambda* (((sub-list ...) memo) (append (flatten sub-list) memo)) ((elem memo) (cons elem memo))) '() lst)) (define (assoc-ref* alist key . rest) "Return the value for KEY from ALIST. For each additional key specified, recursively apply the procedure to the sub-list." (if (null? rest) (assoc-ref alist key) (apply assoc-ref* (assoc-ref alist key) rest))) (define (url-fetch url file-name) "Save the contents of URL to FILE-NAME. Return #f on failure." (parameterize ((current-output-port (current-error-port))) (build:url-fetch url file-name))) (define (guix-hash-url filename) "Return the hash of FILENAME in nix-base32 format." (bytevector->nix-base32-string (file-sha256 filename))) (define (spdx-string->license str) "Convert STR, a SPDX formatted license identifier, to a license object. Return #f if STR does not match any known identifiers." licenses does n't have SPDX identifiers (match str ("AGPL-1.0" 'license:agpl-1.0) ("AGPL-3.0" 'license:agpl-3.0) ("Apache-1.1" 'license:asl1.1) ("Apache-2.0" 'license:asl2.0) ("BSL-1.0" 'license:boost1.0) ("BSD-2-Clause-FreeBSD" 'license:bsd-2) ("BSD-3-Clause" 'license:bsd-3) ("BSD-4-Clause" 'license:bsd-4) ("CC0-1.0" 'license:cc0) ("CC-BY-2.0" 'license:cc-by2.0) ("CC-BY-3.0" 'license:cc-by3.0) ("CC-BY-SA-2.0" 'license:cc-by-sa2.0) ("CC-BY-SA-3.0" 'license:cc-by-sa3.0) ("CC-BY-SA-4.0" 'license:cc-by-sa4.0) ("CDDL-1.0" 'license:cddl1.0) ("CECILL-C" 'license:cecill-c) ("Artistic-2.0" 'license:artistic2.0) ("ClArtistic" 'license:clarified-artistic) ("CPL-1.0" 'license:cpl1.0) ("EPL-1.0" 'license:epl1.0) ("MIT" 'license:expat) ("FTL" 'license:freetype) ("GFDL-1.1" 'license:fdl1.1+) ("GFDL-1.2" 'license:fdl1.2+) ("GFDL-1.3" 'license:fdl1.3+) ("Giftware" 'license:giftware) ("GPL-1.0" 'license:gpl1) ("GPL-1.0+" 'license:gpl1+) ("GPL-2.0" 'license:gpl2) ("GPL-2.0+" 'license:gpl2+) ("GPL-3.0" 'license:gpl3) ("GPL-3.0+" 'license:gpl3+) ("ISC" 'license:isc) ("IJG" 'license:ijg) ("Imlib2" 'license:imlib2) ("IPA" 'license:ipa) ("IPL-1.0" 'license:ibmpl1.0) ("LGPL-2.0" 'license:lgpl2.0) ("LGPL-2.0+" 'license:lgpl2.0+) ("LGPL-2.1" 'license:lgpl2.1) ("LGPL-2.1+" 'license:lgpl2.1+) ("LGPL-3.0" 'license:lgpl3.0) ("LGPL-3.0+" 'license:lgpl3.0+) ("MPL-1.0" 'license:mpl1.0) ("MPL-1.1" 'license:mpl1.1) ("MPL-2.0" 'license:mpl2.0) ("MS-PL" 'license:ms-pl) ("NCSA" 'license:ncsa) ("OpenSSL" 'license:openssl) ("OLDAP-2.8" 'license:openldap2.8) ("CUA-OPL-1.0" 'license:opl1.0) ("QPL-1.0" 'license:qpl) ("Ruby" 'license:ruby) ("SGI-B-2.0" 'license:sgifreeb2.0) ("OFL-1.1" 'license:silofl1.1) ("Sleepycat" 'license:sleepycat) ("TCL" 'license:tcl/tk) ("Unlicense" 'license:unlicense) ("Vim" 'license:vim) ("X11" 'license:x11) ("ZPL-2.1" 'license:zpl2.1) ("Zlib" 'license:zlib) (_ #f))) (define (license->symbol license) "Convert license to a symbol representing the variable the object is bound to in the (guix licenses) module, or #f if there is no such known license." (define licenses (module-map (lambda (sym var) `(,(variable-ref var) . ,sym)) (resolve-interface '(guix licenses) #:prefix 'license:))) (assoc-ref licenses license)) (define (snake-case str) "Return a downcased version of the string STR where underscores are replaced with dashes." (string-join (string-split (string-downcase str) #\_) "-")) (define (beautify-description description) "Improve the package DESCRIPTION by turning a beginning sentence fragment into a proper sentence and by using two spaces between sentences." (let ((cleaned (if (string-prefix? "A " description) (string-append "This package provides a" (substring description 1)) description))) (regexp-substitute/global #f "\\. \\b" cleaned 'pre ". " 'post))) (define* (package-names->package-inputs names #:optional (output #f)) (map (lambda (input) (cons* input (list 'unquote (string->symbol input)) (or (and output (list output)) '()))) names)) (define* (maybe-inputs package-names #:optional (output #f)) "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a package definition." (match (package-names->package-inputs package-names output) (() '()) ((package-inputs ...) `((inputs (,'quasiquote ,package-inputs)))))) (define* (maybe-native-inputs package-names #:optional (output #f)) "Given a list of PACKAGE-NAMES, tries to generate the 'inputs' field of a package definition." (match (package-names->package-inputs package-names output) (() '()) ((package-inputs ...) `((native-inputs (,'quasiquote ,package-inputs)))))) (define (package->definition guix-package) (match guix-package (('package ('name (? string? name)) _ ...) `(define-public ,(string->symbol name) ,guix-package))))
8cf1a680c9be55f3e1742860f1ce501052d0fb9785fa378efaf19f6406d3f502
jeromesimeon/Galax
code_util_materialize.mli
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : code_util_materialize.mli , v 1.8 2007/02/01 22:08:45 simeon Exp $ Module : Code_util_materialize Description : This module contains code to handle the materialization of tuple cursors into an array of physical xml value arrays ( the individual tuples ) Additionally it returns a function which stores one of these tuples without names into the " current " tuple slot destructively . Description: This module contains code to handle the materialization of tuple cursors into an array of physical xml value arrays (the individual tuples) Additionally it returns a function which stores one of these tuples without names into the "current" tuple slot destructively. *) open Xquery_common_ast open Physical_value type sequence_index = int type restore_function = dom_tuple -> unit * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Simple exporting(importing ) of the INPUT tuple to / from a tuple cursor Used in serialization of a table . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Simple exporting(importing) of the INPUT tuple to/from a tuple cursor Used in serialization of a table. *******************************************) (* Currently, export_input_tuple_as_tuple_cursor materializes in horizontal dimension *) val export_input_tuple_as_tuple_cursor : Code_selection_context.code_selection_context -> Xquery_physical_type_ast.physical_tuple_type -> Physical_value.tuple_unit Cursor.cursor -> Physical_value.tuple Cursor.cursor val import_tuple_cursor_as_input_tuple : Code_selection_context.code_selection_context -> Xquery_physical_type_ast.physical_tuple_type -> Physical_value.tuple Cursor.cursor -> Physical_value.tuple_unit Cursor.cursor type array_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> tuple_unit Cursor.cursor -> dom_table (* Get back the array of tuples *) val materialize_cursor_to_dom_value_array : (* Code selection context is needed to get the "needed names" or the tuple field names which are returned as the last portion of the triplet *) Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> unit -> array_materialize_fun * restore_function * cvname array Materialize to a hash table , which maps items ( computed by the provided expression ) - > their sequence number can also be used for just mem if not in doc_order provided expression) -> their sequence number can also be used for just mem if not in doc_order*) type hash_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> dom_table -> int Dm_atomic.AtomicValueHash.t val materialize_array_to_hash : Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> restore_function (* for the array *) -> (Code_util_predicates.predicate_branch * Namespace_context.nsenv) -> hash_materialize_fun * restore_function * cvname array (* Sorted materialization functions *) type sort_array_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> dom_table -> Code_util_ridlist.rid Dm_atomic_btree.btree (* in sorted order *) (* Get back the array of tuples *) val materialize_array_to_sorted_array_index : (* Code selection context is needed to get the "needed names" or the tuple field names which are returned as the last portion of the triplet *) Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> restore_function (* for the array *) -> (Code_util_predicates.predicate_branch * Namespace_context.nsenv) -> sort_array_materialize_fun (* Materializes a cursor. Used when materialization is needed in a statement with side effects *) val build_materialize_table_code : ('a, 'b) Xquery_algebra_ast.aalgop_expr -> Code_selection_context.code_selection_context -> Algebra_type.eval_fun -> (Execution_context.algebra_context -> tuple_unit Cursor.cursor -> tuple_unit Cursor.cursor) (* The decision concerning materialization is stored in annotations that need to be computed beforehand *) val annotate_materialization : Code_selection_context.code_selection_context -> Algebra_type.algop_expr -> unit val should_materialize : Algebra_type.algop_expr -> bool val produces_a_table : Algebra_type.algop_expr -> bool
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/code_selection/code/code_util_materialize.mli
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* Currently, export_input_tuple_as_tuple_cursor materializes in horizontal dimension Get back the array of tuples Code selection context is needed to get the "needed names" or the tuple field names which are returned as the last portion of the triplet for the array Sorted materialization functions in sorted order Get back the array of tuples Code selection context is needed to get the "needed names" or the tuple field names which are returned as the last portion of the triplet for the array Materializes a cursor. Used when materialization is needed in a statement with side effects The decision concerning materialization is stored in annotations that need to be computed beforehand
Copyright 2001 - 2007 . $ I d : code_util_materialize.mli , v 1.8 2007/02/01 22:08:45 simeon Exp $ Module : Code_util_materialize Description : This module contains code to handle the materialization of tuple cursors into an array of physical xml value arrays ( the individual tuples ) Additionally it returns a function which stores one of these tuples without names into the " current " tuple slot destructively . Description: This module contains code to handle the materialization of tuple cursors into an array of physical xml value arrays (the individual tuples) Additionally it returns a function which stores one of these tuples without names into the "current" tuple slot destructively. *) open Xquery_common_ast open Physical_value type sequence_index = int type restore_function = dom_tuple -> unit * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Simple exporting(importing ) of the INPUT tuple to / from a tuple cursor Used in serialization of a table . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Simple exporting(importing) of the INPUT tuple to/from a tuple cursor Used in serialization of a table. *******************************************) val export_input_tuple_as_tuple_cursor : Code_selection_context.code_selection_context -> Xquery_physical_type_ast.physical_tuple_type -> Physical_value.tuple_unit Cursor.cursor -> Physical_value.tuple Cursor.cursor val import_tuple_cursor_as_input_tuple : Code_selection_context.code_selection_context -> Xquery_physical_type_ast.physical_tuple_type -> Physical_value.tuple Cursor.cursor -> Physical_value.tuple_unit Cursor.cursor type array_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> tuple_unit Cursor.cursor -> dom_table val materialize_cursor_to_dom_value_array : Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> unit -> array_materialize_fun * restore_function * cvname array Materialize to a hash table , which maps items ( computed by the provided expression ) - > their sequence number can also be used for just mem if not in doc_order provided expression) -> their sequence number can also be used for just mem if not in doc_order*) type hash_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> dom_table -> int Dm_atomic.AtomicValueHash.t val materialize_array_to_hash : Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> (Code_util_predicates.predicate_branch * Namespace_context.nsenv) -> hash_materialize_fun * restore_function * cvname array type sort_array_materialize_fun = Algebra_type.eval_fun -> Execution_context.algebra_context -> dom_table val materialize_array_to_sorted_array_index : Code_selection_context.code_selection_context -> Xquery_algebra_ast.free_variable_desc -> (Code_util_predicates.predicate_branch * Namespace_context.nsenv) -> sort_array_materialize_fun val build_materialize_table_code : ('a, 'b) Xquery_algebra_ast.aalgop_expr -> Code_selection_context.code_selection_context -> Algebra_type.eval_fun -> (Execution_context.algebra_context -> tuple_unit Cursor.cursor -> tuple_unit Cursor.cursor) val annotate_materialization : Code_selection_context.code_selection_context -> Algebra_type.algop_expr -> unit val should_materialize : Algebra_type.algop_expr -> bool val produces_a_table : Algebra_type.algop_expr -> bool
c2ccf11126e497d0c5a7c4e49e1040f58dc27410b216d9ede81b3e8d14a9cce3
manuel-serrano/bigloo
apply.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / / comptime / Coerce / apply.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Fri Jan 20 17:21:26 1995 * / * Last change : Thu Jul 8 11:28:29 2021 ( serrano ) * / * Copyright : 1995 - 2021 , see LICENSE file * / ;* ------------------------------------------------------------- */ ;* The `apply' coercion */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module coerce_apply (include "Tools/trace.sch" "Tools/location.sch") (import engine_param backend_backend tools_shape tools_location tools_error type_type type_cache ast_var ast_node ast_sexp ast_local ast_lvtype coerce_coerce coerce_convert)) ;*---------------------------------------------------------------------*/ ;* coerce! ::app-ly ... */ ;*---------------------------------------------------------------------*/ (define-method (coerce! node::app-ly caller to safe) (trace coerce "coerce-apply!: " (shape node) #\Newline) (let ((error-msg (list 'quote (shape node)))) ;; we coerce the arguments (app-ly-arg-set! node (coerce! (app-ly-arg node) caller *obj* safe)) ;; we coerce the procedure (let ((c-fun (coerce! (app-ly-fun node) caller *procedure* safe))) ;; we check arity (if *unsafe-arity* (begin (if (var? c-fun) (begin (app-ly-fun-set! node c-fun) (convert! node *obj* to safe)) (let ((fun (make-local-svar 'fun *procedure*))) (app-ly-fun-set! node (instantiate::ref (loc (node-loc c-fun)) (type *procedure*) (variable fun))) (instantiate::let-var (loc (node-loc node)) (type (strict-node-type to (node-type node))) (bindings (list (cons fun c-fun))) (body (convert! node *obj* to safe)))))) (let* ((fun (make-local-svar 'fun *procedure*)) (val (make-local-svar 'val *pair-nil*)) (loc (node-loc node)) (lval (lvtype-node (top-level-sexp->node `(length ,val) loc))) (len (gensym 'len)) (body (lvtype-node (top-level-sexp->node `(let ((,(symbol-append len '::int) ,(coerce! lval caller *int* safe))) (if (correct-arity? ,fun ,len) ,(convert! node *obj* to safe) ,(make-error-node error-msg loc caller to))) loc))) (lnode (instantiate::let-var (loc loc) (type (strict-node-type (node-type body) *obj*)) (bindings (list (cons fun c-fun) (cons val (app-ly-arg node)))) (body body)))) ;; we set the new apply value (app-ly-fun-set! node (instantiate::ref (loc loc) (type *procedure*) (variable fun))) (app-ly-arg-set! node (instantiate::ref (loc loc) (type (strict-node-type (variable-type val) *obj*)) (variable val))) lnode))))) ;*---------------------------------------------------------------------*/ ;* make-error-node ... */ ;*---------------------------------------------------------------------*/ (define (make-error-node error-msg loc caller to) (let ((node (top-level-sexp->node (if (and (or (and (>fx *bdb-debug* 0) (memq 'bdb (backend-debug-support (the-backend)))) (>fx *compiler-debug* 0)) (location? loc)) `(begin ((@ error/location __error) ,(list 'quote (current-function)) "Wrong number of arguments" ,error-msg ,(location-full-fname loc) ,(location-pos loc)) (failure '_ '_ '_)) `(failure ,(list 'quote (current-function)) "Wrong number of arguments" ,error-msg)) loc))) (coerce! node caller to #f)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/fdeac39af72d5119d01818815b0f395f2907d6da/comptime/Coerce/apply.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The `apply' coercion */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * coerce! ::app-ly ... */ *---------------------------------------------------------------------*/ we coerce the arguments we coerce the procedure we check arity we set the new apply value *---------------------------------------------------------------------*/ * make-error-node ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / / comptime / Coerce / apply.scm * / * Author : * / * Creation : Fri Jan 20 17:21:26 1995 * / * Last change : Thu Jul 8 11:28:29 2021 ( serrano ) * / * Copyright : 1995 - 2021 , see LICENSE file * / (module coerce_apply (include "Tools/trace.sch" "Tools/location.sch") (import engine_param backend_backend tools_shape tools_location tools_error type_type type_cache ast_var ast_node ast_sexp ast_local ast_lvtype coerce_coerce coerce_convert)) (define-method (coerce! node::app-ly caller to safe) (trace coerce "coerce-apply!: " (shape node) #\Newline) (let ((error-msg (list 'quote (shape node)))) (app-ly-arg-set! node (coerce! (app-ly-arg node) caller *obj* safe)) (let ((c-fun (coerce! (app-ly-fun node) caller *procedure* safe))) (if *unsafe-arity* (begin (if (var? c-fun) (begin (app-ly-fun-set! node c-fun) (convert! node *obj* to safe)) (let ((fun (make-local-svar 'fun *procedure*))) (app-ly-fun-set! node (instantiate::ref (loc (node-loc c-fun)) (type *procedure*) (variable fun))) (instantiate::let-var (loc (node-loc node)) (type (strict-node-type to (node-type node))) (bindings (list (cons fun c-fun))) (body (convert! node *obj* to safe)))))) (let* ((fun (make-local-svar 'fun *procedure*)) (val (make-local-svar 'val *pair-nil*)) (loc (node-loc node)) (lval (lvtype-node (top-level-sexp->node `(length ,val) loc))) (len (gensym 'len)) (body (lvtype-node (top-level-sexp->node `(let ((,(symbol-append len '::int) ,(coerce! lval caller *int* safe))) (if (correct-arity? ,fun ,len) ,(convert! node *obj* to safe) ,(make-error-node error-msg loc caller to))) loc))) (lnode (instantiate::let-var (loc loc) (type (strict-node-type (node-type body) *obj*)) (bindings (list (cons fun c-fun) (cons val (app-ly-arg node)))) (body body)))) (app-ly-fun-set! node (instantiate::ref (loc loc) (type *procedure*) (variable fun))) (app-ly-arg-set! node (instantiate::ref (loc loc) (type (strict-node-type (variable-type val) *obj*)) (variable val))) lnode))))) (define (make-error-node error-msg loc caller to) (let ((node (top-level-sexp->node (if (and (or (and (>fx *bdb-debug* 0) (memq 'bdb (backend-debug-support (the-backend)))) (>fx *compiler-debug* 0)) (location? loc)) `(begin ((@ error/location __error) ,(list 'quote (current-function)) "Wrong number of arguments" ,error-msg ,(location-full-fname loc) ,(location-pos loc)) (failure '_ '_ '_)) `(failure ,(list 'quote (current-function)) "Wrong number of arguments" ,error-msg)) loc))) (coerce! node caller to #f)))
4bb6c69da9985c54cd28c4280740a4c6f4196b3fa4d481a1bced563da3af2aee
startalkIM/ejabberd
scram.erl
%%%---------------------------------------------------------------------- File : scram.erl Author : < > Purpose : SCRAM ( RFC 5802 ) Created : 7 Aug 2011 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%---------------------------------------------------------------------- -module(scram). -author(''). %% External exports ejabberd does n't implement SASLPREP , so we use the similar RESOURCEPREP instead -export([salted_password/3, stored_key/1, server_key/1, server_signature/2, client_signature/2, client_key/1, client_key/2]). -spec salted_password(binary(), binary(), non_neg_integer()) -> binary(). salted_password(Password, Salt, IterationCount) -> hi(jid:resourceprep(Password), Salt, IterationCount). -spec client_key(binary()) -> binary(). client_key(SaltedPassword) -> sha_mac(SaltedPassword, <<"Client Key">>). -spec stored_key(binary()) -> binary(). stored_key(ClientKey) -> p1_sha:sha1(ClientKey). -spec server_key(binary()) -> binary(). server_key(SaltedPassword) -> sha_mac(SaltedPassword, <<"Server Key">>). -spec client_signature(binary(), binary()) -> binary(). client_signature(StoredKey, AuthMessage) -> sha_mac(StoredKey, AuthMessage). -spec client_key(binary(), binary()) -> binary(). client_key(ClientProof, ClientSignature) -> list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(ClientProof), binary_to_list(ClientSignature))). -spec server_signature(binary(), binary()) -> binary(). server_signature(ServerKey, AuthMessage) -> sha_mac(ServerKey, AuthMessage). hi(Password, Salt, IterationCount) -> U1 = sha_mac(Password, <<Salt/binary, 0, 0, 0, 1>>), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U1), binary_to_list(hi_round(Password, U1, IterationCount - 1)))). hi_round(Password, UPrev, 1) -> sha_mac(Password, UPrev); hi_round(Password, UPrev, IterationCount) -> U = sha_mac(Password, UPrev), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U), binary_to_list(hi_round(Password, U, IterationCount - 1)))). sha_mac(Key, Data) -> crypto:hmac(sha, Key, Data).
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/scram.erl
erlang
---------------------------------------------------------------------- This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ---------------------------------------------------------------------- External exports
File : scram.erl Author : < > Purpose : SCRAM ( RFC 5802 ) Created : 7 Aug 2011 by < > ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(scram). -author(''). ejabberd does n't implement SASLPREP , so we use the similar RESOURCEPREP instead -export([salted_password/3, stored_key/1, server_key/1, server_signature/2, client_signature/2, client_key/1, client_key/2]). -spec salted_password(binary(), binary(), non_neg_integer()) -> binary(). salted_password(Password, Salt, IterationCount) -> hi(jid:resourceprep(Password), Salt, IterationCount). -spec client_key(binary()) -> binary(). client_key(SaltedPassword) -> sha_mac(SaltedPassword, <<"Client Key">>). -spec stored_key(binary()) -> binary(). stored_key(ClientKey) -> p1_sha:sha1(ClientKey). -spec server_key(binary()) -> binary(). server_key(SaltedPassword) -> sha_mac(SaltedPassword, <<"Server Key">>). -spec client_signature(binary(), binary()) -> binary(). client_signature(StoredKey, AuthMessage) -> sha_mac(StoredKey, AuthMessage). -spec client_key(binary(), binary()) -> binary(). client_key(ClientProof, ClientSignature) -> list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(ClientProof), binary_to_list(ClientSignature))). -spec server_signature(binary(), binary()) -> binary(). server_signature(ServerKey, AuthMessage) -> sha_mac(ServerKey, AuthMessage). hi(Password, Salt, IterationCount) -> U1 = sha_mac(Password, <<Salt/binary, 0, 0, 0, 1>>), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U1), binary_to_list(hi_round(Password, U1, IterationCount - 1)))). hi_round(Password, UPrev, 1) -> sha_mac(Password, UPrev); hi_round(Password, UPrev, IterationCount) -> U = sha_mac(Password, UPrev), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U), binary_to_list(hi_round(Password, U, IterationCount - 1)))). sha_mac(Key, Data) -> crypto:hmac(sha, Key, Data).
e59db8f1e1e4616fe690da3e7a46b2424b5800db83e16393a13c7a3aae0a0f97
facebook/duckling
Tests.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Duration.FR.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Duration.FR.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "FR Tests" [ makeCorpusTest [Seal Duration] corpus , makeNegativeCorpusTest [Seal Duration] negativeCorpus ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Duration/FR/Tests.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Duration.FR.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Duration.FR.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "FR Tests" [ makeCorpusTest [Seal Duration] corpus , makeNegativeCorpusTest [Seal Duration] negativeCorpus ]
f349ad056a1d426151d0eff73361454b161cf84623c6d7749adf2a98785fe6d0
kalxd/azelf
json.rkt
#lang racket/base (require racket/generic racket/contract (only-in racket/function identity) (prefix-in base:: racket/base) json) (provide gen:ToJSON ToJSON? ->json json->string json->byte) (define (json-number? x) (or (exact-integer? x) (and (inexact-real? x) (rational? x)))) (define (json-nil? x) (eq? (json-null) x)) (define-generics ToJSON (->json ToJSON) #:defaults ([string? (define ->json identity)] [boolean? (define ->json identity)] [json-number? (define ->json identity)] [json-nil? (define ->json identity)] [list? (define/generic self/to-json ->json) (define/contract (->json xs) (-> (listof ToJSON?) (listof jsexpr?)) (map self/to-json xs))] [hash? (define/generic self/to-json ->json) (define/contract (->json o) (-> (hash/c symbol? ToJSON?) (hash/c symbol? jsexpr?)) (for/hash ([(k v) o]) (values k (self/to-json v))))])) (define/contract json->string (-> ToJSON? string?) (compose jsexpr->string ->json)) (define/contract json->byte (-> ToJSON? bytes?) (compose jsexpr->bytes ->json))
null
https://raw.githubusercontent.com/kalxd/azelf/e078bae30ef695265d1e94c04160916f0ff99652/type/json.rkt
racket
#lang racket/base (require racket/generic racket/contract (only-in racket/function identity) (prefix-in base:: racket/base) json) (provide gen:ToJSON ToJSON? ->json json->string json->byte) (define (json-number? x) (or (exact-integer? x) (and (inexact-real? x) (rational? x)))) (define (json-nil? x) (eq? (json-null) x)) (define-generics ToJSON (->json ToJSON) #:defaults ([string? (define ->json identity)] [boolean? (define ->json identity)] [json-number? (define ->json identity)] [json-nil? (define ->json identity)] [list? (define/generic self/to-json ->json) (define/contract (->json xs) (-> (listof ToJSON?) (listof jsexpr?)) (map self/to-json xs))] [hash? (define/generic self/to-json ->json) (define/contract (->json o) (-> (hash/c symbol? ToJSON?) (hash/c symbol? jsexpr?)) (for/hash ([(k v) o]) (values k (self/to-json v))))])) (define/contract json->string (-> ToJSON? string?) (compose jsexpr->string ->json)) (define/contract json->byte (-> ToJSON? bytes?) (compose jsexpr->bytes ->json))
c5839061f6b71019ac50ff2b58dec13574e55f370c05820496a8141f3e617658
ragkousism/Guix-on-Hurd
graph.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 , 2016 , 2017 < > ;;; ;;; 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 (guix scripts graph) #:use-module (guix ui) #:use-module (guix graph) #:use-module (guix grafts) #:use-module (guix scripts) #:use-module (guix packages) #:use-module (guix monads) #:use-module (guix store) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix memoization) #:use-module ((guix build-system gnu) #:select (standard-packages)) #:use-module (gnu packages) #:use-module (guix sets) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (srfi srfi-34) #:use-module (srfi srfi-35) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:export (%package-node-type %reverse-package-node-type %bag-node-type %bag-with-origins-node-type %bag-emerged-node-type %derivation-node-type %reference-node-type %referrer-node-type %node-types guix-graph)) ;;; ;;; Package DAG. ;;; (define (node-full-name thing) "Return a human-readable name to denote THING, a package, origin, or file name." (cond ((package? thing) (package-full-name thing)) ((origin? thing) (origin-actual-file-name thing)) ((string? thing) ;file name (or (basename thing) (error "basename" thing))) (else (number->string (object-address thing) 16)))) (define (package-node-edges package) "Return the list of dependencies of PACKAGE." (match (package-direct-inputs package) (((labels packages . outputs) ...) ;; Filter out origins and other non-package dependencies. (filter package? packages)))) (define assert-package (match-lambda ((? package? package) package) (x (raise (condition (&message (message (format #f (_ "~a: invalid argument (package name expected)") x)))))))) (define nodes-from-package ;; The default conversion method. (lift1 (compose list assert-package) %store-monad)) (define %package-node-type ;; Type for the traversal of package nodes. (node-type (name "package") (description "the DAG of packages, excluding implicit inputs") (convert nodes-from-package) ;; We use package addresses as unique identifiers. This generally works well , but for generated package objects , we could end up with two ;; packages that are not 'eq?', yet map to the same derivation (XXX). (identifier (lift1 object-address %store-monad)) (label node-full-name) (edges (lift1 package-node-edges %store-monad)))) ;;; Reverse package DAG . ;;; (define %reverse-package-node-type For this node type we first need to compute the list of packages and the ;; list of back-edges. Since we want to do it only once, we use the ;; promises below. (let* ((packages (delay (fold-packages cons '()))) (back-edges (delay (run-with-store #f ;store not actually needed (node-back-edges %package-node-type (force packages)))))) (node-type (inherit %package-node-type) (name "reverse-package") (description "the reverse DAG of packages") (edges (lift1 (force back-edges) %store-monad))))) ;;; ;;; Package DAG using bags. ;;; (define (bag-node-identifier thing) "Return a unique identifier for THING, which may be a package, origin, or a file name." ;; If THING is a file name (a string), we just return it; if it's a package ;; or origin, we return its address. That gives us the object graph, but ;; that may differ from the derivation graph (for instance, ;; 'package-with-bootstrap-guile' generates fresh package objects, and ;; several packages that are not 'eq?' may actually map to the same ;; derivation.) Thus, we lower THING and use its derivation file name as a ;; unique identifier. (with-monad %store-monad (if (string? thing) (return thing) (mlet %store-monad ((low (lower-object thing))) (return (if (derivation? low) (derivation-file-name low) low)))))) (define (bag-node-edges thing) "Return the list of dependencies of THING, a package or origin. Dependencies may include packages, origin, and file names." (cond ((package? thing) (match (bag-direct-inputs (package->bag thing)) (((labels things . outputs) ...) things))) ((origin? thing) (cons (or (origin-patch-guile thing) (default-guile)) (if (or (pair? (origin-patches thing)) (origin-snippet thing)) (match (origin-patch-inputs thing) (#f '()) (((labels dependencies _ ...) ...) (delete-duplicates dependencies eq?))) '()))) (else '()))) (define %bag-node-type ;; Type for the traversal of package nodes via the "bag" representation, ;; which includes implicit inputs. (node-type (name "bag") (description "the DAG of packages, including implicit inputs") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (compose (cut filter package? <>) bag-node-edges) %store-monad)))) (define %bag-with-origins-node-type (node-type (name "bag-with-origins") (description "the DAG of packages and origins, including implicit inputs") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (lambda (thing) (filter (match-lambda ((? package?) #t) ((? origin?) #t) (_ #f)) (bag-node-edges thing))) %store-monad)))) (define standard-package-set (mlambda () "Return the set of standard packages provided by GNU-BUILD-SYSTEM." (match (standard-packages) (((labels packages . output) ...) (list->setq packages))))) (define (bag-node-edges-sans-bootstrap thing) "Like 'bag-node-edges', but pretend that the standard packages of GNU-BUILD-SYSTEM have zero dependencies." (if (set-contains? (standard-package-set) thing) '() (bag-node-edges thing))) (define %bag-emerged-node-type Like % BAG - NODE - TYPE , but without the bootstrap subset of the DAG . (node-type (name "bag-emerged") (description "same as 'bag', but without the bootstrap nodes") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (compose (cut filter package? <>) bag-node-edges-sans-bootstrap) %store-monad)))) ;;; Derivation DAG . ;;; (define (file->derivation file) "Read the derivation from FILE and return it." (call-with-input-file file read-derivation)) (define (derivation-dependencies obj) "Return the <derivation> objects and store items corresponding to the dependencies of OBJ, a <derivation> or store item." (if (derivation? obj) (append (map (compose file->derivation derivation-input-path) (derivation-inputs obj)) (derivation-sources obj)) '())) (define (derivation-node-identifier node) "Return a unique identifier for NODE, which may be either a <derivation> or a plain store file." (if (derivation? node) (derivation-file-name node) node)) (define (derivation-node-label node) "Return a label for NODE, a <derivation> object or plain store item." (store-path-package-name (match node ((? derivation? drv) (derivation-file-name drv)) ((? string? file) file)))) (define %derivation-node-type DAG of derivations . Very accurate , very detailed , but usually too much ;; detailed. (node-type (name "derivation") (description "the DAG of derivations") (convert (match-lambda ((? package? package) (with-monad %store-monad (>>= (package->derivation package) (lift1 list %store-monad)))) ((? derivation-path? item) (mbegin %store-monad ((store-lift add-temp-root) item) (return (list (file->derivation item))))) (x (raise (condition (&message (message "unsupported argument for \ derivation graph"))))))) (identifier (lift1 derivation-node-identifier %store-monad)) (label derivation-node-label) (edges (lift1 derivation-dependencies %store-monad)))) ;;; DAG of residual references ( aka . run - time dependencies ) . ;;; (define ensure-store-items ;; Return a list of store items as a monadic value based on the given ;; argument, which may be a store item or a package. (match-lambda ((? package? package) ;; Return the output file names of PACKAGE. (mlet %store-monad ((drv (package->derivation package))) (return (match (derivation->output-paths drv) (((_ . file-names) ...) file-names))))) ((? store-path? item) (with-monad %store-monad (return (list item)))) (x (raise (condition (&message (message "unsupported argument for \ this type of graph"))))))) (define (references* item) "Return as a monadic value the references of ITEM, based either on the information available in the local store or using information about substitutes." (lambda (store) (guard (c ((nix-protocol-error? c) (match (substitutable-path-info store (list item)) ((info) (values (substitutable-references info) store)) (() (leave (_ "references for '~a' are not known~%") item))))) (values (references store item) store)))) (define %reference-node-type (node-type (name "references") (description "the DAG of run-time dependencies (store references)") (convert ensure-store-items) (identifier (lift1 identity %store-monad)) (label store-path-package-name) (edges references*))) (define non-derivation-referrers (let ((referrers (store-lift referrers))) (lambda (item) "Return the referrers of ITEM, except '.drv' files." (mlet %store-monad ((items (referrers item))) (return (remove derivation-path? items)))))) (define %referrer-node-type (node-type (name "referrers") (description "the DAG of referrers in the store") (convert ensure-store-items) (identifier (lift1 identity %store-monad)) (label store-path-package-name) (edges non-derivation-referrers))) ;;; ;;; List of node types. ;;; (define %node-types ;; List of all the node types. (list %package-node-type %reverse-package-node-type %bag-node-type %bag-with-origins-node-type %bag-emerged-node-type %derivation-node-type %reference-node-type %referrer-node-type)) (define (lookup-node-type name) "Return the node type called NAME. Raise an error if it is not found." (or (find (lambda (type) (string=? (node-type-name type) name)) %node-types) (leave (_ "~a: unknown node type~%") name))) (define (lookup-backend name) "Return the graph backend called NAME. Raise an error if it is not found." (or (find (lambda (backend) (string=? (graph-backend-name backend) name)) %graph-backends) (leave (_ "~a: unknown backend~%") name))) (define (list-node-types) "Print the available node types along with their synopsis." (display (_ "The available node types are:\n")) (newline) (for-each (lambda (type) (format #t " - ~a: ~a~%" (node-type-name type) (node-type-description type))) %node-types)) (define (list-backends) "Print the available backends along with their synopsis." (display (_ "The available backend types are:\n")) (newline) (for-each (lambda (backend) (format #t " - ~a: ~a~%" (graph-backend-name backend) (graph-backend-description backend))) %graph-backends)) ;;; ;;; Command-line options. ;;; (define %options (list (option '(#\t "type") #t #f (lambda (opt name arg result) (alist-cons 'node-type (lookup-node-type arg) result))) (option '("list-types") #f #f (lambda (opt name arg result) (list-node-types) (exit 0))) (option '(#\b "backend") #t #f (lambda (opt name arg result) (alist-cons 'backend (lookup-backend arg) result))) (option '("list-backends") #f #f (lambda (opt name arg result) (list-backends) (exit 0))) (option '(#\e "expression") #t #f (lambda (opt name arg result) (alist-cons 'expression arg result))) (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix edit"))))) (define (show-help) ;; TRANSLATORS: Here 'dot' is the name of a program; it must not be ;; translated. (display (_ "Usage: guix graph PACKAGE... Emit a Graphviz (dot) representation of the dependencies of PACKAGE...\n")) (display (_ " -b, --backend=TYPE produce a graph with the given backend TYPE")) (display (_ " --list-backends list the available graph backends")) (display (_ " -t, --type=TYPE represent nodes of the given TYPE")) (display (_ " --list-types list the available graph types")) (display (_ " -e, --expression=EXPR consider the package EXPR evaluates to")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %default-options `((node-type . ,%package-node-type) (backend . ,%graphviz-backend))) ;;; ;;; Entry point. ;;; (define (guix-graph . args) (with-error-handling (let* ((opts (args-fold* args %options (lambda (opt name arg . rest) (leave (_ "~A: unrecognized option~%") name)) (lambda (arg result) (alist-cons 'argument arg result)) %default-options)) (backend (assoc-ref opts 'backend)) (type (assoc-ref opts 'node-type)) (items (filter-map (match-lambda (('argument . (? store-path? item)) item) (('argument . spec) (specification->package spec)) (('expression . exp) (read/eval-package-expression exp)) (_ #f)) opts))) (with-store store Ask for absolute file names so that .drv file names passed from the ;; user to 'read-derivation' are absolute when it returns. (with-fluids ((%file-port-name-canonicalization 'absolute)) (run-with-store store ;; XXX: Since grafting can trigger unsolicited builds, disable it. (mlet %store-monad ((_ (set-grafting #f)) (nodes (mapm %store-monad (node-type-convert type) items))) (export-graph (concatenate nodes) (current-output-port) #:node-type type #:backend backend))))))) #t) ;;; graph.scm ends here
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/scripts/graph.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. Package DAG. file name Filter out origins and other non-package dependencies. The default conversion method. Type for the traversal of package nodes. We use package addresses as unique identifiers. This generally works packages that are not 'eq?', yet map to the same derivation (XXX). list of back-edges. Since we want to do it only once, we use the promises below. store not actually needed Package DAG using bags. If THING is a file name (a string), we just return it; if it's a package or origin, we return its address. That gives us the object graph, but that may differ from the derivation graph (for instance, 'package-with-bootstrap-guile' generates fresh package objects, and several packages that are not 'eq?' may actually map to the same derivation.) Thus, we lower THING and use its derivation file name as a unique identifier. Type for the traversal of package nodes via the "bag" representation, which includes implicit inputs. detailed. Return a list of store items as a monadic value based on the given argument, which may be a store item or a package. Return the output file names of PACKAGE. List of node types. List of all the node types. Command-line options. TRANSLATORS: Here 'dot' is the name of a program; it must not be translated. Entry point. user to 'read-derivation' are absolute when it returns. XXX: Since grafting can trigger unsolicited builds, disable it. graph.scm ends here
Copyright © 2015 , 2016 , 2017 < > 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 (guix scripts graph) #:use-module (guix ui) #:use-module (guix graph) #:use-module (guix grafts) #:use-module (guix scripts) #:use-module (guix packages) #:use-module (guix monads) #:use-module (guix store) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix memoization) #:use-module ((guix build-system gnu) #:select (standard-packages)) #:use-module (gnu packages) #:use-module (guix sets) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (srfi srfi-34) #:use-module (srfi srfi-35) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:export (%package-node-type %reverse-package-node-type %bag-node-type %bag-with-origins-node-type %bag-emerged-node-type %derivation-node-type %reference-node-type %referrer-node-type %node-types guix-graph)) (define (node-full-name thing) "Return a human-readable name to denote THING, a package, origin, or file name." (cond ((package? thing) (package-full-name thing)) ((origin? thing) (origin-actual-file-name thing)) (or (basename thing) (error "basename" thing))) (else (number->string (object-address thing) 16)))) (define (package-node-edges package) "Return the list of dependencies of PACKAGE." (match (package-direct-inputs package) (((labels packages . outputs) ...) (filter package? packages)))) (define assert-package (match-lambda ((? package? package) package) (x (raise (condition (&message (message (format #f (_ "~a: invalid argument (package name expected)") x)))))))) (define nodes-from-package (lift1 (compose list assert-package) %store-monad)) (define %package-node-type (node-type (name "package") (description "the DAG of packages, excluding implicit inputs") (convert nodes-from-package) well , but for generated package objects , we could end up with two (identifier (lift1 object-address %store-monad)) (label node-full-name) (edges (lift1 package-node-edges %store-monad)))) Reverse package DAG . (define %reverse-package-node-type For this node type we first need to compute the list of packages and the (let* ((packages (delay (fold-packages cons '()))) (node-back-edges %package-node-type (force packages)))))) (node-type (inherit %package-node-type) (name "reverse-package") (description "the reverse DAG of packages") (edges (lift1 (force back-edges) %store-monad))))) (define (bag-node-identifier thing) "Return a unique identifier for THING, which may be a package, origin, or a file name." (with-monad %store-monad (if (string? thing) (return thing) (mlet %store-monad ((low (lower-object thing))) (return (if (derivation? low) (derivation-file-name low) low)))))) (define (bag-node-edges thing) "Return the list of dependencies of THING, a package or origin. Dependencies may include packages, origin, and file names." (cond ((package? thing) (match (bag-direct-inputs (package->bag thing)) (((labels things . outputs) ...) things))) ((origin? thing) (cons (or (origin-patch-guile thing) (default-guile)) (if (or (pair? (origin-patches thing)) (origin-snippet thing)) (match (origin-patch-inputs thing) (#f '()) (((labels dependencies _ ...) ...) (delete-duplicates dependencies eq?))) '()))) (else '()))) (define %bag-node-type (node-type (name "bag") (description "the DAG of packages, including implicit inputs") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (compose (cut filter package? <>) bag-node-edges) %store-monad)))) (define %bag-with-origins-node-type (node-type (name "bag-with-origins") (description "the DAG of packages and origins, including implicit inputs") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (lambda (thing) (filter (match-lambda ((? package?) #t) ((? origin?) #t) (_ #f)) (bag-node-edges thing))) %store-monad)))) (define standard-package-set (mlambda () "Return the set of standard packages provided by GNU-BUILD-SYSTEM." (match (standard-packages) (((labels packages . output) ...) (list->setq packages))))) (define (bag-node-edges-sans-bootstrap thing) "Like 'bag-node-edges', but pretend that the standard packages of GNU-BUILD-SYSTEM have zero dependencies." (if (set-contains? (standard-package-set) thing) '() (bag-node-edges thing))) (define %bag-emerged-node-type Like % BAG - NODE - TYPE , but without the bootstrap subset of the DAG . (node-type (name "bag-emerged") (description "same as 'bag', but without the bootstrap nodes") (convert nodes-from-package) (identifier bag-node-identifier) (label node-full-name) (edges (lift1 (compose (cut filter package? <>) bag-node-edges-sans-bootstrap) %store-monad)))) Derivation DAG . (define (file->derivation file) "Read the derivation from FILE and return it." (call-with-input-file file read-derivation)) (define (derivation-dependencies obj) "Return the <derivation> objects and store items corresponding to the dependencies of OBJ, a <derivation> or store item." (if (derivation? obj) (append (map (compose file->derivation derivation-input-path) (derivation-inputs obj)) (derivation-sources obj)) '())) (define (derivation-node-identifier node) "Return a unique identifier for NODE, which may be either a <derivation> or a plain store file." (if (derivation? node) (derivation-file-name node) node)) (define (derivation-node-label node) "Return a label for NODE, a <derivation> object or plain store item." (store-path-package-name (match node ((? derivation? drv) (derivation-file-name drv)) ((? string? file) file)))) (define %derivation-node-type DAG of derivations . Very accurate , very detailed , but usually too much (node-type (name "derivation") (description "the DAG of derivations") (convert (match-lambda ((? package? package) (with-monad %store-monad (>>= (package->derivation package) (lift1 list %store-monad)))) ((? derivation-path? item) (mbegin %store-monad ((store-lift add-temp-root) item) (return (list (file->derivation item))))) (x (raise (condition (&message (message "unsupported argument for \ derivation graph"))))))) (identifier (lift1 derivation-node-identifier %store-monad)) (label derivation-node-label) (edges (lift1 derivation-dependencies %store-monad)))) DAG of residual references ( aka . run - time dependencies ) . (define ensure-store-items (match-lambda ((? package? package) (mlet %store-monad ((drv (package->derivation package))) (return (match (derivation->output-paths drv) (((_ . file-names) ...) file-names))))) ((? store-path? item) (with-monad %store-monad (return (list item)))) (x (raise (condition (&message (message "unsupported argument for \ this type of graph"))))))) (define (references* item) "Return as a monadic value the references of ITEM, based either on the information available in the local store or using information about substitutes." (lambda (store) (guard (c ((nix-protocol-error? c) (match (substitutable-path-info store (list item)) ((info) (values (substitutable-references info) store)) (() (leave (_ "references for '~a' are not known~%") item))))) (values (references store item) store)))) (define %reference-node-type (node-type (name "references") (description "the DAG of run-time dependencies (store references)") (convert ensure-store-items) (identifier (lift1 identity %store-monad)) (label store-path-package-name) (edges references*))) (define non-derivation-referrers (let ((referrers (store-lift referrers))) (lambda (item) "Return the referrers of ITEM, except '.drv' files." (mlet %store-monad ((items (referrers item))) (return (remove derivation-path? items)))))) (define %referrer-node-type (node-type (name "referrers") (description "the DAG of referrers in the store") (convert ensure-store-items) (identifier (lift1 identity %store-monad)) (label store-path-package-name) (edges non-derivation-referrers))) (define %node-types (list %package-node-type %reverse-package-node-type %bag-node-type %bag-with-origins-node-type %bag-emerged-node-type %derivation-node-type %reference-node-type %referrer-node-type)) (define (lookup-node-type name) "Return the node type called NAME. Raise an error if it is not found." (or (find (lambda (type) (string=? (node-type-name type) name)) %node-types) (leave (_ "~a: unknown node type~%") name))) (define (lookup-backend name) "Return the graph backend called NAME. Raise an error if it is not found." (or (find (lambda (backend) (string=? (graph-backend-name backend) name)) %graph-backends) (leave (_ "~a: unknown backend~%") name))) (define (list-node-types) "Print the available node types along with their synopsis." (display (_ "The available node types are:\n")) (newline) (for-each (lambda (type) (format #t " - ~a: ~a~%" (node-type-name type) (node-type-description type))) %node-types)) (define (list-backends) "Print the available backends along with their synopsis." (display (_ "The available backend types are:\n")) (newline) (for-each (lambda (backend) (format #t " - ~a: ~a~%" (graph-backend-name backend) (graph-backend-description backend))) %graph-backends)) (define %options (list (option '(#\t "type") #t #f (lambda (opt name arg result) (alist-cons 'node-type (lookup-node-type arg) result))) (option '("list-types") #f #f (lambda (opt name arg result) (list-node-types) (exit 0))) (option '(#\b "backend") #t #f (lambda (opt name arg result) (alist-cons 'backend (lookup-backend arg) result))) (option '("list-backends") #f #f (lambda (opt name arg result) (list-backends) (exit 0))) (option '(#\e "expression") #t #f (lambda (opt name arg result) (alist-cons 'expression arg result))) (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix edit"))))) (define (show-help) (display (_ "Usage: guix graph PACKAGE... Emit a Graphviz (dot) representation of the dependencies of PACKAGE...\n")) (display (_ " -b, --backend=TYPE produce a graph with the given backend TYPE")) (display (_ " --list-backends list the available graph backends")) (display (_ " -t, --type=TYPE represent nodes of the given TYPE")) (display (_ " --list-types list the available graph types")) (display (_ " -e, --expression=EXPR consider the package EXPR evaluates to")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %default-options `((node-type . ,%package-node-type) (backend . ,%graphviz-backend))) (define (guix-graph . args) (with-error-handling (let* ((opts (args-fold* args %options (lambda (opt name arg . rest) (leave (_ "~A: unrecognized option~%") name)) (lambda (arg result) (alist-cons 'argument arg result)) %default-options)) (backend (assoc-ref opts 'backend)) (type (assoc-ref opts 'node-type)) (items (filter-map (match-lambda (('argument . (? store-path? item)) item) (('argument . spec) (specification->package spec)) (('expression . exp) (read/eval-package-expression exp)) (_ #f)) opts))) (with-store store Ask for absolute file names so that .drv file names passed from the (with-fluids ((%file-port-name-canonicalization 'absolute)) (run-with-store store (mlet %store-monad ((_ (set-grafting #f)) (nodes (mapm %store-monad (node-type-convert type) items))) (export-graph (concatenate nodes) (current-output-port) #:node-type type #:backend backend))))))) #t)
53ccb87eb3077a35e5560504dff63b68597453d9a6d36d14b041e68207bae97c
Workiva/eva
tracing.clj
Copyright 2015 - 2019 Workiva Inc. ;; ;; Licensed under the Eclipse Public License 1.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -1.0.php ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.utils.tracing (:require [eva.config :refer [config-strict]] [utiliva.macros :refer [when-class]] [ichnaie.core :refer [tracing-with-spanbuilder]]) (:import [io.jaegertracing Configuration] [io.jaegertracing Configuration$ReporterConfiguration] [io.jaegertracing Configuration$SamplerConfiguration] [io.opentracing SpanContext Span Tracer])) (defn construct-tracer [] (let [config (doto (Configuration. "eva") sampler always makes the same decision for all traces ( " const " ) - trace all ( 1 ) ;; See -core/0.34.0/io/jaegertracing/Configuration.html for ;; more details about configuration classes (.withSampler (.. Configuration$SamplerConfiguration (fromEnv) (withType "const") (withParam 1))) (.withReporter (.. Configuration$ReporterConfiguration (fromEnv))))] (.getTracer config))) (defn trace-fn-with-tags [span-name f & args] (if-let [tracer ^Tracer ichnaie.core/*tracer*] (let [span-builder (as-> (.buildSpan tracer span-name) span-builder ;; make span-builder (if (some? ichnaie.core/*trace-stack*) ;; maybe make it a child (.asChildOf span-builder ^Span ichnaie.core/*trace-stack*) span-builder) (if (config-strict :eva.tracing.tag-inputs) (reduce-kv (fn [span-builder position arg] ;; tag it (.withTag span-builder (str position) (str arg))) span-builder (vec args)) span-builder))] (tracing-with-spanbuilder span-builder (apply f args))) (apply f args)))
null
https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/src/eva/utils/tracing.clj
clojure
Licensed under the Eclipse Public License 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -1.0.php 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. See -core/0.34.0/io/jaegertracing/Configuration.html for more details about configuration classes make span-builder maybe make it a child tag it
Copyright 2015 - 2019 Workiva Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns eva.utils.tracing (:require [eva.config :refer [config-strict]] [utiliva.macros :refer [when-class]] [ichnaie.core :refer [tracing-with-spanbuilder]]) (:import [io.jaegertracing Configuration] [io.jaegertracing Configuration$ReporterConfiguration] [io.jaegertracing Configuration$SamplerConfiguration] [io.opentracing SpanContext Span Tracer])) (defn construct-tracer [] (let [config (doto (Configuration. "eva") sampler always makes the same decision for all traces ( " const " ) - trace all ( 1 ) (.withSampler (.. Configuration$SamplerConfiguration (fromEnv) (withType "const") (withParam 1))) (.withReporter (.. Configuration$ReporterConfiguration (fromEnv))))] (.getTracer config))) (defn trace-fn-with-tags [span-name f & args] (if-let [tracer ^Tracer ichnaie.core/*tracer*] (.asChildOf span-builder ^Span ichnaie.core/*trace-stack*) span-builder) (if (config-strict :eva.tracing.tag-inputs) (.withTag span-builder (str position) (str arg))) span-builder (vec args)) span-builder))] (tracing-with-spanbuilder span-builder (apply f args))) (apply f args)))
2c5392dea2524fc3a50ebeca874e45d2113e12bb3abbee3a338d89011dd68c31
montelibero-org/veche
Foundation.hs
# LANGUAGE BlockArguments # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # # LANGUAGE InstanceSigs # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # instance { Yesod , YesodAuth ... } App module Foundation where -- prelude import Foundation.Base import Import.Extra import Import.NoFoundation -- global import Control.Monad.Logger (LogLevel (LevelWarn), LogSource) import Data.Text qualified as Text import Database.Persist.Sql (SqlBackend) import Network.Wai (requestMethod) import Text.Jasmine (minifym) import Yesod.Auth.Dummy (authDummy) import Yesod.Auth.Message (AuthMessage (LoginTitle)) import Yesod.Core (Approot (ApprootRequest), AuthResult (Authorized), HandlerSite, SessionBackend, Yesod, addMessageI, badMethod, defaultClientSessionBackend, defaultCsrfMiddleware, defaultYesodMiddleware, getApprootText, getRouteToParent, guessApproot, unauthorizedI, waiRequest) import Yesod.Core qualified import Yesod.Core.Types (Logger) import Yesod.Core.Unsafe qualified as Unsafe import Yesod.Default.Util (addStaticContentExternal) import Yesod.Static (Route (StaticRoute), base64md5) -- project import Stellar.Horizon.Client qualified as Stellar -- component import Authentication.MyMtlWalletBot (authMyMtlWalletBot) import Authentication.Stellar (authnStellar) import Authentication.Stellar qualified as AuthnStellar import Authentication.Telegram (authTelegram) import Model.Forum qualified as Forum import Model.Telegram (Key (TelegramKey), Telegram (Telegram)) import Model.Telegram qualified import Model.User (UserId) import Model.User qualified as User import Model.Verifier qualified as Verifier import Templates.DefaultLayout (isAuthRMay) import Templates.DefaultLayout qualified -- | A convenient synonym for database access functions. type DB a = forall m. (MonadUnliftIO m) => ReaderT SqlBackend m a -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: -approot approot :: Approot App approot = ApprootRequest $ getApprootText guessApproot -- Store session data on the client in encrypted cookies makeSessionBackend :: App -> IO (Maybe SessionBackend) makeSessionBackend App{appSettings = AppSettings{appSessionKeyFile}} = Just <$> defaultClientSessionBackend idle timeout in minutes appSessionKeyFile where year = 365 * day day = 24 * hour hour = 60 allows you to run code before and after each handler function . -- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. -- Some users may also want to add the defaultCsrfMiddleware, which: -- a) Sets a cookie with a CSRF token in it. -- b) Validates that incoming write requests include that token in either a header or POST parameter. -- To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware For details , see the CSRF documentation in the Yesod . Core . Handler module of the yesod - core package . -- yesodMiddleware :: ToTypedContent res => Handler res -> Handler res yesodMiddleware = defaultYesodMiddleware . csrfMiddleware defaultLayout :: Widget -> Handler Html defaultLayout = Templates.DefaultLayout.defaultLayout -- The page to be redirected to when authentication is required. authRoute :: App -> Maybe (Route App) authRoute _ = Just $ AuthR LoginR isAuthorized :: Route App -- ^ The route the user is visiting. -> Bool -- ^ Whether or not this is a "write" request. -> Handler AuthResult isAuthorized route _isWrite = isAuthorized route -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent :: Text -- ^ The file extension -> Text -- ^ The MIME content type -> LByteString -- ^ The contents of the file -> Handler (Maybe (Either Text (Route App, [(Text, Text)]))) addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . (`StaticRoute` [])) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool shouldLogIO app _source level = pure $ appShouldLogAll (appSettings app) || level >= LevelWarn makeLogger :: App -> IO Logger makeLogger = pure . appLogger csrfMiddleware :: Handler a -> Handler a csrfMiddleware h = do route <- getCurrentRoute let mw | isAuthRMay route = identity | otherwise = defaultCsrfMiddleware mw h -- -- Define breadcrumbs. instance YesodBreadcrumbs App where -- -- Takes the route that the user is currently on, and returns a tuple -- -- of the 'Text' that you want the label to display, and a previous -- -- breadcrumb route. -- breadcrumb : : Route App -- ^ The route the user is visiting currently . - > Handler ( Text , Maybe ( Route App ) ) -- breadcrumb = \case -- -- HomeR -> pure ("Home", Nothing) -- ( AuthR _ ) - > pure ( " Login " , Nothing ) -- -- ProfileR -> pure ("Profile", Nothing) -- _ -> pure ("", Nothing) instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest :: App -> Route App loginDest _ = DashboardR -- Where to send a user after logout logoutDest :: App -> Route App logoutDest _ = AuthR LoginR Override the above two destinations when a : header is present redirectToReferer :: App -> Bool redirectToReferer _ = True -- Record authentication based on the given verified credentials authenticate :: (MonadHandler m, HandlerSite m ~ App) => Creds App -> m (AuthenticationResult App) authenticate Creds{credsPlugin, credsIdent, credsExtra} = case credsPlugin of "dummy" -> authenticateStellar credsIdent "stellar" -> authenticateStellar credsIdent "mymtlwalletbot" -> authenticateStellar credsIdent "telegram" -> authenticateTelegram credsIdent credsExtra _ -> pure $ ServerError "Unknown auth plugin" You can add other plugins like Google Email , email or OAuth here authPlugins :: App -> [AuthPlugin App] authPlugins app@App{appSettings} = [ authnStellar $ authnStellarConfig AuthnStellar.Keybase app , authnStellar $ authnStellarConfig AuthnStellar.Laboratory app , authTelegram , authMyMtlWalletBot ] ++ [authDummy | appAuthDummyLogin] where AppSettings{appAuthDummyLogin} = appSettings loginHandler = do app@App{appSettings = AppSettings{appAuthDummyLogin}} <- getYesod routeToParent <- getRouteToParent let createAccountWidgets = [ apLogin (authnStellar $ authnStellarConfig AuthnStellar.Keybase app) routeToParent , apLogin ( authnStellar $ authnStellarConfig AuthnStellar.Laboratory app ) routeToParent , apLogin authMyMtlWalletBot routeToParent ] ++ [apLogin authDummy routeToParent | appAuthDummyLogin] let widgetIfTelegramBound = apLogin authTelegram routeToParent authLayout do setTitleI LoginTitle [whamlet| <h1 .text-center>_{MsgCreateAccountOrLogIn} $forall loginWidget <- createAccountWidgets <div .mb-1 .text-center>^{loginWidget} <div .text-center> <input #checkTelegramBound .form-check-input data-bs-target="#collapsedTelegramBound" data-bs-toggle=collapse type=checkbox> <label .form-check-label for=checkTelegramBound> _{MsgTelegramIsBound} <div #collapsedTelegramBound .collapse .mb-1 .text-center> ^{widgetIfTelegramBound} |] authenticateStellar :: (MonadHandler m, HandlerSite m ~ App) => Text -> m (AuthenticationResult App) authenticateStellar credsIdent = Authenticated <$> User.getOrCreate (Stellar.Address credsIdent) authenticateTelegram :: (MonadHandler m, HandlerSite m ~ App) => Text -> [(Text, Text)] -> m (AuthenticationResult App) authenticateTelegram credsIdent credsExtra = do mUserTelegram <- User.getByTelegramId telegramId case mUserTelegram of Nothing -> do addMessageI "danger" MsgTelegramNotBound redirect $ AuthR LoginR Just (Entity (TelegramKey userId) Telegram{username}) -> do when (username /= authenticatedUsername) $ User.setTelegramUsername userId authenticatedUsername pure $ Authenticated userId where telegramId = either error identity $ readEither $ Text.unpack credsIdent authenticatedUsername = lookup "username" credsExtra authnStellarConfig :: AuthnStellar.Flavor -> App -> AuthnStellar.Config authnStellarConfig flavor App{appStellarHorizon} = AuthnStellar.Config { flavor , horizon = appStellarHorizon , getVerifyKey = Verifier.getKey , checkAndRemoveVerifyKey = Verifier.checkAndRemoveKey } -- Actually, we check only authentication here. -- Authorization requires data from the database, -- and happens inside handlers after the data is got to minimize DB requests. isAuthorized :: Route App -> HandlerFor App AuthResult isAuthorized = \case -- Routes not requiring authentication. AboutR{} -> authorized FaviconR -> authorized ForumsR{} -> authorized IssueR{} -> authorized RobotsR -> authorized RootR -> authorized SettingsLanguageR{} -> authorized StaticR{} -> authorized StellarFederationR{} -> authorized WellKnownR{} -> authorized Work around buggy GET - based Yesod 's logging out -- AuthR LogoutR -> do method <- requestMethod <$> waiRequest case method of "POST" -> authorizedIfAuthenticated _ -> badMethod AuthR _ -> authorized -- Some forums are public ForumR id | Forum.isPublic id -> authorized | otherwise -> authorizedIfAuthenticated -- All other routes require authentication. _ -> authorizedIfAuthenticated where authorized = pure Authorized -- | Access function to determine if a user is logged in. authorizedIfAuthenticated :: Handler AuthResult authorizedIfAuthenticated = do muid <- maybeAuthId case muid of Nothing -> unauthorizedI MsgUnauthorized Just _ -> pure Authorized instance YesodAuthPersist App unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger type Form = BForm Handler
null
https://raw.githubusercontent.com/montelibero-org/veche/a0a97cf465df7c41bcafbfda0574323a4dab5808/veche-web/src/Foundation.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # prelude global project component | A convenient synonym for database access functions. Please see the documentation for the Yesod typeclass. There are a number of settings which can be configured by overriding methods here. Controls the base of generated URLs. For more information on modifying, see: -approot Store session data on the client in encrypted cookies The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. Some users may also want to add the defaultCsrfMiddleware, which: a) Sets a cookie with a CSRF token in it. b) Validates that incoming write requests include that token in either a header or POST parameter. To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware yesodMiddleware :: ToTypedContent res => Handler res -> Handler res The page to be redirected to when authentication is required. ^ The route the user is visiting. ^ Whether or not this is a "write" request. This function creates static content files in the static folder and names them based on a hash of their content. This allows expiration dates to be set far in the future without worry of users receiving stale content. ^ The file extension ^ The MIME content type ^ The contents of the file Generate a unique filename based on the content itself What messages should be logged. The following includes all messages when in development, and warnings and errors in production. -- Define breadcrumbs. -- Takes the route that the user is currently on, and returns a tuple -- of the 'Text' that you want the label to display, and a previous -- breadcrumb route. breadcrumb ^ The route the user is visiting currently . breadcrumb = \case -- HomeR -> pure ("Home", Nothing) ( AuthR _ ) - > pure ( " Login " , Nothing ) -- ProfileR -> pure ("Profile", Nothing) _ -> pure ("", Nothing) Where to send a user after successful login Where to send a user after logout Record authentication based on the given verified credentials Actually, we check only authentication here. Authorization requires data from the database, and happens inside handlers after the data is got to minimize DB requests. Routes not requiring authentication. Some forums are public All other routes require authentication. | Access function to determine if a user is logged in.
# LANGUAGE BlockArguments # # LANGUAGE DisambiguateRecordFields # # LANGUAGE ImportQualifiedPost # # LANGUAGE InstanceSigs # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # # LANGUAGE NoImplicitPrelude # # LANGUAGE QuasiQuotes # # LANGUAGE TypeFamilies # instance { Yesod , YesodAuth ... } App module Foundation where import Foundation.Base import Import.Extra import Import.NoFoundation import Control.Monad.Logger (LogLevel (LevelWarn), LogSource) import Data.Text qualified as Text import Database.Persist.Sql (SqlBackend) import Network.Wai (requestMethod) import Text.Jasmine (minifym) import Yesod.Auth.Dummy (authDummy) import Yesod.Auth.Message (AuthMessage (LoginTitle)) import Yesod.Core (Approot (ApprootRequest), AuthResult (Authorized), HandlerSite, SessionBackend, Yesod, addMessageI, badMethod, defaultClientSessionBackend, defaultCsrfMiddleware, defaultYesodMiddleware, getApprootText, getRouteToParent, guessApproot, unauthorizedI, waiRequest) import Yesod.Core qualified import Yesod.Core.Types (Logger) import Yesod.Core.Unsafe qualified as Unsafe import Yesod.Default.Util (addStaticContentExternal) import Yesod.Static (Route (StaticRoute), base64md5) import Stellar.Horizon.Client qualified as Stellar import Authentication.MyMtlWalletBot (authMyMtlWalletBot) import Authentication.Stellar (authnStellar) import Authentication.Stellar qualified as AuthnStellar import Authentication.Telegram (authTelegram) import Model.Forum qualified as Forum import Model.Telegram (Key (TelegramKey), Telegram (Telegram)) import Model.Telegram qualified import Model.User (UserId) import Model.User qualified as User import Model.Verifier qualified as Verifier import Templates.DefaultLayout (isAuthRMay) import Templates.DefaultLayout qualified type DB a = forall m. (MonadUnliftIO m) => ReaderT SqlBackend m a instance Yesod App where approot :: Approot App approot = ApprootRequest $ getApprootText guessApproot makeSessionBackend :: App -> IO (Maybe SessionBackend) makeSessionBackend App{appSettings = AppSettings{appSessionKeyFile}} = Just <$> defaultClientSessionBackend idle timeout in minutes appSessionKeyFile where year = 365 * day day = 24 * hour hour = 60 allows you to run code before and after each handler function . For details , see the CSRF documentation in the Yesod . Core . Handler module of the yesod - core package . yesodMiddleware = defaultYesodMiddleware . csrfMiddleware defaultLayout :: Widget -> Handler Html defaultLayout = Templates.DefaultLayout.defaultLayout authRoute :: App -> Maybe (Route App) authRoute _ = Just $ AuthR LoginR isAuthorized -> Handler AuthResult isAuthorized route _isWrite = isAuthorized route addStaticContent -> Handler (Maybe (Either Text (Route App, [(Text, Text)]))) addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . (`StaticRoute` [])) ext mime content where genFileName lbs = "autogen-" ++ base64md5 lbs shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool shouldLogIO app _source level = pure $ appShouldLogAll (appSettings app) || level >= LevelWarn makeLogger :: App -> IO Logger makeLogger = pure . appLogger csrfMiddleware :: Handler a -> Handler a csrfMiddleware h = do route <- getCurrentRoute let mw | isAuthRMay route = identity | otherwise = defaultCsrfMiddleware mw h instance YesodBreadcrumbs App where - > Handler ( Text , Maybe ( Route App ) ) instance YesodAuth App where type AuthId App = UserId loginDest :: App -> Route App loginDest _ = DashboardR logoutDest :: App -> Route App logoutDest _ = AuthR LoginR Override the above two destinations when a : header is present redirectToReferer :: App -> Bool redirectToReferer _ = True authenticate :: (MonadHandler m, HandlerSite m ~ App) => Creds App -> m (AuthenticationResult App) authenticate Creds{credsPlugin, credsIdent, credsExtra} = case credsPlugin of "dummy" -> authenticateStellar credsIdent "stellar" -> authenticateStellar credsIdent "mymtlwalletbot" -> authenticateStellar credsIdent "telegram" -> authenticateTelegram credsIdent credsExtra _ -> pure $ ServerError "Unknown auth plugin" You can add other plugins like Google Email , email or OAuth here authPlugins :: App -> [AuthPlugin App] authPlugins app@App{appSettings} = [ authnStellar $ authnStellarConfig AuthnStellar.Keybase app , authnStellar $ authnStellarConfig AuthnStellar.Laboratory app , authTelegram , authMyMtlWalletBot ] ++ [authDummy | appAuthDummyLogin] where AppSettings{appAuthDummyLogin} = appSettings loginHandler = do app@App{appSettings = AppSettings{appAuthDummyLogin}} <- getYesod routeToParent <- getRouteToParent let createAccountWidgets = [ apLogin (authnStellar $ authnStellarConfig AuthnStellar.Keybase app) routeToParent , apLogin ( authnStellar $ authnStellarConfig AuthnStellar.Laboratory app ) routeToParent , apLogin authMyMtlWalletBot routeToParent ] ++ [apLogin authDummy routeToParent | appAuthDummyLogin] let widgetIfTelegramBound = apLogin authTelegram routeToParent authLayout do setTitleI LoginTitle [whamlet| <h1 .text-center>_{MsgCreateAccountOrLogIn} $forall loginWidget <- createAccountWidgets <div .mb-1 .text-center>^{loginWidget} <div .text-center> <input #checkTelegramBound .form-check-input data-bs-target="#collapsedTelegramBound" data-bs-toggle=collapse type=checkbox> <label .form-check-label for=checkTelegramBound> _{MsgTelegramIsBound} <div #collapsedTelegramBound .collapse .mb-1 .text-center> ^{widgetIfTelegramBound} |] authenticateStellar :: (MonadHandler m, HandlerSite m ~ App) => Text -> m (AuthenticationResult App) authenticateStellar credsIdent = Authenticated <$> User.getOrCreate (Stellar.Address credsIdent) authenticateTelegram :: (MonadHandler m, HandlerSite m ~ App) => Text -> [(Text, Text)] -> m (AuthenticationResult App) authenticateTelegram credsIdent credsExtra = do mUserTelegram <- User.getByTelegramId telegramId case mUserTelegram of Nothing -> do addMessageI "danger" MsgTelegramNotBound redirect $ AuthR LoginR Just (Entity (TelegramKey userId) Telegram{username}) -> do when (username /= authenticatedUsername) $ User.setTelegramUsername userId authenticatedUsername pure $ Authenticated userId where telegramId = either error identity $ readEither $ Text.unpack credsIdent authenticatedUsername = lookup "username" credsExtra authnStellarConfig :: AuthnStellar.Flavor -> App -> AuthnStellar.Config authnStellarConfig flavor App{appStellarHorizon} = AuthnStellar.Config { flavor , horizon = appStellarHorizon , getVerifyKey = Verifier.getKey , checkAndRemoveVerifyKey = Verifier.checkAndRemoveKey } isAuthorized :: Route App -> HandlerFor App AuthResult isAuthorized = \case AboutR{} -> authorized FaviconR -> authorized ForumsR{} -> authorized IssueR{} -> authorized RobotsR -> authorized RootR -> authorized SettingsLanguageR{} -> authorized StaticR{} -> authorized StellarFederationR{} -> authorized WellKnownR{} -> authorized Work around buggy GET - based Yesod 's logging out AuthR LogoutR -> do method <- requestMethod <$> waiRequest case method of "POST" -> authorizedIfAuthenticated _ -> badMethod AuthR _ -> authorized ForumR id | Forum.isPublic id -> authorized | otherwise -> authorizedIfAuthenticated _ -> authorizedIfAuthenticated where authorized = pure Authorized authorizedIfAuthenticated :: Handler AuthResult authorizedIfAuthenticated = do muid <- maybeAuthId case muid of Nothing -> unauthorizedI MsgUnauthorized Just _ -> pure Authorized instance YesodAuthPersist App unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger type Form = BForm Handler
5da6dad9f1d7a90a45a55126a2cf9e7aab5c2d485fea2602fc16bb0c9edead6f
4clojure/4clojure
solutions.clj
(ns foreclojure.solutions (:require [clojure.string :as s]) (:use [somnium.congomongo :only [fetch-one update!]] [useful.debug :only [?]] [foreclojure.messages :only [err-msg]])) (defn get-solution ([perm-level user-id problem-id] (when (or (= :private perm-level) (not (:hide-solutions (fetch-one :users :where {:_id user-id} :only [:hide-solutions])))) (get-solution user-id problem-id))) ([user-id problem-id] (or (:code (fetch-one :solutions :where {:user user-id :problem problem-id})) (let [{:keys [scores solved]} (fetch-one :users :where {:_id user-id} :only [(keyword (str "scores." problem-id)) :solved])] (cond (seq scores) (err-msg "solution.scored-early" (first (vals scores))), (some #{problem-id} solved) (err-msg "solution.solved-early")))))) (defn save-solution [user-id problem-id code] (update! :solutions {:user user-id :problem problem-id} {:$set {:code code}} :upsert true))
null
https://raw.githubusercontent.com/4clojure/4clojure/25dec057d9d6871ce52aee9e2c3de7efdab14373/src/foreclojure/solutions.clj
clojure
(ns foreclojure.solutions (:require [clojure.string :as s]) (:use [somnium.congomongo :only [fetch-one update!]] [useful.debug :only [?]] [foreclojure.messages :only [err-msg]])) (defn get-solution ([perm-level user-id problem-id] (when (or (= :private perm-level) (not (:hide-solutions (fetch-one :users :where {:_id user-id} :only [:hide-solutions])))) (get-solution user-id problem-id))) ([user-id problem-id] (or (:code (fetch-one :solutions :where {:user user-id :problem problem-id})) (let [{:keys [scores solved]} (fetch-one :users :where {:_id user-id} :only [(keyword (str "scores." problem-id)) :solved])] (cond (seq scores) (err-msg "solution.scored-early" (first (vals scores))), (some #{problem-id} solved) (err-msg "solution.solved-early")))))) (defn save-solution [user-id problem-id code] (update! :solutions {:user user-id :problem problem-id} {:$set {:code code}} :upsert true))
125967c2ced25bd4480ea93403e24dc2d73c731ec9cd7832c3a4b01fb720e0b4
VitorCBSB/HetrisV2
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import Constants (windowSize) import Control.Lens import CountingDown import Credits import Game import GameOver import Help import InitialStates import Intro import MainMenu import Paused import qualified SDL import qualified SDL.Font as Ttf import qualified SDL.Mixer as Mixer import Types import UtilsSDL (mainLoop) main :: IO () main = mainLoop initialMainState 60 input tick render "Hetris V2" windowSize initialMainState :: (SDL.Window, SDL.Renderer) -> IO MainState initialMainState (_, r) = do ass <- loadAssets r Mixer.setVolume 10 Mixer.AllChannels Mixer.setMusicVolume 10 let initGameState = initialIntroState return MainState { _gameAssets = ass, _mainPhase = Intro initGameState } loadSoundAssets :: IO SoundAssets loadSoundAssets = do hitWall <- Mixer.load "assets/sfx/hitwall.wav" lineClear <- Mixer.load "assets/sfx/lineclear.wav" landOnSurface <- Mixer.load "assets/sfx/landonsurface.wav" lineDrop <- Mixer.load "assets/sfx/linedrop.wav" lockedPiece <- Mixer.load "assets/sfx/lockedpiece.wav" movement <- Mixer.load "assets/sfx/movement.wav" rotation <- Mixer.load "assets/sfx/rotation.wav" defeat <- Mixer.load "assets/sfx/defeat.wav" pause <- Mixer.load "assets/sfx/pause.wav" menuSelect <- Mixer.load "assets/sfx/menuselect.wav" levelUp <- Mixer.load "assets/sfx/levelup.wav" countdown <- Mixer.load "assets/sfx/countdown.wav" countdownGo <- Mixer.load "assets/sfx/countdowngo.wav" korobeinikiMusic <- Mixer.load "assets/sfx/korobeiniki.ogg" return SoundAssets { _hitWallSfx = hitWall, _lineClearSfx = lineClear, _landOnSurfaceSfx = landOnSurface, _lineDropSfx = lineDrop, _lockedPieceSfx = lockedPiece, _movementSfx = movement, _rotationSfx = rotation, _defeatSfx = defeat, _pauseSfx = pause, _menuSelectSfx = menuSelect, _levelUpSfx = levelUp, _countdownSfx = countdown, _countdownGoSfx = countdownGo, _korobeiniki = korobeinikiMusic } loadImageAssets :: SDL.Renderer -> IO ImageAssets loadImageAssets renderer = do cyanBMP <- loadTexture "assets/img/cyanblock.bmp" greenBMP <- loadTexture "assets/img/greenblock.bmp" blueBMP <- loadTexture "assets/img/blueblock.bmp" orangeBMP <- loadTexture "assets/img/orangeblock.bmp" redBMP <- loadTexture "assets/img/redblock.bmp" purpleBMP <- loadTexture "assets/img/purpleblock.bmp" yellowBMP <- loadTexture "assets/img/yellowblock.bmp" grayBMP <- loadTexture "assets/img/grayblock.bmp" verticalBMP <- loadTexture "assets/img/verticalBorder.bmp" horizontalBMP <- loadTexture "assets/img/horizontalBorder.bmp" return ImageAssets { _cyanBlock = cyanBMP, _greenBlock = greenBMP, _blueBlock = blueBMP, _orangeBlock = orangeBMP, _redBlock = redBMP, _purpleBlock = purpleBMP, _yellowBlock = yellowBMP, _grayBlock = grayBMP, _verticalBorder = verticalBMP, _horizontalBorder = horizontalBMP } where loadTexture fp = do bmpSurf <- SDL.loadBMP fp t <- SDL.createTextureFromSurface renderer bmpSurf SDL.freeSurface bmpSurf return t loadTextAssets :: SDL.Renderer -> IO TextAssets loadTextAssets renderer = do font <- Ttf.load "assets/fonts/PokemonGB.ttf" 20 levelText <- loadText font "Level" scoreText <- loadText font "Score" return $ TextAssets { _font = font, _levelText = levelText, _scoreText = scoreText } where loadText f t = do surf <- Ttf.blended f (SDL.V4 255 255 255 255) t t <- SDL.createTextureFromSurface renderer surf SDL.freeSurface surf return t loadAssets :: SDL.Renderer -> IO Assets loadAssets r = Assets <$> loadImageAssets r <*> loadSoundAssets <*> loadTextAssets r input :: SDL.EventPayload -> MainState -> IO (Maybe MainState) input ev ms = case ms ^. mainPhase of Intro is -> do newPhase <- inputIntro ev (ms ^. gameAssets) is return (Just $ ms & mainPhase .~ newPhase) MainMenu mms -> do maybeNewPhase <- inputMainMenu ev (ms ^. gameAssets) mms case maybeNewPhase of Nothing -> return Nothing Just newPhase -> return (Just $ ms & mainPhase .~ newPhase) Credits -> do newPhase <- inputCredits ev return (Just $ ms & mainPhase .~ newPhase) Help -> do newPhase <- inputHelp ev return (Just $ ms & mainPhase .~ newPhase) Paused ps -> do maybeNewPhase <- inputPaused ev (ms ^. gameAssets) ps case maybeNewPhase of Nothing -> return Nothing Just newPhase -> return (Just $ ms & mainPhase .~ newPhase) CountingDown cds -> do newPhase <- inputCountingDown ev (ms ^. gameAssets) cds return (Just $ ms & mainPhase .~ newPhase) Game gs -> do newPhase <- inputGame ev (ms ^. gameAssets) gs return (Just $ ms & mainPhase .~ newPhase) GameOver gos -> do newPhase <- inputGameOver ev (ms ^. gameAssets) gos return (Just $ ms & mainPhase .~ newPhase) tick :: Double -> MainState -> IO (Maybe MainState) tick dt ms = case ms ^. mainPhase of Intro is -> do newPhase <- tickIntro dt (ms ^. gameAssets) is return (Just $ ms & mainPhase .~ newPhase) MainMenu mms -> do newPhase <- tickMainMenu dt mms return (Just $ ms & mainPhase .~ newPhase) Credits -> do newPhase <- tickCredits dt return (Just $ ms & mainPhase .~ newPhase) Help -> do newPhase <- tickHelp dt return (Just $ ms & mainPhase .~ newPhase) Paused ps -> do newPhase <- tickPaused dt ps return (Just $ ms & mainPhase .~ newPhase) CountingDown cds -> do newPhase <- tickCountingDown dt (ms ^. gameAssets) cds return (Just $ ms & mainPhase .~ newPhase) Game gs -> do newPhase <- tickGame dt (ms ^. gameAssets) gs return (Just $ ms & mainPhase .~ newPhase) GameOver gos -> do newPhase <- tickGameOver dt gos return (Just $ ms & mainPhase .~ newPhase) render :: SDL.Renderer -> MainState -> IO () render renderer ms = case ms ^. mainPhase of Intro is -> renderIntro renderer (ms ^. gameAssets) is MainMenu mms -> renderMainMenu renderer (ms ^. gameAssets) mms Credits -> renderCredits renderer (ms ^. gameAssets) Help -> renderHelp renderer (ms ^. gameAssets) Paused ps -> renderPaused renderer (ms ^. gameAssets) ps CountingDown cds -> renderCountingDown renderer (ms ^. gameAssets) cds Game gs -> renderGame renderer (ms ^. gameAssets) gs (0, 0) GameOver gos -> renderGameOver renderer (ms ^. gameAssets) gos
null
https://raw.githubusercontent.com/VitorCBSB/HetrisV2/2544e8ce56a4d0daba9126642118f0504215f742/app/Main.hs
haskell
# LANGUAGE OverloadedStrings #
module Main where import Constants (windowSize) import Control.Lens import CountingDown import Credits import Game import GameOver import Help import InitialStates import Intro import MainMenu import Paused import qualified SDL import qualified SDL.Font as Ttf import qualified SDL.Mixer as Mixer import Types import UtilsSDL (mainLoop) main :: IO () main = mainLoop initialMainState 60 input tick render "Hetris V2" windowSize initialMainState :: (SDL.Window, SDL.Renderer) -> IO MainState initialMainState (_, r) = do ass <- loadAssets r Mixer.setVolume 10 Mixer.AllChannels Mixer.setMusicVolume 10 let initGameState = initialIntroState return MainState { _gameAssets = ass, _mainPhase = Intro initGameState } loadSoundAssets :: IO SoundAssets loadSoundAssets = do hitWall <- Mixer.load "assets/sfx/hitwall.wav" lineClear <- Mixer.load "assets/sfx/lineclear.wav" landOnSurface <- Mixer.load "assets/sfx/landonsurface.wav" lineDrop <- Mixer.load "assets/sfx/linedrop.wav" lockedPiece <- Mixer.load "assets/sfx/lockedpiece.wav" movement <- Mixer.load "assets/sfx/movement.wav" rotation <- Mixer.load "assets/sfx/rotation.wav" defeat <- Mixer.load "assets/sfx/defeat.wav" pause <- Mixer.load "assets/sfx/pause.wav" menuSelect <- Mixer.load "assets/sfx/menuselect.wav" levelUp <- Mixer.load "assets/sfx/levelup.wav" countdown <- Mixer.load "assets/sfx/countdown.wav" countdownGo <- Mixer.load "assets/sfx/countdowngo.wav" korobeinikiMusic <- Mixer.load "assets/sfx/korobeiniki.ogg" return SoundAssets { _hitWallSfx = hitWall, _lineClearSfx = lineClear, _landOnSurfaceSfx = landOnSurface, _lineDropSfx = lineDrop, _lockedPieceSfx = lockedPiece, _movementSfx = movement, _rotationSfx = rotation, _defeatSfx = defeat, _pauseSfx = pause, _menuSelectSfx = menuSelect, _levelUpSfx = levelUp, _countdownSfx = countdown, _countdownGoSfx = countdownGo, _korobeiniki = korobeinikiMusic } loadImageAssets :: SDL.Renderer -> IO ImageAssets loadImageAssets renderer = do cyanBMP <- loadTexture "assets/img/cyanblock.bmp" greenBMP <- loadTexture "assets/img/greenblock.bmp" blueBMP <- loadTexture "assets/img/blueblock.bmp" orangeBMP <- loadTexture "assets/img/orangeblock.bmp" redBMP <- loadTexture "assets/img/redblock.bmp" purpleBMP <- loadTexture "assets/img/purpleblock.bmp" yellowBMP <- loadTexture "assets/img/yellowblock.bmp" grayBMP <- loadTexture "assets/img/grayblock.bmp" verticalBMP <- loadTexture "assets/img/verticalBorder.bmp" horizontalBMP <- loadTexture "assets/img/horizontalBorder.bmp" return ImageAssets { _cyanBlock = cyanBMP, _greenBlock = greenBMP, _blueBlock = blueBMP, _orangeBlock = orangeBMP, _redBlock = redBMP, _purpleBlock = purpleBMP, _yellowBlock = yellowBMP, _grayBlock = grayBMP, _verticalBorder = verticalBMP, _horizontalBorder = horizontalBMP } where loadTexture fp = do bmpSurf <- SDL.loadBMP fp t <- SDL.createTextureFromSurface renderer bmpSurf SDL.freeSurface bmpSurf return t loadTextAssets :: SDL.Renderer -> IO TextAssets loadTextAssets renderer = do font <- Ttf.load "assets/fonts/PokemonGB.ttf" 20 levelText <- loadText font "Level" scoreText <- loadText font "Score" return $ TextAssets { _font = font, _levelText = levelText, _scoreText = scoreText } where loadText f t = do surf <- Ttf.blended f (SDL.V4 255 255 255 255) t t <- SDL.createTextureFromSurface renderer surf SDL.freeSurface surf return t loadAssets :: SDL.Renderer -> IO Assets loadAssets r = Assets <$> loadImageAssets r <*> loadSoundAssets <*> loadTextAssets r input :: SDL.EventPayload -> MainState -> IO (Maybe MainState) input ev ms = case ms ^. mainPhase of Intro is -> do newPhase <- inputIntro ev (ms ^. gameAssets) is return (Just $ ms & mainPhase .~ newPhase) MainMenu mms -> do maybeNewPhase <- inputMainMenu ev (ms ^. gameAssets) mms case maybeNewPhase of Nothing -> return Nothing Just newPhase -> return (Just $ ms & mainPhase .~ newPhase) Credits -> do newPhase <- inputCredits ev return (Just $ ms & mainPhase .~ newPhase) Help -> do newPhase <- inputHelp ev return (Just $ ms & mainPhase .~ newPhase) Paused ps -> do maybeNewPhase <- inputPaused ev (ms ^. gameAssets) ps case maybeNewPhase of Nothing -> return Nothing Just newPhase -> return (Just $ ms & mainPhase .~ newPhase) CountingDown cds -> do newPhase <- inputCountingDown ev (ms ^. gameAssets) cds return (Just $ ms & mainPhase .~ newPhase) Game gs -> do newPhase <- inputGame ev (ms ^. gameAssets) gs return (Just $ ms & mainPhase .~ newPhase) GameOver gos -> do newPhase <- inputGameOver ev (ms ^. gameAssets) gos return (Just $ ms & mainPhase .~ newPhase) tick :: Double -> MainState -> IO (Maybe MainState) tick dt ms = case ms ^. mainPhase of Intro is -> do newPhase <- tickIntro dt (ms ^. gameAssets) is return (Just $ ms & mainPhase .~ newPhase) MainMenu mms -> do newPhase <- tickMainMenu dt mms return (Just $ ms & mainPhase .~ newPhase) Credits -> do newPhase <- tickCredits dt return (Just $ ms & mainPhase .~ newPhase) Help -> do newPhase <- tickHelp dt return (Just $ ms & mainPhase .~ newPhase) Paused ps -> do newPhase <- tickPaused dt ps return (Just $ ms & mainPhase .~ newPhase) CountingDown cds -> do newPhase <- tickCountingDown dt (ms ^. gameAssets) cds return (Just $ ms & mainPhase .~ newPhase) Game gs -> do newPhase <- tickGame dt (ms ^. gameAssets) gs return (Just $ ms & mainPhase .~ newPhase) GameOver gos -> do newPhase <- tickGameOver dt gos return (Just $ ms & mainPhase .~ newPhase) render :: SDL.Renderer -> MainState -> IO () render renderer ms = case ms ^. mainPhase of Intro is -> renderIntro renderer (ms ^. gameAssets) is MainMenu mms -> renderMainMenu renderer (ms ^. gameAssets) mms Credits -> renderCredits renderer (ms ^. gameAssets) Help -> renderHelp renderer (ms ^. gameAssets) Paused ps -> renderPaused renderer (ms ^. gameAssets) ps CountingDown cds -> renderCountingDown renderer (ms ^. gameAssets) cds Game gs -> renderGame renderer (ms ^. gameAssets) gs (0, 0) GameOver gos -> renderGameOver renderer (ms ^. gameAssets) gos
ac083e40a3e9680b4f38b574fa6ce6973180d3b232faa8e0db259302cc167563
kmi/irs
xpath-parser.lisp
(in-package :kmi.vt.xpath-mini) (defparser xpath-parser ((start PathExpr) $1) PathExpr : : = ( " / " ? ) | ( " // " ) | ((PathExpr :/) `(apply-leading-/ :/)) ((PathExpr :/ RelativePathExpr) `(apply-leading-/ ,$2)) ((PathExpr ://) `(apply-leading-//)) ((PathExpr :// RelativePathExpr) `(apply-leading-// ,$2)) ((PathExpr RelativePathExpr) $1) : : = StepExpr ( ( " / " | " // " ) StepExpr ) * ((RelativePathExpr StepExpr) $1) ((RelativePathExpr StepExpr :/ RelativePathExpr) `(,$1 (apply-inner-/ ,$3))) ((RelativePathExpr StepExpr :// RelativePathExpr) `(,$1 (apply-inner-// ,$3))) ;StepExpr ::= AxisStep | FilterExpr ((StepExpr AxisStep) $1) ((StepExpr FilterExpr) $1) AxisStep : : = ( ForwardStep | ReverseStep ) PredicateList ((AxisStep ForwardStep) $1) ;.. ( ( AxisStep ReverseStep ) $ 1 ) ; .. ForwardStep : : = ( ForwardAxis NodeTest ) | AbbrevForwardStep ((ForwardStep ForwardAxis NodeTest) `(,$1 ,$2)) ((ForwardStep AbbrevForwardStep) $1) ;ForwardAxis ::= <"child" "::"> ;| <"descendant" "::"> ;| <"attribute" "::"> ;| <"self" "::"> ;| <"descendant-or-self" "::"> ;| <"following-sibling" "::"> ;| <"following" "::"> ;| <"namespace" "::"> ((ForwardAxis :child) 'apply-child) ((ForwardAxis :attribute) 'apply-attribute) ;.. AbbrevForwardStep : : = " @ " ? NodeTest ((AbbrevForwardStep :@ NodeTest) `(apply-attribute ,$2)) ((AbbrevForwardStep NodeTest) `(apply-child ,$1)) ;.. : : = ( ReverseAxis NodeTest ) | AbbrevReverseStep NodeTest : : = KindTest | ((NodeTest NameTest) $1) ((NodeTest KindTest) $1) : : = QName | Wildcard ;QName ::= [-xml-names/#NT-QName] ((NameTest :qname) $1) ((NameTest Wildcard) $1) ;Wildcard ::= "*" ;| <NCName ":" "*"> ;| <"*" ":" NCName> ((Wildcard :*) "*") ;.. : : = DocumentTest | ElementTest | AttributeTest ;| SchemaElementTest ;| SchemaAttributeTest | PITest | CommentTest ;| TextTest | AnyKindTest ((KindTest TextTest) $1) ;.. ;TextTest ::= <"text" "("> ")" ((TextTest :text) $1) FilterExpr : : = PrimaryExpr PredicateList ! ! ! ! ! ! ! ! ! ! ! ! ! ! 1Modified ! ! ! ((FilterExpr StepExpr PredicateList) `(,$1 ,$2)) ;PredicateList ::= Predicate* ((PredicateList Predicate) $1) ((PredicateList Predicate PredicateList) `(,$1 ,$2)) Predicate : : = " [ " " ] " ! ! ! ! ! ! ! ! ! ! ! 11for now only numbers ! ! ! ! ((Predicate :[ :num :]) `(apply-predicate-begin ,$2 apply-predicate-end)) ) ;(parse-xpath "//child::toto") ;(parse-xpath "//@toto") ;(parse-xpath "//toto") ;(parse-xpath "//child::toto") ;(parse-xpath "//child::toto/@tata") ;(parse-xpath "/child::toto/tata") ;(parse-xpath "//toto/tata") ;(parse-xpath "//ontology") ;(parse-xpath "//ontology/text()") (defclass scanner () ((ch :accessor ch :initform nil :documentation "the character being parsed") (oldch :accessor oldch :initform nil :documentation "the last parsed character") (chars :accessor chars :initform "" :documentation "the representation of the lexem (if more than one possible, ex:variables)") (terminals :initform nil)) (:documentation "generic scanner (lexer) class")) (defclass xpath-scanner (scanner) ((position :accessor pos :initform 0 :documentation "position in the string being parsed, 0 based") (in :accessor in :initarg :expression :initform "" :documentation "string which contains the xpath") (terminals :initform '(;PathExpr ("/" :/) ("//" ://) ;ForwardAxis ("child::" :child) ("attribute::" :attribute) ;... AbbrevForwardStep ("@" :@) ;ReverseAxis ("parent::" :parent) ;... ;AbbrevReverseStep (".." :..) ;Wildcard ("*" :*) ;Predicate ("[" :[) ("]" :]) ))) (:documentation "scanner (lexer) for xpath")) ( ( make - instance ' xpath - scanner : expression " / " ) ) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ;(describe xp/) ( describe xp// ) ;(slot-value xp/ 'ch) (defgeneric scan-get-terminal (scanner s) (:documentation "gets the terminal from the terminals association list") (:method ((sc scanner) s) (with-slots (terminals) sc (or (cadr (assoc s terminals :test #'string-equal)) :unknown)))) ;(scan-get-terminal xp// "/") ;(scan-get-terminal xp// "child::") (defgeneric next-token (scanner) (:documentation "gets the next token and avoids whitespace and comments") (:method ((sc xpath-scanner)) (if (next-ch sc) (read-token sc) :eoi))) (defparameter *alphanum-chars* (append (loop for char across "abcdefghijklmnopqrstuvwxyz" collecting char into lc collecting (char-upcase char) into uc finally (return (append lc uc))) (loop for char across "0123456789" collecting char) '(#\: #\( #\) #\-))) (defgeneric read-token (scanner) (:documentation "reads next token without whitespace") (:method ((sc xpath-scanner)) (with-slots (ch chars) sc (setf chars "") (cond ((eql ch #\/) (if (and (peek-next-ch sc) (char-equal #\/ (peek-next-ch sc))) (progn (next-ch sc) (setf chars "//") (scan-get-terminal sc chars)) (progn (setf chars "/") (scan-get-terminal sc chars)))) ((member ch *alphanum-chars*) (progn (setf chars (make-array 0 ;in order to use #'vector-push-extend :element-type 'character :fill-pointer 0 :adjustable t)) (vector-push-extend ch chars) (do ((n-ch (peek-next-ch sc) (progn (vector-push-extend n-ch chars) (next-ch sc) (peek-next-ch sc)))) ((or (not n-ch) (not (member n-ch *alphanum-chars*)) (char-equal n-ch #\:)) )) ;(print chars) (cond ((and (peek-next-ch sc) (char-equal (peek-next-ch sc) #\:)) ;test if "::" at the end (progn (next-ch sc) (next-ch sc) (vector-push-extend #\: chars) (vector-push-extend #\: chars) ;(print chars) (scan-get-terminal sc chars))) ((string-equal chars "text()") :text) ((parse-integer chars :junk-allowed t) :num ) (t :qname)))) ((member ch '(#\* #\@ #\[ #\])) (progn (setf chars ch) (scan-get-terminal sc chars))) (t :unknown))))) ;(parse-xpath "//child::*") ;(parse-xpath "//child::*") ;(parse-xpath "//child::toto[1]") ;(parse-xpath "//@toto") ( reverse ( subseq ( reverse " //toto : : " ) 2 ) ) ( ( make - instance ' xpath - scanner : expression " / " ) ) ;(next-token xp/) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( next - token xp// ) (defgeneric next-ch (scanner) (:documentation "puts next char in ch and updates position") (:method ((sc xpath-scanner)) (with-slots (ch oldch position in) sc (setf oldch ch) (if (< position (length in)) (progn (setf ch (char in position)) (incf position) ch) nil)))) ( ( make - instance ' xpath - scanner : expression " / " ) ) ;(next-ch xp/) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( next - ch xp// ) ( describe xp// ) (defgeneric peek-next-ch (scanner) (:documentation "just looks at next char and returns it") (:method ((sc xpath-scanner)) (with-slots (position in) sc (when (< position (length in)) (char in position))))) ;(peek-next-ch xp/) ( peek - next - ch xp// ) ;;; The main function -- note bindings of globals (these are exported from the parsergen package ) . (defun lex-xpath (sc) (let ((token (next-token sc))) (values token (chars sc)))) ( ( make - instance ' xpath - scanner : expression " / " ) ) ;(lex-xpath xp/) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( lex - xpath xp// ) (defun parse-xpath (input) "parses an xpath string and returns a list of actions (yeah, kind of minimal AST)" (list-flatten (let ((sc (make-instance 'xpath-scanner :expression input))) (xpath-parser #'(lambda () (lex-xpath sc)))))) (defun apply-xpath (xpath sequence) "executes the xpath instructions" (let ((op1 (first xpath)) (rest-path (rest xpath))) ;; XXX This should not be here! ;; (declare (special APPLY-LEADING-/ APPLY-CHILD APPLY-INNER-/ APPLY-ATTRIBUTE )) (if (not op1) sequence ;if path expression empty return sequence (ccase op1 (APPLY-LEADING-/ ( when ( : parent sequence ) ( error " not top level , can not apply lading / " ) ) (apply-xpath rest-path (apply *APPLY-LEADING-/* (list sequence)))) (APPLY-CHILD (let ((nodetest (first rest-path))) (unless nodetest (error "forward step without specifier")) (apply-xpath (cdr rest-path) (apply *APPLY-CHILD* nodetest (list sequence))))) (APPLY-INNER-/ (apply-xpath rest-path sequence)) (APPLY-ATTRIBUTE (let ((attrtest (first rest-path))) (unless attrtest (error "attribute test without specifier")) (apply-xpath (cdr rest-path) (apply *APPLY-ATTRIBUTE* attrtest (list sequence))))) (APPLY-PREDICATE-BEGIN ;for now only numerical prediactes ;-) (let ((predicate (1- (parse-integer (first rest-path))))) (when (< predicate 0 ) (error "index below 0!!")) (when (>= predicate (length sequence)) (error "index too large!!")) (apply-xpath (cddr rest-path) (elt sequence predicate)))))))) (defun xp (xpath sequence) "parses and executes xpath expressions" (apply-xpath (parse-xpath xpath) sequence))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/src/xpath-mini/xpath-parser.lisp
lisp
StepExpr ::= AxisStep | FilterExpr .. .. ForwardAxis ::= <"child" "::"> | <"descendant" "::"> | <"attribute" "::"> | <"self" "::"> | <"descendant-or-self" "::"> | <"following-sibling" "::"> | <"following" "::"> | <"namespace" "::"> .. .. QName ::= [-xml-names/#NT-QName] Wildcard ::= "*" | <NCName ":" "*"> | <"*" ":" NCName> .. | SchemaElementTest | SchemaAttributeTest | TextTest .. TextTest ::= <"text" "("> ")" PredicateList ::= Predicate* (parse-xpath "//child::toto") (parse-xpath "//@toto") (parse-xpath "//toto") (parse-xpath "//child::toto") (parse-xpath "//child::toto/@tata") (parse-xpath "/child::toto/tata") (parse-xpath "//toto/tata") (parse-xpath "//ontology") (parse-xpath "//ontology/text()") PathExpr ForwardAxis ... ReverseAxis ... AbbrevReverseStep Wildcard Predicate (describe xp/) (slot-value xp/ 'ch) (scan-get-terminal xp// "/") (scan-get-terminal xp// "child::") in order to use #'vector-push-extend (print chars) test if "::" at the end (print chars) (parse-xpath "//child::*") (parse-xpath "//child::*") (parse-xpath "//child::toto[1]") (parse-xpath "//@toto") (next-token xp/) (next-ch xp/) (peek-next-ch xp/) The main function -- note bindings of globals (these (lex-xpath xp/) XXX This should not be here! (declare (special APPLY-LEADING-/ APPLY-CHILD APPLY-INNER-/ APPLY-ATTRIBUTE )) if path expression empty return sequence for now only numerical prediactes ;-)
(in-package :kmi.vt.xpath-mini) (defparser xpath-parser ((start PathExpr) $1) PathExpr : : = ( " / " ? ) | ( " // " ) | ((PathExpr :/) `(apply-leading-/ :/)) ((PathExpr :/ RelativePathExpr) `(apply-leading-/ ,$2)) ((PathExpr ://) `(apply-leading-//)) ((PathExpr :// RelativePathExpr) `(apply-leading-// ,$2)) ((PathExpr RelativePathExpr) $1) : : = StepExpr ( ( " / " | " // " ) StepExpr ) * ((RelativePathExpr StepExpr) $1) ((RelativePathExpr StepExpr :/ RelativePathExpr) `(,$1 (apply-inner-/ ,$3))) ((RelativePathExpr StepExpr :// RelativePathExpr) `(,$1 (apply-inner-// ,$3))) ((StepExpr AxisStep) $1) ((StepExpr FilterExpr) $1) AxisStep : : = ( ForwardStep | ReverseStep ) PredicateList ForwardStep : : = ( ForwardAxis NodeTest ) | AbbrevForwardStep ((ForwardStep ForwardAxis NodeTest) `(,$1 ,$2)) ((ForwardStep AbbrevForwardStep) $1) ((ForwardAxis :child) 'apply-child) AbbrevForwardStep : : = " @ " ? NodeTest ((AbbrevForwardStep :@ NodeTest) `(apply-attribute ,$2)) : : = ( ReverseAxis NodeTest ) | AbbrevReverseStep NodeTest : : = KindTest | ((NodeTest NameTest) $1) ((NodeTest KindTest) $1) : : = QName | Wildcard ((NameTest :qname) $1) ((NameTest Wildcard) $1) : : = DocumentTest | ElementTest | AttributeTest | PITest | CommentTest | AnyKindTest ((TextTest :text) $1) FilterExpr : : = PrimaryExpr PredicateList ! ! ! ! ! ! ! ! ! ! ! ! ! ! 1Modified ! ! ! ((FilterExpr StepExpr PredicateList) `(,$1 ,$2)) ((PredicateList Predicate) $1) ((PredicateList Predicate PredicateList) `(,$1 ,$2)) Predicate : : = " [ " " ] " ! ! ! ! ! ! ! ! ! ! ! 11for now only numbers ! ! ! ! ((Predicate :[ :num :]) `(apply-predicate-begin ,$2 apply-predicate-end)) ) (defclass scanner () ((ch :accessor ch :initform nil :documentation "the character being parsed") (oldch :accessor oldch :initform nil :documentation "the last parsed character") (chars :accessor chars :initform "" :documentation "the representation of the lexem (if more than one possible, ex:variables)") (terminals :initform nil)) (:documentation "generic scanner (lexer) class")) (defclass xpath-scanner (scanner) ((position :accessor pos :initform 0 :documentation "position in the string being parsed, 0 based") (in :accessor in :initarg :expression :initform "" :documentation "string which contains the xpath") (terminals ("/" :/) ("//" ://) AbbrevForwardStep ("@" :@) (".." :..) ("*" :*) ("[" :[) ("]" :]) ))) (:documentation "scanner (lexer) for xpath")) ( ( make - instance ' xpath - scanner : expression " / " ) ) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( describe xp// ) (defgeneric scan-get-terminal (scanner s) (:documentation "gets the terminal from the terminals association list") (:method ((sc scanner) s) (with-slots (terminals) sc (or (cadr (assoc s terminals :test #'string-equal)) :unknown)))) (defgeneric next-token (scanner) (:documentation "gets the next token and avoids whitespace and comments") (:method ((sc xpath-scanner)) (if (next-ch sc) (read-token sc) :eoi))) (defparameter *alphanum-chars* (append (loop for char across "abcdefghijklmnopqrstuvwxyz" collecting char into lc collecting (char-upcase char) into uc finally (return (append lc uc))) (loop for char across "0123456789" collecting char) '(#\: #\( #\) #\-))) (defgeneric read-token (scanner) (:documentation "reads next token without whitespace") (:method ((sc xpath-scanner)) (with-slots (ch chars) sc (setf chars "") (cond ((eql ch #\/) (if (and (peek-next-ch sc) (char-equal #\/ (peek-next-ch sc))) (progn (next-ch sc) (setf chars "//") (scan-get-terminal sc chars)) (progn (setf chars "/") (scan-get-terminal sc chars)))) ((member ch *alphanum-chars*) (progn :element-type 'character :fill-pointer 0 :adjustable t)) (vector-push-extend ch chars) (do ((n-ch (peek-next-ch sc) (progn (vector-push-extend n-ch chars) (next-ch sc) (peek-next-ch sc)))) ((or (not n-ch) (not (member n-ch *alphanum-chars*)) (char-equal n-ch #\:)) )) (cond (progn (next-ch sc) (next-ch sc) (vector-push-extend #\: chars) (vector-push-extend #\: chars) (scan-get-terminal sc chars))) ((string-equal chars "text()") :text) ((parse-integer chars :junk-allowed t) :num ) (t :qname)))) ((member ch '(#\* #\@ #\[ #\])) (progn (setf chars ch) (scan-get-terminal sc chars))) (t :unknown))))) ( reverse ( subseq ( reverse " //toto : : " ) 2 ) ) ( ( make - instance ' xpath - scanner : expression " / " ) ) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( next - token xp// ) (defgeneric next-ch (scanner) (:documentation "puts next char in ch and updates position") (:method ((sc xpath-scanner)) (with-slots (ch oldch position in) sc (setf oldch ch) (if (< position (length in)) (progn (setf ch (char in position)) (incf position) ch) nil)))) ( ( make - instance ' xpath - scanner : expression " / " ) ) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( next - ch xp// ) ( describe xp// ) (defgeneric peek-next-ch (scanner) (:documentation "just looks at next char and returns it") (:method ((sc xpath-scanner)) (with-slots (position in) sc (when (< position (length in)) (char in position))))) ( peek - next - ch xp// ) are exported from the parsergen package ) . (defun lex-xpath (sc) (let ((token (next-token sc))) (values token (chars sc)))) ( ( make - instance ' xpath - scanner : expression " / " ) ) ( setf xp// ( make - instance ' xpath - scanner : expression " // " ) ) ( lex - xpath xp// ) (defun parse-xpath (input) "parses an xpath string and returns a list of actions (yeah, kind of minimal AST)" (list-flatten (let ((sc (make-instance 'xpath-scanner :expression input))) (xpath-parser #'(lambda () (lex-xpath sc)))))) (defun apply-xpath (xpath sequence) "executes the xpath instructions" (let ((op1 (first xpath)) (rest-path (rest xpath))) (ccase op1 (APPLY-LEADING-/ ( when ( : parent sequence ) ( error " not top level , can not apply lading / " ) ) (apply-xpath rest-path (apply *APPLY-LEADING-/* (list sequence)))) (APPLY-CHILD (let ((nodetest (first rest-path))) (unless nodetest (error "forward step without specifier")) (apply-xpath (cdr rest-path) (apply *APPLY-CHILD* nodetest (list sequence))))) (APPLY-INNER-/ (apply-xpath rest-path sequence)) (APPLY-ATTRIBUTE (let ((attrtest (first rest-path))) (unless attrtest (error "attribute test without specifier")) (apply-xpath (cdr rest-path) (apply *APPLY-ATTRIBUTE* attrtest (list sequence))))) (let ((predicate (1- (parse-integer (first rest-path))))) (when (< predicate 0 ) (error "index below 0!!")) (when (>= predicate (length sequence)) (error "index too large!!")) (apply-xpath (cddr rest-path) (elt sequence predicate)))))))) (defun xp (xpath sequence) "parses and executes xpath expressions" (apply-xpath (parse-xpath xpath) sequence))
6be2234797f08583bdbd50d8bfebecfc64d2264cd5b1ee48e541c02892fffcf7
BranchTaken/Hemlock
u256.ml
open RudimentsInt0 open RudimentsFunctions module T = struct module U = struct type t = {w0: u64; w1: u64; w2: u64; w3: u64} let word_length = 4L let init ~f = {w0=f 0L; w1=f 1L; w2=f 2L; w3=f 3L} let get i t = match i with | 0L -> t.w0 | 1L -> t.w1 | 2L -> t.w2 | 3L -> t.w3 | _ -> not_reached () end include U include Intw.MakeFU(U) end include T module UZ = Convert.Make_wU_wZ(T)(Zint) let trunc_of_zint = UZ.trunc_of_x let extend_to_zint = UZ.extend_to_x let narrow_of_zint_opt = UZ.narrow_of_x_opt let narrow_of_zint_hlt = UZ.narrow_of_x_hlt module UN = Convert.Make_wU_wN(T)(Nat) let trunc_of_nat = UN.trunc_of_u let extend_to_nat = UN.extend_to_u let narrow_of_nat_opt = UN.narrow_of_u_opt let narrow_of_nat_hlt = UN.narrow_of_u_hlt module UX512 = Convert.Make_wU_wX(T)(I512) let trunc_of_i512 = UX512.trunc_of_x let extend_to_i512 = UX512.extend_to_x let narrow_of_i512_opt = UX512.narrow_of_x_opt let narrow_of_i512_hlt = UX512.narrow_of_x_hlt module UU512 = Convert.Make_wU_wU(T)(U512) let trunc_of_u512 = UU512.trunc_of_u let extend_to_u512 = UU512.extend_to_u let narrow_of_u512_opt = UU512.narrow_of_u_opt let narrow_of_u512_hlt = UU512.narrow_of_u_hlt module UI256 = Convert.Make_wU_wI(T)(I256) let bits_of_i256 = UI256.bits_of_x let bits_to_i256 = UI256.bits_to_x let like_of_i256_opt = UI256.like_of_x_opt let like_to_i256_opt = UI256.like_to_x_opt let like_of_i256_hlt = UI256.like_of_x_hlt let like_to_i256_hlt = UI256.like_to_x_hlt
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/53da5c0d9cf0c94d58b4391735d917518eec67fa/bootstrap/src/basis/u256.ml
ocaml
open RudimentsInt0 open RudimentsFunctions module T = struct module U = struct type t = {w0: u64; w1: u64; w2: u64; w3: u64} let word_length = 4L let init ~f = {w0=f 0L; w1=f 1L; w2=f 2L; w3=f 3L} let get i t = match i with | 0L -> t.w0 | 1L -> t.w1 | 2L -> t.w2 | 3L -> t.w3 | _ -> not_reached () end include U include Intw.MakeFU(U) end include T module UZ = Convert.Make_wU_wZ(T)(Zint) let trunc_of_zint = UZ.trunc_of_x let extend_to_zint = UZ.extend_to_x let narrow_of_zint_opt = UZ.narrow_of_x_opt let narrow_of_zint_hlt = UZ.narrow_of_x_hlt module UN = Convert.Make_wU_wN(T)(Nat) let trunc_of_nat = UN.trunc_of_u let extend_to_nat = UN.extend_to_u let narrow_of_nat_opt = UN.narrow_of_u_opt let narrow_of_nat_hlt = UN.narrow_of_u_hlt module UX512 = Convert.Make_wU_wX(T)(I512) let trunc_of_i512 = UX512.trunc_of_x let extend_to_i512 = UX512.extend_to_x let narrow_of_i512_opt = UX512.narrow_of_x_opt let narrow_of_i512_hlt = UX512.narrow_of_x_hlt module UU512 = Convert.Make_wU_wU(T)(U512) let trunc_of_u512 = UU512.trunc_of_u let extend_to_u512 = UU512.extend_to_u let narrow_of_u512_opt = UU512.narrow_of_u_opt let narrow_of_u512_hlt = UU512.narrow_of_u_hlt module UI256 = Convert.Make_wU_wI(T)(I256) let bits_of_i256 = UI256.bits_of_x let bits_to_i256 = UI256.bits_to_x let like_of_i256_opt = UI256.like_of_x_opt let like_to_i256_opt = UI256.like_to_x_opt let like_of_i256_hlt = UI256.like_of_x_hlt let like_to_i256_hlt = UI256.like_to_x_hlt
d4387c5afcf116dff193a806a21a071870b36bab4ef97e44df9f0e479d19acc4
melange-re/melange
ounit_hashtbl_tests.ml
let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: )) let ( =~ ) = OUnit.assert_equal ~printer:Ounit_test_util.dump let suites = __FILE__ >::: [ (* __LOC__ >:: begin fun _ -> *) (* let h = Hash_string.create 0 in *) (* let accu key = *) Hash_string.replace_or_init h key succ 1 in let count = 1000 in (* for i = 0 to count - 1 do *) (* Array.iter accu [|"a";"b";"c";"d";"e";"f"|] *) (* done; *) Hash_string.length h = ~ 6 ; ( fun _ v - > v = ~ count ) h (* end; *) ( "add semantics " >:: fun _ -> let h = Hash_string.create 0 in let count = 1000 in for _ = 0 to 1 do for i = 0 to count - 1 do Hash_string.add h (string_of_int i) i done done; Hash_string.length h =~ 2 * count ); ( "replace semantics" >:: fun _ -> let h = Hash_string.create 0 in let count = 1000 in for _ = 0 to 1 do for i = 0 to count - 1 do Hash_string.replace h (string_of_int i) i done done; Hash_string.length h =~ count ); ( __LOC__ >:: fun _ -> let h = Hash_string.create 0 in let count = 10 in for i = 0 to count - 1 do Hash_string.replace h (string_of_int i) i done; let xs = Hash_string.to_list h (fun k _ -> k) in let ys = List.sort compare xs in ys =~ [ "0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9" ] ); ]
null
https://raw.githubusercontent.com/melange-re/melange/a8f6ddf9f46d51ffd1dde6095f655a8ca9fb6aa5/jscomp/ounit_tests/ounit_hashtbl_tests.ml
ocaml
__LOC__ >:: begin fun _ -> let h = Hash_string.create 0 in let accu key = for i = 0 to count - 1 do Array.iter accu [|"a";"b";"c";"d";"e";"f"|] done; end;
let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: )) let ( =~ ) = OUnit.assert_equal ~printer:Ounit_test_util.dump let suites = __FILE__ >::: [ Hash_string.replace_or_init h key succ 1 in let count = 1000 in Hash_string.length h = ~ 6 ; ( fun _ v - > v = ~ count ) h ( "add semantics " >:: fun _ -> let h = Hash_string.create 0 in let count = 1000 in for _ = 0 to 1 do for i = 0 to count - 1 do Hash_string.add h (string_of_int i) i done done; Hash_string.length h =~ 2 * count ); ( "replace semantics" >:: fun _ -> let h = Hash_string.create 0 in let count = 1000 in for _ = 0 to 1 do for i = 0 to count - 1 do Hash_string.replace h (string_of_int i) i done done; Hash_string.length h =~ count ); ( __LOC__ >:: fun _ -> let h = Hash_string.create 0 in let count = 10 in for i = 0 to count - 1 do Hash_string.replace h (string_of_int i) i done; let xs = Hash_string.to_list h (fun k _ -> k) in let ys = List.sort compare xs in ys =~ [ "0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9" ] ); ]
94080fc3f3f790a7244fdbd0425cfcc8e1bb716436e0abda10033f1535d63cd4
cac-t-u-s/om-sharp
chord-editor.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ; ;============================================================================ File author : ;============================================================================ (in-package :om) ;;;======================================================================== CHORD EDITOR ;;;======================================================================== (defclass chord-editor (score-editor play-editor-mixin) ((temp-arp-chord :accessor temp-arp-chord :initform nil))) (defmethod object-has-editor ((self chord)) t) (defmethod get-editor-class ((self chord)) 'chord-editor) (defmethod object-default-edition-params ((self chord)) (append (call-next-method) '((:y-shift 4) (:chord-mode :chord)))) ;;; chord-mode: ;;; - chord = play the chord (with offsets if there are offsets) ;;; - arp-up = play arpegio up - arp - up = play down ;;; - arp-order = play arpegio in order (defmethod make-editor-window-contents ((editor chord-editor)) (let* ((panel (om-make-view 'score-view :size (omp 50 100) :direct-draw t :bg-color (om-def-color :white) :scrollbars nil :editor editor)) (bottom-area (make-score-display-params-controls editor))) (set-g-component editor :main-panel panel) (om-make-layout 'om-row-layout :ratios '(99 1) :subviews (list (om-make-layout 'om-column-layout :ratios '(99 1) :subviews (list panel bottom-area)) (call-next-method))) )) (defmethod make-score-display-params-controls ((editor chord-editor)) (let ((text-h 16) (control-h 24)) (om-make-layout 'om-row-layout :subviews (list (call-next-method) :separator (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "play-mode" :size (omp 60 text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items '(:chord :arp-up :arp-down :arp-order) :size (omp 80 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :chord-mode) :di-action #'(lambda (list) (editor-set-edit-param editor :chord-mode (om-get-selected-item list)) (update-arp-chord editor) (editor-invalidate-views editor) )))) nil )))) (defmethod update-to-editor ((editor chord-editor) (from t)) (call-next-method) (editor-invalidate-views editor)) (defmethod editor-invalidate-views ((self chord-editor)) (call-next-method) (om-invalidate-view (get-g-component self :main-panel))) ;;; called at add-click (defmethod get-chord-from-editor-click ((self chord-editor) position) (declare (ignore position)) (if (in-arp-mode self) (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (object-value self))) (defmethod editor-key-action ((self chord-editor) key) (if (and (in-arp-mode self) (not (member key '(#\Space)))) ;; a few keys are authorized (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (call-next-method))) (defmethod score-editor-delete ((self chord-editor) element) (let ((c (object-value self))) (if (equal element c) (setf (notes c) nil) (setf (notes c) (remove element (notes c)))))) (defmethod move-editor-selection ((self chord-editor) &key (dx 0) (dy 0)) (declare (ignore dx)) (let* ((chord (object-value self)) (step (or (step-from-scale (editor-get-edit-param self :scale)) 100)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (unless (zerop dy) (loop for n in notes do (setf (midic n) (+ (midic n) (* dy step))))) )) (defmethod score-editor-change-selection-durs ((self chord-editor) delta) (let* ((chord (object-value self)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (loop for n in notes do (setf (dur n) (max (abs delta) (round (+ (dur n) delta))))) )) ;;; SPECIAL/SIMPLE CASE FOR CHORD-EDITOR (defmethod draw-score-object-in-editor-view ((editor chord-editor) view unit) (if (and (in-arp-mode editor) (temp-arp-chord editor)) ;;; draw the arp-chard (actually it's a simple chord-seq) (loop for chord in (chords (temp-arp-chord editor)) do (setf (b-box chord) (draw-chord chord (date chord) 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :selection (if (find chord (selection editor)) T (selection editor)) :time-function #'(lambda (time) (let ((dur-max (get-obj-dur (temp-arp-chord editor)))) (+ 100 (* (- (w view) 150) (/ time dur-max))) )) :build-b-boxes t )) ) (let ((chord (object-value editor))) (setf (b-box chord) (draw-chord chord 0 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :draw-dur-ruler t :selection (if (find chord (selection editor)) T (selection editor)) :offsets (editor-get-edit-param editor :offsets) :time-function #'(lambda (time) (if (notes chord) (let ((dur-max (loop for n in (notes chord) maximize (+ (dur n) (offset n))))) (+ (/ (w view) 2) (* (/ (- (w view) 80) 2) (/ time dur-max))) ) ;;; no contents anyway... (/ (w view) 2) )) :build-b-boxes t )) ; (draw-b-box chord) ) )) ;;;==================================== ;;; PLAY ;;;==================================== (defmethod update-arp-chord ((self chord-editor)) (setf (temp-arp-chord self) (make-arp-chord (object-value self) (editor-get-edit-param self :chord-mode)))) (defmethod in-arp-mode ((self chord-editor)) (find (editor-get-edit-param self :chord-mode) '(:arp-order :arp-up :arp-down))) (defmethod init-editor :after ((self chord-editor)) (update-arp-chord self)) (defun make-arp-chord (chord mode) (case mode (:arp-order (make-instance 'chord-seq :lmidic (lmidic chord) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-up (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'<) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-down (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'>) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (t chord) )) (defmethod get-obj-to-play ((self chord-editor)) (or (temp-arp-chord self) (object-value self))) (defmethod start-editor-callback ((self chord-editor)) (update-arp-chord self) (call-next-method)) (defmethod editor-pause ((self chord-editor)) (editor-stop self)) ;;; play from box (defmethod play-obj-from-value ((val chord) box) (make-arp-chord val (get-edit-param box :chord-mode)))
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/6a9e50f3fc4f42ae881247996d249675b700d0cf/src/packages/score/editor/chord-editor.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ============================================================================ ============================================================================ ======================================================================== ======================================================================== chord-mode: - chord = play the chord (with offsets if there are offsets) - arp-up = play arpegio up - arp-order = play arpegio in order called at add-click a few keys are authorized SPECIAL/SIMPLE CASE FOR CHORD-EDITOR draw the arp-chard (actually it's a simple chord-seq) no contents anyway... (draw-b-box chord) ==================================== PLAY ==================================== play from box
File author : (in-package :om) CHORD EDITOR (defclass chord-editor (score-editor play-editor-mixin) ((temp-arp-chord :accessor temp-arp-chord :initform nil))) (defmethod object-has-editor ((self chord)) t) (defmethod get-editor-class ((self chord)) 'chord-editor) (defmethod object-default-edition-params ((self chord)) (append (call-next-method) '((:y-shift 4) (:chord-mode :chord)))) - arp - up = play down (defmethod make-editor-window-contents ((editor chord-editor)) (let* ((panel (om-make-view 'score-view :size (omp 50 100) :direct-draw t :bg-color (om-def-color :white) :scrollbars nil :editor editor)) (bottom-area (make-score-display-params-controls editor))) (set-g-component editor :main-panel panel) (om-make-layout 'om-row-layout :ratios '(99 1) :subviews (list (om-make-layout 'om-column-layout :ratios '(99 1) :subviews (list panel bottom-area)) (call-next-method))) )) (defmethod make-score-display-params-controls ((editor chord-editor)) (let ((text-h 16) (control-h 24)) (om-make-layout 'om-row-layout :subviews (list (call-next-method) :separator (om-make-layout 'om-row-layout :align :center :subviews (list (om-make-di 'om-simple-text :text "play-mode" :size (omp 60 text-h) :font (om-def-font :gui)) (om-make-di 'om-popup-list :items '(:chord :arp-up :arp-down :arp-order) :size (omp 80 control-h) :font (om-def-font :gui) :value (editor-get-edit-param editor :chord-mode) :di-action #'(lambda (list) (editor-set-edit-param editor :chord-mode (om-get-selected-item list)) (update-arp-chord editor) (editor-invalidate-views editor) )))) nil )))) (defmethod update-to-editor ((editor chord-editor) (from t)) (call-next-method) (editor-invalidate-views editor)) (defmethod editor-invalidate-views ((self chord-editor)) (call-next-method) (om-invalidate-view (get-g-component self :main-panel))) (defmethod get-chord-from-editor-click ((self chord-editor) position) (declare (ignore position)) (if (in-arp-mode self) (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (object-value self))) (defmethod editor-key-action ((self chord-editor) key) (if (and (in-arp-mode self) (om-beep-msg "Chord-editor can not be edited in 'arp' modes") (call-next-method))) (defmethod score-editor-delete ((self chord-editor) element) (let ((c (object-value self))) (if (equal element c) (setf (notes c) nil) (setf (notes c) (remove element (notes c)))))) (defmethod move-editor-selection ((self chord-editor) &key (dx 0) (dy 0)) (declare (ignore dx)) (let* ((chord (object-value self)) (step (or (step-from-scale (editor-get-edit-param self :scale)) 100)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (unless (zerop dy) (loop for n in notes do (setf (midic n) (+ (midic n) (* dy step))))) )) (defmethod score-editor-change-selection-durs ((self chord-editor) delta) (let* ((chord (object-value self)) (notes (if (find chord (selection self)) (notes chord) (selection self)))) (unless (equal (editor-play-state self) :stop) (close-open-chords-at-time (list chord) (get-obj-time chord) chord)) (loop for n in notes do (setf (dur n) (max (abs delta) (round (+ (dur n) delta))))) )) (defmethod draw-score-object-in-editor-view ((editor chord-editor) view unit) (if (and (in-arp-mode editor) (temp-arp-chord editor)) (loop for chord in (chords (temp-arp-chord editor)) do (setf (b-box chord) (draw-chord chord (date chord) 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :selection (if (find chord (selection editor)) T (selection editor)) :time-function #'(lambda (time) (let ((dur-max (get-obj-dur (temp-arp-chord editor)))) (+ 100 (* (- (w view) 150) (/ time dur-max))) )) :build-b-boxes t )) ) (let ((chord (object-value editor))) (setf (b-box chord) (draw-chord chord 0 0 (editor-get-edit-param editor :y-shift) 0 0 (w view) (h view) (editor-get-edit-param editor :font-size) :staff (editor-get-edit-param editor :staff) :scale (editor-get-edit-param editor :scale) :draw-chans (editor-get-edit-param editor :channel-display) :draw-vels (editor-get-edit-param editor :velocity-display) :draw-ports (editor-get-edit-param editor :port-display) :draw-durs (editor-get-edit-param editor :duration-display) :draw-dur-ruler t :selection (if (find chord (selection editor)) T (selection editor)) :offsets (editor-get-edit-param editor :offsets) :time-function #'(lambda (time) (if (notes chord) (let ((dur-max (loop for n in (notes chord) maximize (+ (dur n) (offset n))))) (+ (/ (w view) 2) (* (/ (- (w view) 80) 2) (/ time dur-max))) ) (/ (w view) 2) )) :build-b-boxes t )) ) )) (defmethod update-arp-chord ((self chord-editor)) (setf (temp-arp-chord self) (make-arp-chord (object-value self) (editor-get-edit-param self :chord-mode)))) (defmethod in-arp-mode ((self chord-editor)) (find (editor-get-edit-param self :chord-mode) '(:arp-order :arp-up :arp-down))) (defmethod init-editor :after ((self chord-editor)) (update-arp-chord self)) (defun make-arp-chord (chord mode) (case mode (:arp-order (make-instance 'chord-seq :lmidic (lmidic chord) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-up (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'<) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (:arp-down (make-instance 'chord-seq :lmidic (sort (lmidic chord) #'>) :lchan (lchan chord) :lport (lport chord) :lvel (lvel chord) :lonset '(0 200) :ldur 200)) (t chord) )) (defmethod get-obj-to-play ((self chord-editor)) (or (temp-arp-chord self) (object-value self))) (defmethod start-editor-callback ((self chord-editor)) (update-arp-chord self) (call-next-method)) (defmethod editor-pause ((self chord-editor)) (editor-stop self)) (defmethod play-obj-from-value ((val chord) box) (make-arp-chord val (get-edit-param box :chord-mode)))
1ef1f145c6706c030f4f84c76e94b4218e0e83ac0c91093ea6603138914bf8b4
maximedenes/native-coq
evar_tactics.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Tacmach open Names open Tacexpr open Termops val instantiate : int -> Tacinterp.interp_sign * Glob_term.glob_constr -> (identifier * hyp_location_flag, unit) location -> tactic val let_evar : name -> Term.types -> tactic
null
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/tactics/evar_tactics.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Tacmach open Names open Tacexpr open Termops val instantiate : int -> Tacinterp.interp_sign * Glob_term.glob_constr -> (identifier * hyp_location_flag, unit) location -> tactic val let_evar : name -> Term.types -> tactic
03a0a279c9b80fdb96cd614aed4b7cef20e83218fbbf238f55f605de0f2f0348
ocaml/dune
user_message.ml
module Style = struct type t = | Loc | Error | Warning | Kwd | Id | Prompt | Hint | Details | Ok | Debug | Success | Ansi_styles of Ansi_color.Style.t list end module Annots = struct include Univ_map.Make () let has_embedded_location = Key.create ~name:"has-embedded-location" Unit.to_dyn let needs_stack_trace = Key.create ~name:"needs-stack-trace" Unit.to_dyn end module Print_config = struct type t = Style.t -> Ansi_color.Style.t list let default : t = function | Loc -> [ `Bold ] | Error -> [ `Bold; `Fg_red ] | Warning -> [ `Bold; `Fg_magenta ] | Kwd -> [ `Bold; `Fg_blue ] | Id -> [ `Bold; `Fg_yellow ] | Prompt -> [ `Bold; `Fg_green ] | Hint -> [ `Italic; `Fg_white ] | Details -> [ `Dim; `Fg_white ] | Ok -> [ `Dim; `Fg_green ] | Debug -> [ `Underline; `Fg_bright_cyan ] | Success -> [ `Bold; `Fg_green ] | Ansi_styles l -> l end type t = { loc : Loc0.t option ; paragraphs : Style.t Pp.t list ; hints : Style.t Pp.t list ; annots : Annots.t } let compare { loc; paragraphs; hints; annots } t = let open Ordering.O in let= () = Option.compare Loc0.compare loc t.loc in let= () = List.compare paragraphs t.paragraphs ~compare:Poly.compare in let= () = List.compare hints t.hints ~compare:Poly.compare in Poly.compare annots t.annots let equal a b = Ordering.is_eq (compare a b) let make ?loc ?prefix ?(hints = []) ?(annots = Annots.empty) paragraphs = let paragraphs = match (prefix, paragraphs) with | None, l -> l | Some p, [] -> [ p ] | Some p, x :: l -> Pp.concat ~sep:Pp.space [ p; x ] :: l in { loc; hints; paragraphs; annots } let pp { loc; paragraphs; hints; annots = _ } = let open Pp.O in let paragraphs = match hints with | [] -> paragraphs | _ -> List.append paragraphs (List.map hints ~f:(fun hint -> Pp.tag Style.Hint (Pp.verbatim "Hint:") ++ Pp.space ++ hint)) in let paragraphs = List.map paragraphs ~f:Pp.box in let paragraphs = match loc with | None -> paragraphs | Some { Loc0.start; stop } -> let start_c = start.pos_cnum - start.pos_bol in let stop_c = stop.pos_cnum - start.pos_bol in Pp.box (Pp.tag Style.Loc (Pp.textf "File %S, line %d, characters %d-%d:" start.pos_fname start.pos_lnum start_c stop_c)) :: paragraphs in Pp.vbox (Pp.concat_map paragraphs ~sep:Pp.nop ~f:(fun pp -> Pp.seq pp Pp.cut)) let print ?(config = Print_config.default) t = Ansi_color.print (Pp.map_tags (pp t) ~f:config) let prerr ?(config = Print_config.default) t = Ansi_color.prerr (Pp.map_tags (pp t) ~f:config) (* As found here #OCaml *) let levenshtein_distance s t = let m = String.length s and n = String.length t in for all i and j , d.(i).(j ) will hold the distance between the first i characters of s and the first j characters of t first i characters of s and the first j characters of t *) let d = Array.make_matrix ~dimx:(m + 1) ~dimy:(n + 1) 0 in for i = 0 to m do the distance of any first string to an empty second string d.(i).(0) <- i done; for j = 0 to n do the distance of any second string to an empty first string d.(0).(j) <- j done; for j = 1 to n do for i = 1 to m do if s.[i - 1] = t.[j - 1] then d.(i).(j) <- d.(i - 1).(j - 1) (* no operation required *) else d.(i).(j) <- min (d.(i - 1).(j) + 1) (* a deletion *) (min (d.(i).(j - 1) + 1) (* an insertion *) (d.(i - 1).(j - 1) + 1) (* a substitution *)) done done; d.(m).(n) let did_you_mean s ~candidates = let candidates = List.filter candidates ~f:(fun candidate -> levenshtein_distance s candidate < 3) in match candidates with | [] -> [] | l -> [ Pp.textf "did you mean %s?" (String.enumerate_or l) ] let to_string t = let full_error = Format.asprintf "%a" Pp.to_fmt (pp { t with loc = None }) in match String.drop_prefix ~prefix:"Error: " full_error with | None -> full_error | Some error -> String.trim error let is_loc_none loc = match loc with | None -> true | Some loc -> loc = Loc0.none let has_embedded_location msg = Annots.mem msg.annots Annots.has_embedded_location let has_location msg = (not (is_loc_none msg.loc)) || has_embedded_location msg let needs_stack_trace msg = Annots.mem msg.annots Annots.needs_stack_trace
null
https://raw.githubusercontent.com/ocaml/dune/714626f4d408e5c71c24ba91d0d520588702ec52/otherlibs/stdune/src/user_message.ml
ocaml
As found here #OCaml no operation required a deletion an insertion a substitution
module Style = struct type t = | Loc | Error | Warning | Kwd | Id | Prompt | Hint | Details | Ok | Debug | Success | Ansi_styles of Ansi_color.Style.t list end module Annots = struct include Univ_map.Make () let has_embedded_location = Key.create ~name:"has-embedded-location" Unit.to_dyn let needs_stack_trace = Key.create ~name:"needs-stack-trace" Unit.to_dyn end module Print_config = struct type t = Style.t -> Ansi_color.Style.t list let default : t = function | Loc -> [ `Bold ] | Error -> [ `Bold; `Fg_red ] | Warning -> [ `Bold; `Fg_magenta ] | Kwd -> [ `Bold; `Fg_blue ] | Id -> [ `Bold; `Fg_yellow ] | Prompt -> [ `Bold; `Fg_green ] | Hint -> [ `Italic; `Fg_white ] | Details -> [ `Dim; `Fg_white ] | Ok -> [ `Dim; `Fg_green ] | Debug -> [ `Underline; `Fg_bright_cyan ] | Success -> [ `Bold; `Fg_green ] | Ansi_styles l -> l end type t = { loc : Loc0.t option ; paragraphs : Style.t Pp.t list ; hints : Style.t Pp.t list ; annots : Annots.t } let compare { loc; paragraphs; hints; annots } t = let open Ordering.O in let= () = Option.compare Loc0.compare loc t.loc in let= () = List.compare paragraphs t.paragraphs ~compare:Poly.compare in let= () = List.compare hints t.hints ~compare:Poly.compare in Poly.compare annots t.annots let equal a b = Ordering.is_eq (compare a b) let make ?loc ?prefix ?(hints = []) ?(annots = Annots.empty) paragraphs = let paragraphs = match (prefix, paragraphs) with | None, l -> l | Some p, [] -> [ p ] | Some p, x :: l -> Pp.concat ~sep:Pp.space [ p; x ] :: l in { loc; hints; paragraphs; annots } let pp { loc; paragraphs; hints; annots = _ } = let open Pp.O in let paragraphs = match hints with | [] -> paragraphs | _ -> List.append paragraphs (List.map hints ~f:(fun hint -> Pp.tag Style.Hint (Pp.verbatim "Hint:") ++ Pp.space ++ hint)) in let paragraphs = List.map paragraphs ~f:Pp.box in let paragraphs = match loc with | None -> paragraphs | Some { Loc0.start; stop } -> let start_c = start.pos_cnum - start.pos_bol in let stop_c = stop.pos_cnum - start.pos_bol in Pp.box (Pp.tag Style.Loc (Pp.textf "File %S, line %d, characters %d-%d:" start.pos_fname start.pos_lnum start_c stop_c)) :: paragraphs in Pp.vbox (Pp.concat_map paragraphs ~sep:Pp.nop ~f:(fun pp -> Pp.seq pp Pp.cut)) let print ?(config = Print_config.default) t = Ansi_color.print (Pp.map_tags (pp t) ~f:config) let prerr ?(config = Print_config.default) t = Ansi_color.prerr (Pp.map_tags (pp t) ~f:config) let levenshtein_distance s t = let m = String.length s and n = String.length t in for all i and j , d.(i).(j ) will hold the distance between the first i characters of s and the first j characters of t first i characters of s and the first j characters of t *) let d = Array.make_matrix ~dimx:(m + 1) ~dimy:(n + 1) 0 in for i = 0 to m do the distance of any first string to an empty second string d.(i).(0) <- i done; for j = 0 to n do the distance of any second string to an empty first string d.(0).(j) <- j done; for j = 1 to n do for i = 1 to m do if s.[i - 1] = t.[j - 1] then d.(i).(j) <- d.(i - 1).(j - 1) else d.(i).(j) <- min (min done done; d.(m).(n) let did_you_mean s ~candidates = let candidates = List.filter candidates ~f:(fun candidate -> levenshtein_distance s candidate < 3) in match candidates with | [] -> [] | l -> [ Pp.textf "did you mean %s?" (String.enumerate_or l) ] let to_string t = let full_error = Format.asprintf "%a" Pp.to_fmt (pp { t with loc = None }) in match String.drop_prefix ~prefix:"Error: " full_error with | None -> full_error | Some error -> String.trim error let is_loc_none loc = match loc with | None -> true | Some loc -> loc = Loc0.none let has_embedded_location msg = Annots.mem msg.annots Annots.has_embedded_location let has_location msg = (not (is_loc_none msg.loc)) || has_embedded_location msg let needs_stack_trace msg = Annots.mem msg.annots Annots.needs_stack_trace
976985a18f3d41555aa46430b59acf6fc8be3185880563ee3991bf32893ab292
cram2/cram
tdist.lisp
Regression test TDIST for GSLL ;; Copyright 2009 Distributed under the terms of the GNU General Public License ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 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 </>. (in-package :gsl) (lisp-unit:define-test tdist From randist / test.c (lisp-unit::assert-true (testpdf (lambda (r) (tdist-pdf r 1.75d0)) :tdist :nu 1.75d0)) (lisp-unit::assert-true (testpdf (lambda (r) (tdist-pdf r 12.75d0)) :tdist :nu 12.75d0)) From cdf / test.c (assert-to-tolerance (tdist-P 0.0d0 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 1.0d0) 5.00318309780080559d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 1.0d0) 5.03182992764908255d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 1.0d0) 5.31725517430553569d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 1.0d0) 6.00023120032852123d-1 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 1.0d0) 0.75000000000000000d0 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 1.0d0) 8.12832958189001183d-1 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 1.0d0) 8.52416382349566726d-1 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 1.0d0) 9.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 1.0d0) 9.84097748743823625d-1 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 1.0d0) 9.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 1.0d0) 9.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 1.0d0) 9.99968169011487724d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 1.0d0) 4.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 1.0d0) 4.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 1.0d0) 4.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 1.0d0) 3.99976879967147876d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 1.0d0) 2.5d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 1.0d0) 1.87167041810998816d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 1.0d0) 1.47583617650433274d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 1.0d0) 3.17255174305535695d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 1.0d0) 1.59022512561763752d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 1.0d0) 3.18299276490825515d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 1.0d0) 3.18309780080558939d-4 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 1.0d0) 3.18309885122757724d-5 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 1.0d0) 4.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 1.0d0) 4.96817007235091744d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 1.0d0) 4.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 1.0d0) 3.99976879967147876d-1 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 1.0d0) 0.25d0 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 1.0d0) 1.87167041810998816d-1 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 1.0d0) 1.47583617650433274d-1 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 1.0d0) 3.17255174305535695d-2 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 1.0d0) 1.59022512561763751d-2 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 1.0d0) 3.18299276490825514d-3 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 1.0d0) 3.18309780080558938d-4 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 1.0d0) 3.18309885122757724d-5 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 1.0d0) 5.00318309780080559d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 1.0d0) 5.03182992764908255d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 1.0d0) 5.31725517430553570d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 1.0d0) 6.00023120032852124d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 1.0d0) 7.5d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 1.0d0) 8.12832958189001184d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 1.0d0) 8.52416382349566726d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 1.0d0) 9.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 1.0d0) 9.84097748743823625d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 1.0d0) 9.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 1.0d0) 9.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 1.0d0) 9.99968169011487724d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.0d0 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 2.0d0) 5.00353553302204959d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 2.0d0) 5.03535445520899514d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 2.0d0) 5.35267280792929913d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 2.0d0) 6.11985772746873767d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 2.0d0) 7.88675134594812882d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 2.0d0) 8.63803437554499460d-01 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 2.0d0) 9.08248290463863016d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 2.0d0) 9.95073771488337154d-01 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 2.0d0) 9.98754668053816452d-01 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 2.0d0) 9.99950007498750219d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 2.0d0) 9.99999500000749945d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 2.0d0) 9.999999950000000739d-01 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 2.0d0) 4.99646446697795041d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 2.0d0) 4.96464554479100486d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 2.0d0) 4.64732719207070087d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 2.0d0) 3.88014227253126233d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 2.0d0) 2.11324865405187118d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 2.0d0) 1.36196562445500540d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 2.0d0) 9.17517095361369836d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 2.0d0) 4.92622851166284542d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 2.0d0) 1.24533194618354849d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 2.0d0) 4.99925012497812894d-5 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 2.0d0) 4.99999250001249998d-7 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 2.0d0) 4.99999992500000125d-9 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 2.0d0) 4.99646446697795041d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 2.0d0) 4.96464554479100486d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 2.0d0) 4.64732719207070087d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 2.0d0) 3.88014227253126233d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 2.0d0) 2.11324865405187118d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 2.0d0) 1.36196562445500540d-01 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 2.0d0) 9.17517095361369836d-02 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 2.0d0) 4.92622851166284542d-03 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 2.0d0) 1.24533194618354849d-03 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 2.0d0) 4.99925012497812894d-05 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 2.0d0) 4.99999250001249998d-07 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 2.0d0) 4.99999992500000125d-09 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 2.0d0) 5.00353553302204959d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 2.0d0) 5.03535445520899514d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 2.0d0) 5.35267280792929913d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 2.0d0) 6.11985772746873767d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 2.0d0) 7.88675134594812882d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 2.0d0) 8.63803437554499460d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 2.0d0) 9.08248290463863016d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 2.0d0) 9.95073771488337155d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 2.0d0) 9.98754668053816452d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 2.0d0) 9.99950007498750219d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 2.0d0) 9.99999500000749999d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 2.0d0) 9.99999995000000075d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.0d0 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 300.0d0) 5.00398609900942949d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 300.0d0) 5.03986033020559088d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 300.0d0) 5.39794441177768194d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 300.0d0) 6.27296201542523812d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 300.0d0) 8.40941797784686861d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 300.0d0) 9.32666983425369137d-01 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 300.0d0) 9.76799239508425455d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 300.0d0) 4.99601390099057051d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 300.0d0) 4.96013966979440912d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 300.0d0) 4.60205558822231806d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 300.0d0) 3.72703798457476188d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 300.0d0) 1.59058202215313138d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 300.0d0) 6.73330165746308628d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 300.0d0) 2.32007604915745452d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 300.0d0) 8.279313677d-21 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 300.0d0) 1.93159812815803978d-57 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 300.0d0) 1.02557519997736154d-232 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 300.0d0) 4.99601390099057051d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 300.0d0) 4.96013966979440912d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 300.0d0) 4.60205558822231806d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 300.0d0) 3.72703798457476188d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 300.0d0) 1.59058202215313138d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 300.0d0) 6.73330165746308628d-02 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 300.0d0) 2.32007604915745452d-02 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 300.0d0) 8.279313675556272534d-21 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 300.0d0) 1.93159812815803978d-57 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 300.0d0) 1.02557519997736154d-232 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 300.0d0) 5.00398609900942949d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 300.0d0) 5.03986033020559088d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 300.0d0) 5.39794441177768194d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 300.0d0) 6.27296201542523812d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 300.0d0) 8.40941797784686862d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 300.0d0) 9.32666983425369137d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 300.0d0) 9.76799239508425455d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.5d0 1.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.00318309780080559d-1 1.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.03182992764908255d-1 1.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.31725517430553569d-1 1.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.00023120032852123d-1 1.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.75000000000000000d0 1.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.12832958189001183d-1 1.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.52416382349566726d-1 1.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.68274482569446430d-1 1.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.84097748743823625d-1 1.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.96817007235091745d-1 1.0d0) 100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.99681690219919441d-1 1.0d0) 1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.99968169011487724d-1 1.0d0) 10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 0.5d0 1.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.99681690219919441d-1 1.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.96817007235091745d-1 1.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.68274482569446430d-1 1.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.99976879967147876d-1 1.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 2.5d-1 1.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.87167041810998816d-1 1.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.47583617650433274d-1 1.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.17255174305535695d-2 1.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.59022512561763752d-2 1.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18299276490825515d-3 1.0d0) 100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18309780080558939d-4 1.0d0) 1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18309885122757724d-5 1.0d0) 10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99681690219919441d-1 1.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96817007235091744d-1 1.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.68274482569446430d-1 1.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.99976879967147876d-1 1.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.25d0 1.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.87167041810998816d-1 1.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.47583617650433274d-1 1.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.17255174305535695d-2 1.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.59022512561763751d-2 1.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18299276490825514d-3 1.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18309780080558938d-4 1.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18309885122757724d-5 1.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.00318309780080559d-1 1.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03182992764908255d-1 1.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.31725517430553570d-1 1.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.00023120032852124d-1 1.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 7.5d-1 1.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.12832958189001184d-1 1.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.52416382349566726d-1 1.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.68274482569446430d-1 1.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.84097748743823625d-1 1.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.96817007235091745d-1 1.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99681690219919441d-1 1.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99968169011487724d-1 1.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99646446697795041d-01 2.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96464554479100486d-01 2.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.64732719207070087d-01 2.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.88014227253126233d-01 2.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 2.11324865405187118d-01 2.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.36196562445500540d-01 2.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.17517095361369836d-02 2.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.92622851166284542d-03 2.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.24533194618354849d-03 2.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99925012497812894d-05 2.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99999250001249998d-07 2.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99999992500000125d-09 2.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.00353553302204959d-1 2.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03535445520899514d-1 2.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.35267280792929913d-1 2.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.11985772746873767d-1 2.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 7.88675134594812882d-1 2.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.63803437554499460d-1 2.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.08248290463863016d-1 2.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.95073771488337155d-1 2.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.98754668053816452d-1 2.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99950007498750219d-1 2.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99999500000749999d-1 2.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99999995000000075d-1 2.0d0) -10000.0d0 1.0d-06) (assert-to-tolerance (tdist-Pinv 5.00000000000000000d-01 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.00398609900942949d-01 300.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.03986033020559088d-01 300.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.39794441177768194d-01 300.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.27296201542523812d-01 300.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.40941797784686861d-01 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.32666983425369137d-01 300.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.76799239508425455d-01 300.0d0) 2.0d0 +test-tol6+) (assert-posinf (tdist-Pinv 1.0d0 300.0d0)) (assert-to-tolerance (tdist-Qinv 5.00000000000000000d-01 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.99601390099057051d-1 300.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.96013966979440912d-1 300.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.60205558822231806d-1 300.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.72703798457476188d-1 300.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.59058202215313138d-1 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.73330165746308628d-2 300.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 2.32007604915745452d-2 300.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.279313677d-21 300.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.93159812815803978d-57 300.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.02557519997736154d-232 300.0d0) 100.0d0 +test-tol6+) (assert-posinf (tdist-Qinv 0.0d0 300.0d0)) (assert-to-tolerance (tdist-Pinv 4.99601390099057051d-01 300.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96013966979440912d-01 300.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.60205558822231806d-01 300.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.72703798457476188d-01 300.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.59058202215313138d-01 300.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.73330165746308628d-02 300.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 2.32007604915745452d-02 300.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.279313675556272534d-21 300.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.93159812815803978d-57 300.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.02557519997736154d-232 300.0d0) -100.0d0 +test-tol6+) (assert-neginf (tdist-Pinv 0.0d0 300.0d0)) (assert-to-tolerance (tdist-Qinv 5.00398609900942949d-1 300.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03986033020559088d-1 300.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.39794441177768194d-1 300.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.27296201542523812d-1 300.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.40941797784686862d-1 300.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.32666983425369137d-1 300.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.76799239508425455d-1 300.0d0) -2.0d0 +test-tol6+) (assert-neginf (tdist-Qinv 1.0d0 300.0d0)) ;; Automatically converted from cdf/test_auto.c (ASSERT-TO-TOLERANCE (TDIST-P -1.d10 1.3d0) 3.46784811185d-14 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 3.4678481118500305d-14 1.3d0) -1.d10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d9 1.3d0) 6.91926665161d-13 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 6.919266651610352d-13 1.3d0) -1.d9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d8 1.3d0) 1.380575199718d-11 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 1.3805751997179027d-11 1.3d0) -1.d8 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d7 1.3d0) 2.754609668978d-10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 2.7546096689777484d-10 1.3d0) -1.d7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1000000.0d0 1.3d0) 5.496168864957d-9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 5.496168864956998d-9 1.3d0) -1000000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -100000.0d0 1.3d0) 1.096629861231d-7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 1.0966298612314582d-7 1.3d0) -100000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -10000.0d0 1.3d0) 2.188064222827d-6 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 2.1880642228271703d-6 1.3d0) -10000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1000.0d0 1.3d0) 4.365759541083d-5 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 4.365759541083357d-5 1.3d0) -1000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -100.0d0 1.3d0) 8.710327647608d-4 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 8.71032764760792d-4 1.3d0) -100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -10.0d0 1.3d0) 0.0172789338682d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.017278933868204446d0 1.3d0) -10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.0d0 1.3d0) 0.2336211937932d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.23362119379322516d0 1.3d0) -1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.1d0 1.3d0) 0.4667575980083d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.4667575980082614d0 1.3d0) -0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.01d0 1.3d0) 0.4966660755117d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.49666607551169606d0 1.3d0) -0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.001d0 1.3d0) 0.4996665978189d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.4996665978188763d0 1.3d0) -0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-4 1.3d0) 0.4999666597722d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-5 1.3d0) 0.4999966659772d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-6 1.3d0) 0.4999996665977d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-7 1.3d0) 0.4999999666598d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-8 1.3d0) 0.499999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-9 1.3d0) 0.4999999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-10 1.3d0) 0.4999999999667d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.0d0 1.3d0) 0.5d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.499999999999999d0 1.3d0) 0.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-10 1.3d0) 0.5000000000333d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-9 1.3d0) 0.5000000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-8 1.3d0) 0.500000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-7 1.3d0) 0.5000000333402d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-6 1.3d0) 0.5000003334023d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-5 1.3d0) 0.5000033340228d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-4 1.3d0) 0.5000333402278d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.001d0 1.3d0) 0.5003334021811d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5003334021811237d0 1.3d0) 0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.01d0 1.3d0) 0.5033339244883d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5033339244883039d0 1.3d0) 0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.1d0 1.3d0) 0.5332424019917d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5332424019917386d0 1.3d0) 0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.0d0 1.3d0) 0.7663788062068d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.7663788062067749d0 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 10.0d0 1.3d0) 0.9827210661318d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.9827210661317956d0 1.3d0) 10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 100.0d0 1.3d0) 0.9991289672352d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.9991289672352393d0 1.3d0) 100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1000.0d0 1.3d0) 0.9999563424046d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 10000.0d0 1.3d0) 0.9999978119358d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 100000.0d0 1.3d0) 0.999999890337d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1000000.0d0 1.3d0) 0.9999999945038d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d7 1.3d0) 0.9999999997245d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d8 1.3d0) 0.9999999999862d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d9 1.3d0) 0.9999999999993d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d10 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d10 1.3d0) 3.46784811185d-14 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 3.4678481118500305d-14 1.3d0) 1.d10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d9 1.3d0) 6.91926665161d-13 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 6.919266651610352d-13 1.3d0) 1.d9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d8 1.3d0) 1.380575199718d-11 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 1.3805751997179027d-11 1.3d0) 1.d8 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d7 1.3d0) 2.754609668978d-10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 2.7546096689777484d-10 1.3d0) 1.d7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1000000.0d0 1.3d0) 5.496168864957d-9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 5.496168864956998d-9 1.3d0) 1000000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 100000.0d0 1.3d0) 1.096629861231d-7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 1.0966298612314582d-7 1.3d0) 100000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 10000.0d0 1.3d0) 2.188064222827d-6 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 2.1880642228271703d-6 1.3d0) 10000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1000.0d0 1.3d0) 4.365759541083d-5 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 4.365759541083357d-5 1.3d0) 1000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 100.0d0 1.3d0) 8.710327647608d-4 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 8.71032764760792d-4 1.3d0) 100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 10.0d0 1.3d0) 0.0172789338682d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.017278933868204446d0 1.3d0) 10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.0d0 1.3d0) 0.2336211937932d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.23362119379322516d0 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.1d0 1.3d0) 0.4667575980083d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.4667575980082614d0 1.3d0) 0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.01d0 1.3d0) 0.4966660755117d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.49666607551169606d0 1.3d0) 0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.001d0 1.3d0) 0.4996665978189d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.4996665978188763d0 1.3d0) 0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-4 1.3d0) 0.4999666597722d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-5 1.3d0) 0.4999966659772d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-6 1.3d0) 0.4999996665977d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-7 1.3d0) 0.4999999666598d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-8 1.3d0) 0.499999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-9 1.3d0) 0.4999999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-10 1.3d0) 0.4999999999667d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.0d0 1.3d0) 0.5d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.499999999999999d0 1.3d0) 0.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-10 1.3d0) 0.5000000000333d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-9 1.3d0) 0.5000000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-8 1.3d0) 0.500000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-7 1.3d0) 0.5000000333402d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-6 1.3d0) 0.5000003334023d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-5 1.3d0) 0.5000033340228d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-4 1.3d0) 0.5000333402278d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.001d0 1.3d0) 0.5003334021811d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5003334021811237d0 1.3d0) -0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.01d0 1.3d0) 0.5033339244883d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5033339244883039d0 1.3d0) -0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.1d0 1.3d0) 0.5332424019917d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5332424019917386d0 1.3d0) -0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.0d0 1.3d0) 0.7663788062068d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.7663788062067749d0 1.3d0) -1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -10.0d0 1.3d0) 0.9827210661318d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.9827210661317956d0 1.3d0) -10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -100.0d0 1.3d0) 0.9991289672352d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.9991289672352393d0 1.3d0) -100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1000.0d0 1.3d0) 0.9999563424046d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -10000.0d0 1.3d0) 0.9999978119358d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -100000.0d0 1.3d0) 0.999999890337d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1000000.0d0 1.3d0) 0.9999999945038d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d7 1.3d0) 0.9999999997245d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d8 1.3d0) 0.9999999999862d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d9 1.3d0) 0.9999999999993d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d10 1.3d0) 1.0d0 +TEST-TOL6+))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/tdist.lisp
lisp
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 </>. Automatically converted from cdf/test_auto.c
Regression test TDIST for GSLL Copyright 2009 Distributed under the terms of the GNU General Public License 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 (in-package :gsl) (lisp-unit:define-test tdist From randist / test.c (lisp-unit::assert-true (testpdf (lambda (r) (tdist-pdf r 1.75d0)) :tdist :nu 1.75d0)) (lisp-unit::assert-true (testpdf (lambda (r) (tdist-pdf r 12.75d0)) :tdist :nu 12.75d0)) From cdf / test.c (assert-to-tolerance (tdist-P 0.0d0 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 1.0d0) 5.00318309780080559d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 1.0d0) 5.03182992764908255d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 1.0d0) 5.31725517430553569d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 1.0d0) 6.00023120032852123d-1 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 1.0d0) 0.75000000000000000d0 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 1.0d0) 8.12832958189001183d-1 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 1.0d0) 8.52416382349566726d-1 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 1.0d0) 9.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 1.0d0) 9.84097748743823625d-1 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 1.0d0) 9.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 1.0d0) 9.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 1.0d0) 9.99968169011487724d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 1.0d0) 4.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 1.0d0) 4.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 1.0d0) 4.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 1.0d0) 3.99976879967147876d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 1.0d0) 2.5d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 1.0d0) 1.87167041810998816d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 1.0d0) 1.47583617650433274d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 1.0d0) 3.17255174305535695d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 1.0d0) 1.59022512561763752d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 1.0d0) 3.18299276490825515d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 1.0d0) 3.18309780080558939d-4 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 1.0d0) 3.18309885122757724d-5 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 1.0d0) 4.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 1.0d0) 4.96817007235091744d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 1.0d0) 4.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 1.0d0) 3.99976879967147876d-1 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 1.0d0) 0.25d0 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 1.0d0) 1.87167041810998816d-1 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 1.0d0) 1.47583617650433274d-1 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 1.0d0) 3.17255174305535695d-2 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 1.0d0) 1.59022512561763751d-2 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 1.0d0) 3.18299276490825514d-3 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 1.0d0) 3.18309780080558938d-4 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 1.0d0) 3.18309885122757724d-5 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 1.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 1.0d0) 5.00318309780080559d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 1.0d0) 5.03182992764908255d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 1.0d0) 5.31725517430553570d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 1.0d0) 6.00023120032852124d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 1.0d0) 7.5d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 1.0d0) 8.12832958189001184d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 1.0d0) 8.52416382349566726d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 1.0d0) 9.68274482569446430d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 1.0d0) 9.84097748743823625d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 1.0d0) 9.96817007235091745d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 1.0d0) 9.99681690219919441d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 1.0d0) 9.99968169011487724d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.0d0 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 2.0d0) 5.00353553302204959d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 2.0d0) 5.03535445520899514d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 2.0d0) 5.35267280792929913d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 2.0d0) 6.11985772746873767d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 2.0d0) 7.88675134594812882d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 2.0d0) 8.63803437554499460d-01 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 2.0d0) 9.08248290463863016d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 2.0d0) 9.95073771488337154d-01 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 2.0d0) 9.98754668053816452d-01 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 2.0d0) 9.99950007498750219d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 2.0d0) 9.99999500000749945d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 2.0d0) 9.999999950000000739d-01 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 2.0d0) 4.99646446697795041d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 2.0d0) 4.96464554479100486d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 2.0d0) 4.64732719207070087d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 2.0d0) 3.88014227253126233d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 2.0d0) 2.11324865405187118d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 2.0d0) 1.36196562445500540d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 2.0d0) 9.17517095361369836d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 2.0d0) 4.92622851166284542d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 2.0d0) 1.24533194618354849d-3 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 2.0d0) 4.99925012497812894d-5 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 2.0d0) 4.99999250001249998d-7 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 2.0d0) 4.99999992500000125d-9 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 2.0d0) 4.99646446697795041d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 2.0d0) 4.96464554479100486d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 2.0d0) 4.64732719207070087d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 2.0d0) 3.88014227253126233d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 2.0d0) 2.11324865405187118d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 2.0d0) 1.36196562445500540d-01 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 2.0d0) 9.17517095361369836d-02 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 2.0d0) 4.92622851166284542d-03 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 2.0d0) 1.24533194618354849d-03 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 2.0d0) 4.99925012497812894d-05 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 2.0d0) 4.99999250001249998d-07 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 2.0d0) 4.99999992500000125d-09 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 2.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 2.0d0) 5.00353553302204959d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 2.0d0) 5.03535445520899514d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 2.0d0) 5.35267280792929913d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 2.0d0) 6.11985772746873767d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 2.0d0) 7.88675134594812882d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 2.0d0) 8.63803437554499460d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 2.0d0) 9.08248290463863016d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 2.0d0) 9.95073771488337155d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 2.0d0) 9.98754668053816452d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 2.0d0) 9.99950007498750219d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 2.0d0) 9.99999500000749999d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 2.0d0) 9.99999995000000075d-1 +test-tol6+) (assert-to-tolerance (tdist-P 0.0d0 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 1d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P 0.001d0 300.0d0) 5.00398609900942949d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.01d0 300.0d0) 5.03986033020559088d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.1d0 300.0d0) 5.39794441177768194d-01 +test-tol6+) (assert-to-tolerance (tdist-P 0.325d0 300.0d0) 6.27296201542523812d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.0d0 300.0d0) 8.40941797784686861d-01 +test-tol6+) (assert-to-tolerance (tdist-P 1.5d0 300.0d0) 9.32666983425369137d-01 +test-tol6+) (assert-to-tolerance (tdist-P 2.0d0 300.0d0) 9.76799239508425455d-01 +test-tol6+) (assert-to-tolerance (tdist-P 10.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 20.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 100.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 1000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-P 10000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.0d0 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 1d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q 0.001d0 300.0d0) 4.99601390099057051d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.01d0 300.0d0) 4.96013966979440912d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.1d0 300.0d0) 4.60205558822231806d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 0.325d0 300.0d0) 3.72703798457476188d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.0d0 300.0d0) 1.59058202215313138d-1 +test-tol6+) (assert-to-tolerance (tdist-Q 1.5d0 300.0d0) 6.73330165746308628d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 2.0d0 300.0d0) 2.32007604915745452d-2 +test-tol6+) (assert-to-tolerance (tdist-Q 10.0d0 300.0d0) 8.279313677d-21 +test-tol6+) (assert-to-tolerance (tdist-Q 20.0d0 300.0d0) 1.93159812815803978d-57 +test-tol6+) (assert-to-tolerance (tdist-Q 100.0d0 300.0d0) 1.02557519997736154d-232 +test-tol6+) (assert-to-tolerance (tdist-Q 1000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q 10000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-P -0.001d0 300.0d0) 4.99601390099057051d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.01d0 300.0d0) 4.96013966979440912d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.1d0 300.0d0) 4.60205558822231806d-01 +test-tol6+) (assert-to-tolerance (tdist-P -0.325d0 300.0d0) 3.72703798457476188d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.0d0 300.0d0) 1.59058202215313138d-01 +test-tol6+) (assert-to-tolerance (tdist-P -1.5d0 300.0d0) 6.73330165746308628d-02 +test-tol6+) (assert-to-tolerance (tdist-P -2.0d0 300.0d0) 2.32007604915745452d-02 +test-tol6+) (assert-to-tolerance (tdist-P -10.0d0 300.0d0) 8.279313675556272534d-21 +test-tol6+) (assert-to-tolerance (tdist-P -20.0d0 300.0d0) 1.93159812815803978d-57 +test-tol6+) (assert-to-tolerance (tdist-P -100.0d0 300.0d0) 1.02557519997736154d-232 +test-tol6+) (assert-to-tolerance (tdist-P -1000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-P -10000.0d0 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d-100 300.0d0) 0.5d0 +test-tol6+) (assert-to-tolerance (tdist-Q -0.001d0 300.0d0) 5.00398609900942949d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.01d0 300.0d0) 5.03986033020559088d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.1d0 300.0d0) 5.39794441177768194d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -0.325d0 300.0d0) 6.27296201542523812d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.0d0 300.0d0) 8.40941797784686862d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -1.5d0 300.0d0) 9.32666983425369137d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -2.0d0 300.0d0) 9.76799239508425455d-1 +test-tol6+) (assert-to-tolerance (tdist-Q -10.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -20.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -100.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -1000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Q -10000.0d0 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.5d0 1.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.00318309780080559d-1 1.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.03182992764908255d-1 1.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.31725517430553569d-1 1.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.00023120032852123d-1 1.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.75000000000000000d0 1.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.12832958189001183d-1 1.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.52416382349566726d-1 1.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.68274482569446430d-1 1.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.84097748743823625d-1 1.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.96817007235091745d-1 1.0d0) 100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.99681690219919441d-1 1.0d0) 1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.99968169011487724d-1 1.0d0) 10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 0.5d0 1.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.99681690219919441d-1 1.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.96817007235091745d-1 1.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.68274482569446430d-1 1.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.99976879967147876d-1 1.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 2.5d-1 1.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.87167041810998816d-1 1.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.47583617650433274d-1 1.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.17255174305535695d-2 1.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.59022512561763752d-2 1.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18299276490825515d-3 1.0d0) 100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18309780080558939d-4 1.0d0) 1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.18309885122757724d-5 1.0d0) 10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99681690219919441d-1 1.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96817007235091744d-1 1.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.68274482569446430d-1 1.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.99976879967147876d-1 1.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 0.25d0 1.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.87167041810998816d-1 1.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.47583617650433274d-1 1.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.17255174305535695d-2 1.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.59022512561763751d-2 1.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18299276490825514d-3 1.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18309780080558938d-4 1.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.18309885122757724d-5 1.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.00318309780080559d-1 1.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03182992764908255d-1 1.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.31725517430553570d-1 1.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.00023120032852124d-1 1.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 7.5d-1 1.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.12832958189001184d-1 1.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.52416382349566726d-1 1.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.68274482569446430d-1 1.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.84097748743823625d-1 1.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.96817007235091745d-1 1.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99681690219919441d-1 1.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99968169011487724d-1 1.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99646446697795041d-01 2.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96464554479100486d-01 2.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.64732719207070087d-01 2.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.88014227253126233d-01 2.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 2.11324865405187118d-01 2.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.36196562445500540d-01 2.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.17517095361369836d-02 2.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.92622851166284542d-03 2.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.24533194618354849d-03 2.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99925012497812894d-05 2.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99999250001249998d-07 2.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.99999992500000125d-09 2.0d0) -10000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.00353553302204959d-1 2.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03535445520899514d-1 2.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.35267280792929913d-1 2.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.11985772746873767d-1 2.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 7.88675134594812882d-1 2.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.63803437554499460d-1 2.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.08248290463863016d-1 2.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.95073771488337155d-1 2.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.98754668053816452d-1 2.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99950007498750219d-1 2.0d0) -100.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99999500000749999d-1 2.0d0) -1000.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.99999995000000075d-1 2.0d0) -10000.0d0 1.0d-06) (assert-to-tolerance (tdist-Pinv 5.00000000000000000d-01 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.00398609900942949d-01 300.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.03986033020559088d-01 300.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 5.39794441177768194d-01 300.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.27296201542523812d-01 300.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.40941797784686861d-01 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.32666983425369137d-01 300.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 9.76799239508425455d-01 300.0d0) 2.0d0 +test-tol6+) (assert-posinf (tdist-Pinv 1.0d0 300.0d0)) (assert-to-tolerance (tdist-Qinv 5.00000000000000000d-01 300.0d0) 0.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.99601390099057051d-1 300.0d0) 0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.96013966979440912d-1 300.0d0) 0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 4.60205558822231806d-1 300.0d0) 0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 3.72703798457476188d-1 300.0d0) 0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.59058202215313138d-1 300.0d0) 1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.73330165746308628d-2 300.0d0) 1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 2.32007604915745452d-2 300.0d0) 2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.279313677d-21 300.0d0) 10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.93159812815803978d-57 300.0d0) 20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 1.02557519997736154d-232 300.0d0) 100.0d0 +test-tol6+) (assert-posinf (tdist-Qinv 0.0d0 300.0d0)) (assert-to-tolerance (tdist-Pinv 4.99601390099057051d-01 300.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.96013966979440912d-01 300.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 4.60205558822231806d-01 300.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 3.72703798457476188d-01 300.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.59058202215313138d-01 300.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 6.73330165746308628d-02 300.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 2.32007604915745452d-02 300.0d0) -2.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 8.279313675556272534d-21 300.0d0) -10.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.93159812815803978d-57 300.0d0) -20.0d0 +test-tol6+) (assert-to-tolerance (tdist-Pinv 1.02557519997736154d-232 300.0d0) -100.0d0 +test-tol6+) (assert-neginf (tdist-Pinv 0.0d0 300.0d0)) (assert-to-tolerance (tdist-Qinv 5.00398609900942949d-1 300.0d0) -0.001d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.03986033020559088d-1 300.0d0) -0.01d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 5.39794441177768194d-1 300.0d0) -0.1d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 6.27296201542523812d-1 300.0d0) -0.325d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 8.40941797784686862d-1 300.0d0) -1.0d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.32666983425369137d-1 300.0d0) -1.5d0 +test-tol6+) (assert-to-tolerance (tdist-Qinv 9.76799239508425455d-1 300.0d0) -2.0d0 +test-tol6+) (assert-neginf (tdist-Qinv 1.0d0 300.0d0)) (ASSERT-TO-TOLERANCE (TDIST-P -1.d10 1.3d0) 3.46784811185d-14 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 3.4678481118500305d-14 1.3d0) -1.d10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d9 1.3d0) 6.91926665161d-13 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 6.919266651610352d-13 1.3d0) -1.d9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d8 1.3d0) 1.380575199718d-11 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 1.3805751997179027d-11 1.3d0) -1.d8 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d7 1.3d0) 2.754609668978d-10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 2.7546096689777484d-10 1.3d0) -1.d7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1000000.0d0 1.3d0) 5.496168864957d-9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 5.496168864956998d-9 1.3d0) -1000000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -100000.0d0 1.3d0) 1.096629861231d-7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 1.0966298612314582d-7 1.3d0) -100000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -10000.0d0 1.3d0) 2.188064222827d-6 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 2.1880642228271703d-6 1.3d0) -10000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1000.0d0 1.3d0) 4.365759541083d-5 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 4.365759541083357d-5 1.3d0) -1000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -100.0d0 1.3d0) 8.710327647608d-4 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 8.71032764760792d-4 1.3d0) -100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -10.0d0 1.3d0) 0.0172789338682d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.017278933868204446d0 1.3d0) -10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.0d0 1.3d0) 0.2336211937932d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.23362119379322516d0 1.3d0) -1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.1d0 1.3d0) 0.4667575980083d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.4667575980082614d0 1.3d0) -0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.01d0 1.3d0) 0.4966660755117d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.49666607551169606d0 1.3d0) -0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -0.001d0 1.3d0) 0.4996665978189d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.4996665978188763d0 1.3d0) -0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-4 1.3d0) 0.4999666597722d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-5 1.3d0) 0.4999966659772d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-6 1.3d0) 0.4999996665977d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-7 1.3d0) 0.4999999666598d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-8 1.3d0) 0.499999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-9 1.3d0) 0.4999999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P -1.d-10 1.3d0) 0.4999999999667d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.0d0 1.3d0) 0.5d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.499999999999999d0 1.3d0) 0.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-10 1.3d0) 0.5000000000333d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-9 1.3d0) 0.5000000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-8 1.3d0) 0.500000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-7 1.3d0) 0.5000000333402d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-6 1.3d0) 0.5000003334023d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-5 1.3d0) 0.5000033340228d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d-4 1.3d0) 0.5000333402278d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.001d0 1.3d0) 0.5003334021811d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5003334021811237d0 1.3d0) 0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.01d0 1.3d0) 0.5033339244883d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5033339244883039d0 1.3d0) 0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 0.1d0 1.3d0) 0.5332424019917d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.5332424019917386d0 1.3d0) 0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.0d0 1.3d0) 0.7663788062068d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.7663788062067749d0 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 10.0d0 1.3d0) 0.9827210661318d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.9827210661317956d0 1.3d0) 10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 100.0d0 1.3d0) 0.9991289672352d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-PINV 0.9991289672352393d0 1.3d0) 100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1000.0d0 1.3d0) 0.9999563424046d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 10000.0d0 1.3d0) 0.9999978119358d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 100000.0d0 1.3d0) 0.999999890337d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1000000.0d0 1.3d0) 0.9999999945038d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d7 1.3d0) 0.9999999997245d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d8 1.3d0) 0.9999999999862d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d9 1.3d0) 0.9999999999993d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-P 1.d10 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d10 1.3d0) 3.46784811185d-14 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 3.4678481118500305d-14 1.3d0) 1.d10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d9 1.3d0) 6.91926665161d-13 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 6.919266651610352d-13 1.3d0) 1.d9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d8 1.3d0) 1.380575199718d-11 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 1.3805751997179027d-11 1.3d0) 1.d8 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d7 1.3d0) 2.754609668978d-10 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 2.7546096689777484d-10 1.3d0) 1.d7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1000000.0d0 1.3d0) 5.496168864957d-9 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 5.496168864956998d-9 1.3d0) 1000000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 100000.0d0 1.3d0) 1.096629861231d-7 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 1.0966298612314582d-7 1.3d0) 100000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 10000.0d0 1.3d0) 2.188064222827d-6 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 2.1880642228271703d-6 1.3d0) 10000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1000.0d0 1.3d0) 4.365759541083d-5 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 4.365759541083357d-5 1.3d0) 1000.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 100.0d0 1.3d0) 8.710327647608d-4 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 8.71032764760792d-4 1.3d0) 100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 10.0d0 1.3d0) 0.0172789338682d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.017278933868204446d0 1.3d0) 10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.0d0 1.3d0) 0.2336211937932d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.23362119379322516d0 1.3d0) 1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.1d0 1.3d0) 0.4667575980083d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.4667575980082614d0 1.3d0) 0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.01d0 1.3d0) 0.4966660755117d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.49666607551169606d0 1.3d0) 0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.001d0 1.3d0) 0.4996665978189d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.4996665978188763d0 1.3d0) 0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-4 1.3d0) 0.4999666597722d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-5 1.3d0) 0.4999966659772d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-6 1.3d0) 0.4999996665977d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-7 1.3d0) 0.4999999666598d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-8 1.3d0) 0.499999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-9 1.3d0) 0.4999999996666d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 1.d-10 1.3d0) 0.4999999999667d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q 0.0d0 1.3d0) 0.5d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.499999999999999d0 1.3d0) 0.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-10 1.3d0) 0.5000000000333d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-9 1.3d0) 0.5000000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-8 1.3d0) 0.500000003334d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-7 1.3d0) 0.5000000333402d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-6 1.3d0) 0.5000003334023d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-5 1.3d0) 0.5000033340228d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d-4 1.3d0) 0.5000333402278d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.001d0 1.3d0) 0.5003334021811d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5003334021811237d0 1.3d0) -0.001d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.01d0 1.3d0) 0.5033339244883d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5033339244883039d0 1.3d0) -0.01d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -0.1d0 1.3d0) 0.5332424019917d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.5332424019917386d0 1.3d0) -0.1d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.0d0 1.3d0) 0.7663788062068d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.7663788062067749d0 1.3d0) -1.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -10.0d0 1.3d0) 0.9827210661318d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.9827210661317956d0 1.3d0) -10.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -100.0d0 1.3d0) 0.9991289672352d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-QINV 0.9991289672352393d0 1.3d0) -100.0d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1000.0d0 1.3d0) 0.9999563424046d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -10000.0d0 1.3d0) 0.9999978119358d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -100000.0d0 1.3d0) 0.999999890337d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1000000.0d0 1.3d0) 0.9999999945038d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d7 1.3d0) 0.9999999997245d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d8 1.3d0) 0.9999999999862d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d9 1.3d0) 0.9999999999993d0 +TEST-TOL6+) (ASSERT-TO-TOLERANCE (TDIST-Q -1.d10 1.3d0) 1.0d0 +TEST-TOL6+))
f8849f8f11f285442b195ccdaf155a72a67352c3050c3df9ce884559039a41a4
mattn/clj-ezoe
core_test.clj
(ns ezoe.core-test (:require [clojure.test :refer :all] [ezoe.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/mattn/clj-ezoe/b51e2beceb18d5cd39426e91d45d3a69f2e0b028/test/ezoe/core_test.clj
clojure
(ns ezoe.core-test (:require [clojure.test :refer :all] [ezoe.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
8e9f576a51c6e48c27ad2bf6827b1765eac5c365b2b8a94e22d14bf0a2dd6395
dyzsr/ocaml-selectml
pr7937.ml
(* TEST * expect *) type 'a r = [< `X of int & 'a ] as 'a let f: 'a. 'a r -> 'a r = fun x -> true;; [%%expect {| type 'a r = 'a constraint 'a = [< `X of int & 'a ] Line 3, characters 35-39: 3 | let f: 'a. 'a r -> 'a r = fun x -> true;; ^^^^ Error: This expression has type bool but an expression was expected of type ([< `X of int & 'a ] as 'a) r |}, Principal{| type 'a r = 'a constraint 'a = [< `X of int & 'a ] Line 3, characters 35-39: 3 | let f: 'a. 'a r -> 'a r = fun x -> true;; ^^^^ Error: This expression has type bool but an expression was expected of type ([< `X of 'b & 'a & 'c ] as 'a) r |}] let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; [%%expect {| Line 1, characters 35-51: 1 | let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; ^^^^^^^^^^^^^^^^ Error: This expression has type int ref but an expression was expected of type ([< `X of int & 'a ] as 'a) r |}, Principal{| Line 1, characters 35-51: 1 | let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; ^^^^^^^^^^^^^^^^ Error: This expression has type int ref but an expression was expected of type ([< `X of 'b & 'a & 'c ] as 'a) r |}] let h: 'a. 'a r -> _ = function true | false -> ();; [%%expect {| Line 1, characters 32-36: 1 | let h: 'a. 'a r -> _ = function true | false -> ();; ^^^^ Error: This pattern should not be a boolean literal, the expected type is ([< `X of int & 'a ] as 'a) r |}] let i: 'a. 'a r -> _ = function { contents = 0 } -> ();; [%%expect {| Line 1, characters 32-48: 1 | let i: 'a. 'a r -> _ = function { contents = 0 } -> ();; ^^^^^^^^^^^^^^^^ Error: This pattern should not be a record, the expected type is ([< `X of int & 'a ] as 'a) r |}]
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-misc/pr7937.ml
ocaml
TEST * expect
type 'a r = [< `X of int & 'a ] as 'a let f: 'a. 'a r -> 'a r = fun x -> true;; [%%expect {| type 'a r = 'a constraint 'a = [< `X of int & 'a ] Line 3, characters 35-39: 3 | let f: 'a. 'a r -> 'a r = fun x -> true;; ^^^^ Error: This expression has type bool but an expression was expected of type ([< `X of int & 'a ] as 'a) r |}, Principal{| type 'a r = 'a constraint 'a = [< `X of int & 'a ] Line 3, characters 35-39: 3 | let f: 'a. 'a r -> 'a r = fun x -> true;; ^^^^ Error: This expression has type bool but an expression was expected of type ([< `X of 'b & 'a & 'c ] as 'a) r |}] let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; [%%expect {| Line 1, characters 35-51: 1 | let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; ^^^^^^^^^^^^^^^^ Error: This expression has type int ref but an expression was expected of type ([< `X of int & 'a ] as 'a) r |}, Principal{| Line 1, characters 35-51: 1 | let g: 'a. 'a r -> 'a r = fun x -> { contents = 0 };; ^^^^^^^^^^^^^^^^ Error: This expression has type int ref but an expression was expected of type ([< `X of 'b & 'a & 'c ] as 'a) r |}] let h: 'a. 'a r -> _ = function true | false -> ();; [%%expect {| Line 1, characters 32-36: 1 | let h: 'a. 'a r -> _ = function true | false -> ();; ^^^^ Error: This pattern should not be a boolean literal, the expected type is ([< `X of int & 'a ] as 'a) r |}] let i: 'a. 'a r -> _ = function { contents = 0 } -> ();; [%%expect {| Line 1, characters 32-48: 1 | let i: 'a. 'a r -> _ = function { contents = 0 } -> ();; ^^^^^^^^^^^^^^^^ Error: This pattern should not be a record, the expected type is ([< `X of int & 'a ] as 'a) r |}]
14e5c36aed691995c4d55909d1a9841af7659fcea1841a37397e21712c8dbcef
opencog/pln
simple-assertions.scm
; Define the concepts (ConceptNode "Socrates" (stv .001 0.9)) (ConceptNode "Einstein" (stv .001 0.9)) (ConceptNode "Peirce" (stv .001 0.9)) (ConceptNode "man" (stv .01 0.9)) (ConceptNode "human" (stv .02 0.9)) ; Define the instances of man (InheritanceLink (stv 0.9 0.9) (ConceptNode "Socrates") (ConceptNode "man")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Einstein") (ConceptNode "man")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Peirce") (ConceptNode "man")) ; Define what man is part of (InheritanceLink (stv 0.9 0.9) (ConceptNode "man") (ConceptNode "human")) ; Assign some additional memberships as well (InheritanceLink (stv 0.9 0.9) (ConceptNode "Einstein") (ConceptNode "violin-players")) ; Pattern to match to check the output (define find-humans (BindLink (VariableNode "$X") (InheritanceLink (VariableNode "$X") (ConceptNode "human")) (ListLink (VariableNode "$X"))))
null
https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/tests/pln/rules/simple-assertions.scm
scheme
Define the concepts Define the instances of man Define what man is part of Assign some additional memberships as well Pattern to match to check the output
(ConceptNode "Socrates" (stv .001 0.9)) (ConceptNode "Einstein" (stv .001 0.9)) (ConceptNode "Peirce" (stv .001 0.9)) (ConceptNode "man" (stv .01 0.9)) (ConceptNode "human" (stv .02 0.9)) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Socrates") (ConceptNode "man")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Einstein") (ConceptNode "man")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Peirce") (ConceptNode "man")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "man") (ConceptNode "human")) (InheritanceLink (stv 0.9 0.9) (ConceptNode "Einstein") (ConceptNode "violin-players")) (define find-humans (BindLink (VariableNode "$X") (InheritanceLink (VariableNode "$X") (ConceptNode "human")) (ListLink (VariableNode "$X"))))
f1bae7e0f6333e02a89a03f4aab33b2f2f876a43414baf682c594ac89ee6d6ac
chenyukang/eopl
lang.scm
(load-relative "../libs/init.scm") (load-relative "./base/test.scm") (load-relative "./base/data-structures.scm") (load-relative "./base/type-structures.scm") (load-relative "./base/type-module.scm") (load-relative "./base/grammar.scm") (load-relative "./base/renaming.scm") (load-relative "./base/subtyping.scm") (load-relative "./base/expand-type.scm") (load-relative "./base/type-cases.scm") (run "module mybool interface [opaque t true : t false : t to-bool : (t -> bool)] body [type t = int true = 0 false = 13 to-bool = proc (x : t) zero?(x)] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in let and = proc(x : t) proc(y : t) if zero?(x) then y else false in let not = proc(x : t) proc(x : t) if zero?(x) then false else true in ((and true) false)") (run "module mybool interface [opaque t true : t false : t and : (t -> (t -> t)) not : (t -> t) ] body [type t = int true = 0 false = 13 and = proc (x : t) proc (y : t) if zero?(x) then y else false not = proc (x : t) if zero?(x) then false else true ] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in let to-bool = proc(x : t) zero?(x) in ((and true) false)") (run "module mybool interface [opaque t true : t false : t and : (t -> (t -> t)) not : (t -> t) to-bool : (t -> bool)] body [type t = int true = 0 false = 13 and = proc (x : t) proc (y : t) if zero?(x) then y else false not = proc (x : t) if zero?(x) then false else true to-bool = proc (x : t) zero?(x)] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in ((and true) false)") (check "module m1 interface [opaque t zero : t] body [type t = int zero = 0] 33") (run-all) (check-all)
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch8/lang.scm
scheme
(load-relative "../libs/init.scm") (load-relative "./base/test.scm") (load-relative "./base/data-structures.scm") (load-relative "./base/type-structures.scm") (load-relative "./base/type-module.scm") (load-relative "./base/grammar.scm") (load-relative "./base/renaming.scm") (load-relative "./base/subtyping.scm") (load-relative "./base/expand-type.scm") (load-relative "./base/type-cases.scm") (run "module mybool interface [opaque t true : t false : t to-bool : (t -> bool)] body [type t = int true = 0 false = 13 to-bool = proc (x : t) zero?(x)] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in let and = proc(x : t) proc(y : t) if zero?(x) then y else false in let not = proc(x : t) proc(x : t) if zero?(x) then false else true in ((and true) false)") (run "module mybool interface [opaque t true : t false : t and : (t -> (t -> t)) not : (t -> t) ] body [type t = int true = 0 false = 13 and = proc (x : t) proc (y : t) if zero?(x) then y else false not = proc (x : t) if zero?(x) then false else true ] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in let to-bool = proc(x : t) zero?(x) in ((and true) false)") (run "module mybool interface [opaque t true : t false : t and : (t -> (t -> t)) not : (t -> t) to-bool : (t -> bool)] body [type t = int true = 0 false = 13 and = proc (x : t) proc (y : t) if zero?(x) then y else false not = proc (x : t) if zero?(x) then false else true to-bool = proc (x : t) zero?(x)] let true = from mybool take true in let false = from mybool take false in let and = from mybool take and in ((and true) false)") (check "module m1 interface [opaque t zero : t] body [type t = int zero = 0] 33") (run-all) (check-all)
e411c680ef7caafccfee955fd12635579dfb5cc66d253dd1daf1912ad8da388a
wireapp/wire-server
Services.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Galley.Data.Services * BotMember BotMember (..), newBotMember, botMemId, botMemService, ) where import Data.Id import Galley.Types.Conversations.Members import Imports import Wire.API.Provider.Service BotMember ------------------------------------------------------------------ -- | For now we assume bots to always be local -- -- FUTUREWORK(federation): allow remote bots newtype BotMember = BotMember {fromBotMember :: LocalMember} deriving (Show) instance Eq BotMember where (==) = (==) `on` botMemId instance Ord BotMember where compare = compare `on` botMemId newBotMember :: LocalMember -> Maybe BotMember newBotMember m = BotMember m <$ lmService m botMemId :: BotMember -> BotId botMemId = BotId . lmId . fromBotMember botMemService :: BotMember -> ServiceRef botMemService = fromJust . lmService . fromBotMember
null
https://raw.githubusercontent.com/wireapp/wire-server/bfc329f8aca3b6ecadd801820016f611ef5750a2/services/galley/src/Galley/Data/Services.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. ---------------------------------------------------------------- | For now we assume bots to always be local FUTUREWORK(federation): allow remote bots
Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Galley.Data.Services * BotMember BotMember (..), newBotMember, botMemId, botMemService, ) where import Data.Id import Galley.Types.Conversations.Members import Imports import Wire.API.Provider.Service newtype BotMember = BotMember {fromBotMember :: LocalMember} deriving (Show) instance Eq BotMember where (==) = (==) `on` botMemId instance Ord BotMember where compare = compare `on` botMemId newBotMember :: LocalMember -> Maybe BotMember newBotMember m = BotMember m <$ lmService m botMemId :: BotMember -> BotId botMemId = BotId . lmId . fromBotMember botMemService :: BotMember -> ServiceRef botMemService = fromJust . lmService . fromBotMember
3f2a568c0fc38dfabd8421c4d17fb3c002df18be80f4ba78a55b48d148af3189
LonoCloud/arrows
proc.clj
(ns arrows.proc (:require [monads.core :as m] [monads.macros :as mm])) ;; A simple parser to parse proc expressions (deftype parser-m [v mv f] clojure.lang.IFn (invoke [_ s] (if f (if-let [[v ss] (mv s)] ((f v) ss) nil) [v s])) m/Monad (do-result [_ v] (parser-m. v nil nil)) (bind [mv f] (parser-m. nil mv f)) m/MonadZero (zero [_] (constantly nil)) (plus-step [mv mvs] (parser-m. nil (fn [s] (loop [[mv & mvs] (cons mv mvs)] (when mv (if-let [result (mv s)] result (recur mvs))))) (fn [v] (parser-m. v nil nil))))) (defn parser "Create a parser that always returns a constant value 'v'" [v] (parser-m. v nil nil)) (defmacro parser-do [bindings expr] `(monads.macros/do arrows.proc/parser ~bindings ~expr)) (defn optional "Create a parser for an optional element" [p] (m/plus [p (parser nil)])) (declare one-or-more) (defn none-or-more "Create a parser for zero or occurances of a given parser" [p] (optional (one-or-more p))) (defn one-or-more "Create a parser for one or occurances of a given parser" [p] (parser-do [a p as (none-or-more p)] (cons a as))) ;; a parser that removes the next item from what is being parsed (def next-item (reify m/Monad (do-result [_ v] (parser v)) (bind [mv f] (fn [{:keys [cmd] :as state}] (when (seq cmd) ((f (first cmd)) (update-in state [:cmd] rest))))))) ;; a parser that returns the entire parser state (def get-state (reify clojure.lang.IFn (invoke [_ s] [s s]) m/Monad (do-result [_ v] (parser v)) (bind [mv f] (parser-m. nil mv f)))) (defn get-val "Create a parser to get the value associated with 'k' in the parser state" [k] (m/bind get-state (fn [state] (parser (get state k))))) (defn update-state "Create a parser that will apply a function to the parser state" [f] (reify clojure.lang.IFn (invoke [_ s] (let [new-s (f s)] [new-s new-s])) m/Monad (do-result [_ v] (parser v)) (bind [mv f] (parser-m. nil mv f)))) (defn set-val "Create a parser that set's the value associated with 'k' to 'v'" [k v] (m/bind (update-state #(assoc % k v)) #(parser (get % k)))) (defn item-test "A parser to test the next item to be parsed and proceed only if the result is true." [pred] (parser-do [c next-item :when (pred c)] c)) (defn is-item "A parser to see if the next item to be parsed equals 'item'" [item] (item-test (partial = item))) A parser to match one binding clause in a proc - do binding block (def match-binding-clause (parser-do [bound next-item _ (is-item '<-) arrow next-item _ (is-item '-<) expr next-item env (get-val :env) arr (get-val :arr) final-env (set-val :env (conj env bound))] `[(arrows/seq (~arr (partial repeat 2)) (arrows/par (~arr identity) ~(if (= expr '_) arrow `(arrows/seq (~arr (fn [~(vec env)] ~expr)) ~arrow)))) (~arr (partial apply conj))])) ;; A parser to match a :let clause in a proc-do binding block (def match-let-clause (parser-do [_ (is-item :let) bindings next-item :let [pairs (partition 2 bindings) bound (map first pairs)] env (get-val :env) arr (get-val :arr) _ (set-val :env (concat env bound))] `[(arrows/all (~arr identity) (~arr (fn [~(vec env)] (let ~bindings [~@bound])))) (~arr (partial apply concat))])) ;; A parser that throws an exception when a binding clause is malformed (def malformed-clause (parser-do [cmd (get-val :cmd) :when (seq cmd)] (throw (Exception. (str "Malformed 'proc-do' expression: " cmd))))) ;; A parser to match any clause in a proc-do binding block (def match-clause (m/plus [match-binding-clause match-let-clause malformed-clause])) ;; A parser to match all the clauses in a proc-do binding block (def match-clauses (one-or-more match-clause)) ;; A parser to match proc-do expression (def match-do (parser-do [_ (is-item 'proc-do) starting-env (get-val :env) arr (get-val :arr) bindings next-item :let [[bindings {env :env}] (match-clauses {:env starting-env :arr arr :cmd bindings})] final-expr next-item] (if (nil? bindings) (throw (Exception. "Malformed 'proc-do' expression")) `(arrows/seq (~arr vector) ~@(apply concat bindings) (~arr (fn [~(vec env)] ~final-expr)))))) ;; A parser to match a proc-if expression (def match-if (parser-do [_ (is-item 'proc-if) env (get-val :env) arr (get-val :arr) pred next-item true-expr next-item false-expr next-item] `(arrows/seq (~arr (fn [v#] (let [~@env v#] [(boolean ~pred) v#]))) (arrows/cond true ~true-expr (symbol "_") ~false-expr)))) ;; A parser to match a proc application expression (def match-application (parser-do [arr (get-val :arr) env (get-val :env) arrow next-item expr next-item] `(arrows/seq (~arr (fn [v#] (let [~@env v#] ~expr))) ~arrow))) ;; A parser to match any proc expression (def match-proc (m/plus [match-do match-if match-application]))
null
https://raw.githubusercontent.com/LonoCloud/arrows/2def9db48e684913d51da3065b010687041caf4f/src/arrows/proc.clj
clojure
A simple parser to parse proc expressions a parser that removes the next item from what is being parsed a parser that returns the entire parser state A parser to match a :let clause in a proc-do binding block A parser that throws an exception when a binding clause is malformed A parser to match any clause in a proc-do binding block A parser to match all the clauses in a proc-do binding block A parser to match proc-do expression A parser to match a proc-if expression A parser to match a proc application expression A parser to match any proc expression
(ns arrows.proc (:require [monads.core :as m] [monads.macros :as mm])) (deftype parser-m [v mv f] clojure.lang.IFn (invoke [_ s] (if f (if-let [[v ss] (mv s)] ((f v) ss) nil) [v s])) m/Monad (do-result [_ v] (parser-m. v nil nil)) (bind [mv f] (parser-m. nil mv f)) m/MonadZero (zero [_] (constantly nil)) (plus-step [mv mvs] (parser-m. nil (fn [s] (loop [[mv & mvs] (cons mv mvs)] (when mv (if-let [result (mv s)] result (recur mvs))))) (fn [v] (parser-m. v nil nil))))) (defn parser "Create a parser that always returns a constant value 'v'" [v] (parser-m. v nil nil)) (defmacro parser-do [bindings expr] `(monads.macros/do arrows.proc/parser ~bindings ~expr)) (defn optional "Create a parser for an optional element" [p] (m/plus [p (parser nil)])) (declare one-or-more) (defn none-or-more "Create a parser for zero or occurances of a given parser" [p] (optional (one-or-more p))) (defn one-or-more "Create a parser for one or occurances of a given parser" [p] (parser-do [a p as (none-or-more p)] (cons a as))) (def next-item (reify m/Monad (do-result [_ v] (parser v)) (bind [mv f] (fn [{:keys [cmd] :as state}] (when (seq cmd) ((f (first cmd)) (update-in state [:cmd] rest))))))) (def get-state (reify clojure.lang.IFn (invoke [_ s] [s s]) m/Monad (do-result [_ v] (parser v)) (bind [mv f] (parser-m. nil mv f)))) (defn get-val "Create a parser to get the value associated with 'k' in the parser state" [k] (m/bind get-state (fn [state] (parser (get state k))))) (defn update-state "Create a parser that will apply a function to the parser state" [f] (reify clojure.lang.IFn (invoke [_ s] (let [new-s (f s)] [new-s new-s])) m/Monad (do-result [_ v] (parser v)) (bind [mv f] (parser-m. nil mv f)))) (defn set-val "Create a parser that set's the value associated with 'k' to 'v'" [k v] (m/bind (update-state #(assoc % k v)) #(parser (get % k)))) (defn item-test "A parser to test the next item to be parsed and proceed only if the result is true." [pred] (parser-do [c next-item :when (pred c)] c)) (defn is-item "A parser to see if the next item to be parsed equals 'item'" [item] (item-test (partial = item))) A parser to match one binding clause in a proc - do binding block (def match-binding-clause (parser-do [bound next-item _ (is-item '<-) arrow next-item _ (is-item '-<) expr next-item env (get-val :env) arr (get-val :arr) final-env (set-val :env (conj env bound))] `[(arrows/seq (~arr (partial repeat 2)) (arrows/par (~arr identity) ~(if (= expr '_) arrow `(arrows/seq (~arr (fn [~(vec env)] ~expr)) ~arrow)))) (~arr (partial apply conj))])) (def match-let-clause (parser-do [_ (is-item :let) bindings next-item :let [pairs (partition 2 bindings) bound (map first pairs)] env (get-val :env) arr (get-val :arr) _ (set-val :env (concat env bound))] `[(arrows/all (~arr identity) (~arr (fn [~(vec env)] (let ~bindings [~@bound])))) (~arr (partial apply concat))])) (def malformed-clause (parser-do [cmd (get-val :cmd) :when (seq cmd)] (throw (Exception. (str "Malformed 'proc-do' expression: " cmd))))) (def match-clause (m/plus [match-binding-clause match-let-clause malformed-clause])) (def match-clauses (one-or-more match-clause)) (def match-do (parser-do [_ (is-item 'proc-do) starting-env (get-val :env) arr (get-val :arr) bindings next-item :let [[bindings {env :env}] (match-clauses {:env starting-env :arr arr :cmd bindings})] final-expr next-item] (if (nil? bindings) (throw (Exception. "Malformed 'proc-do' expression")) `(arrows/seq (~arr vector) ~@(apply concat bindings) (~arr (fn [~(vec env)] ~final-expr)))))) (def match-if (parser-do [_ (is-item 'proc-if) env (get-val :env) arr (get-val :arr) pred next-item true-expr next-item false-expr next-item] `(arrows/seq (~arr (fn [v#] (let [~@env v#] [(boolean ~pred) v#]))) (arrows/cond true ~true-expr (symbol "_") ~false-expr)))) (def match-application (parser-do [arr (get-val :arr) env (get-val :env) arrow next-item expr next-item] `(arrows/seq (~arr (fn [v#] (let [~@env v#] ~expr))) ~arrow))) (def match-proc (m/plus [match-do match-if match-application]))
fb83c0c4aed5d4f28cc486a9500ab6e5abc14ccf69952b075c4a2f590d1cf0d3
yesodweb/persistent
UpsertTest.hs
module UpsertTest where import Data.Function (on) import Init import PersistentTestModels -- | MongoDB assumes that a @NULL@ value in the database is some "empty" value . So a query that does @+ 2@ to a @NULL@ value results in @2@. SQL databases instead " annihilate " with null , so + 2 = NULL@. data BackendNullUpdateBehavior = AssumeNullIsZero | Don'tUpdateNull -- | @UPSERT@ on SQL databses does an "update-or-insert," which preserves -- all prior values, including keys. MongoDB does not preserve the -- identifier, so the entity key changes on an upsert. data BackendUpsertKeyBehavior = UpsertGenerateNewKey | UpsertPreserveOldKey specsWith :: forall backend m. Runner backend m => RunDb backend m -> BackendNullUpdateBehavior -> BackendUpsertKeyBehavior -> Spec specsWith runDb handleNull handleKey = describe "UpsertTests" $ do let ifKeyIsPreserved expectation = case handleKey of UpsertGenerateNewKey -> pure () UpsertPreserveOldKey -> expectation describe "upsert" $ do it "adds a new row with no updates" $ runDb $ do Entity _ u <- upsert (Upsert "a" "new" "" 2) [UpsertAttr =. "update"] c <- count ([] :: [Filter (UpsertGeneric backend)]) c @== 1 upsertAttr u @== "new" it "keeps the existing row" $ runDb $ do Entity k0 initial <- insertEntity (Upsert "a" "initial" "" 1) Entity k1 update' <- upsert (Upsert "a" "update" "" 2) [] update' @== initial ifKeyIsPreserved $ k0 @== k1 it "updates an existing row - assignment" $ runDb $ do -- #ifdef WITH_MONGODB initial < - insertEntity ( Upsert " cow " " initial " " extra " 1 ) -- update' <- upsert ( Upsert " cow " " wow " " such unused " 2 ) [ UpsertAttr = . " update " ] -- ((==@) `on` entityKey) initial update' -- upsertAttr (entityVal update') @== "update" upsertExtra ( entityVal update ' ) @== " extra " -- #else initial <- insertEntity (Upsert "a" "initial" "extra" 1) update' <- upsert (Upsert "a" "wow" "such unused" 2) [UpsertAttr =. "update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertAttr (entityVal update') @== "update" upsertExtra (entityVal update') @== "extra" -- #endif it "updates existing row - addition " $ runDb $ do -- #ifdef WITH_MONGODB initial < - insertEntity ( Upsert " a1 " " initial " " extra " 2 ) -- update' <- upsert ( " a1 " " wow " " such unused " 2 ) [ UpsertAge + = . 3 ] -- ((==@) `on` entityKey) initial update' upsertAge ( entityVal update ' ) @== 5 upsertExtra ( entityVal update ' ) @== " extra " -- #else initial <- insertEntity (Upsert "a" "initial" "extra" 2) update' <- upsert (Upsert "a" "wow" "such unused" 2) [UpsertAge +=. 3] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertAge (entityVal update') @== 5 upsertExtra (entityVal update') @== "extra" -- #endif describe "upsertBy" $ do let uniqueEmail = UniqueUpsertBy "a" _uniqueCity = UniqueUpsertByCity "Boston" it "adds a new row with no updates" $ runDb $ do Entity _ u <- upsertBy uniqueEmail (UpsertBy "a" "Boston" "new") [UpsertByAttr =. "update"] c <- count ([] :: [Filter (UpsertByGeneric backend)]) c @== 1 upsertByAttr u @== "new" it "keeps the existing row" $ runDb $ do Entity k0 initial <- insertEntity (UpsertBy "a" "Boston" "initial") Entity k1 update' <- upsertBy uniqueEmail (UpsertBy "a" "Boston" "update") [] update' @== initial ifKeyIsPreserved $ k0 @== k1 it "updates an existing row" $ runDb $ do -- #ifdef WITH_MONGODB initial < - insertEntity ( UpsertBy " ko " " Kumbakonam " " initial " ) -- update' <- upsertBy ( UniqueUpsertBy " " ) ( UpsertBy " ko " " Bangalore " " such unused " ) -- [UpsertByAttr =. "update"] -- ((==@) `on` entityKey) initial update' -- upsertByAttr (entityVal update') @== "update" upsertByCity ( entityVal update ' ) @== " Kumbakonam " -- #else initial <- insertEntity (UpsertBy "a" "Boston" "initial") update' <- upsertBy uniqueEmail (UpsertBy "a" "wow" "such unused") [UpsertByAttr =. "update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertByAttr (entityVal update') @== "update" upsertByCity (entityVal update') @== "Boston" -- #endif it "updates by the appropriate constraint" $ runDb $ do initBoston <- insertEntity (UpsertBy "bos" "Boston" "bos init") initKrum <- insertEntity (UpsertBy "krum" "Krum" "krum init") updBoston <- upsertBy (UniqueUpsertBy "bos") (UpsertBy "bos" "Krum" "unused") [UpsertByAttr =. "bos update"] updKrum <- upsertBy (UniqueUpsertByCity "Krum") (UpsertBy "bos" "Krum" "unused") [UpsertByAttr =. "krum update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initBoston updBoston ifKeyIsPreserved $ ((==@) `on` entityKey) initKrum updKrum entityVal updBoston @== UpsertBy "bos" "Boston" "bos update" entityVal updKrum @== UpsertBy "krum" "Krum" "krum update" it "maybe update" $ runDb $ do let noAge = PersonMaybeAge "Michael" Nothing keyNoAge <- insert noAge noAge2 <- updateGet keyNoAge [PersonMaybeAgeAge +=. Just 2] -- the correct answer depends on the backend. MongoDB assumes a ' Nothing ' value is 0 , and does @0 + 2@ for @Just 2@. In a SQL database , @NULL@ annihilates , so + 2 = NULL@. personMaybeAgeAge noAge2 @== case handleNull of AssumeNullIsZero -> Just 2 Don'tUpdateNull -> Nothing describe "putMany" $ do it "adds new rows when entity has no unique constraints" $ runDb $ do let mkPerson name_ = Person1 name_ 25 let names = ["putMany bob", "putMany bob", "putMany smith"] let records = map mkPerson names _ <- putMany records entitiesDb <- selectList [Person1Name <-. names] [] let recordsDb = fmap entityVal entitiesDb recordsDb @== records deleteWhere [Person1Name <-. names] it "adds new rows when no conflicts" $ runDb $ do let mkUpsert e = Upsert e "new" "" 1 let keys = ["putMany1","putMany2","putMany3"] let vals = map mkUpsert keys _ <- putMany vals Just (Entity _ v1) <- getBy $ UniqueUpsert "putMany1" Just (Entity _ v2) <- getBy $ UniqueUpsert "putMany2" Just (Entity _ v3) <- getBy $ UniqueUpsert "putMany3" [v1,v2,v3] @== vals deleteBy $ UniqueUpsert "putMany1" deleteBy $ UniqueUpsert "putMany2" deleteBy $ UniqueUpsert "putMany3" it "handles conflicts by replacing old keys with new records" $ runDb $ do let mkUpsert1 e = Upsert e "new" "" 1 let mkUpsert2 e = Upsert e "new" "" 2 let vals = map mkUpsert2 ["putMany4", "putMany5", "putMany6", "putMany7"] Entity k1 _ <- insertEntity $ mkUpsert1 "putMany4" Entity k2 _ <- insertEntity $ mkUpsert1 "putMany5" _ <- putMany $ mkUpsert1 "putMany4" : vals Just e1 <- getBy $ UniqueUpsert "putMany4" Just e2 <- getBy $ UniqueUpsert "putMany5" Just e3@(Entity k3 _) <- getBy $ UniqueUpsert "putMany6" Just e4@(Entity k4 _) <- getBy $ UniqueUpsert "putMany7" [e1,e2,e3,e4] @== [ Entity k1 (mkUpsert2 "putMany4") , Entity k2 (mkUpsert2 "putMany5") , Entity k3 (mkUpsert2 "putMany6") , Entity k4 (mkUpsert2 "putMany7") ] deleteBy $ UniqueUpsert "putMany4" deleteBy $ UniqueUpsert "putMany5" deleteBy $ UniqueUpsert "putMany6" deleteBy $ UniqueUpsert "putMany7"
null
https://raw.githubusercontent.com/yesodweb/persistent/bf4c3ae430d7e7ec0351a768783d73e6bd265890/persistent-test/src/UpsertTest.hs
haskell
| MongoDB assumes that a @NULL@ value in the database is some "empty" | @UPSERT@ on SQL databses does an "update-or-insert," which preserves all prior values, including keys. MongoDB does not preserve the identifier, so the entity key changes on an upsert. #ifdef WITH_MONGODB update' <- ((==@) `on` entityKey) initial update' upsertAttr (entityVal update') @== "update" #else #endif #ifdef WITH_MONGODB update' <- ((==@) `on` entityKey) initial update' #else #endif #ifdef WITH_MONGODB update' <- [UpsertByAttr =. "update"] ((==@) `on` entityKey) initial update' upsertByAttr (entityVal update') @== "update" #else #endif the correct answer depends on the backend. MongoDB assumes
module UpsertTest where import Data.Function (on) import Init import PersistentTestModels value . So a query that does @+ 2@ to a @NULL@ value results in @2@. SQL databases instead " annihilate " with null , so + 2 = NULL@. data BackendNullUpdateBehavior = AssumeNullIsZero | Don'tUpdateNull data BackendUpsertKeyBehavior = UpsertGenerateNewKey | UpsertPreserveOldKey specsWith :: forall backend m. Runner backend m => RunDb backend m -> BackendNullUpdateBehavior -> BackendUpsertKeyBehavior -> Spec specsWith runDb handleNull handleKey = describe "UpsertTests" $ do let ifKeyIsPreserved expectation = case handleKey of UpsertGenerateNewKey -> pure () UpsertPreserveOldKey -> expectation describe "upsert" $ do it "adds a new row with no updates" $ runDb $ do Entity _ u <- upsert (Upsert "a" "new" "" 2) [UpsertAttr =. "update"] c <- count ([] :: [Filter (UpsertGeneric backend)]) c @== 1 upsertAttr u @== "new" it "keeps the existing row" $ runDb $ do Entity k0 initial <- insertEntity (Upsert "a" "initial" "" 1) Entity k1 update' <- upsert (Upsert "a" "update" "" 2) [] update' @== initial ifKeyIsPreserved $ k0 @== k1 it "updates an existing row - assignment" $ runDb $ do initial < - insertEntity ( Upsert " cow " " initial " " extra " 1 ) upsert ( Upsert " cow " " wow " " such unused " 2 ) [ UpsertAttr = . " update " ] upsertExtra ( entityVal update ' ) @== " extra " initial <- insertEntity (Upsert "a" "initial" "extra" 1) update' <- upsert (Upsert "a" "wow" "such unused" 2) [UpsertAttr =. "update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertAttr (entityVal update') @== "update" upsertExtra (entityVal update') @== "extra" it "updates existing row - addition " $ runDb $ do initial < - insertEntity ( Upsert " a1 " " initial " " extra " 2 ) upsert ( " a1 " " wow " " such unused " 2 ) [ UpsertAge + = . 3 ] upsertAge ( entityVal update ' ) @== 5 upsertExtra ( entityVal update ' ) @== " extra " initial <- insertEntity (Upsert "a" "initial" "extra" 2) update' <- upsert (Upsert "a" "wow" "such unused" 2) [UpsertAge +=. 3] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertAge (entityVal update') @== 5 upsertExtra (entityVal update') @== "extra" describe "upsertBy" $ do let uniqueEmail = UniqueUpsertBy "a" _uniqueCity = UniqueUpsertByCity "Boston" it "adds a new row with no updates" $ runDb $ do Entity _ u <- upsertBy uniqueEmail (UpsertBy "a" "Boston" "new") [UpsertByAttr =. "update"] c <- count ([] :: [Filter (UpsertByGeneric backend)]) c @== 1 upsertByAttr u @== "new" it "keeps the existing row" $ runDb $ do Entity k0 initial <- insertEntity (UpsertBy "a" "Boston" "initial") Entity k1 update' <- upsertBy uniqueEmail (UpsertBy "a" "Boston" "update") [] update' @== initial ifKeyIsPreserved $ k0 @== k1 it "updates an existing row" $ runDb $ do initial < - insertEntity ( UpsertBy " ko " " Kumbakonam " " initial " ) upsertBy ( UniqueUpsertBy " " ) ( UpsertBy " ko " " Bangalore " " such unused " ) upsertByCity ( entityVal update ' ) @== " Kumbakonam " initial <- insertEntity (UpsertBy "a" "Boston" "initial") update' <- upsertBy uniqueEmail (UpsertBy "a" "wow" "such unused") [UpsertByAttr =. "update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initial update' upsertByAttr (entityVal update') @== "update" upsertByCity (entityVal update') @== "Boston" it "updates by the appropriate constraint" $ runDb $ do initBoston <- insertEntity (UpsertBy "bos" "Boston" "bos init") initKrum <- insertEntity (UpsertBy "krum" "Krum" "krum init") updBoston <- upsertBy (UniqueUpsertBy "bos") (UpsertBy "bos" "Krum" "unused") [UpsertByAttr =. "bos update"] updKrum <- upsertBy (UniqueUpsertByCity "Krum") (UpsertBy "bos" "Krum" "unused") [UpsertByAttr =. "krum update"] ifKeyIsPreserved $ ((==@) `on` entityKey) initBoston updBoston ifKeyIsPreserved $ ((==@) `on` entityKey) initKrum updKrum entityVal updBoston @== UpsertBy "bos" "Boston" "bos update" entityVal updKrum @== UpsertBy "krum" "Krum" "krum update" it "maybe update" $ runDb $ do let noAge = PersonMaybeAge "Michael" Nothing keyNoAge <- insert noAge noAge2 <- updateGet keyNoAge [PersonMaybeAgeAge +=. Just 2] a ' Nothing ' value is 0 , and does @0 + 2@ for @Just 2@. In a SQL database , @NULL@ annihilates , so + 2 = NULL@. personMaybeAgeAge noAge2 @== case handleNull of AssumeNullIsZero -> Just 2 Don'tUpdateNull -> Nothing describe "putMany" $ do it "adds new rows when entity has no unique constraints" $ runDb $ do let mkPerson name_ = Person1 name_ 25 let names = ["putMany bob", "putMany bob", "putMany smith"] let records = map mkPerson names _ <- putMany records entitiesDb <- selectList [Person1Name <-. names] [] let recordsDb = fmap entityVal entitiesDb recordsDb @== records deleteWhere [Person1Name <-. names] it "adds new rows when no conflicts" $ runDb $ do let mkUpsert e = Upsert e "new" "" 1 let keys = ["putMany1","putMany2","putMany3"] let vals = map mkUpsert keys _ <- putMany vals Just (Entity _ v1) <- getBy $ UniqueUpsert "putMany1" Just (Entity _ v2) <- getBy $ UniqueUpsert "putMany2" Just (Entity _ v3) <- getBy $ UniqueUpsert "putMany3" [v1,v2,v3] @== vals deleteBy $ UniqueUpsert "putMany1" deleteBy $ UniqueUpsert "putMany2" deleteBy $ UniqueUpsert "putMany3" it "handles conflicts by replacing old keys with new records" $ runDb $ do let mkUpsert1 e = Upsert e "new" "" 1 let mkUpsert2 e = Upsert e "new" "" 2 let vals = map mkUpsert2 ["putMany4", "putMany5", "putMany6", "putMany7"] Entity k1 _ <- insertEntity $ mkUpsert1 "putMany4" Entity k2 _ <- insertEntity $ mkUpsert1 "putMany5" _ <- putMany $ mkUpsert1 "putMany4" : vals Just e1 <- getBy $ UniqueUpsert "putMany4" Just e2 <- getBy $ UniqueUpsert "putMany5" Just e3@(Entity k3 _) <- getBy $ UniqueUpsert "putMany6" Just e4@(Entity k4 _) <- getBy $ UniqueUpsert "putMany7" [e1,e2,e3,e4] @== [ Entity k1 (mkUpsert2 "putMany4") , Entity k2 (mkUpsert2 "putMany5") , Entity k3 (mkUpsert2 "putMany6") , Entity k4 (mkUpsert2 "putMany7") ] deleteBy $ UniqueUpsert "putMany4" deleteBy $ UniqueUpsert "putMany5" deleteBy $ UniqueUpsert "putMany6" deleteBy $ UniqueUpsert "putMany7"
5ef71875f7114ccb7357210c63bed59bf317517fbbfdd01ae852fefd55cad5dc
kaznum/programming_in_ocaml_exercise
inord.ml
type 'a tree = Lf | Br of 'a * 'a tree * 'a tree;; let comptree = Br(1, Br(2, Br(4, Lf, Lf),Br(5, Lf, Lf)), Br(3, Br(6, Lf, Lf), Br(7, Lf, Lf)));; let rec inord t l = match t with Lf -> l | Br(x, left, right) -> (inord left (x::(inord right l)));; inord comptree [];;
null
https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ex6.6/inord.ml
ocaml
type 'a tree = Lf | Br of 'a * 'a tree * 'a tree;; let comptree = Br(1, Br(2, Br(4, Lf, Lf),Br(5, Lf, Lf)), Br(3, Br(6, Lf, Lf), Br(7, Lf, Lf)));; let rec inord t l = match t with Lf -> l | Br(x, left, right) -> (inord left (x::(inord right l)));; inord comptree [];;