_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
f72fe43ce90f45e2b49e74a5f2934b526076f0181da83e9fdc67a4cbf5b5edea
yetibot/core
about.clj
(ns yetibot.core.commands.about (:require [yetibot.core.hooks :refer [cmd-hook]])) (defn about-cmd "about # about Yetibot" {:yb/cat #{:info}} [& _] {:result/data {:about/url "" :about/name "Yetibot" :about/logo "" :about/description (str "Yetibot is a chat bot written in Clojure;" \newline "it wants to make your life easier;" \newline "it wants you to have fun.") :about/author "@devth"} :result/value ["" "Yetibot is a chat bot written in Clojure;" "it wants to make your life easier;" "it wants you to have fun." ""]}) (cmd-hook #"about" _ about-cmd)
null
https://raw.githubusercontent.com/yetibot/core/e35cc772622e91aec3ad7f411a99fff09acbd3f9/src/yetibot/core/commands/about.clj
clojure
(ns yetibot.core.commands.about (:require [yetibot.core.hooks :refer [cmd-hook]])) (defn about-cmd "about # about Yetibot" {:yb/cat #{:info}} [& _] {:result/data {:about/url "" :about/name "Yetibot" :about/logo "" :about/description (str "Yetibot is a chat bot written in Clojure;" \newline "it wants to make your life easier;" \newline "it wants you to have fun.") :about/author "@devth"} :result/value ["" "Yetibot is a chat bot written in Clojure;" "it wants to make your life easier;" "it wants you to have fun." ""]}) (cmd-hook #"about" _ about-cmd)
dce867d484b915c36e8ba3c3f28c5b25c39b68f588e265147fc1661813b63b91
metosin/ring-swagger
swagger2_test.clj
(ns ring.swagger.swagger2-test (:require [schema.core :as s] [ring.swagger.swagger2 :as swagger2] [ring.swagger.swagger2-full-schema :as full-schema] [ring.swagger.json-schema :as rsjs] [ring.swagger.extension :as extension] [ring.swagger.validator :as validator] [linked.core :as linked] [ring.util.http-status :as status] [midje.sweet :refer :all]) (:import [java.util Date UUID] [java.util.regex Pattern] [org.joda.time DateTime LocalDate LocalTime] (java.io File))) (s/defschema Anything {s/Keyword s/Any}) (s/defschema Nothing {}) (s/defschema LegOfPet {:length Long}) (s/defschema Pet {:id Long :name String :leg LegOfPet (s/optional-key :weight) Double}) (s/defschema Parrot {:name String :type {:name String}}) (s/defschema Turtle {:name String :tags (s/if map? {s/Keyword s/Keyword} [String])}) (s/defschema NotFound {:message s/Str}) (defn validate-swagger-json [swagger & [options]] (s/with-fn-validation (validator/validate (swagger2/swagger-json swagger options)))) (defn validate [swagger & [options]] (s/with-fn-validation (if-let [input-errors (s/check swagger2/Swagger swagger)] {:input-errors input-errors} (if-let [output-errors (validate-swagger-json swagger options)] {:output-errors output-errors})))) (def a-complete-swagger {:swagger "2.0" :info {:version "version" :title "title" :description "description" :termsOfService "jeah" :contact {:name "name" :url "" :email ""} :license {:name "name" :url ""} :x-kikka "jeah"} :host "somehost:8080" :externalDocs {:url "" :description "more info"} :basePath "/" :schemes [] :parameters {} :responses {} :securityDefinitions {} :security [] :tags [{:name "pet", :description "Everything about your Pets", :externalDocs {:description "Find out more", :url ""}} {:name "store", :description "Access to Petstore orders"} {:name "user", :description "Operations about user", :externalDocs {:description "Find out more about our store", :url ""}}] :consumes ["application/json" "application/edn"] :produces ["application/json" "application/edn"] :paths {"/api/:id" {:get {:tags ["pet"] :summary "summary" :description "description" :externalDocs {:url "" :description "more info"} :operationId "operationId" :consumes ["application/xyz"] :produces ["application/xyz"] :parameters {:body nil :query (merge Anything {:x Long :y Long}) :path {:id String} :header Anything :formData Anything} :responses {200 {:description "ok" :schema nil} 400 {:description "not found" :schema NotFound} :default {:description "error" :schema {:code Long}}}}} "/api/parrots" {:get {:responses {200 {:schema Parrot :description ""}}}} "/api/all-types" {:get {:parameters {:body {:a Boolean :b Double :c Long :d String :e {:f [s/Keyword] :g #{String} :h #{(s/enum :kikka :kakka :kukka)} :i Date :j DateTime :k LocalDate :k2 LocalTime :l (s/maybe String) :m (s/both Long (s/pred odd? 'odd?)) :o [{:p #{{:q String}}}] :u UUID :v Pattern :w #"a[6-9]"}}} :responses {200 {:description "file" :schema File}}}} "/api/pets" {:get {:parameters {:body Pet :query (merge Anything {:x Long :y Long}) :path Nothing :header Anything :formData Anything} :responses {200 {:description "ok" :schema {:sum Long}} :default {:description "error" :schema {:code Long}}}} :post {:parameters {:body #{Pet} :query (merge Anything {:x Long :y Long})} :responses {200 {:schema {:sum Long}} :default {:schema {:code Long} :headers {:location String}}}} :put {:parameters {:body [(s/maybe Pet)] :query {:x (s/maybe String)}} :responses {200 {:description "ok" :schema {:sum (s/maybe Long)}} :default {:description "error"}}}} "/api/turtle" {:get {:parameters {:body Turtle :query (merge Anything {:x Long :y Long}) :path Nothing :header Anything :formData Anything} :responses {200 {:description "ok" :schema {:sum Long}} :default {:description "error" :schema {:code Long}}}} :post {:parameters {:body #{Turtle} :query (merge Anything {:x Long :y Long})} :responses {200 {:schema {:sum Long}} :default {:schema {:code Long} :headers {:location String}}}} :put {:parameters {:body [(s/maybe Turtle)] :query {:x (s/maybe String)}} :responses {200 {:description "ok" :schema {:sum (s/maybe Long)}} :default {:description "error"}}}}}}) ;; ;; facts ;; (fact "empty spec" (let [swagger {}] (validate swagger) => nil)) (fact "minimalistic spec" (let [swagger {:paths {"/ping" {:get nil}}}] (validate swagger) => nil)) (fact "more complete spec" (validate a-complete-swagger) => nil) (extension/java-time (fact "spec with java.time" (let [model {:i java.time.Instant :ld java.time.LocalDate :lt java.time.LocalTime} swagger {:paths {"/time" {:post {:parameters {:body model}}}}}] (validate swagger) => nil))) (defrecord InvalidElement []) (facts "with missing schema -> json schema mappings" (fact "non-body-parameters" (let [swagger {:paths {"/hello" {:get {:parameters {:query {:name InvalidElement}}}}}}] (fact "dy default, exception is throws when generating json schema" (validate swagger) => (throws IllegalArgumentException)) (fact "with :ignore-missing-mappings errors (and mappings) are ignored" (validate swagger {:ignore-missing-mappings? true}) => nil))) (fact "body-parameters" (let [swagger {:paths {"/hello" {:post {:parameters {:body {:name InvalidElement :age s/Num}}}}}}] (fact "dy default, exception is throws when generating json schema" (validate swagger) => (throws IllegalArgumentException)) (fact "with :ignore-missing-mappings errors (and mappings) are ignored" (validate swagger {:ignore-missing-mappings? true}) => nil)))) (facts "handling empty responses" (let [swagger {:paths {"/hello" {:post {:responses {200 nil 425 nil 500 {:description "FAIL"}}}}}}] (fact "with defaults" (validate swagger) => nil (swagger2/swagger-json swagger) => (contains {:paths {"/hello" {:post {:responses {200 {:description ""} 425 {:description ""} 500 {:description "FAIL"}}}}}})) (fact ":default-response-description-fn option overriden" (let [options {:default-response-description-fn status/get-description}] (validate swagger options) => nil (swagger2/swagger-json swagger options) => (contains {:paths {"/hello" {:post {:responses {200 {:description "OK"} 425 {:description "The collection is unordered."} 500 {:description "FAIL"}}}}}}))))) (s/defschema Response {:id s/Str}) (defn schema-name [m] (-> m first val (subs (.length "#/definitions/")))) (def valid-reference (just {:$ref anything})) (def valid-optional-reference (just {:$ref anything :x-nullable true})) (defn extract-schema [swagger-spec uri path f] (let [operation (get-in swagger-spec [:paths uri :post]) definitions (:definitions swagger-spec) schema (get-in operation (conj path :schema)) name (schema-name (f schema))] {:name name :schema schema :defined? (boolean (definitions name))})) (facts "transforming subschemas" (let [model {:id s/Str} swagger {:paths {"/resp" {:post {:responses {200 {:schema Response} 201 {:schema [model]} 202 {:schema #{model}} 203 {:schema (s/maybe model)} 204 {:schema [(s/maybe model)]} 205 {:schema #{(s/maybe model)}}}}} "/body1" {:post {:parameters {:body model}}} "/body2" {:post {:parameters {:body [model]}}} "/body3" {:post {:parameters {:body #{model}}}} "/body4" {:post {:parameters {:body (s/maybe model)}}} "/body5" {:post {:parameters {:body [(s/maybe model)]}}} "/body6" {:post {:parameters {:body #{(s/maybe model)}}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil (tabular (fact "body and response schemas in all flavours" (let [{:keys [name schema defined?]} (extract-schema spec ?uri ?path ?fn)] schema => ?schema name => ?name defined? => true)) ?uri ?path ?fn ?name ?schema ;; body models "/body1" [:parameters 0] identity #"Body.*" valid-reference "/body2" [:parameters 0] :items #"Body.*" (just {:items valid-reference, :type "array"}) "/body3" [:parameters 0] :items #"Body.*" (just {:items valid-reference, :type "array", :uniqueItems true}) "/body4" [:parameters 0] identity #"Body.*" valid-optional-reference "/body5" [:parameters 0] :items #"Body.*" (just {:items valid-optional-reference, :type "array"}) "/body6" [:parameters 0] :items #"Body.*" (just {:items valid-optional-reference, :type "array", :uniqueItems true}) ;; response models "/resp" [:responses 200] identity "Response" valid-reference "/resp" [:responses 201] :items #"Response.*" (just {:items valid-reference, :type "array"}) "/resp" [:responses 202] :items #"Response.*" (just {:items valid-reference, :type "array", :uniqueItems true}) "/resp" [:responses 203] identity #"Response.*" valid-optional-reference "/resp" [:responses 204] :items #"Response.*" (just {:items valid-optional-reference, :type "array"}) "/resp" [:responses 205] :items #"Response.*" (just {:items valid-optional-reference, :type "array", :uniqueItems true})))) (fact "multiple different schemas with same name" (let [model1 (s/schema-with-name {:id s/Str} 'Kikka) model2 (s/schema-with-name {:id s/Int} 'Kikka) swagger {:paths {"/body" {:post {:parameters {:body {:1 model1, :2 model2}}}}}}] (fact "with default options" (validate swagger) => nil) (fact "with overriden options" (validate swagger {:handle-duplicate-schemas-fn ring.swagger.core/fail-on-duplicate-schema!}) => (throws IllegalArgumentException)))) (defn has-definition [schema-name value] (chatty-checker [actual] (= (get-in actual [:definitions (name schema-name)]) value))) (fact "additionalProperties" (let [Kikka (s/schema-with-name {:a s/Str s/Str s/Str} 'Kikka) Kukka (s/schema-with-name {:a s/Str s/Int Kikka} 'Kukka) Kakka (s/schema-with-name {s/Keyword Kukka} 'Kakka) swagger {:paths {"/kikka" {:post {:parameters {:body Kikka}}} "/kukka" {:post {:parameters {:body Kukka}}} "/kakka" {:post {:parameters {:body Kakka}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil (fact "keyword to primitive mapping" spec => (has-definition 'Kikka {:type "object" :properties {:a {:type "string"}} :additionalProperties {:type "string"} :required [:a]})) (fact "keyword to model mapping" spec => (has-definition 'Kukka {:type "object" :properties {:a {:type "string"}} :additionalProperties {:$ref "#/definitions/Kikka"} :required [:a]})) (fact "just additional properties" spec => (has-definition 'Kakka {:type "object" :additionalProperties {:$ref "#/definitions/Kukka"}})))) (fact "extra meta-data to properties" (let [Kikka (s/schema-with-name {:a (rsjs/field s/Str {:description "A"}) :b (rsjs/field [s/Str] {:description "B"})} 'Kikka) swagger {:paths {"/kikka" {:post {:parameters {:body Kikka}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil spec => (has-definition 'Kikka {:type "object" :properties {:a {:type "string" :description "A"} :b {:type "array" :items {:type "string"} :description "B"}} :additionalProperties false :required [:a :b]}))) (fact "tags" (let [swagger {:tags [{:name "pet" :description "Everything about your Pets" :externalDocs {:description "Find out more" :url ""}} {:name "store" :description "Operations about user"}] :paths {"/pet" {:post {:tags ["pet"]}} "/store" {:post {:tags ["store"]}}}}] (validate swagger) => nil)) (fact "retain :paths order, #54" (let [->path (fn [x] (str "/" x)) paths (reduce (fn [acc x] (assoc acc (->path x) {:get {}})) (linked/map) (range 100)) swagger {:paths paths} spec (swagger2/swagger-json swagger)] (-> spec :paths keys) => (map ->path (range 100)))) (fact "transform-operations" (let [remove-x-no-doc (fn [endpoint] (if-not (some-> endpoint :x-no-doc true?) endpoint)) swagger {:paths {"/a" {:get {:x-no-doc true}, :post {}} "/b" {:put {:x-no-doc true}}}}] (swagger2/transform-operations remove-x-no-doc swagger) => {:paths {"/a" {:post {}}}} (swagger2/transform-operations remove-x-no-doc {:paths {"/a" {:get {:x-no-doc true}, :post {}} "/b" {:put {:x-no-doc true}}}}))) (s/defschema SchemaA {:a s/Str}) (s/defschema SchemaB {:b s/Str}) (fact "s/either stuff is correctly named" (-> (swagger2/swagger-json {:paths {"/ab" {:get {:parameters {:body (s/either SchemaA SchemaB)}}}}}) (get-in [:paths "/ab" :get :parameters 0])) => {:in "body" :name "SchemaA" :description "" :required true :schema {:$ref "#/definitions/SchemaA"}}) (fact "body wrapped in Maybe make's it optional" (-> (swagger2/swagger-json {:paths {"/maybe" {:post {:parameters {:body (s/maybe {:kikka s/Str})}}}}}) (get-in [:paths "/maybe" :post :parameters 0])) => (contains {:in "body", :required false})) (fact "path-parameters with .dot extension, #82" (swagger2/swagger-json {:paths {"/api/:id.json" {:get {:parameters {:path {:id String}}}}}}) => (contains {:paths (just {"/api/{id}.json" (contains {:get (contains {:parameters (just [(contains {:name "id"})])})})})})) (fact "should validate full swagger 2 schema" (s/validate full-schema/Swagger a-complete-swagger) => a-complete-swagger) (s/defschema Required (rsjs/field {(s/optional-key :name) s/Str (s/optional-key :title) s/Str :address (rsjs/field {:street (rsjs/field s/Str {:description "description here"})} {:description "Streename" :example "Ankkalinna 1"})} {:minProperties 1 :description "I'm required" :example {:name "Iines" :title "Ankka"}})) (fact "models with extra meta, #96" (let [swagger {:paths {"/api" {:post {:parameters {:body Required}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {"Required" {:type "object" :description "I'm required" :example {:name "Iines" :title "Ankka"} :minProperties 1 :required [:address] :properties {:name {:type "string"} :title {:type "string"} :address {:$ref "#/definitions/RequiredAddress"}} :additionalProperties false} "RequiredAddress" {:type "object" :description "Streename" :example "Ankkalinna 1" :properties {:street {:type "string" :description "description here"}} :required [:street] :additionalProperties false}} :paths {"/api" {:post {:parameters [{:description "I'm required" :in "body" :name "Required" :required true :schema {:$ref "#/definitions/Required"}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (s/defschema OptionalMaybe {(s/optional-key :a) s/Str (s/optional-key :b) (s/maybe s/Str) :c (s/maybe s/Str)}) (fact "nillable fields, #97" (let [swagger {:paths {"/api" {:post {:parameters {:body (s/maybe OptionalMaybe)}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {"OptionalMaybe" {:type "object" :properties {:a {:type "string"} :b {:type "string" :x-nullable true} :c {:type "string" :x-nullable true}} :required [:c] :additionalProperties false}} :paths {"/api" {:post {:parameters [{:in "body" :name "OptionalMaybe" :description "" :required false :schema {:$ref "#/definitions/OptionalMaybe" :x-nullable true}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (s/defrecord Keyboard [type :- (s/enum :left :right)]) (s/defrecord User [age :- s/Int, keyboard :- Keyboard]) (fact "top-level & nested records are embedded" (let [swagger {:paths {"/api" {:post {:parameters {:body User}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "User" :description "" :required true :schema {:type "object" :title "User" :properties {:age {:format "int64" :type "integer"} :keyboard {:type "object" :title "Keyboard" :properties {:type {:type "string" :enum [:right :left]}} :required [:type] :additionalProperties false}} :required [:age :keyboard] :additionalProperties false}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (fact "primitive vector body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body [s/Str]} :responses {200 {:schema [s/Str]}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:items {:type "string"} :type "array"}}] :responses {200 {:description "" :schema {:items {:type "string"} :type "array"}}}}}}}) (validate swagger) => nil)) (fact "primitive set body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body #{s/Str}} :responses {200 {:schema #{s/Str}}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:items {:type "string"} :uniqueItems true :type "array"}}] :responses {200 {:description "" :schema {:items {:type "string"} :uniqueItems true :type "array"}}}}}}}) (validate swagger) => nil)) (fact "primitive body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body s/Str} :responses {200 {:schema s/Str}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:type "string"}}] :responses {200 {:description "" :schema {:type "string"}}}}}}}) (validate swagger) => nil)) (s/defschema Person {:age s/Int}) (def Adult (s/constrained Person #(>= (:age %) 18))) (fact "query parameters with ..., #104" (fact "constrained schema" (let [swagger {:paths {"/people" {:get {:parameters {:query Adult} :responses {200 {:schema s/Str}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/people" {:get {:parameters [{:in "query" :name "age" :description "" :required true :type "integer" :format "int64"}] :responses {200 {:description "" :schema {:type "string"}}}}}}}) (validate swagger) => nil)) (fact "top-level maybe schema" (let [swagger {:paths {"/" {:get {:parameters {:query (s/maybe {:a s/Str})}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/" {:get {:parameters [{:in "query" :name "a" :description "" :required true :type "string"}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (fact "nested maybe schema" (let [swagger {:paths {"/" {:get {:parameters {:query {:a (s/maybe s/Str)}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/" {:get {:parameters [{:in "query" :name "a" :description "" :required true :type "string" :allowEmptyValue true}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil))) (fact "qualified keywords" (let [swagger {:paths {"/any" {:get {:parameters {:query {:kikka/kukka String}} :responses {:default {:schema {:olipa/kerran String}}}}}}} endpoint (get-in (swagger2/swagger-json swagger) [:paths "/any" :get]) response (-> (swagger2/swagger-json swagger) :definitions first second)] (get-in endpoint [:parameters 0]) => (contains {:name "kikka/kukka"}) (get-in response [:properties]) => (contains {:olipa/kerran {:type "string"}}))) (fact "Meta-description of body responses are considered" (let [swagger {:paths {"/meta" {:get {:parameters {:query {:kikka/kukka String}} :responses {200 (rsjs/describe {:body {:kikka/kukka String}} "A meta description")}}} "/direct" {:get {:parameters {:query {:kikka/kukka String}} :responses {200 {:body {:kikka/kukka String} :description "A direct description"}}}}}}] (get-in (swagger2/swagger-json swagger) [:paths "/meta" :get :responses 200]) => (contains {:description "A meta description"}) (get-in (swagger2/swagger-json swagger) [:paths "/direct" :get :responses 200]) => (contains {:description "A direct description"})))
null
https://raw.githubusercontent.com/metosin/ring-swagger/0ef9046174dec0ebd4cbf97d6cc5c6846ef11996/test/ring/swagger/swagger2_test.clj
clojure
facts body models response models
(ns ring.swagger.swagger2-test (:require [schema.core :as s] [ring.swagger.swagger2 :as swagger2] [ring.swagger.swagger2-full-schema :as full-schema] [ring.swagger.json-schema :as rsjs] [ring.swagger.extension :as extension] [ring.swagger.validator :as validator] [linked.core :as linked] [ring.util.http-status :as status] [midje.sweet :refer :all]) (:import [java.util Date UUID] [java.util.regex Pattern] [org.joda.time DateTime LocalDate LocalTime] (java.io File))) (s/defschema Anything {s/Keyword s/Any}) (s/defschema Nothing {}) (s/defschema LegOfPet {:length Long}) (s/defschema Pet {:id Long :name String :leg LegOfPet (s/optional-key :weight) Double}) (s/defschema Parrot {:name String :type {:name String}}) (s/defschema Turtle {:name String :tags (s/if map? {s/Keyword s/Keyword} [String])}) (s/defschema NotFound {:message s/Str}) (defn validate-swagger-json [swagger & [options]] (s/with-fn-validation (validator/validate (swagger2/swagger-json swagger options)))) (defn validate [swagger & [options]] (s/with-fn-validation (if-let [input-errors (s/check swagger2/Swagger swagger)] {:input-errors input-errors} (if-let [output-errors (validate-swagger-json swagger options)] {:output-errors output-errors})))) (def a-complete-swagger {:swagger "2.0" :info {:version "version" :title "title" :description "description" :termsOfService "jeah" :contact {:name "name" :url "" :email ""} :license {:name "name" :url ""} :x-kikka "jeah"} :host "somehost:8080" :externalDocs {:url "" :description "more info"} :basePath "/" :schemes [] :parameters {} :responses {} :securityDefinitions {} :security [] :tags [{:name "pet", :description "Everything about your Pets", :externalDocs {:description "Find out more", :url ""}} {:name "store", :description "Access to Petstore orders"} {:name "user", :description "Operations about user", :externalDocs {:description "Find out more about our store", :url ""}}] :consumes ["application/json" "application/edn"] :produces ["application/json" "application/edn"] :paths {"/api/:id" {:get {:tags ["pet"] :summary "summary" :description "description" :externalDocs {:url "" :description "more info"} :operationId "operationId" :consumes ["application/xyz"] :produces ["application/xyz"] :parameters {:body nil :query (merge Anything {:x Long :y Long}) :path {:id String} :header Anything :formData Anything} :responses {200 {:description "ok" :schema nil} 400 {:description "not found" :schema NotFound} :default {:description "error" :schema {:code Long}}}}} "/api/parrots" {:get {:responses {200 {:schema Parrot :description ""}}}} "/api/all-types" {:get {:parameters {:body {:a Boolean :b Double :c Long :d String :e {:f [s/Keyword] :g #{String} :h #{(s/enum :kikka :kakka :kukka)} :i Date :j DateTime :k LocalDate :k2 LocalTime :l (s/maybe String) :m (s/both Long (s/pred odd? 'odd?)) :o [{:p #{{:q String}}}] :u UUID :v Pattern :w #"a[6-9]"}}} :responses {200 {:description "file" :schema File}}}} "/api/pets" {:get {:parameters {:body Pet :query (merge Anything {:x Long :y Long}) :path Nothing :header Anything :formData Anything} :responses {200 {:description "ok" :schema {:sum Long}} :default {:description "error" :schema {:code Long}}}} :post {:parameters {:body #{Pet} :query (merge Anything {:x Long :y Long})} :responses {200 {:schema {:sum Long}} :default {:schema {:code Long} :headers {:location String}}}} :put {:parameters {:body [(s/maybe Pet)] :query {:x (s/maybe String)}} :responses {200 {:description "ok" :schema {:sum (s/maybe Long)}} :default {:description "error"}}}} "/api/turtle" {:get {:parameters {:body Turtle :query (merge Anything {:x Long :y Long}) :path Nothing :header Anything :formData Anything} :responses {200 {:description "ok" :schema {:sum Long}} :default {:description "error" :schema {:code Long}}}} :post {:parameters {:body #{Turtle} :query (merge Anything {:x Long :y Long})} :responses {200 {:schema {:sum Long}} :default {:schema {:code Long} :headers {:location String}}}} :put {:parameters {:body [(s/maybe Turtle)] :query {:x (s/maybe String)}} :responses {200 {:description "ok" :schema {:sum (s/maybe Long)}} :default {:description "error"}}}}}}) (fact "empty spec" (let [swagger {}] (validate swagger) => nil)) (fact "minimalistic spec" (let [swagger {:paths {"/ping" {:get nil}}}] (validate swagger) => nil)) (fact "more complete spec" (validate a-complete-swagger) => nil) (extension/java-time (fact "spec with java.time" (let [model {:i java.time.Instant :ld java.time.LocalDate :lt java.time.LocalTime} swagger {:paths {"/time" {:post {:parameters {:body model}}}}}] (validate swagger) => nil))) (defrecord InvalidElement []) (facts "with missing schema -> json schema mappings" (fact "non-body-parameters" (let [swagger {:paths {"/hello" {:get {:parameters {:query {:name InvalidElement}}}}}}] (fact "dy default, exception is throws when generating json schema" (validate swagger) => (throws IllegalArgumentException)) (fact "with :ignore-missing-mappings errors (and mappings) are ignored" (validate swagger {:ignore-missing-mappings? true}) => nil))) (fact "body-parameters" (let [swagger {:paths {"/hello" {:post {:parameters {:body {:name InvalidElement :age s/Num}}}}}}] (fact "dy default, exception is throws when generating json schema" (validate swagger) => (throws IllegalArgumentException)) (fact "with :ignore-missing-mappings errors (and mappings) are ignored" (validate swagger {:ignore-missing-mappings? true}) => nil)))) (facts "handling empty responses" (let [swagger {:paths {"/hello" {:post {:responses {200 nil 425 nil 500 {:description "FAIL"}}}}}}] (fact "with defaults" (validate swagger) => nil (swagger2/swagger-json swagger) => (contains {:paths {"/hello" {:post {:responses {200 {:description ""} 425 {:description ""} 500 {:description "FAIL"}}}}}})) (fact ":default-response-description-fn option overriden" (let [options {:default-response-description-fn status/get-description}] (validate swagger options) => nil (swagger2/swagger-json swagger options) => (contains {:paths {"/hello" {:post {:responses {200 {:description "OK"} 425 {:description "The collection is unordered."} 500 {:description "FAIL"}}}}}}))))) (s/defschema Response {:id s/Str}) (defn schema-name [m] (-> m first val (subs (.length "#/definitions/")))) (def valid-reference (just {:$ref anything})) (def valid-optional-reference (just {:$ref anything :x-nullable true})) (defn extract-schema [swagger-spec uri path f] (let [operation (get-in swagger-spec [:paths uri :post]) definitions (:definitions swagger-spec) schema (get-in operation (conj path :schema)) name (schema-name (f schema))] {:name name :schema schema :defined? (boolean (definitions name))})) (facts "transforming subschemas" (let [model {:id s/Str} swagger {:paths {"/resp" {:post {:responses {200 {:schema Response} 201 {:schema [model]} 202 {:schema #{model}} 203 {:schema (s/maybe model)} 204 {:schema [(s/maybe model)]} 205 {:schema #{(s/maybe model)}}}}} "/body1" {:post {:parameters {:body model}}} "/body2" {:post {:parameters {:body [model]}}} "/body3" {:post {:parameters {:body #{model}}}} "/body4" {:post {:parameters {:body (s/maybe model)}}} "/body5" {:post {:parameters {:body [(s/maybe model)]}}} "/body6" {:post {:parameters {:body #{(s/maybe model)}}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil (tabular (fact "body and response schemas in all flavours" (let [{:keys [name schema defined?]} (extract-schema spec ?uri ?path ?fn)] schema => ?schema name => ?name defined? => true)) ?uri ?path ?fn ?name ?schema "/body1" [:parameters 0] identity #"Body.*" valid-reference "/body2" [:parameters 0] :items #"Body.*" (just {:items valid-reference, :type "array"}) "/body3" [:parameters 0] :items #"Body.*" (just {:items valid-reference, :type "array", :uniqueItems true}) "/body4" [:parameters 0] identity #"Body.*" valid-optional-reference "/body5" [:parameters 0] :items #"Body.*" (just {:items valid-optional-reference, :type "array"}) "/body6" [:parameters 0] :items #"Body.*" (just {:items valid-optional-reference, :type "array", :uniqueItems true}) "/resp" [:responses 200] identity "Response" valid-reference "/resp" [:responses 201] :items #"Response.*" (just {:items valid-reference, :type "array"}) "/resp" [:responses 202] :items #"Response.*" (just {:items valid-reference, :type "array", :uniqueItems true}) "/resp" [:responses 203] identity #"Response.*" valid-optional-reference "/resp" [:responses 204] :items #"Response.*" (just {:items valid-optional-reference, :type "array"}) "/resp" [:responses 205] :items #"Response.*" (just {:items valid-optional-reference, :type "array", :uniqueItems true})))) (fact "multiple different schemas with same name" (let [model1 (s/schema-with-name {:id s/Str} 'Kikka) model2 (s/schema-with-name {:id s/Int} 'Kikka) swagger {:paths {"/body" {:post {:parameters {:body {:1 model1, :2 model2}}}}}}] (fact "with default options" (validate swagger) => nil) (fact "with overriden options" (validate swagger {:handle-duplicate-schemas-fn ring.swagger.core/fail-on-duplicate-schema!}) => (throws IllegalArgumentException)))) (defn has-definition [schema-name value] (chatty-checker [actual] (= (get-in actual [:definitions (name schema-name)]) value))) (fact "additionalProperties" (let [Kikka (s/schema-with-name {:a s/Str s/Str s/Str} 'Kikka) Kukka (s/schema-with-name {:a s/Str s/Int Kikka} 'Kukka) Kakka (s/schema-with-name {s/Keyword Kukka} 'Kakka) swagger {:paths {"/kikka" {:post {:parameters {:body Kikka}}} "/kukka" {:post {:parameters {:body Kukka}}} "/kakka" {:post {:parameters {:body Kakka}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil (fact "keyword to primitive mapping" spec => (has-definition 'Kikka {:type "object" :properties {:a {:type "string"}} :additionalProperties {:type "string"} :required [:a]})) (fact "keyword to model mapping" spec => (has-definition 'Kukka {:type "object" :properties {:a {:type "string"}} :additionalProperties {:$ref "#/definitions/Kikka"} :required [:a]})) (fact "just additional properties" spec => (has-definition 'Kakka {:type "object" :additionalProperties {:$ref "#/definitions/Kukka"}})))) (fact "extra meta-data to properties" (let [Kikka (s/schema-with-name {:a (rsjs/field s/Str {:description "A"}) :b (rsjs/field [s/Str] {:description "B"})} 'Kikka) swagger {:paths {"/kikka" {:post {:parameters {:body Kikka}}}}} spec (swagger2/swagger-json swagger)] (validate swagger) => nil spec => (has-definition 'Kikka {:type "object" :properties {:a {:type "string" :description "A"} :b {:type "array" :items {:type "string"} :description "B"}} :additionalProperties false :required [:a :b]}))) (fact "tags" (let [swagger {:tags [{:name "pet" :description "Everything about your Pets" :externalDocs {:description "Find out more" :url ""}} {:name "store" :description "Operations about user"}] :paths {"/pet" {:post {:tags ["pet"]}} "/store" {:post {:tags ["store"]}}}}] (validate swagger) => nil)) (fact "retain :paths order, #54" (let [->path (fn [x] (str "/" x)) paths (reduce (fn [acc x] (assoc acc (->path x) {:get {}})) (linked/map) (range 100)) swagger {:paths paths} spec (swagger2/swagger-json swagger)] (-> spec :paths keys) => (map ->path (range 100)))) (fact "transform-operations" (let [remove-x-no-doc (fn [endpoint] (if-not (some-> endpoint :x-no-doc true?) endpoint)) swagger {:paths {"/a" {:get {:x-no-doc true}, :post {}} "/b" {:put {:x-no-doc true}}}}] (swagger2/transform-operations remove-x-no-doc swagger) => {:paths {"/a" {:post {}}}} (swagger2/transform-operations remove-x-no-doc {:paths {"/a" {:get {:x-no-doc true}, :post {}} "/b" {:put {:x-no-doc true}}}}))) (s/defschema SchemaA {:a s/Str}) (s/defschema SchemaB {:b s/Str}) (fact "s/either stuff is correctly named" (-> (swagger2/swagger-json {:paths {"/ab" {:get {:parameters {:body (s/either SchemaA SchemaB)}}}}}) (get-in [:paths "/ab" :get :parameters 0])) => {:in "body" :name "SchemaA" :description "" :required true :schema {:$ref "#/definitions/SchemaA"}}) (fact "body wrapped in Maybe make's it optional" (-> (swagger2/swagger-json {:paths {"/maybe" {:post {:parameters {:body (s/maybe {:kikka s/Str})}}}}}) (get-in [:paths "/maybe" :post :parameters 0])) => (contains {:in "body", :required false})) (fact "path-parameters with .dot extension, #82" (swagger2/swagger-json {:paths {"/api/:id.json" {:get {:parameters {:path {:id String}}}}}}) => (contains {:paths (just {"/api/{id}.json" (contains {:get (contains {:parameters (just [(contains {:name "id"})])})})})})) (fact "should validate full swagger 2 schema" (s/validate full-schema/Swagger a-complete-swagger) => a-complete-swagger) (s/defschema Required (rsjs/field {(s/optional-key :name) s/Str (s/optional-key :title) s/Str :address (rsjs/field {:street (rsjs/field s/Str {:description "description here"})} {:description "Streename" :example "Ankkalinna 1"})} {:minProperties 1 :description "I'm required" :example {:name "Iines" :title "Ankka"}})) (fact "models with extra meta, #96" (let [swagger {:paths {"/api" {:post {:parameters {:body Required}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {"Required" {:type "object" :description "I'm required" :example {:name "Iines" :title "Ankka"} :minProperties 1 :required [:address] :properties {:name {:type "string"} :title {:type "string"} :address {:$ref "#/definitions/RequiredAddress"}} :additionalProperties false} "RequiredAddress" {:type "object" :description "Streename" :example "Ankkalinna 1" :properties {:street {:type "string" :description "description here"}} :required [:street] :additionalProperties false}} :paths {"/api" {:post {:parameters [{:description "I'm required" :in "body" :name "Required" :required true :schema {:$ref "#/definitions/Required"}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (s/defschema OptionalMaybe {(s/optional-key :a) s/Str (s/optional-key :b) (s/maybe s/Str) :c (s/maybe s/Str)}) (fact "nillable fields, #97" (let [swagger {:paths {"/api" {:post {:parameters {:body (s/maybe OptionalMaybe)}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {"OptionalMaybe" {:type "object" :properties {:a {:type "string"} :b {:type "string" :x-nullable true} :c {:type "string" :x-nullable true}} :required [:c] :additionalProperties false}} :paths {"/api" {:post {:parameters [{:in "body" :name "OptionalMaybe" :description "" :required false :schema {:$ref "#/definitions/OptionalMaybe" :x-nullable true}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (s/defrecord Keyboard [type :- (s/enum :left :right)]) (s/defrecord User [age :- s/Int, keyboard :- Keyboard]) (fact "top-level & nested records are embedded" (let [swagger {:paths {"/api" {:post {:parameters {:body User}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "User" :description "" :required true :schema {:type "object" :title "User" :properties {:age {:format "int64" :type "integer"} :keyboard {:type "object" :title "Keyboard" :properties {:type {:type "string" :enum [:right :left]}} :required [:type] :additionalProperties false}} :required [:age :keyboard] :additionalProperties false}}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (fact "primitive vector body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body [s/Str]} :responses {200 {:schema [s/Str]}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:items {:type "string"} :type "array"}}] :responses {200 {:description "" :schema {:items {:type "string"} :type "array"}}}}}}}) (validate swagger) => nil)) (fact "primitive set body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body #{s/Str}} :responses {200 {:schema #{s/Str}}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:items {:type "string"} :uniqueItems true :type "array"}}] :responses {200 {:description "" :schema {:items {:type "string"} :uniqueItems true :type "array"}}}}}}}) (validate swagger) => nil)) (fact "primitive body parameters & responses" (let [swagger {:paths {"/api" {:post {:parameters {:body s/Str} :responses {200 {:schema s/Str}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/api" {:post {:parameters [{:in "body" :name "" :description "" :required true :schema {:type "string"}}] :responses {200 {:description "" :schema {:type "string"}}}}}}}) (validate swagger) => nil)) (s/defschema Person {:age s/Int}) (def Adult (s/constrained Person #(>= (:age %) 18))) (fact "query parameters with ..., #104" (fact "constrained schema" (let [swagger {:paths {"/people" {:get {:parameters {:query Adult} :responses {200 {:schema s/Str}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/people" {:get {:parameters [{:in "query" :name "age" :description "" :required true :type "integer" :format "int64"}] :responses {200 {:description "" :schema {:type "string"}}}}}}}) (validate swagger) => nil)) (fact "top-level maybe schema" (let [swagger {:paths {"/" {:get {:parameters {:query (s/maybe {:a s/Str})}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/" {:get {:parameters [{:in "query" :name "a" :description "" :required true :type "string"}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil)) (fact "nested maybe schema" (let [swagger {:paths {"/" {:get {:parameters {:query {:a (s/maybe s/Str)}}}}}}] (swagger2/swagger-json swagger) => (contains {:definitions {} :paths {"/" {:get {:parameters [{:in "query" :name "a" :description "" :required true :type "string" :allowEmptyValue true}] :responses {:default {:description ""}}}}}}) (validate swagger) => nil))) (fact "qualified keywords" (let [swagger {:paths {"/any" {:get {:parameters {:query {:kikka/kukka String}} :responses {:default {:schema {:olipa/kerran String}}}}}}} endpoint (get-in (swagger2/swagger-json swagger) [:paths "/any" :get]) response (-> (swagger2/swagger-json swagger) :definitions first second)] (get-in endpoint [:parameters 0]) => (contains {:name "kikka/kukka"}) (get-in response [:properties]) => (contains {:olipa/kerran {:type "string"}}))) (fact "Meta-description of body responses are considered" (let [swagger {:paths {"/meta" {:get {:parameters {:query {:kikka/kukka String}} :responses {200 (rsjs/describe {:body {:kikka/kukka String}} "A meta description")}}} "/direct" {:get {:parameters {:query {:kikka/kukka String}} :responses {200 {:body {:kikka/kukka String} :description "A direct description"}}}}}}] (get-in (swagger2/swagger-json swagger) [:paths "/meta" :get :responses 200]) => (contains {:description "A meta description"}) (get-in (swagger2/swagger-json swagger) [:paths "/direct" :get :responses 200]) => (contains {:description "A direct description"})))
9077ea57ed20e8b6aa02c516ed535000cc7e7904380dd84829d9f8c0b968334f
xapi-project/message-switch
q.ml
* Copyright ( c ) Citrix Systems Inc. * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) Citrix Systems Inc. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Sexplib.Std open Clock module Int64Map = struct include Map.Make (Int64) type 'a t' = (int64 * 'a) list [@@deriving sexp] let t_of_sexp a sexp = let t' = t'_of_sexp a sexp in List.fold_left (fun acc (x, y) -> add x y acc) empty t' let sexp_of_t a t = sexp_of_t' a (bindings t) end module Lwt_condition = struct include Lwt_condition type t' = string [@@deriving sexp] let _t_of_sexp _ _ = Lwt_condition.create () let _sexp_of_t _ _ = sexp_of_t' "Lwt_condition.t" end module Lwt_mutex = struct include Lwt_mutex type t' = string [@@deriving sexp] let _t_of_sexp _ = Lwt_mutex.create () let _sexp_of_t _ = sexp_of_t' "Lwt_mutex.t" end type waiter = {mutable next_id: int64} [@@deriving sexp] type t = { q: Message_switch_core.Protocol.Entry.t Int64Map.t ; name: string ; length: int ; owner: string option ; (* if transient, name of the owning connection *) waiter: waiter } [@@deriving sexp] let t_of_sexp sexp = let t = t_of_sexp sexp in (* compute a valid next_id *) let highest_id = try fst (Int64Map.max_binding t.q) with Not_found -> -1L in t.waiter.next_id <- Int64.succ highest_id ; t let get_owner t = t.owner let make owner name = let waiter = {next_id= 0L} in {q= Int64Map.empty; name; length= 0; owner; waiter} module StringMap = struct include Map.Make (String) type 'a t' = (string * 'a) list [@@deriving sexp] let t_of_sexp a sexp = let t' = t'_of_sexp a sexp in List.fold_left (fun acc (x, y) -> add x y acc) empty t' let sexp_of_t a t = sexp_of_t' a (bindings t) end module StringSet = struct include Set.Make (String) type t' = string list [@@deriving sexp] let t_of_sexp sexp = let t' = t'_of_sexp sexp in List.fold_left (fun acc x -> add x acc) empty t' let sexp_of_t t = sexp_of_t' (elements t) end type queues = {queues: t StringMap.t; by_owner: StringSet.t StringMap.t} [@@deriving sexp] let empty = {queues= StringMap.empty; by_owner= StringMap.empty} let owned_queues queues owner = if StringMap.mem owner queues.by_owner then StringMap.find owner queues.by_owner else StringSet.empty let startswith prefix x = String.length x >= String.length prefix && String.sub x 0 (String.length prefix) = prefix module Lengths = struct open Message_switch_core.Measurable let d x = Description.{description= "length of queue " ^ x; units= ""} let _list_available queues = StringMap.fold (fun name _ acc -> (name, d name) :: acc) queues.queues [] let _measure queues name = if StringMap.mem name queues.queues then Some (Measurement.Int (StringMap.find name queues.queues).length) else None end module Internal = struct module Directory = struct let exists queues name = StringMap.mem name queues.queues let add queues ?owner name = if not (exists queues name) then let queues' = StringMap.add name (make owner name) queues.queues in let by_owner = match owner with | None -> queues.by_owner | Some owner -> let existing = if StringMap.mem owner queues.by_owner then StringMap.find owner queues.by_owner else StringSet.empty in StringMap.add owner (StringSet.add name existing) queues.by_owner in {queues= queues'; by_owner} else queues let find queues name = if exists queues name then StringMap.find name queues.queues else make None name let remove queues name = let by_owner = if not (exists queues name) then queues.by_owner else let q = StringMap.find name queues.queues in match q.owner with | None -> queues.by_owner | Some owner -> let owned = StringMap.find owner queues.by_owner in let owned = StringSet.remove name owned in if owned = StringSet.empty then StringMap.remove owner queues.by_owner else StringMap.add owner owned queues.by_owner in let queues = StringMap.remove name queues.queues in {queues; by_owner} let list queues prefix = StringMap.fold (fun name _ acc -> if startswith prefix name then name :: acc else acc) queues.queues [] end let ack queues (name, id) = if Directory.exists queues name then let q = Directory.find queues name in if Int64Map.mem id q.q then let q' = {q with length= q.length - 1; q= Int64Map.remove id q.q} in {queues with queues= StringMap.add name q' queues.queues} else queues else queues let send queues origin name id data = (* If a queue doesn't exist then drop the message *) if Directory.exists queues name then let q = Directory.find queues name in let q' = { q with length= q.length + 1 ; q= Int64Map.add id (Message_switch_core.Protocol.Entry.make (ns ()) origin data) q.q } in let queues = {queues with queues= StringMap.add name q' queues.queues} in queues else queues let get_next_id queues name = let q = Directory.find queues name in let id = q.waiter.next_id in q.waiter.next_id <- Int64.succ id ; id end (* operations which need to be persisted *) module Op = struct type directory_operation = Add of string option * string | Remove of string [@@deriving sexp] type t = | Directory of directory_operation | Ack of Message_switch_core.Protocol.message_id | Send of Message_switch_core.Protocol.origin * string * int64 * Message_switch_core.Protocol.Message.t (* origin * queue * id * body *) [@@deriving sexp] let of_cstruct x = try Some (Cstruct.to_string x |> Sexplib.Sexp.of_string |> t_of_sexp) with _ -> None let to_cstruct t = let s = sexp_of_t t |> Sexplib.Sexp.to_string in let c = Cstruct.create (String.length s) in Cstruct.blit_from_string s 0 c 0 (Cstruct.len c) ; c end let do_op queues = function | Op.Directory (Op.Add (owner, name)) -> Internal.Directory.add queues ?owner name | Op.Directory (Op.Remove name) -> Internal.Directory.remove queues name | Op.Ack id -> Internal.ack queues id | Op.Send (origin, name, id, body) -> Internal.send queues origin name id body let contents q = Int64Map.fold (fun i e acc -> ((q.name, i), e) :: acc) q.q [] module Directory = struct let add _queues ?owner name = Op.Directory (Op.Add (owner, name)) let remove _queues name = Op.Directory (Op.Remove name) let find = Internal.Directory.find let list = Internal.Directory.list end let queue_of_id = fst let ack _queues id = Op.Ack id let transfer queues from names = let messages = List.map (fun name -> let q = Internal.Directory.find queues name in let _, _, not_seen = Int64Map.split from q.q in Int64Map.fold (fun id e acc -> ((name, id), e.Message_switch_core.Protocol.Entry.message) :: acc) not_seen []) names in List.concat messages let entry queues (name, id) = let q = Internal.Directory.find queues name in if Int64Map.mem id q.q then Some (Int64Map.find id q.q) else None let send queues origin name body = if Internal.Directory.exists queues name then let id = Internal.get_next_id queues name in Some ((name, id), Op.Send (origin, name, id, body)) else None (* drop *)
null
https://raw.githubusercontent.com/xapi-project/message-switch/b51b75a5789bec8f8c3a7825eb2af576cdef95ab/switch/q.ml
ocaml
if transient, name of the owning connection compute a valid next_id If a queue doesn't exist then drop the message operations which need to be persisted origin * queue * id * body drop
* Copyright ( c ) Citrix Systems Inc. * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) Citrix Systems Inc. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Sexplib.Std open Clock module Int64Map = struct include Map.Make (Int64) type 'a t' = (int64 * 'a) list [@@deriving sexp] let t_of_sexp a sexp = let t' = t'_of_sexp a sexp in List.fold_left (fun acc (x, y) -> add x y acc) empty t' let sexp_of_t a t = sexp_of_t' a (bindings t) end module Lwt_condition = struct include Lwt_condition type t' = string [@@deriving sexp] let _t_of_sexp _ _ = Lwt_condition.create () let _sexp_of_t _ _ = sexp_of_t' "Lwt_condition.t" end module Lwt_mutex = struct include Lwt_mutex type t' = string [@@deriving sexp] let _t_of_sexp _ = Lwt_mutex.create () let _sexp_of_t _ = sexp_of_t' "Lwt_mutex.t" end type waiter = {mutable next_id: int64} [@@deriving sexp] type t = { q: Message_switch_core.Protocol.Entry.t Int64Map.t ; name: string ; length: int ; owner: string option waiter: waiter } [@@deriving sexp] let t_of_sexp sexp = let t = t_of_sexp sexp in let highest_id = try fst (Int64Map.max_binding t.q) with Not_found -> -1L in t.waiter.next_id <- Int64.succ highest_id ; t let get_owner t = t.owner let make owner name = let waiter = {next_id= 0L} in {q= Int64Map.empty; name; length= 0; owner; waiter} module StringMap = struct include Map.Make (String) type 'a t' = (string * 'a) list [@@deriving sexp] let t_of_sexp a sexp = let t' = t'_of_sexp a sexp in List.fold_left (fun acc (x, y) -> add x y acc) empty t' let sexp_of_t a t = sexp_of_t' a (bindings t) end module StringSet = struct include Set.Make (String) type t' = string list [@@deriving sexp] let t_of_sexp sexp = let t' = t'_of_sexp sexp in List.fold_left (fun acc x -> add x acc) empty t' let sexp_of_t t = sexp_of_t' (elements t) end type queues = {queues: t StringMap.t; by_owner: StringSet.t StringMap.t} [@@deriving sexp] let empty = {queues= StringMap.empty; by_owner= StringMap.empty} let owned_queues queues owner = if StringMap.mem owner queues.by_owner then StringMap.find owner queues.by_owner else StringSet.empty let startswith prefix x = String.length x >= String.length prefix && String.sub x 0 (String.length prefix) = prefix module Lengths = struct open Message_switch_core.Measurable let d x = Description.{description= "length of queue " ^ x; units= ""} let _list_available queues = StringMap.fold (fun name _ acc -> (name, d name) :: acc) queues.queues [] let _measure queues name = if StringMap.mem name queues.queues then Some (Measurement.Int (StringMap.find name queues.queues).length) else None end module Internal = struct module Directory = struct let exists queues name = StringMap.mem name queues.queues let add queues ?owner name = if not (exists queues name) then let queues' = StringMap.add name (make owner name) queues.queues in let by_owner = match owner with | None -> queues.by_owner | Some owner -> let existing = if StringMap.mem owner queues.by_owner then StringMap.find owner queues.by_owner else StringSet.empty in StringMap.add owner (StringSet.add name existing) queues.by_owner in {queues= queues'; by_owner} else queues let find queues name = if exists queues name then StringMap.find name queues.queues else make None name let remove queues name = let by_owner = if not (exists queues name) then queues.by_owner else let q = StringMap.find name queues.queues in match q.owner with | None -> queues.by_owner | Some owner -> let owned = StringMap.find owner queues.by_owner in let owned = StringSet.remove name owned in if owned = StringSet.empty then StringMap.remove owner queues.by_owner else StringMap.add owner owned queues.by_owner in let queues = StringMap.remove name queues.queues in {queues; by_owner} let list queues prefix = StringMap.fold (fun name _ acc -> if startswith prefix name then name :: acc else acc) queues.queues [] end let ack queues (name, id) = if Directory.exists queues name then let q = Directory.find queues name in if Int64Map.mem id q.q then let q' = {q with length= q.length - 1; q= Int64Map.remove id q.q} in {queues with queues= StringMap.add name q' queues.queues} else queues else queues let send queues origin name id data = if Directory.exists queues name then let q = Directory.find queues name in let q' = { q with length= q.length + 1 ; q= Int64Map.add id (Message_switch_core.Protocol.Entry.make (ns ()) origin data) q.q } in let queues = {queues with queues= StringMap.add name q' queues.queues} in queues else queues let get_next_id queues name = let q = Directory.find queues name in let id = q.waiter.next_id in q.waiter.next_id <- Int64.succ id ; id end module Op = struct type directory_operation = Add of string option * string | Remove of string [@@deriving sexp] type t = | Directory of directory_operation | Ack of Message_switch_core.Protocol.message_id | Send of Message_switch_core.Protocol.origin * string * int64 [@@deriving sexp] let of_cstruct x = try Some (Cstruct.to_string x |> Sexplib.Sexp.of_string |> t_of_sexp) with _ -> None let to_cstruct t = let s = sexp_of_t t |> Sexplib.Sexp.to_string in let c = Cstruct.create (String.length s) in Cstruct.blit_from_string s 0 c 0 (Cstruct.len c) ; c end let do_op queues = function | Op.Directory (Op.Add (owner, name)) -> Internal.Directory.add queues ?owner name | Op.Directory (Op.Remove name) -> Internal.Directory.remove queues name | Op.Ack id -> Internal.ack queues id | Op.Send (origin, name, id, body) -> Internal.send queues origin name id body let contents q = Int64Map.fold (fun i e acc -> ((q.name, i), e) :: acc) q.q [] module Directory = struct let add _queues ?owner name = Op.Directory (Op.Add (owner, name)) let remove _queues name = Op.Directory (Op.Remove name) let find = Internal.Directory.find let list = Internal.Directory.list end let queue_of_id = fst let ack _queues id = Op.Ack id let transfer queues from names = let messages = List.map (fun name -> let q = Internal.Directory.find queues name in let _, _, not_seen = Int64Map.split from q.q in Int64Map.fold (fun id e acc -> ((name, id), e.Message_switch_core.Protocol.Entry.message) :: acc) not_seen []) names in List.concat messages let entry queues (name, id) = let q = Internal.Directory.find queues name in if Int64Map.mem id q.q then Some (Int64Map.find id q.q) else None let send queues origin name body = if Internal.Directory.exists queues name then let id = Internal.get_next_id queues name in Some ((name, id), Op.Send (origin, name, id, body)) else None
75acd259ab135df967bf418c6b253c9340654196d295d672c1c72b0d5e14dc8f
facebook/flow
search_tests.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 let tests = "search" >::: [Export_search_tests.suite] let () = run_test_tt_main tests
null
https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/services/export/search/__tests__/search_tests.ml
ocaml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 let tests = "search" >::: [Export_search_tests.suite] let () = run_test_tt_main tests
7d5545c8d7cff05b2f3f41efa5ce5e3e5eda3f19a4114a3c7a65763966b2556f
transient-haskell/transient-stack
Internals.hs
------------------------------------------------------------------------------ -- -- Module : Transient.Internals -- Copyright : License : MIT -- -- Maintainer : -- Stability : -- Portability : -- -- | See -haskell/transient -- Everything in this module is exported in order to allow extensibility. ----------------------------------------------------------------------------- {-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE UndecidableInstances #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE RecordWildCards # {-# LANGUAGE ConstraintKinds #-} { - # LANGUAGE MonoLocalBinds # - } module Transient.Internals where import Control.Applicative import Control.Monad.State import Data . Dynamic import qualified Data.Map as M import System.IO.Unsafe import Unsafe.Coerce import Control.Exception hiding (try,onException) import qualified Control.Exception (try) import Control.Concurrent -- import GHC.Real -- import GHC.Conc(unsafeIOToSTM) import Control . Concurrent . STM hiding ( retry ) import qualified Control . Concurrent . STM as STM ( retry ) import Data.Maybe import Data.List import Data.IORef import System.Environment import System.IO import System.IO.Error import Data.String import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BSL import Data.Typeable import Control.Monad.Fail import System.Directory #ifdef DEBUG import Debug.Trace import System.Exit tshow :: Show a => a -> x -> x tshow= Debug.Trace.traceShow {-# INLINE (!>) #-} (!>) :: Show a => b -> a -> b (!>) x y = trace (show (unsafePerformIO myThreadId, y)) x infixr 0 !> #else tshow :: a -> x -> x tshow _ y= y {-# INLINE (!>) #-} (!>) :: a -> b -> a (!>) = const #endif tr x= return () !> x type StateIO = StateT EventF IO newtype TransIO a = Transient { runTrans :: StateIO (Maybe a) } type SData = () type EventId = Int type TransientIO = TransIO data LifeCycle = Alive | Parent | Listener | Dead deriving (Eq, Show) | EventF describes the context of a TransientIO computation : data EventF = forall a b. EventF { event :: Maybe SData -- ^ Not yet consumed result (event) from the last asynchronous computation , xcomp :: TransIO a , fcomp :: [b -> TransIO b] -- ^ List of continuations , mfData :: M.Map TypeRep SData -- ^ State data accessed with get or put operations , mfSequence :: Int , threadId :: ThreadId , freeTh :: Bool -- ^ When 'True', threads are not killed using kill primitives , parent :: Maybe EventF -- ^ The parent of this thread , children :: MVar [EventF] -- ^ Forked child threads, used only when 'freeTh' is 'False' , maxThread :: Maybe (IORef Int) -- ^ Maximum number of threads that are allowed to be created , labelth :: IORef (LifeCycle, BS.ByteString) -- ^ Label the thread with its lifecycle state and a label string , parseContext :: ParseContext , execMode :: ExecMode } deriving Typeable data ParseContext = ParseContext { more :: TransIO (StreamData BSL.ByteString) , buffer :: BSL.ByteString , done :: IORef Bool} deriving Typeable -- | To define primitives for all the transient monads: TransIO, Cloud and Widget class MonadState EventF m => TransMonad m instance MonadState EventF m => TransMonad m instance MonadState EventF TransIO where get = Transient $ get >>= return . Just put x = Transient $ put x >> return (Just ()) state f = Transient $ do s <- get let ~(a, s') = f s put s' return $ Just a -- | Run a computation in the underlying state monad. it is a little lighter and -- performant and it should not contain advanced effects beyond state. noTrans :: StateIO x -> TransIO x noTrans x = Transient $ x >>= return . Just | filters away the Nothing responses of the State monad . -- in principle the state monad should return a single response, but, for performance reasons, -- it can run inside elements of transient monad (using `runTrans`) which may produce -- many results liftTrans :: StateIO (Maybe b) -> TransIO b liftTrans mx= do r <- noTrans mx case r of Nothing -> empty Just x -> return x emptyEventF :: ThreadId -> IORef (LifeCycle, BS.ByteString) -> MVar [EventF] -> EventF emptyEventF th label childs = EventF { event = mempty , xcomp = empty , fcomp = [] , mfData = mempty , mfSequence = 0 , threadId = th , freeTh = False , parent = Nothing , children = childs , maxThread = Nothing , labelth = label , parseContext = ParseContext (return SDone) mempty undefined , execMode = Serial} -- | Run a transient computation with a default initial state runTransient :: TransIO a -> IO (Maybe a, EventF) runTransient t = do th <- myThreadId label <- newIORef $ (Alive, BS.pack "top") childs <- newMVar [] runStateT (runTrans t) $ emptyEventF th label childs -- | Run a transient computation with a given initial state runTransState :: EventF -> TransIO x -> IO (Maybe x, EventF) runTransState st x = runStateT (runTrans x) st emptyIfNothing :: Maybe a -> TransIO a emptyIfNothing = Transient . return -- | Get the continuation context: closure, continuation, state, child threads etc getCont :: TransIO EventF getCont = Transient $ Just <$> get -- | Run the closure and the continuation using the state data of the calling thread runCont :: EventF -> StateIO (Maybe a) runCont EventF { xcomp = x, fcomp = fs } = runTrans $ do r <- unsafeCoerce x compose fs r -- | Run the closure and the continuation using its own state data. runCont' :: EventF -> IO (Maybe a, EventF) runCont' cont = runStateT (runCont cont) cont -- | Warning: Radically untyped stuff. handle with care getContinuations :: StateIO [a -> TransIO b] getContinuations = do EventF { fcomp = fs } <- get return $ unsafeCoerce fs {- runCont cont = do mr <- runClosure cont case mr of Nothing -> return Nothing Just r -> runContinuation cont r -} -- | Compose a list of continuations. # INLINE compose # compose :: [a -> TransIO a] -> (a -> TransIO b) compose [] = const empty compose (f:fs) = \x -> f x >>= compose fs -- | Run the closure (the 'x' in 'x >>= f') of the current bind operation. runClosure :: EventF -> StateIO (Maybe a) runClosure EventF { xcomp = x } = unsafeCoerce (runTrans x) -- | Run the continuation (the 'f' in 'x >>= f') of the current bind operation with the current state. runContinuation :: EventF -> a -> StateIO (Maybe b) runContinuation EventF { fcomp = fs } = runTrans . (unsafeCoerce $ compose $ fs) -- | Save a closure and a continuation ('x' and 'f' in 'x >>= f'). setContinuation :: TransIO a -> (a -> TransIO b) -> [c -> TransIO c] -> StateIO () setContinuation b c fs = do modify $ \EventF{..} -> EventF { xcomp = b , fcomp = unsafeCoerce c : fs , .. } -- | Save a closure and continuation, run the closure, restore the old continuation. -- | NOTE: The old closure is discarded. withContinuation :: b -> TransIO a -> TransIO a withContinuation c mx = do EventF { fcomp = fs, .. } <- get put $ EventF { xcomp = mx , fcomp = unsafeCoerce c : fs , .. } r <- mx restoreStack fs return r -- | Restore the continuations to the provided ones. -- | NOTE: Events are also cleared out. restoreStack :: TransMonad m => [a -> TransIO a] -> m () restoreStack fs = modify $ \EventF {..} -> EventF { event = Nothing, fcomp = fs, .. } -- | Run a chain of continuations. -- WARNING: It is up to the programmer to assure that each continuation typechecks with the next , and that the parameter type match the input of the first -- continuation. -- NOTE: Normally this makes sense to stop the current flow with `stop` after the -- invocation. runContinuations :: [a -> TransIO b] -> c -> TransIO d runContinuations fs x = compose (unsafeCoerce fs) x -- Instances for Transient Monad instance Functor TransIO where fmap f mx = do x <- mx return $ f x instance Applicative TransIO where pure a = Transient . return $ Just a mf <*> mx = do -- do f <- mf; x <- mx ; return $ f x r1 <- liftIO $ newIORef Nothing r2 <- liftIO $ newIORef Nothing fparallel r1 r2 <|> xparallel r1 r2 where fparallel r1 r2= do f <- mf liftIO $ (writeIORef r1 $ Just f) mr <- liftIO (readIORef r2) case mr of Nothing -> empty Just x -> return $ f x xparallel r1 r2 = do mr <- liftIO (readIORef r1) case mr of Nothing -> do p <- gets execMode if p== Serial then empty else do x <- mx liftIO $ (writeIORef r2 $ Just x) mr <- liftIO (readIORef r1) case mr of Nothing -> empty Just f -> return $ f x Just f -> do x <- mx liftIO $ (writeIORef r2 $ Just x) return $ f x data ExecMode = Remote | Parallel | Serial deriving (Typeable, Eq, Show) -- | stop the current computation and does not execute any alternative computation fullStop :: TransIO stop fullStop= do modify $ \s ->s{execMode= Remote} ; stop instance Monad TransIO where return = pure x >>= f = Transient $ do setEventCont x f mk <- runTrans x resetEventCont mk case mk of Just k -> runTrans (f k) Nothing -> return Nothing instance MonadIO TransIO where liftIO x = Transient $ liftIO x >>= return . Just instance Monoid a => Monoid (TransIO a) where mempty = return mempty #if MIN_VERSION_base(4,11,0) mappend = (<>) instance (Monoid a) => Semigroup (TransIO a) where (<>)= mappendt #else mappend= mappendt #endif mappendt x y = mappend <$> x <*> y instance Alternative TransIO where empty = Transient $ return Nothing (<|>) = mplus instance MonadPlus TransIO where mzero = empty mplus x y = Transient $ do mx <- runTrans x was <- gets execMode -- getData `onNothing` return Serial if was == Remote then return Nothing else case mx of Nothing -> runTrans y justx -> return justx instance MonadFail TransIO where fail _ = mzero readWithErr :: (Typeable a, Read a) => Int -> String -> IO [(a, String)] readWithErr n line = (v `seq` return [(v, left)]) `catch` (\(_ :: SomeException) -> throw $ ParseError $ "read error trying to read type: \"" ++ show (typeOf v) ++ "\" in: " ++ " <" ++ show line ++ "> ") where (v, left):_ = readsPrec n line newtype ParseError= ParseError String instance Show ParseError where show (ParseError s)= "ParseError " ++ s instance Exception ParseError read' s= case readsPrec' 0 s of [(x,"")] -> x _ -> throw $ ParseError $ "reading " ++ s readsPrec' n = unsafePerformIO . readWithErr n -- | A synonym of 'empty' that can be used in a monadic expression. It stops -- the computation, which allows the next computation in an 'Alternative' -- ('<|>') composition to run. stop :: Alternative m => m stopped stop = empty instance (Num a,Eq a,Fractional a) =>Fractional (TransIO a)where mf / mg = (/) <$> mf <*> mg fromRational r = return $ fromRational r instance (Num a, Eq a) => Num (TransIO a) where fromInteger = return . fromInteger mf + mg = (+) <$> mf <*> mg mf * mg = (*) <$> mf <*> mg negate f = f >>= return . negate abs f = f >>= return . abs signum f = f >>= return . signum class AdditionalOperators m where -- | Run @m a@ discarding its result before running @m b@. (**>) :: m a -> m b -> m b | Run @m b@ discarding its result , after the whole task set @m a@ is -- done. (<**) :: m a -> m b -> m a atEnd' :: m a -> m b -> m a atEnd' = (<**) -- | Run @m b@ discarding its result, once after each task in @m a@, and -- once again after the whole task set is done. (<***) :: m a -> m b -> m a atEnd :: m a -> m b -> m a atEnd = (<***) instance AdditionalOperators TransIO where --(**>) :: TransIO a -> TransIO b -> TransIO b (**>) x y = Transient $ do runTrans x runTrans y --(<***) :: TransIO a -> TransIO b -> TransIO a (<***) ma mb = Transient $ do fs <- getContinuations setContinuation ma (\x -> mb >> return x) fs a <- runTrans ma runTrans mb restoreStack fs return a --(<**) :: TransIO a -> TransIO b -> TransIO a (<**) ma mb = Transient $ do a <- runTrans ma runTrans mb return a infixl 4 <***, <**, **> | Run @b@ once , discarding its result when the first task in task set @a@ has finished . Useful to start a singleton task after the first task has been -- setup. (<|) :: TransIO a -> TransIO b -> TransIO a (<|) ma mb = Transient $ do fs <- getContinuations ref <- liftIO $ newIORef False setContinuation ma (cont ref) fs r <- runTrans ma restoreStack fs return r where cont ref x = Transient $ do n <- liftIO $ readIORef ref if n == True then return $ Just x else do liftIO $ writeIORef ref True runTrans mb return $ Just x -- | Set the current closure and continuation for the current statement # INLINABLE setEventCont # setEventCont :: TransIO a -> (a -> TransIO b) -> StateIO () setEventCont x f = modify $ \EventF { fcomp = fs, .. } -> EventF { xcomp = x , fcomp = unsafeCoerce f : fs , .. } -- | Reset the closure and continuation. Remove inner binds than the previous -- computations may have stacked in the list of continuations. resetEventCont : : Maybe a - > EventF - > StateIO ( ) # INLINABLE resetEventCont # resetEventCont mx = modify $ \EventF { fcomp = fs, .. } -> EventF { xcomp = case mx of Nothing -> empty Just x -> unsafeCoerce (head fs) x , fcomp = tailsafe fs , .. } -- | Total variant of `tail` that returns an empty list when given an empty list. # INLINE tailsafe # tailsafe :: [a] -> [a] tailsafe [] = [] tailsafe (_:xs) = xs --instance MonadTrans (Transient ) where -- lift mx = Transient $ mx >>= return . Just -- * Threads waitQSemB onemore sem = atomicModifyIORef sem $ \n -> let one = if onemore then 1 else 0 in if n + one > 0 then(n - 1, True) else (n, False) signalQSemB sem = atomicModifyIORef sem $ \n -> (n + 1, ()) -- | Sets the maximum number of threads that can be created for the given task set . When set to 0 , new tasks start synchronously in the current thread . -- New threads are created by 'parallel', and APIs that use parallel. threads :: Int -> TransIO a -> TransIO a threads n process = do msem <- gets maxThread sem <- liftIO $ newIORef n modify $ \s -> s { maxThread = Just sem } r <- process <*** (modify $ \s -> s { maxThread = msem }) -- restore it return r -- clone the current state as a child of the current state, with the same thread cloneInChild name= do st <- get rchs <- liftIO $ newMVar [] label <- liftIO $ newIORef (Alive, if not $ null name then BS.pack name else mempty) let st' = st { parent = Just st , children = rchs , labelth = label } liftIO $ do atomicModifyIORef (labelth st) $ \(_, label) -> ((Parent,label),()) parent could have more than one children with the same threadId return st' -- remove the current child task from the tree of tasks. -- If the child and parent threads are different, the child is killed removeChild :: (MonadIO m,TransMonad m) => m () removeChild = do st <- get let mparent = parent st case mparent of Nothing -> return () Just parent -> do sts <- liftIO $ modifyMVar (children parent) $ \ths -> do let (xs,sts)= partition (\st' -> threadId st' /= threadId st) ths ys <- case sts of [] -> return [] st':_ -> readMVar $ children st' return (xs ++ ys,sts) put parent case sts of [] -> return() st':_ -> do (status,_) <- liftIO $ readIORef $ labelth st' if status == Listener || threadId parent == threadId st then return () else liftIO $ (killThread . threadId) st' -- | Terminate all the child threads in the given task set and continue -- execution in the current thread. Useful to reap the children when a task is -- done, restart a task when a new event happens etc. -- oneThread :: TransIO a -> TransIO a oneThread comp = do st <- cloneInChild "oneThread" let rchs= children st x <- comp th <- liftIO myThreadId -- !> ("FATHER:", threadId st) chs <- liftIO $ readMVar rchs liftIO $ mapM_ (killChildren1 th) chs -- !> ("KILLEVENT1 ", map threadId chs ) return x where killChildren1 :: ThreadId -> EventF -> IO () killChildren1 th state = do forkIO $ do ths' <- modifyMVar (children state) $ \ths -> do let (inn, ths')= partition (\st -> threadId st == th) ths return (inn, ths') mapM_ (killChildren1 th) ths' mapM_ (killThread . threadId) ths' return() -- | Add a label to the current passing threads so it can be printed by debugging calls like `showThreads` labelState :: (MonadIO m,TransMonad m) => BS.ByteString -> m () labelState l = do st <- get liftIO $ atomicModifyIORef (labelth st) $ \(status,prev) -> ((status, prev <> BS.pack "," <> l), ()) -- | return the threadId associated with an state (you can see all of them with the console option 'ps') threadState thid= do st <- findState match =<< topState return $ threadId st :: TransIO ThreadId where match st= do (_,lab) <-liftIO $ readIORef $ labelth st return $ if lab == thid then True else False -- | kill the thread subtree labeled as such (you can see all of them with the console option 'ps') killState thid= do st <- findState match =<< topState liftIO $ killBranch' st where match st= do (_,lab) <-liftIO $ readIORef $ labelth st return $ if lab == thid then True else False printBlock :: MVar () printBlock = unsafePerformIO $ newMVar () -- | Show the tree of threads hanging from the state. showThreads :: MonadIO m => EventF -> m () showThreads st = liftIO $ withMVar printBlock $ const $ do mythread <- myThreadId putStrLn "---------Threads-----------" let showTree n ch = do liftIO $ do putStr $ take n $ repeat ' ' (state, label) <- readIORef $ labelth ch if BS.null label then putStr . show $ threadId ch else do BS.putStr label; putStr . drop 8 . show $ threadId ch putStr " " > > putStr ( take 3 $ show state ) -- putStrLn $ if mythread == threadId ch then " <--" else "" chs <- readMVar $ children ch mapM_ (showTree $ n + 2) $ reverse chs showTree 0 st -- | Return the state of the thread that initiated the transient computation topState : : TransIO EventF topState :: TransMonad m => m EventF topState = do st <- get return $ toplevel st where toplevel st = case parent st of Nothing -> st Just p -> toplevel p getStateFromThread th top = resp where resp = do let thstring = drop 9 . show $ threadId top if thstring = = th then getstate top else do sts < - liftIO $ readMVar $ children top foldl ( < | > ) empty $ map ( getStateFromThread th ) sts getstate st = case M.lookup ( typeOf $ typeResp resp ) $ mfData st of Just x - > return . Just $ unsafeCoerce x Nothing - > return Nothing typeResp : : m ( Maybe x ) - > x typeResp = undefined getStateFromThread th top = resp where resp = do let thstring = drop 9 . show $ threadId top if thstring == th then getstate top else do sts <- liftIO $ readMVar $ children top foldl (<|>) empty $ map (getStateFromThread th) sts getstate st = case M.lookup (typeOf $ typeResp resp) $ mfData st of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined -} | find the first computation state which match a filter in the subthree of states findState :: (MonadIO m, Alternative m) => (EventF -> m Bool) -> EventF -> m EventF findState filter top= do r <- filter top if r then return top else do sts <- liftIO $ readMVar $ children top foldl (<|>) empty $ map (findState filter) sts -- | Return the state variable of the type desired for a thread number getStateFromThread :: (Typeable a, MonadIO m, Alternative m) => String -> EventF -> m (Maybe a) getStateFromThread th top= getstate =<< findState (matchth th) top where matchth th th'= do let thstring = drop 9 . show $ threadId th' return $ if thstring == th then True else False getstate st = resp where resp= case M.lookup (typeOf $ typeResp resp) $ mfData st of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined -- | execute all the states of the type desired that are created by direct child threads processStates :: Typeable a => (a-> TransIO ()) -> EventF -> TransIO() processStates display st = do getstate st >>= display liftIO $ print $ threadId st sts <- liftIO $ readMVar $ children st mapM_ (processStates display) sts where getstate st = case M.lookup (typeOf $ typeResp display) $ mfData st of Just x -> return $ unsafeCoerce x Nothing -> empty typeResp :: (a -> TransIO()) -> a typeResp = undefined -- | Add n threads to the limit of threads. If there is no limit, the limit is set. addThreads' :: Int -> TransIO () addThreads' n= noTrans $ do msem <- gets maxThread case msem of Just sem -> liftIO $ modifyIORef sem $ \n' -> n + n' Nothing -> do sem <- liftIO (newIORef n) modify $ \ s -> s { maxThread = Just sem } -- | Ensure that at least n threads are available for the current task set. addThreads :: Int -> TransIO () addThreads n = noTrans $ do msem <- gets maxThread case msem of Nothing -> return () Just sem -> liftIO $ modifyIORef sem $ \n' -> if n' > n then n' else n --getNonUsedThreads :: TransIO (Maybe Int) --getNonUsedThreads= Transient $ do < - gets case of -- Just sem -> liftIO $ Just <$> readIORef sem -- Nothing -> return Nothing -- | Disable tracking and therefore the ability to terminate the child threads. -- By default, child threads are terminated automatically when the parent -- thread dies, or they can be terminated using the kill primitives. Disabling -- it may improve performance a bit, however, all threads must be well-behaved -- to exit on their own to avoid a leak. freeThreads :: TransIO a -> TransIO a freeThreads process = Transient $ do st <- get put st { freeTh = True } r <- runTrans process modify $ \s -> s { freeTh = freeTh st } return r -- | Enable tracking and therefore the ability to terminate the child threads. -- This is the default but can be used to re-enable tracking if it was -- previously disabled with 'freeThreads'. hookedThreads :: TransIO a -> TransIO a hookedThreads process = Transient $ do st <- get put st {freeTh = False} r <- runTrans process modify $ \s -> s { freeTh = freeTh st } return r -- | Kill all the child threads of the current thread. killChilds :: TransIO () killChilds = noTrans $ do cont <- get liftIO $ do killChildren $ children cont writeIORef (labelth cont) (Alive, mempty) -- !> (threadId cont,"relabeled") return () -- | Kill the current thread and the childs. killBranch :: TransIO () killBranch = noTrans $ do st <- get liftIO $ killBranch' st -- | Kill the childs and the thread of an state killBranch' :: EventF -> IO () killBranch' cont = do forkIO $ do killChildren $ children cont let thisth = threadId cont mparent = parent cont when (isJust mparent) $ modifyMVar_ (children $ fromJust mparent) $ \sts -> return $ filter (\st -> threadId st /= thisth) sts killThread $ thisth !> ("kill this thread:",thisth) return () -- * Extensible State: Session Data Management -- | Same as 'getSData' but with a more conventional interface. If the data is found, a -- 'Just' value is returned. Otherwise, a 'Nothing' value is returned. getData :: (TransMonad m, Typeable a) => m (Maybe a) getData = resp where resp = do list <- gets mfData case M.lookup (typeOf $ typeResp resp) list of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined -- | Retrieve a previously stored data item of the given data type from the -- monad state. The data type to retrieve is implicitly determined by the data type. -- If the data item is not found, empty is executed, so the alternative computation will be executed, if any. -- Otherwise, the computation will stop. -- If you want to print an error message or return a default value, you can use an 'Alternative' composition. For example: -- -- > getSData <|> error "no data of the type desired" -- > getInt = getSData <|> return (0 :: Int) -- -- The later return either the value set or 0. -- -- It is highly recommended not to use it directly, since his relatively complex behaviour may be confusing sometimes. -- Use instead a monomorphic alias like "getInt" defined above. getSData :: Typeable a => TransIO a getSData = Transient getData -- | Same as `getSData` getState :: Typeable a => TransIO a getState = getSData -- | 'setData' stores a data item in the monad state which can be retrieved -- later using 'getData' or 'getSData'. Stored data items are keyed by their data type , and therefore only one item of a given type can be stored . A newtype wrapper can be used to distinguish two data items of the same type . -- -- @ import Control . Monad . IO.Class ( liftIO ) -- import Transient.Base import Data . Typeable -- -- data Person = Person -- { name :: String -- , age :: Int } deriving -- -- main = keep $ do setData $ Person " " 55 -- Person name age <- getSData -- liftIO $ print (name, age) -- @ setData :: (TransMonad m, Typeable a) => a -> m () setData x = modify $ \st -> st { mfData = M.insert t (unsafeCoerce x) (mfData st) } where t = typeOf x -- | Accepts a function which takes the current value of the stored data type -- and returns the modified value. If the function returns 'Nothing' the value -- is deleted otherwise updated. modifyData :: (TransMonad m, Typeable a) => (Maybe a -> Maybe a) -> m () modifyData f = modify $ \st -> st { mfData = M.alter alterf t (mfData st) } where typeResp :: (Maybe a -> b) -> a typeResp = undefined t = typeOf (typeResp f) alterf mx = unsafeCoerce $ f x' where x' = case mx of Just x -> Just $ unsafeCoerce x Nothing -> Nothing | Either modify according with the first parameter or insert according with the second , depending on if the data exist or not . It returns the -- old value or the new value accordingly. -- -- > runTransient $ do modifyData' (\h -> h ++ " world") "hello new" ; r <- getSData ; liftIO $ putStrLn r -- > "hello new" -- > runTransient $ do setData "hello" ; modifyData' (\h -> h ++ " world") "hello new" ; r <- getSData ; liftIO $ putStrLn r -- > "hello world" modifyData' :: (TransMonad m, Typeable a) => (a -> a) -> a -> m a modifyData' f v= do st <- get let (ma,nmap)= M.insertLookupWithKey alterf t (unsafeCoerce v) (mfData st) put st { mfData =nmap} return $ if isNothing ma then v else unsafeCoerce $ fromJust ma where t = typeOf v alterf _ _ x = unsafeCoerce $ f $ unsafeCoerce x -- | Same as `modifyData` modifyState :: (TransMonad m, Typeable a) => (Maybe a -> Maybe a) -> m () modifyState = modifyData -- | Same as `setData` setState :: (TransMonad m, Typeable a) => a -> m () setState = setData -- | Delete the data item of the given type from the monad state. delData :: (TransMonad m, Typeable a) => a -> m () delData x = modify $ \st -> st { mfData = M.delete (typeOf x) (mfData st) } -- | Same as `delData` delState :: (TransMonad m, Typeable a) => a -> m () delState = delData STRefs for the Transient monad newtype Ref a = Ref (IORef a) -- | Initializes a new mutable reference (similar to STRef in the state monad) -- It is polimorphic. Each type has his own reference It return the associated IORef , so it can be updated in the IO monad newRState:: (MonadIO m,TransMonad m, Typeable a) => a -> m (IORef a) newRState x= do ref@(Ref rx) <- Ref <$> liftIO (newIORef x) setData ref return rx -- | mutable state reference that can be updated (similar to STRef in the state monad) -- They are identified by his type. Initialized the first time it is set . setRState:: (MonadIO m,TransMonad m, Typeable a) => a -> m () setRState x= do Ref ref <- getData `onNothing` do ref <- Ref <$> liftIO (newIORef x) setData ref return ref liftIO $ atomicModifyIORef ref $ const (x,()) getRData :: (MonadIO m, TransMonad m, Typeable a) => m (Maybe a) getRData= do mref <- getData case mref of Just (Ref ref) -> Just <$> (liftIO $ readIORef ref) Nothing -> return Nothing getRState :: Typeable a => TransIO a getRState= Transient getRData delRState x= delState (undefined `asTypeOf` ref x) where ref :: a -> Ref a ref = undefined -- | Run an action, if it does not succeed, undo any state changes -- that may have been caused by the action and allow aternative actions to run with the original state try :: TransIO a -> TransIO a try mx = do s <- get mx <|> (modify (const s) >> empty) -- | Executes the computation and reset the state either if it fails or not. sandbox :: TransIO a -> TransIO a sandbox mx = do sd <- gets mfData mx <*** modify (\s ->s { mfData = sd}) -- | generates an identifier that is unique within the current program execution genGlobalId :: MonadIO m => m Int genGlobalId= liftIO $ atomicModifyIORef rglobalId $ \n -> (n +1,n) rglobalId= unsafePerformIO $ newIORef (0 :: Int) -- | Generator of identifiers that are unique within the current monadic -- sequence They are not unique in the whole program. genId :: TransMonad m => m Int genId = do st <- get let n = mfSequence st put st { mfSequence = n + 1 } return n getPrevId :: TransMonad m => m Int getPrevId = gets mfSequence instance Read SomeException where readsPrec n str = [(SomeException $ ErrorCall s, r)] where [(s , r)] = readsPrec n str -- | 'StreamData' represents an result in an stream being generated. data StreamData a = SMore a -- ^ More to come ^ This is the last one | SDone -- ^ No more, we are done | SError SomeException -- ^ An error occurred deriving (Typeable, Show,Read) instance Functor StreamData where fmap f (SMore a)= SMore (f a) fmap f (SLast a)= SLast (f a) fmap _ SDone= SDone -- | A task stream generator that produces an infinite stream of results by -- running an IO computation in a loop, each result may be processed in different threads (tasks) -- depending on the thread limits stablished with `threads`. waitEvents :: IO a -> TransIO a waitEvents io = do mr <- parallel (SMore <$> io) case mr of SMore x -> return x SError e -> back e -- | Run an IO computation asynchronously carrying -- the result of the computation in a new thread when it completes. -- If there are no threads available, the async computation and his continuation is executed -- in the same thread before any alternative computation. async :: IO a -> TransIO a async io = do mr <- parallel (SLast <$> io) case mr of SLast x -> return x SError e -> back e -- | Avoid the execution of alternative computations when the computation is asynchronous -- -- > sync (async whatever) <|> liftIO (print "hello") -- never print "hello" sync :: TransIO a -> TransIO a sync x = do was <- gets execMode -- getSData <|> return Serial r <- x <** modify (\s ->s{execMode= Remote}) -- setData Remote modify $ \s -> s{execMode= was} return r | create task threads faster , but with no thread control : = freeThreads . spawn :: IO a -> TransIO a spawn = freeThreads . waitEvents -- | An stream generator that run an IO computation periodically at the specified time interval. The -- task carries the result of the computation. A new result is generated only if -- the output of the computation is different from the previous one. sample :: Eq a => IO a -> Int -> TransIO a sample action interval = do v <- liftIO action prev <- liftIO $ newIORef v waitEvents (loop action prev) <|> return v where loop action prev = loop' where loop' = do threadDelay interval v <- action v' <- readIORef prev if v /= v' then writeIORef prev v >> return v else loop' -- | Runs the rest of the computation in a new thread. Returns 'empty' to the current thread abduce = async $ return () -- | fork an independent process. It is equivalent to forkIO. The thread created -- is managed with the thread control primitives of transient fork :: TransIO () -> TransIO () fork proc= (abduce >> proc >> empty) <|> return() | Run an IO action one or more times to generate a stream of tasks . The IO action returns a ' StreamData ' . When it returns an ' SMore ' or ' SLast ' a new -- result is returned with the result value. If there are threads available, the res of the computation is executed in a new thread . If the return value is ' SMore ' , the -- action is run again to generate the next result, otherwise task creation -- stop. -- -- Unless the maximum number of threads (set with 'threads') has been reached, -- the task is generated in a new thread and the current thread returns a void -- task. parallel :: IO (StreamData b) -> TransIO (StreamData b) parallel ioaction = Transient $ do --was <- gets execMode -- getData `onNothing` return Serial --when (was /= Remote) $ modify $ \s -> s{execMode= Parallel} modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} cont <- get ! > " PARALLEL " case event cont of j@(Just _) -> do put cont { event = Nothing } return $ unsafeCoerce j Nothing -> do liftIO $ atomicModifyIORef (labelth cont) $ \(_, lab) -> ((Parent, lab), ()) liftIO $ loop cont ioaction return Nothing | Execute the IO action and the continuation loop :: EventF -> IO (StreamData t) -> IO () loop parentc rec = forkMaybe True parentc $ \cont -> do Execute the IO computation and then the closure - continuation liftIO $ atomicModifyIORef (labelth cont) $ \(_,label) -> ((Listener,label),()) let loop'= do mdat <- rec `catch` \(e :: SomeException) -> return $ SError e case mdat of se@(SError _) -> setworker cont >> iocont se cont SDone -> setworker cont >> iocont SDone cont last@(SLast _) -> setworker cont >> iocont last cont more@(SMore _) -> do forkMaybe False cont $ iocont more loop' where setworker cont= liftIO $ atomicModifyIORef (labelth cont) $ \(_,lab) -> ((Alive,lab),()) iocont dat cont = do let cont'= cont{event= Just $ unsafeCoerce dat} runStateT (runCont cont') cont' return () loop' return () where # INLINABLE forkMaybe # forkMaybe :: Bool -> EventF -> (EventF -> IO ()) -> IO () forkMaybe onemore parent proc = do case maxThread parent of Nothing -> forkIt parent proc Just sem -> do dofork <- waitQSemB onemore sem if dofork then forkIt parent proc else proc parent `catch` \e ->exceptBack parent e >> return() forkIt parent proc= do chs <- liftIO $ newMVar [] label <- newIORef (Alive, BS.pack "work") let cont = parent{parent=Just parent,children= chs, labelth= label} forkFinally1 (do th <- myThreadId let cont'= cont{threadId=th} when(not $ freeTh parent )$ hangThread parent cont' -- !> ("thread created: ",th,"in",threadId parent ) proc cont') $ \me -> do case me of ! > " exceptBack 2 " _ -> return () case maxThread cont of Just sem -> signalQSemB sem -- !> "freed thread" Nothing -> return () when(not $ freeTh parent ) $ do -- if was not a free thread th <- myThreadId (can,label) <- atomicModifyIORef (labelth cont) $ \(l@(status,label)) -> ((if status== Alive then Dead else status, label),l) when (can /= Parent ) $ free th parent return () forkFinally1 :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally1 action and_then = mask $ \restore -> forkIO $ Control.Exception.try (restore action) >>= and_then free th env= do -- return () !> ("freeing",th,"in",threadId env) threadDelay 1000 -- wait for some activity in the children of the parent thread, to avoid -- an early elimination let sibling= children env (sbs',found) <- modifyMVar sibling $ \sbs -> do let (sbs', found) = drop [] th sbs return (sbs',(sbs',found)) if found then do -- !> ("new list for",threadId env,map threadId sbs') (typ,_) <- readIORef $ labelth env if (null sbs' && typ /= Listener && isJust (parent env)) -- free the parent then free (threadId env) ( fromJust $ parent env) else return () else return () -- putMVar sibling sbs -- !> (th,"orphan") where drop processed th []= (processed,False) drop processed th (ev:evts)| th == threadId ev= (processed ++ evts, True) | otherwise= drop (ev:processed) th evts hangThread parentProc child = do let headpths= children parentProc modifyMVar_ headpths $ \ths -> return (child:ths) -- !> ("hang", threadId child, threadId parentProc,map threadId ths,unsafePerformIO $ readIORef $ labelth parentProc) -- | kill all the child threads associated with the continuation context killChildren childs = do forkIO $ do ths <- modifyMVar childs $ \ths -> return ([],ths) mapM_ (killChildren . children) ths mapM_ (\th -> do (status,_) <- readIORef $ labelth th when (status /= Listener && status /= Parent) $ killThread $ threadId th !> ("killChildren",threadId th, status)) ths >> return () return () -- | capture a callback handler so that the execution of the current computation continues -- whenever an event occurs. The effect is called "de-inversion of control" -- The first parameter is a callback setter . The second parameter is a value to be -- returned to the callback; if the callback expects no return value it can just be @return ( ) @. The callback setter expects a function taking the @eventdata@ as an argument and returning a value ; this -- function is the continuation, which is supplied by 'react'. -- -- Callbacks from foreign code can be wrapped into such a handler and hooked -- into the transient monad using 'react'. Every time the callback is called it -- continues the execution on the current transient computation. -- -- > -- > do -- > event <- react onEvent $ return () -- > .... -- > react :: ((eventdata -> IO response) -> IO ()) -> IO response -> TransIO eventdata react setHandler iob= do st <- cloneInChild "react" liftIO $ atomicModifyIORef (labelth st) $ \(_,label) -> ((Listener,label),()) Transient $ do modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} cont <- get case event cont of Nothing -> do liftIO $ setHandler $ \dat ->do runStateT (runCont cont) st{event= Just $ unsafeCoerce dat} `catch` exceptBack cont iob return Nothing j@(Just _) -> do put cont{event=Nothing} return $ unsafeCoerce j -- * Non-blocking keyboard input -- getLineRef= unsafePerformIO $ newTVarIO Nothing | listen stdin and triggers a new task every time the input data matches the first parameter . The value contained by the task is the matched value i.e. the first argument itself . The second parameter is a message for -- the user. The label is displayed in the console when the option match. option :: (Typeable b, Show b, Read b, Eq b) => b -> String -> TransIO b option = optionf False Implements the same functionality than ` option ` but only wait for one input option1 :: (Typeable b, Show b, Read b, Eq b) => b -> String -> TransIO b option1= optionf True optionf :: (Typeable b, Show b, Read b, Eq b) => Bool -> b -> String -> TransIO b optionf flag ret message = do let sret= if typeOf ret == typeOf "" then unsafeCoerce ret else show ret let msg= "Enter "++sret++"\t\tto: " ++ message++"\n" inputf flag sret msg Nothing ( == sret) liftIO $ putStr "\noption: " >> putStrLn sret -- abduce return ret -- | General asynchronous console input. -- inputf < remove input listener after sucessful or not > < listener identifier > < prompt > -- <Maybe default value> <validation proc> inputf :: (Show a, Read a,Typeable a) => Bool -> String -> String -> Maybe a -> (a -> Bool) -> TransIO a inputf remove ident message mv cond = do let loop= do liftIO $ putStr message >> hFlush stdout str <- react (addConsoleAction ident message) (return ()) when remove $ do removeChild; liftIO $ delConsoleAction ident c <- liftIO $ readIORef rconsumed if c then returnm mv else do let rr = read1 str case (rr,str) of (Nothing,_) -> do (liftIO $ when (isJust mv) $ putStrLn ""); returnm mv (Just x,"") -> do (liftIO $ do writeIORef rconsumed True; print x); returnm mv (Just x,_) -> if cond x then liftIO $ do writeIORef rconsumed True print x -- hFlush stdout return x else do liftIO $ when (isJust mv) $ putStrLn "" returnm mv loop where returnm (Just x)= return x returnm _ = empty : : String - > Maybe a read1 s= r where typ= typeOf $ fromJust r r = if typ == typeOf "" then Just $ unsafeCoerce s else if typ == typeOf (BS.pack "") then Just $ unsafeCoerce $ BS.pack s else if typ == typeOf (BSL.pack "") then Just $ unsafeCoerce $ BSL.pack s else case reads s of [] -> Nothing [(x,"")] -> Just x | Waits on stdin and return a value when a console input matches the predicate specified in the first argument . The second parameter is a string -- to be displayed on the console before waiting. input :: (Typeable a, Read a,Show a) => (a -> Bool) -> String -> TransIO a input= input' Nothing -- | `input` with a default value input' :: (Typeable a, Read a,Show a) => Maybe a -> (a -> Bool) -> String -> TransIO a input' mv cond prompt= do --liftIO $ putStr prompt >> hFlush stdout inputf True "input" prompt mv cond rcb= unsafePerformIO $ newIORef [] :: IORef [ (String,String,String -> IO())] addConsoleAction :: String -> String -> (String -> IO ()) -> IO () addConsoleAction name message cb= atomicModifyIORef rcb $ \cbs -> ((name,message, cb) : filter ((/=) name . fst) cbs ,()) where fst (x,_,_)= x delConsoleAction :: String -> IO () delConsoleAction name= atomicModifyIORef rcb $ \cbs -> (filter ((/=) name . fst) cbs,()) where fst (x,_,_)= x reads1 s=x where x= if typeOf(typeOfr x) == typeOf "" then unsafeCoerce[(s,"")] else readsPrec' 0 s typeOfr :: [(a,String)] -> a typeOfr = undefined read1 s= let [(x,"")]= reads1 s in x rprompt= unsafePerformIO $ newIORef "> " inputLoop= do prompt <- readIORef rprompt when (not $ null prompt) $ do putStr prompt ; hFlush stdout line <- getLine threadDelay 1000000 processLine line inputLoop myThreadId > > = # NOINLINE rconsumed # rconsumed = unsafePerformIO $ newIORef False # NOINLINE lineprocessmode # lineprocessmode= unsafePerformIO $ newIORef False processLine r = do linepro <- readIORef lineprocessmode if linepro then do mapM' invokeParsers [r] else do let rs = breakSlash [] r mapM' invokeParsers rs where invokeParsers x= do mbs <- readIORef rcb mapM_ (\cb -> cb x) $ map (\(_,_,p)-> p) mbs mapM' _ []= return () mapM' f (xss@(x:xs)) =do f x r <- readIORef rconsumed if r then do writeIORef riterloop 0 writeIORef rconsumed False mapM' f xs else do threadDelay 1000 n <- atomicModifyIORef riterloop $ \n -> (n+1,n) if n==1 then do when (not $ null x) $ hPutStr stderr x >> hPutStrLn stderr ": can't read, skip" writeIORef riterloop 0 writeIORef rconsumed False mapM' f xs else mapM' f xss riterloop= unsafePerformIO $ newIORef 0 breakSlash :: [String] -> String -> [String] breakSlash [] ""= [""] breakSlash s ""= s breakSlash res ('\"':s)= let (r,rest) = span(/= '\"') s in breakSlash (res++[r]) $ tail1 rest breakSlash res s= let (r,rest) = span(\x -> (not $ elem x "/,:") && x /= ' ') s in breakSlash (res++[r]) $ tail1 rest tail1 []= [] tail1 x= tail x > > > [ ] " test.hs/0/\"-prof -auto\ " " -- ["test.hs","0","-prof -auto"] -- -- | Wait for the execution of `exit` and return the result or the exhaustion of thread activity stay rexit= takeMVar rexit `catch` \(e :: BlockedIndefinitelyOnMVar) -> return Nothing newtype Exit a= Exit a deriving Typeable -- | Runs the transient computation in a child thread and keeps the main thread -- running until all the user threads exit or some thread 'exit'. -- -- The main thread provides facilities for accepting keyboard input in a -- non-blocking but line-oriented manner. The program reads the standard input -- and feeds it to all the async input consumers (e.g. 'option' and 'input'). -- All async input consumers contend for each line entered on the standard -- input and try to read it atomically. When a consumer consumes the input -- others do not get to see it, otherwise it is left in the buffer for others -- to consume. If nobody consumes the input, it is discarded. -- -- A @/@ in the input line is treated as a newline. -- -- When using asynchronous input, regular synchronous IO APIs like getLine -- cannot be used as they will contend for the standard input along with the -- asynchronous input thread. Instead you can use the asynchronous input APIs -- provided by transient. -- A built - in interactive command handler also reads the stdin asynchronously . -- All available options waiting for input are displayed when the -- program is run. The following commands are available: -- 1 . @ps@ : show threads 2 . : inspect the log of a thread 3 . @end@ , @exit@ : terminate the program -- -- An input not handled by the command handler can be handled by the program. -- The program 's command line is scanned for @-p@ or @--path@ command line -- options. The arguments to these options are injected into the async input -- channel as keyboard input to the program. Each line of input is separated by -- a @/@. For example: -- > foo -p ps / end -- keep :: Typeable a => TransIO a -> IO (Maybe a) keep mx = do liftIO $ hSetBuffering stdout LineBuffering rexit <- newEmptyMVar void $ forkIO $ do -- liftIO $ putMVar rexit $ Right Nothing let logFile= "trans.log" void $ runTransient $ do liftIO $ removeFile logFile `catch` \(e :: IOError) -> return () onException $ \(e :: SomeException) -> do --top <- topState liftIO $ print e --showThreads top` liftIO $ appendFile show e + + " \n " -- ` catch ` \(e : : IOError ) - > exc empty onException $ \(e :: IOException) -> do when (ioeGetErrorString e == "resource busy") $ do liftIO $ do print e ; putStrLn "EXITING!!!"; putMVar rexit Nothing empty st <- get setData $ Exit rexit do option "options" "show all options" mbs <- liftIO $ readIORef rcb liftIO $ mapM_ (\c ->do putStr c; putStr "|") $ map (\(fst,_,_) -> fst)mbs d <- input' (Just "n") (\x -> x=="y" || x =="n" || x=="Y" || x=="N") "\nDetails? N/y " when (d == "y") $ do putStr x ; putStr " \t\t " ; in liftIO $ mapM_ line mbs liftIO $ putStrLn "" empty <|> do option "ps" "show threads" liftIO $ showThreads st empty <|> do option "errs" "show exceptions log" c <- liftIO $ readFile logFile `catch` \(e:: IOError) -> return "" liftIO . putStrLn $ if null c then "no errors logged" else c empty {- <|> do option "log" "inspect the log of a thread" th <- input (const True) "thread number>" ml <- liftIO $ getStateFromThread th st liftIO $ print $ fmap (\(Log _ _ log _) -> reverse log) ml empty -} <|> do option "end" "exit" liftIO $ putStrLn "exiting..." abduce killChilds liftIO $ putMVar rexit Nothing empty <|> mx #ifndef ghcjs_HOST_OS <|> do abduce liftIO $ execCommandLine labelState (fromString "input") liftIO inputLoop empty #endif return () stay rexit where type1 :: TransIO a -> Either String (Maybe a) type1= undefined -- | Same as `keep` but does not read from the standard input, and therefore -- the async input APIs ('option' and 'input') cannot respond interactively. -- However, input can still be passed via command line arguments as -- described in 'keep'. Useful for debugging or for creating background tasks, -- as well as to embed the Transient monad inside another computation. It -- returns either the value returned by `exit` or Nothing, when there are no -- more threads running -- keep' :: Typeable a => TransIO a -> IO (Maybe a) keep' mx = do liftIO $ hSetBuffering stdout LineBuffering rexit <- newEmptyMVar void $ forkIO $ do void $ runTransient $ do onException $ \(e :: SomeException ) -> do top <- topState liftIO $ do th <- myThreadId putStr $ show th putStr ": " print e putStrLn "Threads:" showThreads top empty onException $ \(e :: IOException) -> do when (ioeGetErrorString e == "resource busy") $ do liftIO $ do print e ; putStrLn "EXITING!!!"; putMVar rexit Nothing liftIO $ putMVar rexit Nothing empty setData $ Exit rexit mx return () threadDelay 10000 forkIO $ execCommandLine stay rexit execCommandLine= do args <- getArgs let mindex = findIndex (\o -> o == "-p" || o == "--path" ) args when (isJust mindex) $ do let i= fromJust mindex +1 when (length args >= i) $ do let path= args !! i --print $ drop (i-1) args --putStr "Executing: " >> print path processLine path -- | Exit the main thread with a result, and thus all the Transient threads (and the -- application if there is no more code) exit :: Typeable a => a -> TransIO a exit x= do Exit rexit <- getSData <|> error "exit: not the type expected" `asTypeOf` type1 x liftIO $ putMVar rexit $ Just x stop where type1 :: a -> TransIO (Exit (MVar (Maybe a))) type1= undefined | If the first parameter is ' Nothing ' return the second parameter otherwise return the first parameter .. onNothing :: Monad m => m (Maybe b) -> m b -> m b onNothing iox iox'= do mx <- iox case mx of Just x -> return x Nothing -> iox' ----------------------------------backtracking ------------------------ data Backtrack b= Show b =>Backtrack{backtracking :: Maybe b ,backStack :: [EventF] } deriving Typeable -- | Delete all the undo actions registered till now for the given track id. backCut :: (Typeable b, Show b) => b -> TransientIO () backCut reason= Transient $ do delData $ Backtrack (Just reason) [] return $ Just () -- | 'backCut' for the default track; equivalent to @backCut ()@. undoCut :: TransientIO () undoCut = backCut () | Run the action in the first parameter and register the second parameter as the undo action . On undo ( ' back ' ) the second parameter is called with the -- undo track id as argument. -- # NOINLINE onBack # onBack :: (Typeable b, Show b) => TransientIO a -> ( b -> TransientIO a) -> TransientIO a onBack ac bac = registerBack (typeof bac) $ Transient $ do tr "onBack" Backtrack mreason stack <- getData `onNothing` (return $ backStateOf (typeof bac)) runTrans $ case mreason of ! > " ONBACK NOTHING " ! > ( " ONBACK JUST",reason ) where typeof :: (b -> TransIO a) -> b typeof = undefined -- | 'onBack' for the default track; equivalent to @onBack ()@. onUndo :: TransientIO a -> TransientIO a -> TransientIO a onUndo x y= onBack x (\() -> y) | Register an undo action to be executed when backtracking . The first -- parameter is a "witness" whose data type is used to uniquely identify this -- backtracking action. The value of the witness parameter is not used. -- # NOINLINE registerUndo # registerBack :: (Typeable b, Show b) => b -> TransientIO a -> TransientIO a registerBack witness f = Transient $ do tr "registerBack" cont@(EventF _ x _ _ _ _ _ _ _ _ _ _ _) <- get -- if isJust (event cont) then return Nothing else do md <- getData `asTypeOf` (Just <$> return (backStateOf witness)) case md of Just (Backtrack b []) -> setData $ Backtrack b [cont] Just (bss@(Backtrack b (bs@((EventF _ x' _ _ _ _ _ _ _ _ _ _ _):_)))) -> when (isNothing b) $ setData $ Backtrack b (cont:bs) Nothing -> setData $ Backtrack mwit [cont] runTrans $ return () >> f where mwit= Nothing `asTypeOf` (Just witness) --addr x = liftIO $ return . hashStableName =<< (makeStableName $! x) registerUndo :: TransientIO a -> TransientIO a registerUndo f= registerBack () f -- XXX Should we enforce retry of the same track which is being undone? If the -- user specifies a different track would it make sense? -- see -Transient-Universe-HPlay/Lobby?at=5ef46626e0e5673398d33afb -- -- | For a given undo track type, stop executing more backtracking actions and -- resume normal execution in the forward direction. Used inside an undo -- action. -- forward :: (Typeable b, Show b) => b -> TransIO () forward reason= noTrans $ do Backtrack _ stack <- getData `onNothing` ( return $ backStateOf reason) setData $ Backtrack(Nothing `asTypeOf` Just reason) stack -- | put at the end of an backtrack handler intended to backtrack to other previous handlers. -- This is the default behaviour in transient. `backtrack` is in order to keep the type compiler happy backtrack :: TransIO a backtrack= return $ error "backtrack should be called at the end of an exception handler with no `forward`, `continue` or `retry` on it" | ' forward ' for the default undo track ; equivalent to @forward ( ) @. retry= forward () -- | Abort finish. Stop executing more finish actions and resume normal -- execution. Used inside 'onFinish' actions. -- noFinish= continue -- | Start the undo process for a given undo track identifier type. Performs all the undo -- actions registered for that type in reverse order. An undo action can use -- 'forward' to stop the undo process and resume forward execution. If there -- are no more undo actions registered, execution stop -- back :: (Typeable b, Show b) => b -> TransIO a back reason = do tr "back" bs <- getData `onNothing` return (backStateOf reason) ! > " GOBACK " where runClosure :: EventF -> TransIO a runClosure EventF { xcomp = x } = unsafeCoerce x runContinuation :: EventF -> a -> TransIO b runContinuation EventF { fcomp = fs } = (unsafeCoerce $ compose fs) goBackt (Backtrack _ [] )= empty goBackt (Backtrack b (stack@(first : bs)) )= do setData $ Backtrack (Just reason) bs --stack x <- runClosure first !> ("RUNCLOSURE",length stack) Backtrack back bs' <- getData `onNothing` return (backStateOf reason) case back of Nothing -> do setData $ Backtrack (Just reason) stack st <- get runContinuation first x `catcht` (\e -> liftIO(exceptBack st e) >> empty) !> "FORWARD EXEC" justreason -> do setData $ Backtrack justreason bs goBackt $ Backtrack justreason bs !> ("BACK AGAIN",back) empty backStateOf :: (Show a, Typeable a) => a -> Backtrack a backStateOf reason= Backtrack (Nothing `asTypeOf` (Just reason)) [] data BackPoint a = BackPoint (IORef [a -> TransIO()]) -- | a backpoint is a location in the code where callbacks can be installed and will be called when the backtracing pass trough that point. -- Normally used for exceptions. backPoint :: (Typeable reason,Show reason) => TransIO (BackPoint reason) backPoint = do point <- liftIO $ newIORef [] return () `onBack` (\e -> do rs <- liftIO $ readIORef point mapM_ (\r -> r e) rs) return $ BackPoint point -- | install a callback in a backPoint onBackPoint :: MonadIO m => BackPoint t -> (t -> TransIO ()) -> m () onBackPoint (BackPoint ref) handler= liftIO $ atomicModifyIORef ref $ \rs -> (handler:rs,()) -- | 'back' for the default undo track; equivalent to @back ()@. -- undo :: TransIO a undo= back () ------ finalization newtype Finish= Finish String deriving Show instance Exception Finish newtype FinishReason= FinishReason ( Maybe SomeException ) deriving ( Typeable , Show ) -- | Clear all finish actions registered till now. -- initFinish= backCut (FinishReason Nothing) -- | Register an action that to be run when 'finish' is called. 'onFinish' can -- be used multiple times to register multiple actions. Actions are run in -- reverse order. Used in infix style. -- onFinish :: (Finish ->TransIO ()) -> TransIO () onFinish f= onException' (return ()) f | Run the action specified in the first parameter and register the second -- parameter as a finish action to be run when 'finish' is called. Used in -- infix style. -- onFinish' ::TransIO a ->(Finish ->TransIO a) -> TransIO a onFinish' proc f= proc `onException'` f -- | Execute all the finalization actions registered up to the last ' initFinish ' , in reverse order and continue the execution . Either an exception or ' Nothing ' can be initFinish = cutExceptions -- passed to 'finish'. The argument passed is made available in the 'onFinish' -- finish :: String -> TransIO () finish reason= (throwt $ Finish reason) <|> return() -- | trigger finish when the stream of data ends checkFinalize v= case v of SDone -> stop SLast x -> return x SError e -> throwt e SMore x -> return x ------ exceptions --- -- | Install an exception handler . Handlers are executed in reverse ( i.e. last in , first out ) order when such exception happens in the -- continuation. Note that multiple handlers can be installed for the same exception type. -- The semantic is , thus , very different than the one of ` Control . Exception . Base.onException ` onException :: Exception e => (e -> TransIO ()) -> TransIO () onException exc= return () `onException'` exc | set an exception point . is a point in the backtracking in which exception handlers can be inserted with ` onExceptionPoint ` -- it is an specialization of `backPoint` for exceptions. -- -- When an exception backtracking reach the backPoint it executes all the handlers registered for it. -- -- Use case: suppose that when a connection fails, you need to stop a process. -- This process may not be started before the connection. Perhaps it was initiated after the socket read -- so an exception will not backtrack trough the process, since it is downstream, not upstream. The process may -- be even unrelated to the connection, in other branch of the computation. -- -- in this case you only need to create a `exceptionPoint` before stablishin the connection, and use `onExceptionPoint` -- to set a handler that will be called when the connection fail. exceptionPoint :: Exception e => TransIO (BackPoint e) exceptionPoint = do point <- liftIO $ newIORef [] return () `onException'` (\e -> do rs<- liftIO $ readIORef point mapM_ (\r -> r e) rs) return $ BackPoint point -- | in conjunction with `backPoint` it set a handler that will be called when backtracking pass -- trough the point onExceptionPoint :: Exception e => BackPoint e -> (e -> TransIO()) -> TransIO () onExceptionPoint= onBackPoint onException' :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a onException' mx f= onAnyException mx $ \e -> do --return () !> "EXCEPTION HANDLER EXEC" case fromException e of Nothing -> do Backtrack r stack <- getData `onNothing` return (backStateOf e) setData $ Backtrack r $ tail stack back e empty Just e' -> f e' where onAnyException :: TransIO a -> (SomeException ->TransIO a) -> TransIO a onAnyException mx exc= ioexp `onBack` exc ioexp = Transient $ do st <- get (mr,st') <- liftIO $ (runStateT (do case event st of Nothing -> do r <- runTrans mx modify $ \s -> s{event= Just $ unsafeCoerce r} runCont st -- was <- gets execMode -- getData `onNothing` return Serial -- when (was /= Remote) $ modify $ \s -> s{execMode= Parallel} modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} return Nothing Just r -> do modify $ \s -> s{event=Nothing} return $ unsafeCoerce r) st) `catch` exceptBack st put st' return mr exceptBack st = \(e ::SomeException) -> do tr "catched" ! > " EXCEPTBACK " -- `catch` exceptBack st -- removed re execute the first argument as long as the exception is produced within the argument . The second argument is executed before every re - execution if the second argument executes ` empty ` the execution is aborted . whileException :: Exception e => TransIO b -> (e -> TransIO()) -> TransIO b whileException mx fixexc = mx `catcht` \e -> do fixexc e; whileException mx fixexc -- | Delete all the exception handlers registered till now. cutExceptions :: TransIO () cutExceptions= backCut (undefined :: SomeException) -- | Use it inside an exception handler. it stop executing any further exception -- handlers and resume normal execution from this point on. continue :: TransIO () continue = forward (undefined :: SomeException) -- !> "CONTINUE" -- | catch an exception in a Transient block -- -- The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded catcht :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b catcht mx exc= do st <- get (mx,st') <- liftIO $ runStateT ( runTrans $ mx ) st `catch` \e -> runStateT ( runTrans $ exc e ) st put st' case mx of Just x -> return x Nothing -> empty -- | catch an exception in a Transient block -- -- The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded catcht' :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b catcht' mx exc= do rpassed <- liftIO $ newIORef False sandbox $ do r <- onException' mx (\e -> do passed <- liftIO $ readIORef rpassed return () !> ("CATCHT passed", passed) if not passed then continue >> exc e else do Backtrack r stack <- getData `onNothing` return (backStateOf e) setData $ Backtrack r $ tail stack back e return () !> "AFTER BACK" empty ) liftIO $ writeIORef rpassed True return r where sandbox mx= do exState <- getState <|> return (backStateOf (undefined :: SomeException)) mx <*** do setState exState -- | throw an exception in the Transient monad -- there is a difference between `throw` and `throwt` since the latter preserves the state, while the former does not. -- Any exception not thrown with `throwt` does not preserve the state. -- -- > main= keep $ do > onException $ \(e : : SomeException ) - > do -- > v <- getState <|> return "hello" -- > liftIO $ print v -- > setState "world" > throw $ ErrorCall " asdasd " -- -- the latter print "hello". If you use `throwt` instead, it prints "world" throwt :: Exception e => e -> TransIO a throwt = back . toException
null
https://raw.githubusercontent.com/transient-haskell/transient-stack/dde6f6613a946d57bb70879a5c0e7e5a73a91dbe/transient/src/Transient/Internals.hs
haskell
---------------------------------------------------------------------------- Module : Transient.Internals Copyright : Maintainer : Stability : Portability : | See -haskell/transient Everything in this module is exported in order to allow extensibility. --------------------------------------------------------------------------- # LANGUAGE CPP # # LANGUAGE ScopedTypeVariables # # LANGUAGE UndecidableInstances # # LANGUAGE DeriveDataTypeable # # LANGUAGE ConstraintKinds # import GHC.Real import GHC.Conc(unsafeIOToSTM) # INLINE (!>) # # INLINE (!>) # ^ Not yet consumed result (event) from the last asynchronous computation ^ List of continuations ^ State data accessed with get or put operations ^ When 'True', threads are not killed using kill primitives ^ The parent of this thread ^ Forked child threads, used only when 'freeTh' is 'False' ^ Maximum number of threads that are allowed to be created ^ Label the thread with its lifecycle state and a label string | To define primitives for all the transient monads: TransIO, Cloud and Widget | Run a computation in the underlying state monad. it is a little lighter and performant and it should not contain advanced effects beyond state. in principle the state monad should return a single response, but, for performance reasons, it can run inside elements of transient monad (using `runTrans`) which may produce many results | Run a transient computation with a default initial state | Run a transient computation with a given initial state | Get the continuation context: closure, continuation, state, child threads etc | Run the closure and the continuation using the state data of the calling thread | Run the closure and the continuation using its own state data. | Warning: Radically untyped stuff. handle with care runCont cont = do mr <- runClosure cont case mr of Nothing -> return Nothing Just r -> runContinuation cont r | Compose a list of continuations. | Run the closure (the 'x' in 'x >>= f') of the current bind operation. | Run the continuation (the 'f' in 'x >>= f') of the current bind operation with the current state. | Save a closure and a continuation ('x' and 'f' in 'x >>= f'). | Save a closure and continuation, run the closure, restore the old continuation. | NOTE: The old closure is discarded. | Restore the continuations to the provided ones. | NOTE: Events are also cleared out. | Run a chain of continuations. WARNING: It is up to the programmer to assure that each continuation typechecks continuation. NOTE: Normally this makes sense to stop the current flow with `stop` after the invocation. Instances for Transient Monad do f <- mf; x <- mx ; return $ f x | stop the current computation and does not execute any alternative computation getData `onNothing` return Serial | A synonym of 'empty' that can be used in a monadic expression. It stops the computation, which allows the next computation in an 'Alternative' ('<|>') composition to run. | Run @m a@ discarding its result before running @m b@. done. | Run @m b@ discarding its result, once after each task in @m a@, and once again after the whole task set is done. (**>) :: TransIO a -> TransIO b -> TransIO b (<***) :: TransIO a -> TransIO b -> TransIO a (<**) :: TransIO a -> TransIO b -> TransIO a setup. | Set the current closure and continuation for the current statement | Reset the closure and continuation. Remove inner binds than the previous computations may have stacked in the list of continuations. | Total variant of `tail` that returns an empty list when given an empty list. instance MonadTrans (Transient ) where lift mx = Transient $ mx >>= return . Just * Threads | Sets the maximum number of threads that can be created for the given task New threads are created by 'parallel', and APIs that use parallel. restore it clone the current state as a child of the current state, with the same thread remove the current child task from the tree of tasks. If the child and parent threads are different, the child is killed | Terminate all the child threads in the given task set and continue execution in the current thread. Useful to reap the children when a task is done, restart a task when a new event happens etc. !> ("FATHER:", threadId st) !> ("KILLEVENT1 ", map threadId chs ) | Add a label to the current passing threads so it can be printed by debugging calls like `showThreads` | return the threadId associated with an state (you can see all of them with the console option 'ps') | kill the thread subtree labeled as such (you can see all of them with the console option 'ps') | Show the tree of threads hanging from the state. | Return the state of the thread that initiated the transient computation | Return the state variable of the type desired for a thread number | execute all the states of the type desired that are created by direct child threads | Add n threads to the limit of threads. If there is no limit, the limit is set. | Ensure that at least n threads are available for the current task set. getNonUsedThreads :: TransIO (Maybe Int) getNonUsedThreads= Transient $ do Just sem -> liftIO $ Just <$> readIORef sem Nothing -> return Nothing | Disable tracking and therefore the ability to terminate the child threads. By default, child threads are terminated automatically when the parent thread dies, or they can be terminated using the kill primitives. Disabling it may improve performance a bit, however, all threads must be well-behaved to exit on their own to avoid a leak. | Enable tracking and therefore the ability to terminate the child threads. This is the default but can be used to re-enable tracking if it was previously disabled with 'freeThreads'. | Kill all the child threads of the current thread. !> (threadId cont,"relabeled") | Kill the current thread and the childs. | Kill the childs and the thread of an state * Extensible State: Session Data Management | Same as 'getSData' but with a more conventional interface. If the data is found, a 'Just' value is returned. Otherwise, a 'Nothing' value is returned. | Retrieve a previously stored data item of the given data type from the monad state. The data type to retrieve is implicitly determined by the data type. If the data item is not found, empty is executed, so the alternative computation will be executed, if any. Otherwise, the computation will stop. If you want to print an error message or return a default value, you can use an 'Alternative' composition. For example: > getSData <|> error "no data of the type desired" > getInt = getSData <|> return (0 :: Int) The later return either the value set or 0. It is highly recommended not to use it directly, since his relatively complex behaviour may be confusing sometimes. Use instead a monomorphic alias like "getInt" defined above. | Same as `getSData` | 'setData' stores a data item in the monad state which can be retrieved later using 'getData' or 'getSData'. Stored data items are keyed by their @ import Transient.Base data Person = Person { name :: String , age :: Int main = keep $ do Person name age <- getSData liftIO $ print (name, age) @ | Accepts a function which takes the current value of the stored data type and returns the modified value. If the function returns 'Nothing' the value is deleted otherwise updated. old value or the new value accordingly. > runTransient $ do modifyData' (\h -> h ++ " world") "hello new" ; r <- getSData ; liftIO $ putStrLn r -- > "hello new" > runTransient $ do setData "hello" ; modifyData' (\h -> h ++ " world") "hello new" ; r <- getSData ; liftIO $ putStrLn r -- > "hello world" | Same as `modifyData` | Same as `setData` | Delete the data item of the given type from the monad state. | Same as `delData` | Initializes a new mutable reference (similar to STRef in the state monad) It is polimorphic. Each type has his own reference | mutable state reference that can be updated (similar to STRef in the state monad) They are identified by his type. | Run an action, if it does not succeed, undo any state changes that may have been caused by the action and allow aternative actions to run with the original state | Executes the computation and reset the state either if it fails or not. | generates an identifier that is unique within the current program execution | Generator of identifiers that are unique within the current monadic sequence They are not unique in the whole program. | 'StreamData' represents an result in an stream being generated. ^ More to come ^ No more, we are done ^ An error occurred | A task stream generator that produces an infinite stream of results by running an IO computation in a loop, each result may be processed in different threads (tasks) depending on the thread limits stablished with `threads`. | Run an IO computation asynchronously carrying the result of the computation in a new thread when it completes. If there are no threads available, the async computation and his continuation is executed in the same thread before any alternative computation. | Avoid the execution of alternative computations when the computation is asynchronous > sync (async whatever) <|> liftIO (print "hello") -- never print "hello" getSData <|> return Serial setData Remote | An stream generator that run an IO computation periodically at the specified time interval. The task carries the result of the computation. A new result is generated only if the output of the computation is different from the previous one. | Runs the rest of the computation in a new thread. Returns 'empty' to the current thread | fork an independent process. It is equivalent to forkIO. The thread created is managed with the thread control primitives of transient result is returned with the result value. If there are threads available, the res of the action is run again to generate the next result, otherwise task creation stop. Unless the maximum number of threads (set with 'threads') has been reached, the task is generated in a new thread and the current thread returns a void task. was <- gets execMode -- getData `onNothing` return Serial when (was /= Remote) $ modify $ \s -> s{execMode= Parallel} !> ("thread created: ",th,"in",threadId parent ) !> "freed thread" if was not a free thread return () !> ("freeing",th,"in",threadId env) wait for some activity in the children of the parent thread, to avoid an early elimination !> ("new list for",threadId env,map threadId sbs') free the parent putMVar sibling sbs !> (th,"orphan") !> ("hang", threadId child, threadId parentProc,map threadId ths,unsafePerformIO $ readIORef $ labelth parentProc) | kill all the child threads associated with the continuation context | capture a callback handler so that the execution of the current computation continues whenever an event occurs. The effect is called "de-inversion of control" returned to the callback; if the callback expects no return value it function is the continuation, which is supplied by 'react'. Callbacks from foreign code can be wrapped into such a handler and hooked into the transient monad using 'react'. Every time the callback is called it continues the execution on the current transient computation. > > do > event <- react onEvent $ return () > .... > * Non-blocking keyboard input getLineRef= unsafePerformIO $ newTVarIO Nothing the user. The label is displayed in the console when the option match. abduce | General asynchronous console input. <Maybe default value> <validation proc> hFlush stdout to be displayed on the console before waiting. | `input` with a default value liftIO $ putStr prompt >> hFlush stdout ["test.hs","0","-prof -auto"] | Wait for the execution of `exit` and return the result or the exhaustion of thread activity | Runs the transient computation in a child thread and keeps the main thread running until all the user threads exit or some thread 'exit'. The main thread provides facilities for accepting keyboard input in a non-blocking but line-oriented manner. The program reads the standard input and feeds it to all the async input consumers (e.g. 'option' and 'input'). All async input consumers contend for each line entered on the standard input and try to read it atomically. When a consumer consumes the input others do not get to see it, otherwise it is left in the buffer for others to consume. If nobody consumes the input, it is discarded. A @/@ in the input line is treated as a newline. When using asynchronous input, regular synchronous IO APIs like getLine cannot be used as they will contend for the standard input along with the asynchronous input thread. Instead you can use the asynchronous input APIs provided by transient. All available options waiting for input are displayed when the program is run. The following commands are available: An input not handled by the command handler can be handled by the program. path@ command line options. The arguments to these options are injected into the async input channel as keyboard input to the program. Each line of input is separated by a @/@. For example: liftIO $ putMVar rexit $ Right Nothing top <- topState showThreads top` ` catch ` \(e : : IOError ) - > exc <|> do option "log" "inspect the log of a thread" th <- input (const True) "thread number>" ml <- liftIO $ getStateFromThread th st liftIO $ print $ fmap (\(Log _ _ log _) -> reverse log) ml empty | Same as `keep` but does not read from the standard input, and therefore the async input APIs ('option' and 'input') cannot respond interactively. However, input can still be passed via command line arguments as described in 'keep'. Useful for debugging or for creating background tasks, as well as to embed the Transient monad inside another computation. It returns either the value returned by `exit` or Nothing, when there are no more threads running print $ drop (i-1) args putStr "Executing: " >> print path | Exit the main thread with a result, and thus all the Transient threads (and the application if there is no more code) --------------------------------backtracking ------------------------ | Delete all the undo actions registered till now for the given track id. | 'backCut' for the default track; equivalent to @backCut ()@. undo track id as argument. | 'onBack' for the default track; equivalent to @onBack ()@. parameter is a "witness" whose data type is used to uniquely identify this backtracking action. The value of the witness parameter is not used. if isJust (event cont) then return Nothing else do addr x = liftIO $ return . hashStableName =<< (makeStableName $! x) XXX Should we enforce retry of the same track which is being undone? If the user specifies a different track would it make sense? see -Transient-Universe-HPlay/Lobby?at=5ef46626e0e5673398d33afb | For a given undo track type, stop executing more backtracking actions and resume normal execution in the forward direction. Used inside an undo action. | put at the end of an backtrack handler intended to backtrack to other previous handlers. This is the default behaviour in transient. `backtrack` is in order to keep the type compiler happy | Abort finish. Stop executing more finish actions and resume normal execution. Used inside 'onFinish' actions. | Start the undo process for a given undo track identifier type. Performs all the undo actions registered for that type in reverse order. An undo action can use 'forward' to stop the undo process and resume forward execution. If there are no more undo actions registered, execution stop stack | a backpoint is a location in the code where callbacks can be installed and will be called when the backtracing pass trough that point. Normally used for exceptions. | install a callback in a backPoint | 'back' for the default undo track; equivalent to @back ()@. ---- finalization | Clear all finish actions registered till now. initFinish= backCut (FinishReason Nothing) | Register an action that to be run when 'finish' is called. 'onFinish' can be used multiple times to register multiple actions. Actions are run in reverse order. Used in infix style. parameter as a finish action to be run when 'finish' is called. Used in infix style. | Execute all the finalization actions registered up to the last passed to 'finish'. The argument passed is made available in the 'onFinish' | trigger finish when the stream of data ends ---- exceptions --- continuation. Note that multiple handlers can be installed for the same exception type. it is an specialization of `backPoint` for exceptions. When an exception backtracking reach the backPoint it executes all the handlers registered for it. Use case: suppose that when a connection fails, you need to stop a process. This process may not be started before the connection. Perhaps it was initiated after the socket read so an exception will not backtrack trough the process, since it is downstream, not upstream. The process may be even unrelated to the connection, in other branch of the computation. in this case you only need to create a `exceptionPoint` before stablishin the connection, and use `onExceptionPoint` to set a handler that will be called when the connection fail. | in conjunction with `backPoint` it set a handler that will be called when backtracking pass trough the point return () !> "EXCEPTION HANDLER EXEC" was <- gets execMode -- getData `onNothing` return Serial when (was /= Remote) $ modify $ \s -> s{execMode= Parallel} `catch` exceptBack st -- removed | Delete all the exception handlers registered till now. | Use it inside an exception handler. it stop executing any further exception handlers and resume normal execution from this point on. !> "CONTINUE" | catch an exception in a Transient block The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded | catch an exception in a Transient block The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded | throw an exception in the Transient monad there is a difference between `throw` and `throwt` since the latter preserves the state, while the former does not. Any exception not thrown with `throwt` does not preserve the state. > main= keep $ do > v <- getState <|> return "hello" > liftIO $ print v > setState "world" the latter print "hello". If you use `throwt` instead, it prints "world"
License : MIT # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecordWildCards # { - # LANGUAGE MonoLocalBinds # - } module Transient.Internals where import Control.Applicative import Control.Monad.State import Data . Dynamic import qualified Data.Map as M import System.IO.Unsafe import Unsafe.Coerce import Control.Exception hiding (try,onException) import qualified Control.Exception (try) import Control.Concurrent import Control . Concurrent . STM hiding ( retry ) import qualified Control . Concurrent . STM as STM ( retry ) import Data.Maybe import Data.List import Data.IORef import System.Environment import System.IO import System.IO.Error import Data.String import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BSL import Data.Typeable import Control.Monad.Fail import System.Directory #ifdef DEBUG import Debug.Trace import System.Exit tshow :: Show a => a -> x -> x tshow= Debug.Trace.traceShow (!>) :: Show a => b -> a -> b (!>) x y = trace (show (unsafePerformIO myThreadId, y)) x infixr 0 !> #else tshow :: a -> x -> x tshow _ y= y (!>) :: a -> b -> a (!>) = const #endif tr x= return () !> x type StateIO = StateT EventF IO newtype TransIO a = Transient { runTrans :: StateIO (Maybe a) } type SData = () type EventId = Int type TransientIO = TransIO data LifeCycle = Alive | Parent | Listener | Dead deriving (Eq, Show) | EventF describes the context of a TransientIO computation : data EventF = forall a b. EventF { event :: Maybe SData , xcomp :: TransIO a , fcomp :: [b -> TransIO b] , mfData :: M.Map TypeRep SData , mfSequence :: Int , threadId :: ThreadId , freeTh :: Bool , parent :: Maybe EventF , children :: MVar [EventF] , maxThread :: Maybe (IORef Int) , labelth :: IORef (LifeCycle, BS.ByteString) , parseContext :: ParseContext , execMode :: ExecMode } deriving Typeable data ParseContext = ParseContext { more :: TransIO (StreamData BSL.ByteString) , buffer :: BSL.ByteString , done :: IORef Bool} deriving Typeable class MonadState EventF m => TransMonad m instance MonadState EventF m => TransMonad m instance MonadState EventF TransIO where get = Transient $ get >>= return . Just put x = Transient $ put x >> return (Just ()) state f = Transient $ do s <- get let ~(a, s') = f s put s' return $ Just a noTrans :: StateIO x -> TransIO x noTrans x = Transient $ x >>= return . Just | filters away the Nothing responses of the State monad . liftTrans :: StateIO (Maybe b) -> TransIO b liftTrans mx= do r <- noTrans mx case r of Nothing -> empty Just x -> return x emptyEventF :: ThreadId -> IORef (LifeCycle, BS.ByteString) -> MVar [EventF] -> EventF emptyEventF th label childs = EventF { event = mempty , xcomp = empty , fcomp = [] , mfData = mempty , mfSequence = 0 , threadId = th , freeTh = False , parent = Nothing , children = childs , maxThread = Nothing , labelth = label , parseContext = ParseContext (return SDone) mempty undefined , execMode = Serial} runTransient :: TransIO a -> IO (Maybe a, EventF) runTransient t = do th <- myThreadId label <- newIORef $ (Alive, BS.pack "top") childs <- newMVar [] runStateT (runTrans t) $ emptyEventF th label childs runTransState :: EventF -> TransIO x -> IO (Maybe x, EventF) runTransState st x = runStateT (runTrans x) st emptyIfNothing :: Maybe a -> TransIO a emptyIfNothing = Transient . return getCont :: TransIO EventF getCont = Transient $ Just <$> get runCont :: EventF -> StateIO (Maybe a) runCont EventF { xcomp = x, fcomp = fs } = runTrans $ do r <- unsafeCoerce x compose fs r runCont' :: EventF -> IO (Maybe a, EventF) runCont' cont = runStateT (runCont cont) cont getContinuations :: StateIO [a -> TransIO b] getContinuations = do EventF { fcomp = fs } <- get return $ unsafeCoerce fs # INLINE compose # compose :: [a -> TransIO a] -> (a -> TransIO b) compose [] = const empty compose (f:fs) = \x -> f x >>= compose fs runClosure :: EventF -> StateIO (Maybe a) runClosure EventF { xcomp = x } = unsafeCoerce (runTrans x) runContinuation :: EventF -> a -> StateIO (Maybe b) runContinuation EventF { fcomp = fs } = runTrans . (unsafeCoerce $ compose $ fs) setContinuation :: TransIO a -> (a -> TransIO b) -> [c -> TransIO c] -> StateIO () setContinuation b c fs = do modify $ \EventF{..} -> EventF { xcomp = b , fcomp = unsafeCoerce c : fs , .. } withContinuation :: b -> TransIO a -> TransIO a withContinuation c mx = do EventF { fcomp = fs, .. } <- get put $ EventF { xcomp = mx , fcomp = unsafeCoerce c : fs , .. } r <- mx restoreStack fs return r restoreStack :: TransMonad m => [a -> TransIO a] -> m () restoreStack fs = modify $ \EventF {..} -> EventF { event = Nothing, fcomp = fs, .. } with the next , and that the parameter type match the input of the first runContinuations :: [a -> TransIO b] -> c -> TransIO d runContinuations fs x = compose (unsafeCoerce fs) x instance Functor TransIO where fmap f mx = do x <- mx return $ f x instance Applicative TransIO where pure a = Transient . return $ Just a r1 <- liftIO $ newIORef Nothing r2 <- liftIO $ newIORef Nothing fparallel r1 r2 <|> xparallel r1 r2 where fparallel r1 r2= do f <- mf liftIO $ (writeIORef r1 $ Just f) mr <- liftIO (readIORef r2) case mr of Nothing -> empty Just x -> return $ f x xparallel r1 r2 = do mr <- liftIO (readIORef r1) case mr of Nothing -> do p <- gets execMode if p== Serial then empty else do x <- mx liftIO $ (writeIORef r2 $ Just x) mr <- liftIO (readIORef r1) case mr of Nothing -> empty Just f -> return $ f x Just f -> do x <- mx liftIO $ (writeIORef r2 $ Just x) return $ f x data ExecMode = Remote | Parallel | Serial deriving (Typeable, Eq, Show) fullStop :: TransIO stop fullStop= do modify $ \s ->s{execMode= Remote} ; stop instance Monad TransIO where return = pure x >>= f = Transient $ do setEventCont x f mk <- runTrans x resetEventCont mk case mk of Just k -> runTrans (f k) Nothing -> return Nothing instance MonadIO TransIO where liftIO x = Transient $ liftIO x >>= return . Just instance Monoid a => Monoid (TransIO a) where mempty = return mempty #if MIN_VERSION_base(4,11,0) mappend = (<>) instance (Monoid a) => Semigroup (TransIO a) where (<>)= mappendt #else mappend= mappendt #endif mappendt x y = mappend <$> x <*> y instance Alternative TransIO where empty = Transient $ return Nothing (<|>) = mplus instance MonadPlus TransIO where mzero = empty mplus x y = Transient $ do mx <- runTrans x if was == Remote then return Nothing else case mx of Nothing -> runTrans y justx -> return justx instance MonadFail TransIO where fail _ = mzero readWithErr :: (Typeable a, Read a) => Int -> String -> IO [(a, String)] readWithErr n line = (v `seq` return [(v, left)]) `catch` (\(_ :: SomeException) -> throw $ ParseError $ "read error trying to read type: \"" ++ show (typeOf v) ++ "\" in: " ++ " <" ++ show line ++ "> ") where (v, left):_ = readsPrec n line newtype ParseError= ParseError String instance Show ParseError where show (ParseError s)= "ParseError " ++ s instance Exception ParseError read' s= case readsPrec' 0 s of [(x,"")] -> x _ -> throw $ ParseError $ "reading " ++ s readsPrec' n = unsafePerformIO . readWithErr n stop :: Alternative m => m stopped stop = empty instance (Num a,Eq a,Fractional a) =>Fractional (TransIO a)where mf / mg = (/) <$> mf <*> mg fromRational r = return $ fromRational r instance (Num a, Eq a) => Num (TransIO a) where fromInteger = return . fromInteger mf + mg = (+) <$> mf <*> mg mf * mg = (*) <$> mf <*> mg negate f = f >>= return . negate abs f = f >>= return . abs signum f = f >>= return . signum class AdditionalOperators m where (**>) :: m a -> m b -> m b | Run @m b@ discarding its result , after the whole task set @m a@ is (<**) :: m a -> m b -> m a atEnd' :: m a -> m b -> m a atEnd' = (<**) (<***) :: m a -> m b -> m a atEnd :: m a -> m b -> m a atEnd = (<***) instance AdditionalOperators TransIO where (**>) x y = Transient $ do runTrans x runTrans y (<***) ma mb = Transient $ do fs <- getContinuations setContinuation ma (\x -> mb >> return x) fs a <- runTrans ma runTrans mb restoreStack fs return a (<**) ma mb = Transient $ do a <- runTrans ma runTrans mb return a infixl 4 <***, <**, **> | Run @b@ once , discarding its result when the first task in task set @a@ has finished . Useful to start a singleton task after the first task has been (<|) :: TransIO a -> TransIO b -> TransIO a (<|) ma mb = Transient $ do fs <- getContinuations ref <- liftIO $ newIORef False setContinuation ma (cont ref) fs r <- runTrans ma restoreStack fs return r where cont ref x = Transient $ do n <- liftIO $ readIORef ref if n == True then return $ Just x else do liftIO $ writeIORef ref True runTrans mb return $ Just x # INLINABLE setEventCont # setEventCont :: TransIO a -> (a -> TransIO b) -> StateIO () setEventCont x f = modify $ \EventF { fcomp = fs, .. } -> EventF { xcomp = x , fcomp = unsafeCoerce f : fs , .. } resetEventCont : : Maybe a - > EventF - > StateIO ( ) # INLINABLE resetEventCont # resetEventCont mx = modify $ \EventF { fcomp = fs, .. } -> EventF { xcomp = case mx of Nothing -> empty Just x -> unsafeCoerce (head fs) x , fcomp = tailsafe fs , .. } # INLINE tailsafe # tailsafe :: [a] -> [a] tailsafe [] = [] tailsafe (_:xs) = xs waitQSemB onemore sem = atomicModifyIORef sem $ \n -> let one = if onemore then 1 else 0 in if n + one > 0 then(n - 1, True) else (n, False) signalQSemB sem = atomicModifyIORef sem $ \n -> (n + 1, ()) set . When set to 0 , new tasks start synchronously in the current thread . threads :: Int -> TransIO a -> TransIO a threads n process = do msem <- gets maxThread sem <- liftIO $ newIORef n modify $ \s -> s { maxThread = Just sem } return r cloneInChild name= do st <- get rchs <- liftIO $ newMVar [] label <- liftIO $ newIORef (Alive, if not $ null name then BS.pack name else mempty) let st' = st { parent = Just st , children = rchs , labelth = label } liftIO $ do atomicModifyIORef (labelth st) $ \(_, label) -> ((Parent,label),()) parent could have more than one children with the same threadId return st' removeChild :: (MonadIO m,TransMonad m) => m () removeChild = do st <- get let mparent = parent st case mparent of Nothing -> return () Just parent -> do sts <- liftIO $ modifyMVar (children parent) $ \ths -> do let (xs,sts)= partition (\st' -> threadId st' /= threadId st) ths ys <- case sts of [] -> return [] st':_ -> readMVar $ children st' return (xs ++ ys,sts) put parent case sts of [] -> return() st':_ -> do (status,_) <- liftIO $ readIORef $ labelth st' if status == Listener || threadId parent == threadId st then return () else liftIO $ (killThread . threadId) st' oneThread :: TransIO a -> TransIO a oneThread comp = do st <- cloneInChild "oneThread" let rchs= children st x <- comp th <- liftIO myThreadId chs <- liftIO $ readMVar rchs liftIO $ mapM_ (killChildren1 th) chs return x where killChildren1 :: ThreadId -> EventF -> IO () killChildren1 th state = do forkIO $ do ths' <- modifyMVar (children state) $ \ths -> do let (inn, ths')= partition (\st -> threadId st == th) ths return (inn, ths') mapM_ (killChildren1 th) ths' mapM_ (killThread . threadId) ths' return() labelState :: (MonadIO m,TransMonad m) => BS.ByteString -> m () labelState l = do st <- get liftIO $ atomicModifyIORef (labelth st) $ \(status,prev) -> ((status, prev <> BS.pack "," <> l), ()) threadState thid= do st <- findState match =<< topState return $ threadId st :: TransIO ThreadId where match st= do (_,lab) <-liftIO $ readIORef $ labelth st return $ if lab == thid then True else False killState thid= do st <- findState match =<< topState liftIO $ killBranch' st where match st= do (_,lab) <-liftIO $ readIORef $ labelth st return $ if lab == thid then True else False printBlock :: MVar () printBlock = unsafePerformIO $ newMVar () showThreads :: MonadIO m => EventF -> m () showThreads st = liftIO $ withMVar printBlock $ const $ do mythread <- myThreadId putStrLn "---------Threads-----------" let showTree n ch = do liftIO $ do putStr $ take n $ repeat ' ' (state, label) <- readIORef $ labelth ch if BS.null label then putStr . show $ threadId ch else do BS.putStr label; putStr . drop 8 . show $ threadId ch putStrLn $ if mythread == threadId ch then " <--" else "" chs <- readMVar $ children ch mapM_ (showTree $ n + 2) $ reverse chs showTree 0 st topState : : TransIO EventF topState :: TransMonad m => m EventF topState = do st <- get return $ toplevel st where toplevel st = case parent st of Nothing -> st Just p -> toplevel p getStateFromThread th top = resp where resp = do let thstring = drop 9 . show $ threadId top if thstring = = th then getstate top else do sts < - liftIO $ readMVar $ children top foldl ( < | > ) empty $ map ( getStateFromThread th ) sts getstate st = case M.lookup ( typeOf $ typeResp resp ) $ mfData st of Just x - > return . Just $ unsafeCoerce x Nothing - > return Nothing typeResp : : m ( Maybe x ) - > x typeResp = undefined getStateFromThread th top = resp where resp = do let thstring = drop 9 . show $ threadId top if thstring == th then getstate top else do sts <- liftIO $ readMVar $ children top foldl (<|>) empty $ map (getStateFromThread th) sts getstate st = case M.lookup (typeOf $ typeResp resp) $ mfData st of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined -} | find the first computation state which match a filter in the subthree of states findState :: (MonadIO m, Alternative m) => (EventF -> m Bool) -> EventF -> m EventF findState filter top= do r <- filter top if r then return top else do sts <- liftIO $ readMVar $ children top foldl (<|>) empty $ map (findState filter) sts getStateFromThread :: (Typeable a, MonadIO m, Alternative m) => String -> EventF -> m (Maybe a) getStateFromThread th top= getstate =<< findState (matchth th) top where matchth th th'= do let thstring = drop 9 . show $ threadId th' return $ if thstring == th then True else False getstate st = resp where resp= case M.lookup (typeOf $ typeResp resp) $ mfData st of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined processStates :: Typeable a => (a-> TransIO ()) -> EventF -> TransIO() processStates display st = do getstate st >>= display liftIO $ print $ threadId st sts <- liftIO $ readMVar $ children st mapM_ (processStates display) sts where getstate st = case M.lookup (typeOf $ typeResp display) $ mfData st of Just x -> return $ unsafeCoerce x Nothing -> empty typeResp :: (a -> TransIO()) -> a typeResp = undefined addThreads' :: Int -> TransIO () addThreads' n= noTrans $ do msem <- gets maxThread case msem of Just sem -> liftIO $ modifyIORef sem $ \n' -> n + n' Nothing -> do sem <- liftIO (newIORef n) modify $ \ s -> s { maxThread = Just sem } addThreads :: Int -> TransIO () addThreads n = noTrans $ do msem <- gets maxThread case msem of Nothing -> return () Just sem -> liftIO $ modifyIORef sem $ \n' -> if n' > n then n' else n < - gets case of freeThreads :: TransIO a -> TransIO a freeThreads process = Transient $ do st <- get put st { freeTh = True } r <- runTrans process modify $ \s -> s { freeTh = freeTh st } return r hookedThreads :: TransIO a -> TransIO a hookedThreads process = Transient $ do st <- get put st {freeTh = False} r <- runTrans process modify $ \s -> s { freeTh = freeTh st } return r killChilds :: TransIO () killChilds = noTrans $ do cont <- get liftIO $ do killChildren $ children cont writeIORef (labelth cont) (Alive, mempty) return () killBranch :: TransIO () killBranch = noTrans $ do st <- get liftIO $ killBranch' st killBranch' :: EventF -> IO () killBranch' cont = do forkIO $ do killChildren $ children cont let thisth = threadId cont mparent = parent cont when (isJust mparent) $ modifyMVar_ (children $ fromJust mparent) $ \sts -> return $ filter (\st -> threadId st /= thisth) sts killThread $ thisth !> ("kill this thread:",thisth) return () getData :: (TransMonad m, Typeable a) => m (Maybe a) getData = resp where resp = do list <- gets mfData case M.lookup (typeOf $ typeResp resp) list of Just x -> return . Just $ unsafeCoerce x Nothing -> return Nothing typeResp :: m (Maybe x) -> x typeResp = undefined getSData :: Typeable a => TransIO a getSData = Transient getData getState :: Typeable a => TransIO a getState = getSData data type , and therefore only one item of a given type can be stored . A newtype wrapper can be used to distinguish two data items of the same type . import Control . Monad . IO.Class ( liftIO ) import Data . Typeable } deriving setData $ Person " " 55 setData :: (TransMonad m, Typeable a) => a -> m () setData x = modify $ \st -> st { mfData = M.insert t (unsafeCoerce x) (mfData st) } where t = typeOf x modifyData :: (TransMonad m, Typeable a) => (Maybe a -> Maybe a) -> m () modifyData f = modify $ \st -> st { mfData = M.alter alterf t (mfData st) } where typeResp :: (Maybe a -> b) -> a typeResp = undefined t = typeOf (typeResp f) alterf mx = unsafeCoerce $ f x' where x' = case mx of Just x -> Just $ unsafeCoerce x Nothing -> Nothing | Either modify according with the first parameter or insert according with the second , depending on if the data exist or not . It returns the modifyData' :: (TransMonad m, Typeable a) => (a -> a) -> a -> m a modifyData' f v= do st <- get let (ma,nmap)= M.insertLookupWithKey alterf t (unsafeCoerce v) (mfData st) put st { mfData =nmap} return $ if isNothing ma then v else unsafeCoerce $ fromJust ma where t = typeOf v alterf _ _ x = unsafeCoerce $ f $ unsafeCoerce x modifyState :: (TransMonad m, Typeable a) => (Maybe a -> Maybe a) -> m () modifyState = modifyData setState :: (TransMonad m, Typeable a) => a -> m () setState = setData delData :: (TransMonad m, Typeable a) => a -> m () delData x = modify $ \st -> st { mfData = M.delete (typeOf x) (mfData st) } delState :: (TransMonad m, Typeable a) => a -> m () delState = delData STRefs for the Transient monad newtype Ref a = Ref (IORef a) It return the associated IORef , so it can be updated in the IO monad newRState:: (MonadIO m,TransMonad m, Typeable a) => a -> m (IORef a) newRState x= do ref@(Ref rx) <- Ref <$> liftIO (newIORef x) setData ref return rx Initialized the first time it is set . setRState:: (MonadIO m,TransMonad m, Typeable a) => a -> m () setRState x= do Ref ref <- getData `onNothing` do ref <- Ref <$> liftIO (newIORef x) setData ref return ref liftIO $ atomicModifyIORef ref $ const (x,()) getRData :: (MonadIO m, TransMonad m, Typeable a) => m (Maybe a) getRData= do mref <- getData case mref of Just (Ref ref) -> Just <$> (liftIO $ readIORef ref) Nothing -> return Nothing getRState :: Typeable a => TransIO a getRState= Transient getRData delRState x= delState (undefined `asTypeOf` ref x) where ref :: a -> Ref a ref = undefined try :: TransIO a -> TransIO a try mx = do s <- get mx <|> (modify (const s) >> empty) sandbox :: TransIO a -> TransIO a sandbox mx = do sd <- gets mfData mx <*** modify (\s ->s { mfData = sd}) genGlobalId :: MonadIO m => m Int genGlobalId= liftIO $ atomicModifyIORef rglobalId $ \n -> (n +1,n) rglobalId= unsafePerformIO $ newIORef (0 :: Int) genId :: TransMonad m => m Int genId = do st <- get let n = mfSequence st put st { mfSequence = n + 1 } return n getPrevId :: TransMonad m => m Int getPrevId = gets mfSequence instance Read SomeException where readsPrec n str = [(SomeException $ ErrorCall s, r)] where [(s , r)] = readsPrec n str data StreamData a = ^ This is the last one deriving (Typeable, Show,Read) instance Functor StreamData where fmap f (SMore a)= SMore (f a) fmap f (SLast a)= SLast (f a) fmap _ SDone= SDone waitEvents :: IO a -> TransIO a waitEvents io = do mr <- parallel (SMore <$> io) case mr of SMore x -> return x SError e -> back e async :: IO a -> TransIO a async io = do mr <- parallel (SLast <$> io) case mr of SLast x -> return x SError e -> back e sync :: TransIO a -> TransIO a sync x = do modify $ \s -> s{execMode= was} return r | create task threads faster , but with no thread control : = freeThreads . spawn :: IO a -> TransIO a spawn = freeThreads . waitEvents sample :: Eq a => IO a -> Int -> TransIO a sample action interval = do v <- liftIO action prev <- liftIO $ newIORef v waitEvents (loop action prev) <|> return v where loop action prev = loop' where loop' = do threadDelay interval v <- action v' <- readIORef prev if v /= v' then writeIORef prev v >> return v else loop' abduce = async $ return () fork :: TransIO () -> TransIO () fork proc= (abduce >> proc >> empty) <|> return() | Run an IO action one or more times to generate a stream of tasks . The IO action returns a ' StreamData ' . When it returns an ' SMore ' or ' SLast ' a new computation is executed in a new thread . If the return value is ' SMore ' , the parallel :: IO (StreamData b) -> TransIO (StreamData b) parallel ioaction = Transient $ do modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} cont <- get ! > " PARALLEL " case event cont of j@(Just _) -> do put cont { event = Nothing } return $ unsafeCoerce j Nothing -> do liftIO $ atomicModifyIORef (labelth cont) $ \(_, lab) -> ((Parent, lab), ()) liftIO $ loop cont ioaction return Nothing | Execute the IO action and the continuation loop :: EventF -> IO (StreamData t) -> IO () loop parentc rec = forkMaybe True parentc $ \cont -> do Execute the IO computation and then the closure - continuation liftIO $ atomicModifyIORef (labelth cont) $ \(_,label) -> ((Listener,label),()) let loop'= do mdat <- rec `catch` \(e :: SomeException) -> return $ SError e case mdat of se@(SError _) -> setworker cont >> iocont se cont SDone -> setworker cont >> iocont SDone cont last@(SLast _) -> setworker cont >> iocont last cont more@(SMore _) -> do forkMaybe False cont $ iocont more loop' where setworker cont= liftIO $ atomicModifyIORef (labelth cont) $ \(_,lab) -> ((Alive,lab),()) iocont dat cont = do let cont'= cont{event= Just $ unsafeCoerce dat} runStateT (runCont cont') cont' return () loop' return () where # INLINABLE forkMaybe # forkMaybe :: Bool -> EventF -> (EventF -> IO ()) -> IO () forkMaybe onemore parent proc = do case maxThread parent of Nothing -> forkIt parent proc Just sem -> do dofork <- waitQSemB onemore sem if dofork then forkIt parent proc else proc parent `catch` \e ->exceptBack parent e >> return() forkIt parent proc= do chs <- liftIO $ newMVar [] label <- newIORef (Alive, BS.pack "work") let cont = parent{parent=Just parent,children= chs, labelth= label} forkFinally1 (do th <- myThreadId let cont'= cont{threadId=th} when(not $ freeTh parent )$ hangThread parent cont' proc cont') $ \me -> do case me of ! > " exceptBack 2 " _ -> return () case maxThread cont of Nothing -> return () th <- myThreadId (can,label) <- atomicModifyIORef (labelth cont) $ \(l@(status,label)) -> ((if status== Alive then Dead else status, label),l) when (can /= Parent ) $ free th parent return () forkFinally1 :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally1 action and_then = mask $ \restore -> forkIO $ Control.Exception.try (restore action) >>= and_then free th env= do let sibling= children env (sbs',found) <- modifyMVar sibling $ \sbs -> do let (sbs', found) = drop [] th sbs return (sbs',(sbs',found)) if found then do (typ,_) <- readIORef $ labelth env if (null sbs' && typ /= Listener && isJust (parent env)) then free (threadId env) ( fromJust $ parent env) else return () where drop processed th []= (processed,False) drop processed th (ev:evts)| th == threadId ev= (processed ++ evts, True) | otherwise= drop (ev:processed) th evts hangThread parentProc child = do let headpths= children parentProc modifyMVar_ headpths $ \ths -> return (child:ths) killChildren childs = do forkIO $ do ths <- modifyMVar childs $ \ths -> return ([],ths) mapM_ (killChildren . children) ths mapM_ (\th -> do (status,_) <- readIORef $ labelth th when (status /= Listener && status /= Parent) $ killThread $ threadId th !> ("killChildren",threadId th, status)) ths >> return () return () The first parameter is a callback setter . The second parameter is a value to be can just be @return ( ) @. The callback setter expects a function taking the @eventdata@ as an argument and returning a value ; this react :: ((eventdata -> IO response) -> IO ()) -> IO response -> TransIO eventdata react setHandler iob= do st <- cloneInChild "react" liftIO $ atomicModifyIORef (labelth st) $ \(_,label) -> ((Listener,label),()) Transient $ do modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} cont <- get case event cont of Nothing -> do liftIO $ setHandler $ \dat ->do runStateT (runCont cont) st{event= Just $ unsafeCoerce dat} `catch` exceptBack cont iob return Nothing j@(Just _) -> do put cont{event=Nothing} return $ unsafeCoerce j | listen stdin and triggers a new task every time the input data matches the first parameter . The value contained by the task is the matched value i.e. the first argument itself . The second parameter is a message for option :: (Typeable b, Show b, Read b, Eq b) => b -> String -> TransIO b option = optionf False Implements the same functionality than ` option ` but only wait for one input option1 :: (Typeable b, Show b, Read b, Eq b) => b -> String -> TransIO b option1= optionf True optionf :: (Typeable b, Show b, Read b, Eq b) => Bool -> b -> String -> TransIO b optionf flag ret message = do let sret= if typeOf ret == typeOf "" then unsafeCoerce ret else show ret let msg= "Enter "++sret++"\t\tto: " ++ message++"\n" inputf flag sret msg Nothing ( == sret) liftIO $ putStr "\noption: " >> putStrLn sret return ret inputf < remove input listener after sucessful or not > < listener identifier > < prompt > inputf :: (Show a, Read a,Typeable a) => Bool -> String -> String -> Maybe a -> (a -> Bool) -> TransIO a inputf remove ident message mv cond = do let loop= do liftIO $ putStr message >> hFlush stdout str <- react (addConsoleAction ident message) (return ()) when remove $ do removeChild; liftIO $ delConsoleAction ident c <- liftIO $ readIORef rconsumed if c then returnm mv else do let rr = read1 str case (rr,str) of (Nothing,_) -> do (liftIO $ when (isJust mv) $ putStrLn ""); returnm mv (Just x,"") -> do (liftIO $ do writeIORef rconsumed True; print x); returnm mv (Just x,_) -> if cond x then liftIO $ do writeIORef rconsumed True print x return x else do liftIO $ when (isJust mv) $ putStrLn "" returnm mv loop where returnm (Just x)= return x returnm _ = empty : : String - > Maybe a read1 s= r where typ= typeOf $ fromJust r r = if typ == typeOf "" then Just $ unsafeCoerce s else if typ == typeOf (BS.pack "") then Just $ unsafeCoerce $ BS.pack s else if typ == typeOf (BSL.pack "") then Just $ unsafeCoerce $ BSL.pack s else case reads s of [] -> Nothing [(x,"")] -> Just x | Waits on stdin and return a value when a console input matches the predicate specified in the first argument . The second parameter is a string input :: (Typeable a, Read a,Show a) => (a -> Bool) -> String -> TransIO a input= input' Nothing input' :: (Typeable a, Read a,Show a) => Maybe a -> (a -> Bool) -> String -> TransIO a input' mv cond prompt= do inputf True "input" prompt mv cond rcb= unsafePerformIO $ newIORef [] :: IORef [ (String,String,String -> IO())] addConsoleAction :: String -> String -> (String -> IO ()) -> IO () addConsoleAction name message cb= atomicModifyIORef rcb $ \cbs -> ((name,message, cb) : filter ((/=) name . fst) cbs ,()) where fst (x,_,_)= x delConsoleAction :: String -> IO () delConsoleAction name= atomicModifyIORef rcb $ \cbs -> (filter ((/=) name . fst) cbs,()) where fst (x,_,_)= x reads1 s=x where x= if typeOf(typeOfr x) == typeOf "" then unsafeCoerce[(s,"")] else readsPrec' 0 s typeOfr :: [(a,String)] -> a typeOfr = undefined read1 s= let [(x,"")]= reads1 s in x rprompt= unsafePerformIO $ newIORef "> " inputLoop= do prompt <- readIORef rprompt when (not $ null prompt) $ do putStr prompt ; hFlush stdout line <- getLine threadDelay 1000000 processLine line inputLoop myThreadId > > = # NOINLINE rconsumed # rconsumed = unsafePerformIO $ newIORef False # NOINLINE lineprocessmode # lineprocessmode= unsafePerformIO $ newIORef False processLine r = do linepro <- readIORef lineprocessmode if linepro then do mapM' invokeParsers [r] else do let rs = breakSlash [] r mapM' invokeParsers rs where invokeParsers x= do mbs <- readIORef rcb mapM_ (\cb -> cb x) $ map (\(_,_,p)-> p) mbs mapM' _ []= return () mapM' f (xss@(x:xs)) =do f x r <- readIORef rconsumed if r then do writeIORef riterloop 0 writeIORef rconsumed False mapM' f xs else do threadDelay 1000 n <- atomicModifyIORef riterloop $ \n -> (n+1,n) if n==1 then do when (not $ null x) $ hPutStr stderr x >> hPutStrLn stderr ": can't read, skip" writeIORef riterloop 0 writeIORef rconsumed False mapM' f xs else mapM' f xss riterloop= unsafePerformIO $ newIORef 0 breakSlash :: [String] -> String -> [String] breakSlash [] ""= [""] breakSlash s ""= s breakSlash res ('\"':s)= let (r,rest) = span(/= '\"') s in breakSlash (res++[r]) $ tail1 rest breakSlash res s= let (r,rest) = span(\x -> (not $ elem x "/,:") && x /= ' ') s in breakSlash (res++[r]) $ tail1 rest tail1 []= [] tail1 x= tail x > > > [ ] " test.hs/0/\"-prof -auto\ " " stay rexit= takeMVar rexit `catch` \(e :: BlockedIndefinitelyOnMVar) -> return Nothing newtype Exit a= Exit a deriving Typeable A built - in interactive command handler also reads the stdin asynchronously . 1 . @ps@ : show threads 2 . : inspect the log of a thread 3 . @end@ , @exit@ : terminate the program > foo -p ps / end keep :: Typeable a => TransIO a -> IO (Maybe a) keep mx = do liftIO $ hSetBuffering stdout LineBuffering rexit <- newEmptyMVar void $ forkIO $ do let logFile= "trans.log" void $ runTransient $ do liftIO $ removeFile logFile `catch` \(e :: IOError) -> return () onException $ \(e :: SomeException) -> do liftIO $ print e empty onException $ \(e :: IOException) -> do when (ioeGetErrorString e == "resource busy") $ do liftIO $ do print e ; putStrLn "EXITING!!!"; putMVar rexit Nothing empty st <- get setData $ Exit rexit do option "options" "show all options" mbs <- liftIO $ readIORef rcb liftIO $ mapM_ (\c ->do putStr c; putStr "|") $ map (\(fst,_,_) -> fst)mbs d <- input' (Just "n") (\x -> x=="y" || x =="n" || x=="Y" || x=="N") "\nDetails? N/y " when (d == "y") $ do putStr x ; putStr " \t\t " ; in liftIO $ mapM_ line mbs liftIO $ putStrLn "" empty <|> do option "ps" "show threads" liftIO $ showThreads st empty <|> do option "errs" "show exceptions log" c <- liftIO $ readFile logFile `catch` \(e:: IOError) -> return "" liftIO . putStrLn $ if null c then "no errors logged" else c empty <|> do option "end" "exit" liftIO $ putStrLn "exiting..." abduce killChilds liftIO $ putMVar rexit Nothing empty <|> mx #ifndef ghcjs_HOST_OS <|> do abduce liftIO $ execCommandLine labelState (fromString "input") liftIO inputLoop empty #endif return () stay rexit where type1 :: TransIO a -> Either String (Maybe a) type1= undefined keep' :: Typeable a => TransIO a -> IO (Maybe a) keep' mx = do liftIO $ hSetBuffering stdout LineBuffering rexit <- newEmptyMVar void $ forkIO $ do void $ runTransient $ do onException $ \(e :: SomeException ) -> do top <- topState liftIO $ do th <- myThreadId putStr $ show th putStr ": " print e putStrLn "Threads:" showThreads top empty onException $ \(e :: IOException) -> do when (ioeGetErrorString e == "resource busy") $ do liftIO $ do print e ; putStrLn "EXITING!!!"; putMVar rexit Nothing liftIO $ putMVar rexit Nothing empty setData $ Exit rexit mx return () threadDelay 10000 forkIO $ execCommandLine stay rexit execCommandLine= do args <- getArgs let mindex = findIndex (\o -> o == "-p" || o == "--path" ) args when (isJust mindex) $ do let i= fromJust mindex +1 when (length args >= i) $ do let path= args !! i processLine path exit :: Typeable a => a -> TransIO a exit x= do Exit rexit <- getSData <|> error "exit: not the type expected" `asTypeOf` type1 x liftIO $ putMVar rexit $ Just x stop where type1 :: a -> TransIO (Exit (MVar (Maybe a))) type1= undefined | If the first parameter is ' Nothing ' return the second parameter otherwise return the first parameter .. onNothing :: Monad m => m (Maybe b) -> m b -> m b onNothing iox iox'= do mx <- iox case mx of Just x -> return x Nothing -> iox' data Backtrack b= Show b =>Backtrack{backtracking :: Maybe b ,backStack :: [EventF] } deriving Typeable backCut :: (Typeable b, Show b) => b -> TransientIO () backCut reason= Transient $ do delData $ Backtrack (Just reason) [] return $ Just () undoCut :: TransientIO () undoCut = backCut () | Run the action in the first parameter and register the second parameter as the undo action . On undo ( ' back ' ) the second parameter is called with the # NOINLINE onBack # onBack :: (Typeable b, Show b) => TransientIO a -> ( b -> TransientIO a) -> TransientIO a onBack ac bac = registerBack (typeof bac) $ Transient $ do tr "onBack" Backtrack mreason stack <- getData `onNothing` (return $ backStateOf (typeof bac)) runTrans $ case mreason of ! > " ONBACK NOTHING " ! > ( " ONBACK JUST",reason ) where typeof :: (b -> TransIO a) -> b typeof = undefined onUndo :: TransientIO a -> TransientIO a -> TransientIO a onUndo x y= onBack x (\() -> y) | Register an undo action to be executed when backtracking . The first # NOINLINE registerUndo # registerBack :: (Typeable b, Show b) => b -> TransientIO a -> TransientIO a registerBack witness f = Transient $ do tr "registerBack" cont@(EventF _ x _ _ _ _ _ _ _ _ _ _ _) <- get md <- getData `asTypeOf` (Just <$> return (backStateOf witness)) case md of Just (Backtrack b []) -> setData $ Backtrack b [cont] Just (bss@(Backtrack b (bs@((EventF _ x' _ _ _ _ _ _ _ _ _ _ _):_)))) -> when (isNothing b) $ setData $ Backtrack b (cont:bs) Nothing -> setData $ Backtrack mwit [cont] runTrans $ return () >> f where mwit= Nothing `asTypeOf` (Just witness) registerUndo :: TransientIO a -> TransientIO a registerUndo f= registerBack () f forward :: (Typeable b, Show b) => b -> TransIO () forward reason= noTrans $ do Backtrack _ stack <- getData `onNothing` ( return $ backStateOf reason) setData $ Backtrack(Nothing `asTypeOf` Just reason) stack backtrack :: TransIO a backtrack= return $ error "backtrack should be called at the end of an exception handler with no `forward`, `continue` or `retry` on it" | ' forward ' for the default undo track ; equivalent to @forward ( ) @. retry= forward () noFinish= continue back :: (Typeable b, Show b) => b -> TransIO a back reason = do tr "back" bs <- getData `onNothing` return (backStateOf reason) ! > " GOBACK " where runClosure :: EventF -> TransIO a runClosure EventF { xcomp = x } = unsafeCoerce x runContinuation :: EventF -> a -> TransIO b runContinuation EventF { fcomp = fs } = (unsafeCoerce $ compose fs) goBackt (Backtrack _ [] )= empty goBackt (Backtrack b (stack@(first : bs)) )= do x <- runClosure first !> ("RUNCLOSURE",length stack) Backtrack back bs' <- getData `onNothing` return (backStateOf reason) case back of Nothing -> do setData $ Backtrack (Just reason) stack st <- get runContinuation first x `catcht` (\e -> liftIO(exceptBack st e) >> empty) !> "FORWARD EXEC" justreason -> do setData $ Backtrack justreason bs goBackt $ Backtrack justreason bs !> ("BACK AGAIN",back) empty backStateOf :: (Show a, Typeable a) => a -> Backtrack a backStateOf reason= Backtrack (Nothing `asTypeOf` (Just reason)) [] data BackPoint a = BackPoint (IORef [a -> TransIO()]) backPoint :: (Typeable reason,Show reason) => TransIO (BackPoint reason) backPoint = do point <- liftIO $ newIORef [] return () `onBack` (\e -> do rs <- liftIO $ readIORef point mapM_ (\r -> r e) rs) return $ BackPoint point onBackPoint :: MonadIO m => BackPoint t -> (t -> TransIO ()) -> m () onBackPoint (BackPoint ref) handler= liftIO $ atomicModifyIORef ref $ \rs -> (handler:rs,()) undo :: TransIO a undo= back () newtype Finish= Finish String deriving Show instance Exception Finish newtype FinishReason= FinishReason ( Maybe SomeException ) deriving ( Typeable , Show ) onFinish :: (Finish ->TransIO ()) -> TransIO () onFinish f= onException' (return ()) f | Run the action specified in the first parameter and register the second onFinish' ::TransIO a ->(Finish ->TransIO a) -> TransIO a onFinish' proc f= proc `onException'` f ' initFinish ' , in reverse order and continue the execution . Either an exception or ' Nothing ' can be initFinish = cutExceptions finish :: String -> TransIO () finish reason= (throwt $ Finish reason) <|> return() checkFinalize v= case v of SDone -> stop SLast x -> return x SError e -> throwt e SMore x -> return x | Install an exception handler . Handlers are executed in reverse ( i.e. last in , first out ) order when such exception happens in the The semantic is , thus , very different than the one of ` Control . Exception . Base.onException ` onException :: Exception e => (e -> TransIO ()) -> TransIO () onException exc= return () `onException'` exc | set an exception point . is a point in the backtracking in which exception handlers can be inserted with ` onExceptionPoint ` exceptionPoint :: Exception e => TransIO (BackPoint e) exceptionPoint = do point <- liftIO $ newIORef [] return () `onException'` (\e -> do rs<- liftIO $ readIORef point mapM_ (\r -> r e) rs) return $ BackPoint point onExceptionPoint :: Exception e => BackPoint e -> (e -> TransIO()) -> TransIO () onExceptionPoint= onBackPoint onException' :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a onException' mx f= onAnyException mx $ \e -> do case fromException e of Nothing -> do Backtrack r stack <- getData `onNothing` return (backStateOf e) setData $ Backtrack r $ tail stack back e empty Just e' -> f e' where onAnyException :: TransIO a -> (SomeException ->TransIO a) -> TransIO a onAnyException mx exc= ioexp `onBack` exc ioexp = Transient $ do st <- get (mr,st') <- liftIO $ (runStateT (do case event st of Nothing -> do r <- runTrans mx modify $ \s -> s{event= Just $ unsafeCoerce r} runCont st modify $ \s -> s{execMode=let rs= execMode s in if rs /= Remote then Parallel else rs} return Nothing Just r -> do modify $ \s -> s{event=Nothing} return $ unsafeCoerce r) st) `catch` exceptBack st put st' return mr exceptBack st = \(e ::SomeException) -> do tr "catched" ! > " EXCEPTBACK " re execute the first argument as long as the exception is produced within the argument . The second argument is executed before every re - execution if the second argument executes ` empty ` the execution is aborted . whileException :: Exception e => TransIO b -> (e -> TransIO()) -> TransIO b whileException mx fixexc = mx `catcht` \e -> do fixexc e; whileException mx fixexc cutExceptions :: TransIO () cutExceptions= backCut (undefined :: SomeException) continue :: TransIO () catcht :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b catcht mx exc= do st <- get (mx,st') <- liftIO $ runStateT ( runTrans $ mx ) st `catch` \e -> runStateT ( runTrans $ exc e ) st put st' case mx of Just x -> return x Nothing -> empty catcht' :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b catcht' mx exc= do rpassed <- liftIO $ newIORef False sandbox $ do r <- onException' mx (\e -> do passed <- liftIO $ readIORef rpassed return () !> ("CATCHT passed", passed) if not passed then continue >> exc e else do Backtrack r stack <- getData `onNothing` return (backStateOf e) setData $ Backtrack r $ tail stack back e return () !> "AFTER BACK" empty ) liftIO $ writeIORef rpassed True return r where sandbox mx= do exState <- getState <|> return (backStateOf (undefined :: SomeException)) mx <*** do setState exState > onException $ \(e : : SomeException ) - > do > throw $ ErrorCall " asdasd " throwt :: Exception e => e -> TransIO a throwt = back . toException
6d6ae15947229f737200eab95dc0c781c2be7b28f61b7fa3b531613942a95f34
haskell/haskell-language-server
NoExplicitExportCommentAtTop.hs
module Test where -- | a comment class Semigroup a => SomeData a instance SomeData All
null
https://raw.githubusercontent.com/haskell/haskell-language-server/fdbc555a9245cb3761c2bf7335f3d18b8cf7673c/plugins/hls-refactor-plugin/test/data/import-placement/NoExplicitExportCommentAtTop.hs
haskell
| a comment
module Test where class Semigroup a => SomeData a instance SomeData All
4da5ee08cd45aee2fb2782eb1f884c77ced60d4d0ba58a2a3b3ee79846af5338
Bogdanp/racket-lua
lexer.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse) racket/match racket/port racket/string) (provide (struct-out exn:fail:lexer) (struct-out token) make-lexer lexer-peek lexer-take) (struct exn:fail:lexer exn:fail (line col pos) #:transparent) (define (raise-lexer-error message line col pos) (raise (exn:fail:lexer message (current-continuation-marks) line col pos))) (struct token (type str val line col pos) #:prefab) (struct lexer (in skip-comments? partial-strings? [pending #:mutable]) #:transparent) (define (make-lexer in #:skip-comments? [skip-comments? #t] #:partial-strings? [partial-strings? #f]) (lexer in skip-comments? partial-strings? #f)) (define (lexer-peek l) (cond [(lexer-pending l) => values] [else (define pending (lexer-read-token l)) (begin0 pending (set-lexer-pending! l pending))])) (define (lexer-take l) (cond [(lexer-pending l) => (lambda (pending) (begin0 pending (set-lexer-pending! l #f)))] [else (lexer-read-token l)])) (define (lexer-read-token l) (define skip-comments? (lexer-skip-comments? l)) (define partial-strings? (lexer-partial-strings? l)) (let loop () (define t (read-token (lexer-in l) partial-strings?)) (case (token-type t) [(comment whitespace) (if skip-comments? (loop) t)] [else t]))) ;; readers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (read-token in [partial-strings? #f]) (define-values (line col pos) (port-next-location in)) (define (make-token type [str (read-string 1 in)] [val str]) (token type str val line col pos)) (match (peek-char in) [(? eof-object?) (make-token 'eof eof)] [(? whitespace?) (make-token 'whitespace (read-whitespace in))] [#\- #:when (equal? "--" (peek-string 2 0 in)) (case (peek-string 4 0 in) [("--[[" "--[=") (define-values (str _) (lua:read-long-brackets in #t partial-strings?)) (make-token 'comment str)] [else (make-token 'comment (read-line in))])] [#\[ #:when (member (peek-string 2 0 in) '("[[" "[=")) (define-values (s v) (lua:read-long-brackets in #f partial-strings?)) (make-token 'string s v)] [#\: #:when (equal? "::" (peek-string 2 0 in)) (make-token 'coloncolon (read-string 2 in))] [#\: (make-token 'colon)] [#\; (make-token 'semicolon)] [#\( (make-token 'lparen)] [#\) (make-token 'rparen)] [#\[ (make-token 'lsqbrace)] [#\] (make-token 'rsqbrace)] [#\{ (make-token 'lcubrace)] [#\} (make-token 'rcubrace)] [#\, (make-token 'comma)] [#\. #:when (equal? "..." (peek-string 3 0 in)) (make-token 'dotdotdot (read-string 3 in) '...)] [#\. #:when (equal? ".." (peek-string 2 0 in)) (make-token 'op (read-string 2 in) '..)] [#\. #:when (not (decimal-digit? (peek-char in 1))) (make-token 'dot (read-string 1 in) '\.)] [(or #\' #\") (define-values (s v) (lua:read-string in partial-strings?)) (make-token 'string s v)] [(? number-start?) (define-values (s v) (lua:read-number in)) (make-token 'number s v)] [(? op-start?) (define-values (s v) (lua:read-op in)) (make-token 'op s v)] [(? name-start?) (define-values (s v) (lua:read-name in)) (case v [(and or not) (make-token 'op s v)] [(break do else elseif end false for function goto if in local nil repeat return then true until while) (make-token 'keyword s v)] [else (make-token 'name s v)])] [c (raise-lexer-error (format "unexpected character: ~a" c) line col pos)])) ;; helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (read-whitespace in) (read-string-while in whitespace?)) (define (read-string-while in p) (call-with-output-string (lambda (out) (read-while in p (λ (c) (write-char c out)))))) (define (read-while in p proc) (define-values (line col pos) (port-next-location in)) (with-handlers ([exn:fail? (λ (e) (raise-lexer-error (exn-message e) line col pos))]) (let loop ([c (peek-char in)] [p p]) (define next-p (p c)) (when next-p (proc (read-char in)) (loop (peek-char in) next-p))))) ;; matchers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-syntax (λcase stx) (syntax-parse stx #:literals (else) [(_ {~optional {~seq #:char-id char-id}} [(lit ...) e ...] ... {~optional [else else-e ...]}) #:with c #'{~? char-id next-c} #'(λ (c) (case c [(lit ...) e ...] ... {~? [else else-e ...] [else #f]}))])) (define-syntax (define-λcase stx) (syntax-parse stx [(_ name:id . rest) #'(define name (λcase . rest))])) (define (stop _) #f) (define-λcase whitespace? [(#\u00A0 #\space #\tab #\newline #\return) whitespace?]) (define-λcase op-start? [(#\+ #\- #\* #\^ #\% #\& #\| #\#) stop] [(#\/) (λcase [(#\/) stop])] [(#\<) (λcase [(#\< #\=) stop])] [(#\>) (λcase [(#\> #\=) stop])] [(#\=) (λcase [(#\=) stop])] [(#\~) (λcase [(#\=) stop])]) (define ((make-name-predicate [char-categories '(ll lu nd)]) c) (and (char? c) (or (char=? c #\_) (memq (char-general-category c) char-categories)) name-more?)) (define name-start? (make-name-predicate '(ll lu))) (define name-more? (make-name-predicate '(ll lu nd))) (define-λcase number-start? [(#\.) (number-more? #\.)] [(#\0) (λcase [(#\x #\X) (λ (c) (or (hex-digit? c) (error "expected a hex digit")))] [(#\.) decimal-digit-or-exponent?]) ] [(#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) number-more?]) (define-λcase number-more? #:char-id c [(#\e #\E) decimal-digit-or-sign?] [(#\.) (λ (next-c) (or (decimal-digit-or-exponent? next-c) (error "expected a digit")))] [else (and (decimal-digit? c) number-more?)]) (define-λcase decimal-digit-or-sign? #:char-id c [(#\+ #\-) decimal-digit?] [else (and (decimal-digit? c) decimal-digit?)]) (define-λcase decimal-digit-or-exponent? #:char-id c [(#\e #\E) decimal-digit-or-sign?] [else (and (decimal-digit? c) decimal-digit-or-exponent?)]) (define-λcase decimal-digit? [(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) decimal-digit?]) (define-λcase hex-digit? #:char-id c [(#\a #\b #\c #\d #\e #\f) hex-digit?] [(#\A #\B #\C #\D #\E #\F) hex-digit?] [else (and (decimal-digit? c) hex-digit?)]) (define-λcase long-brackets-more? [(#\[) stop] [(#\=) long-brackets-more?] [else (error "expected [ or =")]) (define-λcase long-brackets-start? [(#\[) long-brackets-more?] [else (error "expected [")]) (define-λcase long-brackets-comment-next? [(#\-) (λ (next-c) (or (long-brackets-start? next-c) (error "expected [")))] [else (error "expected -")]) (define-λcase long-brackets-comment-start? [(#\-) long-brackets-comment-next?] [else (error "expected -")]) ;; readers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define ((make-reader p f) in) (define s (read-string-while in p)) (values s (f s))) (define lua:read-name (make-reader name-start? string->symbol)) (define lua:read-op (make-reader op-start? string->symbol)) (define lua:read-number (make-reader number-start? (λ (s) (if (regexp-match? #rx"^0[xX]" s) (string->number (string-append "#x" (substring s 2)) 16) (string->number s))))) (define (lua:read-string in [partial? #f]) (define quote-char (read-char in)) (define lit-str (open-output-string)) (define actual-bs (open-output-bytes)) (write-char quote-char lit-str) (write-char quote-char actual-bs) (define has-end-quote? (let loop ([escaped? #f]) (define char (read-char in)) (cond [(eof-object? char) (cond [partial? #f] [else (error 'lua:read-string "unexpected EOF while reading string")])] [escaped? (define-values (escape-seq escape-char) (lua:string-escape char)) (write-string escape-seq lit-str) (write-char escape-char actual-bs) (loop #f)] [(eqv? char #\\) (loop #t)] [else (write-char char lit-str) (write-char char actual-bs) (cond [(eqv? char quote-char) #t] [else (loop #f)])]))) (define bs (let ([bs (get-output-bytes actual-bs)]) (subbytes bs 1 ((if has-end-quote? sub1 values) (bytes-length bs))))) (values (get-output-string lit-str) bs)) (define (lua:string-escape chr) (case chr [(#\\) (values "\\\\" #\\)] [(#\a) (values "\\a" #\u007)] [(#\b) (values "\\b" #\backspace)] [(#\f) (values "\\f" #\page)] [(#\r) (values "\\r" #\return)] [(#\n) (values "\\n" #\newline)] [(#\t) (values "\\t" #\tab)] [(#\v) (values "\\v" #\vtab)] [(#\[) (values "\\[" #\[)] [(#\]) (values "\\[" #\])] [else (values (string #\\ chr) chr)])) (define (lua:read-long-brackets in [comment? #f] [partial? #f]) (define open-brackets (read-string-while in (if comment? long-brackets-comment-start? long-brackets-start?))) (define close-brackets (string-replace open-brackets "[" "]")) (define close-brackets-re (regexp (regexp-quote close-brackets))) (define-values (str-no-open close-brackets-len) (match (regexp-match-peek-positions close-brackets-re in) [#f #:when partial? (values (port->string in) 0)] [#f (error (format "no matching '~a' for '~a'" close-brackets open-brackets))] [`((,_ . ,end-pos)) (values (read-string end-pos in) (string-length open-brackets))])) (define content-bs (let ([trimmed-str (cond [(regexp-match? #rx"^\r\n" str-no-open) (substring str-no-open 2)] [(regexp-match? #rx"^\n" str-no-open) (substring str-no-open 1)] [else str-no-open])]) (string->bytes/utf-8 (substring trimmed-str 0 (- (string-length trimmed-str) close-brackets-len))))) (values (string-append open-brackets str-no-open) content-bs))
null
https://raw.githubusercontent.com/Bogdanp/racket-lua/e92528c03a66a42adcc7cfede2d4216cf7a581e6/lua-lib/lang/lexer.rkt
racket
readers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (make-token 'semicolon)] helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; matchers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; readers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket/base (require (for-syntax racket/base syntax/parse) racket/match racket/port racket/string) (provide (struct-out exn:fail:lexer) (struct-out token) make-lexer lexer-peek lexer-take) (struct exn:fail:lexer exn:fail (line col pos) #:transparent) (define (raise-lexer-error message line col pos) (raise (exn:fail:lexer message (current-continuation-marks) line col pos))) (struct token (type str val line col pos) #:prefab) (struct lexer (in skip-comments? partial-strings? [pending #:mutable]) #:transparent) (define (make-lexer in #:skip-comments? [skip-comments? #t] #:partial-strings? [partial-strings? #f]) (lexer in skip-comments? partial-strings? #f)) (define (lexer-peek l) (cond [(lexer-pending l) => values] [else (define pending (lexer-read-token l)) (begin0 pending (set-lexer-pending! l pending))])) (define (lexer-take l) (cond [(lexer-pending l) => (lambda (pending) (begin0 pending (set-lexer-pending! l #f)))] [else (lexer-read-token l)])) (define (lexer-read-token l) (define skip-comments? (lexer-skip-comments? l)) (define partial-strings? (lexer-partial-strings? l)) (let loop () (define t (read-token (lexer-in l) partial-strings?)) (case (token-type t) [(comment whitespace) (if skip-comments? (loop) t)] [else t]))) (define (read-token in [partial-strings? #f]) (define-values (line col pos) (port-next-location in)) (define (make-token type [str (read-string 1 in)] [val str]) (token type str val line col pos)) (match (peek-char in) [(? eof-object?) (make-token 'eof eof)] [(? whitespace?) (make-token 'whitespace (read-whitespace in))] [#\- #:when (equal? "--" (peek-string 2 0 in)) (case (peek-string 4 0 in) [("--[[" "--[=") (define-values (str _) (lua:read-long-brackets in #t partial-strings?)) (make-token 'comment str)] [else (make-token 'comment (read-line in))])] [#\[ #:when (member (peek-string 2 0 in) '("[[" "[=")) (define-values (s v) (lua:read-long-brackets in #f partial-strings?)) (make-token 'string s v)] [#\: #:when (equal? "::" (peek-string 2 0 in)) (make-token 'coloncolon (read-string 2 in))] [#\: (make-token 'colon)] [#\( (make-token 'lparen)] [#\) (make-token 'rparen)] [#\[ (make-token 'lsqbrace)] [#\] (make-token 'rsqbrace)] [#\{ (make-token 'lcubrace)] [#\} (make-token 'rcubrace)] [#\, (make-token 'comma)] [#\. #:when (equal? "..." (peek-string 3 0 in)) (make-token 'dotdotdot (read-string 3 in) '...)] [#\. #:when (equal? ".." (peek-string 2 0 in)) (make-token 'op (read-string 2 in) '..)] [#\. #:when (not (decimal-digit? (peek-char in 1))) (make-token 'dot (read-string 1 in) '\.)] [(or #\' #\") (define-values (s v) (lua:read-string in partial-strings?)) (make-token 'string s v)] [(? number-start?) (define-values (s v) (lua:read-number in)) (make-token 'number s v)] [(? op-start?) (define-values (s v) (lua:read-op in)) (make-token 'op s v)] [(? name-start?) (define-values (s v) (lua:read-name in)) (case v [(and or not) (make-token 'op s v)] [(break do else elseif end false for function goto if in local nil repeat return then true until while) (make-token 'keyword s v)] [else (make-token 'name s v)])] [c (raise-lexer-error (format "unexpected character: ~a" c) line col pos)])) (define (read-whitespace in) (read-string-while in whitespace?)) (define (read-string-while in p) (call-with-output-string (lambda (out) (read-while in p (λ (c) (write-char c out)))))) (define (read-while in p proc) (define-values (line col pos) (port-next-location in)) (with-handlers ([exn:fail? (λ (e) (raise-lexer-error (exn-message e) line col pos))]) (let loop ([c (peek-char in)] [p p]) (define next-p (p c)) (when next-p (proc (read-char in)) (loop (peek-char in) next-p))))) (define-syntax (λcase stx) (syntax-parse stx #:literals (else) [(_ {~optional {~seq #:char-id char-id}} [(lit ...) e ...] ... {~optional [else else-e ...]}) #:with c #'{~? char-id next-c} #'(λ (c) (case c [(lit ...) e ...] ... {~? [else else-e ...] [else #f]}))])) (define-syntax (define-λcase stx) (syntax-parse stx [(_ name:id . rest) #'(define name (λcase . rest))])) (define (stop _) #f) (define-λcase whitespace? [(#\u00A0 #\space #\tab #\newline #\return) whitespace?]) (define-λcase op-start? [(#\+ #\- #\* #\^ #\% #\& #\| #\#) stop] [(#\/) (λcase [(#\/) stop])] [(#\<) (λcase [(#\< #\=) stop])] [(#\>) (λcase [(#\> #\=) stop])] [(#\=) (λcase [(#\=) stop])] [(#\~) (λcase [(#\=) stop])]) (define ((make-name-predicate [char-categories '(ll lu nd)]) c) (and (char? c) (or (char=? c #\_) (memq (char-general-category c) char-categories)) name-more?)) (define name-start? (make-name-predicate '(ll lu))) (define name-more? (make-name-predicate '(ll lu nd))) (define-λcase number-start? [(#\.) (number-more? #\.)] [(#\0) (λcase [(#\x #\X) (λ (c) (or (hex-digit? c) (error "expected a hex digit")))] [(#\.) decimal-digit-or-exponent?]) ] [(#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) number-more?]) (define-λcase number-more? #:char-id c [(#\e #\E) decimal-digit-or-sign?] [(#\.) (λ (next-c) (or (decimal-digit-or-exponent? next-c) (error "expected a digit")))] [else (and (decimal-digit? c) number-more?)]) (define-λcase decimal-digit-or-sign? #:char-id c [(#\+ #\-) decimal-digit?] [else (and (decimal-digit? c) decimal-digit?)]) (define-λcase decimal-digit-or-exponent? #:char-id c [(#\e #\E) decimal-digit-or-sign?] [else (and (decimal-digit? c) decimal-digit-or-exponent?)]) (define-λcase decimal-digit? [(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) decimal-digit?]) (define-λcase hex-digit? #:char-id c [(#\a #\b #\c #\d #\e #\f) hex-digit?] [(#\A #\B #\C #\D #\E #\F) hex-digit?] [else (and (decimal-digit? c) hex-digit?)]) (define-λcase long-brackets-more? [(#\[) stop] [(#\=) long-brackets-more?] [else (error "expected [ or =")]) (define-λcase long-brackets-start? [(#\[) long-brackets-more?] [else (error "expected [")]) (define-λcase long-brackets-comment-next? [(#\-) (λ (next-c) (or (long-brackets-start? next-c) (error "expected [")))] [else (error "expected -")]) (define-λcase long-brackets-comment-start? [(#\-) long-brackets-comment-next?] [else (error "expected -")]) (define ((make-reader p f) in) (define s (read-string-while in p)) (values s (f s))) (define lua:read-name (make-reader name-start? string->symbol)) (define lua:read-op (make-reader op-start? string->symbol)) (define lua:read-number (make-reader number-start? (λ (s) (if (regexp-match? #rx"^0[xX]" s) (string->number (string-append "#x" (substring s 2)) 16) (string->number s))))) (define (lua:read-string in [partial? #f]) (define quote-char (read-char in)) (define lit-str (open-output-string)) (define actual-bs (open-output-bytes)) (write-char quote-char lit-str) (write-char quote-char actual-bs) (define has-end-quote? (let loop ([escaped? #f]) (define char (read-char in)) (cond [(eof-object? char) (cond [partial? #f] [else (error 'lua:read-string "unexpected EOF while reading string")])] [escaped? (define-values (escape-seq escape-char) (lua:string-escape char)) (write-string escape-seq lit-str) (write-char escape-char actual-bs) (loop #f)] [(eqv? char #\\) (loop #t)] [else (write-char char lit-str) (write-char char actual-bs) (cond [(eqv? char quote-char) #t] [else (loop #f)])]))) (define bs (let ([bs (get-output-bytes actual-bs)]) (subbytes bs 1 ((if has-end-quote? sub1 values) (bytes-length bs))))) (values (get-output-string lit-str) bs)) (define (lua:string-escape chr) (case chr [(#\\) (values "\\\\" #\\)] [(#\a) (values "\\a" #\u007)] [(#\b) (values "\\b" #\backspace)] [(#\f) (values "\\f" #\page)] [(#\r) (values "\\r" #\return)] [(#\n) (values "\\n" #\newline)] [(#\t) (values "\\t" #\tab)] [(#\v) (values "\\v" #\vtab)] [(#\[) (values "\\[" #\[)] [(#\]) (values "\\[" #\])] [else (values (string #\\ chr) chr)])) (define (lua:read-long-brackets in [comment? #f] [partial? #f]) (define open-brackets (read-string-while in (if comment? long-brackets-comment-start? long-brackets-start?))) (define close-brackets (string-replace open-brackets "[" "]")) (define close-brackets-re (regexp (regexp-quote close-brackets))) (define-values (str-no-open close-brackets-len) (match (regexp-match-peek-positions close-brackets-re in) [#f #:when partial? (values (port->string in) 0)] [#f (error (format "no matching '~a' for '~a'" close-brackets open-brackets))] [`((,_ . ,end-pos)) (values (read-string end-pos in) (string-length open-brackets))])) (define content-bs (let ([trimmed-str (cond [(regexp-match? #rx"^\r\n" str-no-open) (substring str-no-open 2)] [(regexp-match? #rx"^\n" str-no-open) (substring str-no-open 1)] [else str-no-open])]) (string->bytes/utf-8 (substring trimmed-str 0 (- (string-length trimmed-str) close-brackets-len))))) (values (string-append open-brackets str-no-open) content-bs))
cd13912624f2cb7eb813b291534270c33dad20eaf704121a77a641afc400f922
Workiva/eva
errorcode_generation.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.dev.tasks.errorcode-generation (:require [clojure.java.io :as io]) (:import [java.nio.file Files Path Paths FileVisitOption LinkOption])) (def enum-template "// 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. package eva.error.v1; import java.util.HashMap; import java.util.Map; import clojure.lang.Keyword; public enum EvaErrorCode implements IErrorCode { %s; private EvaErrorCode parent; private long evaCode; private long httpCode; private String name; private Keyword keyword; private String explanation; // -on-demand_holder_idiom private static class Mapping { static Map<Long, EvaErrorCode> CODE_TO_CODE = new HashMap<>(); } private EvaErrorCode(EvaErrorCode parent, long evaCode, long httpCode, String name, Keyword keyword, String explanation) { this.parent = parent; this.evaCode = evaCode; this.httpCode = httpCode; this.name = name; this.keyword = keyword; // this.keyword = Keyword.intern(keyword); this.explanation = explanation; Mapping.CODE_TO_CODE.put(evaCode, this); } public static EvaErrorCode getFromLong(Long code) { return Mapping.CODE_TO_CODE.get(code); } @Override public boolean isUnspecified() { return evaCode == -1; } /* * -1 is used by UnknownError. * Long.MIN_VALUE is used by all non-terminal error codes. * The intention is that these error codes will never be returned directly, * but are used merely to provide a sensible hierarchy for `is()` calls. */ @Override public long getCode() { return evaCode; } @Override public long getHttpErrorCode() { return httpCode; } @Override public String getScope() { if (parent == null) { return \"\"; } else { return parent.getScope() + parent.getName() + \": \"; } } @Override public String getName() { return name; } @Override public Keyword getKey() { return keyword; } @Override public String getExplanation() { return explanation; } @Override public boolean is(IErrorCode e) { return (this == e) ? true : (parent == null) ? false : parent.is(e); } } ") (defn- iterate-until-fixed ([f x] (let [r (f x)] (if (= r x) r (recur f r))))) (defn- replace-step [s] (clojure.string/replace-first s #"([^A-Z_])([A-Z])|([A-Z])([A-Z])([a-z])" (fn [[_ x1 x2 y1 y2 y3]] (if x1 (format "%s_%s" x1 x2) (format "%s_%s%s" y1 y2 y3))))) (defn- camelcase->snakecase [sym] (->> (str sym) (iterate-until-fixed replace-step) clojure.string/upper-case)) (def indent " ") (defn make-indent [s] (apply str (repeat (count (str s)) \ ))) (def constructor-template (format "%s%s%s(%s, %s%s%s%s, %s%s%s%s, %s%s%s\"%s\", %s%s%sKeyword.intern(\"%s\", %s%s%s%s\"%s\"), %s%s%s\"%s\")" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent (make-indent "Keyword.intern(") "%s" "%s" "%s" indent "%s" "%s" "%s")) (defn- fill-constructor-template [hier-indent name-indent enum parent-enum code http-status enum-name kw-ns kw-name expl] (format constructor-template hier-indent enum parent-enum hier-indent name-indent code hier-indent name-indent http-status hier-indent name-indent enum-name hier-indent name-indent kw-ns hier-indent name-indent kw-name hier-indent name-indent expl)) (defn- generate-enum-def [level parent {:keys [sym code http-status keyword doc]}] (let [parent-ref (if parent (camelcase->snakecase (:sym parent)) "null") hier-indent (apply str (repeat level indent)) name-indent (make-indent (camelcase->snakecase sym))] (fill-constructor-template hier-indent name-indent (camelcase->snakecase sym) parent-ref code http-status (str sym) (namespace keyword) (name keyword) doc))) (defn- make-kw [top-level-keyword raw-kw] (if top-level-keyword (keyword (or (namespace top-level-keyword) (name top-level-keyword)) (name raw-kw)) (if (nil? (namespace raw-kw)) (keyword "eva.error" (name raw-kw)) raw-kw))) (defn- step [level top-level-keyword {:as parent} [sym raw-subtype]] (let [raw-kw (:keyword raw-subtype) kw (make-kw top-level-keyword raw-kw) doc (:doc raw-subtype) Long / MIN_VALUE used as code for non - terminal types . These types are intended never to be used by directly . ;; The exist to provide a sensible hierarchy for is() checks. eva-code (:code raw-subtype "Long.MIN_VALUE") http-status (get raw-subtype :http-status (get parent :http-status 500)) subtypes (:subtypes raw-subtype) ;; asserts here this {:sym sym, :code eva-code, :http-status http-status, :keyword kw, :doc doc}] (->> this (generate-enum-def level parent) (conj (if subtypes (mapcat (partial step (inc level) (or top-level-keyword raw-kw) this) subtypes) ()))))) (def error-codes (clojure.core/read-string (slurp "core/resources/eva/error/error_codes.edn"))) (defn- delete-previous-file [] (let [file (Paths/get "core/java-src/eva/error/v1/EvaErrorCode.java" (make-array String 0))] (Files/delete file))) (defn- make-file-string [] (format enum-template (clojure.string/join ",\n" (mapcat (partial step 0 nil nil) error-codes)))) (defn generate-error-code-file [] (spit "core/java-src/eva/error/v1/EvaErrorCode.java" (make-file-string))) (defn check-equivalence [] (= (slurp "core/java-src/eva/error/v1/EvaErrorCode.java") (make-file-string)))
null
https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/dev/src/eva/dev/tasks/errorcode_generation.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. The exist to provide a sensible hierarchy for is() checks. asserts here
Copyright 2015 - 2019 Workiva Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns eva.dev.tasks.errorcode-generation (:require [clojure.java.io :as io]) (:import [java.nio.file Files Path Paths FileVisitOption LinkOption])) (def enum-template "// Copyright 2015-2019 Workiva Inc. // // 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. public enum EvaErrorCode implements IErrorCode { // -on-demand_holder_idiom private static class Mapping { } private EvaErrorCode(EvaErrorCode parent, long evaCode, long httpCode, String name, Keyword keyword, String explanation) { } public static EvaErrorCode getFromLong(Long code) { } @Override public boolean isUnspecified() { } /* * -1 is used by UnknownError. * Long.MIN_VALUE is used by all non-terminal error codes. * The intention is that these error codes will never be returned directly, * but are used merely to provide a sensible hierarchy for `is()` calls. */ @Override public long getCode() { } @Override public long getHttpErrorCode() { } @Override public String getScope() { if (parent == null) { } else { } } @Override public String getName() { } @Override public Keyword getKey() { } @Override public String getExplanation() { } @Override public boolean is(IErrorCode e) { return (this == e) ? true : (parent == null) ? false : } } ") (defn- iterate-until-fixed ([f x] (let [r (f x)] (if (= r x) r (recur f r))))) (defn- replace-step [s] (clojure.string/replace-first s #"([^A-Z_])([A-Z])|([A-Z])([A-Z])([a-z])" (fn [[_ x1 x2 y1 y2 y3]] (if x1 (format "%s_%s" x1 x2) (format "%s_%s%s" y1 y2 y3))))) (defn- camelcase->snakecase [sym] (->> (str sym) (iterate-until-fixed replace-step) clojure.string/upper-case)) (def indent " ") (defn make-indent [s] (apply str (repeat (count (str s)) \ ))) (def constructor-template (format "%s%s%s(%s, %s%s%s%s, %s%s%s%s, %s%s%s\"%s\", %s%s%sKeyword.intern(\"%s\", %s%s%s%s\"%s\"), %s%s%s\"%s\")" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent "%s" "%s" "%s" indent (make-indent "Keyword.intern(") "%s" "%s" "%s" indent "%s" "%s" "%s")) (defn- fill-constructor-template [hier-indent name-indent enum parent-enum code http-status enum-name kw-ns kw-name expl] (format constructor-template hier-indent enum parent-enum hier-indent name-indent code hier-indent name-indent http-status hier-indent name-indent enum-name hier-indent name-indent kw-ns hier-indent name-indent kw-name hier-indent name-indent expl)) (defn- generate-enum-def [level parent {:keys [sym code http-status keyword doc]}] (let [parent-ref (if parent (camelcase->snakecase (:sym parent)) "null") hier-indent (apply str (repeat level indent)) name-indent (make-indent (camelcase->snakecase sym))] (fill-constructor-template hier-indent name-indent (camelcase->snakecase sym) parent-ref code http-status (str sym) (namespace keyword) (name keyword) doc))) (defn- make-kw [top-level-keyword raw-kw] (if top-level-keyword (keyword (or (namespace top-level-keyword) (name top-level-keyword)) (name raw-kw)) (if (nil? (namespace raw-kw)) (keyword "eva.error" (name raw-kw)) raw-kw))) (defn- step [level top-level-keyword {:as parent} [sym raw-subtype]] (let [raw-kw (:keyword raw-subtype) kw (make-kw top-level-keyword raw-kw) doc (:doc raw-subtype) Long / MIN_VALUE used as code for non - terminal types . These types are intended never to be used by directly . eva-code (:code raw-subtype "Long.MIN_VALUE") http-status (get raw-subtype :http-status (get parent :http-status 500)) subtypes (:subtypes raw-subtype) this {:sym sym, :code eva-code, :http-status http-status, :keyword kw, :doc doc}] (->> this (generate-enum-def level parent) (conj (if subtypes (mapcat (partial step (inc level) (or top-level-keyword raw-kw) this) subtypes) ()))))) (def error-codes (clojure.core/read-string (slurp "core/resources/eva/error/error_codes.edn"))) (defn- delete-previous-file [] (let [file (Paths/get "core/java-src/eva/error/v1/EvaErrorCode.java" (make-array String 0))] (Files/delete file))) (defn- make-file-string [] (format enum-template (clojure.string/join ",\n" (mapcat (partial step 0 nil nil) error-codes)))) (defn generate-error-code-file [] (spit "core/java-src/eva/error/v1/EvaErrorCode.java" (make-file-string))) (defn check-equivalence [] (= (slurp "core/java-src/eva/error/v1/EvaErrorCode.java") (make-file-string)))
e7552ef897eda1f2e2d6ac646e93a22226f0e21a41d2c3a6219fe0c0256e60d3
hspec/hspec
LocationSpec.hs
# LANGUAGE CPP # # OPTIONS_GHC -fno - warn - incomplete - patterns # # OPTIONS_GHC -fno - warn - missing - fields # # OPTIONS_GHC -fno - warn - overlapping - patterns # # OPTIONS_GHC -fno - warn - missing - methods # # OPTIONS_GHC -fno - warn - incomplete - uni - patterns # {-# OPTIONS_GHC -O0 #-} module Test.Hspec.Core.Example.LocationSpec (spec) where import Prelude () import Helper import Test.Hspec.Core.Example import Test.Hspec.Core.Example.Location class SomeClass a where someMethod :: a -> IO () instance SomeClass () where data Person = Person { name :: String , age :: Int } deriving (Eq, Show) spec :: Spec spec = do describe "parseAssertionFailed" $ do context "with pre-GHC-8.* error message" $ do it "extracts source location" $ do parseAssertionFailed "Foo.hs:4:7-12: Assertion failed\n" `shouldBe` Just (Location "Foo.hs" 4 7) describe "extractLocation" $ do context "with pattern match failure in do expression" $ do context "in IO" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 2) 13 Left e <- try $ do Just n <- return Nothing return (n :: Int) extractLocation e `shouldBe` location #if !MIN_VERSION_base(4,12,0) context "in Either" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 4) 15 let foo :: Either () () foo = do 23 <- Right (42 :: Int) pass Left e <- try (evaluate foo) extractLocation e `shouldBe` location #endif context "with ErrorCall" $ do it "extracts Location" $ do let location = #if MIN_VERSION_base(4,9,0) Just $ Location file (__LINE__ + 4) 34 #else Nothing #endif Left e <- try (evaluate (undefined :: ())) extractLocation e `shouldBe` location context "with PatternMatchFail" $ do context "with single-line source span" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 40 Left e <- try (evaluate (let Just n = Nothing in (n :: Int))) extractLocation e `shouldBe` location context "with multi-line source span" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 36 Left e <- try (evaluate (case Nothing of Just n -> n :: Int )) extractLocation e `shouldBe` location context "with RecConError" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 39 Left e <- try $ evaluate (age Person {name = "foo"}) extractLocation e `shouldBe` location context "with NoMethodError" $ do it "extracts Location" $ do Left e <- try $ someMethod () extractLocation e `shouldBe` Just (Location file 19 10) context "with AssertionFailed" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 36 Left e <- try . evaluate $ assert False () extractLocation e `shouldBe` location describe "parseCallStack" $ do it "parses Location from call stack" $ do let input = unlines [ "CallStack (from HasCallStack):" , " error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err" , " undefined, called at test/Test/Hspec.hs:13:32 in main:Test.Hspec" ] parseCallStack input `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 13 32) describe "parseLocation" $ do it "parses Location" $ do parseLocation "test/Test/Hspec.hs:13:32" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 13 32) describe "parseSourceSpan" $ do it "parses single-line source span" $ do parseSourceSpan "test/Test/Hspec.hs:25:36-51:" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 25 36) it "parses multi-line source span" $ do parseSourceSpan "test/Test/Hspec.hs:(15,7)-(17,26):" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 15 7) file :: FilePath file = workaroundForIssue19236 __FILE__
null
https://raw.githubusercontent.com/hspec/hspec/b87b226730e6997cc516c60727120210a4cf1cf4/hspec-core/test/Test/Hspec/Core/Example/LocationSpec.hs
haskell
# OPTIONS_GHC -O0 #
# LANGUAGE CPP # # OPTIONS_GHC -fno - warn - incomplete - patterns # # OPTIONS_GHC -fno - warn - missing - fields # # OPTIONS_GHC -fno - warn - overlapping - patterns # # OPTIONS_GHC -fno - warn - missing - methods # # OPTIONS_GHC -fno - warn - incomplete - uni - patterns # module Test.Hspec.Core.Example.LocationSpec (spec) where import Prelude () import Helper import Test.Hspec.Core.Example import Test.Hspec.Core.Example.Location class SomeClass a where someMethod :: a -> IO () instance SomeClass () where data Person = Person { name :: String , age :: Int } deriving (Eq, Show) spec :: Spec spec = do describe "parseAssertionFailed" $ do context "with pre-GHC-8.* error message" $ do it "extracts source location" $ do parseAssertionFailed "Foo.hs:4:7-12: Assertion failed\n" `shouldBe` Just (Location "Foo.hs" 4 7) describe "extractLocation" $ do context "with pattern match failure in do expression" $ do context "in IO" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 2) 13 Left e <- try $ do Just n <- return Nothing return (n :: Int) extractLocation e `shouldBe` location #if !MIN_VERSION_base(4,12,0) context "in Either" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 4) 15 let foo :: Either () () foo = do 23 <- Right (42 :: Int) pass Left e <- try (evaluate foo) extractLocation e `shouldBe` location #endif context "with ErrorCall" $ do it "extracts Location" $ do let location = #if MIN_VERSION_base(4,9,0) Just $ Location file (__LINE__ + 4) 34 #else Nothing #endif Left e <- try (evaluate (undefined :: ())) extractLocation e `shouldBe` location context "with PatternMatchFail" $ do context "with single-line source span" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 40 Left e <- try (evaluate (let Just n = Nothing in (n :: Int))) extractLocation e `shouldBe` location context "with multi-line source span" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 36 Left e <- try (evaluate (case Nothing of Just n -> n :: Int )) extractLocation e `shouldBe` location context "with RecConError" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 39 Left e <- try $ evaluate (age Person {name = "foo"}) extractLocation e `shouldBe` location context "with NoMethodError" $ do it "extracts Location" $ do Left e <- try $ someMethod () extractLocation e `shouldBe` Just (Location file 19 10) context "with AssertionFailed" $ do it "extracts Location" $ do let location = Just $ Location file (__LINE__ + 1) 36 Left e <- try . evaluate $ assert False () extractLocation e `shouldBe` location describe "parseCallStack" $ do it "parses Location from call stack" $ do let input = unlines [ "CallStack (from HasCallStack):" , " error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err" , " undefined, called at test/Test/Hspec.hs:13:32 in main:Test.Hspec" ] parseCallStack input `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 13 32) describe "parseLocation" $ do it "parses Location" $ do parseLocation "test/Test/Hspec.hs:13:32" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 13 32) describe "parseSourceSpan" $ do it "parses single-line source span" $ do parseSourceSpan "test/Test/Hspec.hs:25:36-51:" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 25 36) it "parses multi-line source span" $ do parseSourceSpan "test/Test/Hspec.hs:(15,7)-(17,26):" `shouldBe` Just (Location ("test" </> "Test" </> "Hspec.hs") 15 7) file :: FilePath file = workaroundForIssue19236 __FILE__
3223f4f58fa24b43a9ae7f55203406eee00647aba112ec588fd2b3a2f0fc6c69
NorfairKing/validity
Clock.hs
# OPTIONS_GHC -fno - warn - orphans # module Data.GenValidity.Time.Clock where import Data.GenValidity import Data.GenValidity.Time.Calendar () import Data.Time.Clock import Data.Validity.Time.Clock () import Test.QuickCheck instance GenValid UniversalTime where genValid = ModJulianDate <$> genValid shrinkValid = fmap ModJulianDate . shrinkValid . getModJulianDate instance GenValid DiffTime where genValid = picosecondsToDiffTime <$> genValid shrinkValid = fmap picosecondsToDiffTime . shrinkValid . diffTimeToPicoseconds instance GenValid UTCTime where genValid = UTCTime <$> genValid <*> (fromIntegral <$> choose (0 :: Int, 86400)) shrinkValid (UTCTime d dt) = [UTCTime d' dt' | (d', dt') <- shrinkValid (d, dt)] instance GenValid NominalDiffTime where genValid = secondsToNominalDiffTime <$> genValid shrinkValid = fmap secondsToNominalDiffTime . shrinkValid . nominalDiffTimeToSeconds
null
https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-time/src/Data/GenValidity/Time/Clock.hs
haskell
# OPTIONS_GHC -fno - warn - orphans # module Data.GenValidity.Time.Clock where import Data.GenValidity import Data.GenValidity.Time.Calendar () import Data.Time.Clock import Data.Validity.Time.Clock () import Test.QuickCheck instance GenValid UniversalTime where genValid = ModJulianDate <$> genValid shrinkValid = fmap ModJulianDate . shrinkValid . getModJulianDate instance GenValid DiffTime where genValid = picosecondsToDiffTime <$> genValid shrinkValid = fmap picosecondsToDiffTime . shrinkValid . diffTimeToPicoseconds instance GenValid UTCTime where genValid = UTCTime <$> genValid <*> (fromIntegral <$> choose (0 :: Int, 86400)) shrinkValid (UTCTime d dt) = [UTCTime d' dt' | (d', dt') <- shrinkValid (d, dt)] instance GenValid NominalDiffTime where genValid = secondsToNominalDiffTime <$> genValid shrinkValid = fmap secondsToNominalDiffTime . shrinkValid . nominalDiffTimeToSeconds
38b254b380790b9c93307afc4029536c5c86b54b09562e4e41a28fdcb5b45a1f
clojure/clojurescript
base64_vlq.clj
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns cljs.source-map.base64-vlq (:require [clojure.string :as string] [cljs.source-map.base64 :as base64])) (def ^:const vlq-base-shift 5) (def ^:const vlq-base (bit-shift-left 1 vlq-base-shift)) (def ^:const vlq-base-mask (dec vlq-base)) (def ^:const vlq-continuation-bit vlq-base) (defn bit-shift-right-zero-fill [x n] (bit-shift-right (bit-and 0xFFFFFFFF x) n)) (defn to-vlq-signed [v] (if (neg? v) (inc (bit-shift-left (- v) 1)) (+ (bit-shift-left v 1) 0))) (defn from-vlq-signed [v] (let [neg? (= (bit-and v 1) 1) shifted (bit-shift-right v 1)] (if neg? (- shifted) shifted))) (defn encode-val [n] (let [sb (StringBuilder.) vlq (to-vlq-signed n)] (loop [digit (bit-and vlq vlq-base-mask) vlq (bit-shift-right-zero-fill vlq vlq-base-shift)] (if (pos? vlq) (let [digit (bit-or digit vlq-continuation-bit)] (.append sb (base64/encode digit)) (recur (bit-and vlq vlq-base-mask) (bit-shift-right-zero-fill vlq vlq-base-shift))) (.append sb (base64/encode digit)))) (str sb))) (defn encode [v] (apply str (map encode-val v))) (defn decode [^String s] (let [l (.length s)] (loop [i 0 result 0 shift 0] (when (>= i l) (throw (Error. "Expected more digits in base 64 VLQ value."))) (let [digit (base64/decode (.charAt s i))] (let [i (inc i) continuation? (pos? (bit-and digit vlq-continuation-bit)) digit (bit-and digit vlq-base-mask) result (+ result (bit-shift-left digit shift)) shift (+ shift vlq-base-shift)] (if continuation? (recur i result shift) (lazy-seq (cons (from-vlq-signed result) (let [s (.substring s i)] (when-not (string/blank? s) (decode s))))))))))) (comment ;; tests 63 2147483584 64 65 32 (from-vlq-signed 65) ;; -32 Base64 VLQ can only represent 32bit values (encode-val 32) ; "gC" { : value 32 : rest " " } (decode "AAgBC") ; (0 0 16 1) ;; lines kept count by semicolons, segments delimited by commas the above is gline 0 , gcol 0 , file 0 , line 16 , col 1 , no name if this was the first segment read (decode "AAggBC") ; very clever way to encode large values 5 values instead of 4 (encode [0 0 16 1]) ; "AAgBC" ( 4 0 11 -14 -1 ) this is correct ;; gline N, gcol +4, file +0, line +11, col -14, name -1 Notes about format we always have 1 , 4 , or 5 values , all zero - based indexes 1 . generated col - relative - reset on every new line in generated source 2 . index into sources list - relative 3 . original line - relative 4 . origin column - relative 5 . name - relative )
null
https://raw.githubusercontent.com/clojure/clojurescript/a4673b880756531ac5690f7b4721ad76c0810327/src/main/clojure/cljs/source_map/base64_vlq.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. tests -32 "gC" (0 0 16 1) lines kept count by semicolons, segments delimited by commas very clever way to encode large values "AAgBC" gline N, gcol +4, file +0, line +11, col -14, name -1
Copyright ( c ) . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns cljs.source-map.base64-vlq (:require [clojure.string :as string] [cljs.source-map.base64 :as base64])) (def ^:const vlq-base-shift 5) (def ^:const vlq-base (bit-shift-left 1 vlq-base-shift)) (def ^:const vlq-base-mask (dec vlq-base)) (def ^:const vlq-continuation-bit vlq-base) (defn bit-shift-right-zero-fill [x n] (bit-shift-right (bit-and 0xFFFFFFFF x) n)) (defn to-vlq-signed [v] (if (neg? v) (inc (bit-shift-left (- v) 1)) (+ (bit-shift-left v 1) 0))) (defn from-vlq-signed [v] (let [neg? (= (bit-and v 1) 1) shifted (bit-shift-right v 1)] (if neg? (- shifted) shifted))) (defn encode-val [n] (let [sb (StringBuilder.) vlq (to-vlq-signed n)] (loop [digit (bit-and vlq vlq-base-mask) vlq (bit-shift-right-zero-fill vlq vlq-base-shift)] (if (pos? vlq) (let [digit (bit-or digit vlq-continuation-bit)] (.append sb (base64/encode digit)) (recur (bit-and vlq vlq-base-mask) (bit-shift-right-zero-fill vlq vlq-base-shift))) (.append sb (base64/encode digit)))) (str sb))) (defn encode [v] (apply str (map encode-val v))) (defn decode [^String s] (let [l (.length s)] (loop [i 0 result 0 shift 0] (when (>= i l) (throw (Error. "Expected more digits in base 64 VLQ value."))) (let [digit (base64/decode (.charAt s i))] (let [i (inc i) continuation? (pos? (bit-and digit vlq-continuation-bit)) digit (bit-and digit vlq-base-mask) result (+ result (bit-shift-left digit shift)) shift (+ shift vlq-base-shift)] (if continuation? (recur i result shift) (lazy-seq (cons (from-vlq-signed result) (let [s (.substring s i)] (when-not (string/blank? s) (decode s))))))))))) (comment 63 2147483584 64 65 32 Base64 VLQ can only represent 32bit values { : value 32 : rest " " } the above is gline 0 , gcol 0 , file 0 , line 16 , col 1 , no name if this was the first segment read 5 values instead of 4 ( 4 0 11 -14 -1 ) this is correct Notes about format we always have 1 , 4 , or 5 values , all zero - based indexes 1 . generated col - relative - reset on every new line in generated source 2 . index into sources list - relative 3 . original line - relative 4 . origin column - relative 5 . name - relative )
98c41bca4768bbc29746a893a7e26a6536133102fecf8df54d609a0495e001df
khibino/haskell-relational-record
Qualify.hs
# LANGUAGE GeneralizedNewtypeDeriving # -- | Module : Database . Relational . Monad . Trans . Qualify Copyright : 2013 - 2019 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- Portability : unknown -- -- This module defines monad transformer which qualify uniquely SQL table forms. -- -- This is not public interface. module Database.Relational.Monad.Trans.Qualify ( -- * Qualify monad Qualify, qualify, evalQualifyPrime, qualifyQuery ) where import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (StateT, runStateT, get, modify) import Control.Applicative (Applicative) import Control.Monad (liftM, ap) import qualified Database.Relational.SqlSyntax as Syntax -- | Monad type to qualify SQL table forms. newtype Qualify m a = Qualify (StateT Int m a) deriving (Monad, Functor, Applicative) -- | Run qualify monad with initial state to get only result. evalQualifyPrime :: Monad m => Qualify m a -> m a evalQualifyPrime (Qualify s) = fst `liftM` runStateT s 0 {- primary alias id -} -- | Generated new qualifier on internal state. newAlias :: Monad m => Qualify m Syntax.Qualifier newAlias = Qualify $ do ai <- Syntax.Qualifier `liftM` get modify (+ 1) return ai -- | Lift to 'Qualify' qualify :: Monad m => m a -> Qualify m a qualify = Qualify . lift -- | Get qualifyed table form query. qualifyQuery :: Monad m => query -- ^ Query to qualify -> Qualify m (Syntax.Qualified query) -- ^ Result with updated state qualifyQuery query = Syntax.qualify `liftM` newAlias `ap` return query
null
https://raw.githubusercontent.com/khibino/haskell-relational-record/759b3d7cea207e64d2bd1cf195125182f73d2a52/relational-query/src/Database/Relational/Monad/Trans/Qualify.hs
haskell
| License : BSD3 Maintainer : Stability : experimental Portability : unknown This module defines monad transformer which qualify uniquely SQL table forms. This is not public interface. * Qualify monad | Monad type to qualify SQL table forms. | Run qualify monad with initial state to get only result. primary alias id | Generated new qualifier on internal state. | Lift to 'Qualify' | Get qualifyed table form query. ^ Query to qualify ^ Result with updated state
# LANGUAGE GeneralizedNewtypeDeriving # Module : Database . Relational . Monad . Trans . Qualify Copyright : 2013 - 2019 module Database.Relational.Monad.Trans.Qualify ( Qualify, qualify, evalQualifyPrime, qualifyQuery ) where import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (StateT, runStateT, get, modify) import Control.Applicative (Applicative) import Control.Monad (liftM, ap) import qualified Database.Relational.SqlSyntax as Syntax newtype Qualify m a = Qualify (StateT Int m a) deriving (Monad, Functor, Applicative) evalQualifyPrime :: Monad m => Qualify m a -> m a newAlias :: Monad m => Qualify m Syntax.Qualifier newAlias = Qualify $ do ai <- Syntax.Qualifier `liftM` get modify (+ 1) return ai qualify :: Monad m => m a -> Qualify m a qualify = Qualify . lift qualifyQuery :: Monad m qualifyQuery query = Syntax.qualify `liftM` newAlias `ap` return query
6f952a42e92921b0d549cf71181856bc65ff2d3bf14d52efd929bfef972ef1f9
elaforge/karya
CallDoc_test.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt module Cmd.CallDoc_test where import Util.Test import qualified Cmd.CallDoc as CallDoc import qualified Derive.C.All as C.All import qualified Derive.Scale.All as Scale.All test_doc_html :: Test test_doc_html = do Mostly this just makes HPC coverage for all the documentation . let hstate = ("haddock", mempty) not_equal (CallDoc.doc_html hstate (CallDoc.builtins C.All.builtins)) mempty not_equal (CallDoc.scales_html hstate (CallDoc.scale_docs Scale.All.docs)) mempty
null
https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/Cmd/CallDoc_test.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt
Copyright 2013 module Cmd.CallDoc_test where import Util.Test import qualified Cmd.CallDoc as CallDoc import qualified Derive.C.All as C.All import qualified Derive.Scale.All as Scale.All test_doc_html :: Test test_doc_html = do Mostly this just makes HPC coverage for all the documentation . let hstate = ("haddock", mempty) not_equal (CallDoc.doc_html hstate (CallDoc.builtins C.All.builtins)) mempty not_equal (CallDoc.scales_html hstate (CallDoc.scale_docs Scale.All.docs)) mempty
9a4b31bdf41d089cb1195db3005f3d32efa7944f51274a57a3cf07343011e285
TrustInSoft/tis-kernel
stop_at_nth.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 ) . (* *) (**************************************************************************) val clear: unit -> unit val incr: unit -> bool
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/value/slevel/stop_at_nth.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies 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 ) . val clear: unit -> unit val incr: unit -> bool
3235324a44f542d745165b8f37033cb3bdd069c50a1fc6386a92af9d8e172c77
hiredman/clojurebot
tinyurl.clj
(ns hiredman.clojurebot.tinyurl (:use (hiredman.clojurebot core))) (def url-reg #"[A-Za-z]+://[^ ^/]+\.[^ ^/]+[^ ]+") (defn get-tiny-url [url] (with-open [pt (.getContent (java.net.URL. (str "-create.php?url=" (java.net.URLEncoder/encode url)))) dis (java.io.DataInputStream. pt)] (.readLine dis))) (def get-tiny-url-cached (memoize get-tiny-url)) (defmethod responder ::tiny-url [bot pojo] (let [url (re-find url-reg (:message pojo))] (when (> (count url) 60) (try (.sendNotice (:this bot) (who pojo) (get-tiny-url-cached url)) (catch Exception e (println e)))))) (add-dispatch-hook 20 (dfn (re-find url-reg (:message msg))) ::tiny-url)
null
https://raw.githubusercontent.com/hiredman/clojurebot/1e8bde92f2dd45bb7928d4db17de8ec48557ead1/src/hiredman/clojurebot/tinyurl.clj
clojure
(ns hiredman.clojurebot.tinyurl (:use (hiredman.clojurebot core))) (def url-reg #"[A-Za-z]+://[^ ^/]+\.[^ ^/]+[^ ]+") (defn get-tiny-url [url] (with-open [pt (.getContent (java.net.URL. (str "-create.php?url=" (java.net.URLEncoder/encode url)))) dis (java.io.DataInputStream. pt)] (.readLine dis))) (def get-tiny-url-cached (memoize get-tiny-url)) (defmethod responder ::tiny-url [bot pojo] (let [url (re-find url-reg (:message pojo))] (when (> (count url) 60) (try (.sendNotice (:this bot) (who pojo) (get-tiny-url-cached url)) (catch Exception e (println e)))))) (add-dispatch-hook 20 (dfn (re-find url-reg (:message msg))) ::tiny-url)
9deef5fd2de9957c036638b47890d073b2bba9fd07e5b3914e18a49e56e457af
softlab-ntua/bencherl
unit_utils.erl
Copyright ( C ) 2003 - 2014 % This file is part of the Ceylan Erlang library . % % This library is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License or the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) % any later version. % You can also redistribute it and/or modify it under the terms of the Mozilla Public License , version 1.1 or later . % % 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 and the GNU General Public License % for more details. % You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License % along with this library. % If not, see </> and % </>. % Author : ( ) Creation date : Wednesday , October 24 , 2012 % Gathering of unit management facilities. % % All kinds of units are listed here, alongside the reference ones (ex: the meter is the unit of length in the International System of Units ) . % One objective is to be able to specify , instead of mere values ( ex : 1.14 ) , values with units ( ex : { meters , 1.14 } ) , and possibly to convert them into a % canonical form transparently. % % See unit_utils_test.erl for the corresponding test. % -module(unit_utils). Time - related section . % { year(), month(), day() }: -type date() :: calendar:date(). { hour ( ) , minute ( ) , second ( ) } : -type time() :: calendar:time(). -type megaseconds() :: integer(). -type years() :: integer(). -type days() :: integer(). -type hours() :: integer(). -type minutes() :: integer(). -type seconds() :: integer(). -type milliseconds() :: integer(). -type microseconds() :: integer(). % Frequency: -type hertz() :: float(). -type time_reference_unit() :: 'seconds'. -type time_units() :: time_reference_unit() | 'years' | 'days' | 'hours' | 'minutes' | 'milliseconds' | 'microseconds'. -export_type([ date/0, time/0, megaseconds/0, years/0, days/0, hours/0, minutes/0, seconds/0, milliseconds/0, microseconds/0, hertz/0, time_reference_unit/0, time_units/0 ]). % Length-related section. -type meters() :: float(). -type millimeters() :: float(). -type int_millimeters() :: integer(). -type length_reference_unit() :: 'meters'. -type length_units() :: length_reference_unit() | 'millimeters' | 'int_millimeters'. -export_type([ meters/0, millimeters/0, int_millimeters/0, length_reference_unit/0, length_units/0 ]). % Speed related section. -type km_per_hour() :: float(). -type meters_per_second() :: float(). -type meters_per_tick() :: float(). -export_type([ km_per_hour/0, meters_per_second/0, meters_per_tick/0 ]). % Volume-related section. -type cubic_meters() :: float(). -type litre() :: float(). -type volume_reference_unit() :: cubic_meters(). -type volume_units() :: volume_reference_unit() | 'litre'. -export_type([ cubic_meters/0, litre/0, volume_reference_unit/0, volume_units/0 ]). % Mass-related section. -type tons() :: float(). -type kilograms() :: float(). -type grams() :: float(). -type mass_reference_unit() :: 'kilograms'. -type mass_units() :: mass_reference_unit() | 'tons' | 'grams'. -export_type([ tons/0, kilograms/0, grams/0, mass_reference_unit/0, mass_units/0 ]). % Energy-related section (energy, work, heat). -type joules() :: float(). -type energy_reference_unit() :: 'joules'. -type energy_units() :: energy_reference_unit(). -export_type([ joules/0, energy_reference_unit/0, energy_units/0 ]). % Temperature units. % In degree Celsius (°C): -type celsius() :: float(). -export_type([ celsius/0 ]). % Angle section. -type radians() :: float(). % Angle in degrees. % % Preferably to be kept in [0.0,360.0[. % -type degrees() :: float(). % Angle in degrees. % Strictly expected to be in [ 0,360 [ . % -type int_degrees() :: integer(). -type angle_reference_unit() :: 'radians'. -type angle_units() :: angle_reference_unit() | 'degrees' | 'int_degrees'. -export_type([ radians/0, degrees/0, int_degrees/0, angle_reference_unit/0, angle_units/0 ]). % All kinds of units: -type units() :: time_units() | length_units() | volume_units() | mass_units() | energy_units() | angle_units(). -export_type([ units/0 ]). % Conversion section. % Converting speeds. -export([ km_per_hour_to_meters_per_second/1, meters_per_second_to_km_per_hour/1 ]). -spec km_per_hour_to_meters_per_second( km_per_hour() ) -> meters_per_second(). km_per_hour_to_meters_per_second( K ) -> ( K * 1000 ) / 3600. -spec meters_per_second_to_km_per_hour( meters_per_second() ) -> km_per_hour(). meters_per_second_to_km_per_hour( M ) -> M * 3600 / 1000.
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/common/src/utils/unit_utils.erl
erlang
This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License or any later version. You can also redistribute it and/or modify it under the terms of the 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 for more details. along with this library. If not, see </> and </>. Gathering of unit management facilities. All kinds of units are listed here, alongside the reference ones (ex: the canonical form transparently. See unit_utils_test.erl for the corresponding test. { year(), month(), day() }: Frequency: Length-related section. Speed related section. Volume-related section. Mass-related section. Energy-related section (energy, work, heat). Temperature units. In degree Celsius (°C): Angle section. Angle in degrees. Preferably to be kept in [0.0,360.0[. Angle in degrees. All kinds of units: Conversion section. Converting speeds.
Copyright ( C ) 2003 - 2014 This file is part of the Ceylan Erlang library . the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) Mozilla Public License , version 1.1 or later . GNU Lesser General Public License and the GNU General Public License You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License Author : ( ) Creation date : Wednesday , October 24 , 2012 meter is the unit of length in the International System of Units ) . One objective is to be able to specify , instead of mere values ( ex : 1.14 ) , values with units ( ex : { meters , 1.14 } ) , and possibly to convert them into a -module(unit_utils). Time - related section . -type date() :: calendar:date(). { hour ( ) , minute ( ) , second ( ) } : -type time() :: calendar:time(). -type megaseconds() :: integer(). -type years() :: integer(). -type days() :: integer(). -type hours() :: integer(). -type minutes() :: integer(). -type seconds() :: integer(). -type milliseconds() :: integer(). -type microseconds() :: integer(). -type hertz() :: float(). -type time_reference_unit() :: 'seconds'. -type time_units() :: time_reference_unit() | 'years' | 'days' | 'hours' | 'minutes' | 'milliseconds' | 'microseconds'. -export_type([ date/0, time/0, megaseconds/0, years/0, days/0, hours/0, minutes/0, seconds/0, milliseconds/0, microseconds/0, hertz/0, time_reference_unit/0, time_units/0 ]). -type meters() :: float(). -type millimeters() :: float(). -type int_millimeters() :: integer(). -type length_reference_unit() :: 'meters'. -type length_units() :: length_reference_unit() | 'millimeters' | 'int_millimeters'. -export_type([ meters/0, millimeters/0, int_millimeters/0, length_reference_unit/0, length_units/0 ]). -type km_per_hour() :: float(). -type meters_per_second() :: float(). -type meters_per_tick() :: float(). -export_type([ km_per_hour/0, meters_per_second/0, meters_per_tick/0 ]). -type cubic_meters() :: float(). -type litre() :: float(). -type volume_reference_unit() :: cubic_meters(). -type volume_units() :: volume_reference_unit() | 'litre'. -export_type([ cubic_meters/0, litre/0, volume_reference_unit/0, volume_units/0 ]). -type tons() :: float(). -type kilograms() :: float(). -type grams() :: float(). -type mass_reference_unit() :: 'kilograms'. -type mass_units() :: mass_reference_unit() | 'tons' | 'grams'. -export_type([ tons/0, kilograms/0, grams/0, mass_reference_unit/0, mass_units/0 ]). -type joules() :: float(). -type energy_reference_unit() :: 'joules'. -type energy_units() :: energy_reference_unit(). -export_type([ joules/0, energy_reference_unit/0, energy_units/0 ]). -type celsius() :: float(). -export_type([ celsius/0 ]). -type radians() :: float(). -type degrees() :: float(). Strictly expected to be in [ 0,360 [ . -type int_degrees() :: integer(). -type angle_reference_unit() :: 'radians'. -type angle_units() :: angle_reference_unit() | 'degrees' | 'int_degrees'. -export_type([ radians/0, degrees/0, int_degrees/0, angle_reference_unit/0, angle_units/0 ]). -type units() :: time_units() | length_units() | volume_units() | mass_units() | energy_units() | angle_units(). -export_type([ units/0 ]). -export([ km_per_hour_to_meters_per_second/1, meters_per_second_to_km_per_hour/1 ]). -spec km_per_hour_to_meters_per_second( km_per_hour() ) -> meters_per_second(). km_per_hour_to_meters_per_second( K ) -> ( K * 1000 ) / 3600. -spec meters_per_second_to_km_per_hour( meters_per_second() ) -> km_per_hour(). meters_per_second_to_km_per_hour( M ) -> M * 3600 / 1000.
28df771b7ead8589e127a68abcb4fafafda3596e02950c8c800fa575cff5fd1c
ngerakines/etap
etap_t_006.erl
-module(etap_t_006). -export([start/0, start_loop/1]). start() -> etap:plan(3), etap_process:is_pid(spawn(?MODULE, start_loop, [test_group_a]), "Spawned process is a pid"), etap_process:is_alive(spawn(?MODULE, start_loop, [test_group_a]), "Spawned process is alive"), etap_process:is_mfa(spawn(?MODULE, start_loop, [test_group_a]), {?MODULE, start_loop, 1}, "Spawned process has correct MFA"), [ Pid ! done || Pid <- pg2:get_members(test_group_a)], etap:end_tests(). start_loop(GroupName) -> pg2:create(GroupName), pg2:join(GroupName, self()), loop(). loop() -> timer:sleep(10000), receive done -> exit(normal); _ -> ok end, loop().
null
https://raw.githubusercontent.com/ngerakines/etap/3d46faf192a4e1436a058c9cfd7830deac72424b/t/etap_t_006.erl
erlang
-module(etap_t_006). -export([start/0, start_loop/1]). start() -> etap:plan(3), etap_process:is_pid(spawn(?MODULE, start_loop, [test_group_a]), "Spawned process is a pid"), etap_process:is_alive(spawn(?MODULE, start_loop, [test_group_a]), "Spawned process is alive"), etap_process:is_mfa(spawn(?MODULE, start_loop, [test_group_a]), {?MODULE, start_loop, 1}, "Spawned process has correct MFA"), [ Pid ! done || Pid <- pg2:get_members(test_group_a)], etap:end_tests(). start_loop(GroupName) -> pg2:create(GroupName), pg2:join(GroupName, self()), loop(). loop() -> timer:sleep(10000), receive done -> exit(normal); _ -> ok end, loop().
fbe9a6410363f75350000e6501dd16ce33c84fe9c5a4355827a1f4d3ac8872c1
dfordivam/tenjinreader
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import Language . Javascript . JSaddle . Warp import Reflex . Dom . Core ( mainWidget , mainWidgetWithCss ) import Reflex . hiding ( mainWidget , run ) import Reflex.Dom import Data . FileEmbed import TopWidget import Protolude -- main :: IO () -- main = mainWidget $ text "hi" main :: IO () main = -- mainWidget $ topWidget run 3911 $ mainWidgetWithCss -- ($(embedFile "src/bootstrap.css") <> $(embedFile "src/custom.css")) ( $ ( embedFile " src / slate_bootstrap.min.css " ) < > $ ( embedFile " src / custom.css " ) ) (readable_bootstrap_css <> custom_css) $ topWidget
null
https://raw.githubusercontent.com/dfordivam/tenjinreader/894a6f6b23d52c9c048740c0ea62f4c0f47d9561/frontend/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # main :: IO () main = mainWidget $ text "hi" mainWidget $ topWidget ($(embedFile "src/bootstrap.css") <> $(embedFile "src/custom.css"))
module Main where import Language . Javascript . JSaddle . Warp import Reflex . Dom . Core ( mainWidget , mainWidgetWithCss ) import Reflex . hiding ( mainWidget , run ) import Reflex.Dom import Data . FileEmbed import TopWidget import Protolude main :: IO () main = run 3911 $ mainWidgetWithCss ( $ ( embedFile " src / slate_bootstrap.min.css " ) < > $ ( embedFile " src / custom.css " ) ) (readable_bootstrap_css <> custom_css) $ topWidget
a60b321e4a8a0e78de3cd37b1e7c51cbf415c48fe798088d02bd8552f8afd7dc
tfausak/strive
HTTP.hs
-- | Helpers for dealing with HTTP requests. module Strive.Internal.HTTP ( delete, get, post, put, buildRequest, performRequest, handleResponse, decodeValue, ) where import Data.Aeson (FromJSON, eitherDecode) import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy (ByteString) import Network.HTTP.Client ( Request, Response, method, parseRequest, responseBody, ) import Network.HTTP.Types ( Method, Query, QueryLike, methodDelete, methodGet, methodPost, methodPut, renderQuery, toQuery, ) import Strive.Aliases (Result) import Strive.Client (Client (client_accessToken, client_requester)) -- | Perform an HTTP DELETE request. delete :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) delete = http methodDelete -- | Perform an HTTP GET request. get :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) get = http methodGet -- | Perform an HTTP POST request. post :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) post = http methodPost | Perform an HTTP PUT request . put :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) put = http methodPut -- | Perform an HTTP request. http :: (QueryLike q, FromJSON j) => Method -> Client -> String -> q -> IO (Result j) http httpMethod client resource query = do request <- buildRequest httpMethod client resource query response <- performRequest client request pure (handleResponse response) -- | Build a request. buildRequest :: (QueryLike q) => Method -> Client -> String -> q -> IO Request buildRequest httpMethod client resource query = do request <- parseRequest (buildUrl client resource query) pure request {method = httpMethod} -- | Build a URL. buildUrl :: (QueryLike q) => Client -> String -> q -> String buildUrl client resource query = concat [ "/", resource, unpack (renderQuery True (buildQuery client <> toQuery query)) ] -- | Build a query. buildQuery :: Client -> Query buildQuery client = toQuery [("access_token", client_accessToken client)] -- | Actually perform an HTTP request. performRequest :: Client -> Request -> IO (Response ByteString) performRequest = client_requester -- | Handle decoding a potentially failed response. handleResponse :: (FromJSON j) => Response ByteString -> Result j handleResponse response = case decodeValue response of Left message -> Left (response, message) Right value -> Right value -- | Decode a response body as JSON. decodeValue :: (FromJSON j) => Response ByteString -> Either String j decodeValue response = eitherDecode (responseBody response)
null
https://raw.githubusercontent.com/tfausak/strive/82294daca85ca624ca1e746d7aa4c01d57233356/source/library/Strive/Internal/HTTP.hs
haskell
| Helpers for dealing with HTTP requests. | Perform an HTTP DELETE request. | Perform an HTTP GET request. | Perform an HTTP POST request. | Perform an HTTP request. | Build a request. | Build a URL. | Build a query. | Actually perform an HTTP request. | Handle decoding a potentially failed response. | Decode a response body as JSON.
module Strive.Internal.HTTP ( delete, get, post, put, buildRequest, performRequest, handleResponse, decodeValue, ) where import Data.Aeson (FromJSON, eitherDecode) import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy (ByteString) import Network.HTTP.Client ( Request, Response, method, parseRequest, responseBody, ) import Network.HTTP.Types ( Method, Query, QueryLike, methodDelete, methodGet, methodPost, methodPut, renderQuery, toQuery, ) import Strive.Aliases (Result) import Strive.Client (Client (client_accessToken, client_requester)) delete :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) delete = http methodDelete get :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) get = http methodGet post :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) post = http methodPost | Perform an HTTP PUT request . put :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j) put = http methodPut http :: (QueryLike q, FromJSON j) => Method -> Client -> String -> q -> IO (Result j) http httpMethod client resource query = do request <- buildRequest httpMethod client resource query response <- performRequest client request pure (handleResponse response) buildRequest :: (QueryLike q) => Method -> Client -> String -> q -> IO Request buildRequest httpMethod client resource query = do request <- parseRequest (buildUrl client resource query) pure request {method = httpMethod} buildUrl :: (QueryLike q) => Client -> String -> q -> String buildUrl client resource query = concat [ "/", resource, unpack (renderQuery True (buildQuery client <> toQuery query)) ] buildQuery :: Client -> Query buildQuery client = toQuery [("access_token", client_accessToken client)] performRequest :: Client -> Request -> IO (Response ByteString) performRequest = client_requester handleResponse :: (FromJSON j) => Response ByteString -> Result j handleResponse response = case decodeValue response of Left message -> Left (response, message) Right value -> Right value decodeValue :: (FromJSON j) => Response ByteString -> Either String j decodeValue response = eitherDecode (responseBody response)
3d7d18538ecf675f1721d542597d908ed21188f2b7d48436ee9c691dc5ac289e
polytypic/f-omega-mu
FomPP.mli
open FomPPrint module Kind : sig module Numbering : sig type t val create : unit -> t end val pp : ?numbering:Numbering.t -> FomAST.Kind.t -> document val pp_annot : ?numbering:Numbering.t -> FomAST.Kind.t -> document val to_string : ?numbering:Numbering.t -> FomAST.Kind.t -> string end module Label : sig val pp : FomAST.Label.t -> document end module Typ : sig module Const : sig val pp : FomAST.Typ.Const.t -> document end module Var : sig val pp : ?hr:bool -> FomAST.Typ.Var.t -> document end val hanging : ([> ('t, 'k) FomAST.Typ.Core.f] as 't) -> (document * document) option val pp : ?hr:bool -> ?pp_annot:(FomAST.Kind.t -> document) -> ([< ('t, FomAST.Kind.t) FomAST.Typ.f > `App `Const `For `Lam `Mu `Row `Var] as 't) -> document val to_string : ([< ('t, FomAST.Kind.t) FomAST.Typ.f > `App `Const `For `Lam `Mu `Row `Var] as 't) -> string end module Exp : sig module Var : sig val pp : ?hr:bool -> FomAST.Exp.Var.t -> document end module Const : sig val pp' : ('nat -> document) -> ('t -> document) -> ('nat, 't) FomAST.Exp.Const.t -> document val pp : (Bigint.t, FomAST.Typ.t) FomAST.Exp.Const.t -> document end end
null
https://raw.githubusercontent.com/polytypic/f-omega-mu/92590f4ba55d96870dbe7f7d3400d5a4ce8683f0/src/main/FomPP/FomPP.mli
ocaml
open FomPPrint module Kind : sig module Numbering : sig type t val create : unit -> t end val pp : ?numbering:Numbering.t -> FomAST.Kind.t -> document val pp_annot : ?numbering:Numbering.t -> FomAST.Kind.t -> document val to_string : ?numbering:Numbering.t -> FomAST.Kind.t -> string end module Label : sig val pp : FomAST.Label.t -> document end module Typ : sig module Const : sig val pp : FomAST.Typ.Const.t -> document end module Var : sig val pp : ?hr:bool -> FomAST.Typ.Var.t -> document end val hanging : ([> ('t, 'k) FomAST.Typ.Core.f] as 't) -> (document * document) option val pp : ?hr:bool -> ?pp_annot:(FomAST.Kind.t -> document) -> ([< ('t, FomAST.Kind.t) FomAST.Typ.f > `App `Const `For `Lam `Mu `Row `Var] as 't) -> document val to_string : ([< ('t, FomAST.Kind.t) FomAST.Typ.f > `App `Const `For `Lam `Mu `Row `Var] as 't) -> string end module Exp : sig module Var : sig val pp : ?hr:bool -> FomAST.Exp.Var.t -> document end module Const : sig val pp' : ('nat -> document) -> ('t -> document) -> ('nat, 't) FomAST.Exp.Const.t -> document val pp : (Bigint.t, FomAST.Typ.t) FomAST.Exp.Const.t -> document end end
c98122301a5a0a9fe72de57acda35ea2adf19b1721371166cd81af12d878aa85
genenetwork/guix-bioinformatics
genenetwork.scm
(define-module (gn services genenetwork)) (use-modules (gnu) (ice-9 match) (past packages python) (past packages web) (gn packages genenetwork) (gn packages python24)) (use-service-modules web) (define %default-httpd22-modules (map (match-lambda ((name file) (httpd-module (name name) (file file)))) '(("authn_file_module" "modules/mod_authn_file.so") ("authn_dbm_module" "modules/mod_authn_dbm.so") ("authn_anon_module" "modules/mod_authn_anon.so") ("authn_dbd_module" "modules/mod_authn_dbd.so") ("authn_default_module" "modules/mod_authn_default.so") ("authz_host_module" "modules/mod_authz_host.so") ("authz_groupfile_module" "modules/mod_authz_groupfile.so") ("authz_user_module" "modules/mod_authz_user.so") ("authz_dbm_module" "modules/mod_authz_dbm.so") ("authz_owner_module" "modules/mod_authz_owner.so") ("authz_default_module" "modules/mod_authz_default.so") ("auth_basic_module" "modules/mod_auth_basic.so") ("auth_digest_module" "modules/mod_auth_digest.so") ("dbd_module" "modules/mod_dbd.so") ("dumpio_module" "modules/mod_dumpio.so") ("reqtimeout_module" "modules/mod_reqtimeout.so") ("ext_filter_module" "modules/mod_ext_filter.so") ("include_module" "modules/mod_include.so") ("filter_module" "modules/mod_filter.so") ("substitute_module" "modules/mod_substitute.so") ("log_config_module" "modules/mod_log_config.so") ("logio_module" "modules/mod_logio.so") ("env_module" "modules/mod_env.so") ("mime_magic_module" "modules/mod_mime_magic.so") ("expires_module" "modules/mod_expires.so") ("headers_module" "modules/mod_headers.so") ("ident_module" "modules/mod_ident.so") ("setenvif_module" "modules/mod_setenvif.so") ("version_module" "modules/mod_version.so") ("ssl_module" "modules/mod_ssl.so") ("mime_module" "modules/mod_mime.so") ("dav_module" "modules/mod_dav.so") ("status_module" "modules/mod_status.so") ("autoindex_module" "modules/mod_autoindex.so") ("asis_module" "modules/mod_asis.so") ("info_module" "modules/mod_info.so") ("cgi_module" "modules/mod_cgi.so") ("dav_fs_module" "modules/mod_dav_fs.so") ("vhost_alias_module" "modules/mod_vhost_alias.so") ("negotiation_module" "modules/mod_negotiation.so") ("dir_module" "modules/mod_dir.so") ("imagemap_module" "modules/mod_imagemap.so") ("actions_module" "modules/mod_actions.so") ("speling_module" "modules/mod_speling.so") ("userdir_module" "modules/mod_userdir.so") ("alias_module" "modules/mod_alias.so") ("rewrite_module" "modules/mod_rewrite.so")))) (operating-system (host-name "genenetwork") (timezone "Etc/UTC") (locale "en_US.utf8") (bootloader (bootloader-configuration (bootloader grub-bootloader) (target "does-not-matter"))) (file-systems %base-file-systems) No firmware for VMs (firmware '()) (packages (cons* python-2.4 python24-htmlgen-GN1 python24-json-GN1 python24-mysqlclient ; MySQLdb python24-numarray python24-piddle python24-pp python24-pyx python24-pyxlwriter python24-qtlreaper python24-rpy2 python24-svg-GN1 %base-packages)) (services (list (service special-files-service-type ;; The genotypes folder doesn't have it's shebangs patched. `(("/usr/bin/python" ,(file-append python-2.4 "/bin/python")))) (service httpd-service-type (httpd-configuration Must be a httpd-2.2 variant . (package httpd22-with-mod-python) (config (httpd-config-file (server-name "gn1-test.genenetwork.org") ;; Defaults to httpd, should be same as 'package' above. (server-root httpd22-with-mod-python) (user "nobody") (group "root") ;; Only while debugging (pid-file "/tmp/httpd-genenetwork1") (error-log "/tmp/httpd-genenetwork1-error-log") (listen '("8042")) (modules (cons* (httpd-module (name "python_module") (file "modules/mod_python.so")) %default-httpd22-modules)) (extra-config (list "\ TypesConfig " httpd22-with-mod-python "/etc/httpd/mime.types DefaultType application/octet-stream # DocumentRoot MUST NOT be in the PythonPath. Because genenetwork1 must be in PythonPath we leave the document-root keyword above unset. PythonPath \"sys.path+['/run/current-system/profile/lib/python2.4', '/run/current-system/profile/lib/python2.4/site-packages', '" genenetwork1 "/web/webqtl']\" # same as 'listen' above NameVirtualHost *:8042 <VirtualHost *:8042> DocumentRoot "genenetwork1 "/web </VirtualHost> <Directory " genenetwork1 "/web/webqtl> PythonOption session FileSession #what is the difference between these two? #AddHandler mod_python .py SetHandler python-program #publisher has more debug information PythonHandler " genenetwork1 "/web/webqtl/main.py #PythonHandler mod_python.publisher #PythonHandler mod_python.cgihandler # only while debugging: PythonDebug On </Directory> # only while debugging: <Location /mpinfo> SetHandler python-program PythonHandler mod_python.testhandler </Location>"))))))))) guix system container -L /path / to / guix - past / modules/ -L /path / to / guix - bioinformatics/ /path / to / guix - bioinformatics / gn / services / genenetwork.scm --network --expose=/gnshare / gn / web / genotypes ;; xdg-open :8042
null
https://raw.githubusercontent.com/genenetwork/guix-bioinformatics/9e1e668e4f9f9e2b595620fda831da0525db4095/gn/services/genenetwork.scm
scheme
MySQLdb The genotypes folder doesn't have it's shebangs patched. Defaults to httpd, should be same as 'package' above. Only while debugging xdg-open :8042
(define-module (gn services genenetwork)) (use-modules (gnu) (ice-9 match) (past packages python) (past packages web) (gn packages genenetwork) (gn packages python24)) (use-service-modules web) (define %default-httpd22-modules (map (match-lambda ((name file) (httpd-module (name name) (file file)))) '(("authn_file_module" "modules/mod_authn_file.so") ("authn_dbm_module" "modules/mod_authn_dbm.so") ("authn_anon_module" "modules/mod_authn_anon.so") ("authn_dbd_module" "modules/mod_authn_dbd.so") ("authn_default_module" "modules/mod_authn_default.so") ("authz_host_module" "modules/mod_authz_host.so") ("authz_groupfile_module" "modules/mod_authz_groupfile.so") ("authz_user_module" "modules/mod_authz_user.so") ("authz_dbm_module" "modules/mod_authz_dbm.so") ("authz_owner_module" "modules/mod_authz_owner.so") ("authz_default_module" "modules/mod_authz_default.so") ("auth_basic_module" "modules/mod_auth_basic.so") ("auth_digest_module" "modules/mod_auth_digest.so") ("dbd_module" "modules/mod_dbd.so") ("dumpio_module" "modules/mod_dumpio.so") ("reqtimeout_module" "modules/mod_reqtimeout.so") ("ext_filter_module" "modules/mod_ext_filter.so") ("include_module" "modules/mod_include.so") ("filter_module" "modules/mod_filter.so") ("substitute_module" "modules/mod_substitute.so") ("log_config_module" "modules/mod_log_config.so") ("logio_module" "modules/mod_logio.so") ("env_module" "modules/mod_env.so") ("mime_magic_module" "modules/mod_mime_magic.so") ("expires_module" "modules/mod_expires.so") ("headers_module" "modules/mod_headers.so") ("ident_module" "modules/mod_ident.so") ("setenvif_module" "modules/mod_setenvif.so") ("version_module" "modules/mod_version.so") ("ssl_module" "modules/mod_ssl.so") ("mime_module" "modules/mod_mime.so") ("dav_module" "modules/mod_dav.so") ("status_module" "modules/mod_status.so") ("autoindex_module" "modules/mod_autoindex.so") ("asis_module" "modules/mod_asis.so") ("info_module" "modules/mod_info.so") ("cgi_module" "modules/mod_cgi.so") ("dav_fs_module" "modules/mod_dav_fs.so") ("vhost_alias_module" "modules/mod_vhost_alias.so") ("negotiation_module" "modules/mod_negotiation.so") ("dir_module" "modules/mod_dir.so") ("imagemap_module" "modules/mod_imagemap.so") ("actions_module" "modules/mod_actions.so") ("speling_module" "modules/mod_speling.so") ("userdir_module" "modules/mod_userdir.so") ("alias_module" "modules/mod_alias.so") ("rewrite_module" "modules/mod_rewrite.so")))) (operating-system (host-name "genenetwork") (timezone "Etc/UTC") (locale "en_US.utf8") (bootloader (bootloader-configuration (bootloader grub-bootloader) (target "does-not-matter"))) (file-systems %base-file-systems) No firmware for VMs (firmware '()) (packages (cons* python-2.4 python24-htmlgen-GN1 python24-json-GN1 python24-numarray python24-piddle python24-pp python24-pyx python24-pyxlwriter python24-qtlreaper python24-rpy2 python24-svg-GN1 %base-packages)) (services (list (service special-files-service-type `(("/usr/bin/python" ,(file-append python-2.4 "/bin/python")))) (service httpd-service-type (httpd-configuration Must be a httpd-2.2 variant . (package httpd22-with-mod-python) (config (httpd-config-file (server-name "gn1-test.genenetwork.org") (server-root httpd22-with-mod-python) (user "nobody") (group "root") (pid-file "/tmp/httpd-genenetwork1") (error-log "/tmp/httpd-genenetwork1-error-log") (listen '("8042")) (modules (cons* (httpd-module (name "python_module") (file "modules/mod_python.so")) %default-httpd22-modules)) (extra-config (list "\ TypesConfig " httpd22-with-mod-python "/etc/httpd/mime.types DefaultType application/octet-stream # DocumentRoot MUST NOT be in the PythonPath. Because genenetwork1 must be in PythonPath we leave the document-root keyword above unset. PythonPath \"sys.path+['/run/current-system/profile/lib/python2.4', '/run/current-system/profile/lib/python2.4/site-packages', '" genenetwork1 "/web/webqtl']\" # same as 'listen' above NameVirtualHost *:8042 <VirtualHost *:8042> DocumentRoot "genenetwork1 "/web </VirtualHost> <Directory " genenetwork1 "/web/webqtl> PythonOption session FileSession #what is the difference between these two? #AddHandler mod_python .py SetHandler python-program #publisher has more debug information PythonHandler " genenetwork1 "/web/webqtl/main.py #PythonHandler mod_python.publisher #PythonHandler mod_python.cgihandler # only while debugging: PythonDebug On </Directory> # only while debugging: <Location /mpinfo> SetHandler python-program PythonHandler mod_python.testhandler </Location>"))))))))) guix system container -L /path / to / guix - past / modules/ -L /path / to / guix - bioinformatics/ /path / to / guix - bioinformatics / gn / services / genenetwork.scm --network --expose=/gnshare / gn / web / genotypes
85541b861fdf25321d38c1b50e4a8d9a7c4403a3be36c0afd966d1c9cc544ac2
danieljharvey/mimsa
Builder.hs
# LANGUAGE DerivingStrategies # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Builder (doJobsIO, doJobsPure, getMissing, Plan (..), State (..), Job, Inputs) where import qualified Control.Concurrent.STM as STM import Control.Monad.Identity import Data.Foldable (traverse_) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Set (Set) import qualified Data.Set as S import qualified Ki import System.IO.Unsafe -- a thing we want to do data Plan k input = Plan { jbDeps :: Set k, jbInput :: input } deriving stock (Eq, Ord, Show) -- how we're going to do it type Job m e k input output = Map k output -> input -> m (Either e output) type Inputs k input = Map k (Plan k input) -- state of the job data State k input output = State { stInputs :: Inputs k input, stOutputs :: Map k output } deriving stock (Eq, Ord, Show) -- list the required deps that cannot possibly be provided (usually indicates -- an error with implementation) getMissing :: (Ord k) => State k input output -> Set k getMissing (State inputs outputs) = let getMissingDeps (Plan deps _) = S.filter (\dep -> dep `M.notMember` inputs && dep `M.notMember` outputs) deps in mconcat (getMissingDeps <$> M.elems inputs) getReadyJobs :: (Ord k) => Either e (State k input output) -> Set k -> Inputs k input getReadyJobs (Left _) _ = mempty getReadyJobs (Right st) inFlight = -- disregard any jobs that are inflight let inputs = M.filterWithKey (\k _ -> S.notMember k inFlight) (stInputs st) in -- get jobs we are ready to do M.filter ( \plan -> let requiredKeys = jbDeps plan in and ((\depK -> M.member depK (stOutputs st)) <$> S.toList requiredKeys) ) inputs -- | remove job from input, add it to output markJobAsDone :: (Ord k) => k -> output -> Either e (State k input output) -> Either e (State k input output) markJobAsDone _ _ (Left e) = Left e markJobAsDone k output (Right st) = Right $ State (M.delete k (stInputs st)) (stOutputs st <> M.singleton k output) -- unsafely do the things doJobsPure :: forall e k input output. (Ord k, Show k) => Job Identity e k input output -> State k input output -> Either e (State k input output) doJobsPure fn st = unsafePerformIO (doJobsIO ioFn st) where ioFn dep input = pure $ runIdentity $ fn dep input -- run through a list of jobs and do them doJobsIO :: forall e k input output. (Ord k, Show k) => Job IO e k input output -> State k input output -> IO (Either e (State k input output)) doJobsIO fn st = do let missingDeps = getMissing st if not (S.null missingDeps) then error ("Missing deps in build: " <> show missingDeps) else do Ki.scoped $ \scope -> do mutableState <- STM.newTVarIO (Right st) inFlight <- STM.newTVarIO mempty -- list of keys currently being built let getReadyJobsIO = getReadyJobs <$> STM.readTVarIO mutableState <*> STM.readTVarIO inFlight readyJobs <- getReadyJobsIO let doJob :: (k, Plan k input) -> IO () doJob (k, plan) = do -- mark this job as inflight filteredOutput <- STM.atomically $ do STM.modifyTVar' inFlight (S.insert k) eitherState <- STM.readTVar mutableState pure $ case eitherState of Left _ -> mempty Right state -> M.filterWithKey (\depK _ -> S.member depK (jbDeps plan)) (stOutputs state) -- do the work newOutput <- fn filteredOutput (jbInput plan) case newOutput of Left e -> STM.atomically $ STM.writeTVar mutableState (Left e) Right success -> do -- update the state _ <- STM.atomically $ do STM.modifyTVar' mutableState (markJobAsDone k success) STM.modifyTVar' inFlight (S.delete k) -- get the resulting jobs newReadyJobs <- getReadyJobsIO -- run them traverse_ (Ki.fork scope . doJob) (M.toList newReadyJobs) start first jobs traverse_ (Ki.fork scope . doJob) (M.toList readyJobs) -- wait for all the sillyness to stop STM.atomically $ Ki.awaitAll scope -- read the var and give up STM.readTVarIO mutableState get jobs available to start , fork them , and add key to ` inFlight ` -- each one, when done, updates state, and then checks again what can -- be started, and forks those -- when no more inputs (and nothing else in flight, return state)
null
https://raw.githubusercontent.com/danieljharvey/mimsa/703513748847b3dc9be99573afb582ec05244f3f/builder/src/Builder.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # a thing we want to do how we're going to do it state of the job list the required deps that cannot possibly be provided (usually indicates an error with implementation) disregard any jobs that are inflight get jobs we are ready to do | remove job from input, add it to output unsafely do the things run through a list of jobs and do them list of keys currently being built mark this job as inflight do the work update the state get the resulting jobs run them wait for all the sillyness to stop read the var and give up each one, when done, updates state, and then checks again what can be started, and forks those when no more inputs (and nothing else in flight, return state)
# LANGUAGE DerivingStrategies # # LANGUAGE ScopedTypeVariables # module Builder (doJobsIO, doJobsPure, getMissing, Plan (..), State (..), Job, Inputs) where import qualified Control.Concurrent.STM as STM import Control.Monad.Identity import Data.Foldable (traverse_) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Set (Set) import qualified Data.Set as S import qualified Ki import System.IO.Unsafe data Plan k input = Plan { jbDeps :: Set k, jbInput :: input } deriving stock (Eq, Ord, Show) type Job m e k input output = Map k output -> input -> m (Either e output) type Inputs k input = Map k (Plan k input) data State k input output = State { stInputs :: Inputs k input, stOutputs :: Map k output } deriving stock (Eq, Ord, Show) getMissing :: (Ord k) => State k input output -> Set k getMissing (State inputs outputs) = let getMissingDeps (Plan deps _) = S.filter (\dep -> dep `M.notMember` inputs && dep `M.notMember` outputs) deps in mconcat (getMissingDeps <$> M.elems inputs) getReadyJobs :: (Ord k) => Either e (State k input output) -> Set k -> Inputs k input getReadyJobs (Left _) _ = mempty getReadyJobs (Right st) inFlight = let inputs = M.filterWithKey (\k _ -> S.notMember k inFlight) (stInputs st) M.filter ( \plan -> let requiredKeys = jbDeps plan in and ((\depK -> M.member depK (stOutputs st)) <$> S.toList requiredKeys) ) inputs markJobAsDone :: (Ord k) => k -> output -> Either e (State k input output) -> Either e (State k input output) markJobAsDone _ _ (Left e) = Left e markJobAsDone k output (Right st) = Right $ State (M.delete k (stInputs st)) (stOutputs st <> M.singleton k output) doJobsPure :: forall e k input output. (Ord k, Show k) => Job Identity e k input output -> State k input output -> Either e (State k input output) doJobsPure fn st = unsafePerformIO (doJobsIO ioFn st) where ioFn dep input = pure $ runIdentity $ fn dep input doJobsIO :: forall e k input output. (Ord k, Show k) => Job IO e k input output -> State k input output -> IO (Either e (State k input output)) doJobsIO fn st = do let missingDeps = getMissing st if not (S.null missingDeps) then error ("Missing deps in build: " <> show missingDeps) else do Ki.scoped $ \scope -> do mutableState <- STM.newTVarIO (Right st) let getReadyJobsIO = getReadyJobs <$> STM.readTVarIO mutableState <*> STM.readTVarIO inFlight readyJobs <- getReadyJobsIO let doJob :: (k, Plan k input) -> IO () doJob (k, plan) = do filteredOutput <- STM.atomically $ do STM.modifyTVar' inFlight (S.insert k) eitherState <- STM.readTVar mutableState pure $ case eitherState of Left _ -> mempty Right state -> M.filterWithKey (\depK _ -> S.member depK (jbDeps plan)) (stOutputs state) newOutput <- fn filteredOutput (jbInput plan) case newOutput of Left e -> STM.atomically $ STM.writeTVar mutableState (Left e) Right success -> do _ <- STM.atomically $ do STM.modifyTVar' mutableState (markJobAsDone k success) STM.modifyTVar' inFlight (S.delete k) newReadyJobs <- getReadyJobsIO traverse_ (Ki.fork scope . doJob) (M.toList newReadyJobs) start first jobs traverse_ (Ki.fork scope . doJob) (M.toList readyJobs) STM.atomically $ Ki.awaitAll scope STM.readTVarIO mutableState get jobs available to start , fork them , and add key to ` inFlight `
ab547fbeb58ff7fcdb609a03d1d5c15a9cf8d956f6556ddfd92260bbe4399d18
lichenscript/lichenscript
linker.mli
open Lichenscript_typing type t val create: prog:Program.t -> unit -> t val link_from_entry: t -> verbose:bool -> int -> Typedtree.Declaration.t list val set_module: t -> string -> Module.t -> unit val get_module: t -> string -> Module.t option val has_module: t -> string -> bool val iter_modules: t -> f:(Module.t -> unit) -> unit val add_external_resource: t -> string -> unit val external_resources: t -> string list
null
https://raw.githubusercontent.com/lichenscript/lichenscript/0b03566b85079e5360ec75fdeb120c028c3d39dd/lib/resolver/linker.mli
ocaml
open Lichenscript_typing type t val create: prog:Program.t -> unit -> t val link_from_entry: t -> verbose:bool -> int -> Typedtree.Declaration.t list val set_module: t -> string -> Module.t -> unit val get_module: t -> string -> Module.t option val has_module: t -> string -> bool val iter_modules: t -> f:(Module.t -> unit) -> unit val add_external_resource: t -> string -> unit val external_resources: t -> string list
8a500cb5f5d6dc1ce2e89ebc87faf6c06307d72971238a7cd450eac9bce63ddf
papertrail/slack-hooks
tender.clj
(ns slack-hooks.service.tender (:require [slack-hooks.slack :as slack] [clojurewerkz.urly.core :as urly])) (def tender-base-url (System/getenv "TENDER_BASE_URL")) (def tender-username (or (System/getenv "TENDER_USERNAME") "tender")) (def tender-avatar (System/getenv "TENDER_AVATAR")) (def tender-color (or (System/getenv "TENDER_COLOR") "#6DB4D3")) (def tender-slack-url (System/getenv "TENDER_SLACK_URL")) (defn truncate-string "Take a string and limit it to a certain number of characters" [string limit] (let [truncate-limit (- limit 3)] (if (<= (count string) truncate-limit) string (str (subs string 0 truncate-limit) "...")))) (defn swap-base-url "Takes a URL and base URL and returns a new URL that is the original with the protocl and host of the base." [url base-url] (if base-url (let [base-url (urly/url-like base-url) protocol (urly/protocol-of base-url) host (urly/host-of base-url) swapped-url (-> url urly/url-like (.mutateProtocol protocol) (.mutateHost host))] (str swapped-url)) url)) (defn internal-message-link "Returns an internal URL to the message suitable for support staff." [message] (str (swap-base-url (:href message) tender-base-url) "#comment_" (:last-comment-id message))) (defn extract-system-message "Returns the important part of a system message or nil." [text] (last (re-find #"(?:The discussion has been|Discussion was) (.*?)\.?$" text))) (defn message-action "Returns an action that describes the message." [message] (let [system-message (:system-message message)] (cond (:new-discussion? message) "opened" (:resolved? message) "resolved" system-message system-message (and (:internal? message) (not (:system-message? message))) "updated (internal)" :else "updated"))) (defn message-from-request "Accepts a map of the body of a Tender webhook and returns a map describing the message." [request] (let [payload (:body request) {:keys [discussion html_href author_name body number internal resolution system_message]} payload {:keys [title last_comment_id]} discussion extracted-system-message (extract-system-message body)] {:href html_href :number (:number discussion) :title title :author author_name :last-comment-id last_comment_id :body body :new-discussion? (= 1 number) :internal? internal :resolved? (= true resolution) :system-message? system_message :system-message (if system_message extracted-system-message) :system-body (if (and system_message (not extracted-system-message)) (str ": " body) "")})) (defn formatted-message "Returns a string describing the given message" [request] (let [message (message-from-request request)] (format "#%d <%s|\"%s\"> was %s by %s%s" (:number message) (internal-message-link message) (slack/escape (truncate-string (:title message) 100)) (message-action message) (:author message) (:system-body message)))) (defn tender "Accepts an HTTP request from a Tender webhook and reports the details to a Slack webhook." [request] (slack/notify {:slack-url (or (-> request :params :slack_url) tender-slack-url) :username tender-username :icon_url tender-avatar :attachments [{:text (formatted-message request) :color tender-color}]}))
null
https://raw.githubusercontent.com/papertrail/slack-hooks/e9cfdbfee40e678be956416366684ee22d6cb282/src/slack_hooks/service/tender.clj
clojure
(ns slack-hooks.service.tender (:require [slack-hooks.slack :as slack] [clojurewerkz.urly.core :as urly])) (def tender-base-url (System/getenv "TENDER_BASE_URL")) (def tender-username (or (System/getenv "TENDER_USERNAME") "tender")) (def tender-avatar (System/getenv "TENDER_AVATAR")) (def tender-color (or (System/getenv "TENDER_COLOR") "#6DB4D3")) (def tender-slack-url (System/getenv "TENDER_SLACK_URL")) (defn truncate-string "Take a string and limit it to a certain number of characters" [string limit] (let [truncate-limit (- limit 3)] (if (<= (count string) truncate-limit) string (str (subs string 0 truncate-limit) "...")))) (defn swap-base-url "Takes a URL and base URL and returns a new URL that is the original with the protocl and host of the base." [url base-url] (if base-url (let [base-url (urly/url-like base-url) protocol (urly/protocol-of base-url) host (urly/host-of base-url) swapped-url (-> url urly/url-like (.mutateProtocol protocol) (.mutateHost host))] (str swapped-url)) url)) (defn internal-message-link "Returns an internal URL to the message suitable for support staff." [message] (str (swap-base-url (:href message) tender-base-url) "#comment_" (:last-comment-id message))) (defn extract-system-message "Returns the important part of a system message or nil." [text] (last (re-find #"(?:The discussion has been|Discussion was) (.*?)\.?$" text))) (defn message-action "Returns an action that describes the message." [message] (let [system-message (:system-message message)] (cond (:new-discussion? message) "opened" (:resolved? message) "resolved" system-message system-message (and (:internal? message) (not (:system-message? message))) "updated (internal)" :else "updated"))) (defn message-from-request "Accepts a map of the body of a Tender webhook and returns a map describing the message." [request] (let [payload (:body request) {:keys [discussion html_href author_name body number internal resolution system_message]} payload {:keys [title last_comment_id]} discussion extracted-system-message (extract-system-message body)] {:href html_href :number (:number discussion) :title title :author author_name :last-comment-id last_comment_id :body body :new-discussion? (= 1 number) :internal? internal :resolved? (= true resolution) :system-message? system_message :system-message (if system_message extracted-system-message) :system-body (if (and system_message (not extracted-system-message)) (str ": " body) "")})) (defn formatted-message "Returns a string describing the given message" [request] (let [message (message-from-request request)] (format "#%d <%s|\"%s\"> was %s by %s%s" (:number message) (internal-message-link message) (slack/escape (truncate-string (:title message) 100)) (message-action message) (:author message) (:system-body message)))) (defn tender "Accepts an HTTP request from a Tender webhook and reports the details to a Slack webhook." [request] (slack/notify {:slack-url (or (-> request :params :slack_url) tender-slack-url) :username tender-username :icon_url tender-avatar :attachments [{:text (formatted-message request) :color tender-color}]}))
3149080ad670d9dbed084c0e27a89fb0f56cc140fd9cbd688212f9c31416772c
onaio/milia
retry_test.clj
(ns milia.utils.retry-test (:require [chimera.seq :refer [mapply]] [midje.sweet :refer :all] [milia.utils.retry :refer :all] [milia.api.http :refer [parse-http]])) (facts "about retry-parse-http" (fact "should return result of mapply parse-http" (retry-parse-http :method :url) => :response (provided (mapply parse-http :method :url nil) => :response)) (doseq [status default-retry-for-statuses] (fact "should retry for status in retry statuses" (retry-parse-http :method :url) => {:status status} (provided (mapply parse-http :method :url nil) => {:status status} :times 2))))
null
https://raw.githubusercontent.com/onaio/milia/c68b612bd640aa2499e4ac2f907a7ef793d0820a/test/clj/milia/utils/retry_test.clj
clojure
(ns milia.utils.retry-test (:require [chimera.seq :refer [mapply]] [midje.sweet :refer :all] [milia.utils.retry :refer :all] [milia.api.http :refer [parse-http]])) (facts "about retry-parse-http" (fact "should return result of mapply parse-http" (retry-parse-http :method :url) => :response (provided (mapply parse-http :method :url nil) => :response)) (doseq [status default-retry-for-statuses] (fact "should retry for status in retry statuses" (retry-parse-http :method :url) => {:status status} (provided (mapply parse-http :method :url nil) => {:status status} :times 2))))
edd605875748bad772ea0efd0e0664a609265e422f4bf96de7e8da98eb256e0d
rizo/snowflake-os
play.ml
open Bigarray open BlockIO open FileSystems open Ext2fs provide a static buffer size of 65536 bytes let ba = Array1.create int8_unsigned c_layout 65536 let init () = match !FileSystems.fs with | None -> () | Some fs -> (* add a command to shell thing *) let did_it = ref false in let play name = begin try let inode = fs.read_inode begin (List.find begin fun entry -> entry.name = name && entry.file_type = 1 end !FileSystems.dirs).inode end in Vt100.printf "play: file %s....\n" name; let limit = inode.i_size in let rec loop pos = if pos = limit then () else begin let len = fs.read_file_range_with_buffer inode ba pos in let ba = if len <> Array1.dim ba then Array1.sub ba 0 len else ba in if pos = 0 then begin AudioMixer.play begin AudioMixer.Wave.read begin BlockIO.make ba end end end else begin AudioMixer.play_raw begin BlockIO.make ba end end; loop (pos + Array1.dim ba) end in loop 0 with Not_found -> Vt100.printf "play: file not found, or not a file\n" end; did_it := true in let play_def () = if !did_it = false then Vt100.printf "play: require a filename\n"; did_it := true in Shell.add_command "play" play_def [] ~anon:play
null
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/play.ml
ocaml
add a command to shell thing
open Bigarray open BlockIO open FileSystems open Ext2fs provide a static buffer size of 65536 bytes let ba = Array1.create int8_unsigned c_layout 65536 let init () = match !FileSystems.fs with | None -> () | Some fs -> let did_it = ref false in let play name = begin try let inode = fs.read_inode begin (List.find begin fun entry -> entry.name = name && entry.file_type = 1 end !FileSystems.dirs).inode end in Vt100.printf "play: file %s....\n" name; let limit = inode.i_size in let rec loop pos = if pos = limit then () else begin let len = fs.read_file_range_with_buffer inode ba pos in let ba = if len <> Array1.dim ba then Array1.sub ba 0 len else ba in if pos = 0 then begin AudioMixer.play begin AudioMixer.Wave.read begin BlockIO.make ba end end end else begin AudioMixer.play_raw begin BlockIO.make ba end end; loop (pos + Array1.dim ba) end in loop 0 with Not_found -> Vt100.printf "play: file not found, or not a file\n" end; did_it := true in let play_def () = if !did_it = false then Vt100.printf "play: require a filename\n"; did_it := true in Shell.add_command "play" play_def [] ~anon:play
ee359deccfa2d4dc4cdfcb13667fae5ef2b324a396167ba85995975345f0315c
softwarelanguageslab/maf
R5RS_scp1_list-compare-n-5.scm
; Changes: * removed : 0 * added : 1 * swaps : 0 * negated predicates : 1 * swapped branches : 2 * calls to i d fun : 1 (letrec ((compare (lambda (lijst1 lijst2) (if (let ((__or_res (null? lijst1))) (<change> (if __or_res __or_res (null? lijst2)) ((lambda (x) x) (if (<change> __or_res (not __or_res)) __or_res (null? lijst2))))) 0 (if (eq? (car lijst1) (car lijst2)) (+ 1 (compare (cdr lijst1) (cdr lijst2))) 0)))) (compare-iter (lambda (lijst1 lijst2) (letrec ((loop (lambda (l1 l2 res) (if (let ((__or_res (null? l1))) (if __or_res __or_res (null? l2))) res (if (eq? (car l1) (car l2)) (loop (cdr l1) (cdr l2) (+ res 1)) res))))) (loop lijst1 lijst2 0)))) (algemene-compare (lambda (lijst1 lijst2 test) (<change> () car) (if (let ((__or_res (null? lijst1))) (if __or_res __or_res (null? lijst2))) (<change> 0 (if (test (car lijst1) (car lijst2)) (+ 1 (algemene-compare (cdr lijst1) (cdr lijst2) test)) 0)) (<change> (if (test (car lijst1) (car lijst2)) (+ 1 (algemene-compare (cdr lijst1) (cdr lijst2) test)) 0) 0)))) (compare-greater (lambda (lijst1 lijst2) (algemene-compare lijst1 lijst2 >)))) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (<change> (if (= (compare (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (if (= (compare-iter (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (= (compare-greater (__toplevel_cons 3 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 5 ())))))) (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 8 (__toplevel_cons 5 (__toplevel_cons 5 ()))))))) 3) #f) #f) #f) #f) #f) #f) (<change> #f (if (= (compare (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (if (= (compare-iter (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (= (compare-greater (__toplevel_cons 3 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 5 ())))))) (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 8 (__toplevel_cons 5 (__toplevel_cons 5 ()))))))) 3) #f) #f) #f) #f) #f))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_list-compare-n-5.scm
scheme
Changes:
* removed : 0 * added : 1 * swaps : 0 * negated predicates : 1 * swapped branches : 2 * calls to i d fun : 1 (letrec ((compare (lambda (lijst1 lijst2) (if (let ((__or_res (null? lijst1))) (<change> (if __or_res __or_res (null? lijst2)) ((lambda (x) x) (if (<change> __or_res (not __or_res)) __or_res (null? lijst2))))) 0 (if (eq? (car lijst1) (car lijst2)) (+ 1 (compare (cdr lijst1) (cdr lijst2))) 0)))) (compare-iter (lambda (lijst1 lijst2) (letrec ((loop (lambda (l1 l2 res) (if (let ((__or_res (null? l1))) (if __or_res __or_res (null? l2))) res (if (eq? (car l1) (car l2)) (loop (cdr l1) (cdr l2) (+ res 1)) res))))) (loop lijst1 lijst2 0)))) (algemene-compare (lambda (lijst1 lijst2 test) (<change> () car) (if (let ((__or_res (null? lijst1))) (if __or_res __or_res (null? lijst2))) (<change> 0 (if (test (car lijst1) (car lijst2)) (+ 1 (algemene-compare (cdr lijst1) (cdr lijst2) test)) 0)) (<change> (if (test (car lijst1) (car lijst2)) (+ 1 (algemene-compare (cdr lijst1) (cdr lijst2) test)) 0) 0)))) (compare-greater (lambda (lijst1 lijst2) (algemene-compare lijst1 lijst2 >)))) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (<change> (if (= (compare (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (if (= (compare-iter (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (= (compare-greater (__toplevel_cons 3 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 5 ())))))) (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 8 (__toplevel_cons 5 (__toplevel_cons 5 ()))))))) 3) #f) #f) #f) #f) #f) #f) (<change> #f (if (= (compare (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ()))))))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'x (__toplevel_cons 'y ())))))) 3) (if (= (compare-iter (__toplevel_cons 'x (__toplevel_cons 'a (__toplevel_cons 'b ()))) (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'd (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))))) 0) (if (= (compare-iter (__toplevel_cons 'a (__toplevel_cons 'b (__toplevel_cons 'c (__toplevel_cons 'e (__toplevel_cons 'f (__toplevel_cons 'g ())))))) (__toplevel_cons 'a (__toplevel_cons 'b ()))) 2) (= (compare-greater (__toplevel_cons 3 (__toplevel_cons 5 (__toplevel_cons 6 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 5 ())))))) (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 8 (__toplevel_cons 5 (__toplevel_cons 5 ()))))))) 3) #f) #f) #f) #f) #f))))
def474f99bbffdba00f47411f0b2540305b6b0437a8cabaa0a2e02bfd314092a
opencog/learn
in-group.scm
; ; in-group.scm ; ; Obtain an in-group of similar words. In-groups are those whose members have a lot in common with one - another . In - groups can be cliques , and ; more generally are almost-cliques. ; Copyright ( c ) 2021 Linas Vepstas ; ; --------------------------------------------------------------------- ; OVERVIEW ; -------- ; Given a word-pair with a high similarity score, expand that word-pair ; into a clique or an almost-clique, such that all similarity scores in ; that clique are no less than epsilon below the similarity score of the ; initial pair. A clique is formed if *all* pair-scores meet this ; requirement. An in-group is formed, if the majority of the scores to ; other members in the in-group are above the epsilon threshold. (use-modules (srfi srfi-1)) (use-modules (ice-9 optargs)) ; for define*-public (define-public (find-in-group SIMFUN WA WB LOWER-BOUND EPSILON TIGHTNESS CANDIDATES) " find-in-group SIMFUN WA WB LOWER-BOUND EPSILON TIGHTNESS CANDIDATES Return an in-group of closely related words. Given two words WA and WB with a high similarity score, find a clique an almost-clique (the in-group), such that all similarity scores in that in-group are greater than LOWER-BOUND and are also no less than EPSILON below the similarity score of the initial pair. A clique is formed if *all* pair-scores meet this requirement. An in-group is formed, if more than a TIGHTNESS fraction of the scores to other members in the in-group are above the epsilon threshold. (A TIGHTNESS of 0.5 means that a simple majority of the in-group meets the a TIGHTNESS of 1.0 means the in - group is a clique . ) Arguments: WA and WB seed the initial in-group. SIMFUN is an function that, given two items, returns a similarity score for those items. Similarities are assumed to be symmetric, that is, (SIMFUN a b) == (SIMFUN b a). Usually, the similarity is a floating point number, but in fact it can be anything that is comparable with greater-than. At this time, all experimental results (and thus, recommended parameter values) have been done ONLY with ranked-MI. The code should still work for other SIMFUN's, but these have not been characterized. LOWER-BOUND is an absolute lower bound on the in-group similarities. All members of the in-group must have similarities that are greater than LOWER-BOUND. Recommended value of 0.0 to 4.0. EPSILON is a relative lower bound on the in-group similarities. Most members of the in-group must have similarities that are within EPSILON of the initial pair. Pairs that are within EPSILON are termed `similar enough`. Recommended value of 0.5 to 8.0. TIGHTNESS is a number between 0 and 1, specifying the fraction of the in-group pairs that must be similar enough to one-another. A TIGHTNESS of 0.5 means that a majority of the pair-relations must be `similar enough`, while a TIGHTNESS of 1.0 means that all of them will be. Recommended value of 0.7. Experiments reveal that results are relatively insensitive to this value, ranging over 0.3 to 1.0. CANDIDATES is a list of individuals to consider adding to the group. Experiments show that the size of the group at first grows slowly as a function of increasing EPSILON, followed by a very rapid increase after some threshold is passed. Obviously, EPSILON should be set below that threshold. Unfortunately, this threshold depends strongly on the initial pair, even when working within the same dataset. " Given the current ingroup INGRP and the CANDIDATE , return # t if the candidate has a similarity score above MINSCORE to at ; least TIGHT other members of the ingroup. Return #f if the ; candidate has a score below LOWER-BOUND to any member of the ; ingroup. (define (accept INGRP CANDIDATE MINSCORE TIGHT) ; There can be at most `maxfail` bad scores (define maxfail (- (length INGRP) TIGHT)) (define failcnt 0) (every (lambda (MEMB) (define score (SIMFUN CANDIDATE MEMB)) (if (< score LOWER-BOUND) (set! failcnt (+ failcnt maxfail 999))) (if (< score MINSCORE) (set! failcnt (+ failcnt 1))) (<= failcnt maxfail) ) INGRP)) (define benchmark (SIMFUN WA WB)) (define minscore (- benchmark EPSILON)) ; Convert fractional TIGHTNESS to an integer. (define (get-tight INGRP) (define insz (length INGRP)) (if (equal? 2 insz) 2 (inexact->exact (round (* TIGHTNESS insz))))) Remove WA , WB from the list of candidates (define clean-cand (filter (lambda (cand) (not (or (equal? cand WA) (equal? cand WB)))) CANDIDATES)) Starting with the minimal clique of ` ( list WA WB ) ` , create ; an ingroup by adding members to the ingroup if that candidate ; has a score no less than `minscore` to at least `TIGHT` members ; of the group. (fold (lambda (CAND INGRP) (if (accept INGRP CAND minscore (get-tight INGRP)) (cons CAND INGRP) INGRP)) (list WA WB) clean-cand) ) ; --------------------------------------------------------------- (define*-public (optimal-in-group SIMFUN WA WB CANDIDATES #:key ; The tightness of the almost-clique. This is the fraction of ; the in-group members that have a similarity above the the threshold . A tightness of 0.5 means the majority of the in - group members are similar to one - another ; a tightness of 1.0 means that ; they all are (and so form a clique.) See `find-in-group` for ; more. (tightness 0.7) ; Size of steps (changes in the threshold) that will be taken. The initial threshold is set to the similarity of WA and WB . ; The threshold is then lowered by steps of epsi-step, until ; stopping conditions are obtained. For MI - similarity , 0.1 is a good step - size . (epsi-step 0.1) ; The largest change in threshold to consider. The threshold will never go below ( similarity of WA and WB ) minus this number . For grammatical - MI , experiments suggest this should be 8.5 . ; Specifically, the grouping of roman numerals is still coherent, despite individual pair - wise MI 's being 8.5 apart . (max-epsi 8.5) ; Lower bound on the similarity between members of the in-group. ; All members of the in-group must have a pair-wise similarity ; greater than this. For MI - similarity , we want similarities greater than about 2.0 or 4.0 . Experiments show 1.0 works OK . (lower-bound 1.0) ; The size of the in-group should not jump by more than this over ; the width of moving window. If it does change by more than this, ; then we assume that the 'knee' has been found, and the search ; is halted. This enforces a max linear growth rate in the size of the ingroup . The default value of 2.5 means the ingroup will not add more than two members over the width of the window . (max-jump 2.5) ; The size of the moving window. The size of the in-group at a ; given threshold is compared to the size of the in-group at ; (threshold + win-size.) If the change in the in-group size ; is more than 'max-jump', then search is halted. For grammatical - MI , a delta - MI of 1.0 seems like a reasonable ; window. (win-size 1.0) ; Hard-coded maximum size of the in-group. We don't return ; in-groups larger than this. (max-size 12) ) " optimal-in-group SIMFUN WA WB CANDIDATES Return an ingroup of closely related words. The initial members of the ingroup are WA and WB. Additional potential members are drawn from CANDIDATES if they are similar-enough to the current ingroup, as measured by the similarity function SIMFUN. This searches for the largest ingroup that is still exclusive. The search is performed by admitting individuals from CANDIDATES, one at a time, if they are judged similar-enough by SIMFUN. The membership requirements are slowly loosened (by dropping the lower bound of what is considered 'similar-enough'), until membership explodes. Then the lower bound is backed off a bit, just before the explosion. Experiments show that as membership requirements are loosened, there is a knee in the size of the group: the group size suddenly explodes. That is, as the similarity threshold is loosened, the size of the group grows slowly at first, and then, at some point, it takes off, growing rapidly (growing 'explosively'). This searches for the largest group below that inflection point. Arguments: WA and WB seed the initial in-group. SIMFUN is an function that, given two items, returns a similarity score for those items. Similarities are assumed to be symmetric, that is, (SIMFUN a b) == (SIMFUN b a). Usually, the similarity is a floating point number, but in fact it can be anything that is comparable with greater-than. For similarities that are floating point numbers, the larger the value, the more similar they are. This function has been experimentally tested only for SIMFUN being ranked-MI! CANDIDATES is a list of individuals to consider adding to the group. " ; Loop and try to find the knee. This uses a moving window to ; try to find the knee. We record all of the in-group sizes in ; the list called `window`. The length of that list is `win-slots` ; and is set to `win-size` divided by `epsi-step`. The list is treated as a queue : pop the old size off one end , push the new ; size onto the other end. The change in group size is just the difference between the two ends of this queue . (define epsilon #f) (define nsteps (inexact->exact (round (/ max-epsi epsi-step)))) (define win-slots (inexact->exact (round (/ win-size epsi-step)))) (define window (make-list win-slots 2)) (take-while (lambda (N) (set! epsilon (* N epsi-step)) (define ing (find-in-group SIMFUN WB WA lower-bound epsilon tightness CANDIDATES)) (define ingsz (length ing)) (define prevsz (car window)) Slide the window over by one slot . (set! window (append (drop window 1) (list ingsz))) Compare the two ends of the window . (define jump (- ingsz prevsz)) (and (< jump max-jump) (< ingsz max-size)) ) (iota nsteps 1)) The above loop halts when we 've gone too far . So back off by one step , and return that . ( Maybe we should back off two steps , to be ; conservative?) (define in-grp (find-in-group SIMFUN WA WB lower-bound (- epsilon epsi-step) tightness CANDIDATES)) ; Reverse the list before sending it out. This way, the initial WA and WB appear first in the list , instead of last . This ; improves readability slightly, with trivial impact to performance. (reverse in-grp) ) ; ----- (define-public (optimal-mi-in-group SIMFUN WA WB CANDIDATES) " optimal-mi-in-group - version of optimal-in-group with parameters that work for grammatical-MI similarity. See `optimal-in-group` for documentation. " (optimal-in-group SIMFUN WA WB CANDIDATES ; Tightness. Experiments show that the results are insensitive of this , with values ranging from 0.3 to 1.0 giving identical ; results in many cases. #:tightness 0.7 ; Size of steps (changes in similarity) that will be taken in epsilon . For MI - similarity , 0.1 is a good step - size . #:epsi-step 0.1 ; The size of the in-group should not jump by more than this ; over the moving window. #:max-jump 2.5 ; The window size #:win-size 1.0 The largest espsilon to consider . The value of 8.5 comes from experiments : the grouping of roman ; numerals were still coherent, despite being this far apart. #:max-epsi 8.5 ; Lower bound on the similarity between members of the in-group. ; All members of the in-group must have a pair-wise similarity ; greater than this. For grammatical-MI, this obviously has to be between 0.0 and 4.0 . #:lower-bound 1.0 ; Maximum size of the in-group. We don't return in-groups ; larger than this. #:max-size 12 )) ; --------------------------------------------------------------- ; Example usage. ; Assumes that a suitable number of word similarities have been ; previously computed. Assumes that shapes are enabled and being used. ; #! =========== ;; General setup of data (define pca (make-pseudo-cset-api)) (define pcs (add-pair-stars pca)) (define sha (add-covering-sections pcs)) (sha 'fetch-pairs) (sha 'explode-sections) (define sap (add-similarity-api sha #f "shape-mi")) (sap 'fetch-pairs) ;;; same as (load-atoms-of-type 'Similarity) (define sim (add-pair-stars sap)) ;; Create a list of candidates. (define e (make-elapsed-secs)) (define ranked-words (rank-words pcs)) 19 seconds ; A short list (those that we have similarities for) (define words-with-sims (take ranked-words 1200)) ; Get all of the pairs with similarities on them. ; Same thing as `(cog-get-atoms 'Similarity)` ; Well, not quite ... similarity object fails to get the WordClass node similarities ! ; Its also slower, because 'get-all-elts does a Pattern search. (define e (make-elapsed-secs)) (define all-sim-pairs (sim 'get-all-elts)) 32 seconds 668610 ; ; Exclude self-similar pairs. (define uniq-sims (filter (lambda (SIM) (not (equal? (gar SIM) (gdr SIM)))) all-sim-pairs)) (length uniq-sims) ; Use the "ranked-MI" for ranking (define (ranked-mi-sim WA WB) (define miv (sap 'pair-count WA WB)) (if miv (cog-value-ref miv 1) -inf.0)) ;; Discard all similarity pairs with low common-MI. (define e (make-elapsed-secs)) (define hi-comi-sims (filter (lambda (SIM) (< 6.0 (ranked-MI (gar SIM) (gdr SIM)))) uniq-sims)) 32 seconds 1499 pairs in earlier versions ;; Create a sorted list of ranked pairs. ;; We want to find the top-ranked word-pairs (define (rank-pairs FUN) (sort hi-comi-sims (lambda (ATOM-A ATOM-B) (> (FUN ATOM-A) (FUN ATOM-B)))) ) ;; Now sort all of the available pairs. (Sorting all of them takes 15 minutes . So sort only the high common - MI pairs . ) (define sorted-pairs (rank-pairs (lambda (SIM) (ranked-mi-sim (gar SIM) (gdr SIM))))) ;; What are the top-ranked pairs? (take sorted-pairs 10) ; Take a look at what we're dealing with. (define (prt-sorted-pairs N) (for-each (lambda (PR) (format #t "common-MI= ~6F ~A <<-->> ~A\n" (common-MI (gar PR) (gdr PR)) (cog-name (gar PR)) (cog-name (gdr PR)))) (drop (take sorted-pairs (+ N 20)) N))) (prt-sorted-pairs 0) ; Go for it (define in-group (find-in-group ranked-mi-sim (Word "is") (Word "was") 0.5 0.7 (take words-with-sims 10))) ; Given a word, what is it's ranking? (define (rank-of-word WRD) (list-index (lambda (RW) (equal? WRD RW)) words-with-sims)) Create graphs for the diary . These appear in Diary Part Four . (define (in-group-csv FILENAME WA WB TIGHT) (define csv (open FILENAME (logior O_WRONLY O_CREAT O_TRUNC))) (format csv "#\n# Initial 2-clique: ~A <<>> ~A\n#\n" (cog-name WA) (cog-name WB)) (format csv "# Tightness = ~6F\n" TIGHT) (format csv "# This is using common-MI to determine in-group membership.\n") ; (format csv "# This is using plain MI NOT common-MI\n") (format csv "#\n# idx\tepsilon\tsize\tmin-index\tmax-index\twords\n") (for-each (lambda (N) (define epsi (+ (* 0.1 N) -2)) ( define epsi ( * 0.1 N ) ) (define in-group (find-in-group common-MI ;;;; mi-sim WA WB epsi TIGHT words-with-sims)) (define max-idx (fold (lambda (W MAXI) (max MAXI (rank-of-word W))) -1000 in-group)) (define min-idx (fold (lambda (W MINI) (min MINI (rank-of-word W))) 1000 in-group)) (format csv "~D\t~6F\t~D\t~D\t~D\t{ " N epsi (length in-group) min-idx max-idx) (for-each (lambda (WRD) (format csv "~A " (cog-name WRD))) in-group) (format csv "}\n") (force-output csv)) (iota 100)) (close csv)) (in-group-csv "/tmp/grp-is-was.dat" (Word "is") (Word "was") 0.7) (in-group-csv "/tmp/grp-and-but.dat" (Word "and") (Word "but") 0.7) (in-group-csv "/tmp/grp-in-of.dat" (Word "in") (Word "of") 0.7) (in-group-csv "/tmp/grp-she-he.dat" (Word "she") (Word "he") 0.7) (in-group-csv "/tmp/grp-comma-semi.dat" (Word ",") (Word ";") 0.7) (in-group-csv "/tmp/grp-period-quest.dat" (Word ".") (Word "?") 0.7) (in-group-csv "/tmp/grp-plus-minus.dat" (Word "+") (Word "—") 0.7) (in-group-csv "/tmp/grp-roman-i-ii.dat" (Word "i") (Word "ii") 0.7) (in-group-csv "/tmp/grp-It-There.dat" (Word "It") (Word "There") 0.7) (in-group-csv "/tmp/grp-spoke-sat.dat" (Word "spoke") (Word "sat") 0.7) (in-group-csv "/tmp/grp-look-smile.dat" (Word "look") (Word "smile") 0.7) (in-group-csv "/tmp/grp-town-earth.dat" (Word "town") (Word "earth") 0.7) (in-group-csv "/tmp/grp-door-house.dat" (Word "door") (Word "house") 0.7) ========== !#
null
https://raw.githubusercontent.com/opencog/learn/b3f2bc8260bdea5f2ba64dab7a20e265d23a14c3/scm/gram-class/in-group.scm
scheme
in-group.scm Obtain an in-group of similar words. In-groups are those whose members more generally are almost-cliques. --------------------------------------------------------------------- OVERVIEW -------- Given a word-pair with a high similarity score, expand that word-pair into a clique or an almost-clique, such that all similarity scores in that clique are no less than epsilon below the similarity score of the initial pair. A clique is formed if *all* pair-scores meet this requirement. An in-group is formed, if the majority of the scores to other members in the in-group are above the epsilon threshold. for define*-public least TIGHT other members of the ingroup. Return #f if the candidate has a score below LOWER-BOUND to any member of the ingroup. There can be at most `maxfail` bad scores Convert fractional TIGHTNESS to an integer. an ingroup by adding members to the ingroup if that candidate has a score no less than `minscore` to at least `TIGHT` members of the group. --------------------------------------------------------------- The tightness of the almost-clique. This is the fraction of the in-group members that have a similarity above the the a tightness of 1.0 means that they all are (and so form a clique.) See `find-in-group` for more. Size of steps (changes in the threshold) that will be taken. The threshold is then lowered by steps of epsi-step, until stopping conditions are obtained. The largest change in threshold to consider. The threshold Specifically, the grouping of roman numerals is still coherent, Lower bound on the similarity between members of the in-group. All members of the in-group must have a pair-wise similarity greater than this. The size of the in-group should not jump by more than this over the width of moving window. If it does change by more than this, then we assume that the 'knee' has been found, and the search is halted. This enforces a max linear growth rate in the size of The size of the moving window. The size of the in-group at a given threshold is compared to the size of the in-group at (threshold + win-size.) If the change in the in-group size is more than 'max-jump', then search is halted. window. Hard-coded maximum size of the in-group. We don't return in-groups larger than this. Loop and try to find the knee. This uses a moving window to try to find the knee. We record all of the in-group sizes in the list called `window`. The length of that list is `win-slots` and is set to `win-size` divided by `epsi-step`. The list is size onto the other end. The change in group size is just the conservative?) Reverse the list before sending it out. This way, the initial improves readability slightly, with trivial impact to performance. ----- Tightness. Experiments show that the results are insensitive results in many cases. Size of steps (changes in similarity) that will be taken The size of the in-group should not jump by more than this over the moving window. The window size numerals were still coherent, despite being this far apart. Lower bound on the similarity between members of the in-group. All members of the in-group must have a pair-wise similarity greater than this. For grammatical-MI, this obviously has to Maximum size of the in-group. We don't return in-groups larger than this. --------------------------------------------------------------- Example usage. Assumes that a suitable number of word similarities have been previously computed. Assumes that shapes are enabled and being used. General setup of data same as (load-atoms-of-type 'Similarity) Create a list of candidates. A short list (those that we have similarities for) Get all of the pairs with similarities on them. Same thing as `(cog-get-atoms 'Similarity)` Well, not quite ... similarity object fails to get Its also slower, because 'get-all-elts does a Pattern search. Exclude self-similar pairs. Use the "ranked-MI" for ranking Discard all similarity pairs with low common-MI. Create a sorted list of ranked pairs. We want to find the top-ranked word-pairs Now sort all of the available pairs. (Sorting all of them takes What are the top-ranked pairs? Take a look at what we're dealing with. Go for it Given a word, what is it's ranking? (format csv "# This is using plain MI NOT common-MI\n") mi-sim
have a lot in common with one - another . In - groups can be cliques , and Copyright ( c ) 2021 Linas Vepstas (use-modules (srfi srfi-1)) (define-public (find-in-group SIMFUN WA WB LOWER-BOUND EPSILON TIGHTNESS CANDIDATES) " find-in-group SIMFUN WA WB LOWER-BOUND EPSILON TIGHTNESS CANDIDATES Return an in-group of closely related words. Given two words WA and WB with a high similarity score, find a clique an almost-clique (the in-group), such that all similarity scores in that in-group are greater than LOWER-BOUND and are also no less than EPSILON below the similarity score of the initial pair. A clique is formed if *all* pair-scores meet this requirement. An in-group is formed, if more than a TIGHTNESS fraction of the scores to other members in the in-group are above the epsilon threshold. (A TIGHTNESS of 0.5 means that a simple majority of the in-group meets the a TIGHTNESS of 1.0 means the in - group is a clique . ) Arguments: WA and WB seed the initial in-group. SIMFUN is an function that, given two items, returns a similarity score for those items. Similarities are assumed to be symmetric, that is, (SIMFUN a b) == (SIMFUN b a). Usually, the similarity is a floating point number, but in fact it can be anything that is comparable with greater-than. At this time, all experimental results (and thus, recommended parameter values) have been done ONLY with ranked-MI. The code should still work for other SIMFUN's, but these have not been characterized. LOWER-BOUND is an absolute lower bound on the in-group similarities. All members of the in-group must have similarities that are greater than LOWER-BOUND. Recommended value of 0.0 to 4.0. EPSILON is a relative lower bound on the in-group similarities. Most members of the in-group must have similarities that are within EPSILON of the initial pair. Pairs that are within EPSILON are termed `similar enough`. Recommended value of 0.5 to 8.0. TIGHTNESS is a number between 0 and 1, specifying the fraction of the in-group pairs that must be similar enough to one-another. A TIGHTNESS of 0.5 means that a majority of the pair-relations must be `similar enough`, while a TIGHTNESS of 1.0 means that all of them will be. Recommended value of 0.7. Experiments reveal that results are relatively insensitive to this value, ranging over 0.3 to 1.0. CANDIDATES is a list of individuals to consider adding to the group. Experiments show that the size of the group at first grows slowly as a function of increasing EPSILON, followed by a very rapid increase after some threshold is passed. Obviously, EPSILON should be set below that threshold. Unfortunately, this threshold depends strongly on the initial pair, even when working within the same dataset. " Given the current ingroup INGRP and the CANDIDATE , return # t if the candidate has a similarity score above MINSCORE to at (define (accept INGRP CANDIDATE MINSCORE TIGHT) (define maxfail (- (length INGRP) TIGHT)) (define failcnt 0) (every (lambda (MEMB) (define score (SIMFUN CANDIDATE MEMB)) (if (< score LOWER-BOUND) (set! failcnt (+ failcnt maxfail 999))) (if (< score MINSCORE) (set! failcnt (+ failcnt 1))) (<= failcnt maxfail) ) INGRP)) (define benchmark (SIMFUN WA WB)) (define minscore (- benchmark EPSILON)) (define (get-tight INGRP) (define insz (length INGRP)) (if (equal? 2 insz) 2 (inexact->exact (round (* TIGHTNESS insz))))) Remove WA , WB from the list of candidates (define clean-cand (filter (lambda (cand) (not (or (equal? cand WA) (equal? cand WB)))) CANDIDATES)) Starting with the minimal clique of ` ( list WA WB ) ` , create (fold (lambda (CAND INGRP) (if (accept INGRP CAND minscore (get-tight INGRP)) (cons CAND INGRP) INGRP)) (list WA WB) clean-cand) ) (define*-public (optimal-in-group SIMFUN WA WB CANDIDATES #:key threshold . A tightness of 0.5 means the majority of the in - group (tightness 0.7) The initial threshold is set to the similarity of WA and WB . For MI - similarity , 0.1 is a good step - size . (epsi-step 0.1) will never go below ( similarity of WA and WB ) minus this number . For grammatical - MI , experiments suggest this should be 8.5 . despite individual pair - wise MI 's being 8.5 apart . (max-epsi 8.5) For MI - similarity , we want similarities greater than about 2.0 or 4.0 . Experiments show 1.0 works OK . (lower-bound 1.0) the ingroup . The default value of 2.5 means the ingroup will not add more than two members over the width of the window . (max-jump 2.5) For grammatical - MI , a delta - MI of 1.0 seems like a reasonable (win-size 1.0) (max-size 12) ) " optimal-in-group SIMFUN WA WB CANDIDATES Return an ingroup of closely related words. The initial members of the ingroup are WA and WB. Additional potential members are drawn from CANDIDATES if they are similar-enough to the current ingroup, as measured by the similarity function SIMFUN. This searches for the largest ingroup that is still exclusive. The search is performed by admitting individuals from CANDIDATES, one at a time, if they are judged similar-enough by SIMFUN. The membership requirements are slowly loosened (by dropping the lower bound of what is considered 'similar-enough'), until membership explodes. Then the lower bound is backed off a bit, just before the explosion. Experiments show that as membership requirements are loosened, there is a knee in the size of the group: the group size suddenly explodes. That is, as the similarity threshold is loosened, the size of the group grows slowly at first, and then, at some point, it takes off, growing rapidly (growing 'explosively'). This searches for the largest group below that inflection point. Arguments: WA and WB seed the initial in-group. SIMFUN is an function that, given two items, returns a similarity score for those items. Similarities are assumed to be symmetric, that is, (SIMFUN a b) == (SIMFUN b a). Usually, the similarity is a floating point number, but in fact it can be anything that is comparable with greater-than. For similarities that are floating point numbers, the larger the value, the more similar they are. This function has been experimentally tested only for SIMFUN being ranked-MI! CANDIDATES is a list of individuals to consider adding to the group. " treated as a queue : pop the old size off one end , push the new difference between the two ends of this queue . (define epsilon #f) (define nsteps (inexact->exact (round (/ max-epsi epsi-step)))) (define win-slots (inexact->exact (round (/ win-size epsi-step)))) (define window (make-list win-slots 2)) (take-while (lambda (N) (set! epsilon (* N epsi-step)) (define ing (find-in-group SIMFUN WB WA lower-bound epsilon tightness CANDIDATES)) (define ingsz (length ing)) (define prevsz (car window)) Slide the window over by one slot . (set! window (append (drop window 1) (list ingsz))) Compare the two ends of the window . (define jump (- ingsz prevsz)) (and (< jump max-jump) (< ingsz max-size)) ) (iota nsteps 1)) The above loop halts when we 've gone too far . So back off by one step , and return that . ( Maybe we should back off two steps , to be (define in-grp (find-in-group SIMFUN WA WB lower-bound (- epsilon epsi-step) tightness CANDIDATES)) WA and WB appear first in the list , instead of last . This (reverse in-grp) ) (define-public (optimal-mi-in-group SIMFUN WA WB CANDIDATES) " optimal-mi-in-group - version of optimal-in-group with parameters that work for grammatical-MI similarity. See `optimal-in-group` for documentation. " (optimal-in-group SIMFUN WA WB CANDIDATES of this , with values ranging from 0.3 to 1.0 giving identical #:tightness 0.7 in epsilon . For MI - similarity , 0.1 is a good step - size . #:epsi-step 0.1 #:max-jump 2.5 #:win-size 1.0 The largest espsilon to consider . The value of 8.5 comes from experiments : the grouping of roman #:max-epsi 8.5 be between 0.0 and 4.0 . #:lower-bound 1.0 #:max-size 12 )) #! =========== (define pca (make-pseudo-cset-api)) (define pcs (add-pair-stars pca)) (define sha (add-covering-sections pcs)) (sha 'fetch-pairs) (sha 'explode-sections) (define sap (add-similarity-api sha #f "shape-mi")) (define sim (add-pair-stars sap)) (define e (make-elapsed-secs)) (define ranked-words (rank-words pcs)) 19 seconds (define words-with-sims (take ranked-words 1200)) the WordClass node similarities ! (define e (make-elapsed-secs)) (define all-sim-pairs (sim 'get-all-elts)) 32 seconds 668610 (define uniq-sims (filter (lambda (SIM) (not (equal? (gar SIM) (gdr SIM)))) all-sim-pairs)) (length uniq-sims) (define (ranked-mi-sim WA WB) (define miv (sap 'pair-count WA WB)) (if miv (cog-value-ref miv 1) -inf.0)) (define e (make-elapsed-secs)) (define hi-comi-sims (filter (lambda (SIM) (< 6.0 (ranked-MI (gar SIM) (gdr SIM)))) uniq-sims)) 32 seconds 1499 pairs in earlier versions (define (rank-pairs FUN) (sort hi-comi-sims (lambda (ATOM-A ATOM-B) (> (FUN ATOM-A) (FUN ATOM-B)))) ) 15 minutes . So sort only the high common - MI pairs . ) (define sorted-pairs (rank-pairs (lambda (SIM) (ranked-mi-sim (gar SIM) (gdr SIM))))) (take sorted-pairs 10) (define (prt-sorted-pairs N) (for-each (lambda (PR) (format #t "common-MI= ~6F ~A <<-->> ~A\n" (common-MI (gar PR) (gdr PR)) (cog-name (gar PR)) (cog-name (gdr PR)))) (drop (take sorted-pairs (+ N 20)) N))) (prt-sorted-pairs 0) (define in-group (find-in-group ranked-mi-sim (Word "is") (Word "was") 0.5 0.7 (take words-with-sims 10))) (define (rank-of-word WRD) (list-index (lambda (RW) (equal? WRD RW)) words-with-sims)) Create graphs for the diary . These appear in Diary Part Four . (define (in-group-csv FILENAME WA WB TIGHT) (define csv (open FILENAME (logior O_WRONLY O_CREAT O_TRUNC))) (format csv "#\n# Initial 2-clique: ~A <<>> ~A\n#\n" (cog-name WA) (cog-name WB)) (format csv "# Tightness = ~6F\n" TIGHT) (format csv "# This is using common-MI to determine in-group membership.\n") (format csv "#\n# idx\tepsilon\tsize\tmin-index\tmax-index\twords\n") (for-each (lambda (N) (define epsi (+ (* 0.1 N) -2)) ( define epsi ( * 0.1 N ) ) WA WB epsi TIGHT words-with-sims)) (define max-idx (fold (lambda (W MAXI) (max MAXI (rank-of-word W))) -1000 in-group)) (define min-idx (fold (lambda (W MINI) (min MINI (rank-of-word W))) 1000 in-group)) (format csv "~D\t~6F\t~D\t~D\t~D\t{ " N epsi (length in-group) min-idx max-idx) (for-each (lambda (WRD) (format csv "~A " (cog-name WRD))) in-group) (format csv "}\n") (force-output csv)) (iota 100)) (close csv)) (in-group-csv "/tmp/grp-is-was.dat" (Word "is") (Word "was") 0.7) (in-group-csv "/tmp/grp-and-but.dat" (Word "and") (Word "but") 0.7) (in-group-csv "/tmp/grp-in-of.dat" (Word "in") (Word "of") 0.7) (in-group-csv "/tmp/grp-she-he.dat" (Word "she") (Word "he") 0.7) (in-group-csv "/tmp/grp-comma-semi.dat" (Word ",") (Word ";") 0.7) (in-group-csv "/tmp/grp-period-quest.dat" (Word ".") (Word "?") 0.7) (in-group-csv "/tmp/grp-plus-minus.dat" (Word "+") (Word "—") 0.7) (in-group-csv "/tmp/grp-roman-i-ii.dat" (Word "i") (Word "ii") 0.7) (in-group-csv "/tmp/grp-It-There.dat" (Word "It") (Word "There") 0.7) (in-group-csv "/tmp/grp-spoke-sat.dat" (Word "spoke") (Word "sat") 0.7) (in-group-csv "/tmp/grp-look-smile.dat" (Word "look") (Word "smile") 0.7) (in-group-csv "/tmp/grp-town-earth.dat" (Word "town") (Word "earth") 0.7) (in-group-csv "/tmp/grp-door-house.dat" (Word "door") (Word "house") 0.7) ========== !#
5603de9fe19ba2cd444df8ae2b3cd89889b01d15b6f6090dd93181af2d395278
rescript-association/reanalyze
RunConfig.ml
type t = { mutable bsbProjectRoot : string; mutable dce : bool; mutable exception_ : bool; mutable noalloc : bool; mutable projectRoot : string; mutable suppress : string list; mutable termination : bool; mutable unsuppress : string list; } let runConfig = { bsbProjectRoot = ""; dce = false; exception_ = false; noalloc = false; projectRoot = ""; suppress = []; termination = false; unsuppress = []; } let all () = runConfig.dce <- true; runConfig.exception_ <- true; runConfig.termination <- true let dce () = runConfig.dce <- true let exception_ () = runConfig.exception_ <- true let noalloc () = runConfig.noalloc <- true let termination () = runConfig.termination <- true
null
https://raw.githubusercontent.com/rescript-association/reanalyze/57c22938d266d7eeae00e7caf09924fd271207c2/src/RunConfig.ml
ocaml
type t = { mutable bsbProjectRoot : string; mutable dce : bool; mutable exception_ : bool; mutable noalloc : bool; mutable projectRoot : string; mutable suppress : string list; mutable termination : bool; mutable unsuppress : string list; } let runConfig = { bsbProjectRoot = ""; dce = false; exception_ = false; noalloc = false; projectRoot = ""; suppress = []; termination = false; unsuppress = []; } let all () = runConfig.dce <- true; runConfig.exception_ <- true; runConfig.termination <- true let dce () = runConfig.dce <- true let exception_ () = runConfig.exception_ <- true let noalloc () = runConfig.noalloc <- true let termination () = runConfig.termination <- true
8355719a87c21010211db523ca3abaa850579317e7eb5c0e161be1ff2ee0a225
meooow25/haccepted
MiscSpec.hs
# LANGUAGE ScopedTypeVariables # module MiscSpec where import Data.List import Test.Hspec import Test.Hspec.QuickCheck import Misc ( foldExclusive ) spec :: Spec spec = do prop "foldExclusive" $ \(xs :: [Int]) -> foldExclusive (+) 0 xs `shouldBe` naiveFoldExclusive (+) 0 xs naiveFoldExclusive :: (b -> a -> b) -> b -> [a] -> [b] naiveFoldExclusive f b as = map (foldl' f b) $ zipWith (++) (init $ inits as) (tail $ tails as)
null
https://raw.githubusercontent.com/meooow25/haccepted/2bc153ca95038de3b8bac83eee4419b3ecc116c5/tests/MiscSpec.hs
haskell
# LANGUAGE ScopedTypeVariables # module MiscSpec where import Data.List import Test.Hspec import Test.Hspec.QuickCheck import Misc ( foldExclusive ) spec :: Spec spec = do prop "foldExclusive" $ \(xs :: [Int]) -> foldExclusive (+) 0 xs `shouldBe` naiveFoldExclusive (+) 0 xs naiveFoldExclusive :: (b -> a -> b) -> b -> [a] -> [b] naiveFoldExclusive f b as = map (foldl' f b) $ zipWith (++) (init $ inits as) (tail $ tails as)
e733e4887e44945c11b9086e80c6a811a93107c839af803389f327b907a0559d
clojurians-org/haskell-example
Streaming.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE OverloadedLabels # {-# LANGUAGE RankNTypes #-} # LANGUAGE DataKinds # module Backend.Streaming where import Common.Types import Data.Conduit (ConduitT, runConduit, runConduitRes, bracketP, yield, (.|)) import qualified Data.Conduit.Combinators as C import qualified Data.Conduit.List as CL import qualified Data.Text as T import Data.Functor ((<&>)) import Control.Monad.Loops (iterateWhile) import Data.String.Conversions (cs) import qualified Database.Dpi as Oracle import qualified Database.Dpi.Field as Oracle import Control.Monad.Trans.Resource (MonadResource, allocate, release, runResourceT) import Control.Monad.Trans (MonadIO(liftIO), MonadTrans(lift)) import Control.Exception (finally, catch, SomeException(..)) import Control.Monad (when, void) import UnliftIO.STM as U import UnliftIO.Async as U import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Maybe (isJust, fromMaybe) import Control.Concurrent.STM.TBMChan (TBMChan, newTBMChanIO, closeTBMChan, writeTBMChan, readTBMChan) import Data.Conduit.TMChan (sourceTBMChan) import qualified Data.ByteString as B import Text.Heredoc (str) import Labels tshow :: (Show a) => a -> T.Text tshow = cs . show bracketR :: forall a b c m.MonadResource m => IO a -> (a -> IO c) -> (a -> m b) -> m b bracketR alloc free inside = do (key, seed) <- allocate alloc (void . free) res <- inside seed release key return res oracleChan :: forall m. (MonadResource m, MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> T.Text -> m (TBMChan [Oracle.DataField]) oracleChan (Credential hostName hostPort username password) database sql = do let config = Oracle.defaultOracle (cs username) (cs password) (cs (hostName <> ":" <> tshow hostPort <> "/" <> database)) defCursorSize = 2000 defBatchSize = 20000 (reg, chan) <- allocate (newTBMChanIO defBatchSize) (U.atomically . closeTBMChan) U.async $ bracketR Oracle.createContext Oracle.destroyContext $ \ctx -> bracketR (Oracle.createConnection ctx config return) (\c -> Oracle.closeConnection Oracle.ModeConnCloseDefault c `finally` Oracle.releaseConnection c) $ \conn -> bracketR (Oracle.prepareStatement conn False (cs sql)) Oracle.releaseStatement $ \stmt -> liftIO $ do Oracle.setFetchArraySize stmt defCursorSize cn <- Oracle.executeStatement stmt Oracle.ModeExecDefault `catch` \(SomeException e) -> print e >> fail (show e) sinkRows chan stmt cn defCursorSize release reg return chan where -- sinkRows chan stmt cn cursorSize = do offset <- Oracle.fetch stmt when (isJust offset) $ do row <- mapM (\i -> Oracle.DataField <$> Oracle.getQueryInfo stmt i <*> Oracle.getQueryValue stmt i) [1..cn] atomically $ writeTBMChan chan row sinkRows chan stmt cn cursorSize textOracle :: (MonadIO m) => Oracle.DataField -> m T.Text textOracle v = liftIO (Oracle.fromDataField v) <&> maybe "" (cs :: B.ByteString -> T.Text) oracleShowTables :: forall m. (MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> m [("schema" := T.Text, "table" := T.Text)] oracleShowTables credential database = runConduitRes $ (lift chan >>= sourceTBMChan) .| C.mapM (liftIO . labelOracle) .| C.sinkList where chan = oracleChan credential database sql sql = [str| select owner, table_name | from all_tables | where tablespace_name not in ('SYSTEM', 'SYSAUX') |] labelOracle xs = (,) <$> fmap (#schema := ) (textOracle (xs !! 0)) <*> fmap (#table :=) (textOracle (xs !! 1)) oracleDescribeTable :: forall m. (MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> (T.Text, T.Text) -> m [("name" := T.Text, "type" := T.Text, "desc" := T.Text)] oracleDescribeTable credential database (schema, table) = do liftIO $ print sql runConduitRes $ (lift chan >>= sourceTBMChan) .| C.mapM (liftIO . labelOracle) .| C.sinkList where chan = oracleChan credential database sql sql = "select t1.column_name, t1.data_type, t2.comments from all_tab_columns t1 inner join all_col_comments t2" <> " on t1.owner = t2.owner and t1.table_name = t2.table_name and t1.column_name = t2.column_name" <> " where t1.owner = '" <> schema <> "' AND t1.table_name = '" <> table <> "'" labelOracle xs = (,,) <$> fmap (#name :=) (textOracle (xs !! 0)) <*> fmap (#type :=) (textOracle (xs !! 1)) <*> fmap (#desc :=) (textOracle (xs !! 2)) myRepl :: IO () myRepl = do oracleShowTables ( credential " 10.132.37.241:1521 " " KB " " KB123456 " ) " EDMP " > > = print oracleDescribeTable (credential "10.132.37.241:1521" "KB" "KB123456") "EDMP" ("KB", "TB_INTERFACE_LOG") >>= mapM_ print
null
https://raw.githubusercontent.com/clojurians-org/haskell-example/c96b021bdef52a121e04ea203c8c3e458770a25a/conduit-ui/backend/src/Backend/Streaming.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
# LANGUAGE OverloadedLabels # # LANGUAGE DataKinds # module Backend.Streaming where import Common.Types import Data.Conduit (ConduitT, runConduit, runConduitRes, bracketP, yield, (.|)) import qualified Data.Conduit.Combinators as C import qualified Data.Conduit.List as CL import qualified Data.Text as T import Data.Functor ((<&>)) import Control.Monad.Loops (iterateWhile) import Data.String.Conversions (cs) import qualified Database.Dpi as Oracle import qualified Database.Dpi.Field as Oracle import Control.Monad.Trans.Resource (MonadResource, allocate, release, runResourceT) import Control.Monad.Trans (MonadIO(liftIO), MonadTrans(lift)) import Control.Exception (finally, catch, SomeException(..)) import Control.Monad (when, void) import UnliftIO.STM as U import UnliftIO.Async as U import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Maybe (isJust, fromMaybe) import Control.Concurrent.STM.TBMChan (TBMChan, newTBMChanIO, closeTBMChan, writeTBMChan, readTBMChan) import Data.Conduit.TMChan (sourceTBMChan) import qualified Data.ByteString as B import Text.Heredoc (str) import Labels tshow :: (Show a) => a -> T.Text tshow = cs . show bracketR :: forall a b c m.MonadResource m => IO a -> (a -> IO c) -> (a -> m b) -> m b bracketR alloc free inside = do (key, seed) <- allocate alloc (void . free) res <- inside seed release key return res oracleChan :: forall m. (MonadResource m, MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> T.Text -> m (TBMChan [Oracle.DataField]) oracleChan (Credential hostName hostPort username password) database sql = do let config = Oracle.defaultOracle (cs username) (cs password) (cs (hostName <> ":" <> tshow hostPort <> "/" <> database)) defCursorSize = 2000 defBatchSize = 20000 (reg, chan) <- allocate (newTBMChanIO defBatchSize) (U.atomically . closeTBMChan) U.async $ bracketR Oracle.createContext Oracle.destroyContext $ \ctx -> bracketR (Oracle.createConnection ctx config return) (\c -> Oracle.closeConnection Oracle.ModeConnCloseDefault c `finally` Oracle.releaseConnection c) $ \conn -> bracketR (Oracle.prepareStatement conn False (cs sql)) Oracle.releaseStatement $ \stmt -> liftIO $ do Oracle.setFetchArraySize stmt defCursorSize cn <- Oracle.executeStatement stmt Oracle.ModeExecDefault `catch` \(SomeException e) -> print e >> fail (show e) sinkRows chan stmt cn defCursorSize release reg return chan where sinkRows chan stmt cn cursorSize = do offset <- Oracle.fetch stmt when (isJust offset) $ do row <- mapM (\i -> Oracle.DataField <$> Oracle.getQueryInfo stmt i <*> Oracle.getQueryValue stmt i) [1..cn] atomically $ writeTBMChan chan row sinkRows chan stmt cn cursorSize textOracle :: (MonadIO m) => Oracle.DataField -> m T.Text textOracle v = liftIO (Oracle.fromDataField v) <&> maybe "" (cs :: B.ByteString -> T.Text) oracleShowTables :: forall m. (MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> m [("schema" := T.Text, "table" := T.Text)] oracleShowTables credential database = runConduitRes $ (lift chan >>= sourceTBMChan) .| C.mapM (liftIO . labelOracle) .| C.sinkList where chan = oracleChan credential database sql sql = [str| select owner, table_name | from all_tables | where tablespace_name not in ('SYSTEM', 'SYSAUX') |] labelOracle xs = (,) <$> fmap (#schema := ) (textOracle (xs !! 0)) <*> fmap (#table :=) (textOracle (xs !! 1)) oracleDescribeTable :: forall m. (MonadIO m, MonadUnliftIO m) => Credential -> T.Text -> (T.Text, T.Text) -> m [("name" := T.Text, "type" := T.Text, "desc" := T.Text)] oracleDescribeTable credential database (schema, table) = do liftIO $ print sql runConduitRes $ (lift chan >>= sourceTBMChan) .| C.mapM (liftIO . labelOracle) .| C.sinkList where chan = oracleChan credential database sql sql = "select t1.column_name, t1.data_type, t2.comments from all_tab_columns t1 inner join all_col_comments t2" <> " on t1.owner = t2.owner and t1.table_name = t2.table_name and t1.column_name = t2.column_name" <> " where t1.owner = '" <> schema <> "' AND t1.table_name = '" <> table <> "'" labelOracle xs = (,,) <$> fmap (#name :=) (textOracle (xs !! 0)) <*> fmap (#type :=) (textOracle (xs !! 1)) <*> fmap (#desc :=) (textOracle (xs !! 2)) myRepl :: IO () myRepl = do oracleShowTables ( credential " 10.132.37.241:1521 " " KB " " KB123456 " ) " EDMP " > > = print oracleDescribeTable (credential "10.132.37.241:1521" "KB" "KB123456") "EDMP" ("KB", "TB_INTERFACE_LOG") >>= mapM_ print
21a646ce1daf887f30d709dacaef108eb63f51559ec173c9124a295927753a0b
deadpendency/deadpendency
DependencyType.hs
{-# LANGUAGE DeriveAnyClass #-} module Common.Model.Dependency.DependencyType ( DependencyType (..), ) where import Common.Aeson.Aeson import Data.Aeson data DependencyType = CoreDependency | DevDependency deriving stock (Eq, Show, Generic, Ord) deriving anyclass (NFData) instance ToJSON DependencyType where toJSON = genericToJSON cleanJSONOptions toEncoding = genericToEncoding cleanJSONOptions instance FromJSON DependencyType where parseJSON = genericParseJSON cleanJSONOptions
null
https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/Model/Dependency/DependencyType.hs
haskell
# LANGUAGE DeriveAnyClass #
module Common.Model.Dependency.DependencyType ( DependencyType (..), ) where import Common.Aeson.Aeson import Data.Aeson data DependencyType = CoreDependency | DevDependency deriving stock (Eq, Show, Generic, Ord) deriving anyclass (NFData) instance ToJSON DependencyType where toJSON = genericToJSON cleanJSONOptions toEncoding = genericToEncoding cleanJSONOptions instance FromJSON DependencyType where parseJSON = genericParseJSON cleanJSONOptions
6cd789be72b694b3180a3b31e6aff3defa1593a2cd5e60af3e994c6d479ad3f8
simmsb/calamity
SnowflakeMap.hs
| Module for custom instance of Data . . Strict that decodes from any list of objects that have an i d field module Calamity.Internal.SnowflakeMap where import Calamity.Internal.Utils () import Calamity.Types.Snowflake import Data.Aeson (FromJSON (..), ToJSON (..), withArray) import Data.Data import Data.Foldable qualified as F import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as SH import Data.Hashable import GHC.Exts (IsList) import Optics import TextShow import Unsafe.Coerce newtype SnowflakeMap a = SnowflakeMap { unSnowflakeMap :: HashMap (Snowflake a) a } deriving stock (Eq, Data, Ord, Show) deriving (TextShow) via FromStringShow (SnowflakeMap a) deriving newtype (IsList, Semigroup, Monoid) deriving newtype (Hashable) instance At ( SnowflakeMap a ) where -- at k f m = at (unSnowflakeMap k) f m instance Functor SnowflakeMap where fmap f = SnowflakeMap . coerceSnowflakeMap . fmap f . unSnowflakeMap instance Foldable SnowflakeMap where foldr f b = Prelude.foldr f b . unSnowflakeMap instance Traversable SnowflakeMap where traverse f = fmap (SnowflakeMap . coerceSnowflakeMap) . traverse f . unSnowflakeMap type instance Index (SnowflakeMap a) = Snowflake a type instance IxValue (SnowflakeMap a) = a _SnowflakeMap :: ( Iso (SnowflakeMap a) (SnowflakeMap a1) (HashMap (Snowflake a) a) (HashMap (Snowflake a1) a1) ) _SnowflakeMap = iso unSnowflakeMap SnowflakeMap instance Ixed (SnowflakeMap a) where ix i = _SnowflakeMap % ix i # INLINE ix # instance At (SnowflakeMap a) where at i = _SnowflakeMap % at i # INLINE at # overSM :: (HashMap (Snowflake a) a -> HashMap (Snowflake b) b) -> SnowflakeMap a -> SnowflakeMap b overSM f = SnowflakeMap . f . unSnowflakeMap # INLINEABLE overSM # -- SAFETY: 'Snowflake' always uses the underlying hash function (Word64) coerceSnowflakeMap :: HashMap (Snowflake a) v -> HashMap (Snowflake b) v coerceSnowflakeMap = unsafeCoerce # INLINEABLE coerceSnowflakeMap # empty :: SnowflakeMap a empty = SnowflakeMap SH.empty # INLINEABLE empty # singleton :: HasID' a => a -> SnowflakeMap a singleton v = SnowflakeMap $ SH.singleton (getID v) v # INLINEABLE singleton # null :: SnowflakeMap a -> Bool null = SH.null . unSnowflakeMap # INLINEABLE null # size :: SnowflakeMap a -> Int size = SH.size . unSnowflakeMap # INLINEABLE size # member :: Snowflake a -> SnowflakeMap a -> Bool member k = SH.member k . unSnowflakeMap # INLINEABLE member # lookup :: Snowflake a -> SnowflakeMap a -> Maybe a lookup k = SH.lookup k . unSnowflakeMap # INLINEABLE lookup # lookupDefault :: a -> Snowflake a -> SnowflakeMap a -> a lookupDefault d k = SH.lookupDefault d k . unSnowflakeMap # INLINEABLE lookupDefault # (!) :: SnowflakeMap a -> Snowflake a -> a (!) m k = unSnowflakeMap m SH.! k # INLINEABLE ( ! ) # infixl 9 ! insert :: HasID' a => a -> SnowflakeMap a -> SnowflakeMap a insert v = overSM $ SH.insert (getID v) v # INLINEABLE insert # insertWith :: HasID' a => (a -> a -> a) -> a -> SnowflakeMap a -> SnowflakeMap a insertWith f v = overSM $ SH.insertWith f (getID v) v # INLINEABLE insertWith # delete :: Snowflake a -> SnowflakeMap a -> SnowflakeMap a delete k = overSM $ SH.delete k # INLINEABLE delete # adjust :: (a -> a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a adjust f k = overSM $ SH.adjust f k # INLINEABLE adjust # update :: (a -> Maybe a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a update f k = overSM $ SH.update f k # INLINEABLE update # alter :: (Maybe a -> Maybe a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a alter f k = overSM $ SH.alter f k # INLINEABLE alter # union :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a union m m' = SnowflakeMap $ SH.union (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE union # unionWith :: (a -> a -> a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a unionWith f m m' = SnowflakeMap $ SH.unionWith f (unSnowflakeMap m) (unSnowflakeMap m') {-# INLINEABLE unionWith #-} unionWithKey :: (Snowflake a -> a -> a -> a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a unionWithKey f m m' = SnowflakeMap $ SH.unionWithKey f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE unionWithKey # unions :: [SnowflakeMap a] -> SnowflakeMap a unions = SnowflakeMap . SH.unions . Prelude.map unSnowflakeMap # INLINEABLE unions # map :: (a1 -> a2) -> SnowflakeMap a1 -> SnowflakeMap a2 map f = overSM $ coerceSnowflakeMap . SH.map f # INLINEABLE map # mapWithKey :: (Snowflake a1 -> a1 -> a2) -> SnowflakeMap a1 -> SnowflakeMap a2 mapWithKey f = overSM $ coerceSnowflakeMap . SH.mapWithKey f {-# INLINEABLE mapWithKey #-} traverseWithKey :: Applicative f => (Snowflake a1 -> a1 -> f a2) -> SnowflakeMap a1 -> f (SnowflakeMap a2) traverseWithKey f = fmap (SnowflakeMap . coerceSnowflakeMap) . SH.traverseWithKey f . unSnowflakeMap # INLINEABLE traverseWithKey # difference :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a difference m m' = SnowflakeMap $ SH.difference (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE difference # differenceWith :: (a -> a -> Maybe a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a differenceWith f m m' = SnowflakeMap $ SH.differenceWith f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE differenceWith # intersection :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a intersection m m' = SnowflakeMap $ SH.intersection (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE intersection # intersectionWith :: (a -> a -> b) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap b intersectionWith f m m' = SnowflakeMap . coerceSnowflakeMap $ SH.intersectionWith f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE intersectionWith # intersectionWithKey :: (Snowflake a -> a -> a -> b) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap b intersectionWithKey f m m' = SnowflakeMap . coerceSnowflakeMap $ SH.intersectionWithKey f (unSnowflakeMap m) (unSnowflakeMap m') {-# INLINEABLE intersectionWithKey #-} foldl' :: (a -> b -> a) -> a -> SnowflakeMap b -> a foldl' f s m = SH.foldl' f s $ unSnowflakeMap m # INLINEABLE foldl ' # foldlWithKey' :: (a -> Snowflake b -> b -> a) -> a -> SnowflakeMap b -> a foldlWithKey' f s m = SH.foldlWithKey' f s $ unSnowflakeMap m # INLINEABLE foldlWithKey ' # foldr :: (b -> a -> a) -> a -> SnowflakeMap b -> a foldr f s m = SH.foldr f s $ unSnowflakeMap m # INLINEABLE foldr # foldrWithKey :: (Snowflake b -> b -> a -> a) -> a -> SnowflakeMap b -> a foldrWithKey f s m = SH.foldrWithKey f s $ unSnowflakeMap m # INLINEABLE foldrWithKey # filter :: (a -> Bool) -> SnowflakeMap a -> SnowflakeMap a filter f = overSM $ SH.filter f # INLINEABLE filter # filterWithKey :: (Snowflake a -> a -> Bool) -> SnowflakeMap a -> SnowflakeMap a filterWithKey f = overSM $ SH.filterWithKey f # INLINEABLE filterWithKey # mapMaybe :: (a -> Maybe b) -> SnowflakeMap a -> SnowflakeMap b mapMaybe f = overSM $ coerceSnowflakeMap . SH.mapMaybe f {-# INLINEABLE mapMaybe #-} mapMaybeWithKey :: (Snowflake a -> a -> Maybe b) -> SnowflakeMap a -> SnowflakeMap b mapMaybeWithKey f = overSM $ coerceSnowflakeMap . SH.mapMaybeWithKey f # INLINEABLE mapMaybeWithKey # keys :: SnowflakeMap a -> [Snowflake a] keys = SH.keys . unSnowflakeMap # INLINEABLE keys # elems :: SnowflakeMap a -> [a] elems = SH.elems . unSnowflakeMap # INLINEABLE elems # toList :: SnowflakeMap a -> [(Snowflake a, a)] toList = SH.toList . unSnowflakeMap # INLINEABLE toList # fromList :: HasID' a => [a] -> SnowflakeMap a fromList = SnowflakeMap . SH.fromList . Prelude.map (\v -> (getID v, v)) # INLINEABLE fromList # fromListWith :: HasID' a => (a -> a -> a) -> [a] -> SnowflakeMap a fromListWith f = SnowflakeMap . SH.fromListWith f . Prelude.map (\v -> (getID v, v)) # INLINEABLE fromListWith # instance (FromJSON a, HasID' a) => FromJSON (SnowflakeMap a) where parseJSON = withArray "SnowflakeMap" $ \l -> do parsed <- traverse parseJSON l pure . Calamity.Internal.SnowflakeMap.fromList . F.toList $ parsed instance ToJSON a => ToJSON (SnowflakeMap a) where toJSON = toJSON . elems toEncoding = toEncoding . elems
null
https://raw.githubusercontent.com/simmsb/calamity/be310255b446e87e7432673de1fbc67ef46de3ae/calamity/Calamity/Internal/SnowflakeMap.hs
haskell
at k f m = at (unSnowflakeMap k) f m SAFETY: 'Snowflake' always uses the underlying hash function (Word64) # INLINEABLE unionWith # # INLINEABLE mapWithKey # # INLINEABLE intersectionWithKey # # INLINEABLE mapMaybe #
| Module for custom instance of Data . . Strict that decodes from any list of objects that have an i d field module Calamity.Internal.SnowflakeMap where import Calamity.Internal.Utils () import Calamity.Types.Snowflake import Data.Aeson (FromJSON (..), ToJSON (..), withArray) import Data.Data import Data.Foldable qualified as F import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as SH import Data.Hashable import GHC.Exts (IsList) import Optics import TextShow import Unsafe.Coerce newtype SnowflakeMap a = SnowflakeMap { unSnowflakeMap :: HashMap (Snowflake a) a } deriving stock (Eq, Data, Ord, Show) deriving (TextShow) via FromStringShow (SnowflakeMap a) deriving newtype (IsList, Semigroup, Monoid) deriving newtype (Hashable) instance At ( SnowflakeMap a ) where instance Functor SnowflakeMap where fmap f = SnowflakeMap . coerceSnowflakeMap . fmap f . unSnowflakeMap instance Foldable SnowflakeMap where foldr f b = Prelude.foldr f b . unSnowflakeMap instance Traversable SnowflakeMap where traverse f = fmap (SnowflakeMap . coerceSnowflakeMap) . traverse f . unSnowflakeMap type instance Index (SnowflakeMap a) = Snowflake a type instance IxValue (SnowflakeMap a) = a _SnowflakeMap :: ( Iso (SnowflakeMap a) (SnowflakeMap a1) (HashMap (Snowflake a) a) (HashMap (Snowflake a1) a1) ) _SnowflakeMap = iso unSnowflakeMap SnowflakeMap instance Ixed (SnowflakeMap a) where ix i = _SnowflakeMap % ix i # INLINE ix # instance At (SnowflakeMap a) where at i = _SnowflakeMap % at i # INLINE at # overSM :: (HashMap (Snowflake a) a -> HashMap (Snowflake b) b) -> SnowflakeMap a -> SnowflakeMap b overSM f = SnowflakeMap . f . unSnowflakeMap # INLINEABLE overSM # coerceSnowflakeMap :: HashMap (Snowflake a) v -> HashMap (Snowflake b) v coerceSnowflakeMap = unsafeCoerce # INLINEABLE coerceSnowflakeMap # empty :: SnowflakeMap a empty = SnowflakeMap SH.empty # INLINEABLE empty # singleton :: HasID' a => a -> SnowflakeMap a singleton v = SnowflakeMap $ SH.singleton (getID v) v # INLINEABLE singleton # null :: SnowflakeMap a -> Bool null = SH.null . unSnowflakeMap # INLINEABLE null # size :: SnowflakeMap a -> Int size = SH.size . unSnowflakeMap # INLINEABLE size # member :: Snowflake a -> SnowflakeMap a -> Bool member k = SH.member k . unSnowflakeMap # INLINEABLE member # lookup :: Snowflake a -> SnowflakeMap a -> Maybe a lookup k = SH.lookup k . unSnowflakeMap # INLINEABLE lookup # lookupDefault :: a -> Snowflake a -> SnowflakeMap a -> a lookupDefault d k = SH.lookupDefault d k . unSnowflakeMap # INLINEABLE lookupDefault # (!) :: SnowflakeMap a -> Snowflake a -> a (!) m k = unSnowflakeMap m SH.! k # INLINEABLE ( ! ) # infixl 9 ! insert :: HasID' a => a -> SnowflakeMap a -> SnowflakeMap a insert v = overSM $ SH.insert (getID v) v # INLINEABLE insert # insertWith :: HasID' a => (a -> a -> a) -> a -> SnowflakeMap a -> SnowflakeMap a insertWith f v = overSM $ SH.insertWith f (getID v) v # INLINEABLE insertWith # delete :: Snowflake a -> SnowflakeMap a -> SnowflakeMap a delete k = overSM $ SH.delete k # INLINEABLE delete # adjust :: (a -> a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a adjust f k = overSM $ SH.adjust f k # INLINEABLE adjust # update :: (a -> Maybe a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a update f k = overSM $ SH.update f k # INLINEABLE update # alter :: (Maybe a -> Maybe a) -> Snowflake a -> SnowflakeMap a -> SnowflakeMap a alter f k = overSM $ SH.alter f k # INLINEABLE alter # union :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a union m m' = SnowflakeMap $ SH.union (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE union # unionWith :: (a -> a -> a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a unionWith f m m' = SnowflakeMap $ SH.unionWith f (unSnowflakeMap m) (unSnowflakeMap m') unionWithKey :: (Snowflake a -> a -> a -> a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a unionWithKey f m m' = SnowflakeMap $ SH.unionWithKey f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE unionWithKey # unions :: [SnowflakeMap a] -> SnowflakeMap a unions = SnowflakeMap . SH.unions . Prelude.map unSnowflakeMap # INLINEABLE unions # map :: (a1 -> a2) -> SnowflakeMap a1 -> SnowflakeMap a2 map f = overSM $ coerceSnowflakeMap . SH.map f # INLINEABLE map # mapWithKey :: (Snowflake a1 -> a1 -> a2) -> SnowflakeMap a1 -> SnowflakeMap a2 mapWithKey f = overSM $ coerceSnowflakeMap . SH.mapWithKey f traverseWithKey :: Applicative f => (Snowflake a1 -> a1 -> f a2) -> SnowflakeMap a1 -> f (SnowflakeMap a2) traverseWithKey f = fmap (SnowflakeMap . coerceSnowflakeMap) . SH.traverseWithKey f . unSnowflakeMap # INLINEABLE traverseWithKey # difference :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a difference m m' = SnowflakeMap $ SH.difference (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE difference # differenceWith :: (a -> a -> Maybe a) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a differenceWith f m m' = SnowflakeMap $ SH.differenceWith f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE differenceWith # intersection :: SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap a intersection m m' = SnowflakeMap $ SH.intersection (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE intersection # intersectionWith :: (a -> a -> b) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap b intersectionWith f m m' = SnowflakeMap . coerceSnowflakeMap $ SH.intersectionWith f (unSnowflakeMap m) (unSnowflakeMap m') # INLINEABLE intersectionWith # intersectionWithKey :: (Snowflake a -> a -> a -> b) -> SnowflakeMap a -> SnowflakeMap a -> SnowflakeMap b intersectionWithKey f m m' = SnowflakeMap . coerceSnowflakeMap $ SH.intersectionWithKey f (unSnowflakeMap m) (unSnowflakeMap m') foldl' :: (a -> b -> a) -> a -> SnowflakeMap b -> a foldl' f s m = SH.foldl' f s $ unSnowflakeMap m # INLINEABLE foldl ' # foldlWithKey' :: (a -> Snowflake b -> b -> a) -> a -> SnowflakeMap b -> a foldlWithKey' f s m = SH.foldlWithKey' f s $ unSnowflakeMap m # INLINEABLE foldlWithKey ' # foldr :: (b -> a -> a) -> a -> SnowflakeMap b -> a foldr f s m = SH.foldr f s $ unSnowflakeMap m # INLINEABLE foldr # foldrWithKey :: (Snowflake b -> b -> a -> a) -> a -> SnowflakeMap b -> a foldrWithKey f s m = SH.foldrWithKey f s $ unSnowflakeMap m # INLINEABLE foldrWithKey # filter :: (a -> Bool) -> SnowflakeMap a -> SnowflakeMap a filter f = overSM $ SH.filter f # INLINEABLE filter # filterWithKey :: (Snowflake a -> a -> Bool) -> SnowflakeMap a -> SnowflakeMap a filterWithKey f = overSM $ SH.filterWithKey f # INLINEABLE filterWithKey # mapMaybe :: (a -> Maybe b) -> SnowflakeMap a -> SnowflakeMap b mapMaybe f = overSM $ coerceSnowflakeMap . SH.mapMaybe f mapMaybeWithKey :: (Snowflake a -> a -> Maybe b) -> SnowflakeMap a -> SnowflakeMap b mapMaybeWithKey f = overSM $ coerceSnowflakeMap . SH.mapMaybeWithKey f # INLINEABLE mapMaybeWithKey # keys :: SnowflakeMap a -> [Snowflake a] keys = SH.keys . unSnowflakeMap # INLINEABLE keys # elems :: SnowflakeMap a -> [a] elems = SH.elems . unSnowflakeMap # INLINEABLE elems # toList :: SnowflakeMap a -> [(Snowflake a, a)] toList = SH.toList . unSnowflakeMap # INLINEABLE toList # fromList :: HasID' a => [a] -> SnowflakeMap a fromList = SnowflakeMap . SH.fromList . Prelude.map (\v -> (getID v, v)) # INLINEABLE fromList # fromListWith :: HasID' a => (a -> a -> a) -> [a] -> SnowflakeMap a fromListWith f = SnowflakeMap . SH.fromListWith f . Prelude.map (\v -> (getID v, v)) # INLINEABLE fromListWith # instance (FromJSON a, HasID' a) => FromJSON (SnowflakeMap a) where parseJSON = withArray "SnowflakeMap" $ \l -> do parsed <- traverse parseJSON l pure . Calamity.Internal.SnowflakeMap.fromList . F.toList $ parsed instance ToJSON a => ToJSON (SnowflakeMap a) where toJSON = toJSON . elems toEncoding = toEncoding . elems
c35bb337d5c1cabc328c11c9d89353803e64c6ab0b581293d2e4cffbb8c8737a
foxford/mqtt-gateway
mqttgw_ratelimit.erl
-module(mqttgw_ratelimit). %% API -export([ read_config/0, read_config_file/1 ]). %% Types -type config() :: mqttgw_ratelimitstate:constraints(). %% ============================================================================= %% API %% ============================================================================= -spec read_config() -> disabled | {enabled, config()}. read_config() -> case os:getenv("APP_RATE_LIMIT_ENABLED", "1") of "0" -> error_logger:info_msg("[CONFIG] Rate limits are disabled~n"), disabled; _ -> Config = read_config_file(mqttgw_config:read_config_file()), error_logger:info_msg("[CONFIG] Rate limits are loaded: ~p~n", [Config]), {enabled, Config} end. -spec read_config_file(toml:config()) -> config(). read_config_file(TomlConfig) -> #{message_count => parse_message_count(TomlConfig), byte_count => parse_byte_count(TomlConfig)}. %% ============================================================================= Internal functions %% ============================================================================= -spec parse_message_count(toml:config()) -> non_neg_integer(). parse_message_count(TomlConfig) -> case toml:get_value(["rate_limit"], "message_count", TomlConfig) of {integer, Val} -> Val; Other -> error({bad_message_count, Other}) end. -spec parse_byte_count(toml:config()) -> non_neg_integer(). parse_byte_count(TomlConfig) -> case toml:get_value(["rate_limit"], "byte_count", TomlConfig) of {integer, Val} -> Val; Other -> error({bad_byte_count, Other}) end.
null
https://raw.githubusercontent.com/foxford/mqtt-gateway/21428a63ef6d3676934b51b8a96481c9274ad7ff/src/mqttgw_ratelimit.erl
erlang
API Types ============================================================================= API ============================================================================= ============================================================================= =============================================================================
-module(mqttgw_ratelimit). -export([ read_config/0, read_config_file/1 ]). -type config() :: mqttgw_ratelimitstate:constraints(). -spec read_config() -> disabled | {enabled, config()}. read_config() -> case os:getenv("APP_RATE_LIMIT_ENABLED", "1") of "0" -> error_logger:info_msg("[CONFIG] Rate limits are disabled~n"), disabled; _ -> Config = read_config_file(mqttgw_config:read_config_file()), error_logger:info_msg("[CONFIG] Rate limits are loaded: ~p~n", [Config]), {enabled, Config} end. -spec read_config_file(toml:config()) -> config(). read_config_file(TomlConfig) -> #{message_count => parse_message_count(TomlConfig), byte_count => parse_byte_count(TomlConfig)}. Internal functions -spec parse_message_count(toml:config()) -> non_neg_integer(). parse_message_count(TomlConfig) -> case toml:get_value(["rate_limit"], "message_count", TomlConfig) of {integer, Val} -> Val; Other -> error({bad_message_count, Other}) end. -spec parse_byte_count(toml:config()) -> non_neg_integer(). parse_byte_count(TomlConfig) -> case toml:get_value(["rate_limit"], "byte_count", TomlConfig) of {integer, Val} -> Val; Other -> error({bad_byte_count, Other}) end.
ed379e444501e342ce88b38d64dd6f8ae6e524353876c0329b93763950dea148
haskell-suite/haskell-src-exts
TrailingWhere2.hs
data Baz = Baz instance Show Baz where show _ = "" where show _ = ""
null
https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/TrailingWhere2.hs
haskell
data Baz = Baz instance Show Baz where show _ = "" where show _ = ""
5dee93f07084636b7f9206cb117ee389aecb34664e0c981cd92627ed01e3e65a
hasufell/hsfm
Data.hs
- HSFM , a written in Haskell . Copyright ( C ) 2016 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA . - HSFM, a filemanager written in Haskell. Copyright (C) 2016 Julian Ospald This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --} # OPTIONS_HADDOCK ignore - exports # module HSFM.GUI.Gtk.Data where import Control.Concurrent.MVar ( MVar ) import Control.Concurrent.STM ( TVar ) import Graphics.UI.Gtk hiding (MenuBar) import HSFM.FileSystem.FileType import HSFM.FileSystem.UtilTypes import HSFM.History import System.INotify ( INotify ) ------------------ --[ Base Types ]-- ------------------ -- |Monolithic object passed to various GUI functions in order -- to keep the API stable and not alter the parameters too much. -- This only holds GUI widgets that are needed to be read during -- runtime. data MyGUI = MkMyGUI { -- |main Window rootWin :: !Window -- widgets on the main window , menubar :: !MenuBar , statusBar :: !Statusbar , clearStatusBar :: !Button , notebook1 :: !Notebook , leftNbBtn :: !ToggleButton , leftNbIcon :: !Image , notebook2 :: !Notebook , rightNbBtn :: !ToggleButton , rightNbIcon :: !Image -- other , fprop :: !FilePropertyGrid , settings :: !(TVar FMSettings) , operationBuffer :: !(TVar FileOperation) } |This describes the contents of the current view and is separated from MyGUI , -- because we might want to have multiple views. data MyView = MkMyView { view :: !(TVar FMView) , cwd :: !(MVar Item) , rawModel :: !(TVar (ListStore Item)) , sortedModel :: !(TVar (TypedTreeModelSort Item)) , filteredModel :: !(TVar (TypedTreeModelFilter Item)) , inotify :: !(MVar INotify) , notebook :: !Notebook -- current notebook the first part of the tuple represents the " go back " the second part the " go forth " in the history , history :: !(MVar BrowsingHistory) -- sub-widgets , scroll :: !ScrolledWindow , viewBox :: !Box , backViewB :: !Button , upViewB :: !Button , forwardViewB :: !Button , homeViewB :: !Button , refreshViewB :: !Button , urlBar :: !Entry } data MenuBar = MkMenuBar { menubarFileQuit :: !ImageMenuItem , menubarHelpAbout :: !ImageMenuItem } data RightClickMenu = MkRightClickMenu { rcMenu :: !Menu , rcFileOpen :: !ImageMenuItem , rcFileExecute :: !ImageMenuItem , rcFileNewRegFile :: !ImageMenuItem , rcFileNewDir :: !ImageMenuItem , rcFileNewTab :: !ImageMenuItem , rcFileNewTerm :: !ImageMenuItem , rcFileCut :: !ImageMenuItem , rcFileCopy :: !ImageMenuItem , rcFileRename :: !ImageMenuItem , rcFilePaste :: !ImageMenuItem , rcFileDelete :: !ImageMenuItem , rcFileProperty :: !ImageMenuItem , rcFileIconView :: !ImageMenuItem , rcFileTreeView :: !ImageMenuItem } data FilePropertyGrid = MkFilePropertyGrid { fpropGrid :: !Grid , fpropFnEntry :: !Entry , fpropLocEntry :: !Entry , fpropTsEntry :: !Entry , fpropModEntry :: !Entry , fpropAcEntry :: !Entry , fpropFTEntry :: !Entry , fpropPermEntry :: !Entry , fpropLDEntry :: !Entry } -- |FM-wide settings. data FMSettings = MkFMSettings { showHidden :: !Bool , isLazy :: !Bool , iconSize :: !Int } data FMView = FMTreeView !TreeView | FMIconView !IconView type Item = File FileInfo fmViewToContainer :: FMView -> Container fmViewToContainer (FMTreeView x) = castToContainer . toGObject $ x fmViewToContainer (FMIconView x) = castToContainer . toGObject $ x
null
https://raw.githubusercontent.com/hasufell/hsfm/322c766ae534fb21e3427d2845011123ddb90952/src/HSFM/GUI/Gtk/Data.hs
haskell
} ---------------- [ Base Types ]-- ---------------- |Monolithic object passed to various GUI functions in order to keep the API stable and not alter the parameters too much. This only holds GUI widgets that are needed to be read during runtime. |main Window widgets on the main window other because we might want to have multiple views. current notebook sub-widgets |FM-wide settings.
- HSFM , a written in Haskell . Copyright ( C ) 2016 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA . - HSFM, a filemanager written in Haskell. Copyright (C) 2016 Julian Ospald This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # OPTIONS_HADDOCK ignore - exports # module HSFM.GUI.Gtk.Data where import Control.Concurrent.MVar ( MVar ) import Control.Concurrent.STM ( TVar ) import Graphics.UI.Gtk hiding (MenuBar) import HSFM.FileSystem.FileType import HSFM.FileSystem.UtilTypes import HSFM.History import System.INotify ( INotify ) data MyGUI = MkMyGUI { rootWin :: !Window , menubar :: !MenuBar , statusBar :: !Statusbar , clearStatusBar :: !Button , notebook1 :: !Notebook , leftNbBtn :: !ToggleButton , leftNbIcon :: !Image , notebook2 :: !Notebook , rightNbBtn :: !ToggleButton , rightNbIcon :: !Image , fprop :: !FilePropertyGrid , settings :: !(TVar FMSettings) , operationBuffer :: !(TVar FileOperation) } |This describes the contents of the current view and is separated from MyGUI , data MyView = MkMyView { view :: !(TVar FMView) , cwd :: !(MVar Item) , rawModel :: !(TVar (ListStore Item)) , sortedModel :: !(TVar (TypedTreeModelSort Item)) , filteredModel :: !(TVar (TypedTreeModelFilter Item)) , inotify :: !(MVar INotify) the first part of the tuple represents the " go back " the second part the " go forth " in the history , history :: !(MVar BrowsingHistory) , scroll :: !ScrolledWindow , viewBox :: !Box , backViewB :: !Button , upViewB :: !Button , forwardViewB :: !Button , homeViewB :: !Button , refreshViewB :: !Button , urlBar :: !Entry } data MenuBar = MkMenuBar { menubarFileQuit :: !ImageMenuItem , menubarHelpAbout :: !ImageMenuItem } data RightClickMenu = MkRightClickMenu { rcMenu :: !Menu , rcFileOpen :: !ImageMenuItem , rcFileExecute :: !ImageMenuItem , rcFileNewRegFile :: !ImageMenuItem , rcFileNewDir :: !ImageMenuItem , rcFileNewTab :: !ImageMenuItem , rcFileNewTerm :: !ImageMenuItem , rcFileCut :: !ImageMenuItem , rcFileCopy :: !ImageMenuItem , rcFileRename :: !ImageMenuItem , rcFilePaste :: !ImageMenuItem , rcFileDelete :: !ImageMenuItem , rcFileProperty :: !ImageMenuItem , rcFileIconView :: !ImageMenuItem , rcFileTreeView :: !ImageMenuItem } data FilePropertyGrid = MkFilePropertyGrid { fpropGrid :: !Grid , fpropFnEntry :: !Entry , fpropLocEntry :: !Entry , fpropTsEntry :: !Entry , fpropModEntry :: !Entry , fpropAcEntry :: !Entry , fpropFTEntry :: !Entry , fpropPermEntry :: !Entry , fpropLDEntry :: !Entry } data FMSettings = MkFMSettings { showHidden :: !Bool , isLazy :: !Bool , iconSize :: !Int } data FMView = FMTreeView !TreeView | FMIconView !IconView type Item = File FileInfo fmViewToContainer :: FMView -> Container fmViewToContainer (FMTreeView x) = castToContainer . toGObject $ x fmViewToContainer (FMIconView x) = castToContainer . toGObject $ x
681fe8ff13946bb74591c71729fb48f085787fd5874d796bdeffd90fc19a4ce1
janestreet/universe
token.ml
open Base open Ppxlib module Directive = struct type t = If | Else | Elif | Endif | Ifdef | Ifndef | Define | Undef | Error | Warning | Import | (* deprecated, but provide useful warnings *) Elifdef | Elifndef let matches ~expected matched = String.(=) expected matched || String.(=) ("optcomp." ^ expected) matched (* not using [matches] here because I'm pretty sure the pattern matching compiler will make this faster than string equality. *) let of_string_opt s = match s with | "optcomp.if" | "if" -> Some If | "optcomp.else" | "else" -> Some Else | "optcomp.elif" | "elif" -> Some Elif | "optcomp.endif" | "endif" -> Some Endif | "optcomp.ifdef" | "ifdef" -> Some Ifdef | "optcomp.ifndef" | "ifndef" -> Some Ifndef | "optcomp.define" | "define" -> Some Define | "optcomp.undef" | "undef" -> Some Undef | "optcomp.error" -> Some Error | "optcomp.warning" | "warning" -> Some Warning | "optcomp.import" | "import" -> Some Import | "optcomp.elifdef" | "elifdef" -> Some Elifdef | "optcomp.elifndef" | "elifndef" -> Some Elifndef | _ -> None end type 'a t = | Block of 'a list (** blocks with no optcomp extensions in it *) | Directive of Directive.t * location * payload let make_directive name loc payload = match Directive.of_string_opt name with | Some dir -> Directive (dir, loc, payload) | None -> Location.raise_errorf ~loc "optcomp: unknown directive" let just_directives_exn ~loc ls = List.filter_map ls ~f:(fun token -> match token with | Directive _ as dir -> Some dir | Block [] -> None | Block _ -> Location.raise_errorf ~loc "optcomp: only optcomp directives allowed in this context" )
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/ppx_optcomp/src/token.ml
ocaml
deprecated, but provide useful warnings not using [matches] here because I'm pretty sure the pattern matching compiler will make this faster than string equality. * blocks with no optcomp extensions in it
open Base open Ppxlib module Directive = struct type t = If | Else | Elif | Endif | Ifdef | Ifndef | Define | Undef | Error | Warning | Import | Elifdef | Elifndef let matches ~expected matched = String.(=) expected matched || String.(=) ("optcomp." ^ expected) matched let of_string_opt s = match s with | "optcomp.if" | "if" -> Some If | "optcomp.else" | "else" -> Some Else | "optcomp.elif" | "elif" -> Some Elif | "optcomp.endif" | "endif" -> Some Endif | "optcomp.ifdef" | "ifdef" -> Some Ifdef | "optcomp.ifndef" | "ifndef" -> Some Ifndef | "optcomp.define" | "define" -> Some Define | "optcomp.undef" | "undef" -> Some Undef | "optcomp.error" -> Some Error | "optcomp.warning" | "warning" -> Some Warning | "optcomp.import" | "import" -> Some Import | "optcomp.elifdef" | "elifdef" -> Some Elifdef | "optcomp.elifndef" | "elifndef" -> Some Elifndef | _ -> None end type 'a t = | Directive of Directive.t * location * payload let make_directive name loc payload = match Directive.of_string_opt name with | Some dir -> Directive (dir, loc, payload) | None -> Location.raise_errorf ~loc "optcomp: unknown directive" let just_directives_exn ~loc ls = List.filter_map ls ~f:(fun token -> match token with | Directive _ as dir -> Some dir | Block [] -> None | Block _ -> Location.raise_errorf ~loc "optcomp: only optcomp directives allowed in this context" )
aa46b8443e71e11a8ce818bea0f8ba9df7abbf89eec0842dc0c30c0c338c5f60
sbtourist/clamq
project.clj
(defproject clamq "0.5-SNAPSHOT" :description "Clojure APIs for Message Queues" :dev-dependencies [[lein-sub "0.1.1"]] :sub ["clamq-core" "clamq-jms" "clamq-activemq" "clamq-rabbitmq" "clamq-runner"])
null
https://raw.githubusercontent.com/sbtourist/clamq/34a6bbcb7a2a431ea629aa5cfbc687ef31f860f2/project.clj
clojure
(defproject clamq "0.5-SNAPSHOT" :description "Clojure APIs for Message Queues" :dev-dependencies [[lein-sub "0.1.1"]] :sub ["clamq-core" "clamq-jms" "clamq-activemq" "clamq-rabbitmq" "clamq-runner"])
ceba3901a69b64d8b9b46e917ab2eaa508d80e09aba8d4d434f24c801f2a2291
MarkCurtiss/sicp
interpreted-procedures-compiler.scm
(load "book_code/ch5-compiler.scm") ;; generate interpreted procedure calls (define (compile-procedure-call target linkage) (let ((primitive-branch (make-label 'primitive-branch)) (compiled-branch (make-label 'compiled-branch)) (interpreted-branch (make-label 'interpreted-branch)) (after-call (make-label 'after-call))) (let ((compiled-linkage (if (eq? linkage 'next) after-call linkage))) (append-instruction-sequences (make-instruction-sequence '(proc) '() `((test (op primitive-procedure?) (reg proc)) (branch (label ,primitive-branch)) (test (op compound-procedure?) (reg proc)) (branch (label, interpreted-branch)))) (parallel-instruction-sequences (append-instruction-sequences compiled-branch (compile-proc-appl target compiled-linkage)) (parallel-instruction-sequences (append-instruction-sequences interpreted-branch (compile-interp-proc-appl target compiled-linkage)) (append-instruction-sequences primitive-branch (end-with-linkage linkage (make-instruction-sequence '(proc argl) (list target) `((assign ,target (op apply-primitive-procedure) (reg proc) (reg argl))))))) ) after-call)))) ;; applying interpreted procedures (define (compile-interp-proc-appl target linkage) (cond ((and (eq? target 'val) (not (eq? linkage 'return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,linkage)) (save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (not (eq? linkage 'return))) (let ((proc-return (make-label 'proc-return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,proc-return)) (save continue) (goto (reg compapp)) ,proc-return (assign ,target (reg val)) (goto (label ,linkage)))))) ((and (eq? target 'val) (eq? linkage 'return)) (make-instruction-sequence '(proc continue) all-regs '((save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (eq? linkage 'return)) (error "return linkage, target not val -- COMPILE" target))))
null
https://raw.githubusercontent.com/MarkCurtiss/sicp/8b55a3371458014c815ba8792218b6440127ab40/chapter_5_exercises/interpreted-procedures-compiler.scm
scheme
generate interpreted procedure calls applying interpreted procedures
(load "book_code/ch5-compiler.scm") (define (compile-procedure-call target linkage) (let ((primitive-branch (make-label 'primitive-branch)) (compiled-branch (make-label 'compiled-branch)) (interpreted-branch (make-label 'interpreted-branch)) (after-call (make-label 'after-call))) (let ((compiled-linkage (if (eq? linkage 'next) after-call linkage))) (append-instruction-sequences (make-instruction-sequence '(proc) '() `((test (op primitive-procedure?) (reg proc)) (branch (label ,primitive-branch)) (test (op compound-procedure?) (reg proc)) (branch (label, interpreted-branch)))) (parallel-instruction-sequences (append-instruction-sequences compiled-branch (compile-proc-appl target compiled-linkage)) (parallel-instruction-sequences (append-instruction-sequences interpreted-branch (compile-interp-proc-appl target compiled-linkage)) (append-instruction-sequences primitive-branch (end-with-linkage linkage (make-instruction-sequence '(proc argl) (list target) `((assign ,target (op apply-primitive-procedure) (reg proc) (reg argl))))))) ) after-call)))) (define (compile-interp-proc-appl target linkage) (cond ((and (eq? target 'val) (not (eq? linkage 'return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,linkage)) (save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (not (eq? linkage 'return))) (let ((proc-return (make-label 'proc-return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,proc-return)) (save continue) (goto (reg compapp)) ,proc-return (assign ,target (reg val)) (goto (label ,linkage)))))) ((and (eq? target 'val) (eq? linkage 'return)) (make-instruction-sequence '(proc continue) all-regs '((save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (eq? linkage 'return)) (error "return linkage, target not val -- COMPILE" target))))
4cc9b9e2d94e3bd2ea73196d42c7874410ea6bdba286bbaa1362a122e6350092
acl2/acl2
variable-mix-upper-lower-case.cpp.ref.ast.lsp
(funcdef foo (a) (block (declare A 2) (return a)))
null
https://raw.githubusercontent.com/acl2/acl2/c2d69bad0ed3132cc19a00cb632de8b73558b1f9/books/projects/rac/tests/yaml_test/program_structure/variable-mix-upper-lower-case.cpp.ref.ast.lsp
lisp
(funcdef foo (a) (block (declare A 2) (return a)))
09e744798bdfcade93eda4e3530901c0d3a711e07136c6259fe7e758203f333f
c-cube/funarith
Rat_zarith.mli
include Funarith.Rat.S with type t = Q.t
null
https://raw.githubusercontent.com/c-cube/funarith/1c86ac45e9608efaa761e3f14455402730885339/src/zarith/Rat_zarith.mli
ocaml
include Funarith.Rat.S with type t = Q.t
df77190d37100c42085fde8e9dc0ad49d62436c177b99092e406bd9b751d2336
binsec/binsec
imap.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2022 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 ) . (* *) (**************************************************************************) (* TODO: poor man interval map -- sorted list *) include Map.Make (struct type t = Z.t * Z.t let compare (lo, hi) (lo', hi') = if Z.lt hi lo' then -1 else if Z.gt lo hi' then 1 else 0 end) let add ~base size x t = add (base, Z.pred (Z.add base (Z.of_int size))) x t let mem a t = mem (a, a) t let find a t = find (a, a) t
null
https://raw.githubusercontent.com/binsec/binsec/8ed9991d36451a3ae7487b966c4b38acca21a5b3/src/base/imap.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. ************************************************************************ TODO: poor man interval map -- sorted list
This file is part of BINSEC . Copyright ( C ) 2016 - 2022 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 ) . include Map.Make (struct type t = Z.t * Z.t let compare (lo, hi) (lo', hi') = if Z.lt hi lo' then -1 else if Z.gt lo hi' then 1 else 0 end) let add ~base size x t = add (base, Z.pred (Z.add base (Z.of_int size))) x t let mem a t = mem (a, a) t let find a t = find (a, a) t
b252d28dab208ea91a6c0fd9495b0109df2ee047edfb301cc1f6b39ed9a18917
Leberwurscht/Diaspora-User-Directory
bdbwrap.ml
(************************************************************************) This file is part of SKS . SKS is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (***********************************************************************) (** Wrapper module for Bdb to allow for logging of database operations *) open Common open Printf exception Key_exists = Bdb.Key_exists let wrap name f = plerror 10 "( Starting %s" name; try let rval = f () in plerror 10 " %s Done )" name; rval with e -> plerror 10 " %s Done <%s>)" name (Printexc.to_string e); raise e module Dbenv = struct include Bdb.Dbenv let create x = wrap "Dbenv.create" (fun () -> create x) let dopen x y z w = wrap "Dbenv.dopen" (fun () -> dopen x y z w) let sopen x y z = wrap "Dbenv.sopen" (fun () -> sopen x y z) let close x = wrap "Dbenv.close" (fun () -> close x) let set_verbose_internal x y z = wrap "Dbenv.set_verbose_internal" (fun () -> set_verbose_internal x y z) let set_verbose x y z = wrap "Dbenv.set_verbose" (fun () -> set_verbose x y z) let set_cachesize x ~gbytes ~bytes ~ncache = wrap "Dbenv.set_cachesize" (fun () -> set_cachesize x ~gbytes ~bytes ~ncache) end module Db = struct include Bdb.Db let create ?dbenv y = wrap "Db.create" (fun () -> create ?dbenv y) let dopen x y z w u = wrap "Db.dopen" (fun () -> dopen x y z w u) let close x = wrap "Db.close" (fun () -> close x) let del x ?txn y = wrap "Db.del" (fun () -> del x ?txn y) let put x ?txn ~key ~data y = wrap "Db.put" (fun () -> put x ?txn ~key ~data y) let get x ?txn y z = wrap "Db.get" (fun () -> get x ?txn y z ) let set_flags x y = wrap "Db.set_flags" (fun () -> set_flags x y) let sopen ?dbenv x y ?moreflags z w = wrap "Db.sopen" (fun () -> sopen ?dbenv x y ?moreflags z w ) let set_h_ffactor x y = wrap "Db.set_h_ffactor" (fun () -> set_h_ffactor x y) let set_pagesize x y = wrap "Db.set_pagesize" (fun () -> set_pagesize x y) let set_cachesize x ~gbytes ~bytes ~ncache = wrap "Db.set_cachesize" (fun () -> set_cachesize x ~gbytes ~bytes ~ncache) let sync x = wrap "Db.sync" (fun () -> sync x) end module Cursor = struct include Bdb.Cursor let create ?writecursor ?txn x = wrap "Cursor.create" (fun () -> create ?writecursor ?txn x) let close x = wrap "Cursor.close" (fun () -> close x) let put x y z = wrap "Cursor.put" (fun () -> put x y z) let kput x ~key ~data y = wrap "Cursor.kput" (fun () -> kput x ~key ~data y ) let init x y z = wrap "Cursor.init" (fun () -> init x y z ) let init_range x y z = wrap "Cursor.init_range" (fun () -> init_range x y z ) let init_both x ~key ~data y = wrap "Cursor.init_both" (fun () -> init_both x ~key ~data y) let get x y z = wrap "Cursor.get" (fun () -> get x y z ) let get_keyonly x y z = wrap "Cursor.get_keyonly" (fun () -> get_keyonly x y z ) let del x = wrap "Cursor.del" (fun () -> del x) let count x = wrap "Cursor.count" (fun () -> count x ) let dup ?keep_position x = wrap "Cursor.dup" (fun () -> dup ?keep_position x) let ajoin ?nosort x y z = wrap "Cursor.ajoin" (fun () -> ajoin ?nosort x y z) let join ?nosort x y z = wrap "Cursor.join" (fun () -> join ?nosort x y z) end module Txn = struct include Bdb.Txn let set_txn_max x y = wrap "Txn.set_txn_max" (fun () -> set_txn_max x y) let abort x = wrap "Txn.abort" (fun () -> abort x) let txn_begin x y z = wrap "Txn.txn_begin" (fun () -> txn_begin x y z) let checkpoint x ~kbyte ~min y = wrap "Txn.checkpoint" (fun () -> checkpoint x ~kbyte ~min y) let commit x y = wrap "Txn.commit" (fun () -> commit x y) end
null
https://raw.githubusercontent.com/Leberwurscht/Diaspora-User-Directory/1ca4a06a67d591760516edffddb0308b86b6314c/trie_manager/bdbwrap.ml
ocaml
********************************************************************** ********************************************************************* * Wrapper module for Bdb to allow for logging of database operations
This file is part of SKS . SKS is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open Common open Printf exception Key_exists = Bdb.Key_exists let wrap name f = plerror 10 "( Starting %s" name; try let rval = f () in plerror 10 " %s Done )" name; rval with e -> plerror 10 " %s Done <%s>)" name (Printexc.to_string e); raise e module Dbenv = struct include Bdb.Dbenv let create x = wrap "Dbenv.create" (fun () -> create x) let dopen x y z w = wrap "Dbenv.dopen" (fun () -> dopen x y z w) let sopen x y z = wrap "Dbenv.sopen" (fun () -> sopen x y z) let close x = wrap "Dbenv.close" (fun () -> close x) let set_verbose_internal x y z = wrap "Dbenv.set_verbose_internal" (fun () -> set_verbose_internal x y z) let set_verbose x y z = wrap "Dbenv.set_verbose" (fun () -> set_verbose x y z) let set_cachesize x ~gbytes ~bytes ~ncache = wrap "Dbenv.set_cachesize" (fun () -> set_cachesize x ~gbytes ~bytes ~ncache) end module Db = struct include Bdb.Db let create ?dbenv y = wrap "Db.create" (fun () -> create ?dbenv y) let dopen x y z w u = wrap "Db.dopen" (fun () -> dopen x y z w u) let close x = wrap "Db.close" (fun () -> close x) let del x ?txn y = wrap "Db.del" (fun () -> del x ?txn y) let put x ?txn ~key ~data y = wrap "Db.put" (fun () -> put x ?txn ~key ~data y) let get x ?txn y z = wrap "Db.get" (fun () -> get x ?txn y z ) let set_flags x y = wrap "Db.set_flags" (fun () -> set_flags x y) let sopen ?dbenv x y ?moreflags z w = wrap "Db.sopen" (fun () -> sopen ?dbenv x y ?moreflags z w ) let set_h_ffactor x y = wrap "Db.set_h_ffactor" (fun () -> set_h_ffactor x y) let set_pagesize x y = wrap "Db.set_pagesize" (fun () -> set_pagesize x y) let set_cachesize x ~gbytes ~bytes ~ncache = wrap "Db.set_cachesize" (fun () -> set_cachesize x ~gbytes ~bytes ~ncache) let sync x = wrap "Db.sync" (fun () -> sync x) end module Cursor = struct include Bdb.Cursor let create ?writecursor ?txn x = wrap "Cursor.create" (fun () -> create ?writecursor ?txn x) let close x = wrap "Cursor.close" (fun () -> close x) let put x y z = wrap "Cursor.put" (fun () -> put x y z) let kput x ~key ~data y = wrap "Cursor.kput" (fun () -> kput x ~key ~data y ) let init x y z = wrap "Cursor.init" (fun () -> init x y z ) let init_range x y z = wrap "Cursor.init_range" (fun () -> init_range x y z ) let init_both x ~key ~data y = wrap "Cursor.init_both" (fun () -> init_both x ~key ~data y) let get x y z = wrap "Cursor.get" (fun () -> get x y z ) let get_keyonly x y z = wrap "Cursor.get_keyonly" (fun () -> get_keyonly x y z ) let del x = wrap "Cursor.del" (fun () -> del x) let count x = wrap "Cursor.count" (fun () -> count x ) let dup ?keep_position x = wrap "Cursor.dup" (fun () -> dup ?keep_position x) let ajoin ?nosort x y z = wrap "Cursor.ajoin" (fun () -> ajoin ?nosort x y z) let join ?nosort x y z = wrap "Cursor.join" (fun () -> join ?nosort x y z) end module Txn = struct include Bdb.Txn let set_txn_max x y = wrap "Txn.set_txn_max" (fun () -> set_txn_max x y) let abort x = wrap "Txn.abort" (fun () -> abort x) let txn_begin x y z = wrap "Txn.txn_begin" (fun () -> txn_begin x y z) let checkpoint x ~kbyte ~min y = wrap "Txn.checkpoint" (fun () -> checkpoint x ~kbyte ~min y) let commit x y = wrap "Txn.commit" (fun () -> commit x y) end
3407a7237a90aab417579bc127750a41f0c14c959a7377b82af6f123ab9710d7
haskellari/indexed-traversable
CoerceCompat.hs
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 702 # LANGUAGE Trustworthy # #endif module CoerceCompat where #if __GLASGOW_HASKELL__ >=708 import Data.Coerce (Coercible, coerce) #else import Unsafe.Coerce (unsafeCoerce) #endif #if __GLASGOW_HASKELL__ >=708 (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) _ #. x = coerce x (#..) :: Coercible b c => (b -> c) -> (i -> a -> b) -> (i -> a -> c) _ #.. x = coerce x #else (#.) :: (b -> c) -> (a -> b) -> (a -> c) _ #. x = unsafeCoerce x (#..) :: (b -> c) -> (i -> a -> b) -> (i -> a -> c) _ #.. x = unsafeCoerce x #endif infixr 9 #., #.. # INLINE ( # . ) # # INLINE ( # .. ) #
null
https://raw.githubusercontent.com/haskellari/indexed-traversable/8403a52163e5b8f3ec32a2846b53ccc2e8088a6f/indexed-traversable/src/CoerceCompat.hs
haskell
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 702 # LANGUAGE Trustworthy # #endif module CoerceCompat where #if __GLASGOW_HASKELL__ >=708 import Data.Coerce (Coercible, coerce) #else import Unsafe.Coerce (unsafeCoerce) #endif #if __GLASGOW_HASKELL__ >=708 (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) _ #. x = coerce x (#..) :: Coercible b c => (b -> c) -> (i -> a -> b) -> (i -> a -> c) _ #.. x = coerce x #else (#.) :: (b -> c) -> (a -> b) -> (a -> c) _ #. x = unsafeCoerce x (#..) :: (b -> c) -> (i -> a -> b) -> (i -> a -> c) _ #.. x = unsafeCoerce x #endif infixr 9 #., #.. # INLINE ( # . ) # # INLINE ( # .. ) #
8fbc0bb21a5240a802c72dd57b8ccd73f7e05427fa3e1fe76e4c1b255ba6e5a5
erdos/sphere
macros.clj
(ns erdos.lenart.macros) (defn- expr-branch? [x] (and (coll? x) (not (and (seq? x) (= 'quote (first x)))))) (defn- expr-deref? [x] (when (and (seq? x) (= 'clojure.core/deref (first x))) (second x))) (def genkwd "Generate a random keyword, like gensym" (comp keyword name gensym)) (defmacro defatom= [n expr] (assert (symbol? n)) (let [expr (clojure.walk/macroexpand-all expr) xs (->> (tree-seq expr-branch? seq expr) (keep expr-deref?) (filter symbol?)) f (gensym)] `(let [~f (fn [] ~expr)] (def ~(with-meta n nil) (reagent.core/atom (~f))) ~@(for [x xs] (list 'add-watch x (genkwd) (list 'fn '[_ _ _ _] (list 'reset! n (list f))))) #'~n))) (defmacro fnx [& bodies] `(fn [~'x] & bodies)) (defmacro fnxy [& bodies] `(fn [~'x ~'y] & bodies)) (defmacro fnxyz [& bodies] `(fn [~'x ~'y ~'z] & bodies)) (defmacro fn-> [& bodies] `(fn [x#] (-> x# ~@bodies))) (defmacro fn->> [& bodies] `(fn [x#] (->> x# ~@bodies))) (defn partial_ [f & xs] (fn [x] (apply f x xs))) (defmacro comp_ [& fs] `(comp ~@(reverse fs))) ;; procedural style programming (defn- proc-disp ([] ::end) ([x & _] x)) (defmulti proc proc-disp :default ::default) (defmethod proc ::end []) (defmethod proc ::default [x & xs] `(do ~x ~(apply proc xs))) (defmethod proc :if [_ c & xs] (let [[as [_ & bs]] (split-with #{:else} xs)] ;; todo: find :elsif clauses in #'as `(if ~c ~(apply proc as) ~(apply proc bs)))) (defmethod proc :when [_ y & xs] `(if ~y ~(apply proc xs)) ) (defmethod proc :let [_ bs & xs] `(let ~bs ~(apply proc xs))) (defmethod proc :for [_ bs & xs] `(for ~bs ~(apply proc xs))) (defmethod proc :loop [_ bs & xs] `(loop ~bs ~(apply proc xs))) ;; todo: test :recur clause (defmethod proc :recur [_ & bs] `(recur ~@bs)) (defn scalar? [x] (or (string? x) (number? x) (nil? x) (keyword? x) (true? x) (false? x))) (defn- match-seq-1 [b case then else] (assert (symbol? b)) (assert (vector? case)) (let [ks (for [[i k] (map vector (range) case) :when (not (symbol? k))] `(= (nth ~b ~i) ~k)) rest? (if (-> case butlast last (= '&)) (last case)) ls (for [[i k] (map vector (range) case) :when (symbol? k)] `(~k (nth ~b ~i))) ls (if rest? (butlast (butlast ls)) ls) cnt (if rest? `(<= ~(dec (dec (count case))) (count ~b)) `(= ~(count case) (count ~b)))] (assert (or rest? cnt (seq ks)) (str "No literal in pattern: " case)) `(if (and ~cnt ~@ks) (let [~@(apply concat ls) ~@(if rest? `(~rest? (nthrest ~b ~(- (count case) 2))))] ~then) ~else))) (defmacro match-seq [expr & clauses] (let [b (gensym) cls (partition 2 clauses) default (if (odd? (count clauses)) (last clauses) `(assert false (str "no match for " ~b))) ] `(let [~b ~expr] ~(reduce (fn [acc [cond then]] (match-seq-1 b cond then acc)) default (reverse cls))))) (defmacro template [p & itms] ( .log js / console ( str p ( type p ) ) ) (assert (string? p) (str "no str: " p)) (let [ls (.split p "%")] (assert (= (dec (count ls)) (count itms)) (str "arg count does not match")) `(str ~@(interleave ls itms)) ) ;; idea; can parse str now ) (defmacro format [s & params] (loop [xs [] ;; output s s [p & ps] params] (let [idx (.indexOf s "%")] (if (neg? idx) (do (assert (nil? p)) `(.join (cljs.core/array ~@(remove #{""} (conj xs s))) "")) (let [s0 (.substring s 0 idx) st (.substring s (inc idx))] (cond (.startsWith st "d") (recur (conj xs s0 p) (.substring st 1) ps) (.startsWith st ".4f") (recur (conj xs s0 `(.toFixed ~p 4)) (.substring st 3) ps) (.startsWith st ".2f") (recur (conj xs s0 `(.toFixed ~p 2)) (.substring st 3) ps) :else (assert false "Unexpected str!"))))))) :OK
null
https://raw.githubusercontent.com/erdos/sphere/8de04d3e7c2b18430cff5d3f05933c8243919523/src/erdos/lenart/macros.clj
clojure
procedural style programming todo: find :elsif clauses in #'as todo: test :recur clause idea; can parse str now output
(ns erdos.lenart.macros) (defn- expr-branch? [x] (and (coll? x) (not (and (seq? x) (= 'quote (first x)))))) (defn- expr-deref? [x] (when (and (seq? x) (= 'clojure.core/deref (first x))) (second x))) (def genkwd "Generate a random keyword, like gensym" (comp keyword name gensym)) (defmacro defatom= [n expr] (assert (symbol? n)) (let [expr (clojure.walk/macroexpand-all expr) xs (->> (tree-seq expr-branch? seq expr) (keep expr-deref?) (filter symbol?)) f (gensym)] `(let [~f (fn [] ~expr)] (def ~(with-meta n nil) (reagent.core/atom (~f))) ~@(for [x xs] (list 'add-watch x (genkwd) (list 'fn '[_ _ _ _] (list 'reset! n (list f))))) #'~n))) (defmacro fnx [& bodies] `(fn [~'x] & bodies)) (defmacro fnxy [& bodies] `(fn [~'x ~'y] & bodies)) (defmacro fnxyz [& bodies] `(fn [~'x ~'y ~'z] & bodies)) (defmacro fn-> [& bodies] `(fn [x#] (-> x# ~@bodies))) (defmacro fn->> [& bodies] `(fn [x#] (->> x# ~@bodies))) (defn partial_ [f & xs] (fn [x] (apply f x xs))) (defmacro comp_ [& fs] `(comp ~@(reverse fs))) (defn- proc-disp ([] ::end) ([x & _] x)) (defmulti proc proc-disp :default ::default) (defmethod proc ::end []) (defmethod proc ::default [x & xs] `(do ~x ~(apply proc xs))) (defmethod proc :if [_ c & xs] (let [[as [_ & bs]] (split-with #{:else} xs)] `(if ~c ~(apply proc as) ~(apply proc bs)))) (defmethod proc :when [_ y & xs] `(if ~y ~(apply proc xs)) ) (defmethod proc :let [_ bs & xs] `(let ~bs ~(apply proc xs))) (defmethod proc :for [_ bs & xs] `(for ~bs ~(apply proc xs))) (defmethod proc :loop [_ bs & xs] `(loop ~bs ~(apply proc xs))) (defmethod proc :recur [_ & bs] `(recur ~@bs)) (defn scalar? [x] (or (string? x) (number? x) (nil? x) (keyword? x) (true? x) (false? x))) (defn- match-seq-1 [b case then else] (assert (symbol? b)) (assert (vector? case)) (let [ks (for [[i k] (map vector (range) case) :when (not (symbol? k))] `(= (nth ~b ~i) ~k)) rest? (if (-> case butlast last (= '&)) (last case)) ls (for [[i k] (map vector (range) case) :when (symbol? k)] `(~k (nth ~b ~i))) ls (if rest? (butlast (butlast ls)) ls) cnt (if rest? `(<= ~(dec (dec (count case))) (count ~b)) `(= ~(count case) (count ~b)))] (assert (or rest? cnt (seq ks)) (str "No literal in pattern: " case)) `(if (and ~cnt ~@ks) (let [~@(apply concat ls) ~@(if rest? `(~rest? (nthrest ~b ~(- (count case) 2))))] ~then) ~else))) (defmacro match-seq [expr & clauses] (let [b (gensym) cls (partition 2 clauses) default (if (odd? (count clauses)) (last clauses) `(assert false (str "no match for " ~b))) ] `(let [~b ~expr] ~(reduce (fn [acc [cond then]] (match-seq-1 b cond then acc)) default (reverse cls))))) (defmacro template [p & itms] ( .log js / console ( str p ( type p ) ) ) (assert (string? p) (str "no str: " p)) (let [ls (.split p "%")] (assert (= (dec (count ls)) (count itms)) (str "arg count does not match")) `(str ~@(interleave ls itms)) ) (defmacro format [s & params] s s [p & ps] params] (let [idx (.indexOf s "%")] (if (neg? idx) (do (assert (nil? p)) `(.join (cljs.core/array ~@(remove #{""} (conj xs s))) "")) (let [s0 (.substring s 0 idx) st (.substring s (inc idx))] (cond (.startsWith st "d") (recur (conj xs s0 p) (.substring st 1) ps) (.startsWith st ".4f") (recur (conj xs s0 `(.toFixed ~p 4)) (.substring st 3) ps) (.startsWith st ".2f") (recur (conj xs s0 `(.toFixed ~p 2)) (.substring st 3) ps) :else (assert false "Unexpected str!"))))))) :OK
00cb09ab9ddb4d9898fa787256f2bc02f75f1bb40f80dd98c9d3ec31e2b9adcf
spawnfest/eep49ers
wxCommandEvent.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2021 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT -module(wxCommandEvent). -include("wxe.hrl"). -export([getClientData/1,getExtraLong/1,getInt/1,getSelection/1,getString/1, isChecked/1,isSelection/1,setInt/2,setString/2]). %% inherited exports -export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1, resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]). -type wxCommandEvent() :: wx:wx_object(). -include("wx.hrl"). -type wxCommandEventType() :: 'command_button_clicked' | 'command_checkbox_clicked' | 'command_choice_selected' | 'command_listbox_selected' | 'command_listbox_doubleclicked' | 'command_text_updated' | 'command_text_enter' | 'text_maxlen' | 'command_menu_selected' | 'command_slider_updated' | 'command_radiobox_selected' | 'command_radiobutton_selected' | 'command_scrollbar_updated' | 'command_vlbox_selected' | 'command_combobox_selected' | 'combobox_dropdown' | 'combobox_closeup' | 'command_tool_rclicked' | 'command_tool_enter' | 'tool_dropdown' | 'command_checklistbox_toggled' | 'command_togglebutton_clicked' | 'command_left_click' | 'command_left_dclick' | 'command_right_click' | 'command_set_focus' | 'command_kill_focus' | 'command_enter' | 'notification_message_click' | 'notification_message_dismissed' | 'notification_message_action'. -export_type([wxCommandEvent/0, wxCommand/0, wxCommandEventType/0]). %% @hidden parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). %% @doc See <a href="#wxcommandeventgetclientobject">external documentation</a>. -spec getClientData(This) -> term() when This::wxCommandEvent(). getClientData(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_getClientData), wxe_util:rec(?wxCommandEvent_getClientData). %% @doc See <a href="#wxcommandeventgetextralong">external documentation</a>. -spec getExtraLong(This) -> integer() when This::wxCommandEvent(). getExtraLong(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetExtraLong), wxe_util:rec(?wxCommandEvent_GetExtraLong). %% @doc See <a href="#wxcommandeventgetint">external documentation</a>. -spec getInt(This) -> integer() when This::wxCommandEvent(). getInt(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetInt), wxe_util:rec(?wxCommandEvent_GetInt). %% @doc See <a href="#wxcommandeventgetselection">external documentation</a>. -spec getSelection(This) -> integer() when This::wxCommandEvent(). getSelection(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetSelection), wxe_util:rec(?wxCommandEvent_GetSelection). %% @doc See <a href="#wxcommandeventgetstring">external documentation</a>. -spec getString(This) -> unicode:charlist() when This::wxCommandEvent(). getString(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetString), wxe_util:rec(?wxCommandEvent_GetString). %% @doc See <a href="#wxcommandeventischecked">external documentation</a>. -spec isChecked(This) -> boolean() when This::wxCommandEvent(). isChecked(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_IsChecked), wxe_util:rec(?wxCommandEvent_IsChecked). %% @doc See <a href="#wxcommandeventisselection">external documentation</a>. -spec isSelection(This) -> boolean() when This::wxCommandEvent(). isSelection(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_IsSelection), wxe_util:rec(?wxCommandEvent_IsSelection). %% @doc See <a href="#wxcommandeventsetint">external documentation</a>. -spec setInt(This, IntCommand) -> 'ok' when This::wxCommandEvent(), IntCommand::integer(). setInt(#wx_ref{type=ThisT}=This,IntCommand) when is_integer(IntCommand) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,IntCommand,?get_env(),?wxCommandEvent_SetInt). @doc See < a href=" / manuals/2.8.12 / wx_wxcommandevent.html#wxcommandeventsetstring">external documentation</a > . -spec setString(This, String) -> 'ok' when This::wxCommandEvent(), String::unicode:chardata(). setString(#wx_ref{type=ThisT}=This,String) when ?is_chardata(String) -> ?CLASS(ThisT,wxCommandEvent), String_UC = unicode:characters_to_binary(String), wxe_util:queue_cmd(This,String_UC,?get_env(),?wxCommandEvent_SetString). %% From wxEvent %% @hidden stopPropagation(This) -> wxEvent:stopPropagation(This). %% @hidden skip(This, Options) -> wxEvent:skip(This, Options). %% @hidden skip(This) -> wxEvent:skip(This). %% @hidden shouldPropagate(This) -> wxEvent:shouldPropagate(This). %% @hidden resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). %% @hidden isCommandEvent(This) -> wxEvent:isCommandEvent(This). %% @hidden getTimestamp(This) -> wxEvent:getTimestamp(This). %% @hidden getSkipped(This) -> wxEvent:getSkipped(This). %% @hidden getId(This) -> wxEvent:getId(This).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxCommandEvent.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT inherited exports @hidden @doc See <a href="#wxcommandeventgetclientobject">external documentation</a>. @doc See <a href="#wxcommandeventgetextralong">external documentation</a>. @doc See <a href="#wxcommandeventgetint">external documentation</a>. @doc See <a href="#wxcommandeventgetselection">external documentation</a>. @doc See <a href="#wxcommandeventgetstring">external documentation</a>. @doc See <a href="#wxcommandeventischecked">external documentation</a>. @doc See <a href="#wxcommandeventisselection">external documentation</a>. @doc See <a href="#wxcommandeventsetint">external documentation</a>. From wxEvent @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2021 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(wxCommandEvent). -include("wxe.hrl"). -export([getClientData/1,getExtraLong/1,getInt/1,getSelection/1,getString/1, isChecked/1,isSelection/1,setInt/2,setString/2]). -export([getId/1,getSkipped/1,getTimestamp/1,isCommandEvent/1,parent_class/1, resumePropagation/2,shouldPropagate/1,skip/1,skip/2,stopPropagation/1]). -type wxCommandEvent() :: wx:wx_object(). -include("wx.hrl"). -type wxCommandEventType() :: 'command_button_clicked' | 'command_checkbox_clicked' | 'command_choice_selected' | 'command_listbox_selected' | 'command_listbox_doubleclicked' | 'command_text_updated' | 'command_text_enter' | 'text_maxlen' | 'command_menu_selected' | 'command_slider_updated' | 'command_radiobox_selected' | 'command_radiobutton_selected' | 'command_scrollbar_updated' | 'command_vlbox_selected' | 'command_combobox_selected' | 'combobox_dropdown' | 'combobox_closeup' | 'command_tool_rclicked' | 'command_tool_enter' | 'tool_dropdown' | 'command_checklistbox_toggled' | 'command_togglebutton_clicked' | 'command_left_click' | 'command_left_dclick' | 'command_right_click' | 'command_set_focus' | 'command_kill_focus' | 'command_enter' | 'notification_message_click' | 'notification_message_dismissed' | 'notification_message_action'. -export_type([wxCommandEvent/0, wxCommand/0, wxCommandEventType/0]). parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -spec getClientData(This) -> term() when This::wxCommandEvent(). getClientData(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_getClientData), wxe_util:rec(?wxCommandEvent_getClientData). -spec getExtraLong(This) -> integer() when This::wxCommandEvent(). getExtraLong(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetExtraLong), wxe_util:rec(?wxCommandEvent_GetExtraLong). -spec getInt(This) -> integer() when This::wxCommandEvent(). getInt(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetInt), wxe_util:rec(?wxCommandEvent_GetInt). -spec getSelection(This) -> integer() when This::wxCommandEvent(). getSelection(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetSelection), wxe_util:rec(?wxCommandEvent_GetSelection). -spec getString(This) -> unicode:charlist() when This::wxCommandEvent(). getString(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_GetString), wxe_util:rec(?wxCommandEvent_GetString). -spec isChecked(This) -> boolean() when This::wxCommandEvent(). isChecked(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_IsChecked), wxe_util:rec(?wxCommandEvent_IsChecked). -spec isSelection(This) -> boolean() when This::wxCommandEvent(). isSelection(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,?get_env(),?wxCommandEvent_IsSelection), wxe_util:rec(?wxCommandEvent_IsSelection). -spec setInt(This, IntCommand) -> 'ok' when This::wxCommandEvent(), IntCommand::integer(). setInt(#wx_ref{type=ThisT}=This,IntCommand) when is_integer(IntCommand) -> ?CLASS(ThisT,wxCommandEvent), wxe_util:queue_cmd(This,IntCommand,?get_env(),?wxCommandEvent_SetInt). @doc See < a href=" / manuals/2.8.12 / wx_wxcommandevent.html#wxcommandeventsetstring">external documentation</a > . -spec setString(This, String) -> 'ok' when This::wxCommandEvent(), String::unicode:chardata(). setString(#wx_ref{type=ThisT}=This,String) when ?is_chardata(String) -> ?CLASS(ThisT,wxCommandEvent), String_UC = unicode:characters_to_binary(String), wxe_util:queue_cmd(This,String_UC,?get_env(),?wxCommandEvent_SetString). stopPropagation(This) -> wxEvent:stopPropagation(This). skip(This, Options) -> wxEvent:skip(This, Options). skip(This) -> wxEvent:skip(This). shouldPropagate(This) -> wxEvent:shouldPropagate(This). resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). isCommandEvent(This) -> wxEvent:isCommandEvent(This). getTimestamp(This) -> wxEvent:getTimestamp(This). getSkipped(This) -> wxEvent:getSkipped(This). getId(This) -> wxEvent:getId(This).
ad89dc8e16b2fa8e9ab92029ee3fd060ea55787b78af301c5af159aa0a439dbd
softlab-ntua/bencherl
list_utils.erl
Copyright ( C ) 2003 - 2014 % This file is part of the Ceylan Erlang library . % % This library is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License or the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) % any later version. % You can also redistribute it and/or modify it under the terms of the Mozilla Public License , version 1.1 or later . % % 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 and the GNU General Public License % for more details. % You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License % along with this library. % If not, see </> and % </>. % Author : ( ) Creation date : July 1 , 2007 . % Gathering of various facilities about lists. % See for the corresponding test . % -module(list_utils). % For list_impl: -include("data_types.hrl"). % Basic list operations: % -export([ get_element_at/2, insert_element_at/3, remove_element_at/2, remove_last_element/1, get_last_element/1, get_index_of/2, split_at/2, uniquify/1, has_duplicates/1, get_duplicates/1, intersect/2, subtract_all_duplicates/2, delete_existing/2, delete_all_in/2, append_at_end/2, is_list_of_integers/1, unordered_compare/2, add_if_not_existing/2 ]). % listimpl-relation operations: % -export([ safe_listimpl_delete/2, listimpl_add/2 ]). Ring - related operations : % -export([ list_to_ring/1, head/1, get_next/2, get_ring_size/1 ]). % A ring behaves as an (infinite) list whose next element after its last is its first again . % Internally , the first list is the working one ( from which elements may be extracted ) , while the second is a copy of the full reference one . % -opaque ring() :: { list(), list() }. % Random operations on lists: % -export([ random_permute/1, random_permute_reciprocal/1, draw_element/1, draw_element/2, draw_element_weighted/1, draw_elements_from/2 ]). -export_type([ ring/0 ]). % Section for basic list operations. Index start at position # 1 , not # 0 . Returns the element in the list at the specified index , in [ 1 .. length(List ) ] . % % If the index is out of bounds, a function_clause is raised. % % Note: usually these kinds of functions should not be used, recursive % algorithms are a lot more effective, when applicable. % % Not tail recursive version: % get_element_at ( List , 1 ) - > hd(List ) ; % get_element_at ( [ _ H | T ] , Index ) - > get_element_at ( T , Index-1 ) . % -spec get_element_at( list(), basic_utils:positive_index() ) -> any(). get_element_at( List, Index ) -> io : format ( " - getting element # ~B of ~w ~ n " , [ Index , List ] ) , lists:nth( Index, List ). % Inserts specified element at specified position in specified list. % For example , insert_element_at ( foo , [ a , b , c , d ] , 3 ) will return % [ a, b, foo, c, d ]. % -spec insert_element_at( any(), list(), basic_utils:positive_index() ) -> list(). insert_element_at( Element, List, Index ) -> %io:format( " - inserting element ~p at #~B in ~w~n", % [ Element, Index, List ] ), insert_element_at( Element, List, Index, _Acc=[] ). insert_element_at( Element, _List=[], _Index=1, Acc ) -> lists:reverse( [ Element | Acc ] ); insert_element_at( _Element, _List=[], Index, Acc ) -> % Rebuilds input parameters: throw( { invalid_index, Index + length( Acc ), lists:reverse( Acc ) } ); insert_element_at( Element, List, _Index=1, Acc ) -> lists:reverse( [ Element | Acc ] ) ++ List; insert_element_at( Element, _List=[ H | T ], Index, Acc ) -> insert_element_at( Element, T, Index - 1, [ H | Acc ] ). % Returns a list corresponding to the specified one with the element at % specified index removed. % % If the index is out of bounds, a function_clause like % '[{list_utils,remove_element_at,...}]' is triggered. % % Note: usually these kinds of functions should not be used, recursive % algorithms are a lot more effective, when applicable. % Signature : remove_element_at ( List , Index ) . % % Curiously lists:nth exists, but no function to remove an element specified by % its index seems to be available in the lists module. % % Not tail recursive version: remove_element_at ( [ _ H | T ] , _ LastIndex=1 ) - > % T; % %remove_element_at( [ H | T ], _Index=N ) -> [ H | remove_element_at ( T , _ NextIndex = N-1 ) ] . % % Tail recursive version: % -spec remove_element_at( list(), basic_utils:positive_index()) -> list(). remove_element_at( List, Index ) -> remove_element_at( List, Index, _Result=[] ). remove_element_at( [ _H | RemainingList ], 1, Result ) -> lists:reverse( Result ) ++ RemainingList; remove_element_at( [ H | RemainingList ], Index, Result ) -> remove_element_at( RemainingList, Index-1, [ H | Result ] ). % Removes the last element of the specified list. % % Crashes (with 'no function clause') if the input list is empty. % % Note: not computationnally efficient, usually removing the last element % suggests a bad code design. % -spec remove_last_element( list() ) -> list(). remove_last_element( List ) -> remove_last_element( List, _Acc=[] ). remove_last_element( _List=[ _Last ], Acc ) -> lists:reverse( Acc ); remove_last_element( _List=[ H | T ], Acc ) -> remove_last_element( T, [ H | Acc ] ). % Returns the last element of the specified list. % % Note: not computationnally efficient, usually having to retrieve the last % element suggests a bad code design. % % Crashes (with 'no function clause') if the input list is empty. % -spec get_last_element( list() ) -> term(). get_last_element( _List=[ SingleElement ] ) -> SingleElement; get_last_element( _List=[ _H | T ] ) -> get_last_element( T ). Returns the index , in [ 1 .. length(List ) ] , of the ( first occurrence of the % )specified element in the specified list. Throws an exception if the element % is not found. % Ex : 3 = get_index_of ( bar , [ foo , ugh , bar , baz ] ) % -spec get_index_of( term(), list() ) -> basic_utils:count(). get_index_of( Element, List ) -> get_index_of( Element, List, _Count=1 ). get_index_of( Element, _List=[], _Count ) -> throw( { non_existing_element, Element } ); get_index_of( Element, _List=[ Element | _T ], Count ) -> Count; get_index_of( Element, _List=[ _H | T ], Count ) -> get_index_of( Element, T, Count + 1 ). Splits the specified ( plain ) list in two parts ( two plain lists , that are returned ): the first contains the first elements , up to MaxLen ( in reverse order ) , and the second the others ( if any ) . % Ex : split_at ( [ a , b , c , d , e ] , 3 ) = { [ c , b , a ] , [ d , e ] } % -spec split_at( list(), basic_utils:count() ) -> { list(), list() }. split_at( List, MaxLen ) -> split_at( List, _Count=0, MaxLen, _Acc=[] ). % (helper) split_at( InputList, _Count=MaxLen, MaxLen, AccList ) -> reached , stopping here : { AccList, InputList }; split_at( _InputList=[], _Count, _MaxLen, AccList ) -> % Input list exhausted: { AccList, _InputList=[] }; split_at( _List=[ H | T ], Count, MaxLen, Acc ) -> split_at( T, Count + 1, MaxLen, [ H | Acc ] ). % Returns a list whose elements are the ones of the specified list, except that % they are unique (all their duplicates have been removed). % % No specific order is respected in the returned list. % % Ex: if L = [1,2,3,2,2,4,5,5,4,6,6,5], then basic_utils:uniquify(L) is: % [3,6,2,5,1,4]. % -spec uniquify( list() ) -> list(). uniquify( List ) -> % There is probably a more efficient way of doing the same: sets:to_list( sets:from_list( List ) ). % Tells whether there are in the specified list elements that are present more % than once. % has_duplicates( List ) -> length( uniquify( List ) ) =/= length( List ). % Returns the duplicates in the specified list: returns a list of { DuplicatedTerm , DuplicationCount } pairs , where each duplicated term is % specified, alongside the total number of occurrences of that terms in the % specified list. % % Duplicates are returned in the reverse order of their appearance in the specified list ; for example , for input list [ a , a , b , b , b , c , c , c ] , returned % duplicates are [{b,3},{c,3},{a,2}]. % -spec get_duplicates( list() ) -> list( { term(), basic_utils:count() } ). get_duplicates( List ) -> get_duplicates( List, _Acc=[] ). get_duplicates( _List=[], Acc ) -> Acc; get_duplicates( _List=[ Term | T ], Acc ) -> % io:format( "Inquiring about term '~p' into ~p.~n", [ Term, T ] ), case count_and_filter_term( Term, _InitialList=T, _FilteredList=[], _InitialCount=0 ) of not_found -> % No a duplicated element, just iterating on the next term: get_duplicates( T, Acc ); { TermCount, FilteredList } -> We already extracted the first Term : get_duplicates( FilteredList, [ { Term, TermCount + 1 } | Acc ] ) end. count_and_filter_term( _Term, _List=[], _FilteredList, _CurrentCount=0 ) -> not_found; count_and_filter_term( _Term, _List=[], FilteredList, CurrentCount ) -> { CurrentCount, FilteredList }; % Term found: count_and_filter_term( Term, _List=[ Term | H ], FilteredList, CurrentCount ) -> count_and_filter_term( Term, H, FilteredList, CurrentCount + 1 ); % Other term: count_and_filter_term( Term, _List=[ OtherTerm | H ], FilteredList, CurrentCount ) -> count_and_filter_term( Term, H, [ OtherTerm | FilteredList ], CurrentCount ). Returns the intersection of the two specified lists , i.e. the list of all % elements that are in both lists. % % See also: subtract_all_duplicates/2. % -spec intersect( list(), list() ) -> list(). intersect( L1, L2 ) -> lists:filter( fun( E ) -> lists:member( E, L2 ) end, L1 ). % Returns a list equal to L1 except that all elements found in L2 have been % removed, even if in L1 they were duplicated. % Note : like lists : subtract , except that * all * occurences from L2 in L1 ( not only the first one ) are removed . % Example : [ 1,4 ] = basic_utils : subtract_all_duplicates ( [ 1,2,3,4,2 ] , [ 2,3 ] ) % % Taken from % % -spec subtract_all_duplicates( list(), list() ) -> list(). subtract_all_duplicates( L1, L2 ) -> lists:filter( fun( E ) -> not lists:member( E, L2 ) end, L1 ). Returns a copy of the specified list where the first element matching is deleted , ensuring at least one of these elements exists ( as opposed to % lists:delete/2). The order of the specified list is preserved. % -spec delete_existing( term(), list() ) -> list(). delete_existing( Elem, List ) -> delete_existing( Elem, List, _Acc=[] ). delete_existing( Elem, _List=[], _Acc ) -> throw( { element_to_delete_not_found, Elem } ); delete_existing( Elem, _List=[ Elem | T ], Acc ) -> The first element found stops the iteration : lists:reverse( Acc ) ++ T; delete_existing( Elem, _List=[ H | T ], Acc ) -> delete_existing( Elem, T, [ H | Acc ] ). Returns a copy of the specified list where all elements matching are % deleted, whether or not there is any. % % The element order of the specified list is preserved. % -spec delete_all_in( term(), list() ) -> list(). delete_all_in( Elem, List ) -> delete_all_in( Elem, List, _Acc=[] ). delete_all_in( _Elem, _List=[], Acc ) -> lists:reverse( Acc ); delete_all_in( Elem, _List=[ Elem | T ], Acc ) -> % An element not to retain: delete_all_in( Elem, T, Acc ); delete_all_in( Elem, _List=[ H | T ], Acc ) -> % Non-matching, keep it: delete_all_in( Elem, T, [ H | Acc ] ). % Appends specified element at the end of specified list, without changing the % order of the list. % % Ex: append_at_end( d, [a,b,c] ) returns [a,b,c,d]. % % Note: usually such an addition should be avoided, as it is costly. % -spec append_at_end( any(), list() ) -> nonempty_list(). append_at_end( Elem, L ) when is_list(L) -> Should be more efficient than lists : reverse ( [ Elem|lists : reverse(L ) ] ): L ++ [ Elem ]. % Returns whether the specified list contains only integers. -spec is_list_of_integers( any() ) -> boolean(). is_list_of_integers( [] ) -> true; is_list_of_integers( [ H | T ] ) when is_integer(H) -> is_list_of_integers( T ); is_list_of_integers( _ ) -> false. Compares the two specified lists with no regard to the order of their % elements: returns true iff they have the exact same elements (differentiating between 1 and 1.0 for example ) , possibly in a different order . % -spec unordered_compare( list(), list() ) -> boolean(). unordered_compare( L1, L2 ) -> lists:sort( L1 ) =:= lists:sort( L2 ). % Adds each element of PlainList (a plain list) in ListImpl (a ?list_impl list), % if this element is not already there, and returns the corresponding % ?list_impl. So at the end all elements of PlainList will be exactly once in % the returned list, with all past elements still there. % % Supposedly PlainList is rather short and ListImpl can be rather long. % -spec add_if_not_existing( list(), ?list_impl_type ) -> ?list_impl_type. add_if_not_existing( _PlainList=[], ListImpl ) -> ListImpl ; add_if_not_existing( _PlainList=[ H | T ], ListImpl ) -> case ?list_impl:is_member( H, ListImpl ) of true -> % Already there, not to added: add_if_not_existing( T, ListImpl ); false -> % Not present, so let's add it: add_if_not_existing( T, ?list_impl:add_element( H, ListImpl ) ) end. % Section for listimpl-relation operations. % Ensures that the specified element was indeed in the specified list before % removing it and returning the resulting list. % -spec safe_listimpl_delete( term(), ?list_impl_type ) -> ?list_impl_type. safe_listimpl_delete( Element, List ) -> case ?list_impl:is_element( Element, List ) of true -> ?list_impl:del_element( Element, List ); false -> throw( { non_existing_element_to_delete, Element, ?list_impl:to_list( List ) } ) end. % Quicker, less safe (no checking) version: %?list_impl:del_element( Element, List ); Returns a list_impl list made of the first list_impl list to which the % elements of the specified plain list have been added (it is basically a % ?list_impl ++ list() -> ?list_impl operations). % -spec listimpl_add( ?list_impl_type, list() ) -> ?list_impl_type. listimpl_add( ListImplList, _PlainList=[] ) -> ListImplList; listimpl_add( ListImplList, _PlainList=[ H | T ] ) -> listimpl_add( ?list_impl:add_element( H, ListImplList ), T ). % Ring-related section. % Returns a ring corresponding to the specified list. % -spec list_to_ring( list() ) -> ring(). list_to_ring( InputList ) -> { InputList, InputList }. % Pops the head of specified ring: return { Head, UpdatedRing }. % -spec head( ring() ) -> { term(), ring() }. head( { _WorkingList=[], ReferenceList } ) -> % Replenish: % does not want an opaque argument to be used : head ( { ReferenceList , ReferenceList } ) ; head( list_to_ring( ReferenceList ) ); head( { _WorkingList=[ H | T ], ReferenceList } ) -> { H, { T, ReferenceList } }. Returns a list of the Count popped elements ( in their order in the ring ) , and % the updated ring. % Ex : for a new ring based on [ a , b , c , d ] , if Count=6 then [ a , b , c , d , a , % b] will be returned. % -spec get_next( basic_utils:count(), ring() ) -> { [ term() ], ring() }. get_next( Count, Ring ) -> % Quite similar to a map:foldl/3: get_next_helper( Count, Ring, _Acc=[] ). get_next_helper( _Count=0, Ring, Acc ) -> { lists:reverse( Acc ), Ring }; get_next_helper( Count, Ring, Acc ) -> { H, NewRing } = head( Ring ), get_next_helper( Count-1, NewRing, [ H | Acc ] ). % Returns the number of elements in the specified ring. % -spec get_ring_size( ring() ) -> basic_utils:count(). get_ring_size( _Ring={ _WorkingList, ReferenceList } ) -> length( ReferenceList ). % Section to perform random operations on lists. % Returns a random uniform permutation of the specified list. % % Inspired from . % % All these algorithms would need random access to a list, which is not readily % possible here, hence must be emulated. % See also the ' Speedy unsort : shuffle/1,2 ' thread in the erlang - questions % mailing list for counterparts. % -spec random_permute( list() ) -> list(). random_permute( List ) -> random_permute( List, length( List ) ). random_permute( _List, _RemainingLen=0 ) -> []; random_permute( List, RemainingLen ) -> % Checking is commented-out: RemainingLen = length ( List ) , % (using remove_element_at/2 should be quicker than using proplists : delete/2 , as we stop at the first matching element found ) % Index = random_utils:get_random_value( RemainingLen ), io : format ( " Index=~p , " , [ Index ] ) , % We put the drawn element at head, and recurse in the remaining list: [ get_element_at( List, Index ) | random_permute( remove_element_at( List, Index ), RemainingLen - 1 ) ]. % Returns a reciprocal random uniform permutation of the specified list, % compared to random_permute/1. % % Consists on the reciprocal operation, so that, if starting from a random state % S (see set_random_state/1) and if L2 = random_permute( L1 ), then, if starting % again from S, L1 = random_permute_reciprocal( L2 ). % -spec random_permute_reciprocal( list() ) -> list(). random_permute_reciprocal( List ) -> % This is a little trickier than random_permute/1; we have to reverse operations for latest to first , hence we must start with the latest drawn value . So we draw them all first , and start by the end of that list , % taking into account that the range is decremented at each draw: % ReciprocalIndex = lists:reverse( [ random_utils:get_random_value( L ) || L <- lists:reverse( lists:seq( 1, length( List ) ) ) ] ), %io:format( "Reciprocal index = ~p~n", [ ReciprocalIndex ] ), random_permute_reciprocal( lists:reverse( List ), ReciprocalIndex, _Acc=[] ). random_permute_reciprocal( _List=[], _ReciprocalIndex=[], Acc ) -> Acc; random_permute_reciprocal( _List=[ H | T ], _ReciprocalIndex=[ I | Is ], Acc ) -> NewAcc = insert_element_at( _Elem=H, Acc, _Index=I ), random_permute_reciprocal( T, Is, NewAcc ). Draws one element at random of the specified list , knowing they all have the % same probability of being drawn (uniform probability). % -spec draw_element( [ any() ] ) -> any(). draw_element( _ElementList=[] ) -> throw( cannot_draw_from_empty_list ); draw_element( ElementList ) -> Len = length( ElementList ), draw_element( ElementList, Len ). Draws one element at random of the specified list , whose length must be the % specified one (allows to precompute it once for multiple drawings), knowing % all elements have the same probability of being drawn (uniform probability). % -spec draw_element( [ any() ], basic_utils:count() ) -> any(). draw_element( ElementList, Length ) -> DrawnIndex = random_utils:get_random_value( Length ), get_element_at( ElementList, DrawnIndex ). % Alternate, less efficient, implementation: % Same probability: %UniformList = [ { Elem, 1 } || Elem <- ElementList ], draw_element_weighted ( UniformList ) . Draws one element at random of the specified list , which is a list of { % Element, Probability } pairs: returns the drawn element, knowing that it will % be chosen according to the probability associated to each element. % % Probabilities are managed as integer values defined relatively to each other ( and they do not have to sum up to 1.0 ) ; they must be positive or null % integers, and their sum must not be null. % % Ex: ElementList = [ {first,1}, {second,2}, {third,1} ] is excepted to return on average ' second ' twice as frequently as ' first ' or ' third ' . % Using [ { first,1 } , { second,0 } , { third,1 } ] instead would mean that ' second ' % would never be drawn. % -spec draw_element_weighted( [ { any(), integer() } ] ) -> any(). draw_element_weighted( ElementList ) -> draw_element_weighted( ElementList, sum_probabilities( ElementList ) ). -spec sum_probabilities( [ { _Element, number() } ] ) -> number(). sum_probabilities( ElementList ) -> sum_probabilities( ElementList, _Acc=0 ). sum_probabilities( _ElementList=[], Acc ) -> Acc; sum_probabilities( _ElementList=[ { _Element, Probability } | T ], Acc ) -> sum_probabilities( T, Acc + Probability ). Sum must be equal to the sum of all probabilities in ElementList . draw_element_weighted( _ElementList, 0 ) -> throw( null_total_probability ); draw_element_weighted( ElementList, Sum ) -> DrawnValue = random_utils:get_random_value( Sum ), io : format ( " draw_element : drawn ~B.~n " , [ DrawnValue ] ) , select_element( ElementList, DrawnValue, _CurrentSum=0 ). select_element( [ { Element, Probability } | _T ], DrawnValue, CurrentSum ) when Probability + CurrentSum >= DrawnValue -> % Just gone past the probability range: Element; select_element( [ { _Element, Probability } | T ], DrawnValue, CurrentSum ) -> % Drawn value still not reached, continuing: select_element( T, DrawnValue, CurrentSum + Probability ). % Draws the specified number of elements at random of the specified list, % knowing they all have the same probability of being drawn initially, but when % an element is drawn, it is removed from the candidate list so that the next % drawing operates on the resulting shorten list. % -spec draw_elements_from( [ any() ], basic_utils:count() ) -> [ any() ]. draw_elements_from( ElementList, Count ) -> draw_elements_from( ElementList, Count, _Acc=[] ). draw_elements_from( _ElementList, _Count=0, Acc ) -> Acc; draw_elements_from( ElementList, Count, Acc ) -> Drawn = draw_element( ElementList ), ShortenList = lists:delete( Drawn, ElementList ), draw_elements_from( ShortenList, Count - 1, [ Drawn | Acc ] ).
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/common/src/utils/list_utils.erl
erlang
This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License or any later version. You can also redistribute it and/or modify it under the terms of the 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 for more details. along with this library. If not, see </> and </>. Gathering of various facilities about lists. For list_impl: Basic list operations: listimpl-relation operations: A ring behaves as an (infinite) list whose next element after its last is its Random operations on lists: Section for basic list operations. If the index is out of bounds, a function_clause is raised. Note: usually these kinds of functions should not be used, recursive algorithms are a lot more effective, when applicable. Not tail recursive version: Inserts specified element at specified position in specified list. [ a, b, foo, c, d ]. io:format( " - inserting element ~p at #~B in ~w~n", [ Element, Index, List ] ), Rebuilds input parameters: Returns a list corresponding to the specified one with the element at specified index removed. If the index is out of bounds, a function_clause like '[{list_utils,remove_element_at,...}]' is triggered. Note: usually these kinds of functions should not be used, recursive algorithms are a lot more effective, when applicable. Curiously lists:nth exists, but no function to remove an element specified by its index seems to be available in the lists module. Not tail recursive version: T; remove_element_at( [ H | T ], _Index=N ) -> Tail recursive version: Removes the last element of the specified list. Crashes (with 'no function clause') if the input list is empty. Note: not computationnally efficient, usually removing the last element suggests a bad code design. Returns the last element of the specified list. Note: not computationnally efficient, usually having to retrieve the last element suggests a bad code design. Crashes (with 'no function clause') if the input list is empty. )specified element in the specified list. Throws an exception if the element is not found. (helper) Input list exhausted: Returns a list whose elements are the ones of the specified list, except that they are unique (all their duplicates have been removed). No specific order is respected in the returned list. Ex: if L = [1,2,3,2,2,4,5,5,4,6,6,5], then basic_utils:uniquify(L) is: [3,6,2,5,1,4]. There is probably a more efficient way of doing the same: Tells whether there are in the specified list elements that are present more than once. Returns the duplicates in the specified list: returns a list of { specified, alongside the total number of occurrences of that terms in the specified list. Duplicates are returned in the reverse order of their appearance in the duplicates are [{b,3},{c,3},{a,2}]. io:format( "Inquiring about term '~p' into ~p.~n", [ Term, T ] ), No a duplicated element, just iterating on the next term: Term found: Other term: elements that are in both lists. See also: subtract_all_duplicates/2. Returns a list equal to L1 except that all elements found in L2 have been removed, even if in L1 they were duplicated. Taken from lists:delete/2). The order of the specified list is preserved. deleted, whether or not there is any. The element order of the specified list is preserved. An element not to retain: Non-matching, keep it: Appends specified element at the end of specified list, without changing the order of the list. Ex: append_at_end( d, [a,b,c] ) returns [a,b,c,d]. Note: usually such an addition should be avoided, as it is costly. Returns whether the specified list contains only integers. elements: returns true iff they have the exact same elements (differentiating Adds each element of PlainList (a plain list) in ListImpl (a ?list_impl list), if this element is not already there, and returns the corresponding ?list_impl. So at the end all elements of PlainList will be exactly once in the returned list, with all past elements still there. Supposedly PlainList is rather short and ListImpl can be rather long. Already there, not to added: Not present, so let's add it: Section for listimpl-relation operations. Ensures that the specified element was indeed in the specified list before removing it and returning the resulting list. Quicker, less safe (no checking) version: ?list_impl:del_element( Element, List ); elements of the specified plain list have been added (it is basically a ?list_impl ++ list() -> ?list_impl operations). Ring-related section. Returns a ring corresponding to the specified list. Pops the head of specified ring: return { Head, UpdatedRing }. Replenish: the updated ring. b] will be returned. Quite similar to a map:foldl/3: Returns the number of elements in the specified ring. Section to perform random operations on lists. Returns a random uniform permutation of the specified list. Inspired from . All these algorithms would need random access to a list, which is not readily possible here, hence must be emulated. mailing list for counterparts. Checking is commented-out: (using remove_element_at/2 should be quicker than using We put the drawn element at head, and recurse in the remaining list: Returns a reciprocal random uniform permutation of the specified list, compared to random_permute/1. Consists on the reciprocal operation, so that, if starting from a random state S (see set_random_state/1) and if L2 = random_permute( L1 ), then, if starting again from S, L1 = random_permute_reciprocal( L2 ). This is a little trickier than random_permute/1; we have to reverse taking into account that the range is decremented at each draw: io:format( "Reciprocal index = ~p~n", [ ReciprocalIndex ] ), same probability of being drawn (uniform probability). specified one (allows to precompute it once for multiple drawings), knowing all elements have the same probability of being drawn (uniform probability). Alternate, less efficient, implementation: Same probability: UniformList = [ { Elem, 1 } || Elem <- ElementList ], Element, Probability } pairs: returns the drawn element, knowing that it will be chosen according to the probability associated to each element. Probabilities are managed as integer values defined relatively to each other integers, and their sum must not be null. Ex: ElementList = [ {first,1}, {second,2}, {third,1} ] is excepted to return would never be drawn. Just gone past the probability range: Drawn value still not reached, continuing: Draws the specified number of elements at random of the specified list, knowing they all have the same probability of being drawn initially, but when an element is drawn, it is removed from the candidate list so that the next drawing operates on the resulting shorten list.
Copyright ( C ) 2003 - 2014 This file is part of the Ceylan Erlang library . the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) Mozilla Public License , version 1.1 or later . GNU Lesser General Public License and the GNU General Public License You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License Author : ( ) Creation date : July 1 , 2007 . See for the corresponding test . -module(list_utils). -include("data_types.hrl"). -export([ get_element_at/2, insert_element_at/3, remove_element_at/2, remove_last_element/1, get_last_element/1, get_index_of/2, split_at/2, uniquify/1, has_duplicates/1, get_duplicates/1, intersect/2, subtract_all_duplicates/2, delete_existing/2, delete_all_in/2, append_at_end/2, is_list_of_integers/1, unordered_compare/2, add_if_not_existing/2 ]). -export([ safe_listimpl_delete/2, listimpl_add/2 ]). Ring - related operations : -export([ list_to_ring/1, head/1, get_next/2, get_ring_size/1 ]). first again . Internally , the first list is the working one ( from which elements may be extracted ) , while the second is a copy of the full reference one . -opaque ring() :: { list(), list() }. -export([ random_permute/1, random_permute_reciprocal/1, draw_element/1, draw_element/2, draw_element_weighted/1, draw_elements_from/2 ]). -export_type([ ring/0 ]). Index start at position # 1 , not # 0 . Returns the element in the list at the specified index , in [ 1 .. length(List ) ] . get_element_at ( List , 1 ) - > hd(List ) ; get_element_at ( [ _ H | T ] , Index ) - > get_element_at ( T , Index-1 ) . -spec get_element_at( list(), basic_utils:positive_index() ) -> any(). get_element_at( List, Index ) -> io : format ( " - getting element # ~B of ~w ~ n " , [ Index , List ] ) , lists:nth( Index, List ). For example , insert_element_at ( foo , [ a , b , c , d ] , 3 ) will return -spec insert_element_at( any(), list(), basic_utils:positive_index() ) -> list(). insert_element_at( Element, List, Index ) -> insert_element_at( Element, List, Index, _Acc=[] ). insert_element_at( Element, _List=[], _Index=1, Acc ) -> lists:reverse( [ Element | Acc ] ); insert_element_at( _Element, _List=[], Index, Acc ) -> throw( { invalid_index, Index + length( Acc ), lists:reverse( Acc ) } ); insert_element_at( Element, List, _Index=1, Acc ) -> lists:reverse( [ Element | Acc ] ) ++ List; insert_element_at( Element, _List=[ H | T ], Index, Acc ) -> insert_element_at( Element, T, Index - 1, [ H | Acc ] ). Signature : remove_element_at ( List , Index ) . remove_element_at ( [ _ H | T ] , _ LastIndex=1 ) - > [ H | remove_element_at ( T , _ NextIndex = N-1 ) ] . -spec remove_element_at( list(), basic_utils:positive_index()) -> list(). remove_element_at( List, Index ) -> remove_element_at( List, Index, _Result=[] ). remove_element_at( [ _H | RemainingList ], 1, Result ) -> lists:reverse( Result ) ++ RemainingList; remove_element_at( [ H | RemainingList ], Index, Result ) -> remove_element_at( RemainingList, Index-1, [ H | Result ] ). -spec remove_last_element( list() ) -> list(). remove_last_element( List ) -> remove_last_element( List, _Acc=[] ). remove_last_element( _List=[ _Last ], Acc ) -> lists:reverse( Acc ); remove_last_element( _List=[ H | T ], Acc ) -> remove_last_element( T, [ H | Acc ] ). -spec get_last_element( list() ) -> term(). get_last_element( _List=[ SingleElement ] ) -> SingleElement; get_last_element( _List=[ _H | T ] ) -> get_last_element( T ). Returns the index , in [ 1 .. length(List ) ] , of the ( first occurrence of the Ex : 3 = get_index_of ( bar , [ foo , ugh , bar , baz ] ) -spec get_index_of( term(), list() ) -> basic_utils:count(). get_index_of( Element, List ) -> get_index_of( Element, List, _Count=1 ). get_index_of( Element, _List=[], _Count ) -> throw( { non_existing_element, Element } ); get_index_of( Element, _List=[ Element | _T ], Count ) -> Count; get_index_of( Element, _List=[ _H | T ], Count ) -> get_index_of( Element, T, Count + 1 ). Splits the specified ( plain ) list in two parts ( two plain lists , that are returned ): the first contains the first elements , up to MaxLen ( in reverse order ) , and the second the others ( if any ) . Ex : split_at ( [ a , b , c , d , e ] , 3 ) = { [ c , b , a ] , [ d , e ] } -spec split_at( list(), basic_utils:count() ) -> { list(), list() }. split_at( List, MaxLen ) -> split_at( List, _Count=0, MaxLen, _Acc=[] ). split_at( InputList, _Count=MaxLen, MaxLen, AccList ) -> reached , stopping here : { AccList, InputList }; split_at( _InputList=[], _Count, _MaxLen, AccList ) -> { AccList, _InputList=[] }; split_at( _List=[ H | T ], Count, MaxLen, Acc ) -> split_at( T, Count + 1, MaxLen, [ H | Acc ] ). -spec uniquify( list() ) -> list(). uniquify( List ) -> sets:to_list( sets:from_list( List ) ). has_duplicates( List ) -> length( uniquify( List ) ) =/= length( List ). DuplicatedTerm , DuplicationCount } pairs , where each duplicated term is specified list ; for example , for input list [ a , a , b , b , b , c , c , c ] , returned -spec get_duplicates( list() ) -> list( { term(), basic_utils:count() } ). get_duplicates( List ) -> get_duplicates( List, _Acc=[] ). get_duplicates( _List=[], Acc ) -> Acc; get_duplicates( _List=[ Term | T ], Acc ) -> case count_and_filter_term( Term, _InitialList=T, _FilteredList=[], _InitialCount=0 ) of not_found -> get_duplicates( T, Acc ); { TermCount, FilteredList } -> We already extracted the first Term : get_duplicates( FilteredList, [ { Term, TermCount + 1 } | Acc ] ) end. count_and_filter_term( _Term, _List=[], _FilteredList, _CurrentCount=0 ) -> not_found; count_and_filter_term( _Term, _List=[], FilteredList, CurrentCount ) -> { CurrentCount, FilteredList }; count_and_filter_term( Term, _List=[ Term | H ], FilteredList, CurrentCount ) -> count_and_filter_term( Term, H, FilteredList, CurrentCount + 1 ); count_and_filter_term( Term, _List=[ OtherTerm | H ], FilteredList, CurrentCount ) -> count_and_filter_term( Term, H, [ OtherTerm | FilteredList ], CurrentCount ). Returns the intersection of the two specified lists , i.e. the list of all -spec intersect( list(), list() ) -> list(). intersect( L1, L2 ) -> lists:filter( fun( E ) -> lists:member( E, L2 ) end, L1 ). Note : like lists : subtract , except that * all * occurences from L2 in L1 ( not only the first one ) are removed . Example : [ 1,4 ] = basic_utils : subtract_all_duplicates ( [ 1,2,3,4,2 ] , [ 2,3 ] ) -spec subtract_all_duplicates( list(), list() ) -> list(). subtract_all_duplicates( L1, L2 ) -> lists:filter( fun( E ) -> not lists:member( E, L2 ) end, L1 ). Returns a copy of the specified list where the first element matching is deleted , ensuring at least one of these elements exists ( as opposed to -spec delete_existing( term(), list() ) -> list(). delete_existing( Elem, List ) -> delete_existing( Elem, List, _Acc=[] ). delete_existing( Elem, _List=[], _Acc ) -> throw( { element_to_delete_not_found, Elem } ); delete_existing( Elem, _List=[ Elem | T ], Acc ) -> The first element found stops the iteration : lists:reverse( Acc ) ++ T; delete_existing( Elem, _List=[ H | T ], Acc ) -> delete_existing( Elem, T, [ H | Acc ] ). Returns a copy of the specified list where all elements matching are -spec delete_all_in( term(), list() ) -> list(). delete_all_in( Elem, List ) -> delete_all_in( Elem, List, _Acc=[] ). delete_all_in( _Elem, _List=[], Acc ) -> lists:reverse( Acc ); delete_all_in( Elem, _List=[ Elem | T ], Acc ) -> delete_all_in( Elem, T, Acc ); delete_all_in( Elem, _List=[ H | T ], Acc ) -> delete_all_in( Elem, T, [ H | Acc ] ). -spec append_at_end( any(), list() ) -> nonempty_list(). append_at_end( Elem, L ) when is_list(L) -> Should be more efficient than lists : reverse ( [ Elem|lists : reverse(L ) ] ): L ++ [ Elem ]. -spec is_list_of_integers( any() ) -> boolean(). is_list_of_integers( [] ) -> true; is_list_of_integers( [ H | T ] ) when is_integer(H) -> is_list_of_integers( T ); is_list_of_integers( _ ) -> false. Compares the two specified lists with no regard to the order of their between 1 and 1.0 for example ) , possibly in a different order . -spec unordered_compare( list(), list() ) -> boolean(). unordered_compare( L1, L2 ) -> lists:sort( L1 ) =:= lists:sort( L2 ). -spec add_if_not_existing( list(), ?list_impl_type ) -> ?list_impl_type. add_if_not_existing( _PlainList=[], ListImpl ) -> ListImpl ; add_if_not_existing( _PlainList=[ H | T ], ListImpl ) -> case ?list_impl:is_member( H, ListImpl ) of true -> add_if_not_existing( T, ListImpl ); false -> add_if_not_existing( T, ?list_impl:add_element( H, ListImpl ) ) end. -spec safe_listimpl_delete( term(), ?list_impl_type ) -> ?list_impl_type. safe_listimpl_delete( Element, List ) -> case ?list_impl:is_element( Element, List ) of true -> ?list_impl:del_element( Element, List ); false -> throw( { non_existing_element_to_delete, Element, ?list_impl:to_list( List ) } ) end. Returns a list_impl list made of the first list_impl list to which the -spec listimpl_add( ?list_impl_type, list() ) -> ?list_impl_type. listimpl_add( ListImplList, _PlainList=[] ) -> ListImplList; listimpl_add( ListImplList, _PlainList=[ H | T ] ) -> listimpl_add( ?list_impl:add_element( H, ListImplList ), T ). -spec list_to_ring( list() ) -> ring(). list_to_ring( InputList ) -> { InputList, InputList }. -spec head( ring() ) -> { term(), ring() }. head( { _WorkingList=[], ReferenceList } ) -> does not want an opaque argument to be used : head ( { ReferenceList , ReferenceList } ) ; head( list_to_ring( ReferenceList ) ); head( { _WorkingList=[ H | T ], ReferenceList } ) -> { H, { T, ReferenceList } }. Returns a list of the Count popped elements ( in their order in the ring ) , and Ex : for a new ring based on [ a , b , c , d ] , if Count=6 then [ a , b , c , d , a , -spec get_next( basic_utils:count(), ring() ) -> { [ term() ], ring() }. get_next( Count, Ring ) -> get_next_helper( Count, Ring, _Acc=[] ). get_next_helper( _Count=0, Ring, Acc ) -> { lists:reverse( Acc ), Ring }; get_next_helper( Count, Ring, Acc ) -> { H, NewRing } = head( Ring ), get_next_helper( Count-1, NewRing, [ H | Acc ] ). -spec get_ring_size( ring() ) -> basic_utils:count(). get_ring_size( _Ring={ _WorkingList, ReferenceList } ) -> length( ReferenceList ). See also the ' Speedy unsort : shuffle/1,2 ' thread in the erlang - questions -spec random_permute( list() ) -> list(). random_permute( List ) -> random_permute( List, length( List ) ). random_permute( _List, _RemainingLen=0 ) -> []; random_permute( List, RemainingLen ) -> RemainingLen = length ( List ) , proplists : delete/2 , as we stop at the first matching element found ) Index = random_utils:get_random_value( RemainingLen ), io : format ( " Index=~p , " , [ Index ] ) , [ get_element_at( List, Index ) | random_permute( remove_element_at( List, Index ), RemainingLen - 1 ) ]. -spec random_permute_reciprocal( list() ) -> list(). random_permute_reciprocal( List ) -> operations for latest to first , hence we must start with the latest drawn value . So we draw them all first , and start by the end of that list , ReciprocalIndex = lists:reverse( [ random_utils:get_random_value( L ) || L <- lists:reverse( lists:seq( 1, length( List ) ) ) ] ), random_permute_reciprocal( lists:reverse( List ), ReciprocalIndex, _Acc=[] ). random_permute_reciprocal( _List=[], _ReciprocalIndex=[], Acc ) -> Acc; random_permute_reciprocal( _List=[ H | T ], _ReciprocalIndex=[ I | Is ], Acc ) -> NewAcc = insert_element_at( _Elem=H, Acc, _Index=I ), random_permute_reciprocal( T, Is, NewAcc ). Draws one element at random of the specified list , knowing they all have the -spec draw_element( [ any() ] ) -> any(). draw_element( _ElementList=[] ) -> throw( cannot_draw_from_empty_list ); draw_element( ElementList ) -> Len = length( ElementList ), draw_element( ElementList, Len ). Draws one element at random of the specified list , whose length must be the -spec draw_element( [ any() ], basic_utils:count() ) -> any(). draw_element( ElementList, Length ) -> DrawnIndex = random_utils:get_random_value( Length ), get_element_at( ElementList, DrawnIndex ). draw_element_weighted ( UniformList ) . Draws one element at random of the specified list , which is a list of { ( and they do not have to sum up to 1.0 ) ; they must be positive or null on average ' second ' twice as frequently as ' first ' or ' third ' . Using [ { first,1 } , { second,0 } , { third,1 } ] instead would mean that ' second ' -spec draw_element_weighted( [ { any(), integer() } ] ) -> any(). draw_element_weighted( ElementList ) -> draw_element_weighted( ElementList, sum_probabilities( ElementList ) ). -spec sum_probabilities( [ { _Element, number() } ] ) -> number(). sum_probabilities( ElementList ) -> sum_probabilities( ElementList, _Acc=0 ). sum_probabilities( _ElementList=[], Acc ) -> Acc; sum_probabilities( _ElementList=[ { _Element, Probability } | T ], Acc ) -> sum_probabilities( T, Acc + Probability ). Sum must be equal to the sum of all probabilities in ElementList . draw_element_weighted( _ElementList, 0 ) -> throw( null_total_probability ); draw_element_weighted( ElementList, Sum ) -> DrawnValue = random_utils:get_random_value( Sum ), io : format ( " draw_element : drawn ~B.~n " , [ DrawnValue ] ) , select_element( ElementList, DrawnValue, _CurrentSum=0 ). select_element( [ { Element, Probability } | _T ], DrawnValue, CurrentSum ) when Probability + CurrentSum >= DrawnValue -> Element; select_element( [ { _Element, Probability } | T ], DrawnValue, CurrentSum ) -> select_element( T, DrawnValue, CurrentSum + Probability ). -spec draw_elements_from( [ any() ], basic_utils:count() ) -> [ any() ]. draw_elements_from( ElementList, Count ) -> draw_elements_from( ElementList, Count, _Acc=[] ). draw_elements_from( _ElementList, _Count=0, Acc ) -> Acc; draw_elements_from( ElementList, Count, Acc ) -> Drawn = draw_element( ElementList ), ShortenList = lists:delete( Drawn, ElementList ), draw_elements_from( ShortenList, Count - 1, [ Drawn | Acc ] ).
28afa645288f33bd51e16ee03f8a16a4c1437d73d2421b1535b5cf0dc9017394
alanz/ghc-exactprint
T10045.hs
module T10045 where newtype Meta = Meta () foo (Meta ws1) = let copy :: _ copy w from = copy w True in copy ws1 False
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T10045.hs
haskell
module T10045 where newtype Meta = Meta () foo (Meta ws1) = let copy :: _ copy w from = copy w True in copy ws1 False
d44f3cbe48eac3516e948f40934ceed060d86ee579d3f3a0ded73211e45f1f26
Clozure/ccl-tests
exp.lsp
;-*- Mode: Lisp -*- Author : Created : Mon Sep 1 21:24:44 2003 Contains : Tests of EXP (in-package :cl-test) (compile-and-load "numbers-aux.lsp") (compile-and-load "exp-aux.lsp") ;;; Error tests (deftest exp.error.1 (signals-error (exp) program-error) t) (deftest exp.error.2 (signals-error (exp 0 nil) program-error) t) (deftest exp.error.3 (signals-error (exp 0 0 0) program-error) t) ;;; Other tests (deftest exp.1 (let ((result (exp 0))) (or (eqlt result 1) (eqlt result 1.0f0))) t) (deftest exp.2 (mapcar #'exp '(0.0s0 0.0f0 0.0d0 0.0l0)) (1.0s0 1.0f0 1.0d0 1.0l0)) (deftest exp.3 (mapcar #'exp '(-0.0s0 -0.0f0 -0.0d0 -0.0l0)) (1.0s0 1.0f0 1.0d0 1.0l0)) FIXME ;;; Add more tests here for floating point accuracy (deftest exp.error.4 (signals-error (exp (+ (log most-positive-short-float) 100)) floating-point-overflow) t) (deftest exp.error.5 (signals-error (exp (+ (log most-positive-single-float) 100)) floating-point-overflow) t) #-ccl-qres (deftest exp.error.6 (signals-error (exp (+ (log most-positive-double-float) 100)) floating-point-overflow) t) #-ccl-qres (deftest exp.error.7 (signals-error (exp (+ (log most-positive-long-float) 100)) floating-point-overflow) t) #+bogus-test (deftest exp.error.8 (signals-error (exp (- (log least-positive-short-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.9 (signals-error (exp (- (log least-positive-single-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.10 (signals-error (exp (- (log least-positive-double-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.11 (signals-error (exp (- (log least-positive-double-float) 100)) floating-point-underflow) t)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/exp.lsp
lisp
-*- Mode: Lisp -*- Error tests Other tests Add more tests here for floating point accuracy
Author : Created : Mon Sep 1 21:24:44 2003 Contains : Tests of EXP (in-package :cl-test) (compile-and-load "numbers-aux.lsp") (compile-and-load "exp-aux.lsp") (deftest exp.error.1 (signals-error (exp) program-error) t) (deftest exp.error.2 (signals-error (exp 0 nil) program-error) t) (deftest exp.error.3 (signals-error (exp 0 0 0) program-error) t) (deftest exp.1 (let ((result (exp 0))) (or (eqlt result 1) (eqlt result 1.0f0))) t) (deftest exp.2 (mapcar #'exp '(0.0s0 0.0f0 0.0d0 0.0l0)) (1.0s0 1.0f0 1.0d0 1.0l0)) (deftest exp.3 (mapcar #'exp '(-0.0s0 -0.0f0 -0.0d0 -0.0l0)) (1.0s0 1.0f0 1.0d0 1.0l0)) FIXME (deftest exp.error.4 (signals-error (exp (+ (log most-positive-short-float) 100)) floating-point-overflow) t) (deftest exp.error.5 (signals-error (exp (+ (log most-positive-single-float) 100)) floating-point-overflow) t) #-ccl-qres (deftest exp.error.6 (signals-error (exp (+ (log most-positive-double-float) 100)) floating-point-overflow) t) #-ccl-qres (deftest exp.error.7 (signals-error (exp (+ (log most-positive-long-float) 100)) floating-point-overflow) t) #+bogus-test (deftest exp.error.8 (signals-error (exp (- (log least-positive-short-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.9 (signals-error (exp (- (log least-positive-single-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.10 (signals-error (exp (- (log least-positive-double-float) 100)) floating-point-underflow) t) #+bogus-test (deftest exp.error.11 (signals-error (exp (- (log least-positive-double-float) 100)) floating-point-underflow) t)
86613c37868c9b219df9122ae39d47534a0865b9bc641a6eebb113094b771d69
expipiplus1/vulkan
VK_KHR_external_fence.hs
{-# language CPP #-} -- | = Name -- -- VK_KHR_external_fence - device extension -- -- == VK_KHR_external_fence -- -- [__Name String__] -- @VK_KHR_external_fence@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] 114 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- - Requires @VK_KHR_external_fence_capabilities@ to be enabled for -- any device-level functionality -- -- [__Deprecation state__] -- -- - /Promoted/ to -- <-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1> -- -- [__Contact__] -- - -- <-Docs/issues/new?body=[VK_KHR_external_fence] @critsec%0A*Here describe the issue or question you have about the VK_KHR_external_fence extension* > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2017 - 05 - 08 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- - Promoted to Vulkan 1.1 Core -- -- [__Contributors__] -- - , Google -- - , NVIDIA -- - , NVIDIA -- - , Oculus -- -- - Contributors to @VK_KHR_external_semaphore@ -- -- == Description -- -- An application using external memory may wish to synchronize access to -- that memory using fences. This extension enables an application to create fences from which non - Vulkan handles that reference the -- underlying synchronization primitive can be exported. -- = = Promotion to Vulkan 1.1 -- All functionality in this extension is included in core Vulkan 1.1 , with the suffix omitted . The original type , enum and command names are -- still available as aliases of the core functionality. -- -- == New Structures -- - Extending ' Vulkan . Core10.Fence . FenceCreateInfo ' : -- -- - 'ExportFenceCreateInfoKHR' -- -- == New Enums -- - ' FenceImportFlagBitsKHR ' -- -- == New Bitmasks -- - ' FenceImportFlagsKHR ' -- -- == New Enum Constants -- - ' KHR_EXTERNAL_FENCE_EXTENSION_NAME ' -- - ' KHR_EXTERNAL_FENCE_SPEC_VERSION ' -- -- - Extending ' Vulkan . Core11.Enums . FenceImportFlagBits . FenceImportFlagBits ' : -- -- - 'FENCE_IMPORT_TEMPORARY_BIT_KHR' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- -- - 'STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR' -- -- == Issues -- -- This extension borrows concepts, semantics, and language from -- @VK_KHR_external_semaphore@. That extension’s issues apply equally to -- this extension. -- -- == Version History -- - Revision 1 , 2017 - 05 - 08 ( ) -- -- - Initial revision -- -- == See Also -- ' ExportFenceCreateInfoKHR ' , ' FenceImportFlagBitsKHR ' , ' FenceImportFlagsKHR ' -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_KHR_external_fence Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_external_fence ( pattern STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR , pattern FENCE_IMPORT_TEMPORARY_BIT_KHR , FenceImportFlagsKHR , FenceImportFlagBitsKHR , ExportFenceCreateInfoKHR , KHR_EXTERNAL_FENCE_SPEC_VERSION , pattern KHR_EXTERNAL_FENCE_SPEC_VERSION , KHR_EXTERNAL_FENCE_EXTENSION_NAME , pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME ) where import Data.String (IsString) import Vulkan.Core11.Promoted_From_VK_KHR_external_fence (ExportFenceCreateInfo) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlagBits) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlags) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlags) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlagBits(FENCE_IMPORT_TEMPORARY_BIT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO)) No documentation found for TopLevel " VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR " pattern STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR = STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO No documentation found for TopLevel " VK_FENCE_IMPORT_TEMPORARY_BIT_KHR " pattern FENCE_IMPORT_TEMPORARY_BIT_KHR = FENCE_IMPORT_TEMPORARY_BIT No documentation found for TopLevel " VkFenceImportFlagsKHR " type FenceImportFlagsKHR = FenceImportFlags No documentation found for TopLevel " VkFenceImportFlagBitsKHR " type FenceImportFlagBitsKHR = FenceImportFlagBits No documentation found for TopLevel " VkExportFenceCreateInfoKHR " type ExportFenceCreateInfoKHR = ExportFenceCreateInfo type KHR_EXTERNAL_FENCE_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_EXTERNAL_FENCE_SPEC_VERSION " pattern KHR_EXTERNAL_FENCE_SPEC_VERSION :: forall a . Integral a => a pattern KHR_EXTERNAL_FENCE_SPEC_VERSION = 1 type KHR_EXTERNAL_FENCE_EXTENSION_NAME = "VK_KHR_external_fence" No documentation found for TopLevel " VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME " pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME = "VK_KHR_external_fence"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_KHR_external_fence.hs
haskell
# language CPP # | = Name VK_KHR_external_fence - device extension == VK_KHR_external_fence [__Name String__] @VK_KHR_external_fence@ [__Extension Type__] Device extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] - Requires @VK_KHR_external_fence_capabilities@ to be enabled for any device-level functionality [__Deprecation state__] - /Promoted/ to <-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1> [__Contact__] <-Docs/issues/new?body=[VK_KHR_external_fence] @critsec%0A*Here describe the issue or question you have about the VK_KHR_external_fence extension* > == Other Extension Metadata [__Last Modified Date__] [__IP Status__] No known IP claims. [__Interactions and External Dependencies__] [__Contributors__] - Contributors to @VK_KHR_external_semaphore@ == Description An application using external memory may wish to synchronize access to that memory using fences. This extension enables an application to underlying synchronization primitive can be exported. still available as aliases of the core functionality. == New Structures - 'ExportFenceCreateInfoKHR' == New Enums == New Bitmasks == New Enum Constants - Extending - 'FENCE_IMPORT_TEMPORARY_BIT_KHR' - 'STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR' == Issues This extension borrows concepts, semantics, and language from @VK_KHR_external_semaphore@. That extension’s issues apply equally to this extension. == Version History - Initial revision == See Also == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_KHR_external_fence Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly.
114 1 - Requires support for Vulkan 1.0 - 2017 - 05 - 08 - Promoted to Vulkan 1.1 Core - , Google - , NVIDIA - , NVIDIA - , Oculus create fences from which non - Vulkan handles that reference the = = Promotion to Vulkan 1.1 All functionality in this extension is included in core Vulkan 1.1 , with the suffix omitted . The original type , enum and command names are - Extending ' Vulkan . Core10.Fence . FenceCreateInfo ' : - ' FenceImportFlagBitsKHR ' - ' FenceImportFlagsKHR ' - ' KHR_EXTERNAL_FENCE_EXTENSION_NAME ' - ' KHR_EXTERNAL_FENCE_SPEC_VERSION ' ' Vulkan . Core11.Enums . FenceImportFlagBits . FenceImportFlagBits ' : - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - Revision 1 , 2017 - 05 - 08 ( ) ' ExportFenceCreateInfoKHR ' , ' FenceImportFlagBitsKHR ' , ' FenceImportFlagsKHR ' module Vulkan.Extensions.VK_KHR_external_fence ( pattern STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR , pattern FENCE_IMPORT_TEMPORARY_BIT_KHR , FenceImportFlagsKHR , FenceImportFlagBitsKHR , ExportFenceCreateInfoKHR , KHR_EXTERNAL_FENCE_SPEC_VERSION , pattern KHR_EXTERNAL_FENCE_SPEC_VERSION , KHR_EXTERNAL_FENCE_EXTENSION_NAME , pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME ) where import Data.String (IsString) import Vulkan.Core11.Promoted_From_VK_KHR_external_fence (ExportFenceCreateInfo) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlagBits) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlags) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlags) import Vulkan.Core11.Enums.FenceImportFlagBits (FenceImportFlagBits(FENCE_IMPORT_TEMPORARY_BIT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO)) No documentation found for TopLevel " VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR " pattern STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR = STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO No documentation found for TopLevel " VK_FENCE_IMPORT_TEMPORARY_BIT_KHR " pattern FENCE_IMPORT_TEMPORARY_BIT_KHR = FENCE_IMPORT_TEMPORARY_BIT No documentation found for TopLevel " VkFenceImportFlagsKHR " type FenceImportFlagsKHR = FenceImportFlags No documentation found for TopLevel " VkFenceImportFlagBitsKHR " type FenceImportFlagBitsKHR = FenceImportFlagBits No documentation found for TopLevel " VkExportFenceCreateInfoKHR " type ExportFenceCreateInfoKHR = ExportFenceCreateInfo type KHR_EXTERNAL_FENCE_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_EXTERNAL_FENCE_SPEC_VERSION " pattern KHR_EXTERNAL_FENCE_SPEC_VERSION :: forall a . Integral a => a pattern KHR_EXTERNAL_FENCE_SPEC_VERSION = 1 type KHR_EXTERNAL_FENCE_EXTENSION_NAME = "VK_KHR_external_fence" No documentation found for TopLevel " VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME " pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_EXTERNAL_FENCE_EXTENSION_NAME = "VK_KHR_external_fence"
359c390608002a8435cc633e2e38f0635bc870486cf1da8534b722e6d4163f17
leviroth/ocaml-reddit-api
test_trophies.ml
open! Core open! Async open! Import let%expect_test _ = with_cassette "trophies" ~f:(fun connection -> let%bind trophies = Connection.call_exn connection Endpoint.trophies in print_s [%message "" (trophies : Thing.Award.t list)]; [%expect {| (trophies (((award_id (String v)) (description (String "Since January 2021")) (granted_at (Number 1609678143)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2pgty2)) (name (String "Reddit Premium")) (url (String /premium))) ((award_id Null) (description Null) (granted_at (Number 1585935110)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id Null) (name (String "Three-Year Club")) (url Null)) ((award_id (String o)) (description Null) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 1qr5eq)) (name (String "Verified Email")) (url Null)))) |}]; return ()) ;; let%expect_test _ = with_cassette "user_trophies" ~f:(fun connection -> let%bind trophies = Connection.call_exn connection (Endpoint.user_trophies ~username:(Username.of_string "spez")) in print_s [%message "" ~trophies:(List.take trophies 5 : Thing.Award.t list)]; [%expect {| (trophies (((award_id Null) (description Null) (granted_at (Number 1591416000)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id Null) (name (String "15-Year Club")) (url Null)) ((award_id (String 33)) (description Null) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2mimqo)) (name (String "Argentium Club")) (url Null)) ((award_id (String 32)) (description Null) (granted_at Null) (icon_40 (String -is-Caring-40.png)) (icon_70 (String -is-Caring-70.png)) (id (String 2migfn)) (name (String "Wearing is Caring")) (url Null)) ((award_id (String 31)) (description Null) (granted_at Null) (icon_40 (String -awards-40.png)) (icon_70 (String -awards-70.png)) (id (String 2m8tiw)) (name (String "100 Awards Club")) (url Null)) ((award_id (String 8)) (description (String 2020-06-05)) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2houdv)) (name (String "Inciteful Comment")) (url (String /r/announcements/comments/gxas21/upcoming_changes_to_our_content_policy_our_board/ft0ekhk/?context=5#ft0ekhk))))) |}]; return ()) ;;
null
https://raw.githubusercontent.com/leviroth/ocaml-reddit-api/6519697a39d68d675c3c36fd54add8ba35e939f3/test/test_trophies.ml
ocaml
open! Core open! Async open! Import let%expect_test _ = with_cassette "trophies" ~f:(fun connection -> let%bind trophies = Connection.call_exn connection Endpoint.trophies in print_s [%message "" (trophies : Thing.Award.t list)]; [%expect {| (trophies (((award_id (String v)) (description (String "Since January 2021")) (granted_at (Number 1609678143)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2pgty2)) (name (String "Reddit Premium")) (url (String /premium))) ((award_id Null) (description Null) (granted_at (Number 1585935110)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id Null) (name (String "Three-Year Club")) (url Null)) ((award_id (String o)) (description Null) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 1qr5eq)) (name (String "Verified Email")) (url Null)))) |}]; return ()) ;; let%expect_test _ = with_cassette "user_trophies" ~f:(fun connection -> let%bind trophies = Connection.call_exn connection (Endpoint.user_trophies ~username:(Username.of_string "spez")) in print_s [%message "" ~trophies:(List.take trophies 5 : Thing.Award.t list)]; [%expect {| (trophies (((award_id Null) (description Null) (granted_at (Number 1591416000)) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id Null) (name (String "15-Year Club")) (url Null)) ((award_id (String 33)) (description Null) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2mimqo)) (name (String "Argentium Club")) (url Null)) ((award_id (String 32)) (description Null) (granted_at Null) (icon_40 (String -is-Caring-40.png)) (icon_70 (String -is-Caring-70.png)) (id (String 2migfn)) (name (String "Wearing is Caring")) (url Null)) ((award_id (String 31)) (description Null) (granted_at Null) (icon_40 (String -awards-40.png)) (icon_70 (String -awards-70.png)) (id (String 2m8tiw)) (name (String "100 Awards Club")) (url Null)) ((award_id (String 8)) (description (String 2020-06-05)) (granted_at Null) (icon_40 (String -40.png)) (icon_70 (String -70.png)) (id (String 2houdv)) (name (String "Inciteful Comment")) (url (String /r/announcements/comments/gxas21/upcoming_changes_to_our_content_policy_our_board/ft0ekhk/?context=5#ft0ekhk))))) |}]; return ()) ;;
02620aa7bd6c228b5d64590995696694cd87c143de3e7ee9c3b317d42d7fc964
reborg/clojure-essential-reference
6.clj
< 1 > ;; IllegalArgumentException Duplicate key: (rand) < 2 > # { 0.53148213003 0.7171734431 0.5055531620 }
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sets/hash-set/6.clj
clojure
IllegalArgumentException Duplicate key: (rand)
< 1 > < 2 > # { 0.53148213003 0.7171734431 0.5055531620 }
6cc7e8eb6397f31ddff86cab20fd0094ff319ddbf2b338d6d39f37f84356432a
serokell/universum
Reexport.hs
{-# LANGUAGE Safe #-} | This module reexports functions to work with ' ' type . module Universum.Bool.Reexport ( module Control.Monad , module Data.Bool ) where import Control.Monad (guard, unless, when) import Data.Bool (Bool (..), bool, not, otherwise, (&&), (||))
null
https://raw.githubusercontent.com/serokell/universum/7fc5dd3951d1177d1873e36b0678c759aeb5dc08/src/Universum/Bool/Reexport.hs
haskell
# LANGUAGE Safe #
| This module reexports functions to work with ' ' type . module Universum.Bool.Reexport ( module Control.Monad , module Data.Bool ) where import Control.Monad (guard, unless, when) import Data.Bool (Bool (..), bool, not, otherwise, (&&), (||))
55ab8badca1f38d3e1a1fbc8de88060bbcdc94d32bf70f84073b8726bc72cc95
onedata/op-worker
connection_api.erl
%%%------------------------------------------------------------------- @author ( C ) 2019 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Public API for sending messages via connections of given session. %%% @end %%%------------------------------------------------------------------- -module(connection_api). -author("Bartosz Walkowicz"). -include("proto/oneclient/client_messages.hrl"). -include("proto/oneclient/server_messages.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("ctool/include/errors.hrl"). %% API -export([send/2, send/3, send/4, send_via_any/3]). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc @equiv send(SessionId , , [ ] ) . %% @end %%-------------------------------------------------------------------- -spec send(session:id(), communicator:message()) -> ok | {error, Reason :: term()}. send(SessionId, Msg) -> send(SessionId, Msg, []). %%-------------------------------------------------------------------- %% @doc @equiv send(SessionId , Msg , ExcludedCons , false ) . %% @end %%-------------------------------------------------------------------- -spec send(session:id(), communicator:message(), ExcludedCons :: [pid()]) -> ok | {error, Reason :: term()}. send(SessionId, Msg, ExcludedCons) -> send(SessionId, Msg, ExcludedCons, false). %%-------------------------------------------------------------------- %% @doc %% Sends message to peer. In case of errors during sending tries other %% session connections until message is send or no more available %% connections remains. %% Exceptions to this are encoding errors which immediately fails call. Additionally logs eventual errors if LogErrors is set to true . %% @end %%-------------------------------------------------------------------- -spec send(session:id(), communicator:message(), ExcludedCons :: [pid()], boolean()) -> ok | {error, Reason :: term()}. send(SessionId, Msg, ExcludedCons, LogErrors) -> case send_msg_excluding_connections(SessionId, Msg, ExcludedCons) of ok -> ok; Error -> LogErrors andalso log_sending_msg_error(SessionId, Msg, Error), Error end. %%-------------------------------------------------------------------- %% @doc %% TODO VFS-6364 refactor proxy session - session restart should be on this level %% Tries to send given message via any of specified connections. %% @end %%-------------------------------------------------------------------- -spec send_via_any(communicator:message(), EffSessId :: session:id(), [pid()]) -> ok | {error, term()}. send_via_any(_Msg, EffSessId, []) -> session_manager:restart_session_if_dead(EffSessId), {error, no_connections}; send_via_any(Msg, EffSessId, [Conn]) -> case connection:send_msg(Conn, Msg) of {error, no_connection} = Error -> session_manager:restart_session_if_dead(EffSessId), Error; Result -> Result end; send_via_any(Msg, EffSessId, [Conn | Cons]) -> case connection:send_msg(Conn, Msg) of ok -> ok; {error, serialization_failed} = SerializationError -> SerializationError; {error, sending_msg_via_wrong_conn_type} = WrongConnError -> WrongConnError; {error, no_connection} -> session_manager:restart_session_if_dead(EffSessId), send_via_any(Msg, EffSessId, Cons); _Error -> send_via_any(Msg, EffSessId, Cons) end. %%%=================================================================== Internal functions %%%=================================================================== @private -spec send_msg_excluding_connections(session:id(), communicator:message(), ExcludedCons :: [pid()]) -> ok | {error, term()}. send_msg_excluding_connections(SessionId, Msg, ExcludedCons) -> case session_connections:list(SessionId) of {ok, EffSessId, AllCons} -> Cons = lists_utils:shuffle(AllCons -- ExcludedCons), send_via_any(Msg, EffSessId, Cons); Error -> Error end. @private -spec log_sending_msg_error(session:id(), communicator:message(), {error, term()}) -> ok. log_sending_msg_error(SessionId, _Msg, {error, no_connections}) -> ?debug("Failed to send msg to ~p due to lack of available " "connections", [SessionId]); log_sending_msg_error(SessionId, _Msg, ?ERROR_NOT_FOUND) -> % there is no registry of tasks for session and therefore they are not % interrupted even if session dies. As such it is possible for them to try % send response long after session died ?debug("Failed to send msg to session ~p as it no longer exist", [SessionId]); log_sending_msg_error(SessionId, Msg, Error) -> ?error("Failed to send msg ~s to peer ~p due to: ~p", [ clproto_utils:msg_to_string(Msg), SessionId, Error ]).
null
https://raw.githubusercontent.com/onedata/op-worker/66f5efb3212be16b492e4f500913327777ca7961/src/modules/communication/connection/connection_api.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc Public API for sending messages via connections of given session. @end ------------------------------------------------------------------- API =================================================================== API =================================================================== -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Sends message to peer. In case of errors during sending tries other session connections until message is send or no more available connections remains. Exceptions to this are encoding errors which immediately fails call. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc TODO VFS-6364 refactor proxy session - session restart should be on this level Tries to send given message via any of specified connections. @end -------------------------------------------------------------------- =================================================================== =================================================================== there is no registry of tasks for session and therefore they are not interrupted even if session dies. As such it is possible for them to try send response long after session died
@author ( C ) 2019 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(connection_api). -author("Bartosz Walkowicz"). -include("proto/oneclient/client_messages.hrl"). -include("proto/oneclient/server_messages.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("ctool/include/errors.hrl"). -export([send/2, send/3, send/4, send_via_any/3]). @equiv send(SessionId , , [ ] ) . -spec send(session:id(), communicator:message()) -> ok | {error, Reason :: term()}. send(SessionId, Msg) -> send(SessionId, Msg, []). @equiv send(SessionId , Msg , ExcludedCons , false ) . -spec send(session:id(), communicator:message(), ExcludedCons :: [pid()]) -> ok | {error, Reason :: term()}. send(SessionId, Msg, ExcludedCons) -> send(SessionId, Msg, ExcludedCons, false). Additionally logs eventual errors if LogErrors is set to true . -spec send(session:id(), communicator:message(), ExcludedCons :: [pid()], boolean()) -> ok | {error, Reason :: term()}. send(SessionId, Msg, ExcludedCons, LogErrors) -> case send_msg_excluding_connections(SessionId, Msg, ExcludedCons) of ok -> ok; Error -> LogErrors andalso log_sending_msg_error(SessionId, Msg, Error), Error end. -spec send_via_any(communicator:message(), EffSessId :: session:id(), [pid()]) -> ok | {error, term()}. send_via_any(_Msg, EffSessId, []) -> session_manager:restart_session_if_dead(EffSessId), {error, no_connections}; send_via_any(Msg, EffSessId, [Conn]) -> case connection:send_msg(Conn, Msg) of {error, no_connection} = Error -> session_manager:restart_session_if_dead(EffSessId), Error; Result -> Result end; send_via_any(Msg, EffSessId, [Conn | Cons]) -> case connection:send_msg(Conn, Msg) of ok -> ok; {error, serialization_failed} = SerializationError -> SerializationError; {error, sending_msg_via_wrong_conn_type} = WrongConnError -> WrongConnError; {error, no_connection} -> session_manager:restart_session_if_dead(EffSessId), send_via_any(Msg, EffSessId, Cons); _Error -> send_via_any(Msg, EffSessId, Cons) end. Internal functions @private -spec send_msg_excluding_connections(session:id(), communicator:message(), ExcludedCons :: [pid()]) -> ok | {error, term()}. send_msg_excluding_connections(SessionId, Msg, ExcludedCons) -> case session_connections:list(SessionId) of {ok, EffSessId, AllCons} -> Cons = lists_utils:shuffle(AllCons -- ExcludedCons), send_via_any(Msg, EffSessId, Cons); Error -> Error end. @private -spec log_sending_msg_error(session:id(), communicator:message(), {error, term()}) -> ok. log_sending_msg_error(SessionId, _Msg, {error, no_connections}) -> ?debug("Failed to send msg to ~p due to lack of available " "connections", [SessionId]); log_sending_msg_error(SessionId, _Msg, ?ERROR_NOT_FOUND) -> ?debug("Failed to send msg to session ~p as it no longer exist", [SessionId]); log_sending_msg_error(SessionId, Msg, Error) -> ?error("Failed to send msg ~s to peer ~p due to: ~p", [ clproto_utils:msg_to_string(Msg), SessionId, Error ]).
4c3b7c7142c74546ffec9767c0b22fe5c0baee26c49c294060cede34bc630099
backtracking/combine
pyth.ml
Given a Pythagorean triple ( a , b , c ) , with a < b < c , tile a c*c square using the hooks ( L shapes ) from the two squares a*a and b*b tile a c*c square using the hooks (L shapes) from the two squares a*a and b*b *) open Format primitive Pythagorean triples are generated using a = 2mn b = ( m^2 - n^2 ) c = ( m^2 + n^2 ) primitive Pythagorean triples are generated using a = 2mn b = (m^2 - n^2) c = (m^2 + n^2) *) let n = int_of_string Sys.argv.(1) let m = int_of_string Sys.argv.(2) let f = try int_of_string Sys.argv.(3) with _ -> 1 let rec gcd n m = if m = 0 then n else gcd m (n mod m) let gcd n m = if n > m then gcd n m else gcd m n let () = assert (n < m) let () = assert (n mod 2 <> m mod 2) let () = assert (gcd n m = 1) let a = f * 2*m*n let b = f * (m*m - n*n) let c = f * (m*m + n*n) let a = min a b and b = max a b let () = printf "%d %d %d@." a b c let file = sprintf "pyth-%d-%d-%d.cmb" a b c let cout = open_out file let fmt = formatter_of_out_channel cout let () = fprintf fmt "debug on@\n@\n" let () = fprintf fmt "timing on@\n@\n" let hooks n = for k = 1 to n do fprintf fmt "pattern p_%d_%d = {@\n" n k; fprintf fmt "%s@\n" (String.make k '*'); for i = 1 to k - 1 do fprintf fmt "*@\n" done; fprintf fmt "}@\n@\n" done let () = hooks a; hooks b let () = fprintf fmt "@[tiles all_tiles =@\n[ "; let tiles n = for k = 1 to n do fprintf fmt "p_%d_%d ~one ~sym" n k; if k < n then fprintf fmt ",@ " done in tiles a; fprintf fmt ",@ "; tiles b; fprintf fmt "]@]@\n@\n" let () = fprintf fmt "problem pbm%d = {@\n" c; for k = 1 to c do fprintf fmt "%s@\n" (String.make c '*') done; fprintf fmt "} all_tiles@\n@\n"; fprintf fmt "solve dlx pbm%d svg \"solutions/pyth-%d-%d-%d.svg\"@\n" c a b c; fprintf fmt "# count dlx pbm%d@\n" c let () = fprintf fmt "@."; close_out cout
null
https://raw.githubusercontent.com/backtracking/combine/d2d9276c99f6d09662900c348f062c618a1b4c95/examples/cmb/pyth.ml
ocaml
Given a Pythagorean triple ( a , b , c ) , with a < b < c , tile a c*c square using the hooks ( L shapes ) from the two squares a*a and b*b tile a c*c square using the hooks (L shapes) from the two squares a*a and b*b *) open Format primitive Pythagorean triples are generated using a = 2mn b = ( m^2 - n^2 ) c = ( m^2 + n^2 ) primitive Pythagorean triples are generated using a = 2mn b = (m^2 - n^2) c = (m^2 + n^2) *) let n = int_of_string Sys.argv.(1) let m = int_of_string Sys.argv.(2) let f = try int_of_string Sys.argv.(3) with _ -> 1 let rec gcd n m = if m = 0 then n else gcd m (n mod m) let gcd n m = if n > m then gcd n m else gcd m n let () = assert (n < m) let () = assert (n mod 2 <> m mod 2) let () = assert (gcd n m = 1) let a = f * 2*m*n let b = f * (m*m - n*n) let c = f * (m*m + n*n) let a = min a b and b = max a b let () = printf "%d %d %d@." a b c let file = sprintf "pyth-%d-%d-%d.cmb" a b c let cout = open_out file let fmt = formatter_of_out_channel cout let () = fprintf fmt "debug on@\n@\n" let () = fprintf fmt "timing on@\n@\n" let hooks n = for k = 1 to n do fprintf fmt "pattern p_%d_%d = {@\n" n k; fprintf fmt "%s@\n" (String.make k '*'); for i = 1 to k - 1 do fprintf fmt "*@\n" done; fprintf fmt "}@\n@\n" done let () = hooks a; hooks b let () = fprintf fmt "@[tiles all_tiles =@\n[ "; let tiles n = for k = 1 to n do fprintf fmt "p_%d_%d ~one ~sym" n k; if k < n then fprintf fmt ",@ " done in tiles a; fprintf fmt ",@ "; tiles b; fprintf fmt "]@]@\n@\n" let () = fprintf fmt "problem pbm%d = {@\n" c; for k = 1 to c do fprintf fmt "%s@\n" (String.make c '*') done; fprintf fmt "} all_tiles@\n@\n"; fprintf fmt "solve dlx pbm%d svg \"solutions/pyth-%d-%d-%d.svg\"@\n" c a b c; fprintf fmt "# count dlx pbm%d@\n" c let () = fprintf fmt "@."; close_out cout
26797a31c653570636b0fd4c823b3d717d9eed7bdc11a80ca592dc455da35173
orbitz/oort
msg_dispatch.erl
%%%------------------------------------------------------------------- %%% File : msg_dispatch.erl %%% Author : ortitz <> %%% Description : Handles dispatching messages to select receivers %%% Created : 14 May 2006 by ortitz < > %%%------------------------------------------------------------------- -module(msg_dispatch). -behaviour(gen_server). %% API -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([add/1, remove/0, remove/1, dispatch/3, stop/0]). -export([test/0]). -record(state, {dispatch_map}). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> {ok, #state{dispatch_map=dict:new()}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({add, Pid, Messages}, _From, #state{dispatch_map=Map} = State) when is_pid(Pid), is_list(Messages) -> F = fun(Msg, Dict) -> dict:append(Msg, Pid, Dict) end, {reply, ok, State#state{dispatch_map=lists:foldl(F, Map, Messages)}}; handle_call({remove, Pid, Messages}, _From, #state{dispatch_map=Map} = State) when is_pid(Pid), is_list(Messages) -> F = fun(Msg, Dict) -> case dict:find(Msg, Dict) of {ok, Value} -> dict:store(Msg, lists:filter(fun(Elm) -> Elm /= Pid end, Value), Dict); _ -> Dict end end, {reply, ok, State#state{dispatch_map=lists:foldl(F, Map, Messages)}}; handle_call({remove, Pid}, _From, State) -> handle_call({remove, Pid, dict:fetch_keys(State#state.dispatch_map)}, _From, State). %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(stop, State) -> {stop, normal, State}; handle_cast({Message, Params, Extra}, #state{dispatch_map=Map} = State) -> case dict:find(Message, Map) of {ok, Pids} -> lists:foreach(fun(P) -> P ! {Message, Params, Extra} end, Pids); _ -> ok end, {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %%% Exported functions %%-------------------------------------------------------------------- % Add messages for yourself to receive add(Messages) when is_list(Messages) -> ok = gen_server:call(?MODULE, {add, self(), Messages}). % Remove self from some mesages remove(Messages) when is_list(Messages) -> ok = gen_server:call(?MODULE, {remove, self(), Messages}). remove() -> ok = gen_server:call(?MODULE, {remove, self()}). dispatch(Message, Params, Extra) -> ok = gen_server:cast(?MODULE, {Message, Params, Extra}). stop() -> gen_server:cast(?MODULE, stop). %% Unit test test() -> start_link(), add([boo]), dispatch(boo, [test, test1], []), receive Anything -> Anything = {boo, [test, test1], []} end, dispatch(bar, [], []), remove([boo]), dispatch(boo, [], []), receive Anything1 -> Anything1 = {boo, [], []} after 10000 -> ok end, stop().
null
https://raw.githubusercontent.com/orbitz/oort/a61ec85508917ae9a3f6672a0b708d47c23bb260/src/msg_dispatch.erl
erlang
------------------------------------------------------------------- File : msg_dispatch.erl Author : ortitz <> Description : Handles dispatching messages to select receivers ------------------------------------------------------------------- API gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- Exported functions -------------------------------------------------------------------- Add messages for yourself to receive Remove self from some mesages Unit test
Created : 14 May 2006 by ortitz < > -module(msg_dispatch). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([add/1, remove/0, remove/1, dispatch/3, stop/0]). -export([test/0]). -record(state, {dispatch_map}). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). { ok , State , Timeout } | init([]) -> {ok, #state{dispatch_map=dict:new()}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({add, Pid, Messages}, _From, #state{dispatch_map=Map} = State) when is_pid(Pid), is_list(Messages) -> F = fun(Msg, Dict) -> dict:append(Msg, Pid, Dict) end, {reply, ok, State#state{dispatch_map=lists:foldl(F, Map, Messages)}}; handle_call({remove, Pid, Messages}, _From, #state{dispatch_map=Map} = State) when is_pid(Pid), is_list(Messages) -> F = fun(Msg, Dict) -> case dict:find(Msg, Dict) of {ok, Value} -> dict:store(Msg, lists:filter(fun(Elm) -> Elm /= Pid end, Value), Dict); _ -> Dict end end, {reply, ok, State#state{dispatch_map=lists:foldl(F, Map, Messages)}}; handle_call({remove, Pid}, _From, State) -> handle_call({remove, Pid, dict:fetch_keys(State#state.dispatch_map)}, _From, State). Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(stop, State) -> {stop, normal, State}; handle_cast({Message, Params, Extra}, #state{dispatch_map=Map} = State) -> case dict:find(Message, Map) of {ok, Pids} -> lists:foreach(fun(P) -> P ! {Message, Params, Extra} end, Pids); _ -> ok end, {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. add(Messages) when is_list(Messages) -> ok = gen_server:call(?MODULE, {add, self(), Messages}). remove(Messages) when is_list(Messages) -> ok = gen_server:call(?MODULE, {remove, self(), Messages}). remove() -> ok = gen_server:call(?MODULE, {remove, self()}). dispatch(Message, Params, Extra) -> ok = gen_server:cast(?MODULE, {Message, Params, Extra}). stop() -> gen_server:cast(?MODULE, stop). test() -> start_link(), add([boo]), dispatch(boo, [test, test1], []), receive Anything -> Anything = {boo, [test, test1], []} end, dispatch(bar, [], []), remove([boo]), dispatch(boo, [], []), receive Anything1 -> Anything1 = {boo, [], []} after 10000 -> ok end, stop().
b58079a6cd02e98217c1a408291ab037c19541e3fec2286cbb71d0c74db47824
amnh/PCG
Internal.hs
---------------------------------------------------------------------------- -- | -- Module : File.Format.TNT.Internal Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- Internal types and functions for TNT parsing . Only a subset of types -- should be exported from top level module. ----------------------------------------------------------------------------- # LANGUAGE BangPatterns # # LANGUAGE DeriveFoldable # {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DerivingStrategies #-} # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE StrictData # # LANGUAGE TypeFamilies # module File.Format.TNT.Internal ( TntResult , TreeOnly , WithTaxa(..) , CCode , CCodeAugment(..) , CharacterState(..) , CharacterSet(..) , CNames , CharacterName(..) , Cost(..) , NStates(..) , TRead , TReadTree , LeafyTree(..) , NodeType(..) , XRead(..) , TaxonInfo , TaxonName , TaxonSequence , TntCharacter(..) , TntContinuousCharacter , TntDiscreteCharacter , TntDnaCharacter , TntProteinCharacter , CharacterMetadata(..) , bitsToFlags , characterIndicies , characterStateChar , deserializeStateDiscrete , deserializeStateDna , deserializeStateProtein , discreteStateValues , dnaStateValues , findFirstSet , flexibleNonNegativeInt , flexiblePositiveInt , initialMetaData , keyword , metaDataTemplate , modifyMetaDataState , modifyMetaDataNames , modifyMetaDataTCM , nonNegInt , proteinStateValues , serializeStateDiscrete , symbol , trim , whitespace , whitespaceInline ) where import Control.DeepSeq (NFData, force) import Control.Monad ((<=<)) import Data.Alphabet.IUPAC import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.Bits import Data.CaseInsensitive (FoldCase) import Data.Char (isAlpha, isLower, isUpper, toLower, toUpper) import Data.Foldable import Data.Functor (($>)) import Data.Key (lookup, (!)) import Data.List (inits) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import Data.Map (Map, assocs, insert, insertWith, keys) import qualified Data.Map as M import Data.Matrix.NotStupid (Matrix) import Data.Proxy import Data.Scientific (floatingOrInteger) import Data.Sequence (Seq) import Data.Tuple (swap) import Data.Vector (Vector) import qualified Data.Vector as V (fromList) import Data.Word (Word32, Word64, Word8) import GHC.Generics (Generic) import Prelude hiding (lookup) import Text.Megaparsec import Text.Megaparsec.Char import Text.Megaparsec.Char.Lexer (decimal, scientific, signed) -- | The result of parsing a TNT file . -- A file can contain either only tree data with labeled leaf nodes or -- a collection of taxa sequences with coresponsing metadata and possibly -- corresponding tree data. type TntResult = Either TreeOnly WithTaxa -- | -- The possible parse result when the file contains only tree data. type TreeOnly = TRead -- | -- The possible parse result when the file contains taxa sequences. -- 'trees' represents a (possibly empty) forest where each tree in -- the forest must have the complete taxa set as it's leaf node set. data WithTaxa = WithTaxa { sequences :: Vector TaxonInfo , charMetaData :: Vector CharacterMetadata , trees :: [LeafyTree TaxonInfo] } deriving stock (Show) CCode types -------------------------------------------------------------------------------- -- | Parse result from a CCODE command that represents a list of augmentations to -- the default metadata state for some characters. type CCode = NonEmpty CCodeAugment -- | -- The specification of which characters need which metadata mutations. data CCodeAugment = CCodeAugment { charState :: NonEmpty CharacterState , charSet :: NonEmpty CharacterSet } deriving stock (Show) -- | -- The possible character metatadata values that can be mutated. data CharacterState = Additive | NonAdditive | Active | NonActive | Sankoff | NonSankoff | Weight Int | Steps Int deriving stock (Eq, Show) -- | -- A nonempty contiguous character range. data CharacterSet = Single Int | Range Int Int | FromStart Int | ToEnd Int | Whole deriving stock (Eq, Show) -- CNames types -------------------------------------------------------------------------------- -- | -- A list of names for the states of characters in the taxa sequences. type CNames = NonEmpty CharacterName -- | -- A specification for the state names of a given character in the taxon's sequence. data CharacterName = CharacterName { sequenceIndex :: Int , characterId :: String , characterStateNames :: [String] } deriving stock (Show) -- Cost types -------------------------------------------------------------------------------- -- | A custom TCM derivation for a list of characters in the taxa sequences . data Cost = Cost { costIndicies :: CharacterSet , costMatrix :: Matrix Double } deriving stock (Eq, Show) NStates types -------------------------------------------------------------------------------- -- | -- Specifies how to interpret the various character types in the taxa sequences. data NStates = DnaStates Bool | NumericStates Int | ProteinStates | ContinuousStates deriving stock (Show) TRead types -------------------------------------------------------------------------------- -- | Parse result of an internal TREAD command . -- Specifies a nonempty forest of trees, where the leaf node set must be validated againtst the taxa set from a command . type TRead = NonEmpty TReadTree -- | -- A tree with data only at the leaf nodes. Leaf nodes contain different criteria -- for matching the node against a given taxa from the taxa set. type TReadTree = LeafyTree NodeType -- | -- A tree which has had each leaf node matched against the taxon from the taxa set . type TNTTree = LeafyTree TaxonInfo -- | -- A tree which has had each leaf node matched against the taxon from the taxa set. type TNTTree = LeafyTree TaxonInfo -} -- | -- A rose tree which only contains data at the leaf nodes. data LeafyTree a = Leaf a | Branch [LeafyTree a] deriving stock (Eq, Foldable, Functor, Show, Traversable) -- | -- Multiple possible criteria for matching leaf nodes to taxa from the taxa set. data NodeType = Index Int | Name String | Prefix String deriving stock (Eq, Show) types -------------------------------------------------------------------------------- -- | Parse result of an XREAD command . data XRead = XRead { charCountx :: Int , taxaCountx :: Int , sequencesx :: NonEmpty TaxonInfo } deriving stock (Show) -- | The sequence information for a taxon within the TNT file 's command . -- Contains the 'TaxonName' and the naive 'TaxonSequence' type TaxonInfo = (TaxonName, TaxonSequence) -- | The name of a taxon in a TNT file 's command . type TaxonName = String -- | The naive sequence of a taxon in a TNT files ' XREAD command . type TaxonSequence = Seq TntCharacter -- | -- Different character types are deserialized from sequences segments. -- After all segments are collected they are de-interleaved into a single -- 'TaxonSequence'. data TntCharacter = Continuous TntContinuousCharacter | Discrete TntDiscreteCharacter | Dna TntDnaCharacter | Protein TntProteinCharacter deriving stock (Eq) -- | -- A 'TntContinuousCharacter' is an real valued character. Continuous -- characters can have negative values. Continuous values are serialized -- textually as decimal values or integral values, scientific notation supported. type TntContinuousCharacter = Maybe Double -- | -- A 'TntDiscreteCharacter' is an integral value in the range '[0..62]'. Discrete values are serialized textualy as one of the 64 values : ' [ 0 .. 9 ] < > [ \'A\' .. \'B\ ' ] < > [ \'a\' .. \'z\ ' ] < > " - ? " ' . -- Missing \'?\' represents the empty ambiguity group. -- Each value corresponds to it's respective bit in the 'Word64'. Ambiguity groups -- are represented by 'Word64' values with multiple set bits. newtype TntDiscreteCharacter = TntDis Word64 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) -- | A ' ' represents a nucleotide ( ' " ACGT " ' ) as an integral value in the range ' [ 0 .. 3 ] ' respectively . If gap characters ( \'-\ ' ) are treated as a fifth -- state then values the additional value '4' is added to the integral range. Discrete values are serialized textualy as the DNA IUPAC codes case - insensitively , -- along with \'-\' & \'?\' characters representing gap or missing data respecitively. Gap represents an ambiguity group of all possible proteins unless gaps are treated as a fifth state . Missing represents the empty ambiguity group . newtype TntDnaCharacter = TntDna Word8 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) -- | A ' TntProteinCharacter ' is an integral value in the range ' [ 0 .. 20 ] ' . Discrete values are serialized textualy as the protein IUPAC codes case - insensitively , -- along with \'-\' & \'?\' characters representing gap or missing data respecitively. -- Missing represents the empty ambiguity group. newtype TntProteinCharacter = TntPro Word32 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) instance Show TntCharacter where show (Continuous x) = show x show (Discrete x) = show x show (Dna x) = show x show (Protein x) = show x instance Show TntDiscreteCharacter where show x = case x `lookup` serializeStateDiscrete of Just c -> [c] Nothing -> "[" <> str <> "]" where str = (serializeStateDiscrete !) <$> bitsToFlags x instance Show TntDnaCharacter where show x = [serializeStateDna ! x] instance Show TntProteinCharacter where show x = case x `lookup` serializeStateProtein of Just c -> [c] Nothing -> "[" <> str <> "]" where str = (serializeStateProtein !) <$> bitsToFlags x CharacterMetadata types -------------------------------------------------------------------------------- -- | -- The metadata of a character specifying the attributes of the character -- specified in the file. -- -- Default 'CharacterMetadata' values: -- > > > defaultMetaData -- CharMeta -- { characterName = "" , characterStates = mempty -- , additive = False -- , active = True -- , sankoff = False , weight = 1 , steps = 1 -- , costTCM = Nothing -- } data CharacterMetadata = CharMeta { characterName :: String , characterStates :: Vector String , additive :: Bool --- Mutually exclusive sankoff! , active :: Bool , sankoff :: Bool , weight :: Int , steps :: Int , costTCM :: Maybe (Matrix Double) } deriving stock (Show) -- | The default values for ' CharacterMetadata ' as specified by the TNT " documentation . " initialMetaData :: CharacterMetadata initialMetaData = CharMeta { characterName = "" , characterStates = mempty , additive = False , active = True , sankoff = False , weight = 1 , steps = 1 , costTCM = Nothing } -- | Convienece method for generating a ' CharacterMetadata ' by specifying a single -- attribute value and defaulting all the other values. metaDataTemplate :: CharacterState -> CharacterMetadata metaDataTemplate state = modifyMetaDataState state initialMetaData -- | Overwrite the value of the ' CharacterMetadata ' with the ' CharacterState ' value . modifyMetaDataState :: CharacterState -> CharacterMetadata -> CharacterMetadata modifyMetaDataState Additive old = old { additive = True , sankoff = False } modifyMetaDataState NonAdditive old = old { additive = False } modifyMetaDataState Active old = old { active = True } modifyMetaDataState NonActive old = old { active = False } modifyMetaDataState Sankoff old = old { additive = False, sankoff = True } modifyMetaDataState NonSankoff old = old { sankoff = False } modifyMetaDataState (Weight n) old = old { weight = n } modifyMetaDataState (Steps n) old = old { steps = n } -- | -- Overwrite the naming variables of the 'CharacterMetadata'. modifyMetaDataNames :: CharacterName -> CharacterMetadata -> CharacterMetadata modifyMetaDataNames charName old = old { characterName = characterId charName , characterStates = V.fromList $ characterStateNames charName } -- | Overwrite the TCM attribute of the ' CharacterMetadata ' . modifyMetaDataTCM :: Matrix Double -> CharacterMetadata -> CharacterMetadata modifyMetaDataTCM mat old = old { costTCM = Just mat } -- | -- Parses an non-negative integer from a variety of representations. -- Parses both signed integral values and signed floating values -- if the value is non-negative and an integer. flexibleNonNegativeInt :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> m Int flexibleNonNegativeInt labeling = either coerceFloating coerceIntegral . floatingOrInteger =<< signed whitespace scientific <?> ("positive integer for " <> labeling) where coerceIntegral x | x < (0::Int) = fail $ concat ["The ",labeling," value (",show x,") is a negative number"] | otherwise = pure $ fromEnum x coerceFloating : : ( MonadParsec e s m { - , s ~ Char - } ) = > Double - > m Int coerceFloating = assertNonNegative <=< assertIntegral labeling where assertNonNegative x | x >= 0 = pure x | otherwise = fail $ concat ["The ",labeling," value (",show x,") is a negative value"] -- | -- Parses an positive integer from a variety of representations. -- Parses both signed integral values and signed floating values -- if the value is positive and an integer. -- -- @flexiblePositiveInt labeling@ uses the @labeling@ parameter to improve ParseError generation . -- -- ==== __Examples__ -- -- Basic usage: -- > > > parse ( flexiblePositiveInt " errorCount " ) " " " 1\n " -- Right 1 -- > > > parse ( flexiblePositiveInt " errorCount " ) " " " 0\n " -- Left 1:2: -- expecting rest of number -- The errorCount value (0) is not a positive number -- > > > parse ( flexiblePositiveInt " errorCount " ) " " " 42.0\n " -- Right 42 -- > > > parse ( flexiblePositiveInt " errorCount " ) " " " 0.1337\n " -- Left 1:7: -- expecting 'E', 'e', or rest of number The errorCount value ( 0.1337 ) is a real value , not an integral value The errorCount value ( 0.1337 ) is not a positive integer flexiblePositiveInt :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> m Int flexiblePositiveInt labeling = either coerceFloating coerceIntegral . floatingOrInteger =<< signed whitespace scientific <?> ("positive integer for " <> labeling) where coerceIntegral x | x <= (0::Int) = fail $ concat ["The ",labeling," value (",show x,") is not a positive number"] | otherwise = pure $ fromEnum x coerceFloating = assertPositive <=< assertIntegral labeling where assertPositive x | x > 0 = pure x | otherwise = fail $ concat ["The ",labeling," value (",show x,") is not a positive integer"] -- | Consumes a TNT keyword flexibly . -- @keyword fullName minChars@ will parse the __longest prefix of__ @fullName@ requiring that _ _ at least _ _ the first @minChars@ of @fullName@ are in the prefix . -- Keyword prefixes are terminated with an `hspace` which is not consumed by the combinator. -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> parse (keyword "abrakadabra" 4) "" "abrakadabra" -- Right "abrakadabra" -- -- >>> parse (keyword "abrakadabra" 4) "" "abrakad" -- Right "abrakadabra" -- -- >>> parse (keyword "abrakadabra" 4) "" "abra" -- Right "abrakadabra" -- -- >>> parse (keyword "abrakadabra" 4) "" "abr" -- Left 1:1: -- unexpected "abr" -- expecting keyword 'abrakadabra' keyword :: forall e s m. (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> Int -> m () keyword x y = abreviatable x y $> () where abreviatable fullName minimumChars | minimumChars < 1 = fail $ "Nonpositive abbreviation prefix (" <> show minimumChars <> ") supplied to abreviatable combinator" | not $ all isAlpha fullName = fail $ "A keyword containing a non alphabetic character: '" <> show fullName <> "' supplied to abreviateable combinator" | otherwise = combinator <?> "keyword '" <> fullName <> "'" where combinator = choice partialOptions $> fullName partialOptions = makePartial <$> drop minimumChars (inits fullName) makePartial = try . (<* terminator) . string' . tokensToChunk (Proxy :: Proxy s) terminator = lookAhead $ satisfy (not . isAlpha) -- | -- Parses an Int which is non-negative. This Int is not parsed flexibly. -- Will fail integral valued Double literals. Use this in preference to 'flexibleNonNegativeInt' when expecting one of these chars " .eE " adjacent to the Int value . nonNegInt :: (MonadParsec e s m, Token s ~ Char) => m Int nonNegInt = decimal -- | -- Parses an Integral value from a 'Double' value. If the 'Double' is not an integral value , then a parse error is raised . The first ' String ' parameter -- is used as a label in the error reporting. assertIntegral :: MonadFail m => String -> Double -> m Int assertIntegral labeling x | isInt x = pure $ fromEnum rounded | otherwise = fail $ fold [ "The ", labeling, " value (", show x, ") is a real value, not an integral value" ] where isInt n = n == fromInteger rounded rounded = round x -- | -- Parses a single character index or a contiguous character range. characterIndicies :: (MonadParsec e s m, Token s ~ Char) => m CharacterSet characterIndicies = choice $ try <$> [range, fromStart, singleVal, toEnd, whole] where range = Range <$> num <* dot <*> num fromStart = FromStart <$> num <* dot singleVal = Single <$> num toEnd = dot *> (ToEnd <$> num) whole = dot $> Whole num = symbol (nonNegInt <?> "sequence index value") dot = symbol (char '.') -- | Parses one of the valid character states for a TNT file . characterStateChar :: (MonadParsec e s m, Token s ~ Char) => m Char characterStateChar = oneOf (toList discreteStateValues) -- | The only 64 ( case - insensitive ) valid state values for a TNT file . discreteStateValues :: Vector Char discreteStateValues = V.fromList $ fold [['0'..'9'], ['A'..'Z'], ['a'..'z'], "-", "?"] -- | -- The only valid state values for a DNA character. dnaStateValues :: Vector Char dnaStateValues = V.fromList $ keys deserializeStateDna -- | -- The only valid state values for a protein character. proteinStateValues :: Vector Char proteinStateValues = V.fromList $ keys deserializeStateProtein -- | A map for serializing discrete state chatracters . serializeStateDiscrete :: Map TntDiscreteCharacter Char serializeStateDiscrete = swapMap deserializeStateDiscrete -- | A map for deserializing discrete state chatracters . deserializeStateDiscrete :: Map Char TntDiscreteCharacter deserializeStateDiscrete = force $ insert '?' allBits core where allBits = foldl (.|.) zeroBits core core = M.fromList $ zip (toList discreteStateValues) (bit <$> [0..]) -- | A map for serializing dna state chatracters . serializeStateDna :: Map TntDnaCharacter Char serializeStateDna = swapMap deserializeStateDna -- | A map for deserializing dna state chatracters . deserializeStateDna :: Map Char TntDnaCharacter deserializeStateDna = force . buildFromBimap f $ BM.filter g iupacToDna where f = \case 'A' -> 0 'G' -> 1 'C' -> 2 'T' -> 3 '-' -> 4 _ -> error "Fatal construction error in TNT parser's DNA IUPAC deserializer" g x _ = not . isLower . head $ NE.head x -- | A map for deserializing protein state chatracters . serializeStateProtein :: Map TntProteinCharacter Char serializeStateProtein = swapMap deserializeStateProtein -- | A map for deserializing protein state chatracters . deserializeStateProtein :: Map Char TntProteinCharacter deserializeStateProtein = force $ buildFromBimap f iupacToDna where f = \case 'A' -> 0 'C' -> 1 'D' -> 2 'E' -> 3 'F' -> 4 'G' -> 5 'H' -> 6 'I' -> 7 'K' -> 8 'L' -> 9 'M' -> 10 'N' -> 11 'P' -> 12 'Q' -> 13 'R' -> 14 'S' -> 15 'T' -> 16 'V' -> 17 'W' -> 18 'Y' -> 19 '-' -> 20 _ -> error "Fatal construction error in TNT parser's protein IUPAC deserializer" buildFromBimap :: Bits b => (Char -> Int) -> Bimap (NonEmpty String) (NonEmpty String) -> Map Char b buildFromBimap f = casei . M.fromDistinctAscList . fmap convert . BM.toAscList where convert :: Bits b => (NonEmpty String, NonEmpty String) -> (Char, b) convert (x,y) = (key, val) where key = head $ NE.head x val = foldl (\b -> (b .|.) . bit . f . head) zeroBits y -- | -- Add case insensitive keys to map with the corresponding keys. casei :: Map Char v -> Map Char v casei x = foldl f x $ assocs x where f m (k,v) | isLower k = insertWith g (toUpper k) v m | isUpper k = insertWith g (toLower k) v m | otherwise = m g _ o = o -- Don't overwrite old, opposite case values in the map. -- | -- Gets the set bit flags of all bits in the finite bit structure. -- A useful decunstruction to supply to folds. bitsToFlags :: FiniteBits b => b -> [b] bitsToFlags b | zeroBits == b = [] | otherwise = bit i : bitsToFlags (b `clearBit` i) where i = findFirstSet b -- | -- Gets the index of the least significant set bit. findFirstSet :: FiniteBits b => b -> Int findFirstSet = countTrailingZeros -- | -- Inverts a map. swapMap :: Ord a => Map k a -> Map a k swapMap x = let !tups = assocs x in M.fromList $ swap <$> tups -- | -- Consumes trailing whitespace after the parameter combinator. symbol :: (MonadParsec e s m, Token s ~ Char) => m a -> m a symbol c = c <* whitespace -- | -- Consumes trailing whitespace after the parameter combinator. trim :: (MonadParsec e s m, Token s ~ Char) => m a -> m a trim c = whitespace *> c <* whitespace -- | Consumes zero or more whitespace characters _ _ including _ _ line breaks . # INLINE whitespace # whitespace :: (MonadParsec e s m, Token s ~ Char) => m () whitespace = space -- | Consumes zero or more whitespace characters that are not line breaks . # INLINE whitespaceInline # whitespaceInline :: (MonadParsec e s m, Token s ~ Char) => m () whitespaceInline = hspace
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/file-parsers/src/File/Format/TNT/Internal.hs
haskell
-------------------------------------------------------------------------- | Module : File.Format.TNT.Internal License : BSD-style Maintainer : Stability : provisional Portability : portable should be exported from top level module. --------------------------------------------------------------------------- # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE DeriveTraversable # # LANGUAGE DerivingStrategies # | A file can contain either only tree data with labeled leaf nodes or a collection of taxa sequences with coresponsing metadata and possibly corresponding tree data. | The possible parse result when the file contains only tree data. | The possible parse result when the file contains taxa sequences. 'trees' represents a (possibly empty) forest where each tree in the forest must have the complete taxa set as it's leaf node set. ------------------------------------------------------------------------------ | the default metadata state for some characters. | The specification of which characters need which metadata mutations. | The possible character metatadata values that can be mutated. | A nonempty contiguous character range. CNames types ------------------------------------------------------------------------------ | A list of names for the states of characters in the taxa sequences. | A specification for the state names of a given character in the taxon's sequence. Cost types ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | Specifies how to interpret the various character types in the taxa sequences. ------------------------------------------------------------------------------ | Specifies a nonempty forest of trees, where the leaf node set must be validated | A tree with data only at the leaf nodes. Leaf nodes contain different criteria for matching the node against a given taxa from the taxa set. | A tree which has had each leaf node matched against the taxon from the taxa set . | A tree which has had each leaf node matched against the taxon from the taxa set. | A rose tree which only contains data at the leaf nodes. | Multiple possible criteria for matching leaf nodes to taxa from the taxa set. ------------------------------------------------------------------------------ | | Contains the 'TaxonName' and the naive 'TaxonSequence' | | | Different character types are deserialized from sequences segments. After all segments are collected they are de-interleaved into a single 'TaxonSequence'. | A 'TntContinuousCharacter' is an real valued character. Continuous characters can have negative values. Continuous values are serialized textually as decimal values or integral values, scientific notation supported. | A 'TntDiscreteCharacter' is an integral value in the range '[0..62]'. Discrete Missing \'?\' represents the empty ambiguity group. Each value corresponds to it's respective bit in the 'Word64'. Ambiguity groups are represented by 'Word64' values with multiple set bits. | state then values the additional value '4' is added to the integral range. along with \'-\' & \'?\' characters representing gap or missing data respecitively. | along with \'-\' & \'?\' characters representing gap or missing data respecitively. Missing represents the empty ambiguity group. ------------------------------------------------------------------------------ | The metadata of a character specifying the attributes of the character specified in the file. Default 'CharacterMetadata' values: CharMeta { characterName = "" , additive = False , active = True , sankoff = False , costTCM = Nothing } - Mutually exclusive sankoff! | | attribute value and defaulting all the other values. | | Overwrite the naming variables of the 'CharacterMetadata'. | | Parses an non-negative integer from a variety of representations. Parses both signed integral values and signed floating values if the value is non-negative and an integer. | Parses an positive integer from a variety of representations. Parses both signed integral values and signed floating values if the value is positive and an integer. @flexiblePositiveInt labeling@ uses the @labeling@ parameter to ==== __Examples__ Basic usage: Right 1 Left 1:2: expecting rest of number The errorCount value (0) is not a positive number Right 42 Left 1:7: expecting 'E', 'e', or rest of number | @keyword fullName minChars@ will parse the __longest prefix of__ @fullName@ Keyword prefixes are terminated with an `hspace` which is not consumed by the combinator. ==== __Examples__ Basic usage: >>> parse (keyword "abrakadabra" 4) "" "abrakadabra" Right "abrakadabra" >>> parse (keyword "abrakadabra" 4) "" "abrakad" Right "abrakadabra" >>> parse (keyword "abrakadabra" 4) "" "abra" Right "abrakadabra" >>> parse (keyword "abrakadabra" 4) "" "abr" Left 1:1: unexpected "abr" expecting keyword 'abrakadabra' | Parses an Int which is non-negative. This Int is not parsed flexibly. Will fail integral valued Double literals. Use this in preference to 'flexibleNonNegativeInt' | Parses an Integral value from a 'Double' value. If the 'Double' is not an is used as a label in the error reporting. | Parses a single character index or a contiguous character range. | | | The only valid state values for a DNA character. | The only valid state values for a protein character. | | | | | | | Add case insensitive keys to map with the corresponding keys. Don't overwrite old, opposite case values in the map. | Gets the set bit flags of all bits in the finite bit structure. A useful decunstruction to supply to folds. | Gets the index of the least significant set bit. | Inverts a map. | Consumes trailing whitespace after the parameter combinator. | Consumes trailing whitespace after the parameter combinator. | |
Copyright : ( c ) 2015 - 2021 Ward Wheeler Internal types and functions for TNT parsing . Only a subset of types # LANGUAGE BangPatterns # # LANGUAGE DeriveFoldable # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE StrictData # # LANGUAGE TypeFamilies # module File.Format.TNT.Internal ( TntResult , TreeOnly , WithTaxa(..) , CCode , CCodeAugment(..) , CharacterState(..) , CharacterSet(..) , CNames , CharacterName(..) , Cost(..) , NStates(..) , TRead , TReadTree , LeafyTree(..) , NodeType(..) , XRead(..) , TaxonInfo , TaxonName , TaxonSequence , TntCharacter(..) , TntContinuousCharacter , TntDiscreteCharacter , TntDnaCharacter , TntProteinCharacter , CharacterMetadata(..) , bitsToFlags , characterIndicies , characterStateChar , deserializeStateDiscrete , deserializeStateDna , deserializeStateProtein , discreteStateValues , dnaStateValues , findFirstSet , flexibleNonNegativeInt , flexiblePositiveInt , initialMetaData , keyword , metaDataTemplate , modifyMetaDataState , modifyMetaDataNames , modifyMetaDataTCM , nonNegInt , proteinStateValues , serializeStateDiscrete , symbol , trim , whitespace , whitespaceInline ) where import Control.DeepSeq (NFData, force) import Control.Monad ((<=<)) import Data.Alphabet.IUPAC import Data.Bimap (Bimap) import qualified Data.Bimap as BM import Data.Bits import Data.CaseInsensitive (FoldCase) import Data.Char (isAlpha, isLower, isUpper, toLower, toUpper) import Data.Foldable import Data.Functor (($>)) import Data.Key (lookup, (!)) import Data.List (inits) import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NE import Data.Map (Map, assocs, insert, insertWith, keys) import qualified Data.Map as M import Data.Matrix.NotStupid (Matrix) import Data.Proxy import Data.Scientific (floatingOrInteger) import Data.Sequence (Seq) import Data.Tuple (swap) import Data.Vector (Vector) import qualified Data.Vector as V (fromList) import Data.Word (Word32, Word64, Word8) import GHC.Generics (Generic) import Prelude hiding (lookup) import Text.Megaparsec import Text.Megaparsec.Char import Text.Megaparsec.Char.Lexer (decimal, scientific, signed) The result of parsing a TNT file . type TntResult = Either TreeOnly WithTaxa type TreeOnly = TRead data WithTaxa = WithTaxa { sequences :: Vector TaxonInfo , charMetaData :: Vector CharacterMetadata , trees :: [LeafyTree TaxonInfo] } deriving stock (Show) CCode types Parse result from a CCODE command that represents a list of augmentations to type CCode = NonEmpty CCodeAugment data CCodeAugment = CCodeAugment { charState :: NonEmpty CharacterState , charSet :: NonEmpty CharacterSet } deriving stock (Show) data CharacterState = Additive | NonAdditive | Active | NonActive | Sankoff | NonSankoff | Weight Int | Steps Int deriving stock (Eq, Show) data CharacterSet = Single Int | Range Int Int | FromStart Int | ToEnd Int | Whole deriving stock (Eq, Show) type CNames = NonEmpty CharacterName data CharacterName = CharacterName { sequenceIndex :: Int , characterId :: String , characterStateNames :: [String] } deriving stock (Show) A custom TCM derivation for a list of characters in the taxa sequences . data Cost = Cost { costIndicies :: CharacterSet , costMatrix :: Matrix Double } deriving stock (Eq, Show) NStates types data NStates = DnaStates Bool | NumericStates Int | ProteinStates | ContinuousStates deriving stock (Show) TRead types Parse result of an internal TREAD command . againtst the taxa set from a command . type TRead = NonEmpty TReadTree type TReadTree = LeafyTree NodeType type TNTTree = LeafyTree TaxonInfo type TNTTree = LeafyTree TaxonInfo -} data LeafyTree a = Leaf a | Branch [LeafyTree a] deriving stock (Eq, Foldable, Functor, Show, Traversable) data NodeType = Index Int | Name String | Prefix String deriving stock (Eq, Show) types Parse result of an XREAD command . data XRead = XRead { charCountx :: Int , taxaCountx :: Int , sequencesx :: NonEmpty TaxonInfo } deriving stock (Show) The sequence information for a taxon within the TNT file 's command . type TaxonInfo = (TaxonName, TaxonSequence) The name of a taxon in a TNT file 's command . type TaxonName = String The naive sequence of a taxon in a TNT files ' XREAD command . type TaxonSequence = Seq TntCharacter data TntCharacter = Continuous TntContinuousCharacter | Discrete TntDiscreteCharacter | Dna TntDnaCharacter | Protein TntProteinCharacter deriving stock (Eq) type TntContinuousCharacter = Maybe Double values are serialized textualy as one of the 64 values : ' [ 0 .. 9 ] < > [ \'A\' .. \'B\ ' ] < > [ \'a\' .. \'z\ ' ] < > " - ? " ' . newtype TntDiscreteCharacter = TntDis Word64 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) A ' ' represents a nucleotide ( ' " ACGT " ' ) as an integral value in the range ' [ 0 .. 3 ] ' respectively . If gap characters ( \'-\ ' ) are treated as a fifth Discrete values are serialized textualy as the DNA IUPAC codes case - insensitively , Gap represents an ambiguity group of all possible proteins unless gaps are treated as a fifth state . Missing represents the empty ambiguity group . newtype TntDnaCharacter = TntDna Word8 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) A ' TntProteinCharacter ' is an integral value in the range ' [ 0 .. 20 ] ' . Discrete values are serialized textualy as the protein IUPAC codes case - insensitively , newtype TntProteinCharacter = TntPro Word32 deriving newtype (Bits, Eq, FiniteBits, NFData, Ord) deriving stock (Generic) instance Show TntCharacter where show (Continuous x) = show x show (Discrete x) = show x show (Dna x) = show x show (Protein x) = show x instance Show TntDiscreteCharacter where show x = case x `lookup` serializeStateDiscrete of Just c -> [c] Nothing -> "[" <> str <> "]" where str = (serializeStateDiscrete !) <$> bitsToFlags x instance Show TntDnaCharacter where show x = [serializeStateDna ! x] instance Show TntProteinCharacter where show x = case x `lookup` serializeStateProtein of Just c -> [c] Nothing -> "[" <> str <> "]" where str = (serializeStateProtein !) <$> bitsToFlags x CharacterMetadata types > > > defaultMetaData , characterStates = mempty , weight = 1 , steps = 1 data CharacterMetadata = CharMeta { characterName :: String , characterStates :: Vector String , active :: Bool , sankoff :: Bool , weight :: Int , steps :: Int , costTCM :: Maybe (Matrix Double) } deriving stock (Show) The default values for ' CharacterMetadata ' as specified by the TNT " documentation . " initialMetaData :: CharacterMetadata initialMetaData = CharMeta { characterName = "" , characterStates = mempty , additive = False , active = True , sankoff = False , weight = 1 , steps = 1 , costTCM = Nothing } Convienece method for generating a ' CharacterMetadata ' by specifying a single metaDataTemplate :: CharacterState -> CharacterMetadata metaDataTemplate state = modifyMetaDataState state initialMetaData Overwrite the value of the ' CharacterMetadata ' with the ' CharacterState ' value . modifyMetaDataState :: CharacterState -> CharacterMetadata -> CharacterMetadata modifyMetaDataState Additive old = old { additive = True , sankoff = False } modifyMetaDataState NonAdditive old = old { additive = False } modifyMetaDataState Active old = old { active = True } modifyMetaDataState NonActive old = old { active = False } modifyMetaDataState Sankoff old = old { additive = False, sankoff = True } modifyMetaDataState NonSankoff old = old { sankoff = False } modifyMetaDataState (Weight n) old = old { weight = n } modifyMetaDataState (Steps n) old = old { steps = n } modifyMetaDataNames :: CharacterName -> CharacterMetadata -> CharacterMetadata modifyMetaDataNames charName old = old { characterName = characterId charName , characterStates = V.fromList $ characterStateNames charName } Overwrite the TCM attribute of the ' CharacterMetadata ' . modifyMetaDataTCM :: Matrix Double -> CharacterMetadata -> CharacterMetadata modifyMetaDataTCM mat old = old { costTCM = Just mat } flexibleNonNegativeInt :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> m Int flexibleNonNegativeInt labeling = either coerceFloating coerceIntegral . floatingOrInteger =<< signed whitespace scientific <?> ("positive integer for " <> labeling) where coerceIntegral x | x < (0::Int) = fail $ concat ["The ",labeling," value (",show x,") is a negative number"] | otherwise = pure $ fromEnum x coerceFloating : : ( MonadParsec e s m { - , s ~ Char - } ) = > Double - > m Int coerceFloating = assertNonNegative <=< assertIntegral labeling where assertNonNegative x | x >= 0 = pure x | otherwise = fail $ concat ["The ",labeling," value (",show x,") is a negative value"] improve ParseError generation . > > > parse ( flexiblePositiveInt " errorCount " ) " " " 1\n " > > > parse ( flexiblePositiveInt " errorCount " ) " " " 0\n " > > > parse ( flexiblePositiveInt " errorCount " ) " " " 42.0\n " > > > parse ( flexiblePositiveInt " errorCount " ) " " " 0.1337\n " The errorCount value ( 0.1337 ) is a real value , not an integral value The errorCount value ( 0.1337 ) is not a positive integer flexiblePositiveInt :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> m Int flexiblePositiveInt labeling = either coerceFloating coerceIntegral . floatingOrInteger =<< signed whitespace scientific <?> ("positive integer for " <> labeling) where coerceIntegral x | x <= (0::Int) = fail $ concat ["The ",labeling," value (",show x,") is not a positive number"] | otherwise = pure $ fromEnum x coerceFloating = assertPositive <=< assertIntegral labeling where assertPositive x | x > 0 = pure x | otherwise = fail $ concat ["The ",labeling," value (",show x,") is not a positive integer"] Consumes a TNT keyword flexibly . requiring that _ _ at least _ _ the first @minChars@ of @fullName@ are in the prefix . keyword :: forall e s m. (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => String -> Int -> m () keyword x y = abreviatable x y $> () where abreviatable fullName minimumChars | minimumChars < 1 = fail $ "Nonpositive abbreviation prefix (" <> show minimumChars <> ") supplied to abreviatable combinator" | not $ all isAlpha fullName = fail $ "A keyword containing a non alphabetic character: '" <> show fullName <> "' supplied to abreviateable combinator" | otherwise = combinator <?> "keyword '" <> fullName <> "'" where combinator = choice partialOptions $> fullName partialOptions = makePartial <$> drop minimumChars (inits fullName) makePartial = try . (<* terminator) . string' . tokensToChunk (Proxy :: Proxy s) terminator = lookAhead $ satisfy (not . isAlpha) when expecting one of these chars " .eE " adjacent to the Int value . nonNegInt :: (MonadParsec e s m, Token s ~ Char) => m Int nonNegInt = decimal integral value , then a parse error is raised . The first ' String ' parameter assertIntegral :: MonadFail m => String -> Double -> m Int assertIntegral labeling x | isInt x = pure $ fromEnum rounded | otherwise = fail $ fold [ "The ", labeling, " value (", show x, ") is a real value, not an integral value" ] where isInt n = n == fromInteger rounded rounded = round x characterIndicies :: (MonadParsec e s m, Token s ~ Char) => m CharacterSet characterIndicies = choice $ try <$> [range, fromStart, singleVal, toEnd, whole] where range = Range <$> num <* dot <*> num fromStart = FromStart <$> num <* dot singleVal = Single <$> num toEnd = dot *> (ToEnd <$> num) whole = dot $> Whole num = symbol (nonNegInt <?> "sequence index value") dot = symbol (char '.') Parses one of the valid character states for a TNT file . characterStateChar :: (MonadParsec e s m, Token s ~ Char) => m Char characterStateChar = oneOf (toList discreteStateValues) The only 64 ( case - insensitive ) valid state values for a TNT file . discreteStateValues :: Vector Char discreteStateValues = V.fromList $ fold [['0'..'9'], ['A'..'Z'], ['a'..'z'], "-", "?"] dnaStateValues :: Vector Char dnaStateValues = V.fromList $ keys deserializeStateDna proteinStateValues :: Vector Char proteinStateValues = V.fromList $ keys deserializeStateProtein A map for serializing discrete state chatracters . serializeStateDiscrete :: Map TntDiscreteCharacter Char serializeStateDiscrete = swapMap deserializeStateDiscrete A map for deserializing discrete state chatracters . deserializeStateDiscrete :: Map Char TntDiscreteCharacter deserializeStateDiscrete = force $ insert '?' allBits core where allBits = foldl (.|.) zeroBits core core = M.fromList $ zip (toList discreteStateValues) (bit <$> [0..]) A map for serializing dna state chatracters . serializeStateDna :: Map TntDnaCharacter Char serializeStateDna = swapMap deserializeStateDna A map for deserializing dna state chatracters . deserializeStateDna :: Map Char TntDnaCharacter deserializeStateDna = force . buildFromBimap f $ BM.filter g iupacToDna where f = \case 'A' -> 0 'G' -> 1 'C' -> 2 'T' -> 3 '-' -> 4 _ -> error "Fatal construction error in TNT parser's DNA IUPAC deserializer" g x _ = not . isLower . head $ NE.head x A map for deserializing protein state chatracters . serializeStateProtein :: Map TntProteinCharacter Char serializeStateProtein = swapMap deserializeStateProtein A map for deserializing protein state chatracters . deserializeStateProtein :: Map Char TntProteinCharacter deserializeStateProtein = force $ buildFromBimap f iupacToDna where f = \case 'A' -> 0 'C' -> 1 'D' -> 2 'E' -> 3 'F' -> 4 'G' -> 5 'H' -> 6 'I' -> 7 'K' -> 8 'L' -> 9 'M' -> 10 'N' -> 11 'P' -> 12 'Q' -> 13 'R' -> 14 'S' -> 15 'T' -> 16 'V' -> 17 'W' -> 18 'Y' -> 19 '-' -> 20 _ -> error "Fatal construction error in TNT parser's protein IUPAC deserializer" buildFromBimap :: Bits b => (Char -> Int) -> Bimap (NonEmpty String) (NonEmpty String) -> Map Char b buildFromBimap f = casei . M.fromDistinctAscList . fmap convert . BM.toAscList where convert :: Bits b => (NonEmpty String, NonEmpty String) -> (Char, b) convert (x,y) = (key, val) where key = head $ NE.head x val = foldl (\b -> (b .|.) . bit . f . head) zeroBits y casei :: Map Char v -> Map Char v casei x = foldl f x $ assocs x where f m (k,v) | isLower k = insertWith g (toUpper k) v m | isUpper k = insertWith g (toLower k) v m | otherwise = m bitsToFlags :: FiniteBits b => b -> [b] bitsToFlags b | zeroBits == b = [] | otherwise = bit i : bitsToFlags (b `clearBit` i) where i = findFirstSet b findFirstSet :: FiniteBits b => b -> Int findFirstSet = countTrailingZeros swapMap :: Ord a => Map k a -> Map a k swapMap x = let !tups = assocs x in M.fromList $ swap <$> tups symbol :: (MonadParsec e s m, Token s ~ Char) => m a -> m a symbol c = c <* whitespace trim :: (MonadParsec e s m, Token s ~ Char) => m a -> m a trim c = whitespace *> c <* whitespace Consumes zero or more whitespace characters _ _ including _ _ line breaks . # INLINE whitespace # whitespace :: (MonadParsec e s m, Token s ~ Char) => m () whitespace = space Consumes zero or more whitespace characters that are not line breaks . # INLINE whitespaceInline # whitespaceInline :: (MonadParsec e s m, Token s ~ Char) => m () whitespaceInline = hspace
7601d23b174c08c183b98aa75a41f92e700e20a070db9cc3b0ef1e93d2d7de7b
digikar99/numericals
n-arg-fn-compiler-macros.lisp
(numericals.common:compiler-in-package numericals.common:*compiler-package*) (5am:in-suite nu::array) ;; TODO: Add macros for comparison and bitwise operations (define-condition out-unknown-at-compile-time (compiler-macro-notes:optimization-failure-note) ((args :initarg :args :reader condition-args)) (:report (lambda (c s) (format s "Unable to infer :OUT parameter from argument list~% ~S~%not derived to be numbers" (condition-args c))))) (define-condition bad-position-for-out (compiler-macro-notes:optimization-failure-note) ((args :initarg :args :reader condition-args)) (:report (lambda (c s) (format s "Failed to infer :OUT argument to be the last in the argument list~% ~S" (condition-args c))))) (define-condition arg-out-type-mismatch (compiler-macro-notes:optimization-failure-note) ((arg :initarg :arg :reader condition-arg) (arg-type :initarg :arg-type :reader condition-arg-type) (out :initarg :out :reader condition-out) (out-type :initarg :out-type :reader condition-out-type)) (:report (lambda (c s) (format s "Argument~% ~S~%is derived to be of type~% ~S~%which is different from type~% ~S~%of OUT~%~S" (condition-arg c) (condition-arg-type c) (condition-out-type c) (condition-out c))))) (define-condition arg-is-not-array (compiler-macro-notes:optimization-failure-note) ((arg :initarg :arg :reader condition-arg) (arg-type :initarg :arg-type :reader condition-arg-type)) (:report (lambda (c s) (format s "Expected argument~% ~S~%to be an array but it was derived to be a~% ~S" (condition-arg c) (condition-arg-type c))))) (define-condition array-type-is-unoptimized (compiler-macro-notes:optimization-failure-note) ((type :initarg :type :reader condition-type)) (:report (lambda (c s) (format s "NUMERICALS is only optimized for arrays with element types~% ~S~%and not: ~S" nu:+optimized-types+ (condition-type c))))) ;;; TODO: Handle BROADCAST option (macrolet ((def (name reduce-fn initial-value &optional returns-identity) `(define-compiler-macro ,name (&whole form &rest args &environment env) (compiler-macro-notes:with-notes (form env :optimization-note-condition optim-speed) ;; 0. Abort optimization if not asked to do so; to help debug better (unless optim-speed (return-from ,name form)) (let* ((arg-types (loop :for arg :in args :collect (cl-form-types:nth-form-type arg env 0 t t))) (out-pos (loop :for arg :in args :for arg-type :in arg-types :for i :from 0 :if (subtypep arg-type '(eql :out)) :do (return (1+ i)) 1 . Optimization is insignificant if OUT is unsupplied :finally (cond ((every (lm type (subtypep type 'number)) arg-types) (return-from ,name `(,',(swank/backend:function-name (cl-name reduce-fn)) ,@args))) ,@(if returns-identity `(((= 1 (length arg-types)) (return-from ,name (first args))))) ((= 2 (length arg-types)) (return-from ,name `(,',reduce-fn ,@args))) (t (signal 'out-unknown-at-compile-time :args args)))))) 2 . We do n't want to not detect bad cases (unless (null (nthcdr (1+ out-pos) args)) (signal 'bad-position-for-out :args args)) (let ((out-arg (nth out-pos args)) (out-type (nth out-pos arg-types)) (array-likes (subseq args 0 (1- out-pos))) (array-types (subseq arg-types 0 (1- out-pos)))) 3 . OUT is supplied and is at the right place , but the array - likes are either not arrays or not of types TYPE= to OUT (unless (subtypep out-type 'array) (signal 'arg-is-not-array :arg out-arg :arg-type out-type)) (mapc (lambda (array-like array-type) (unless (subtypep array-type 'array) (signal 'arg-is-not-array :arg array-like :arg-type array-type)) (unless (type= array-type out-type) (signal 'arg-out-type-mismatch :arg array-like :arg-type array-type :out out-arg :out-type out-type))) array-likes array-types) 4 . Everything else is good ; check for broadcast once , to avoid " wasting time " later (with-gensyms (out-sym broadcast-compatible-p dimensions) (let* ((array-like-syms (make-gensym-list (length array-likes) "ARRAY-LIKE")) (element-type (array-type-element-type out-type)) (main-code (cond ((null array-like-syms) `(,',reduce-fn (the ,element-type (coerce ,,initial-value ',element-type)) ,out-sym :out ,out-sym)) ((null (rest array-like-syms)) `(,',reduce-fn (the ,element-type (coerce ,,initial-value ',element-type)) ,(first array-like-syms) :out ,out-sym)) (t `(progn (,',reduce-fn ,(first array-like-syms) ,(second array-like-syms) :out ,out-sym) ,@(mapcar (lm sym `(,',reduce-fn ,out-sym ,sym :out ,out-sym)) (cddr array-like-syms))))))) (unless (member element-type nu:+optimized-types+ :test (lambda (a b) (and #+extensible-compound-types (and (extensible-compound-types:type-specifier-p a) (extensible-compound-types:type-specifier-p b)) #-extensible-compound-types (and (trivial-types:type-specifier-p a) (trivial-types:type-specifier-p b)) (not (eq a 'cl:*)) (not (eq b 'cl:*)) (type= a b)))) (signal 'array-type-is-unoptimized :type element-type)) ;; FIXME: Mysterious consing `(the ,out-type (let* (,@(mapcar (lm sym array-like `(,sym ,array-like)) array-like-syms array-likes) (,out-sym ,out-arg) (,dimensions (narray-dimensions ,out-sym))) (declare (type (array ,element-type) ,@array-like-syms ,out-sym) (ignorable ,dimensions)) (if (and ,@(mapcar (lm sym `(equal ,dimensions (narray-dimensions ,sym))) array-like-syms)) (locally ;; (declare (optimize (safety 0))) ,main-code) (multiple-value-bind (,broadcast-compatible-p ,dimensions) (broadcast-compatible-p ,out-sym ,@array-like-syms) (declare (ignorable ,dimensions)) (if ,broadcast-compatible-p (locally (declare (type (array ,element-type) ,@array-like-syms ,out-sym) ;; (optimize (safety 0)) ) ,main-code) (error 'incompatible-broadcast-dimensions :array-likes (list ,@array-like-syms ,out-sym) :dimensions (mapcar #'narray-dimensions (list ,@array-like-syms)))))) ,out-sym)))))))))) (def nu:+ nu:add 0 t) (def nu:- nu:subtract 0) (def nu:* nu:multiply 1 t) (def nu:/ nu:divide 1))
null
https://raw.githubusercontent.com/digikar99/numericals/34601bc63f02774c012ed4949f87baf7e63661ff/src/n-arg-fn-compiler-macros.lisp
lisp
TODO: Add macros for comparison and bitwise operations TODO: Handle BROADCAST option 0. Abort optimization if not asked to do so; to help debug better check for broadcast once , to avoid " wasting time " later FIXME: Mysterious consing (declare (optimize (safety 0))) (optimize (safety 0))
(numericals.common:compiler-in-package numericals.common:*compiler-package*) (5am:in-suite nu::array) (define-condition out-unknown-at-compile-time (compiler-macro-notes:optimization-failure-note) ((args :initarg :args :reader condition-args)) (:report (lambda (c s) (format s "Unable to infer :OUT parameter from argument list~% ~S~%not derived to be numbers" (condition-args c))))) (define-condition bad-position-for-out (compiler-macro-notes:optimization-failure-note) ((args :initarg :args :reader condition-args)) (:report (lambda (c s) (format s "Failed to infer :OUT argument to be the last in the argument list~% ~S" (condition-args c))))) (define-condition arg-out-type-mismatch (compiler-macro-notes:optimization-failure-note) ((arg :initarg :arg :reader condition-arg) (arg-type :initarg :arg-type :reader condition-arg-type) (out :initarg :out :reader condition-out) (out-type :initarg :out-type :reader condition-out-type)) (:report (lambda (c s) (format s "Argument~% ~S~%is derived to be of type~% ~S~%which is different from type~% ~S~%of OUT~%~S" (condition-arg c) (condition-arg-type c) (condition-out-type c) (condition-out c))))) (define-condition arg-is-not-array (compiler-macro-notes:optimization-failure-note) ((arg :initarg :arg :reader condition-arg) (arg-type :initarg :arg-type :reader condition-arg-type)) (:report (lambda (c s) (format s "Expected argument~% ~S~%to be an array but it was derived to be a~% ~S" (condition-arg c) (condition-arg-type c))))) (define-condition array-type-is-unoptimized (compiler-macro-notes:optimization-failure-note) ((type :initarg :type :reader condition-type)) (:report (lambda (c s) (format s "NUMERICALS is only optimized for arrays with element types~% ~S~%and not: ~S" nu:+optimized-types+ (condition-type c))))) (macrolet ((def (name reduce-fn initial-value &optional returns-identity) `(define-compiler-macro ,name (&whole form &rest args &environment env) (compiler-macro-notes:with-notes (form env :optimization-note-condition optim-speed) (unless optim-speed (return-from ,name form)) (let* ((arg-types (loop :for arg :in args :collect (cl-form-types:nth-form-type arg env 0 t t))) (out-pos (loop :for arg :in args :for arg-type :in arg-types :for i :from 0 :if (subtypep arg-type '(eql :out)) :do (return (1+ i)) 1 . Optimization is insignificant if OUT is unsupplied :finally (cond ((every (lm type (subtypep type 'number)) arg-types) (return-from ,name `(,',(swank/backend:function-name (cl-name reduce-fn)) ,@args))) ,@(if returns-identity `(((= 1 (length arg-types)) (return-from ,name (first args))))) ((= 2 (length arg-types)) (return-from ,name `(,',reduce-fn ,@args))) (t (signal 'out-unknown-at-compile-time :args args)))))) 2 . We do n't want to not detect bad cases (unless (null (nthcdr (1+ out-pos) args)) (signal 'bad-position-for-out :args args)) (let ((out-arg (nth out-pos args)) (out-type (nth out-pos arg-types)) (array-likes (subseq args 0 (1- out-pos))) (array-types (subseq arg-types 0 (1- out-pos)))) 3 . OUT is supplied and is at the right place , but the array - likes are either not arrays or not of types TYPE= to OUT (unless (subtypep out-type 'array) (signal 'arg-is-not-array :arg out-arg :arg-type out-type)) (mapc (lambda (array-like array-type) (unless (subtypep array-type 'array) (signal 'arg-is-not-array :arg array-like :arg-type array-type)) (unless (type= array-type out-type) (signal 'arg-out-type-mismatch :arg array-like :arg-type array-type :out out-arg :out-type out-type))) array-likes array-types) (with-gensyms (out-sym broadcast-compatible-p dimensions) (let* ((array-like-syms (make-gensym-list (length array-likes) "ARRAY-LIKE")) (element-type (array-type-element-type out-type)) (main-code (cond ((null array-like-syms) `(,',reduce-fn (the ,element-type (coerce ,,initial-value ',element-type)) ,out-sym :out ,out-sym)) ((null (rest array-like-syms)) `(,',reduce-fn (the ,element-type (coerce ,,initial-value ',element-type)) ,(first array-like-syms) :out ,out-sym)) (t `(progn (,',reduce-fn ,(first array-like-syms) ,(second array-like-syms) :out ,out-sym) ,@(mapcar (lm sym `(,',reduce-fn ,out-sym ,sym :out ,out-sym)) (cddr array-like-syms))))))) (unless (member element-type nu:+optimized-types+ :test (lambda (a b) (and #+extensible-compound-types (and (extensible-compound-types:type-specifier-p a) (extensible-compound-types:type-specifier-p b)) #-extensible-compound-types (and (trivial-types:type-specifier-p a) (trivial-types:type-specifier-p b)) (not (eq a 'cl:*)) (not (eq b 'cl:*)) (type= a b)))) (signal 'array-type-is-unoptimized :type element-type)) `(the ,out-type (let* (,@(mapcar (lm sym array-like `(,sym ,array-like)) array-like-syms array-likes) (,out-sym ,out-arg) (,dimensions (narray-dimensions ,out-sym))) (declare (type (array ,element-type) ,@array-like-syms ,out-sym) (ignorable ,dimensions)) (if (and ,@(mapcar (lm sym `(equal ,dimensions (narray-dimensions ,sym))) array-like-syms)) ,main-code) (multiple-value-bind (,broadcast-compatible-p ,dimensions) (broadcast-compatible-p ,out-sym ,@array-like-syms) (declare (ignorable ,dimensions)) (if ,broadcast-compatible-p (locally (declare (type (array ,element-type) ,@array-like-syms ,out-sym) ) ,main-code) (error 'incompatible-broadcast-dimensions :array-likes (list ,@array-like-syms ,out-sym) :dimensions (mapcar #'narray-dimensions (list ,@array-like-syms)))))) ,out-sym)))))))))) (def nu:+ nu:add 0 t) (def nu:- nu:subtract 0) (def nu:* nu:multiply 1 t) (def nu:/ nu:divide 1))
708158e459f72e15f7f909ee69af6ddcfdb746d8646646b15546aa7080a41740
genmeblog/genuary
day01.clj
Draw 10,000 of something . (ns genuary.2022.day01 (:require [clojure2d.core :as c2d] [clojure2d.extra.utils :as utils] [fastmath.core :as m] [fastmath.random :as r] [clojure2d.color :as c])) (defn iterator [x curr] (+ 4.0 curr (* 18.0 (r/noise x (/ curr 5.0))))) (def p (c/palette 88)) (c2d/with-canvas [c (c2d/canvas 1400 900 :highest)] (c2d/set-background c [10 20 30]) (c2d/set-stroke c 5.0) (c2d/set-color c (p 0) 220) (c2d/translate c 30 50) (doseq [y (m/slice-range 0.0 4.0 100) [xx yy] (->> (* y 7.0) (r/noise) (* 50.0) (iterate (partial iterator y)) (partition 2 1) (take 100)) :let [ny (* y 200)]] (cond (< (r/drand) 0.01) (c2d/set-color c (p 1) 220) (< (r/drand) 0.02) (c2d/set-color c (p 2) 220) (< (r/drand) 0.03) (c2d/set-color c (p 3) 220) (< (r/drand) 0.02) (c2d/set-color c (p 4) 220) (< (r/drand) 0.3) (c2d/set-color c (p 0) 220)) (c2d/line c xx (+ (* 20.0 (- (r/noise y (/ xx 20.0)) 0.5)) ny) (- yy 7) (+ (* 20.0 (- (r/vnoise y (/ xx 20.0)) 0.5)) ny))) ;; (c2d/save c "results/2022/day01.jpg") (utils/show-image c))
null
https://raw.githubusercontent.com/genmeblog/genuary/effe2cd784a38a688a58edf703b3acc1900d1805/src/genuary/2022/day01.clj
clojure
(c2d/save c "results/2022/day01.jpg")
Draw 10,000 of something . (ns genuary.2022.day01 (:require [clojure2d.core :as c2d] [clojure2d.extra.utils :as utils] [fastmath.core :as m] [fastmath.random :as r] [clojure2d.color :as c])) (defn iterator [x curr] (+ 4.0 curr (* 18.0 (r/noise x (/ curr 5.0))))) (def p (c/palette 88)) (c2d/with-canvas [c (c2d/canvas 1400 900 :highest)] (c2d/set-background c [10 20 30]) (c2d/set-stroke c 5.0) (c2d/set-color c (p 0) 220) (c2d/translate c 30 50) (doseq [y (m/slice-range 0.0 4.0 100) [xx yy] (->> (* y 7.0) (r/noise) (* 50.0) (iterate (partial iterator y)) (partition 2 1) (take 100)) :let [ny (* y 200)]] (cond (< (r/drand) 0.01) (c2d/set-color c (p 1) 220) (< (r/drand) 0.02) (c2d/set-color c (p 2) 220) (< (r/drand) 0.03) (c2d/set-color c (p 3) 220) (< (r/drand) 0.02) (c2d/set-color c (p 4) 220) (< (r/drand) 0.3) (c2d/set-color c (p 0) 220)) (c2d/line c xx (+ (* 20.0 (- (r/noise y (/ xx 20.0)) 0.5)) ny) (- yy 7) (+ (* 20.0 (- (r/vnoise y (/ xx 20.0)) 0.5)) ny))) (utils/show-image c))
81315560a8832d4484d6bbad407e77b2e961d75bd9a3b2537e2b2959585faf97
rrnewton/haskell-lockfree
Fetch.hs
module Fetch (tests) where -- tests for our fetch-and-* family of functions. import Control.Monad import System.Random import Test.Framework.Providers.HUnit (testCase) import Test.Framework (Test) import Test.HUnit (assertEqual,assertBool) import Data.Primitive import Data.List import Data.Bits import Data.Atomics import Control.Monad.Primitive import Control.Concurrent tests :: [Test] tests = [ testCase "Fetch-and-* operations return previous value" case_return_previous , testCase "Fetch-and-* operations behave like their corresponding bitwise operators" case_like_bitwise , testCase "fetchAndIntArray and fetchOrIntArray are atomic" $ fetchAndOrTest 10000000 , testCase "fetchNandIntArray atomic" $ fetchNandTest 1000000 , testCase "fetchAddIntArray and fetchSubIntArray are atomic" $ fetchAddSubTest 10000000 , testCase "fetchXorIntArray is atomic" $ fetchXorTest 10000000 ] nand :: Bits a => a -> a -> a nand x y = complement (x .&. y) fetchOps :: [( String , MutableByteArray RealWorld -> Int -> Int -> IO Int , Int -> Int -> Int )] fetchOps = [ ("Add", fetchAddIntArray, (+)), ("Sub", fetchSubIntArray, (-)), ("And", fetchAndIntArray, (.&.)), ("Nand", fetchNandIntArray, nand), ("Or", fetchOrIntArray, (.|.)), ("Xor", fetchXorIntArray, xor) ] -- Test all operations at once, somewhat randomly, ensuring they behave like -- their corresponding bitwise operator; we compose a few operations before -- inspecting the intermediate result, and spread them randomly around a small -- array. TODO use quickcheck if we want case_like_bitwise :: IO () case_like_bitwise = do let opGroupSize = 5 let grp n = go n [] where go _ stck [] = [stck] go 0 stck xs = stck : go n [] xs go i stck (x:xs) = go (i-1) (x:stck) xs -- Inf list of different short sequences of bitwise operations: let opGroups = grp opGroupSize $ cycle $ concat $ permutations fetchOps let size = 4 randIxs <- randomRs (0, size-1) <$> newStdGen randArgs <- grp opGroupSize . randoms <$> newStdGen a <- newByteArray (sizeOf (undefined::Int) * size) forM_ [0.. size-1] $ \ix-> writeByteArray a ix (0::Int) forM_ (take 1000000 $ zip randIxs $ zipWith zip opGroups randArgs) $ \ (ix, opsArgs)-> do assertEqual "test not b0rken" (length opsArgs) opGroupSize let doOpGroups pureLHS [] = return pureLHS doOpGroups pureLHS (((_,atomicOp,op), v) : rest) = do atomicOp a ix v >> doOpGroups (pureLHS `op` v) rest vInitial <- readByteArray a ix vFinalPure <- doOpGroups vInitial opsArgs vFinal <- readByteArray a ix let nmsArgs = map (\ ((nm,_,_),v) -> (nm,v)) opsArgs assertEqual ("sequence on initial value "++(show vInitial) ++" of ops with RHS args: "++(show nmsArgs) ++" gives same result in both pure and atomic op" ) vFinal vFinalPure -- check all operations return the value before the operation was applied; -- basic smoke test, with each op tested individually. case_return_previous :: IO () case_return_previous = do let l = length fetchOps a <- newByteArray (sizeOf (undefined::Int) * l) let randomInts = take l . randoms <$> newStdGen :: IO [Int] initial <- randomInts forM_ (zip [0..] initial) $ \(ix, v)-> writeByteArray a ix v args <- randomInts forM_ (zip4 [0..] initial args fetchOps) $ \(ix, pre, v, (nm,atomicOp,op))-> do pre' <- atomicOp a ix v assertEqual (fetchStr nm "returned previous value") pre pre' let post = pre `op` v post' <- readByteArray a ix assertEqual (fetchStrArgVal nm v pre "operation was seen correctly on read") post post' fetchStr :: String -> String -> String fetchStr nm = (("fetch"++nm++"IntArray: ")++) fetchStrArgVal :: (Show a, Show a1) => String -> a -> a1 -> String -> String fetchStrArgVal nm v initial = (("fetch"++nm++"IntArray, with arg "++(show v)++" on value "++(show initial)++": ")++) -- ---------------------------------------------------------------------------- -- Tests of atomicity: -- Concurrently run a sequence of AND and OR simultaneously on separate parts -- of the bit range of an Int. fetchAndOrTest :: Int -> IO () fetchAndOrTest iters = do out0 <- newEmptyMVar out1 <- newEmptyMVar mba <- newByteArray (sizeOf (undefined :: Int)) let andLowersBit , orRaisesBit :: Int -> Int andLowersBit = clearBit (complement 0) orRaisesBit = setBit 0 writeByteArray mba 0 (0 :: Int) thread 1 toggles bit 0 , thread 2 toggles bit 1 ; then we verify results -- in the main thread. let go v b = do Avoid stack overflow on GHC 7.6 : let replicateMrev l 0 = putMVar v l replicateMrev l iter = do low <- fetchOrIntArray mba 0 (orRaisesBit b) high <- fetchAndIntArray mba 0 (andLowersBit b) replicateMrev ((low,high):l) (iter-1) in replicateMrev [] iters void $ forkIO $ go out0 0 void $ forkIO $ go out1 1 res0 <- takeMVar out0 res1 <- takeMVar out1 let check b = all ( \(low,high)-> (not $ testBit low b) && testBit high b) assertBool "fetchAndOrTest not broken" $ length (res0++res1) == iters*2 assertBool "fetchAndOrTest thread1" $ check 0 res0 assertBool "fetchAndOrTest thread2" $ check 1 res1 Nand of 1 is a bit complement . Concurrently run two threads running an even -- number of complements in this way and verify the final value is unchanged. -- TODO think of a more clever test fetchNandTest :: Int -> IO () fetchNandTest iters = do let nandComplements = complement 0 dblComplement mba = replicateM_ (2 * iters) $ fetchNandIntArray mba 0 nandComplements randomInts <- take 10 . randoms <$> newStdGen :: IO [Int] forM_ randomInts $ \ initial -> do final <- race initial dblComplement dblComplement assertEqual "fetchNandTest" initial final -- ---------------------------------------------------------------------------- Code below copied with minor modifications from GHC -- testsuite/tests/concurrent/should_run/AtomicPrimops.hs @ f293931 -- ---------------------------------------------------------------------------- | Test fetchAddIntArray # by having two threads concurrenctly -- increment a counter and then checking the sum at the end. fetchAddSubTest :: Int -> IO () fetchAddSubTest iters = do tot <- race 0 (\ mba -> work fetchAddIntArray mba iters 2) (\ mba -> work fetchSubIntArray mba iters 1) assertEqual "fetchAddSubTest" iters tot where work :: (MutableByteArray RealWorld -> Int -> Int -> IO Int) -> MutableByteArray RealWorld -> Int -> Int -> IO () work _ _ 0 _ = return () work op mba n val = op mba 0 val >> work op mba (n-1) val | Test fetchXorIntArray # by having two threads concurrenctly XORing -- and then checking the result at the end. Works since XOR is -- commutative. -- -- Covers the code paths for AND, NAND, and OR as well. fetchXorTest :: Int -> IO () fetchXorTest iters = do res <- race n0 (\ mba -> work mba iters t1pat) (\ mba -> work mba iters t2pat) assertEqual "fetchXorTest" expected res where work :: MutableByteArray RealWorld -> Int -> Int -> IO () work _ 0 _ = return () work mba n val = fetchXorIntArray mba 0 val >> work mba (n-1) val Initial value is a large prime and the two patterns are 1010 ... and 0101 ... (n0, t1pat, t2pat) TODO : If we want to silence warnings from here , use CPP conditional -- on arch x86_64 | sizeOf (undefined :: Int) == 8 = (0x00000000ffffffff, 0x5555555555555555, 0x9999999999999999) | otherwise = (0x0000ffff, 0x55555555, 0x99999999) expected | sizeOf (undefined :: Int) == 8 = 4294967295 | otherwise = 65535 | Create two threads that mutate the byte array passed to them -- concurrently. The array is one word large. race :: Int -- ^ Initial value of array element ^ Thread 1 action ^ Thread 2 action -> IO Int -- ^ Final value of array element race n0 thread1 thread2 = do done1 <- newEmptyMVar done2 <- newEmptyMVar mba <- newByteArray (sizeOf (undefined :: Int)) writeByteArray mba 0 n0 void $ forkIO $ thread1 mba >> putMVar done1 () void $ forkIO $ thread2 mba >> putMVar done2 () mapM_ takeMVar [done1, done2] readByteArray mba 0
null
https://raw.githubusercontent.com/rrnewton/haskell-lockfree/87122157cbbc96954fcc575b4b110003d3e5c2f8/atomic-primops/testing/Fetch.hs
haskell
tests for our fetch-and-* family of functions. Test all operations at once, somewhat randomly, ensuring they behave like their corresponding bitwise operator; we compose a few operations before inspecting the intermediate result, and spread them randomly around a small array. Inf list of different short sequences of bitwise operations: check all operations return the value before the operation was applied; basic smoke test, with each op tested individually. ---------------------------------------------------------------------------- Tests of atomicity: Concurrently run a sequence of AND and OR simultaneously on separate parts of the bit range of an Int. in the main thread. number of complements in this way and verify the final value is unchanged. TODO think of a more clever test ---------------------------------------------------------------------------- testsuite/tests/concurrent/should_run/AtomicPrimops.hs @ f293931 ---------------------------------------------------------------------------- increment a counter and then checking the sum at the end. and then checking the result at the end. Works since XOR is commutative. Covers the code paths for AND, NAND, and OR as well. on arch x86_64 concurrently. The array is one word large. ^ Initial value of array element ^ Final value of array element
module Fetch (tests) where import Control.Monad import System.Random import Test.Framework.Providers.HUnit (testCase) import Test.Framework (Test) import Test.HUnit (assertEqual,assertBool) import Data.Primitive import Data.List import Data.Bits import Data.Atomics import Control.Monad.Primitive import Control.Concurrent tests :: [Test] tests = [ testCase "Fetch-and-* operations return previous value" case_return_previous , testCase "Fetch-and-* operations behave like their corresponding bitwise operators" case_like_bitwise , testCase "fetchAndIntArray and fetchOrIntArray are atomic" $ fetchAndOrTest 10000000 , testCase "fetchNandIntArray atomic" $ fetchNandTest 1000000 , testCase "fetchAddIntArray and fetchSubIntArray are atomic" $ fetchAddSubTest 10000000 , testCase "fetchXorIntArray is atomic" $ fetchXorTest 10000000 ] nand :: Bits a => a -> a -> a nand x y = complement (x .&. y) fetchOps :: [( String , MutableByteArray RealWorld -> Int -> Int -> IO Int , Int -> Int -> Int )] fetchOps = [ ("Add", fetchAddIntArray, (+)), ("Sub", fetchSubIntArray, (-)), ("And", fetchAndIntArray, (.&.)), ("Nand", fetchNandIntArray, nand), ("Or", fetchOrIntArray, (.|.)), ("Xor", fetchXorIntArray, xor) ] TODO use quickcheck if we want case_like_bitwise :: IO () case_like_bitwise = do let opGroupSize = 5 let grp n = go n [] where go _ stck [] = [stck] go 0 stck xs = stck : go n [] xs go i stck (x:xs) = go (i-1) (x:stck) xs let opGroups = grp opGroupSize $ cycle $ concat $ permutations fetchOps let size = 4 randIxs <- randomRs (0, size-1) <$> newStdGen randArgs <- grp opGroupSize . randoms <$> newStdGen a <- newByteArray (sizeOf (undefined::Int) * size) forM_ [0.. size-1] $ \ix-> writeByteArray a ix (0::Int) forM_ (take 1000000 $ zip randIxs $ zipWith zip opGroups randArgs) $ \ (ix, opsArgs)-> do assertEqual "test not b0rken" (length opsArgs) opGroupSize let doOpGroups pureLHS [] = return pureLHS doOpGroups pureLHS (((_,atomicOp,op), v) : rest) = do atomicOp a ix v >> doOpGroups (pureLHS `op` v) rest vInitial <- readByteArray a ix vFinalPure <- doOpGroups vInitial opsArgs vFinal <- readByteArray a ix let nmsArgs = map (\ ((nm,_,_),v) -> (nm,v)) opsArgs assertEqual ("sequence on initial value "++(show vInitial) ++" of ops with RHS args: "++(show nmsArgs) ++" gives same result in both pure and atomic op" ) vFinal vFinalPure case_return_previous :: IO () case_return_previous = do let l = length fetchOps a <- newByteArray (sizeOf (undefined::Int) * l) let randomInts = take l . randoms <$> newStdGen :: IO [Int] initial <- randomInts forM_ (zip [0..] initial) $ \(ix, v)-> writeByteArray a ix v args <- randomInts forM_ (zip4 [0..] initial args fetchOps) $ \(ix, pre, v, (nm,atomicOp,op))-> do pre' <- atomicOp a ix v assertEqual (fetchStr nm "returned previous value") pre pre' let post = pre `op` v post' <- readByteArray a ix assertEqual (fetchStrArgVal nm v pre "operation was seen correctly on read") post post' fetchStr :: String -> String -> String fetchStr nm = (("fetch"++nm++"IntArray: ")++) fetchStrArgVal :: (Show a, Show a1) => String -> a -> a1 -> String -> String fetchStrArgVal nm v initial = (("fetch"++nm++"IntArray, with arg "++(show v)++" on value "++(show initial)++": ")++) fetchAndOrTest :: Int -> IO () fetchAndOrTest iters = do out0 <- newEmptyMVar out1 <- newEmptyMVar mba <- newByteArray (sizeOf (undefined :: Int)) let andLowersBit , orRaisesBit :: Int -> Int andLowersBit = clearBit (complement 0) orRaisesBit = setBit 0 writeByteArray mba 0 (0 :: Int) thread 1 toggles bit 0 , thread 2 toggles bit 1 ; then we verify results let go v b = do Avoid stack overflow on GHC 7.6 : let replicateMrev l 0 = putMVar v l replicateMrev l iter = do low <- fetchOrIntArray mba 0 (orRaisesBit b) high <- fetchAndIntArray mba 0 (andLowersBit b) replicateMrev ((low,high):l) (iter-1) in replicateMrev [] iters void $ forkIO $ go out0 0 void $ forkIO $ go out1 1 res0 <- takeMVar out0 res1 <- takeMVar out1 let check b = all ( \(low,high)-> (not $ testBit low b) && testBit high b) assertBool "fetchAndOrTest not broken" $ length (res0++res1) == iters*2 assertBool "fetchAndOrTest thread1" $ check 0 res0 assertBool "fetchAndOrTest thread2" $ check 1 res1 Nand of 1 is a bit complement . Concurrently run two threads running an even fetchNandTest :: Int -> IO () fetchNandTest iters = do let nandComplements = complement 0 dblComplement mba = replicateM_ (2 * iters) $ fetchNandIntArray mba 0 nandComplements randomInts <- take 10 . randoms <$> newStdGen :: IO [Int] forM_ randomInts $ \ initial -> do final <- race initial dblComplement dblComplement assertEqual "fetchNandTest" initial final Code below copied with minor modifications from GHC | Test fetchAddIntArray # by having two threads concurrenctly fetchAddSubTest :: Int -> IO () fetchAddSubTest iters = do tot <- race 0 (\ mba -> work fetchAddIntArray mba iters 2) (\ mba -> work fetchSubIntArray mba iters 1) assertEqual "fetchAddSubTest" iters tot where work :: (MutableByteArray RealWorld -> Int -> Int -> IO Int) -> MutableByteArray RealWorld -> Int -> Int -> IO () work _ _ 0 _ = return () work op mba n val = op mba 0 val >> work op mba (n-1) val | Test fetchXorIntArray # by having two threads concurrenctly XORing fetchXorTest :: Int -> IO () fetchXorTest iters = do res <- race n0 (\ mba -> work mba iters t1pat) (\ mba -> work mba iters t2pat) assertEqual "fetchXorTest" expected res where work :: MutableByteArray RealWorld -> Int -> Int -> IO () work _ 0 _ = return () work mba n val = fetchXorIntArray mba 0 val >> work mba (n-1) val Initial value is a large prime and the two patterns are 1010 ... and 0101 ... (n0, t1pat, t2pat) TODO : If we want to silence warnings from here , use CPP conditional | sizeOf (undefined :: Int) == 8 = (0x00000000ffffffff, 0x5555555555555555, 0x9999999999999999) | otherwise = (0x0000ffff, 0x55555555, 0x99999999) expected | sizeOf (undefined :: Int) == 8 = 4294967295 | otherwise = 65535 | Create two threads that mutate the byte array passed to them ^ Thread 1 action ^ Thread 2 action race n0 thread1 thread2 = do done1 <- newEmptyMVar done2 <- newEmptyMVar mba <- newByteArray (sizeOf (undefined :: Int)) writeByteArray mba 0 n0 void $ forkIO $ thread1 mba >> putMVar done1 () void $ forkIO $ thread2 mba >> putMVar done2 () mapM_ takeMVar [done1, done2] readByteArray mba 0
0d2cc2ecc2887b90e49c0e7e357a56d2db65ccd8530367593cc28dbe2d9b99cc
roburio/udns
dns_client_lwt.ml
{ ! } provides the implementation of the underlying flow that is in turn used by { ! Dns_client_flow . Make } to provide the Lwt convenience module that is in turn used by {!Dns_client_flow.Make} to provide the Lwt convenience module *) open Lwt.Infix module Uflow : Dns_client_flow.S with type flow = Lwt_unix.file_descr and type io_addr = Lwt_unix.inet_addr * int and type (+'a,+'b) io = ('a,'b) Lwt_result.t and type stack = unit = struct type io_addr = Lwt_unix.inet_addr * int type flow = Lwt_unix.file_descr type ns_addr = [`TCP | `UDP] * io_addr type (+'a,+'b) io = ('a,'b) Lwt_result.t constraint 'b = [> `Msg of string] type stack = unit type t = { nameserver : ns_addr } let create ?(nameserver = `TCP, (Unix.inet_addr_of_string "91.239.100.100", 53)) () = { nameserver } let nameserver { nameserver } = nameserver let send socket tx = let open Lwt in Lwt_unix.send socket (Cstruct.to_bytes tx) 0 (Cstruct.len tx) [] >>= fun res -> if res <> Cstruct.len tx then Lwt_result.fail (`Msg ("oops" ^ (string_of_int res))) else Lwt_result.return () let recv socket = let open Lwt in let recv_buffer = Bytes.make 2048 '\000' in Lwt_unix.recv socket recv_buffer 0 (Bytes.length recv_buffer) [] >>= fun read_len -> let open Lwt_result in (if read_len > 0 then Lwt_result.return () else Lwt_result.fail (`Msg "Empty response")) >|= fun () -> (Cstruct.of_bytes ~len:read_len recv_buffer) let map = Lwt_result.bind let resolve = Lwt_result.bind_result let lift = Lwt_result.lift let connect ?nameserver:ns t = let (proto, (server, port)) = match ns with None -> nameserver t | Some x -> x in begin match proto with | `UDP -> Lwt_unix.((getprotobyname "udp") >|= fun x -> x.p_proto, SOCK_DGRAM) | `TCP -> Lwt_unix.((getprotobyname "tcp") >|= fun x -> x.p_proto, SOCK_STREAM) end >>= fun (proto_number, socket_type) -> let socket = Lwt_unix.socket PF_INET socket_type proto_number in let addr = Lwt_unix.ADDR_INET (server, port) in Lwt_unix.connect socket addr >|= fun () -> Ok socket end Now that we have our { ! } implementation we can include the logic that goes on top of it : that goes on top of it: *) include Dns_client_flow.Make(Uflow)
null
https://raw.githubusercontent.com/roburio/udns/585c40933ac3d5eceb351f7edd3f45cf2615a9f8/lwt/client/dns_client_lwt.ml
ocaml
{ ! } provides the implementation of the underlying flow that is in turn used by { ! Dns_client_flow . Make } to provide the Lwt convenience module that is in turn used by {!Dns_client_flow.Make} to provide the Lwt convenience module *) open Lwt.Infix module Uflow : Dns_client_flow.S with type flow = Lwt_unix.file_descr and type io_addr = Lwt_unix.inet_addr * int and type (+'a,+'b) io = ('a,'b) Lwt_result.t and type stack = unit = struct type io_addr = Lwt_unix.inet_addr * int type flow = Lwt_unix.file_descr type ns_addr = [`TCP | `UDP] * io_addr type (+'a,+'b) io = ('a,'b) Lwt_result.t constraint 'b = [> `Msg of string] type stack = unit type t = { nameserver : ns_addr } let create ?(nameserver = `TCP, (Unix.inet_addr_of_string "91.239.100.100", 53)) () = { nameserver } let nameserver { nameserver } = nameserver let send socket tx = let open Lwt in Lwt_unix.send socket (Cstruct.to_bytes tx) 0 (Cstruct.len tx) [] >>= fun res -> if res <> Cstruct.len tx then Lwt_result.fail (`Msg ("oops" ^ (string_of_int res))) else Lwt_result.return () let recv socket = let open Lwt in let recv_buffer = Bytes.make 2048 '\000' in Lwt_unix.recv socket recv_buffer 0 (Bytes.length recv_buffer) [] >>= fun read_len -> let open Lwt_result in (if read_len > 0 then Lwt_result.return () else Lwt_result.fail (`Msg "Empty response")) >|= fun () -> (Cstruct.of_bytes ~len:read_len recv_buffer) let map = Lwt_result.bind let resolve = Lwt_result.bind_result let lift = Lwt_result.lift let connect ?nameserver:ns t = let (proto, (server, port)) = match ns with None -> nameserver t | Some x -> x in begin match proto with | `UDP -> Lwt_unix.((getprotobyname "udp") >|= fun x -> x.p_proto, SOCK_DGRAM) | `TCP -> Lwt_unix.((getprotobyname "tcp") >|= fun x -> x.p_proto, SOCK_STREAM) end >>= fun (proto_number, socket_type) -> let socket = Lwt_unix.socket PF_INET socket_type proto_number in let addr = Lwt_unix.ADDR_INET (server, port) in Lwt_unix.connect socket addr >|= fun () -> Ok socket end Now that we have our { ! } implementation we can include the logic that goes on top of it : that goes on top of it: *) include Dns_client_flow.Make(Uflow)
786bfbb4a21d30c124e707e033ba1d52f84cb320ecee826e7a697d456e737078
racket/scribble
xref.rkt
#lang racket/base (require scribble/xref racket/fasl setup/dirs tests/eli-tester) FIXME : need to look for out < i>.sxref files (provide xref-tests) (module+ main (xref-tests)) (define (xref-tests) (define sxref (build-path (find-doc-dir) "reference" "out.sxref")) (when (file-exists? sxref) (define xref (load-xref (list (λ () (cadr (call-with-input-file* sxref fasl->s-exp)))))) (test (xref-binding->definition-tag xref (list '(lib "contract.rkt" "racket") '->) #f) => '(form ((lib "racket/contract/base.rkt") ->)))))
null
https://raw.githubusercontent.com/racket/scribble/beb2d9834169665121d34b5f3195ddf252c3c998/scribble-test/tests/scribble/xref.rkt
racket
#lang racket/base (require scribble/xref racket/fasl setup/dirs tests/eli-tester) FIXME : need to look for out < i>.sxref files (provide xref-tests) (module+ main (xref-tests)) (define (xref-tests) (define sxref (build-path (find-doc-dir) "reference" "out.sxref")) (when (file-exists? sxref) (define xref (load-xref (list (λ () (cadr (call-with-input-file* sxref fasl->s-exp)))))) (test (xref-binding->definition-tag xref (list '(lib "contract.rkt" "racket") '->) #f) => '(form ((lib "racket/contract/base.rkt") ->)))))
6bffd433886ff01758e2dfa3238a0763cd8478ba5317f7968680fbe029460dd4
hbr/albatross
proof_context.ml
Copyright ( C ) < helmut dot brandl at gmx dot net > This file is distributed under the terms of the GNU General Public License version 2 ( GPLv2 ) as published by the Free Software Foundation . This file is distributed under the terms of the GNU General Public License version 2 (GPLv2) as published by the Free Software Foundation. *) open Container open Term open Proof open Support open Printf module Option = Fmlib.Option module RD = Rule_data type slot_data = {ndown:int; sprvd: int TermMap.t} type var_def_data = { definition: int option; used: int list } type entry = {mutable prvd: Term_table.t; (* all proved (incl. schematic) terms *) mutable bwd: Term_table.t; mutable fwd: Term_table.t; mutable left: Term_table.t; mutable reeval: Term_table.t; mutable slots: slot_data array} type gdesc = {mutable pub: bool; (*deferred: int option; ( * The owner class of a deferred assertion *) defer: bool; anchor: int} type t = {base: Proof_table.t; terms: RD.t Ass_seq.t; gseq: gdesc Seq.t; mutable def_ass: Term_table.t; depth: int; mutable work: int list; count0: int; entry: entry; prev: t option; var_defs: var_def_data array; trace: bool; verbosity: int} let verbosity (pc:t): int = pc.verbosity let is_tracing (pc:t): bool = pc.verbosity >= 3 let context (pc:t): Context.t = Proof_table.context pc.base let feature_table (pc:t): Feature_table.t = let c = context pc in Context.feature_table c let class_table (pc:t): Class_table.t = let c = context pc in Context.class_table c let is_private (pc:t): bool = Proof_table.is_private pc.base let is_public (pc:t): bool = Proof_table.is_public pc.base let is_interface_use (pc:t): bool = Proof_table.is_interface_use pc.base let is_interface_check (pc:t): bool = Proof_table.is_interface_check pc.base let add_used_module (m:Module.M.t) (pc:t): unit = Proof_table.add_used_module m pc.base let add_current_module (m:Module.M.t) (pc:t): unit = Proof_table.add_current_module m pc.base let set_interface_check (pc:t): unit = Proof_table.set_interface_check pc.base let make_entry () = let e = Term_table.empty in {prvd=e; bwd=e; fwd=e; left=e; reeval=e; slots = Array.make 1 {ndown = 0; sprvd = TermMap.empty}} let copied_entry (e:entry): entry = {prvd = e.prvd; bwd = e.bwd; fwd = e.fwd; left = e.left; reeval = e.reeval; slots = Array.copy e.slots} let make (comp:Module.Compile.t): t = let verbosity = Module.Compile.verbosity comp in let res = {base = Proof_table.make comp; terms = Ass_seq.empty (); gseq = Seq.empty (); def_ass = Term_table.empty; depth = 0; prev = None; var_defs = [||]; work = []; count0 = 0; entry = make_entry (); trace = verbosity >= 3; verbosity= verbosity} in res let is_global (at:t): bool = Proof_table.is_global at.base let is_local (at:t): bool = Proof_table.is_local at.base let is_toplevel (at:t): bool = Proof_table.is_toplevel at.base let nbenv (at:t): int = Proof_table.count_variables at.base let count_all_type_variables (pc:t): int = Context.count_all_type_variables (context pc) let count_type_variables (pc:t): int = Context.count_type_variables (context pc) let count_variables (at:t): int = Proof_table.count_variables at.base let count_last_arguments (pc:t): int = Proof_table.count_last_arguments pc.base let count_last_variables (pc:t): int = Proof_table.count_last_variables pc.base let count_last_type_variables (pc:t): int = Proof_table.count_last_type_variables pc.base let local_argnames (pc:t): int array = Proof_table.local_argnames pc.base let local_formals (pc:t): formals0 = Proof_table.local_formals pc.base let local_fgs (pc:t): formals0 = Proof_table.local_fgs pc.base let count_base (pc:t): int = Proof_table.count pc.base let count (pc:t): int = Ass_seq.count pc.terms let is_consistent (pc:t): bool = count_base pc = count pc let count_previous (pc:t): int = Proof_table.count_previous pc.base let count_global(pc:t): int = Proof_table.count_global pc.base let imp_id(pc:t): int = Proof_table.imp_id pc.base let term (i:int) (pc:t): term = (** The [i]th proved term in the current environment. *) assert (i < count pc); assert (count pc <= count_base pc); Proof_table.local_term i pc.base let depth (pc:t): int = pc.depth let trace_prefix_0 (pc:t): string = assert (not (is_global pc)); String.make (3 + 2*(pc.depth-1)) ' ' let trace_prefix (pc:t): string = String.make (3 + 2*pc.depth) ' ' let trace_pop (pc:t): unit = printf "%send\n" (trace_prefix_0 pc) let pop (pc:t): t = assert (is_local pc); match pc.prev with None -> assert false | Some x -> x let trace_push (pc:t): unit = let str = Proof_table.last_arguments_string pc.base in let prefix = trace_prefix_0 pc in if str <> "" then printf "%sall%s\n" prefix str; printf "%srequire\n" prefix let push_slots (nbenv:int) (pc:t): unit = pc.entry.slots <- if nbenv=0 then Array.copy pc.entry.slots else let len = Array.length pc.entry.slots in Array.init (len+1) (fun i -> if i<len then let sd = pc.entry.slots.(i) in {sd with ndown = sd.ndown+nbenv} else {ndown=0; sprvd=TermMap.empty}) let push0 (base:Proof_table.t) (pc:t): t = let nbenv = Proof_table.count_variables base and nargs = Proof_table.count_last_variables base in let var_defs = Array.init nbenv (fun i -> if i < nargs then {definition = None; used = []} else pc.var_defs.(i-nargs) ) in let res = {pc with base = base; terms = Ass_seq.clone pc.terms; work = pc.work; depth = 1 + pc.depth; count0 = count pc; entry = copied_entry pc.entry; var_defs = var_defs; prev = Some pc} in push_slots nbenv res; if res.trace then trace_push res; res let push (entlst:entities list withinfo) (rt:return_type) (is_pred:bool) (is_func:bool) (rvar: bool) (pc:t): t = let base = Proof_table.push entlst rt is_pred is_func rvar pc.base in push0 base pc let push_typed (fargs:Formals.t) (fgs:Formals.t) (rvar:bool) (pc:t): t = let base = Proof_table.push_typed fargs fgs rvar pc.base in push0 base pc let push_typed0 (fargs:Formals.t) (fgs:Formals.t) (pc:t): t = push_typed fargs fgs false pc let push_empty (pc:t): t = let base = Proof_table.push_empty pc.base in push0 base pc let arguments_string (pc:t): string = Context.arguments_string (context pc) let rec global (pc:t): t = if is_global pc then pc else global (pop pc) let type_of_term (t:term) (pc:t): type_term = Context.type_of_term t (context pc) let rule_data (idx:int) (pc:t): RD.t = assert (idx < count pc); Ass_seq.elem idx pc.terms let is_fully_specialized (idx:int) (pc:t): bool = RD.is_fully_specialized (rule_data idx pc) let is_assumption (i:int) (pc:t): bool = assert (i < count pc); Proof_table.is_assumption i pc.base let is_local_assumption (i:int) (pc:t): bool = Proof_table.is_local_assumption i pc.base let count_local_assumptions (pc:t): int = Proof_table.count_local_assumptions pc.base let tvars (pc:t): Tvars.t = Context.tvars (context pc) let signature (pc:t): Signature.Sign.t = Context.signature (context pc) let string_of_term (t:term) (pc:t): string = Context.string_of_term t (context pc) let string_long_of_term (t:term) (pc:t): string = Context.string_long_of_term t (context pc) let string_of_term_anon (t:term) (nb:int) (pc:t): string = Context.string_of_term0 t true false nb (context pc) let string_of_term_i (i:int) (pc:t): string = assert (i < count pc); Proof_table.string_of_term_i i pc.base let string_long_of_term_i (i:int) (pc:t): string = assert (i < count pc); Proof_table.string_long_of_term_i i pc.base let string_of_term_array (args: term array) (pc:t): string = "[" ^ (String.concat "," (List.map (fun t -> string_of_term t pc) (Array.to_list args))) ^ "]" let string_of_tvs (pc:t): string = Class_table.string_of_tvs (tvars pc) (class_table pc) let string_of_type (tp:type_term) (pc:t): string = Context.string_of_type tp (context pc) let string_of_ags (ags:agens) (pc:t): string = Context.string_of_ags ags (context pc) let is_visible (i:int) (pc:t): bool = not (is_interface_check pc) || let ft = feature_table pc and t,c = Proof_table.term i pc.base in let nb = Context.count_variables c in Feature_table.is_term_visible t nb ft let split_implication (t:term) (pc:t): term * term = Proof_table.split_implication t pc.base let implication (a:term) (b:term) (pc:t): term = Proof_table.implication a b pc.base let negation (a:term) (pc:t): term = let nb = nbenv pc in Term.unary (nb + Constants.not_index) a let disjunction (a:term) (b:term) (pc:t): term = let nb = nbenv pc in Term.binary (nb + Constants.or_index) a b let false_constant (pc:t): term = let nb = nbenv pc in Feature_table.false_constant nb let negation_expanded (a:term) (pc:t): term = implication a (false_constant pc) pc let split_general_implication_chain (t:term) (pc:t): Formals.t * Formals.t * term list * term = Context.split_general_implication_chain t (context pc) let all_quantified (tps:Formals.t) (fgs:Formals.t) (t:term) (pc:t): term = Proof_table.all_quantified tps fgs t pc.base let prenex_term (t:term) (pc:t): term = Proof_table.prenex_term t pc.base let implication_chain (ps:term list) (tgt:term) (pc:t): term = Proof_table.implication_chain ps tgt pc.base let assumptions (pc:t): term list = Proof_table.assumptions pc.base let assumption_indices (pc:t): int list = Proof_table.assumption_indices pc.base let assumptions_chain (tgt:term) (pc:t): term = implication_chain (List.rev (assumptions pc)) tgt pc let assumptions_for_variables_0 (vars: int array) (* The variables *) (pc:t) : int list * int = (* All assumptions of the contexts which are needed to define the variables [vars] and the number of variables in these contexts. *) let nvars = Array.length vars in assert (0 < nvars); let var_max = Array.fold_left (fun v i -> max v i) (-1) vars in let rec collect (nargs:int) (ass:int list) (pc:t): int list * int = (* collect while [nargs <= var_max] *) let idx_lst_rev = assumption_indices pc in let ass = List.rev_append idx_lst_rev ass in let nargs_new = nargs + count_last_variables pc in if var_max < nargs_new then ass, nargs_new else collect nargs_new ass (pop pc) in collect 0 [] pc let assumptions_for_variables (ind_vars: int array) (* The induction variables *) (insp_vars: int list) (* All variables of the inspect expression *) (goal: term) (pc:t) : int list * int list * int = (* All assumptions of the contexts which are needed to define the variables [ind_vars], all the other variables which are not in [insp_vars] but in the contexts plus the variables in the goal and the total number of variables encounterd in the contexts. *) let ass, nvars = assumptions_for_variables_0 ind_vars pc in let used_lst = let used_lst_rev = List.fold_left (fun lst idx -> Term.used_variables_0 (term idx pc) nvars lst) (Term.used_variables goal nvars) ass in let insp_vars = Array.of_list insp_vars in Array.sort Stdlib.compare insp_vars; List.filter (fun i -> try ignore(Search.binsearch i insp_vars); false with Not_found -> true ) (List.rev used_lst_rev) in ass, used_lst, nvars let work (pc:t): int list = pc.work let has_work (pc:t): bool = pc.work <> [] let clear_work (pc:t): unit = pc.work <- [] let has_result (pc:t): bool = Proof_table.has_result pc.base let has_result_variable (pc:t): bool = Proof_table.has_result_variable pc.base let seed_function (pc:t): int -> int = Feature_table.seed_function (feature_table pc) let is_well_typed (t:term) (pc:t): bool = Context.is_well_typed t (context pc) let transformed_to_current (t:term) (idx:int) (pc:t): term = Proof_table.transformed_to_current t idx pc.base let unify_0 (t:term) (tab:Term_table.t) (pc:t): (int * Term_sub.t) list = List.rev (Term_table.unify t (nbenv pc) (seed_function pc) tab) let args_and_ags_of_substitution (idx:int) (sub:Term_sub.t) (pc:t) : arguments * agens = let rd = rule_data idx pc in let args = Term_sub.arguments (Term_sub.count sub) sub in try let ags = RD.verify_specialization args (context pc) rd in args,ags with Not_found -> printf " can not unify types of actual arguments with formal arguments\n " ; printf " actuals % s\n " ( string_of_term_array args pc ) ; printf " rule % s\n " ( string_long_of_term_i idx pc ) ; printf " actuals %s\n" (string_of_term_array args pc); printf " rule %s\n" (string_long_of_term_i idx pc);*) raise Not_found let unify (t:term) (tab:Term_table.t) (pc:t) : (int * arguments * agens) list = let lst = unify_0 t tab pc in List.fold_left (fun lst (idx,sub) -> try let args,ags = args_and_ags_of_substitution idx sub pc in (idx,args,ags) :: lst with Not_found -> lst ) [] lst let unify_with_0 (t:term) (nargs:int) (tab:Term_table.t) (pc:t) : (int * Term_sub.t) list = (* Find the terms which can be unified with [t] which has [nargs] arguments and comes from the current environment. *) let nvars = nbenv pc and tps,_,t0 = Term.all_quantifier_split_1 t in let nb = Formals.count tps in Term_table.unify_with t0 nb nargs nvars true (seed_function pc) tab let unify_with (t:term) (nargs:int) (tps:types) (tab:Term_table.t) (pc:t) : (int * arguments) list = (* Find the terms which can be unified with [t] which has [nargs] arguments with types [tps] and comes from the current environment. *) let lst = unify_with_0 t nargs tab pc in List.fold_left (fun lst (idx,sub) -> (* [sub] is valid in the environment of [idx] *) let args = Term_sub.arguments (Term_sub.count sub) sub in let args = Array.map (fun t -> transformed_to_current t idx pc) args in let argtps = Array.map (fun t -> type_of_term t pc) args in if Term.equivalent_array tps argtps then (idx,args)::lst else lst ) [] lst let is_trace_extended (pc:t): bool = 3 < pc.verbosity let trace_term (t:term) (rd:RD.t) (search:bool) (dup:bool) (pc:t): unit = let str = string_long_of_term t pc and cnt = count pc and prefix = trace_prefix pc in assert (cnt + 1 = count_base pc); let ext = if is_trace_extended pc then let pt = Proof_table.proof_term cnt pc.base in let ptstr = Proof_term.short_string pt and rdstr = RD.short_string rd and cntstr = (string_of_int cnt) ^ (if is_global pc then "global" else "") in let str = (if search then "" else "n") ^ (if dup then "d" else "") in let rstr = str ^ rdstr in cntstr ^ "'" ^ ptstr ^ (if rstr <> "" then "," else "") ^ rstr ^ "' " else "" in printf "%s%s%s\n" prefix ext str; if is_trace_extended pc then printf "%s\t%s\n" prefix (Term.to_string t); if is_global pc then printf "\n" let find (t:term) (pc:t): int = let tps,fgs,t0 = Term.all_quantifier_split_1 t in let n = Formals.count tps and fgtps = Formals.types fgs in let nfgs = Array.length fgtps in let sublst = Term_table.find t0 n (nbenv pc) (seed_function pc) pc.entry.prvd in let idx,sub = List.find (fun (idx,sub) -> assert (Term_sub.is_empty sub); if nfgs = 0 then true else let _,fgs,_ = Term.all_quantifier_split_1 (term idx pc) in let fgtps_found = Formals.types fgs in Array.length fgtps_found = nfgs && Term.equivalent_array fgtps fgtps_found ) sublst in idx let has (t:term) (pc:t): bool = (** Is the term [t] already in the proof context [pc]? *) try ignore(find t pc); true with Not_found -> false let has_in_view (t:term) (pc:t): bool = assert (is_global pc); try let i = find t pc in assert (i < count_global pc); if is_private pc then true else let gdesc = Seq.elem i pc.gseq in gdesc.pub with Not_found -> false let equal_symmetry (pc:t): int = find (Feature_table.equal_symmetry_term ()) (global pc) let leibniz_term (pc:t): int = find (Feature_table.leibniz_term ()) (global pc) let split_equality (t:term) (pc:t): int * term * term = Proof_table.split_equality t 0 pc.base let split_specific_equality (t:term) (pc:t): term * term = let nargs,left,right = split_equality t pc in if nargs = 0 then left, right else raise Not_found let equality_data (i:int) (pc:t): int * term * term = assert (count_variables pc = Proof_table.nbenv_term i pc.base); let rd = rule_data i pc in let nargs, eq_id, left, right = Rule_data.equality_data rd in if nargs = 0 then eq_id, left, right else raise Not_found let add_variable_definition (v:int) (idx:int) (pc:t): unit = (* The assertion at [idx] is a valid definition assertion of the form v = exp *) assert (v < count_variables pc); if pc.trace then printf "%svariable definition %d %s\n" (trace_prefix pc) idx (string_of_term_i idx pc); let def = pc.var_defs.(v) in assert (not (Option.has def.definition)); pc.var_defs.(v) <- {def with definition = Some idx} let add_variable_usage (v:int) (idx:int) (pc:t): unit = (* The variable [v] is part of the definition term of another variable and has been used to substitute the other variable in an assertion to get the assertion at [idx] *) assert (v < count_variables pc); let def = pc.var_defs.(v) in assert (not (Option.has def.definition)); if List.mem idx def.used then () else pc.var_defs.(v) <- {def with used = idx :: def.used} let variable_definition (v:int) (pc:t): int = The index of the defining assertin of the variable [ v ] . Raise [ Not_found ] if the variable has no definition . if the variable has no definition. *) assert (v < count_variables pc); match pc.var_defs.(v).definition with None -> raise Not_found | Some idx -> idx let variable_has_definition (v:int) (pc:t): bool = try ignore(variable_definition v pc); true with Not_found -> false let extended_variable_definition (v:int) (pc:t): int * term = (* The index of the defining assertion of the variable [v] and its definition term. *) try let idx = variable_definition v pc in let t = term idx pc in let left,right = split_specific_equality t pc in assert (left = Variable v); idx, right with Not_found -> assert false (* Illegal call *) let get_variable_definitions (t:term) (pc:t): (int*int*term) list = (* Get the list of all applicable variable definitions in the term [t]. The definition consists of the index of the defining assertion, the variable and the definition term. The list must be applied in reversed form. *) let nvars = count_variables pc in let filter v = v < nvars && variable_has_definition v pc in let get_used t lst = Term.used_variables_filtered_0 t filter false lst in let get_defs var_lst = List.rev_map (fun v -> let idx,exp = extended_variable_definition v pc in idx,v,exp ) var_lst in let rec get_definitions (rcnt:int) (vars_new: int list) (defs:(int*int*term) list) : (int*int*term) list = assert (rcnt <= nvars); match vars_new with [] -> defs | _ -> let vars_new, defs = List.fold_left (fun (vs,defs) (idx,v,exp) -> let vs = get_used exp vs and defs = (idx,v,exp)::defs in vs,defs ) ([],defs) (get_defs vars_new) in get_definitions (rcnt+1) vars_new defs in get_definitions 0 (get_used t []) [] let complexity (t:term) (pc:t): int = Context.complexity t (context pc) let add_to_equalities (t:term) (idx:int) (pc:t): unit = (* Check the assertion [t] at [idx] if it is a simplifying equality. If yes, add it to the equality table. *) let nbenv = nbenv pc in try let nargs, left,right = split_equality t pc in let is_simpl = Term.nodes right < Term.nodes left else complexity right pc < complexity left pc in if is_simpl then begin printf " add_to_equalities % d % s < % s>\n " idx ( string_of_term t pc ) ( Term.to_string t ) ; idx (string_of_term t pc) (Term.to_string t);*) pc.entry.left <- Term_table.add left nargs nbenv idx (seed_function pc) pc.entry.left end with Not_found -> () let has_public_deferred (t:term) (pc:t): bool = assert (is_global pc); try let sublst = Term_table.find t 0 0 (seed_function pc) pc.def_ass in match sublst with [] -> false | [idx,sub] -> true | _ -> assert false (* no duplicates *) with Not_found -> false let add_to_public_deferred (t:term) (idx:int) (pc:t): unit = assert (is_global pc); if not (has_public_deferred t pc) then let sfun = seed_function pc in pc.def_ass <- Term_table.add t 0 0 idx sfun pc.def_ass let add_to_proved (t:term) (idx:int) (pc:t): unit = let sfun = seed_function pc in let tps,_,t0 = Term.all_quantifier_split_1 t in let n = Formals.count tps in pc.entry.prvd <- Term_table.add t0 n (count_variables pc) idx sfun pc.entry.prvd let add_to_forward (rd:RD.t) (idx:int) (pc:t): unit = if not (RD.is_forward rd) then () else begin let nargs,_,nbenv,t = RD.schematic_premise rd in pc.entry.fwd <- Term_table.add t nargs nbenv idx (seed_function pc) pc.entry.fwd end let add_to_backward (rd:RD.t) (idx:int) (pc:t): unit = if not (RD.is_backward rd) then begin () end else begin let nargs,nbenv,t = RD.schematic_target rd in pc.entry.bwd <- Term_table.add t nargs nbenv idx (seed_function pc) pc.entry.bwd end let add_last_to_tables (pc:t): unit = assert (0 < count pc); let idx = count pc - 1 in let t = term idx pc and rd = rule_data idx pc in assert (not (has t pc)); add_to_proved t idx pc; add_to_forward rd idx pc; add_to_backward rd idx pc; add_to_equalities t idx pc; assert (has t pc) let filter_tables (pred:int->bool) (pc:t): unit = assert (is_global pc); let e = pc.entry in e.prvd <- Term_table.filter pred e.prvd; e.bwd <- Term_table.filter pred e.bwd; e.fwd <- Term_table.filter pred e.fwd; e.left <- Term_table.filter pred e.left let filter_and_remap_tables (pred:int->bool) (pc:t): unit = assert (is_global pc); let e = pc.entry and f = seed_function pc in e.prvd <- Term_table.filter_and_remap pred f e.prvd; e.bwd <- Term_table.filter_and_remap pred f e.bwd; e.fwd <- Term_table.filter_and_remap pred f e.fwd; e.left <- Term_table.filter_and_remap pred f e.left let add_to_work (idx:int) (pc:t): unit = pc.work <- idx :: pc.work let add_last_to_work (pc:t): unit = assert (0 < count pc); if not (is_global pc || is_interface_use pc) then let idx = count pc - 1 in pc.work <- idx :: pc.work let get_rule_data (t:term) (pc:t): RD.t = RD.make t (context pc) let raw_add0 (t:term) (rd:RD.t) (search:bool) (pc:t): int = assert (count pc + 1 = count_base pc); let cnt = count pc in let res = try find t pc with Not_found -> cnt in let dup = res <> cnt in if pc.trace && ((search && not dup) || is_trace_extended pc) then trace_term t rd search dup pc else if is_global pc && verbosity pc > 1 then begin printf "\n%s\n" (string_of_term t pc); flush_all () end; Ass_seq.push rd pc.terms; if search && not dup then begin add_last_to_tables pc; if not dup && is_global pc then Feature_table.add_involved_assertion cnt t (feature_table pc); List.iter (fun (i,_) -> add_to_work i pc; if is_tracing pc then begin printf "reevaluate %s\n" (string_of_term_i i pc); printf " because of %s\n" (string_of_term t pc) end ) (unify_0 t pc.entry.reeval pc) end; if not dup && is_global pc then Induction.put_assertion res t (context pc); res let raw_add (t:term) (search:bool) (pc:t): int = raw_add0 t (get_rule_data t pc) search pc let raw_add_work (t:term) (search:bool) (pc:t): int = let idx = raw_add t search pc in if search && idx + 1 = count pc then add_last_to_work pc; idx let arguments_of_sub (sub:Term_sub.t): term array = let nargs = Term_sub.count sub in let args = Term_sub.arguments nargs sub in args let specialized (idx:int) (args:arguments) (ags:agens) 0 : match , 1 : fwd , 2 : bwd (pc:t): int = The schematic rule [ idx ] specialized by the arguments [ args ] and the actual generics [ ags ] . Note : The arguments [ args ] are valid in the current enviroment ! actual generics [ags]. Note: The arguments [args] are valid in the current enviroment! *) assert (is_consistent pc); assert (idx < count pc); let rd = rule_data idx pc in if RD.is_specialized rd then begin if Array.length args <> 0 then begin printf "specialize\n"; printf " idx %d term %s\n" idx (string_long_of_term_i idx pc); printf " |args| %d\n" (Array.length args); end; assert (Array.length args = 0); idx end else if Array.length args = 0 && RD.count_args_to_specialize rd > 0 then idx else begin let rd = RD.specialize rd args ags idx (context pc) in let t = RD.term rd in try find t pc with Not_found -> let search = if reason = 0 then false else if reason = 1 then not (RD.is_forward rd) && RD.is_backward rd else true in Proof_table.add_specialize t idx args ags pc.base; raw_add0 t rd search pc end let find_schematic (t:term) (nargs:int) (pc:t): int * agens = (* Find a universally quantified assertion and a substitution for it so that the substituted assertion is the same as the term 't' and the substitution is the indentity substitution with [nargs] arguments. *) let sublst = unify t pc.entry.prvd pc in let sublst = List.filter (fun (_,args,_) -> Array.length args = nargs && interval_for_all (fun i -> args.(i) = Variable i ) 0 nargs ) sublst in match sublst with [] -> raise Not_found | (idx,_,ags):: tail -> idx, ags let find_match (g:term) (pc:t): int = try find g pc with Not_found -> let sublst = unify g pc.entry.prvd pc in if sublst = [] then raise Not_found; try let idx,_,_ = List.find (fun (_,args,_) -> Array.length args = 0) sublst in idx with Not_found -> let idx,args,ags = List.hd sublst in try specialized idx args ags 0 pc with Not_found -> assert false (* specialization not type safe ? *) let find_match_list (lst:term list) (pc:t): int list = List.fold_left (fun lst t -> (find_match t pc) :: lst) [] (List.rev lst) let simplified_term (t:term) (below_idx:int) (pc:t): term * Eval.t * bool = (* Simplify the term [t] and return the simplified term, the corresponding Eval structure and a flag which tells if the term [t] and its simplification are different. [below_idx]: consider only rules below [below_idx] for equality. Note: [t] is valid in the current environment! *) let rec simp t = let do_subterms t = let simpl_args args modi = let arglst, modi = Array.fold_left (fun (arglst,modi) a -> let asimp,ae,amodi = simp a in (asimp,ae)::arglst, modi || amodi) ([],modi) args in let args, argse = Myarray.split (Array.of_list (List.rev arglst)) in args, argse, modi in match t with Variable _ -> t, Eval.Term t, false | VAppl (i,args,ags,oo) -> let args, argse, modi = simpl_args args false in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), modi | Application(f,args,inop) -> let fsimp,fe,fmodi = simp f in let args, argse, modi = simpl_args args fmodi in let res = Application(fsimp, args, inop) in let rese = Eval.Term res in res, Eval.Apply(fe,argse,rese), modi | Lam _ | QExp _ | Ifexp _ | Asexp _ | Inspect _ | Indset _ -> t, Eval.Term t, false in let sublst = unify t pc.entry.left pc in let sublst = List.filter (fun (idx,sub,_) -> idx < below_idx && Array.length sub = 0) sublst in match sublst with (idx,_,ags) :: _ -> (* Note: This is a workaround. Only single entries in the equality table should be accepted. But multiple entries are possible as long we do not make specializations type safe. *) let eq = term idx pc in let nargs, left, right = Proof_table.split_equality eq 0 pc.base in assert (nargs = 0); assert (Term.equivalent t left); right, Eval.Simpl(Eval.Term t,idx,[||],ags), true | _ -> do_subterms t in let tsimp, te, modi = simp t in let ta, tb = Proof_table.reconstruct_evaluation te pc.base in assert (Term.equivalent ta t); if not (Term.equivalent tb tsimp) then begin printf "simplified_term %s\n" (string_of_term t pc); printf " tb %s\n" (string_of_term tb pc); printf " tsimp %s\n" (string_of_term tsimp pc); assert (is_well_typed t pc); end; assert (Term.equivalent tb tsimp); assert (modi = not (Term.equivalent tsimp t)); if modi then begin printf " simplification found\n " ; printf " term % s\n " ( string_of_term t pc ) ; printf " simpl % s\n " ( string_of_term tsimp pc ) ; end ; printf "simplification found\n"; printf " term %s\n" (string_of_term t pc); printf " simpl %s\n" (string_of_term tsimp pc); end;*) tsimp, te, modi let triggers_eval (i:int) (nb:int) (pc:t): bool = Does the term [ Variable i ] trigger a full evaluation when used as a top level function term , i.e. is it a variable which describes a function which has no expansion and is not owned by BOOLEAN ? level function term, i.e. is it a variable which describes a function which has no expansion and is not owned by BOOLEAN? *) let nbenv = nb + nbenv pc and ft = feature_table pc in i < nbenv || let idx = i - nbenv in idx = Constants.or_index || Feature_table.owner idx ft <> Constants.boolean_class let beta_reduce (n:int) (t:term) (tup_tp:type_term) (args:term array) (nb:int) (pc:t) : term = Proof_table.beta_reduce n t tup_tp args nb pc.base let beta_reduce_term (t:term) (pc:t): term = match t with | Application (Lam(tps,_,_,t0,_), args, _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in beta_reduce n t0 tup_tp args 0 pc | _ -> printf "beta_reduce_term %s\n" (string_long_of_term t pc); assert false (* Is not a redex *) let make_lambda (tps:Formals.t) (fgs:Formals.t) (ps: term list) (t:term) (rt: type_term option) (pc:t) : term = let c = context pc in Context.make_lambda tps fgs ps t rt c let make_application (f:term) (args:term array) (tup:type_term) (nb:int) (pc:t) : term = let c = context pc in Context.make_application f args tup nb c let is_inductive_set (i:int) (pc:t): bool = Proof_table.is_inductive_set i pc.base let inductive_set (t:term) (pc:t): term = Proof_table.inductive_set t pc.base let definition_term (i:int) (nb:int) (ags:agens) (pc:t): int * int array * term = if i < nb || is_inductive_set (i-nb) pc then raise Not_found else Proof_table.definition_term i nb ags pc.base let arity (i:int) (nb:int) (pc:t): int = Proof_table.arity i nb pc.base exception Undecidable of term exception No_evaluation of term option exception No_branch_evaluation of term option let decide (t:term) (pc:t): bool * int = try true, find_match t pc with Not_found -> try false, find_match (negation_expanded t pc) pc with Not_found -> raise (Undecidable t) let string_of_term_option (t:term option) (pc:t): string = match t with | None -> "None" | Some t -> "Some(" ^ string_of_term t pc ^ ")" let chain_term_option (t1:term option) (t2:term option): term option = match t1 with | None -> t2 | Some _ -> t1 let eval_term (t:term) (pc:t): term * Eval.t * term option = (* Evaluate the term [t] and return the evaluated term, the corresponding Eval structure. Raise [No_evaluation] if the term does not have an evaluation. *) let rec eval (t:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = if depth > 500 then raise (No_evaluation None); let depth = depth + 1 in let nvars = nbenv pc in let domain_id = nvars + Constants.domain_index in match t with Variable i -> assert (i < nvars); raise (No_evaluation None) | VAppl (i,[|Lam(tps,fgs,pres,t0,rt)|],ags,inop) when i = domain_id -> assert (rt <> None); let args = [|Eval.Term (Lam(tps,fgs,pres,t0,rt))|] and dom = Context.domain_of_lambda tps fgs pres 0 (context pc) in dom, Eval.Exp(i, ags, args, Eval.Term dom),None | VAppl(i,args,ags,oo) -> eval_vappl t i args ags oo lazy_ depth pc | Application (Lam(tps,fgs,_,t0,_), args, inop) -> let tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) and n = Formals.count tps in let reduct = beta_reduce n t0 tup_tp args 0 pc and te = Eval.Term t in begin try let res,rese,cond = maybe_eval reduct lazy_ depth pc in let e = Eval.Beta (te, rese) in res, e, cond with No_branch_evaluation cond -> raise (No_evaluation cond) end | Application (f,args,inop) -> assert (Array.length args = 1); begin try let f_exp,fe,fcond = eval f lazy_ (depth - 1) pc and argse = [| Eval.Term args.(0) |] in let t_exp,te,tcond = maybe_eval (Application(f_exp,args,inop)) lazy_ depth pc in let cond = match fcond with | None -> tcond | Some _ -> fcond in t_exp, Eval.Apply(fe,argse,te), cond with No_evaluation cond -> if depth = 1 then let args,argse,cond = eval_args args (depth - 1) pc in let t_exp = Application(f,args,inop) in let fe = Eval.Term f and te = Eval.Term t_exp in t_exp, Eval.Apply(fe, argse,te), cond else raise (No_evaluation cond) end | Lam _ -> raise (No_evaluation None) | QExp _ -> raise (No_evaluation None) | Ifexp (c, a, b) -> eval_if c a b lazy_ depth pc | Asexp (insp, tps, pat) -> eval_as t insp tps pat lazy_ depth pc | Inspect (insp, cases) -> eval_inspect t insp cases lazy_ depth pc | Indset _ -> raise (No_evaluation None) and eval_vappl (t:term) (i:int) (args:arguments) (ags:agens) (oo:bool) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let nvars = nbenv pc in let and_id = nvars + Constants.and_index and or_id = nvars + Constants.or_index and imp_id = nvars + Constants.implication_index in let is_lazy i = i = and_id || i = or_id || i = imp_id in try let n,nms,t0 = definition_term i 0 ags pc and argse = Array.map (fun t -> Eval.Term t) args in assert (n = Array.length args); let t_expanded = Proof_table.apply_term t0 args 0 pc.base in begin try let res, rese,cond = maybe_eval t_expanded lazy_ depth pc in res, Eval.Exp(i,ags,argse,rese), cond with No_branch_evaluation cond_t -> try let args,argse,cond = eval_args args depth pc in let cond = chain_term_option cond_t cond in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond with No_evaluation cond -> let cond = chain_term_option cond_t cond in let argse = Array.map (fun t -> Eval.Term t) args in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond let args , , cond = eval_args args depth pc in let cond = match cond_t with | None - > cond | Some _ - > cond_t in VAppl(i , args , ags , oo ) , Eval . VApply(i , argse , ags ) , cond let cond = match cond_t with | None -> cond | Some _ -> cond_t in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond*) end with Not_found -> (* No definition *) if Array.length args = 0 || (lazy_ && depth > 1) || is_lazy i then raise (No_evaluation None) else let args,argse,cond = eval_args args depth pc in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond and eval_args (args:arguments) (depth:int) (pc:t) : arguments * Eval.t array * term option = let len = Array.length args in let args = Array.copy args and argse = Array.map (fun t -> Eval.Term t) args in let modi,cond = interval_fold (fun (modi,cond) i -> try let t, te, cond_i = eval args.(i) false depth pc in args.(i) <- t; argse.(i) <- te; true, if cond = None then cond_i else cond with No_evaluation cond_i -> if cond = None then modi,cond_i else modi, cond ) (false,None) 0 len in if modi then args, argse, cond else raise (No_evaluation cond) and eval_if (cond:term) (a:term) (b:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let conde = Eval.Term cond in try let res,idx = decide cond pc in if res then let fst,fste,fst_cond = maybe_eval a lazy_ depth pc in fst, Eval.If (true, idx, [|conde; fste; Eval.Term b|]), fst_cond else let snd,snde,snd_cond = maybe_eval b lazy_ depth pc in snd, Eval.If (false, idx, [|conde; Eval.Term a; snde|]), snd_cond with Undecidable cond -> raise (No_branch_evaluation (Some cond)) and eval_inspect (t:term) (insp:term) (cases: (formals*term*term) array) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let insp, inspe, icond = maybe_eval insp true depth pc and c = context pc in match Pattern.decide_inspect insp cases c with | None -> raise (No_branch_evaluation None) | Some (i, args, pres) -> try nyi : include in proof term let _,_,res = cases.(i) in let res = Term.apply res args in let res,rese,rcond = maybe_eval res lazy_ depth pc in let cond = chain_term_option icond rcond in res, Eval.Inspect(t,inspe,i,rese), cond with Not_found -> let pre = try List.find (fun pre -> try ignore(find_match pre pc); false with Not_found -> true) pres with Not_found -> assert false (* Cannot happen *) in raise (No_branch_evaluation (Some pre)) and eval_as (t:term) (insp:term) (tps:types) (pat:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let nvars = nbenv pc in let n = Array.length tps in let insp,inspe,cond = maybe_eval insp lazy_ depth pc in let c = context pc in let undecide () = Pattern.evaluated_as_expression t (context pc), Eval.AsExp t, cond in let find_pres pres = try find_match_list pres pc with Not_found -> raise Support.Undecidable in try begin match Pattern.unify_with_pattern insp n pat c with | None -> undecide () | Some (Error (pres) ) -> nyi : include in proof term Feature_table.false_constant nvars, Eval.As(false,inspe,tps,pat), cond | Some ( Ok (args,pres) ) -> nyi : include in proof term Feature_table.true_constant nvars, Eval.As(true,inspe,tps,pat), None end with Support.Undecidable -> undecide () and maybe_eval (t:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option= try eval t lazy_ depth pc with No_evaluation cond -> t, Eval.Term t, cond in try eval t true 0 pc with No_branch_evaluation cond -> raise (No_evaluation cond) let evaluated_term (t:term) (pc:t): term * Eval.t * term option * bool = try let t,e,cond = eval_term t pc in t, e, cond, true with No_evaluation cond -> t, Eval.Term t, cond, false let add_mp0 (t:term) (i:int) (j:int) (search:bool) (pc:t): int = (* Add the term [t] by applying the modus ponens rule with [i] as the premise and [j] as the implication. *) let cnt = count pc and rd = RD.drop (rule_data j pc) (context pc) in Proof_table.add_mp t i j pc.base; (if RD.is_implication rd then let _ = raw_add0 t rd search pc in () else let _ = raw_add t search pc in ()); cnt let add_mp (i:int) (j:int) (search:bool) (pc:t): int = (* Apply the modus ponens rule with [i] as the premise and [j] as the implication. *) assert (i < count pc); assert (j < count pc); let rdj = rule_data j pc and c = context pc in if not (RD.is_specialized rdj) then printf "add_mp %s\n" (string_long_of_term_i j pc); assert (RD.is_specialized rdj); assert (RD.is_implication rdj); let t = RD.term_b rdj c in if not (Term.equivalent (term i pc) (RD.term_a rdj c)) then begin printf "add_mp premise %d %s %s\n" i (string_long_of_term_i i pc) (Term.to_string (term i pc)); printf " implication %d %s %s\n" j (string_long_of_term_i j pc) (Term.to_string (term j pc)); printf " term_a %s %s\n" (string_long_of_term (RD.term_a rdj c) pc) (Term.to_string (RD.term_a rdj c)) end; assert (Term.equivalent (term i pc) (RD.term_a rdj c)); try find t pc with Not_found -> add_mp0 t i j search pc let try_add_beta_reduced (idx:int) (search:bool) (pc:t): int = let t = term idx pc in match t with | Application(Lam(tps,fgs,_,t0,_), [|arg|], _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in let reduct = beta_reduce n t0 tup_tp [|arg|] 0 pc in let pt = Eval(idx, Eval.Beta (Eval.Term t, Eval.Term reduct)) in Proof_table.add_proved reduct pt 0 pc.base; raw_add_work reduct search pc | _ -> raise Not_found let add_beta_reduced (idx:int) (search:bool) (pc:t): int = (* [idx] must represent a term which can be beta reduced *) try try_add_beta_reduced idx search pc with Not_found -> printf "add_beta_reduced\n"; printf " The term %d \"%s\" is not a beta redex\n" idx (string_of_term_i idx pc); assert false (* The term [idx] is not a beta redex *) let add_beta_redex (t:term) (idx:int) (search:bool) (pc:t): int = (* The term [t] must be beta reducible and its beta reduction is the term [idx]. The term [t] is added. *) match t with | Application(Lam(tps,fgs,_,t0,_), [|arg|], _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in let reduced = beta_reduce n t0 tup_tp [|arg|] 0 pc in let e1,e2 = Eval.Term t, Eval.Term reduced in let pt = Eval_bwd(t,Eval.Beta (e1,e2)) (* proves the implication [t_idx ==> t] *) in let impl = implication reduced t pc in Proof_table.add_proved impl pt 0 pc.base; let idx_impl = raw_add impl false pc in add_mp idx idx_impl search pc | _ -> assert false let add_some_elim (i:int) (search:bool) (pc:t): int = (* The term [i] has the form [some(a,b,...) t0]. Add the elimination law all(e) (all(a,b,..) t0 ==> e) ==> e *) let t = try Proof_table.someelim i pc.base with Not_found -> assert false in Proof_table.add_proved t (Someelim i) 0 pc.base; raw_add t search pc let add_some_elim_specialized (i:int) (goal:term) (search:bool) (pc:t): int = (* The term [i] has the form [some(a,b,...) t0]. Add the elimination law all(e) (all(a,b,..) t0 ==> e) ==> e and the specialized version (all(a,b,...) t0 ==> goal) ==> goal *) let idx = add_some_elim i search pc in specialized idx [|goal|] [||] 0 pc let add_mp_fwd (i:int) (j:int) (pc:t): unit = let rdj = rule_data j pc in if RD.is_forward rdj then begin let cnt = count pc in let res = add_mp i j true pc in if res = cnt then add_last_to_work pc end let is_nbenv_current (i:int) (pc:t): bool = assert (i < count pc); let nbenv_i = RD.count_variables (rule_data i pc) in nbenv_i = nbenv pc let add_consequence (i:int ) (j:int) (args:arguments) (ags:agens) (pc:t): unit = (* Add the consequence of [i] and the implication [j]. The term [j] might be a schematic implication which has to be converted into a specific implication by using the substitution [sub]. Note: The arguments [args] and the actual generics [ags] are valid in the current environment. *) (*printf "add_consequence\n"; printf " premise %d %s\n" i (string_long_of_term_i i pc); printf " impl %d %s\n" j (string_long_of_term_i j pc); printf " args %s\n" (string_of_term_array args pc);*) assert (is_consistent pc); assert (i < count pc); assert (j < count pc); let nbenv_sub = Proof_table.nbenv_term i pc.base in assert (nbenv_sub <= nbenv pc); try let j = specialized j args ags 1 pc in add_mp_fwd i j pc with Not_found -> () let add_consequences_premise (i:int) (pc:t): unit = (** Add the consequences of the term [i] by using the term as a premise for already available implications. *) assert (i < count pc); if not (is_nbenv_current i pc) then printf "add_consequences_premise %s\n" (string_of_term_i i pc); assert (is_nbenv_current i pc); assert (not (RD.is_intermediate (rule_data i pc))); let nbenv = nbenv pc in let t,c_t = Proof_table.term i pc.base in assert (nbenv = Context.count_variables c_t); let sublst = unify t pc.entry.fwd pc in let sublst = List.rev sublst in List.iter (fun (idx,sub,ags) -> assert (is_consistent pc); assert (idx < count pc); if is_visible idx pc then add_consequence i idx sub ags pc) sublst let add_consequences_implication (i:int) (rd:RD.t) (pc:t): unit = (* Add the consequences of the term [i] by using the term as an implication and searching for matching premises. *) assert (i < count pc); assert (is_nbenv_current i pc); let rd = rule_data i pc and nbenv = nbenv pc in assert (RD.is_implication rd); assert (not (RD.is_generic rd)); let gp1,tps,nbenv_a,a = RD.schematic_premise rd in assert (nbenv_a = nbenv); if RD.is_schematic rd then (* the implication is schematic *) if RD.is_forward rd then begin let sublst = unify_with a gp1 tps pc.entry.prvd pc in let sublst = List.rev sublst in List.iter (fun (idx,args) -> if not (RD.is_intermediate (rule_data idx pc)) then add_consequence idx i args [||] pc ) sublst end else () else (* the implication is not schematic *) try let idx = find a pc in (* check for exact match *) add_mp_fwd idx i pc with Not_found -> (* no exact match *) let sublst = unify a pc.entry.prvd pc in match sublst with [] -> () | (idx,sub,ags)::_ -> (* the schematic rule [idx] matches the premise of [i]*) begin try let idx_premise = specialized idx sub ags 1 pc in add_mp_fwd idx_premise i pc with Not_found -> () end let add_fwd_evaluation (t:term) (i:int) (e:Eval.t) (full:bool) (pc:t): int = (* Add the term [t] which is an evaluation of the term [i] to the proof context if it is not yet in and return the index *) try find t pc with Not_found -> let rd = get_rule_data t pc in Proof_table.add_eval t i e pc.base; let res = raw_add0 t rd full pc in (); if full then add_last_to_work pc; res let add_consequences_evaluation (i:int) (pc:t): unit = (* Add the simplification and the evaluation of the term [i] in case that there is one if it is not yet in the proof context [pc] to the proof context and to the work items. *) let t = term i pc in let add_eval t e = add_fwd_evaluation t i e true pc in let t1,e,modi = simplified_term t i pc in if modi then ignore(add_eval t1 e); let t1,e,reeval_term,modi = evaluated_term t pc in let idx = if modi then add_eval t1 e else i in begin match reeval_term with | None -> () | Some cond -> if is_tracing pc then begin printf "more evaluation would be possible of\n"; printf " %s\n" (string_of_term t pc); printf "if the following condition where decidable\n"; printf " %s\n" (string_of_term cond pc) end; let nbenv = count_variables pc in pc.entry.reeval <- Term_table.add cond 0 nbenv idx (seed_function pc) pc.entry.reeval; pc.entry.reeval <- let cond = negation_expanded cond pc in Term_table.add cond 0 nbenv idx (seed_function pc) pc.entry.reeval; end let add_consequences_someelim (i:int) (pc:t): unit = try let some_consequence = Proof_table.someelim i pc.base in if has some_consequence pc then () else begin Proof_table.add_someelim i some_consequence pc.base; let _ = raw_add some_consequence true pc in (); add_last_to_work pc end with Not_found -> () let type_of_term (t:term) (pc:t): type_term = Context.type_of_term t (context pc) let predicate_of_type (tp:type_term) (pc:t): type_term = Context.predicate_of_type tp (context pc) let add_assumption_or_axiom (t:term) (is_axiom: bool) (search:bool) (pc:t): int = (** Add the term [t] as an assumption or an axiom to the context [pc]. *) assert (is_consistent pc); let cnt = count pc in if is_axiom then Proof_table.add_axiom t pc.base else Proof_table.add_assumption t pc.base; ignore(raw_add t search pc); if not is_axiom && search then add_last_to_work pc; cnt let add_assumption (t:term) (search:bool) (pc:t): int = (** Add the term [t] as an assumption to the context [pc]. *) add_assumption_or_axiom t false search pc let add_axiom (t:term) (pc:t): int = (** Add the term [t] as an axiom to the context [pc]. *) add_assumption_or_axiom t true false pc let specialize_induction_law (idx:int) (* induction law *) (p: term) (* goal predicate *) (ivar: int) (* induction variable *) (pc:t) : int = Specialize the induction law [ idx ] with the goal predicate [ p ] . An induction law has the form all(p0,x ) p01 = = > p02 = = > ... = = > x in p0 where each p0i is a constructor rule . The specialized induction law has the form p1 = = > p2 = = > ... ivar in p where p0i and p0 are specialized with ivar and p An induction law has the form all(p0,x) p01 ==> p02 ==> ... ==> x in p0 where each p0i is a constructor rule. The specialized induction law has the form p1 ==> p2 ==> ... ivar in p where p0i and p0 are specialized with ivar and p *) let sub = [|p; Variable ivar|] in let ags = try RD.verify_specialization sub (context pc) (rule_data idx pc) with Not_found -> assert false in specialized idx sub ags 0 pc let add_set_induction_law (set:term) (q:term) (elem:term) (pc:t): int = try let indlaw = Proof_table.set_induction_law set pc.base and pt = Indset_ind set in Proof_table.add_proved_0 indlaw pt pc.base; let idx = raw_add indlaw false pc in let rd = rule_data idx pc in let args = [|q;elem|] and ags = [||] (* is not generic *) in let rd = RD.specialize rd args ags idx (context pc) in assert (RD.is_specialized rd); let t = RD.term rd in Proof_table.add_specialize t idx args ags pc.base; raw_add0 t rd false pc with Not_found -> invalid_arg "Not an inductive set" let add_inductive_set_rules (fwd:bool) (t:term) (pc:t): unit = match t with Application(set,args,_) -> assert (Array.length args = 1); begin try let nme,tp,rs = let indset = inductive_set set pc in match indset with Indset(nme,tp,rs) -> nme,tp,rs | _ -> assert false in let len = Array.length rs in for i = 0 to len-1 do let rule = Term.apply rs.(i) [|set|] in if has rule pc then begin () end else begin let pt = Indset_rule (set,i) in Proof_table.add_proved_0 rule pt pc.base; ignore(raw_add rule true pc); add_last_to_work pc end done with Not_found -> () end | _ -> () let equality_swapped (i:int) (left:term) (right:term) (pc:t): int = (* The term at [i] is a equality of the form [left = right]. Add the term [right = left] to the context and return its index. *) let eq_sym = equal_symmetry pc and tp = type_of_term left pc in let eq_sym = specialized eq_sym [|left;right|] [|tp|] 0 pc in add_mp i eq_sym false pc let leibniz (i:int) (left:term) (right:term) (pc:t): int = The term at [ i ] is a equality of the form [ left = right ] . Add the term [ all(p ) p(left ) = = > p(right ) ] derived from the leibniz condition all(a , b , p ) a = b = = > p(a ) = = > p(b ) to the context and return its index . term [all(p) p(left) ==> p(right)] derived from the leibniz condition all(a,b,p) a = b ==> p(a) ==> p(b) to the context and return its index. *) let idx = leibniz_term pc and tp = type_of_term left pc in let idx = specialized idx [|left;right|] [|tp|] 0 pc in add_mp i idx false pc let can_be_variable_definition (v:int) (t:term) (pc:t): bool = not (variable_has_definition v pc) && let nvars = count_variables pc in let used = Term.used_variables t nvars in not (List.mem v used) && List.for_all (fun v -> not (variable_has_definition v pc)) used let variable_substitution_implication (v:int) (idx:int) (exp:term) (t:term) (search:bool) (pc:t) :term * int = (* Insert the term [t[v:=exp] ==> t] and return the term [t[v:=exp]] and the index of the implication. where [idx] is the assertion with the variable definition [v = exp]. Raise [Not_found] if the symmetry law of equality is not available or if the leibniz law is not available. The term [t] must be a boolean term. *) let idx = equality_swapped idx (Variable v) exp pc in let pterm = Term.lambda_inner t v and tp = type_of_term (Variable v) pc in let ptp = predicate_of_type tp pc in let tps = Formals.make (standard_argnames 1) [|tp|] in let p = make_lambda tps Formals.empty [] pterm None pc in let redex1 = make_application p [|exp|] tp 0 pc and tr = beta_reduce 1 pterm ptp [|exp|] 0 pc and idx_leib = leibniz idx exp (Variable v) pc in let idx_leib = specialized idx_leib [|p|] [||] 0 pc in let pc0 = push_empty pc in let idx_a = add_assumption tr false pc0 in let idx_redex1 = add_beta_redex redex1 idx_a false pc0 in let idx_redex2 = add_mp idx_redex1 idx_leib false pc0 in let idx_t = add_beta_reduced idx_redex2 false pc0 in assert (Term.equivalent (term idx_t pc0) t); let imp,pt = Proof_table.discharged idx_t pc0.base in Proof_table.add_proved imp pt 0 pc.base; let res_idx = raw_add imp search pc in tr,res_idx let substitute_variable (var:int) (def_idx:int) (def_term:term) (t:term) (idx:int) (search:bool) (pc:t): int = (* The variable [var] has the defining assertion [def_idx] with the definition term [def_term]. Use this definition to substitute the variable in the assertion [t] at [idx] *) if pc.trace then begin let prefix = trace_prefix pc in printf "%ssubstitute variable %s by %s\n" prefix (string_of_term (Variable var) pc) (string_of_term def_term pc); printf "%s in %d %s\n" prefix idx (string_of_term t pc) end; let leib = leibniz def_idx (Variable var) def_term pc leib : all(p:{T } p(var ) = = > p(def_term ) and pterm = Term.lambda_inner t var and tp = type_of_term (Variable var) pc in let tps = Formals.make (standard_argnames 1) [|tp|] in let p = make_lambda tps Formals.empty [] pterm None pc in let imp_idx = specialized leib [|p|] [||] 0 pc (* {var: term}(var) ==> {var:term}(def_term) *) and redex1 = make_application p [|Variable var|] tp 0 pc in let idx_redex1 = add_beta_redex redex1 idx false pc in let idx_redex2 = add_mp idx_redex1 imp_idx false pc in let res = add_beta_reduced idx_redex2 search pc in if pc.trace then printf "%ssubstituted term %s\n" (trace_prefix pc) (string_of_term_i res pc); res let add_consequences_variable_definition (i:int) (pc:t): unit = (* If the assertion [i] is a variable definition of the form [v = exp] or [exp = v] where [exp] does not contain [v] then add all the consequences of the variable definition. - Use symmetry of [=] and swap the operands if necessary to get the expression into the form [v = exp] so that [v] has no definition and does not occur in [exp] and none of the variables in [exp] has a definition. If this is not possible then do nothing. - Add [exp] as a defintion of [v]. - Scan all assumptions which contain [v] and add the assumptions with [v] substituted by [exp] to the context. Furthermore add the substituted assumptions to all variables occurring in [exp]. - Scan all assertions where [v] has already been used in the substitution term of another variable. *) let var_def (i:int): int * int * term = let eq_id, left, right = equality_data i pc in match left,right with Variable j, Variable k -> if can_be_variable_definition j right pc then i,j,right else if can_be_variable_definition k left pc then let i = equality_swapped i left right pc in i,k,left else raise Not_found | Variable j, _ -> if can_be_variable_definition j right pc then i, j, right else raise Not_found | _, Variable k -> if can_be_variable_definition k left pc then let i = equality_swapped i left right pc in i, k, left else raise Not_found | _,_ -> raise Not_found in try let idx, ivar, exp = var_def i in assert (not (variable_has_definition ivar pc)); let ass_lst, _ = assumptions_for_variables_0 [|ivar|] pc in add_variable_definition ivar idx pc; let nvars = count_variables pc in let exp_used = Term.used_variables exp nvars in List.iter (fun ass_idx -> if ass_idx <> idx then let ass = term ass_idx pc in let used = Term.used_variables ass nvars in if List.mem ivar used then begin try let idx_sub = substitute_variable ivar idx exp ass ass_idx true pc in (* add idx_sub to all variables in exp *) List.iter (fun v -> add_variable_usage v idx_sub pc) exp_used with Not_found -> () end ) ass_lst; List.iter (fun ass_idx -> ignore(substitute_variable ivar idx exp (term ass_idx pc) ass_idx true pc) ) pc.var_defs.(ivar).used with Not_found -> () let expand_variable_definitions (i:int) (pc:t): unit = (* Check if the assertion at [i] has variables which have a definition. If yes then use these variable definitions and add the substituted assertion.*) let subst (i:int) (idx:int) (v:int) (exp:term) (search:bool): int = let t = term i pc in substitute_variable v idx exp t i search pc in let t = term i pc in let defs = get_variable_definitions t pc in match defs with [] -> () | (idx,v,exp)::tail -> let i = List.fold_right (fun (idx,v,exp) i -> subst i idx v exp false ) tail i in try ignore(subst i idx v exp true) with Not_found -> (* The leibniz law is not yet available *) () let add_consequences (i:int) (pc:t): unit = (** Add the consequences of the term [i] which are not yet in the proof context [pc] to the proof context and to the work items. *) (*printf "add_consequences %d %s\n" i (string_long_of_term_i i pc);*) let t = term i pc and rd = rule_data i pc in add_inductive_set_rules true t pc; if not (RD.is_intermediate rd) then add_consequences_premise i pc; if RD.is_implication rd then add_consequences_implication i rd pc; add_consequences_evaluation i pc; add_consequences_someelim i pc; if is_local_assumption i pc then expand_variable_definitions i pc; add_consequences_variable_definition i pc let clear_work (pc:t): unit = pc.work <- [] let close_step (pc:t): unit = assert (has_work pc); let i = List.hd pc.work in pc.work <- List.tl pc.work; add_consequences i pc let prefix (pc:t): string = String.make (2*(depth pc)+2) ' ' let close (pc:t): unit = if is_global pc then () else begin let rec cls (round:int): unit = if has_work pc then begin let lst = List.rev pc.work in pc.work <- []; List.iter (fun i -> add_consequences i pc ) lst; if is_interface_check pc then pc.work <- [] else cls (1+round) end in cls 0 end let close_assumptions (pc:t): unit = (*pc.work <- List.rev pc.work;*) if pc.trace then printf "%sproof\n" (trace_prefix_0 pc); close pc let trying_goal (g:term) (pc:t): unit = if pc.trace then begin let prefix = trace_prefix pc in printf "%strying to prove: %s\n" prefix (string_of_term g pc); if is_trace_extended pc then printf "%s\t%s\n" prefix (Term.to_string g); end let failed_goal (g:term) (pc:t): unit = if pc.trace then printf "%sfailure: %s\n" (trace_prefix pc) (string_of_term g pc) let proved_goal (g:term) (pc:t): unit = if pc.trace then printf "%ssuccess: %s\n" (trace_prefix pc) (string_of_term g pc) let print_work (pc:t): unit = if has_work pc then begin printf "open work to close\n"; List.iter (fun i -> printf " %d %s\n" i (string_of_term_i i pc)) pc.work end let boolean_type (nb:int) (pc:t): type_term = let ntvs = Context.count_all_type_variables (context pc) in Variable (Constants.boolean_class + nb + ntvs) let check_deferred (pc:t): unit = Context.check_deferred (context pc) let owner (pc:t): int = (* The owner class of the signature *) assert (is_toplevel pc); let ct = class_table pc and tvs = tvars pc and s = signature pc in match Class_table.dominant_class tvs s ct with | None -> -1 | Some cls -> cls let variant (i:int) (bcls:int) (cls:int) (pc:t): term = Proof_table.variant i bcls cls pc.base let add_global (defer:bool) (anchor:int) (pc:t): unit = assert (is_global pc); let cnt = count pc in if cnt <> Seq.count pc.gseq + 1 then printf "add_global count pc = %d, Seq.count pc.gseq = %d\n" cnt (Seq.count pc.gseq); assert (cnt = Seq.count pc.gseq + 1); Seq.push {pub = is_public pc; defer = defer; anchor = anchor} pc.gseq; assert (count pc = Seq.count pc.gseq) let eval_backward (tgt:term) (imp:term) (e:Eval.t) (pc:t): int = (* Add [imp] as an evaluation where [imp] has the form [teval ==> tgt] and [teval] is the term [tgt] evaluated with [e]. *) Proof_table.add_eval_backward tgt imp e pc.base; raw_add imp false pc let predicate_of_term (t:term) (pc:t): type_term = Context.predicate_of_term t (context pc) let find_equality (t1:term) (t2:term) (pc:t): int = let eq = Context.equality_term t1 t2 (context pc) in find_match eq pc let find_leibniz_for (t1:term) (t2:term) (pc:t): int = let gen_leibniz = leibniz_term pc in let eq_idx = find_equality t1 t2 pc in let tp = Context.type_of_term t1 (context pc) in let spec_leibniz = specialized gen_leibniz [|t1;t2|] [|tp|] 0 pc in add_mp eq_idx spec_leibniz false pc Subterm equality : The goal has the form lhs = rhs which we can transform into f(a1,a2 , .. ) = , .. ) as a lambda term [ f ] and two argument arrays [ a1,a2 , .. ] , [ , .. ] and we have found the leibniz rules all(p ) p(ai ) = = > p(bi ) for all arguments start : f(a1,a2 , .. ) = f(a1,a2 , .. ) reflexivity step i : f(a1,a2 , .. ) = f(b1,b2, .. ,ai , , .. ) start point { x : f(a1,a2 , .. ) = f(b1,b2, .. ,x , ai+1, .. )}(ai ) Eval_bwd { x: .. }(ai ) = = > { x: .. }(bi ) specialize leibniz { x: .. }(bi ) modus ponens f(a1,a2 , .. ) = f(b1,b2, .. ,bi , , .. ) Eval last : f(a1,a2 , .. ) = , .. ) result : lhs = rhs The goal has the form lhs = rhs which we can transform into f(a1,a2,..) = f(b1,b2,..) as a lambda term [f] and two argument arrays [a1,a2,..], [b1,b2,..] and we have found the leibniz rules all(p) p(ai) ==> p(bi) for all arguments start: f(a1,a2,..) = f(a1,a2,..) reflexivity step i: f(a1,a2,..) = f(b1,b2,..,ai,ai+1,..) start point {x: f(a1,a2,..) = f(b1,b2,..,x,ai+1,..)}(ai) Eval_bwd {x:..}(ai) ==> {x:..}(bi) specialize leibniz {x:..}(bi) modus ponens f(a1,a2,..) = f(b1,b2,..,bi,ai+1,..) Eval last: f(a1,a2,..) = f(b1,b2,..) result: lhs = rhs Eval *) let prove_equality (g:term) (pc:t): int = let c = context pc in let eq_id, left, right, ags = match g with VAppl (eq_id, [|left;right|], ags, _) when Context.is_equality_index eq_id c -> eq_id, left, right, ags | _ -> raise Not_found in let find_leibniz t1 t2 = find_leibniz_for t1 t2 pc in let tlam, leibniz, args1, args2 = Term_algo.compare left right find_leibniz in let nargs = Array.length args1 in let tup = Context.tuple_type_of_terms args1 c and tps = Array.map (fun t -> Context.type_of_term t c) args1 and r_tp = Context.type_of_term left c in let tps = Formals.make (standard_argnames nargs) tps in let lam = make_lambda tps Formals.empty [] tlam (Some r_tp) pc in assert (nargs = Array.length args2); assert (0 < nargs); let lam_1up = Term.up 1 lam and args1_up1 = Term.array_up 1 args1 and args2_up1 = Term.array_up 1 args2 in try let flhs_1up = make_application lam_1up args1_up1 tup 1 pc and frhs_x i = let args = Array.init nargs (fun j -> if j < i then args2_up1.(j) else if j = i then Variable 0 else args1_up1.(j)) in make_application lam_1up args tup 1 pc in let pred_inner i = VAppl (eq_id+1, [|flhs_1up; (frhs_x i)|], ags, false) in let start_term = let t = make_application lam args1 tup 0 pc in VAppl (eq_id, [|t;t|], ags, false) in let start_idx = find_match start_term pc in let result = ref start_idx in for i = 0 to nargs - 1 do let pred_inner_i = pred_inner i and tp = type_of_term args1.(i) pc in let tps = Formals.make [|ST.symbol "$1"|] [|tp|] in let pred_i = Lam(tps,Formals.empty,[],pred_inner_i,None) in let ai_abstracted = make_application pred_i [|args1.(i)|] tp 0 pc and ai_reduced = term !result pc in let imp = implication ai_reduced ai_abstracted pc in let idx2 = eval_backward ai_abstracted imp (Eval.Beta (Eval.Term ai_abstracted, Eval.Term ai_reduced)) pc in let idx = add_mp !result idx2 false pc in let sub = [|pred_i|] in let idx2 = specialized leibniz.(i) sub [||] 0 pc in let idx = add_mp idx idx2 false pc in let t = Term.apply pred_inner_i [|args2.(i)|] in let e = Eval.Beta (Eval.Term (term idx pc), Eval.Term t) in Proof_table.add_eval t idx e pc.base; result := raw_add t false pc done; let e = let ev args t = Eval.Beta (Eval.Term (make_application lam args tup 0 pc), Eval.Term t) in Eval.VApply(eq_id, [|ev args1 left; ev args2 right|], ags) in result := add_fwd_evaluation g !result e false pc; !result with Not_found -> assert false (* cannot happen *) let backward_witness (t:term) (pc:t): int = (* Find a witness for the existentially quantified term [t] or raise [Not_found] if there is no witness or [t] is not existentially quantified. *) let tps,t0 = Term.some_quantifier_split t in let nargs = Formals.count tps and nms = Formals.names tps and tps = Formals.types tps in let sublst = unify_with t0 nargs tps pc.entry.prvd pc in let idx,args = List.find (fun (idx,args) -> Array.length args = nargs) sublst in let witness = term idx pc in let impl = implication witness t pc in Proof_table.add_witness impl idx nms tps t0 args pc.base; let idx_impl = raw_add impl false pc in add_mp0 t idx idx_impl false pc let find_goal (g:term) (pc:t): int = (* Find either an exact match of the goal or a schematic assertion which can be fully specialized to match the goal. *) add_inductive_set_rules false g pc; close pc; try find_match g pc with Not_found -> try backward_witness g pc with Not_found -> prove_equality g pc module Backward = struct type rule = { idx: int; tps: Formals.t; fgs: Formals.t; mutable ps: term list; (* remaining premises *) mutable subs: Term_sub.t list; (* set of substitutions *) pc: t } let has_some (r:rule): bool = r.subs <> [] let is_complete (r:rule): bool = match r.subs with | [] -> true | sub :: _ -> Term_sub.count sub = Formals.count r.tps (* all the others must have the same variables substituted, because the same subterms have been used to find them *) let merge (sub:Term_sub.t) (old_subs:Term_sub.t list) (cumulated:Term_sub.t list) : Term_sub.t list = (* Merge the new substitution [sub] with each substitutions of [old_subs] and prepend the merged substitutions in front of [cumulated]. *) List.fold_left (fun cumulated old_sub -> try (Term_sub.merge sub old_sub) :: cumulated with Not_found -> cumulated ) cumulated old_subs let rec complete_rule (r:rule): rule = (* Returns a rule with a nonempty list of complete substitutions or raises Not_found, if not possible.*) assert (has_some r); if is_complete r then r else match r.ps with | [] -> assert false (* As long as the substitutions are not yet complete there must be premises *) | p :: ps when Term.is_variable_below (Formals.count r.tps) p -> printf "\n\nRule %s\nhas a premise which is catch all\n\n" (string_of_term_i r.idx r.pc); r.ps <- ps; complete_rule r | p :: ps -> r.ps <- ps; let sublst = unify_with_0 p (Formals.count r.tps) r.pc.entry.prvd r.pc in r.subs <- List.fold_left (fun subs (idx,new_sub) -> let new_sub = Term_sub.map (fun t -> transformed_to_current t idx r.pc) new_sub in merge new_sub r.subs subs ) [] sublst; if r.subs = [] then raise Not_found; (* The rule cannot be completed *) complete_rule r let find_rules (g:term) (blacklst:IntSet.t) (pc:t): rule list = List.fold_left (fun lst (idx,sub) -> if IntSet.mem idx blacklst || not (is_visible idx pc) then lst else let tps,fgs,ps_rev,tgt = split_general_implication_chain (term idx pc) pc in assert (ps_rev <> []); (* has to be a backward rule i.e. an implication *) let ps = List.rev ps_rev in try {tps; fgs; idx; ps; subs = [sub]; pc} :: lst with Not_found -> lst ) [] (unify_0 g pc.entry.bwd pc) let specialize_rule (r:rule) (lst:int list): int list = Specialized the rule [ r ] for all its substitutions and append the successfully specialized rules to the list [ lst ] . the successfully specialized rules to the list [lst]. *) assert (RD.is_backward (rule_data r.idx r.pc)); List.fold_left (fun lst sub -> try let args,ags = args_and_ags_of_substitution r.idx sub r.pc in if Array.length args = 0 then r.idx :: lst else let cnt = count r.pc in let idx = specialized r.idx args ags 2 r.pc in if idx = cnt then (* no duplicate *) cnt :: lst else lst with Not_found -> lst ) lst r.subs let complete_rules (rules:rule list): int list = List.fold_left (fun lst r -> try let r = complete_rule r in specialize_rule r lst with Not_found -> lst ) [] rules let find (g:term) (blacklst:IntSet.t) (pc:t): int list = let rules = find_rules g blacklst pc in let lst = complete_rules rules in List.sort (fun i j -> let rdi = rule_data i pc and rdj = rule_data j pc in compare (RD.count_premises rdi) (RD.count_premises rdj)) lst end (* Backward *) let backward_in_table ( g : term ) ( blacklst : IntSet.t ) ( pc : t ): int list = let sublst = unify g pc.entry.bwd pc in let lst = List.fold_left ( fun lst ( idx , sub , ags ) - > if IntSet.mem idx blacklst || not ( is_visible idx pc ) then lst else if Array.length sub = 0 then if RD.is_backward ( rule_data idx pc ) then idx : : lst else lst else begin let cnt = count pc in let idx = specialized idx sub ags 2 pc in if idx = cnt & & RD.is_backward ( rule_data idx pc ) then begin : : lst end else begin lst end end ) [ ] sublst in List.sort ( fun i j - > let and rdj = rule_data j pc in compare ( RD.count_premises rdi ) ( RD.count_premises rdj ) ) lst let backward_in_table (g:term) (blacklst: IntSet.t) (pc:t): int list = let sublst = unify g pc.entry.bwd pc in let lst = List.fold_left (fun lst (idx,sub,ags) -> if IntSet.mem idx blacklst || not (is_visible idx pc) then lst else if Array.length sub = 0 then if RD.is_backward (rule_data idx pc) then idx :: lst else lst else begin let cnt = count pc in let idx = specialized idx sub ags 2 pc in if idx = cnt && RD.is_backward (rule_data idx pc) then begin cnt :: lst end else begin lst end end) [] sublst in List.sort (fun i j -> let rdi = rule_data i pc and rdj = rule_data j pc in compare (RD.count_premises rdi) (RD.count_premises rdj)) lst *) let eval_reduce (g:term) (lst:int list) (pc:t): int list = let add_eval t e lst = let impl = implication t g pc in if has impl pc then lst else (eval_backward g impl e pc) :: lst in let t1,e,modi = simplified_term g (count pc) pc in let lst = if modi then add_eval t1 e lst else lst in let t1,e,_,modi = evaluated_term g pc in if modi then add_eval t1 e lst else lst let substituted_goal (g:term) (lst:int list) (pc:t): int list = (* Apply all variable substitutions in backward direction and add [gsub ==> g] to the context and add its index to the list *) try let gsub,imps = List.fold_left (fun (gsub,imps) (idx,v,exp) -> let gsub,imp = variable_substitution_implication v idx exp gsub false pc in gsub, imp::imps ) (g,[]) (get_variable_definitions g pc) (*(List.rev (get_variable_definitions g pc))*) in if imps = [] then lst else let pc0 = push_empty pc in let idx_gsub = add_assumption gsub false pc0 in let idx_g = List.fold_left (fun g imp -> add_mp g imp false pc0) idx_gsub imps in let imp,pt = Proof_table.discharged idx_g pc0.base in Proof_table.add_proved imp pt 0 pc.base; let imp_idx = raw_add imp false pc in if pc.trace then begin let prefix = trace_prefix pc in printf "%sgoal substitution backward rule\n" prefix; printf "%s %d %s\n" prefix imp_idx (string_of_term_i imp_idx pc) end; imp_idx :: lst with Not_found -> lst let find_backward_goal (g:term) (blacklst:IntSet.t) (pc:t): int list = (*assert (is_well_typed g pc);*) let lst = substituted_goal g [] pc in if lst <> [] then lst else begin let lst = Backward.find g blacklst pc in let lst = backward_in_table g blacklst pc in let lst = eval_reduce g lst pc in if pc.trace && is_trace_extended pc then begin let prefix = trace_prefix pc and str = string_of_intlist lst in printf "%salternatives %s\n" prefix str; if not (IntSet.is_empty blacklst) then printf "%s blacklist %s\n" prefix (string_of_intset blacklst) end; lst end let discharged (i:int) (pc:t): term * proof_term = (** The [i]th term of the current environment with all local variables and assumptions discharged together with its proof term. *) Proof_table.discharged i pc.base let discharged_bubbled (i:int) (pc:t): term * proof_term = (** The [i]th term of the current environment with all local variables and assumptions discharged together with its proof term. *) Proof_table.discharged_bubbled i pc.base let is_proof_pair (t:term) (pt:proof_term) (pc:t): bool = Proof_table.is_proof_pair t pt pc.base let add_proved_term (t:term) (pt:proof_term) (search:bool) (pc:t): int = (* Add the proof pair [t,pt] to the table and include it into the search tables if [search] is flagged and the term [t] is not a duplicate. Note: Not allowed as a global assertion! *) assert (not (is_global pc)); let cnt = count pc in Proof_table.add_proved t pt 0 pc.base; let idx = raw_add t search pc in if search && idx = cnt then add_last_to_work pc; idx let add_proved_0 (defer:bool) (anchor:int) (t:term) (pterm:proof_term) (delta:int) (pc:t) : int = assert (not defer || anchor <> 0); let cnt = count pc and ct = class_table pc in Proof_table.add_proved t pterm delta pc.base; let idx = raw_add t true pc in let dup = idx < cnt and is_glob = idx < count_global pc in if not dup || is_glob then (* duplicates of globals must be added to work, because globals are not closed *) add_last_to_work pc; if defer && is_interface_check pc then begin assert (is_global pc); add_to_public_deferred t cnt pc end; if is_global pc then begin add_global defer anchor pc; if defer && not dup then begin assert (idx = cnt); Class_table.add_generic idx true anchor ct; let gdesc = Seq.elem idx pc.gseq in if is_interface_check pc && not gdesc.pub then gdesc.pub <- true end else if dup && is_interface_check pc then (Seq.elem idx pc.gseq).pub <- true end; cnt let add_proved_with_delta (t:term) (pterm:proof_term) (delta: int) (pc:t) : int = add_proved_0 false (-1) t pterm delta pc let add_proved (t:term) (pterm:proof_term) (pc:t) : int = add_proved_0 false (-1) t pterm 0 pc let add_proved_list (defer:bool) (anchor:int) (lst: (term*proof_term) list) (pc:t) : unit = let cnt = count pc in List.iter (fun (t,pt) -> let delta = count pc - cnt in let _ = add_proved_0 defer anchor t pt delta pc in ()) lst let remove_or_remap (set:IntSet.t) (pc:t): unit = (* All assertions in the set [set] have some features which have got a new seed. If an assertion can still be found then there is a more general assertion in the search tables and the assertion has to be removed from the search tables. If an assertion cannot be found anymore then the search tables have to be remapped to find them again. Furthermore an assertion which has to be remapped might be an equality assertion. If yes, its left hand side has to be added to the equality table. *) let index i = try find (term i pc) pc with Not_found -> -1 in let remap_set = IntSet.filter (fun i -> let idx = index i in assert (idx <> i); (* Some features have new seeds *) idx = -1) set in let pred i = IntSet.mem i remap_set || not (IntSet.mem i set) in filter_and_remap_tables pred pc; IntSet.iter (fun i -> let t = term i pc in add_to_equalities t i pc) remap_set let add_induction_law0 (cls:int) (pc:t): unit = assert (is_global pc); let law = Proof_table.type_induction_law cls pc.base and pt = Indtype cls and defer = Class_table.is_deferred cls (class_table pc) in ignore(add_proved_0 defer cls law pt 0 pc) let previous_schematics (idx:int) (pc:t): int list = assert (idx < count pc); let rd = rule_data idx pc in RD.previous_schematics rd let premises (idx:int) (pc:t): (term*bool) list = assert (idx < count pc); let rd = rule_data idx pc in assert (RD.is_fully_specialized rd); assert (RD.is_implication rd); RD.premises rd (context pc) let check_interface (pc:t): unit = assert (is_interface_check pc); let ft = feature_table pc in Feature_table.check_interface ft; assert (count pc = Seq.count pc.gseq); for i = 0 to count pc - 1 do let gdesc = Seq.elem i pc.gseq in if gdesc.defer && not gdesc.pub && Class_table.is_class_public gdesc.anchor (class_table pc) && not (has_public_deferred (term i pc) pc) then begin let open Module in let m = Compile.current (Feature_table.compilation_context ft) in assert (M.has_interface m); let fn = Src.path (M.interface m) in error_info (FINFO (1,0,fn)) ("deferred assertion \"" ^ (string_of_term (term i pc) pc) ^ "\" is not public") end done let excluded_middle (pc:t): int = let nvars = nbenv pc in let or_id = 1 + nvars + Constants.or_index and not_id = 1 + nvars + Constants.not_index in let em = Term.binary or_id (Variable 0) (Term.unary not_id (Variable 0)) in let nms = standard_argnames 1 and tps = [| boolean_type 1 pc |] in let em = Term.all_quantified (Formals.make nms tps) Formals.empty em in find em pc let indirect_proof_law (pc:t): int = let nvars = nbenv pc in let not_id = 1 + nvars + Constants.not_index and imp_id = 1 + nvars + Constants.implication_index and false_const = Feature_table.false_constant (1 + nvars) in (* all(a) (not a ==> false) ==> a *) let nota = Term.unary not_id (Variable 0) in let nota_imp_false = Term.binary imp_id nota false_const in let t = Term.binary imp_id nota_imp_false false_const in let btp = boolean_type 1 pc in let nms = standard_argnames 1 and tps = [| btp |] in let indirect = Term.all_quantified (Formals.make nms tps) Formals.empty t in find indirect pc let or_elimination (pc:t): int = let nvars = nbenv pc in let or_id = 3 + nvars + Constants.or_index and imp_id = 3 + nvars + Constants.implication_index in let a_or_b = Term.binary or_id (Variable 0) (Variable 1) and a_imp_c = Term.binary imp_id (Variable 0) (Variable 2) and b_imp_c = Term.binary imp_id (Variable 1) (Variable 2) in let or_elim = Term.binary imp_id a_or_b (Term.binary imp_id a_imp_c (Term.binary imp_id b_imp_c (Variable 2))) in let btp = boolean_type 3 pc in let nms = standard_argnames 3 and tps = [| btp; btp; btp |] in let or_elim = Term.all_quantified (Formals.make nms tps) Formals.empty or_elim in find or_elim pc let has_excluded_middle (pc:t): bool = try ignore(excluded_middle pc); true with Not_found -> false let has_or_elimination (pc:t): bool = try ignore(or_elimination pc); true with Not_found -> false
null
https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/alba1/proof_context.ml
ocaml
all proved (incl. schematic) terms deferred: int option; ( * The owner class of a deferred assertion * The [i]th proved term in the current environment. The variables All assumptions of the contexts which are needed to define the variables [vars] and the number of variables in these contexts. collect while [nargs <= var_max] The induction variables All variables of the inspect expression All assumptions of the contexts which are needed to define the variables [ind_vars], all the other variables which are not in [insp_vars] but in the contexts plus the variables in the goal and the total number of variables encounterd in the contexts. Find the terms which can be unified with [t] which has [nargs] arguments and comes from the current environment. Find the terms which can be unified with [t] which has [nargs] arguments with types [tps] and comes from the current environment. [sub] is valid in the environment of [idx] * Is the term [t] already in the proof context [pc]? The assertion at [idx] is a valid definition assertion of the form v = exp The variable [v] is part of the definition term of another variable and has been used to substitute the other variable in an assertion to get the assertion at [idx] The index of the defining assertion of the variable [v] and its definition term. Illegal call Get the list of all applicable variable definitions in the term [t]. The definition consists of the index of the defining assertion, the variable and the definition term. The list must be applied in reversed form. Check the assertion [t] at [idx] if it is a simplifying equality. If yes, add it to the equality table. no duplicates Find a universally quantified assertion and a substitution for it so that the substituted assertion is the same as the term 't' and the substitution is the indentity substitution with [nargs] arguments. specialization not type safe ? Simplify the term [t] and return the simplified term, the corresponding Eval structure and a flag which tells if the term [t] and its simplification are different. [below_idx]: consider only rules below [below_idx] for equality. Note: [t] is valid in the current environment! Note: This is a workaround. Only single entries in the equality table should be accepted. But multiple entries are possible as long we do not make specializations type safe. Is not a redex Evaluate the term [t] and return the evaluated term, the corresponding Eval structure. Raise [No_evaluation] if the term does not have an evaluation. No definition Cannot happen Add the term [t] by applying the modus ponens rule with [i] as the premise and [j] as the implication. Apply the modus ponens rule with [i] as the premise and [j] as the implication. [idx] must represent a term which can be beta reduced The term [idx] is not a beta redex The term [t] must be beta reducible and its beta reduction is the term [idx]. The term [t] is added. proves the implication [t_idx ==> t] The term [i] has the form [some(a,b,...) t0]. Add the elimination law all(e) (all(a,b,..) t0 ==> e) ==> e The term [i] has the form [some(a,b,...) t0]. Add the elimination law all(e) (all(a,b,..) t0 ==> e) ==> e and the specialized version (all(a,b,...) t0 ==> goal) ==> goal Add the consequence of [i] and the implication [j]. The term [j] might be a schematic implication which has to be converted into a specific implication by using the substitution [sub]. Note: The arguments [args] and the actual generics [ags] are valid in the current environment. printf "add_consequence\n"; printf " premise %d %s\n" i (string_long_of_term_i i pc); printf " impl %d %s\n" j (string_long_of_term_i j pc); printf " args %s\n" (string_of_term_array args pc); * Add the consequences of the term [i] by using the term as a premise for already available implications. Add the consequences of the term [i] by using the term as an implication and searching for matching premises. the implication is schematic the implication is not schematic check for exact match no exact match the schematic rule [idx] matches the premise of [i] Add the term [t] which is an evaluation of the term [i] to the proof context if it is not yet in and return the index Add the simplification and the evaluation of the term [i] in case that there is one if it is not yet in the proof context [pc] to the proof context and to the work items. * Add the term [t] as an assumption or an axiom to the context [pc]. * Add the term [t] as an assumption to the context [pc]. * Add the term [t] as an axiom to the context [pc]. induction law goal predicate induction variable is not generic The term at [i] is a equality of the form [left = right]. Add the term [right = left] to the context and return its index. Insert the term [t[v:=exp] ==> t] and return the term [t[v:=exp]] and the index of the implication. where [idx] is the assertion with the variable definition [v = exp]. Raise [Not_found] if the symmetry law of equality is not available or if the leibniz law is not available. The term [t] must be a boolean term. The variable [var] has the defining assertion [def_idx] with the definition term [def_term]. Use this definition to substitute the variable in the assertion [t] at [idx] {var: term}(var) ==> {var:term}(def_term) If the assertion [i] is a variable definition of the form [v = exp] or [exp = v] where [exp] does not contain [v] then add all the consequences of the variable definition. - Use symmetry of [=] and swap the operands if necessary to get the expression into the form [v = exp] so that [v] has no definition and does not occur in [exp] and none of the variables in [exp] has a definition. If this is not possible then do nothing. - Add [exp] as a defintion of [v]. - Scan all assumptions which contain [v] and add the assumptions with [v] substituted by [exp] to the context. Furthermore add the substituted assumptions to all variables occurring in [exp]. - Scan all assertions where [v] has already been used in the substitution term of another variable. add idx_sub to all variables in exp Check if the assertion at [i] has variables which have a definition. If yes then use these variable definitions and add the substituted assertion. The leibniz law is not yet available * Add the consequences of the term [i] which are not yet in the proof context [pc] to the proof context and to the work items. printf "add_consequences %d %s\n" i (string_long_of_term_i i pc); pc.work <- List.rev pc.work; The owner class of the signature Add [imp] as an evaluation where [imp] has the form [teval ==> tgt] and [teval] is the term [tgt] evaluated with [e]. cannot happen Find a witness for the existentially quantified term [t] or raise [Not_found] if there is no witness or [t] is not existentially quantified. Find either an exact match of the goal or a schematic assertion which can be fully specialized to match the goal. remaining premises set of substitutions all the others must have the same variables substituted, because the same subterms have been used to find them Merge the new substitution [sub] with each substitutions of [old_subs] and prepend the merged substitutions in front of [cumulated]. Returns a rule with a nonempty list of complete substitutions or raises Not_found, if not possible. As long as the substitutions are not yet complete there must be premises The rule cannot be completed has to be a backward rule i.e. an implication no duplicate Backward Apply all variable substitutions in backward direction and add [gsub ==> g] to the context and add its index to the list (List.rev (get_variable_definitions g pc)) assert (is_well_typed g pc); * The [i]th term of the current environment with all local variables and assumptions discharged together with its proof term. * The [i]th term of the current environment with all local variables and assumptions discharged together with its proof term. Add the proof pair [t,pt] to the table and include it into the search tables if [search] is flagged and the term [t] is not a duplicate. Note: Not allowed as a global assertion! duplicates of globals must be added to work, because globals are not closed All assertions in the set [set] have some features which have got a new seed. If an assertion can still be found then there is a more general assertion in the search tables and the assertion has to be removed from the search tables. If an assertion cannot be found anymore then the search tables have to be remapped to find them again. Furthermore an assertion which has to be remapped might be an equality assertion. If yes, its left hand side has to be added to the equality table. Some features have new seeds all(a) (not a ==> false) ==> a
Copyright ( C ) < helmut dot brandl at gmx dot net > This file is distributed under the terms of the GNU General Public License version 2 ( GPLv2 ) as published by the Free Software Foundation . This file is distributed under the terms of the GNU General Public License version 2 (GPLv2) as published by the Free Software Foundation. *) open Container open Term open Proof open Support open Printf module Option = Fmlib.Option module RD = Rule_data type slot_data = {ndown:int; sprvd: int TermMap.t} type var_def_data = { definition: int option; used: int list } mutable bwd: Term_table.t; mutable fwd: Term_table.t; mutable left: Term_table.t; mutable reeval: Term_table.t; mutable slots: slot_data array} type gdesc = {mutable pub: bool; defer: bool; anchor: int} type t = {base: Proof_table.t; terms: RD.t Ass_seq.t; gseq: gdesc Seq.t; mutable def_ass: Term_table.t; depth: int; mutable work: int list; count0: int; entry: entry; prev: t option; var_defs: var_def_data array; trace: bool; verbosity: int} let verbosity (pc:t): int = pc.verbosity let is_tracing (pc:t): bool = pc.verbosity >= 3 let context (pc:t): Context.t = Proof_table.context pc.base let feature_table (pc:t): Feature_table.t = let c = context pc in Context.feature_table c let class_table (pc:t): Class_table.t = let c = context pc in Context.class_table c let is_private (pc:t): bool = Proof_table.is_private pc.base let is_public (pc:t): bool = Proof_table.is_public pc.base let is_interface_use (pc:t): bool = Proof_table.is_interface_use pc.base let is_interface_check (pc:t): bool = Proof_table.is_interface_check pc.base let add_used_module (m:Module.M.t) (pc:t): unit = Proof_table.add_used_module m pc.base let add_current_module (m:Module.M.t) (pc:t): unit = Proof_table.add_current_module m pc.base let set_interface_check (pc:t): unit = Proof_table.set_interface_check pc.base let make_entry () = let e = Term_table.empty in {prvd=e; bwd=e; fwd=e; left=e; reeval=e; slots = Array.make 1 {ndown = 0; sprvd = TermMap.empty}} let copied_entry (e:entry): entry = {prvd = e.prvd; bwd = e.bwd; fwd = e.fwd; left = e.left; reeval = e.reeval; slots = Array.copy e.slots} let make (comp:Module.Compile.t): t = let verbosity = Module.Compile.verbosity comp in let res = {base = Proof_table.make comp; terms = Ass_seq.empty (); gseq = Seq.empty (); def_ass = Term_table.empty; depth = 0; prev = None; var_defs = [||]; work = []; count0 = 0; entry = make_entry (); trace = verbosity >= 3; verbosity= verbosity} in res let is_global (at:t): bool = Proof_table.is_global at.base let is_local (at:t): bool = Proof_table.is_local at.base let is_toplevel (at:t): bool = Proof_table.is_toplevel at.base let nbenv (at:t): int = Proof_table.count_variables at.base let count_all_type_variables (pc:t): int = Context.count_all_type_variables (context pc) let count_type_variables (pc:t): int = Context.count_type_variables (context pc) let count_variables (at:t): int = Proof_table.count_variables at.base let count_last_arguments (pc:t): int = Proof_table.count_last_arguments pc.base let count_last_variables (pc:t): int = Proof_table.count_last_variables pc.base let count_last_type_variables (pc:t): int = Proof_table.count_last_type_variables pc.base let local_argnames (pc:t): int array = Proof_table.local_argnames pc.base let local_formals (pc:t): formals0 = Proof_table.local_formals pc.base let local_fgs (pc:t): formals0 = Proof_table.local_fgs pc.base let count_base (pc:t): int = Proof_table.count pc.base let count (pc:t): int = Ass_seq.count pc.terms let is_consistent (pc:t): bool = count_base pc = count pc let count_previous (pc:t): int = Proof_table.count_previous pc.base let count_global(pc:t): int = Proof_table.count_global pc.base let imp_id(pc:t): int = Proof_table.imp_id pc.base let term (i:int) (pc:t): term = assert (i < count pc); assert (count pc <= count_base pc); Proof_table.local_term i pc.base let depth (pc:t): int = pc.depth let trace_prefix_0 (pc:t): string = assert (not (is_global pc)); String.make (3 + 2*(pc.depth-1)) ' ' let trace_prefix (pc:t): string = String.make (3 + 2*pc.depth) ' ' let trace_pop (pc:t): unit = printf "%send\n" (trace_prefix_0 pc) let pop (pc:t): t = assert (is_local pc); match pc.prev with None -> assert false | Some x -> x let trace_push (pc:t): unit = let str = Proof_table.last_arguments_string pc.base in let prefix = trace_prefix_0 pc in if str <> "" then printf "%sall%s\n" prefix str; printf "%srequire\n" prefix let push_slots (nbenv:int) (pc:t): unit = pc.entry.slots <- if nbenv=0 then Array.copy pc.entry.slots else let len = Array.length pc.entry.slots in Array.init (len+1) (fun i -> if i<len then let sd = pc.entry.slots.(i) in {sd with ndown = sd.ndown+nbenv} else {ndown=0; sprvd=TermMap.empty}) let push0 (base:Proof_table.t) (pc:t): t = let nbenv = Proof_table.count_variables base and nargs = Proof_table.count_last_variables base in let var_defs = Array.init nbenv (fun i -> if i < nargs then {definition = None; used = []} else pc.var_defs.(i-nargs) ) in let res = {pc with base = base; terms = Ass_seq.clone pc.terms; work = pc.work; depth = 1 + pc.depth; count0 = count pc; entry = copied_entry pc.entry; var_defs = var_defs; prev = Some pc} in push_slots nbenv res; if res.trace then trace_push res; res let push (entlst:entities list withinfo) (rt:return_type) (is_pred:bool) (is_func:bool) (rvar: bool) (pc:t): t = let base = Proof_table.push entlst rt is_pred is_func rvar pc.base in push0 base pc let push_typed (fargs:Formals.t) (fgs:Formals.t) (rvar:bool) (pc:t): t = let base = Proof_table.push_typed fargs fgs rvar pc.base in push0 base pc let push_typed0 (fargs:Formals.t) (fgs:Formals.t) (pc:t): t = push_typed fargs fgs false pc let push_empty (pc:t): t = let base = Proof_table.push_empty pc.base in push0 base pc let arguments_string (pc:t): string = Context.arguments_string (context pc) let rec global (pc:t): t = if is_global pc then pc else global (pop pc) let type_of_term (t:term) (pc:t): type_term = Context.type_of_term t (context pc) let rule_data (idx:int) (pc:t): RD.t = assert (idx < count pc); Ass_seq.elem idx pc.terms let is_fully_specialized (idx:int) (pc:t): bool = RD.is_fully_specialized (rule_data idx pc) let is_assumption (i:int) (pc:t): bool = assert (i < count pc); Proof_table.is_assumption i pc.base let is_local_assumption (i:int) (pc:t): bool = Proof_table.is_local_assumption i pc.base let count_local_assumptions (pc:t): int = Proof_table.count_local_assumptions pc.base let tvars (pc:t): Tvars.t = Context.tvars (context pc) let signature (pc:t): Signature.Sign.t = Context.signature (context pc) let string_of_term (t:term) (pc:t): string = Context.string_of_term t (context pc) let string_long_of_term (t:term) (pc:t): string = Context.string_long_of_term t (context pc) let string_of_term_anon (t:term) (nb:int) (pc:t): string = Context.string_of_term0 t true false nb (context pc) let string_of_term_i (i:int) (pc:t): string = assert (i < count pc); Proof_table.string_of_term_i i pc.base let string_long_of_term_i (i:int) (pc:t): string = assert (i < count pc); Proof_table.string_long_of_term_i i pc.base let string_of_term_array (args: term array) (pc:t): string = "[" ^ (String.concat "," (List.map (fun t -> string_of_term t pc) (Array.to_list args))) ^ "]" let string_of_tvs (pc:t): string = Class_table.string_of_tvs (tvars pc) (class_table pc) let string_of_type (tp:type_term) (pc:t): string = Context.string_of_type tp (context pc) let string_of_ags (ags:agens) (pc:t): string = Context.string_of_ags ags (context pc) let is_visible (i:int) (pc:t): bool = not (is_interface_check pc) || let ft = feature_table pc and t,c = Proof_table.term i pc.base in let nb = Context.count_variables c in Feature_table.is_term_visible t nb ft let split_implication (t:term) (pc:t): term * term = Proof_table.split_implication t pc.base let implication (a:term) (b:term) (pc:t): term = Proof_table.implication a b pc.base let negation (a:term) (pc:t): term = let nb = nbenv pc in Term.unary (nb + Constants.not_index) a let disjunction (a:term) (b:term) (pc:t): term = let nb = nbenv pc in Term.binary (nb + Constants.or_index) a b let false_constant (pc:t): term = let nb = nbenv pc in Feature_table.false_constant nb let negation_expanded (a:term) (pc:t): term = implication a (false_constant pc) pc let split_general_implication_chain (t:term) (pc:t): Formals.t * Formals.t * term list * term = Context.split_general_implication_chain t (context pc) let all_quantified (tps:Formals.t) (fgs:Formals.t) (t:term) (pc:t): term = Proof_table.all_quantified tps fgs t pc.base let prenex_term (t:term) (pc:t): term = Proof_table.prenex_term t pc.base let implication_chain (ps:term list) (tgt:term) (pc:t): term = Proof_table.implication_chain ps tgt pc.base let assumptions (pc:t): term list = Proof_table.assumptions pc.base let assumption_indices (pc:t): int list = Proof_table.assumption_indices pc.base let assumptions_chain (tgt:term) (pc:t): term = implication_chain (List.rev (assumptions pc)) tgt pc let assumptions_for_variables_0 (pc:t) : int list * int = let nvars = Array.length vars in assert (0 < nvars); let var_max = Array.fold_left (fun v i -> max v i) (-1) vars in let rec collect (nargs:int) (ass:int list) (pc:t): int list * int = let idx_lst_rev = assumption_indices pc in let ass = List.rev_append idx_lst_rev ass in let nargs_new = nargs + count_last_variables pc in if var_max < nargs_new then ass, nargs_new else collect nargs_new ass (pop pc) in collect 0 [] pc let assumptions_for_variables (goal: term) (pc:t) : int list * int list * int = let ass, nvars = assumptions_for_variables_0 ind_vars pc in let used_lst = let used_lst_rev = List.fold_left (fun lst idx -> Term.used_variables_0 (term idx pc) nvars lst) (Term.used_variables goal nvars) ass in let insp_vars = Array.of_list insp_vars in Array.sort Stdlib.compare insp_vars; List.filter (fun i -> try ignore(Search.binsearch i insp_vars); false with Not_found -> true ) (List.rev used_lst_rev) in ass, used_lst, nvars let work (pc:t): int list = pc.work let has_work (pc:t): bool = pc.work <> [] let clear_work (pc:t): unit = pc.work <- [] let has_result (pc:t): bool = Proof_table.has_result pc.base let has_result_variable (pc:t): bool = Proof_table.has_result_variable pc.base let seed_function (pc:t): int -> int = Feature_table.seed_function (feature_table pc) let is_well_typed (t:term) (pc:t): bool = Context.is_well_typed t (context pc) let transformed_to_current (t:term) (idx:int) (pc:t): term = Proof_table.transformed_to_current t idx pc.base let unify_0 (t:term) (tab:Term_table.t) (pc:t): (int * Term_sub.t) list = List.rev (Term_table.unify t (nbenv pc) (seed_function pc) tab) let args_and_ags_of_substitution (idx:int) (sub:Term_sub.t) (pc:t) : arguments * agens = let rd = rule_data idx pc in let args = Term_sub.arguments (Term_sub.count sub) sub in try let ags = RD.verify_specialization args (context pc) rd in args,ags with Not_found -> printf " can not unify types of actual arguments with formal arguments\n " ; printf " actuals % s\n " ( string_of_term_array args pc ) ; printf " rule % s\n " ( string_long_of_term_i idx pc ) ; printf " actuals %s\n" (string_of_term_array args pc); printf " rule %s\n" (string_long_of_term_i idx pc);*) raise Not_found let unify (t:term) (tab:Term_table.t) (pc:t) : (int * arguments * agens) list = let lst = unify_0 t tab pc in List.fold_left (fun lst (idx,sub) -> try let args,ags = args_and_ags_of_substitution idx sub pc in (idx,args,ags) :: lst with Not_found -> lst ) [] lst let unify_with_0 (t:term) (nargs:int) (tab:Term_table.t) (pc:t) : (int * Term_sub.t) list = let nvars = nbenv pc and tps,_,t0 = Term.all_quantifier_split_1 t in let nb = Formals.count tps in Term_table.unify_with t0 nb nargs nvars true (seed_function pc) tab let unify_with (t:term) (nargs:int) (tps:types) (tab:Term_table.t) (pc:t) : (int * arguments) list = let lst = unify_with_0 t nargs tab pc in List.fold_left (fun lst (idx,sub) -> let args = Term_sub.arguments (Term_sub.count sub) sub in let args = Array.map (fun t -> transformed_to_current t idx pc) args in let argtps = Array.map (fun t -> type_of_term t pc) args in if Term.equivalent_array tps argtps then (idx,args)::lst else lst ) [] lst let is_trace_extended (pc:t): bool = 3 < pc.verbosity let trace_term (t:term) (rd:RD.t) (search:bool) (dup:bool) (pc:t): unit = let str = string_long_of_term t pc and cnt = count pc and prefix = trace_prefix pc in assert (cnt + 1 = count_base pc); let ext = if is_trace_extended pc then let pt = Proof_table.proof_term cnt pc.base in let ptstr = Proof_term.short_string pt and rdstr = RD.short_string rd and cntstr = (string_of_int cnt) ^ (if is_global pc then "global" else "") in let str = (if search then "" else "n") ^ (if dup then "d" else "") in let rstr = str ^ rdstr in cntstr ^ "'" ^ ptstr ^ (if rstr <> "" then "," else "") ^ rstr ^ "' " else "" in printf "%s%s%s\n" prefix ext str; if is_trace_extended pc then printf "%s\t%s\n" prefix (Term.to_string t); if is_global pc then printf "\n" let find (t:term) (pc:t): int = let tps,fgs,t0 = Term.all_quantifier_split_1 t in let n = Formals.count tps and fgtps = Formals.types fgs in let nfgs = Array.length fgtps in let sublst = Term_table.find t0 n (nbenv pc) (seed_function pc) pc.entry.prvd in let idx,sub = List.find (fun (idx,sub) -> assert (Term_sub.is_empty sub); if nfgs = 0 then true else let _,fgs,_ = Term.all_quantifier_split_1 (term idx pc) in let fgtps_found = Formals.types fgs in Array.length fgtps_found = nfgs && Term.equivalent_array fgtps fgtps_found ) sublst in idx let has (t:term) (pc:t): bool = try ignore(find t pc); true with Not_found -> false let has_in_view (t:term) (pc:t): bool = assert (is_global pc); try let i = find t pc in assert (i < count_global pc); if is_private pc then true else let gdesc = Seq.elem i pc.gseq in gdesc.pub with Not_found -> false let equal_symmetry (pc:t): int = find (Feature_table.equal_symmetry_term ()) (global pc) let leibniz_term (pc:t): int = find (Feature_table.leibniz_term ()) (global pc) let split_equality (t:term) (pc:t): int * term * term = Proof_table.split_equality t 0 pc.base let split_specific_equality (t:term) (pc:t): term * term = let nargs,left,right = split_equality t pc in if nargs = 0 then left, right else raise Not_found let equality_data (i:int) (pc:t): int * term * term = assert (count_variables pc = Proof_table.nbenv_term i pc.base); let rd = rule_data i pc in let nargs, eq_id, left, right = Rule_data.equality_data rd in if nargs = 0 then eq_id, left, right else raise Not_found let add_variable_definition (v:int) (idx:int) (pc:t): unit = assert (v < count_variables pc); if pc.trace then printf "%svariable definition %d %s\n" (trace_prefix pc) idx (string_of_term_i idx pc); let def = pc.var_defs.(v) in assert (not (Option.has def.definition)); pc.var_defs.(v) <- {def with definition = Some idx} let add_variable_usage (v:int) (idx:int) (pc:t): unit = assert (v < count_variables pc); let def = pc.var_defs.(v) in assert (not (Option.has def.definition)); if List.mem idx def.used then () else pc.var_defs.(v) <- {def with used = idx :: def.used} let variable_definition (v:int) (pc:t): int = The index of the defining assertin of the variable [ v ] . Raise [ Not_found ] if the variable has no definition . if the variable has no definition. *) assert (v < count_variables pc); match pc.var_defs.(v).definition with None -> raise Not_found | Some idx -> idx let variable_has_definition (v:int) (pc:t): bool = try ignore(variable_definition v pc); true with Not_found -> false let extended_variable_definition (v:int) (pc:t): int * term = try let idx = variable_definition v pc in let t = term idx pc in let left,right = split_specific_equality t pc in assert (left = Variable v); idx, right with Not_found -> let get_variable_definitions (t:term) (pc:t): (int*int*term) list = let nvars = count_variables pc in let filter v = v < nvars && variable_has_definition v pc in let get_used t lst = Term.used_variables_filtered_0 t filter false lst in let get_defs var_lst = List.rev_map (fun v -> let idx,exp = extended_variable_definition v pc in idx,v,exp ) var_lst in let rec get_definitions (rcnt:int) (vars_new: int list) (defs:(int*int*term) list) : (int*int*term) list = assert (rcnt <= nvars); match vars_new with [] -> defs | _ -> let vars_new, defs = List.fold_left (fun (vs,defs) (idx,v,exp) -> let vs = get_used exp vs and defs = (idx,v,exp)::defs in vs,defs ) ([],defs) (get_defs vars_new) in get_definitions (rcnt+1) vars_new defs in get_definitions 0 (get_used t []) [] let complexity (t:term) (pc:t): int = Context.complexity t (context pc) let add_to_equalities (t:term) (idx:int) (pc:t): unit = let nbenv = nbenv pc in try let nargs, left,right = split_equality t pc in let is_simpl = Term.nodes right < Term.nodes left else complexity right pc < complexity left pc in if is_simpl then begin printf " add_to_equalities % d % s < % s>\n " idx ( string_of_term t pc ) ( Term.to_string t ) ; idx (string_of_term t pc) (Term.to_string t);*) pc.entry.left <- Term_table.add left nargs nbenv idx (seed_function pc) pc.entry.left end with Not_found -> () let has_public_deferred (t:term) (pc:t): bool = assert (is_global pc); try let sublst = Term_table.find t 0 0 (seed_function pc) pc.def_ass in match sublst with [] -> false | [idx,sub] -> true | _ -> with Not_found -> false let add_to_public_deferred (t:term) (idx:int) (pc:t): unit = assert (is_global pc); if not (has_public_deferred t pc) then let sfun = seed_function pc in pc.def_ass <- Term_table.add t 0 0 idx sfun pc.def_ass let add_to_proved (t:term) (idx:int) (pc:t): unit = let sfun = seed_function pc in let tps,_,t0 = Term.all_quantifier_split_1 t in let n = Formals.count tps in pc.entry.prvd <- Term_table.add t0 n (count_variables pc) idx sfun pc.entry.prvd let add_to_forward (rd:RD.t) (idx:int) (pc:t): unit = if not (RD.is_forward rd) then () else begin let nargs,_,nbenv,t = RD.schematic_premise rd in pc.entry.fwd <- Term_table.add t nargs nbenv idx (seed_function pc) pc.entry.fwd end let add_to_backward (rd:RD.t) (idx:int) (pc:t): unit = if not (RD.is_backward rd) then begin () end else begin let nargs,nbenv,t = RD.schematic_target rd in pc.entry.bwd <- Term_table.add t nargs nbenv idx (seed_function pc) pc.entry.bwd end let add_last_to_tables (pc:t): unit = assert (0 < count pc); let idx = count pc - 1 in let t = term idx pc and rd = rule_data idx pc in assert (not (has t pc)); add_to_proved t idx pc; add_to_forward rd idx pc; add_to_backward rd idx pc; add_to_equalities t idx pc; assert (has t pc) let filter_tables (pred:int->bool) (pc:t): unit = assert (is_global pc); let e = pc.entry in e.prvd <- Term_table.filter pred e.prvd; e.bwd <- Term_table.filter pred e.bwd; e.fwd <- Term_table.filter pred e.fwd; e.left <- Term_table.filter pred e.left let filter_and_remap_tables (pred:int->bool) (pc:t): unit = assert (is_global pc); let e = pc.entry and f = seed_function pc in e.prvd <- Term_table.filter_and_remap pred f e.prvd; e.bwd <- Term_table.filter_and_remap pred f e.bwd; e.fwd <- Term_table.filter_and_remap pred f e.fwd; e.left <- Term_table.filter_and_remap pred f e.left let add_to_work (idx:int) (pc:t): unit = pc.work <- idx :: pc.work let add_last_to_work (pc:t): unit = assert (0 < count pc); if not (is_global pc || is_interface_use pc) then let idx = count pc - 1 in pc.work <- idx :: pc.work let get_rule_data (t:term) (pc:t): RD.t = RD.make t (context pc) let raw_add0 (t:term) (rd:RD.t) (search:bool) (pc:t): int = assert (count pc + 1 = count_base pc); let cnt = count pc in let res = try find t pc with Not_found -> cnt in let dup = res <> cnt in if pc.trace && ((search && not dup) || is_trace_extended pc) then trace_term t rd search dup pc else if is_global pc && verbosity pc > 1 then begin printf "\n%s\n" (string_of_term t pc); flush_all () end; Ass_seq.push rd pc.terms; if search && not dup then begin add_last_to_tables pc; if not dup && is_global pc then Feature_table.add_involved_assertion cnt t (feature_table pc); List.iter (fun (i,_) -> add_to_work i pc; if is_tracing pc then begin printf "reevaluate %s\n" (string_of_term_i i pc); printf " because of %s\n" (string_of_term t pc) end ) (unify_0 t pc.entry.reeval pc) end; if not dup && is_global pc then Induction.put_assertion res t (context pc); res let raw_add (t:term) (search:bool) (pc:t): int = raw_add0 t (get_rule_data t pc) search pc let raw_add_work (t:term) (search:bool) (pc:t): int = let idx = raw_add t search pc in if search && idx + 1 = count pc then add_last_to_work pc; idx let arguments_of_sub (sub:Term_sub.t): term array = let nargs = Term_sub.count sub in let args = Term_sub.arguments nargs sub in args let specialized (idx:int) (args:arguments) (ags:agens) 0 : match , 1 : fwd , 2 : bwd (pc:t): int = The schematic rule [ idx ] specialized by the arguments [ args ] and the actual generics [ ags ] . Note : The arguments [ args ] are valid in the current enviroment ! actual generics [ags]. Note: The arguments [args] are valid in the current enviroment! *) assert (is_consistent pc); assert (idx < count pc); let rd = rule_data idx pc in if RD.is_specialized rd then begin if Array.length args <> 0 then begin printf "specialize\n"; printf " idx %d term %s\n" idx (string_long_of_term_i idx pc); printf " |args| %d\n" (Array.length args); end; assert (Array.length args = 0); idx end else if Array.length args = 0 && RD.count_args_to_specialize rd > 0 then idx else begin let rd = RD.specialize rd args ags idx (context pc) in let t = RD.term rd in try find t pc with Not_found -> let search = if reason = 0 then false else if reason = 1 then not (RD.is_forward rd) && RD.is_backward rd else true in Proof_table.add_specialize t idx args ags pc.base; raw_add0 t rd search pc end let find_schematic (t:term) (nargs:int) (pc:t): int * agens = let sublst = unify t pc.entry.prvd pc in let sublst = List.filter (fun (_,args,_) -> Array.length args = nargs && interval_for_all (fun i -> args.(i) = Variable i ) 0 nargs ) sublst in match sublst with [] -> raise Not_found | (idx,_,ags):: tail -> idx, ags let find_match (g:term) (pc:t): int = try find g pc with Not_found -> let sublst = unify g pc.entry.prvd pc in if sublst = [] then raise Not_found; try let idx,_,_ = List.find (fun (_,args,_) -> Array.length args = 0) sublst in idx with Not_found -> let idx,args,ags = List.hd sublst in try specialized idx args ags 0 pc with Not_found -> let find_match_list (lst:term list) (pc:t): int list = List.fold_left (fun lst t -> (find_match t pc) :: lst) [] (List.rev lst) let simplified_term (t:term) (below_idx:int) (pc:t): term * Eval.t * bool = let rec simp t = let do_subterms t = let simpl_args args modi = let arglst, modi = Array.fold_left (fun (arglst,modi) a -> let asimp,ae,amodi = simp a in (asimp,ae)::arglst, modi || amodi) ([],modi) args in let args, argse = Myarray.split (Array.of_list (List.rev arglst)) in args, argse, modi in match t with Variable _ -> t, Eval.Term t, false | VAppl (i,args,ags,oo) -> let args, argse, modi = simpl_args args false in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), modi | Application(f,args,inop) -> let fsimp,fe,fmodi = simp f in let args, argse, modi = simpl_args args fmodi in let res = Application(fsimp, args, inop) in let rese = Eval.Term res in res, Eval.Apply(fe,argse,rese), modi | Lam _ | QExp _ | Ifexp _ | Asexp _ | Inspect _ | Indset _ -> t, Eval.Term t, false in let sublst = unify t pc.entry.left pc in let sublst = List.filter (fun (idx,sub,_) -> idx < below_idx && Array.length sub = 0) sublst in match sublst with (idx,_,ags) :: _ -> let eq = term idx pc in let nargs, left, right = Proof_table.split_equality eq 0 pc.base in assert (nargs = 0); assert (Term.equivalent t left); right, Eval.Simpl(Eval.Term t,idx,[||],ags), true | _ -> do_subterms t in let tsimp, te, modi = simp t in let ta, tb = Proof_table.reconstruct_evaluation te pc.base in assert (Term.equivalent ta t); if not (Term.equivalent tb tsimp) then begin printf "simplified_term %s\n" (string_of_term t pc); printf " tb %s\n" (string_of_term tb pc); printf " tsimp %s\n" (string_of_term tsimp pc); assert (is_well_typed t pc); end; assert (Term.equivalent tb tsimp); assert (modi = not (Term.equivalent tsimp t)); if modi then begin printf " simplification found\n " ; printf " term % s\n " ( string_of_term t pc ) ; printf " simpl % s\n " ( string_of_term tsimp pc ) ; end ; printf "simplification found\n"; printf " term %s\n" (string_of_term t pc); printf " simpl %s\n" (string_of_term tsimp pc); end;*) tsimp, te, modi let triggers_eval (i:int) (nb:int) (pc:t): bool = Does the term [ Variable i ] trigger a full evaluation when used as a top level function term , i.e. is it a variable which describes a function which has no expansion and is not owned by BOOLEAN ? level function term, i.e. is it a variable which describes a function which has no expansion and is not owned by BOOLEAN? *) let nbenv = nb + nbenv pc and ft = feature_table pc in i < nbenv || let idx = i - nbenv in idx = Constants.or_index || Feature_table.owner idx ft <> Constants.boolean_class let beta_reduce (n:int) (t:term) (tup_tp:type_term) (args:term array) (nb:int) (pc:t) : term = Proof_table.beta_reduce n t tup_tp args nb pc.base let beta_reduce_term (t:term) (pc:t): term = match t with | Application (Lam(tps,_,_,t0,_), args, _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in beta_reduce n t0 tup_tp args 0 pc | _ -> printf "beta_reduce_term %s\n" (string_long_of_term t pc); let make_lambda (tps:Formals.t) (fgs:Formals.t) (ps: term list) (t:term) (rt: type_term option) (pc:t) : term = let c = context pc in Context.make_lambda tps fgs ps t rt c let make_application (f:term) (args:term array) (tup:type_term) (nb:int) (pc:t) : term = let c = context pc in Context.make_application f args tup nb c let is_inductive_set (i:int) (pc:t): bool = Proof_table.is_inductive_set i pc.base let inductive_set (t:term) (pc:t): term = Proof_table.inductive_set t pc.base let definition_term (i:int) (nb:int) (ags:agens) (pc:t): int * int array * term = if i < nb || is_inductive_set (i-nb) pc then raise Not_found else Proof_table.definition_term i nb ags pc.base let arity (i:int) (nb:int) (pc:t): int = Proof_table.arity i nb pc.base exception Undecidable of term exception No_evaluation of term option exception No_branch_evaluation of term option let decide (t:term) (pc:t): bool * int = try true, find_match t pc with Not_found -> try false, find_match (negation_expanded t pc) pc with Not_found -> raise (Undecidable t) let string_of_term_option (t:term option) (pc:t): string = match t with | None -> "None" | Some t -> "Some(" ^ string_of_term t pc ^ ")" let chain_term_option (t1:term option) (t2:term option): term option = match t1 with | None -> t2 | Some _ -> t1 let eval_term (t:term) (pc:t): term * Eval.t * term option = let rec eval (t:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = if depth > 500 then raise (No_evaluation None); let depth = depth + 1 in let nvars = nbenv pc in let domain_id = nvars + Constants.domain_index in match t with Variable i -> assert (i < nvars); raise (No_evaluation None) | VAppl (i,[|Lam(tps,fgs,pres,t0,rt)|],ags,inop) when i = domain_id -> assert (rt <> None); let args = [|Eval.Term (Lam(tps,fgs,pres,t0,rt))|] and dom = Context.domain_of_lambda tps fgs pres 0 (context pc) in dom, Eval.Exp(i, ags, args, Eval.Term dom),None | VAppl(i,args,ags,oo) -> eval_vappl t i args ags oo lazy_ depth pc | Application (Lam(tps,fgs,_,t0,_), args, inop) -> let tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) and n = Formals.count tps in let reduct = beta_reduce n t0 tup_tp args 0 pc and te = Eval.Term t in begin try let res,rese,cond = maybe_eval reduct lazy_ depth pc in let e = Eval.Beta (te, rese) in res, e, cond with No_branch_evaluation cond -> raise (No_evaluation cond) end | Application (f,args,inop) -> assert (Array.length args = 1); begin try let f_exp,fe,fcond = eval f lazy_ (depth - 1) pc and argse = [| Eval.Term args.(0) |] in let t_exp,te,tcond = maybe_eval (Application(f_exp,args,inop)) lazy_ depth pc in let cond = match fcond with | None -> tcond | Some _ -> fcond in t_exp, Eval.Apply(fe,argse,te), cond with No_evaluation cond -> if depth = 1 then let args,argse,cond = eval_args args (depth - 1) pc in let t_exp = Application(f,args,inop) in let fe = Eval.Term f and te = Eval.Term t_exp in t_exp, Eval.Apply(fe, argse,te), cond else raise (No_evaluation cond) end | Lam _ -> raise (No_evaluation None) | QExp _ -> raise (No_evaluation None) | Ifexp (c, a, b) -> eval_if c a b lazy_ depth pc | Asexp (insp, tps, pat) -> eval_as t insp tps pat lazy_ depth pc | Inspect (insp, cases) -> eval_inspect t insp cases lazy_ depth pc | Indset _ -> raise (No_evaluation None) and eval_vappl (t:term) (i:int) (args:arguments) (ags:agens) (oo:bool) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let nvars = nbenv pc in let and_id = nvars + Constants.and_index and or_id = nvars + Constants.or_index and imp_id = nvars + Constants.implication_index in let is_lazy i = i = and_id || i = or_id || i = imp_id in try let n,nms,t0 = definition_term i 0 ags pc and argse = Array.map (fun t -> Eval.Term t) args in assert (n = Array.length args); let t_expanded = Proof_table.apply_term t0 args 0 pc.base in begin try let res, rese,cond = maybe_eval t_expanded lazy_ depth pc in res, Eval.Exp(i,ags,argse,rese), cond with No_branch_evaluation cond_t -> try let args,argse,cond = eval_args args depth pc in let cond = chain_term_option cond_t cond in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond with No_evaluation cond -> let cond = chain_term_option cond_t cond in let argse = Array.map (fun t -> Eval.Term t) args in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond let args , , cond = eval_args args depth pc in let cond = match cond_t with | None - > cond | Some _ - > cond_t in VAppl(i , args , ags , oo ) , Eval . VApply(i , argse , ags ) , cond let cond = match cond_t with | None -> cond | Some _ -> cond_t in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond*) end if Array.length args = 0 || (lazy_ && depth > 1) || is_lazy i then raise (No_evaluation None) else let args,argse,cond = eval_args args depth pc in VAppl(i,args,ags,oo), Eval.VApply(i,argse,ags), cond and eval_args (args:arguments) (depth:int) (pc:t) : arguments * Eval.t array * term option = let len = Array.length args in let args = Array.copy args and argse = Array.map (fun t -> Eval.Term t) args in let modi,cond = interval_fold (fun (modi,cond) i -> try let t, te, cond_i = eval args.(i) false depth pc in args.(i) <- t; argse.(i) <- te; true, if cond = None then cond_i else cond with No_evaluation cond_i -> if cond = None then modi,cond_i else modi, cond ) (false,None) 0 len in if modi then args, argse, cond else raise (No_evaluation cond) and eval_if (cond:term) (a:term) (b:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let conde = Eval.Term cond in try let res,idx = decide cond pc in if res then let fst,fste,fst_cond = maybe_eval a lazy_ depth pc in fst, Eval.If (true, idx, [|conde; fste; Eval.Term b|]), fst_cond else let snd,snde,snd_cond = maybe_eval b lazy_ depth pc in snd, Eval.If (false, idx, [|conde; Eval.Term a; snde|]), snd_cond with Undecidable cond -> raise (No_branch_evaluation (Some cond)) and eval_inspect (t:term) (insp:term) (cases: (formals*term*term) array) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let insp, inspe, icond = maybe_eval insp true depth pc and c = context pc in match Pattern.decide_inspect insp cases c with | None -> raise (No_branch_evaluation None) | Some (i, args, pres) -> try nyi : include in proof term let _,_,res = cases.(i) in let res = Term.apply res args in let res,rese,rcond = maybe_eval res lazy_ depth pc in let cond = chain_term_option icond rcond in res, Eval.Inspect(t,inspe,i,rese), cond with Not_found -> let pre = try List.find (fun pre -> try ignore(find_match pre pc); false with Not_found -> true) pres with Not_found -> in raise (No_branch_evaluation (Some pre)) and eval_as (t:term) (insp:term) (tps:types) (pat:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option = let nvars = nbenv pc in let n = Array.length tps in let insp,inspe,cond = maybe_eval insp lazy_ depth pc in let c = context pc in let undecide () = Pattern.evaluated_as_expression t (context pc), Eval.AsExp t, cond in let find_pres pres = try find_match_list pres pc with Not_found -> raise Support.Undecidable in try begin match Pattern.unify_with_pattern insp n pat c with | None -> undecide () | Some (Error (pres) ) -> nyi : include in proof term Feature_table.false_constant nvars, Eval.As(false,inspe,tps,pat), cond | Some ( Ok (args,pres) ) -> nyi : include in proof term Feature_table.true_constant nvars, Eval.As(true,inspe,tps,pat), None end with Support.Undecidable -> undecide () and maybe_eval (t:term) (lazy_:bool) (depth:int) (pc:t) : term * Eval.t * term option= try eval t lazy_ depth pc with No_evaluation cond -> t, Eval.Term t, cond in try eval t true 0 pc with No_branch_evaluation cond -> raise (No_evaluation cond) let evaluated_term (t:term) (pc:t): term * Eval.t * term option * bool = try let t,e,cond = eval_term t pc in t, e, cond, true with No_evaluation cond -> t, Eval.Term t, cond, false let add_mp0 (t:term) (i:int) (j:int) (search:bool) (pc:t): int = let cnt = count pc and rd = RD.drop (rule_data j pc) (context pc) in Proof_table.add_mp t i j pc.base; (if RD.is_implication rd then let _ = raw_add0 t rd search pc in () else let _ = raw_add t search pc in ()); cnt let add_mp (i:int) (j:int) (search:bool) (pc:t): int = assert (i < count pc); assert (j < count pc); let rdj = rule_data j pc and c = context pc in if not (RD.is_specialized rdj) then printf "add_mp %s\n" (string_long_of_term_i j pc); assert (RD.is_specialized rdj); assert (RD.is_implication rdj); let t = RD.term_b rdj c in if not (Term.equivalent (term i pc) (RD.term_a rdj c)) then begin printf "add_mp premise %d %s %s\n" i (string_long_of_term_i i pc) (Term.to_string (term i pc)); printf " implication %d %s %s\n" j (string_long_of_term_i j pc) (Term.to_string (term j pc)); printf " term_a %s %s\n" (string_long_of_term (RD.term_a rdj c) pc) (Term.to_string (RD.term_a rdj c)) end; assert (Term.equivalent (term i pc) (RD.term_a rdj c)); try find t pc with Not_found -> add_mp0 t i j search pc let try_add_beta_reduced (idx:int) (search:bool) (pc:t): int = let t = term idx pc in match t with | Application(Lam(tps,fgs,_,t0,_), [|arg|], _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in let reduct = beta_reduce n t0 tup_tp [|arg|] 0 pc in let pt = Eval(idx, Eval.Beta (Eval.Term t, Eval.Term reduct)) in Proof_table.add_proved reduct pt 0 pc.base; raw_add_work reduct search pc | _ -> raise Not_found let add_beta_reduced (idx:int) (search:bool) (pc:t): int = try try_add_beta_reduced idx search pc with Not_found -> printf "add_beta_reduced\n"; printf " The term %d \"%s\" is not a beta redex\n" idx (string_of_term_i idx pc); let add_beta_redex (t:term) (idx:int) (search:bool) (pc:t): int = match t with | Application(Lam(tps,fgs,_,t0,_), [|arg|], _) -> let n = Formals.count tps and tup_tp = Context.tuple_type_of_types (Formals.types tps) (context pc) in let reduced = beta_reduce n t0 tup_tp [|arg|] 0 pc in let e1,e2 = Eval.Term t, Eval.Term reduced in in let impl = implication reduced t pc in Proof_table.add_proved impl pt 0 pc.base; let idx_impl = raw_add impl false pc in add_mp idx idx_impl search pc | _ -> assert false let add_some_elim (i:int) (search:bool) (pc:t): int = let t = try Proof_table.someelim i pc.base with Not_found -> assert false in Proof_table.add_proved t (Someelim i) 0 pc.base; raw_add t search pc let add_some_elim_specialized (i:int) (goal:term) (search:bool) (pc:t): int = let idx = add_some_elim i search pc in specialized idx [|goal|] [||] 0 pc let add_mp_fwd (i:int) (j:int) (pc:t): unit = let rdj = rule_data j pc in if RD.is_forward rdj then begin let cnt = count pc in let res = add_mp i j true pc in if res = cnt then add_last_to_work pc end let is_nbenv_current (i:int) (pc:t): bool = assert (i < count pc); let nbenv_i = RD.count_variables (rule_data i pc) in nbenv_i = nbenv pc let add_consequence (i:int ) (j:int) (args:arguments) (ags:agens) (pc:t): unit = assert (is_consistent pc); assert (i < count pc); assert (j < count pc); let nbenv_sub = Proof_table.nbenv_term i pc.base in assert (nbenv_sub <= nbenv pc); try let j = specialized j args ags 1 pc in add_mp_fwd i j pc with Not_found -> () let add_consequences_premise (i:int) (pc:t): unit = assert (i < count pc); if not (is_nbenv_current i pc) then printf "add_consequences_premise %s\n" (string_of_term_i i pc); assert (is_nbenv_current i pc); assert (not (RD.is_intermediate (rule_data i pc))); let nbenv = nbenv pc in let t,c_t = Proof_table.term i pc.base in assert (nbenv = Context.count_variables c_t); let sublst = unify t pc.entry.fwd pc in let sublst = List.rev sublst in List.iter (fun (idx,sub,ags) -> assert (is_consistent pc); assert (idx < count pc); if is_visible idx pc then add_consequence i idx sub ags pc) sublst let add_consequences_implication (i:int) (rd:RD.t) (pc:t): unit = assert (i < count pc); assert (is_nbenv_current i pc); let rd = rule_data i pc and nbenv = nbenv pc in assert (RD.is_implication rd); assert (not (RD.is_generic rd)); let gp1,tps,nbenv_a,a = RD.schematic_premise rd in assert (nbenv_a = nbenv); if RD.is_forward rd then begin let sublst = unify_with a gp1 tps pc.entry.prvd pc in let sublst = List.rev sublst in List.iter (fun (idx,args) -> if not (RD.is_intermediate (rule_data idx pc)) then add_consequence idx i args [||] pc ) sublst end else () try add_mp_fwd idx i pc let sublst = unify a pc.entry.prvd pc in match sublst with [] -> () | (idx,sub,ags)::_ -> begin try let idx_premise = specialized idx sub ags 1 pc in add_mp_fwd idx_premise i pc with Not_found -> () end let add_fwd_evaluation (t:term) (i:int) (e:Eval.t) (full:bool) (pc:t): int = try find t pc with Not_found -> let rd = get_rule_data t pc in Proof_table.add_eval t i e pc.base; let res = raw_add0 t rd full pc in (); if full then add_last_to_work pc; res let add_consequences_evaluation (i:int) (pc:t): unit = let t = term i pc in let add_eval t e = add_fwd_evaluation t i e true pc in let t1,e,modi = simplified_term t i pc in if modi then ignore(add_eval t1 e); let t1,e,reeval_term,modi = evaluated_term t pc in let idx = if modi then add_eval t1 e else i in begin match reeval_term with | None -> () | Some cond -> if is_tracing pc then begin printf "more evaluation would be possible of\n"; printf " %s\n" (string_of_term t pc); printf "if the following condition where decidable\n"; printf " %s\n" (string_of_term cond pc) end; let nbenv = count_variables pc in pc.entry.reeval <- Term_table.add cond 0 nbenv idx (seed_function pc) pc.entry.reeval; pc.entry.reeval <- let cond = negation_expanded cond pc in Term_table.add cond 0 nbenv idx (seed_function pc) pc.entry.reeval; end let add_consequences_someelim (i:int) (pc:t): unit = try let some_consequence = Proof_table.someelim i pc.base in if has some_consequence pc then () else begin Proof_table.add_someelim i some_consequence pc.base; let _ = raw_add some_consequence true pc in (); add_last_to_work pc end with Not_found -> () let type_of_term (t:term) (pc:t): type_term = Context.type_of_term t (context pc) let predicate_of_type (tp:type_term) (pc:t): type_term = Context.predicate_of_type tp (context pc) let add_assumption_or_axiom (t:term) (is_axiom: bool) (search:bool) (pc:t): int = assert (is_consistent pc); let cnt = count pc in if is_axiom then Proof_table.add_axiom t pc.base else Proof_table.add_assumption t pc.base; ignore(raw_add t search pc); if not is_axiom && search then add_last_to_work pc; cnt let add_assumption (t:term) (search:bool) (pc:t): int = add_assumption_or_axiom t false search pc let add_axiom (t:term) (pc:t): int = add_assumption_or_axiom t true false pc let specialize_induction_law (pc:t) : int = Specialize the induction law [ idx ] with the goal predicate [ p ] . An induction law has the form all(p0,x ) p01 = = > p02 = = > ... = = > x in p0 where each p0i is a constructor rule . The specialized induction law has the form p1 = = > p2 = = > ... ivar in p where p0i and p0 are specialized with ivar and p An induction law has the form all(p0,x) p01 ==> p02 ==> ... ==> x in p0 where each p0i is a constructor rule. The specialized induction law has the form p1 ==> p2 ==> ... ivar in p where p0i and p0 are specialized with ivar and p *) let sub = [|p; Variable ivar|] in let ags = try RD.verify_specialization sub (context pc) (rule_data idx pc) with Not_found -> assert false in specialized idx sub ags 0 pc let add_set_induction_law (set:term) (q:term) (elem:term) (pc:t): int = try let indlaw = Proof_table.set_induction_law set pc.base and pt = Indset_ind set in Proof_table.add_proved_0 indlaw pt pc.base; let idx = raw_add indlaw false pc in let rd = rule_data idx pc in let args = [|q;elem|] let rd = RD.specialize rd args ags idx (context pc) in assert (RD.is_specialized rd); let t = RD.term rd in Proof_table.add_specialize t idx args ags pc.base; raw_add0 t rd false pc with Not_found -> invalid_arg "Not an inductive set" let add_inductive_set_rules (fwd:bool) (t:term) (pc:t): unit = match t with Application(set,args,_) -> assert (Array.length args = 1); begin try let nme,tp,rs = let indset = inductive_set set pc in match indset with Indset(nme,tp,rs) -> nme,tp,rs | _ -> assert false in let len = Array.length rs in for i = 0 to len-1 do let rule = Term.apply rs.(i) [|set|] in if has rule pc then begin () end else begin let pt = Indset_rule (set,i) in Proof_table.add_proved_0 rule pt pc.base; ignore(raw_add rule true pc); add_last_to_work pc end done with Not_found -> () end | _ -> () let equality_swapped (i:int) (left:term) (right:term) (pc:t): int = let eq_sym = equal_symmetry pc and tp = type_of_term left pc in let eq_sym = specialized eq_sym [|left;right|] [|tp|] 0 pc in add_mp i eq_sym false pc let leibniz (i:int) (left:term) (right:term) (pc:t): int = The term at [ i ] is a equality of the form [ left = right ] . Add the term [ all(p ) p(left ) = = > p(right ) ] derived from the leibniz condition all(a , b , p ) a = b = = > p(a ) = = > p(b ) to the context and return its index . term [all(p) p(left) ==> p(right)] derived from the leibniz condition all(a,b,p) a = b ==> p(a) ==> p(b) to the context and return its index. *) let idx = leibniz_term pc and tp = type_of_term left pc in let idx = specialized idx [|left;right|] [|tp|] 0 pc in add_mp i idx false pc let can_be_variable_definition (v:int) (t:term) (pc:t): bool = not (variable_has_definition v pc) && let nvars = count_variables pc in let used = Term.used_variables t nvars in not (List.mem v used) && List.for_all (fun v -> not (variable_has_definition v pc)) used let variable_substitution_implication (v:int) (idx:int) (exp:term) (t:term) (search:bool) (pc:t) :term * int = let idx = equality_swapped idx (Variable v) exp pc in let pterm = Term.lambda_inner t v and tp = type_of_term (Variable v) pc in let ptp = predicate_of_type tp pc in let tps = Formals.make (standard_argnames 1) [|tp|] in let p = make_lambda tps Formals.empty [] pterm None pc in let redex1 = make_application p [|exp|] tp 0 pc and tr = beta_reduce 1 pterm ptp [|exp|] 0 pc and idx_leib = leibniz idx exp (Variable v) pc in let idx_leib = specialized idx_leib [|p|] [||] 0 pc in let pc0 = push_empty pc in let idx_a = add_assumption tr false pc0 in let idx_redex1 = add_beta_redex redex1 idx_a false pc0 in let idx_redex2 = add_mp idx_redex1 idx_leib false pc0 in let idx_t = add_beta_reduced idx_redex2 false pc0 in assert (Term.equivalent (term idx_t pc0) t); let imp,pt = Proof_table.discharged idx_t pc0.base in Proof_table.add_proved imp pt 0 pc.base; let res_idx = raw_add imp search pc in tr,res_idx let substitute_variable (var:int) (def_idx:int) (def_term:term) (t:term) (idx:int) (search:bool) (pc:t): int = if pc.trace then begin let prefix = trace_prefix pc in printf "%ssubstitute variable %s by %s\n" prefix (string_of_term (Variable var) pc) (string_of_term def_term pc); printf "%s in %d %s\n" prefix idx (string_of_term t pc) end; let leib = leibniz def_idx (Variable var) def_term pc leib : all(p:{T } p(var ) = = > p(def_term ) and pterm = Term.lambda_inner t var and tp = type_of_term (Variable var) pc in let tps = Formals.make (standard_argnames 1) [|tp|] in let p = make_lambda tps Formals.empty [] pterm None pc in let imp_idx = specialized leib [|p|] [||] 0 pc and redex1 = make_application p [|Variable var|] tp 0 pc in let idx_redex1 = add_beta_redex redex1 idx false pc in let idx_redex2 = add_mp idx_redex1 imp_idx false pc in let res = add_beta_reduced idx_redex2 search pc in if pc.trace then printf "%ssubstituted term %s\n" (trace_prefix pc) (string_of_term_i res pc); res let add_consequences_variable_definition (i:int) (pc:t): unit = let var_def (i:int): int * int * term = let eq_id, left, right = equality_data i pc in match left,right with Variable j, Variable k -> if can_be_variable_definition j right pc then i,j,right else if can_be_variable_definition k left pc then let i = equality_swapped i left right pc in i,k,left else raise Not_found | Variable j, _ -> if can_be_variable_definition j right pc then i, j, right else raise Not_found | _, Variable k -> if can_be_variable_definition k left pc then let i = equality_swapped i left right pc in i, k, left else raise Not_found | _,_ -> raise Not_found in try let idx, ivar, exp = var_def i in assert (not (variable_has_definition ivar pc)); let ass_lst, _ = assumptions_for_variables_0 [|ivar|] pc in add_variable_definition ivar idx pc; let nvars = count_variables pc in let exp_used = Term.used_variables exp nvars in List.iter (fun ass_idx -> if ass_idx <> idx then let ass = term ass_idx pc in let used = Term.used_variables ass nvars in if List.mem ivar used then begin try let idx_sub = substitute_variable ivar idx exp ass ass_idx true pc in List.iter (fun v -> add_variable_usage v idx_sub pc) exp_used with Not_found -> () end ) ass_lst; List.iter (fun ass_idx -> ignore(substitute_variable ivar idx exp (term ass_idx pc) ass_idx true pc) ) pc.var_defs.(ivar).used with Not_found -> () let expand_variable_definitions (i:int) (pc:t): unit = let subst (i:int) (idx:int) (v:int) (exp:term) (search:bool): int = let t = term i pc in substitute_variable v idx exp t i search pc in let t = term i pc in let defs = get_variable_definitions t pc in match defs with [] -> () | (idx,v,exp)::tail -> let i = List.fold_right (fun (idx,v,exp) i -> subst i idx v exp false ) tail i in try ignore(subst i idx v exp true) with Not_found -> () let add_consequences (i:int) (pc:t): unit = let t = term i pc and rd = rule_data i pc in add_inductive_set_rules true t pc; if not (RD.is_intermediate rd) then add_consequences_premise i pc; if RD.is_implication rd then add_consequences_implication i rd pc; add_consequences_evaluation i pc; add_consequences_someelim i pc; if is_local_assumption i pc then expand_variable_definitions i pc; add_consequences_variable_definition i pc let clear_work (pc:t): unit = pc.work <- [] let close_step (pc:t): unit = assert (has_work pc); let i = List.hd pc.work in pc.work <- List.tl pc.work; add_consequences i pc let prefix (pc:t): string = String.make (2*(depth pc)+2) ' ' let close (pc:t): unit = if is_global pc then () else begin let rec cls (round:int): unit = if has_work pc then begin let lst = List.rev pc.work in pc.work <- []; List.iter (fun i -> add_consequences i pc ) lst; if is_interface_check pc then pc.work <- [] else cls (1+round) end in cls 0 end let close_assumptions (pc:t): unit = if pc.trace then printf "%sproof\n" (trace_prefix_0 pc); close pc let trying_goal (g:term) (pc:t): unit = if pc.trace then begin let prefix = trace_prefix pc in printf "%strying to prove: %s\n" prefix (string_of_term g pc); if is_trace_extended pc then printf "%s\t%s\n" prefix (Term.to_string g); end let failed_goal (g:term) (pc:t): unit = if pc.trace then printf "%sfailure: %s\n" (trace_prefix pc) (string_of_term g pc) let proved_goal (g:term) (pc:t): unit = if pc.trace then printf "%ssuccess: %s\n" (trace_prefix pc) (string_of_term g pc) let print_work (pc:t): unit = if has_work pc then begin printf "open work to close\n"; List.iter (fun i -> printf " %d %s\n" i (string_of_term_i i pc)) pc.work end let boolean_type (nb:int) (pc:t): type_term = let ntvs = Context.count_all_type_variables (context pc) in Variable (Constants.boolean_class + nb + ntvs) let check_deferred (pc:t): unit = Context.check_deferred (context pc) let owner (pc:t): int = assert (is_toplevel pc); let ct = class_table pc and tvs = tvars pc and s = signature pc in match Class_table.dominant_class tvs s ct with | None -> -1 | Some cls -> cls let variant (i:int) (bcls:int) (cls:int) (pc:t): term = Proof_table.variant i bcls cls pc.base let add_global (defer:bool) (anchor:int) (pc:t): unit = assert (is_global pc); let cnt = count pc in if cnt <> Seq.count pc.gseq + 1 then printf "add_global count pc = %d, Seq.count pc.gseq = %d\n" cnt (Seq.count pc.gseq); assert (cnt = Seq.count pc.gseq + 1); Seq.push {pub = is_public pc; defer = defer; anchor = anchor} pc.gseq; assert (count pc = Seq.count pc.gseq) let eval_backward (tgt:term) (imp:term) (e:Eval.t) (pc:t): int = Proof_table.add_eval_backward tgt imp e pc.base; raw_add imp false pc let predicate_of_term (t:term) (pc:t): type_term = Context.predicate_of_term t (context pc) let find_equality (t1:term) (t2:term) (pc:t): int = let eq = Context.equality_term t1 t2 (context pc) in find_match eq pc let find_leibniz_for (t1:term) (t2:term) (pc:t): int = let gen_leibniz = leibniz_term pc in let eq_idx = find_equality t1 t2 pc in let tp = Context.type_of_term t1 (context pc) in let spec_leibniz = specialized gen_leibniz [|t1;t2|] [|tp|] 0 pc in add_mp eq_idx spec_leibniz false pc Subterm equality : The goal has the form lhs = rhs which we can transform into f(a1,a2 , .. ) = , .. ) as a lambda term [ f ] and two argument arrays [ a1,a2 , .. ] , [ , .. ] and we have found the leibniz rules all(p ) p(ai ) = = > p(bi ) for all arguments start : f(a1,a2 , .. ) = f(a1,a2 , .. ) reflexivity step i : f(a1,a2 , .. ) = f(b1,b2, .. ,ai , , .. ) start point { x : f(a1,a2 , .. ) = f(b1,b2, .. ,x , ai+1, .. )}(ai ) Eval_bwd { x: .. }(ai ) = = > { x: .. }(bi ) specialize leibniz { x: .. }(bi ) modus ponens f(a1,a2 , .. ) = f(b1,b2, .. ,bi , , .. ) Eval last : f(a1,a2 , .. ) = , .. ) result : lhs = rhs The goal has the form lhs = rhs which we can transform into f(a1,a2,..) = f(b1,b2,..) as a lambda term [f] and two argument arrays [a1,a2,..], [b1,b2,..] and we have found the leibniz rules all(p) p(ai) ==> p(bi) for all arguments start: f(a1,a2,..) = f(a1,a2,..) reflexivity step i: f(a1,a2,..) = f(b1,b2,..,ai,ai+1,..) start point {x: f(a1,a2,..) = f(b1,b2,..,x,ai+1,..)}(ai) Eval_bwd {x:..}(ai) ==> {x:..}(bi) specialize leibniz {x:..}(bi) modus ponens f(a1,a2,..) = f(b1,b2,..,bi,ai+1,..) Eval last: f(a1,a2,..) = f(b1,b2,..) result: lhs = rhs Eval *) let prove_equality (g:term) (pc:t): int = let c = context pc in let eq_id, left, right, ags = match g with VAppl (eq_id, [|left;right|], ags, _) when Context.is_equality_index eq_id c -> eq_id, left, right, ags | _ -> raise Not_found in let find_leibniz t1 t2 = find_leibniz_for t1 t2 pc in let tlam, leibniz, args1, args2 = Term_algo.compare left right find_leibniz in let nargs = Array.length args1 in let tup = Context.tuple_type_of_terms args1 c and tps = Array.map (fun t -> Context.type_of_term t c) args1 and r_tp = Context.type_of_term left c in let tps = Formals.make (standard_argnames nargs) tps in let lam = make_lambda tps Formals.empty [] tlam (Some r_tp) pc in assert (nargs = Array.length args2); assert (0 < nargs); let lam_1up = Term.up 1 lam and args1_up1 = Term.array_up 1 args1 and args2_up1 = Term.array_up 1 args2 in try let flhs_1up = make_application lam_1up args1_up1 tup 1 pc and frhs_x i = let args = Array.init nargs (fun j -> if j < i then args2_up1.(j) else if j = i then Variable 0 else args1_up1.(j)) in make_application lam_1up args tup 1 pc in let pred_inner i = VAppl (eq_id+1, [|flhs_1up; (frhs_x i)|], ags, false) in let start_term = let t = make_application lam args1 tup 0 pc in VAppl (eq_id, [|t;t|], ags, false) in let start_idx = find_match start_term pc in let result = ref start_idx in for i = 0 to nargs - 1 do let pred_inner_i = pred_inner i and tp = type_of_term args1.(i) pc in let tps = Formals.make [|ST.symbol "$1"|] [|tp|] in let pred_i = Lam(tps,Formals.empty,[],pred_inner_i,None) in let ai_abstracted = make_application pred_i [|args1.(i)|] tp 0 pc and ai_reduced = term !result pc in let imp = implication ai_reduced ai_abstracted pc in let idx2 = eval_backward ai_abstracted imp (Eval.Beta (Eval.Term ai_abstracted, Eval.Term ai_reduced)) pc in let idx = add_mp !result idx2 false pc in let sub = [|pred_i|] in let idx2 = specialized leibniz.(i) sub [||] 0 pc in let idx = add_mp idx idx2 false pc in let t = Term.apply pred_inner_i [|args2.(i)|] in let e = Eval.Beta (Eval.Term (term idx pc), Eval.Term t) in Proof_table.add_eval t idx e pc.base; result := raw_add t false pc done; let e = let ev args t = Eval.Beta (Eval.Term (make_application lam args tup 0 pc), Eval.Term t) in Eval.VApply(eq_id, [|ev args1 left; ev args2 right|], ags) in result := add_fwd_evaluation g !result e false pc; !result with Not_found -> let backward_witness (t:term) (pc:t): int = let tps,t0 = Term.some_quantifier_split t in let nargs = Formals.count tps and nms = Formals.names tps and tps = Formals.types tps in let sublst = unify_with t0 nargs tps pc.entry.prvd pc in let idx,args = List.find (fun (idx,args) -> Array.length args = nargs) sublst in let witness = term idx pc in let impl = implication witness t pc in Proof_table.add_witness impl idx nms tps t0 args pc.base; let idx_impl = raw_add impl false pc in add_mp0 t idx idx_impl false pc let find_goal (g:term) (pc:t): int = add_inductive_set_rules false g pc; close pc; try find_match g pc with Not_found -> try backward_witness g pc with Not_found -> prove_equality g pc module Backward = struct type rule = { idx: int; tps: Formals.t; fgs: Formals.t; pc: t } let has_some (r:rule): bool = r.subs <> [] let is_complete (r:rule): bool = match r.subs with | [] -> true | sub :: _ -> Term_sub.count sub = Formals.count r.tps let merge (sub:Term_sub.t) (old_subs:Term_sub.t list) (cumulated:Term_sub.t list) : Term_sub.t list = List.fold_left (fun cumulated old_sub -> try (Term_sub.merge sub old_sub) :: cumulated with Not_found -> cumulated ) cumulated old_subs let rec complete_rule (r:rule): rule = assert (has_some r); if is_complete r then r else match r.ps with | [] -> | p :: ps when Term.is_variable_below (Formals.count r.tps) p -> printf "\n\nRule %s\nhas a premise which is catch all\n\n" (string_of_term_i r.idx r.pc); r.ps <- ps; complete_rule r | p :: ps -> r.ps <- ps; let sublst = unify_with_0 p (Formals.count r.tps) r.pc.entry.prvd r.pc in r.subs <- List.fold_left (fun subs (idx,new_sub) -> let new_sub = Term_sub.map (fun t -> transformed_to_current t idx r.pc) new_sub in merge new_sub r.subs subs ) [] sublst; if r.subs = [] then complete_rule r let find_rules (g:term) (blacklst:IntSet.t) (pc:t): rule list = List.fold_left (fun lst (idx,sub) -> if IntSet.mem idx blacklst || not (is_visible idx pc) then lst else let tps,fgs,ps_rev,tgt = split_general_implication_chain (term idx pc) pc in let ps = List.rev ps_rev in try {tps; fgs; idx; ps; subs = [sub]; pc} :: lst with Not_found -> lst ) [] (unify_0 g pc.entry.bwd pc) let specialize_rule (r:rule) (lst:int list): int list = Specialized the rule [ r ] for all its substitutions and append the successfully specialized rules to the list [ lst ] . the successfully specialized rules to the list [lst]. *) assert (RD.is_backward (rule_data r.idx r.pc)); List.fold_left (fun lst sub -> try let args,ags = args_and_ags_of_substitution r.idx sub r.pc in if Array.length args = 0 then r.idx :: lst else let cnt = count r.pc in let idx = specialized r.idx args ags 2 r.pc in cnt :: lst else lst with Not_found -> lst ) lst r.subs let complete_rules (rules:rule list): int list = List.fold_left (fun lst r -> try let r = complete_rule r in specialize_rule r lst with Not_found -> lst ) [] rules let find (g:term) (blacklst:IntSet.t) (pc:t): int list = let rules = find_rules g blacklst pc in let lst = complete_rules rules in List.sort (fun i j -> let rdi = rule_data i pc and rdj = rule_data j pc in compare (RD.count_premises rdi) (RD.count_premises rdj)) lst let backward_in_table ( g : term ) ( blacklst : IntSet.t ) ( pc : t ): int list = let sublst = unify g pc.entry.bwd pc in let lst = List.fold_left ( fun lst ( idx , sub , ags ) - > if IntSet.mem idx blacklst || not ( is_visible idx pc ) then lst else if Array.length sub = 0 then if RD.is_backward ( rule_data idx pc ) then idx : : lst else lst else begin let cnt = count pc in let idx = specialized idx sub ags 2 pc in if idx = cnt & & RD.is_backward ( rule_data idx pc ) then begin : : lst end else begin lst end end ) [ ] sublst in List.sort ( fun i j - > let and rdj = rule_data j pc in compare ( RD.count_premises rdi ) ( RD.count_premises rdj ) ) lst let backward_in_table (g:term) (blacklst: IntSet.t) (pc:t): int list = let sublst = unify g pc.entry.bwd pc in let lst = List.fold_left (fun lst (idx,sub,ags) -> if IntSet.mem idx blacklst || not (is_visible idx pc) then lst else if Array.length sub = 0 then if RD.is_backward (rule_data idx pc) then idx :: lst else lst else begin let cnt = count pc in let idx = specialized idx sub ags 2 pc in if idx = cnt && RD.is_backward (rule_data idx pc) then begin cnt :: lst end else begin lst end end) [] sublst in List.sort (fun i j -> let rdi = rule_data i pc and rdj = rule_data j pc in compare (RD.count_premises rdi) (RD.count_premises rdj)) lst *) let eval_reduce (g:term) (lst:int list) (pc:t): int list = let add_eval t e lst = let impl = implication t g pc in if has impl pc then lst else (eval_backward g impl e pc) :: lst in let t1,e,modi = simplified_term g (count pc) pc in let lst = if modi then add_eval t1 e lst else lst in let t1,e,_,modi = evaluated_term g pc in if modi then add_eval t1 e lst else lst let substituted_goal (g:term) (lst:int list) (pc:t): int list = try let gsub,imps = List.fold_left (fun (gsub,imps) (idx,v,exp) -> let gsub,imp = variable_substitution_implication v idx exp gsub false pc in gsub, imp::imps ) (g,[]) (get_variable_definitions g pc) in if imps = [] then lst else let pc0 = push_empty pc in let idx_gsub = add_assumption gsub false pc0 in let idx_g = List.fold_left (fun g imp -> add_mp g imp false pc0) idx_gsub imps in let imp,pt = Proof_table.discharged idx_g pc0.base in Proof_table.add_proved imp pt 0 pc.base; let imp_idx = raw_add imp false pc in if pc.trace then begin let prefix = trace_prefix pc in printf "%sgoal substitution backward rule\n" prefix; printf "%s %d %s\n" prefix imp_idx (string_of_term_i imp_idx pc) end; imp_idx :: lst with Not_found -> lst let find_backward_goal (g:term) (blacklst:IntSet.t) (pc:t): int list = let lst = substituted_goal g [] pc in if lst <> [] then lst else begin let lst = Backward.find g blacklst pc in let lst = backward_in_table g blacklst pc in let lst = eval_reduce g lst pc in if pc.trace && is_trace_extended pc then begin let prefix = trace_prefix pc and str = string_of_intlist lst in printf "%salternatives %s\n" prefix str; if not (IntSet.is_empty blacklst) then printf "%s blacklist %s\n" prefix (string_of_intset blacklst) end; lst end let discharged (i:int) (pc:t): term * proof_term = Proof_table.discharged i pc.base let discharged_bubbled (i:int) (pc:t): term * proof_term = Proof_table.discharged_bubbled i pc.base let is_proof_pair (t:term) (pt:proof_term) (pc:t): bool = Proof_table.is_proof_pair t pt pc.base let add_proved_term (t:term) (pt:proof_term) (search:bool) (pc:t): int = assert (not (is_global pc)); let cnt = count pc in Proof_table.add_proved t pt 0 pc.base; let idx = raw_add t search pc in if search && idx = cnt then add_last_to_work pc; idx let add_proved_0 (defer:bool) (anchor:int) (t:term) (pterm:proof_term) (delta:int) (pc:t) : int = assert (not defer || anchor <> 0); let cnt = count pc and ct = class_table pc in Proof_table.add_proved t pterm delta pc.base; let idx = raw_add t true pc in let dup = idx < cnt and is_glob = idx < count_global pc in add_last_to_work pc; if defer && is_interface_check pc then begin assert (is_global pc); add_to_public_deferred t cnt pc end; if is_global pc then begin add_global defer anchor pc; if defer && not dup then begin assert (idx = cnt); Class_table.add_generic idx true anchor ct; let gdesc = Seq.elem idx pc.gseq in if is_interface_check pc && not gdesc.pub then gdesc.pub <- true end else if dup && is_interface_check pc then (Seq.elem idx pc.gseq).pub <- true end; cnt let add_proved_with_delta (t:term) (pterm:proof_term) (delta: int) (pc:t) : int = add_proved_0 false (-1) t pterm delta pc let add_proved (t:term) (pterm:proof_term) (pc:t) : int = add_proved_0 false (-1) t pterm 0 pc let add_proved_list (defer:bool) (anchor:int) (lst: (term*proof_term) list) (pc:t) : unit = let cnt = count pc in List.iter (fun (t,pt) -> let delta = count pc - cnt in let _ = add_proved_0 defer anchor t pt delta pc in ()) lst let remove_or_remap (set:IntSet.t) (pc:t): unit = let index i = try find (term i pc) pc with Not_found -> -1 in let remap_set = IntSet.filter (fun i -> let idx = index i in idx = -1) set in let pred i = IntSet.mem i remap_set || not (IntSet.mem i set) in filter_and_remap_tables pred pc; IntSet.iter (fun i -> let t = term i pc in add_to_equalities t i pc) remap_set let add_induction_law0 (cls:int) (pc:t): unit = assert (is_global pc); let law = Proof_table.type_induction_law cls pc.base and pt = Indtype cls and defer = Class_table.is_deferred cls (class_table pc) in ignore(add_proved_0 defer cls law pt 0 pc) let previous_schematics (idx:int) (pc:t): int list = assert (idx < count pc); let rd = rule_data idx pc in RD.previous_schematics rd let premises (idx:int) (pc:t): (term*bool) list = assert (idx < count pc); let rd = rule_data idx pc in assert (RD.is_fully_specialized rd); assert (RD.is_implication rd); RD.premises rd (context pc) let check_interface (pc:t): unit = assert (is_interface_check pc); let ft = feature_table pc in Feature_table.check_interface ft; assert (count pc = Seq.count pc.gseq); for i = 0 to count pc - 1 do let gdesc = Seq.elem i pc.gseq in if gdesc.defer && not gdesc.pub && Class_table.is_class_public gdesc.anchor (class_table pc) && not (has_public_deferred (term i pc) pc) then begin let open Module in let m = Compile.current (Feature_table.compilation_context ft) in assert (M.has_interface m); let fn = Src.path (M.interface m) in error_info (FINFO (1,0,fn)) ("deferred assertion \"" ^ (string_of_term (term i pc) pc) ^ "\" is not public") end done let excluded_middle (pc:t): int = let nvars = nbenv pc in let or_id = 1 + nvars + Constants.or_index and not_id = 1 + nvars + Constants.not_index in let em = Term.binary or_id (Variable 0) (Term.unary not_id (Variable 0)) in let nms = standard_argnames 1 and tps = [| boolean_type 1 pc |] in let em = Term.all_quantified (Formals.make nms tps) Formals.empty em in find em pc let indirect_proof_law (pc:t): int = let nvars = nbenv pc in let not_id = 1 + nvars + Constants.not_index and imp_id = 1 + nvars + Constants.implication_index and false_const = Feature_table.false_constant (1 + nvars) in let nota = Term.unary not_id (Variable 0) in let nota_imp_false = Term.binary imp_id nota false_const in let t = Term.binary imp_id nota_imp_false false_const in let btp = boolean_type 1 pc in let nms = standard_argnames 1 and tps = [| btp |] in let indirect = Term.all_quantified (Formals.make nms tps) Formals.empty t in find indirect pc let or_elimination (pc:t): int = let nvars = nbenv pc in let or_id = 3 + nvars + Constants.or_index and imp_id = 3 + nvars + Constants.implication_index in let a_or_b = Term.binary or_id (Variable 0) (Variable 1) and a_imp_c = Term.binary imp_id (Variable 0) (Variable 2) and b_imp_c = Term.binary imp_id (Variable 1) (Variable 2) in let or_elim = Term.binary imp_id a_or_b (Term.binary imp_id a_imp_c (Term.binary imp_id b_imp_c (Variable 2))) in let btp = boolean_type 3 pc in let nms = standard_argnames 3 and tps = [| btp; btp; btp |] in let or_elim = Term.all_quantified (Formals.make nms tps) Formals.empty or_elim in find or_elim pc let has_excluded_middle (pc:t): bool = try ignore(excluded_middle pc); true with Not_found -> false let has_or_elimination (pc:t): bool = try ignore(or_elimination pc); true with Not_found -> false
8f435595cf63f648635c48e00d8764a824a9f3e22a6ecf4c67dc5c8dc6a9a914
emotiq/emotiq
package.lisp
(defpackage #:emotiq-test (:use #:cl #:emotiq #:lisp-unit) (:export test-blockchain)) (defpackage #:emotiq-config-generate-test (:nicknames #:test-generate) ;;; The road to madness (:use #:cl #:emotiq #:lisp-unit))
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/test/package.lisp
lisp
The road to madness
(defpackage #:emotiq-test (:use #:cl #:emotiq #:lisp-unit) (:export test-blockchain)) (defpackage #:emotiq-config-generate-test (:use #:cl #:emotiq #:lisp-unit))
15991640086297115751b43558f76978bb3c5be0ec892c860e099846baaf9cbb
icfpcontest2021/icfpcontest2021.github.io
JasperSolver.hs
module Main where import qualified BrainWall.JasperSolver main :: IO () main = BrainWall.JasperSolver.main
null
https://raw.githubusercontent.com/icfpcontest2021/icfpcontest2021.github.io/fb23fea2a8ecec7740017d3dda78d921c1df5a26/toolchain/src/JasperSolver.hs
haskell
module Main where import qualified BrainWall.JasperSolver main :: IO () main = BrainWall.JasperSolver.main
db66f22dad4103b83e86384cadb43db3aadb0e7880d14216d4d9131f687fbb34
kupl/FixML
sub4.ml
let rec max : int list -> int =fun l -> match l with |[] -> 0 |h::t -> if h > max t then h else max t
null
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/maxmin/maxmin/submissions/sub4.ml
ocaml
let rec max : int list -> int =fun l -> match l with |[] -> 0 |h::t -> if h > max t then h else max t
a74ba63d67003f3a44adb636da1349577d3f4d941c97271371bf21d947cd6c29
mokus0/junkbox
DoubleExponential.hs
module Monads.DoubleExponential where import Control.Comonad import Control.Monad.Instances -- the exponential bifunctor; contravariant argument placed last , because that 's the one -- we're interested in here. newtype E x y = E { runE :: y -> x } -- 'E x' is a contravariant functor. -- its action on arrows is postcomposition. cmap :: (a -> b) -> E x b -> E x a cmap f (E g) = E (g . f) -- That functor is self-adjoint, and the hom-isomorphism is 'flip' (modulo newtype wrapping) adj :: (a -> E x b) -> (b -> E x a) adj f = E . flip (runE . f) -- the unit/counit: eta :: a -> E x (E x a) eta = adj id -- the zig/zag transformations zig :: E x (E y (E y a)) -> E x a zig = cmap eta zag :: E y a -> E x (E x (E y a)) zag = eta -- mu = zig ( whiskered by on the right , which corresponds to simply refining the type ) mu :: E x (E y (E y (E z a))) -> E x (E z a) mu = zig -- the zig-zag equation (@zag . zig = id@ is the same equation because the -- composition happens in the opposite category): -- zig . zag = id it 's not actually necessary to prove this in Haskell because parametricity -- ensures naturality of adj, but just for fun here we go: -- zig . zag . eta ( adj i d ) . adj i d ( adj i d ) . E . flip runE = \x - > cmap ( adj i d ) ( E ( flip runE x ) ) = \x - > E ( flip runE x . adj i d ) = \x - > E ( flip runE x . E . flip runE ) = \x - > E ( ( \y - > flip runE x ( E y ) ) . flip runE ) = \x - > E ( ( \y - > runE ( E y ) x ) . flip runE ) = \x - > E ( ( \y - > y x ) . flip runE ) = \x - > E ( \z - > ( $ x ) ( flip runE z ) ) = \x - > E ( \z - > flip runE z x ) = \x - > E ( \z - > runE x z ) = \x - > E ( runE x ) = \x - > x -- = id since @E is self - adjoint , composing it with itself gives a monad -- (or dually, a comonad in the opposite category; they are effectively the same) newtype K x y = K { runK :: E x (E x y) } instance Functor (K x) where fmap f = K . cmap (cmap f) . runK instance Monad (K x) where return = K . eta x >>= f = joinK (fmap f x) joinK :: K x (K x y) -> K x y joinK = K . mu . runK . fmap runK -- runCont = ($) -- (evaluate a double-exponential at the object corresponding to the upper exponential) runCont :: K x y -> E x y -> x runCont = runE . runK -- this is to be thought of as a global element of the exponential object. -- Abstraction (a meta-operation of type @((g,a) -> b) -> (g -> E b a)@) constructs -- the universal morphism of the exponential diagram; abstracting the identity morphism ( from 1 * x - > 1 * x ) gives the identity element of the exponential -- @E x x@. i :: E x x i = E id -- Since every exponential of the form @E x x@ has a global element, evaluation at that element gives a -- morphism (K x x -> x). runCont_ :: K x x -> x runCont_ x = runCont x i
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Monads/DoubleExponential.hs
haskell
the exponential bifunctor; we're interested in here. 'E x' is a contravariant functor. its action on arrows is postcomposition. That functor is self-adjoint, and the hom-isomorphism is 'flip' (modulo newtype wrapping) the unit/counit: the zig/zag transformations mu = zig the zig-zag equation (@zag . zig = id@ is the same equation because the composition happens in the opposite category): zig . zag = id ensures naturality of adj, but just for fun here we go: zig . zag = id (or dually, a comonad in the opposite category; they are effectively the same) runCont = ($) (evaluate a double-exponential at the object corresponding to the upper exponential) this is to be thought of as a global element of the exponential object. Abstraction (a meta-operation of type @((g,a) -> b) -> (g -> E b a)@) constructs the universal morphism of the exponential diagram; abstracting the identity @E x x@. Since every exponential of the form @E x x@ has a global element, evaluation at that element gives a morphism (K x x -> x).
module Monads.DoubleExponential where import Control.Comonad import Control.Monad.Instances contravariant argument placed last , because that 's the one newtype E x y = E { runE :: y -> x } cmap :: (a -> b) -> E x b -> E x a cmap f (E g) = E (g . f) adj :: (a -> E x b) -> (b -> E x a) adj f = E . flip (runE . f) eta :: a -> E x (E x a) eta = adj id zig :: E x (E y (E y a)) -> E x a zig = cmap eta zag :: E y a -> E x (E x (E y a)) zag = eta ( whiskered by on the right , which corresponds to simply refining the type ) mu :: E x (E y (E y (E z a))) -> E x (E z a) mu = zig it 's not actually necessary to prove this in Haskell because parametricity . eta ( adj i d ) . adj i d ( adj i d ) . E . flip runE = \x - > cmap ( adj i d ) ( E ( flip runE x ) ) = \x - > E ( flip runE x . adj i d ) = \x - > E ( flip runE x . E . flip runE ) = \x - > E ( ( \y - > flip runE x ( E y ) ) . flip runE ) = \x - > E ( ( \y - > runE ( E y ) x ) . flip runE ) = \x - > E ( ( \y - > y x ) . flip runE ) = \x - > E ( \z - > ( $ x ) ( flip runE z ) ) = \x - > E ( \z - > flip runE z x ) = \x - > E ( \z - > runE x z ) = \x - > E ( runE x ) = \x - > x since @E is self - adjoint , composing it with itself gives a monad newtype K x y = K { runK :: E x (E x y) } instance Functor (K x) where fmap f = K . cmap (cmap f) . runK instance Monad (K x) where return = K . eta x >>= f = joinK (fmap f x) joinK :: K x (K x y) -> K x y joinK = K . mu . runK . fmap runK runCont :: K x y -> E x y -> x runCont = runE . runK morphism ( from 1 * x - > 1 * x ) gives the identity element of the exponential i :: E x x i = E id runCont_ :: K x x -> x runCont_ x = runCont x i
48bed6d7f4c71df98b769f0109654d88ea5ab3d61b53022aaeeb78127b8d07fc
wangweihao/ProgrammingErlangAnswer
test3.erl
-module(test3). -export([test/0, factorial/1]). test() -> factorial(-5). factorial(0) -> 1; factorial(N) -> N*factorial(N-1).
null
https://raw.githubusercontent.com/wangweihao/ProgrammingErlangAnswer/b145b5e6a19cb866ce5d2ceeac116d751f6e2b3d/9/1/test3.erl
erlang
-module(test3). -export([test/0, factorial/1]). test() -> factorial(-5). factorial(0) -> 1; factorial(N) -> N*factorial(N-1).
de3c34c3f58288bfcb3571c471424cf18aa9ea81ade704245c24761afb6209b1
psyeugenic/fgraph
provisual_fgraph.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% -module(provisual_fgraph). -export([ composition/2, load_provisual_nif/0, step/3 ]). -export([ new/0, add/3, set/3, del/2, is_defined/2, get/2, size/1, foreach/2, map/2, foldl/3, mapfoldl/3 ]). -on_load(load_provisual_nif/0). -compile(inline). -compile({inline_size, 128}). -include_lib("provisual_fgraph.hrl"). % size(S) -> dict:size(S). % new() -> dict:new(). % add(K, V, S) -> dict:store(K, {K,V}, S). set(K , V , S ) - > dict : store(K , { K , V } , S ) . % del(K, S) -> dict:erase(K, S). get(K , S ) - > case catch dict : fetch(K , S ) of { ' EXIT ' , _ } - > undefined ; % {_, V} -> V % end. is_defined(K , S ) - > dict : is_key(K , S ) . % % map(F, S) -> dict:map(fun(_,V) -> F(V) end, S). % foldl(F, I, S) -> dict:fold(fun(_, V, O) -> F(V,O) end, I, S). % % foreach(F, S) -> dict:map(fun(_,V) -> F(V) end, S), S. % mapfoldl(_F, I, S) -> {I, S}. KEY - VALUE STORAGE Process dictionary new() -> []. is_defined(Key, _Fg) -> case get(Key) of undefined -> false; _ -> true end. get(K, _Fg) -> case get(K) of {_, V} -> V; _ -> undefined end. add(Key, Value, Fg) -> put(Key, {Key, Value}), [Key|Fg]. set(Key, Value, Fg) -> put(Key, {Key, Value}), Fg. size(Fg) -> length(Fg). del(Key, Fg) -> erase(Key), lists:delete(Key, Fg). foreach(Fun, Fg) -> lists:foreach(fun (Key) -> Fun(get(Key)) end, Fg), Fg. map(Fun, Fg) -> lists:foreach(fun (Key) -> put(Key,Fun(get(Key))) end, Fg), Fg. foldl(Fun, I, Fg) -> lists:foldl(fun (Key, Out) -> Fun(get(Key), Out) end, I, Fg). mapfoldl(Fun, I, Fg) -> Acc = lists:foldl(fun (Key, Out) -> {Value, Acc} = Fun(get(Key), Out), put(Key, Value), Acc end, I, Fg), {Fg, Acc}. step(Vs, Es, Pa) -> ?MODULE:map(fun (Node = {_, #fg_v{ type = static }}) -> Node; ({Key, #fg_v{ p = {_,_,_}, type = dynamic} = Value}) -> F0 = {0.0,0.0,0.0}, F1 = coulomb_repulsion(Key, Value, Vs, F0), F2 = hooke_attraction(Key, Value, Vs, Es, F1), F3 = point_attraction(Key, Value, Pa, F2), {Key, force_step(Key, Value, F3)}; ({Key, #fg_v{ p = {_,_}, type = dynamic} = Value}) -> F0 = {0.0,0.0}, F1 = coulomb_repulsion(Key, Value, Vs, F0), F2 = hooke_attraction(Key, Value, Vs, Es, F1), F3 = point_attraction(Key, Value, Pa, F2), {Key, force_step(Key, Value, F3) }; (Node) -> Node end, Vs). force_step(_Key, #fg_v{ p = {Px, Py, Pz}, v = {Vx, Vy, Vz}} = Value, {Fx, Fy, Fz}) -> Vx1 = (Vx + ?fg_th*Fx)*?fg_damp, Vy1 = (Vy + ?fg_th*Fy)*?fg_damp, Vz1 = (Vz + ?fg_th*Fz)*?fg_damp, Px1 = Px + ?fg_th*Vx1, Py1 = Py + ?fg_th*Vy1, Pz1 = Pz + ?fg_th*Vz1, Value#fg_v{ p = {Px1, Py1, Pz1}, v = {Vx1, Vy1, Vz1}}; force_step(_Key, #fg_v{ p = {Px, Py}, v = {Vx, Vy}} = Value, {Fx, Fy}) -> Vx1 = (Vx + ?fg_th*Fx)*?fg_damp, Vy1 = (Vy + ?fg_th*Fy)*?fg_damp, Px1 = Px + ?fg_th*Vx1, Py1 = Py + ?fg_th*Vy1, Value#fg_v{ p = {Px1, Py1}, v = {Vx1, Vy1}}. point_attraction(_, #fg_v{ p = P0 }, Pa, {Fx, Fy, Fz}) when is_float(Fx), is_float(Fy), is_float(Fz) -> K = 20, L = 150, {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, Pa), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F}; point_attraction(_, #fg_v{ p = P0 }, Pa, {Fx, Fy}) when is_float(Fx), is_float(Fy) -> K = 20, L = 150, {R, {Cx,Cy}} = ?MODULE:composition(P0, Pa), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F}. coulomb_repulsion(K0, #fg_v{ p = P0, q = Q0}, Vs, {Fx0, Fy0,Fz0}) when is_float(Fx0), is_float(Fy0), is_float(Fz0) -> ?MODULE:foldl(fun ({K1, _}, F) when K1 == K0 -> F; ({_, #fg_v{ p = P1, q = Q1}}, {Fx, Fy, Fz}) -> {R, {Cx, Cy,Cz}} = ?MODULE:composition(P0, P1), F = ?fg_kc*(Q1*Q0)/(R*R+?fg_sqrt_eps), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F}; (_, F) -> F end, {Fx0, Fy0, Fz0}, Vs); coulomb_repulsion(K0, #fg_v{ p = P0, q = Q0}, Vs, {Fx0, Fy0}) when is_float(Fx0), is_float(Fy0) -> ?MODULE:foldl(fun ({K1, _}, F) when K1 == K0 -> F; ({_, #fg_v{ p = P1, q = Q1}}, {Fx, Fy}) -> {R, {Cx, Cy}} = ?MODULE:composition(P0, P1), F = ?fg_kc*(Q1*Q0)/(R*R+?fg_sqrt_eps), {Fx + Cx*F, Fy + Cy*F}; (_, F) -> F end, {Fx0, Fy0}, Vs). hooke_attraction(Key0, #fg_v{ p = P0 }, Vs, Es, {Fx0, Fy0, Fz0}=F0) when is_float(Fx0), is_float(Fy0), is_float(Fz0) -> ?MODULE:foldl(fun ({{Key1,Key1}, _}, F) -> F; ({{Key1,Key2}, #fg_e{ l = L, k = K}}, {Fx, Fy, Fz}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy, Fz} end; ({{Key2,Key1}, #fg_e{ l = L, k = K}}, {Fx, Fy, Fz}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy, Fz} end; (_, F) -> F end, F0, Es); hooke_attraction(Key0, #fg_v{ p = P0 }, Vs, Es, {Fx0, Fy0}) when is_float(Fx0), is_float(Fy0) -> ?MODULE:foldl(fun ({{Key1,Key1}, _}, F) -> F; ({{Key1,Key2}, #fg_e{ l = L, k = K}}, {Fx, Fy}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy} end; ({{Key2,Key1}, #fg_e{ l = L, k = K}}, {Fx, Fy}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy} end; (_, F) -> F end, {Fx0, Fy0}, Es). % This decomposition takes a lot of computing power, needs optimizing composition({Px1, Py1, Pz1}, {Px0, Py0, Pz0}) when is_float(Px1), is_float(Py1), is_float(Pz1), is_float(Px0), is_float(Py0), is_float(Pz0) -> Dx = Px1 - Px0, Dy = Py1 - Py0, Dz = Pz1 - Pz0, R = qsqrt(Dx*Dx + Dy*Dy + Dz*Dz + ?fg_sqrt_eps), %R = math:sqrt(Dx*Dx + Dy*Dy + Dz*Dz + ?fg_sqrt_eps), {R, {Dx/R, Dy/R, Dz/R}}; composition({Px1, Py1}, {Px0, Py0}) when is_float(Px1), is_float(Py1), is_float(Px0), is_float(Py0) -> Dx = Px1 - Px0, Dy = Py1 - Py0, R = qsqrt(Dx*Dx + Dy*Dy + ?fg_sqrt_eps), %R = math:sqrt(Dx*Dx + Dy*Dy + ?fg_sqrt_eps), {R, {Dx/R, Dy/R}}. %% Carmacks Quake3 square root trick (sadly not faster then builtin math:sqrt/1) qsqrt(X) -> X2 = X*0.5, <<I:32>> = <<X:32/float>>, Trick = 16#5f3759df - ( I bsr 1 ), <<Inv:32/float>> = <<Trick:32>>, Inv0 = Inv*(1.50 - (X2 * Inv * Inv)), % Inv1 = Inv0*(1.5 - (X2 * Inv0 * Inv0)), 1/Inv0. load_provisual_nif() -> case code:priv_dir(provisual) of {error, bad_name} -> SoName = filename:join("priv", provisual_drv); Dir -> SoName = filename:join(Dir, provisual_drv) end, erlang:load_nif(SoName, 0).
null
https://raw.githubusercontent.com/psyeugenic/fgraph/c485fefc9de78012b13b35abe59f0d29090ff6d1/src/provisual_fgraph.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% size(S) -> dict:size(S). new() -> dict:new(). add(K, V, S) -> dict:store(K, {K,V}, S). del(K, S) -> dict:erase(K, S). {_, V} -> V end. map(F, S) -> dict:map(fun(_,V) -> F(V) end, S). foldl(F, I, S) -> dict:fold(fun(_, V, O) -> F(V,O) end, I, S). foreach(F, S) -> dict:map(fun(_,V) -> F(V) end, S), S. mapfoldl(_F, I, S) -> {I, S}. This decomposition takes a lot of computing power, needs optimizing R = math:sqrt(Dx*Dx + Dy*Dy + Dz*Dz + ?fg_sqrt_eps), R = math:sqrt(Dx*Dx + Dy*Dy + ?fg_sqrt_eps), Carmacks Quake3 square root trick (sadly not faster then builtin math:sqrt/1) Inv1 = Inv0*(1.5 - (X2 * Inv0 * Inv0)),
Copyright Ericsson AB 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(provisual_fgraph). -export([ composition/2, load_provisual_nif/0, step/3 ]). -export([ new/0, add/3, set/3, del/2, is_defined/2, get/2, size/1, foreach/2, map/2, foldl/3, mapfoldl/3 ]). -on_load(load_provisual_nif/0). -compile(inline). -compile({inline_size, 128}). -include_lib("provisual_fgraph.hrl"). set(K , V , S ) - > dict : store(K , { K , V } , S ) . get(K , S ) - > case catch dict : fetch(K , S ) of { ' EXIT ' , _ } - > undefined ; is_defined(K , S ) - > dict : is_key(K , S ) . KEY - VALUE STORAGE Process dictionary new() -> []. is_defined(Key, _Fg) -> case get(Key) of undefined -> false; _ -> true end. get(K, _Fg) -> case get(K) of {_, V} -> V; _ -> undefined end. add(Key, Value, Fg) -> put(Key, {Key, Value}), [Key|Fg]. set(Key, Value, Fg) -> put(Key, {Key, Value}), Fg. size(Fg) -> length(Fg). del(Key, Fg) -> erase(Key), lists:delete(Key, Fg). foreach(Fun, Fg) -> lists:foreach(fun (Key) -> Fun(get(Key)) end, Fg), Fg. map(Fun, Fg) -> lists:foreach(fun (Key) -> put(Key,Fun(get(Key))) end, Fg), Fg. foldl(Fun, I, Fg) -> lists:foldl(fun (Key, Out) -> Fun(get(Key), Out) end, I, Fg). mapfoldl(Fun, I, Fg) -> Acc = lists:foldl(fun (Key, Out) -> {Value, Acc} = Fun(get(Key), Out), put(Key, Value), Acc end, I, Fg), {Fg, Acc}. step(Vs, Es, Pa) -> ?MODULE:map(fun (Node = {_, #fg_v{ type = static }}) -> Node; ({Key, #fg_v{ p = {_,_,_}, type = dynamic} = Value}) -> F0 = {0.0,0.0,0.0}, F1 = coulomb_repulsion(Key, Value, Vs, F0), F2 = hooke_attraction(Key, Value, Vs, Es, F1), F3 = point_attraction(Key, Value, Pa, F2), {Key, force_step(Key, Value, F3)}; ({Key, #fg_v{ p = {_,_}, type = dynamic} = Value}) -> F0 = {0.0,0.0}, F1 = coulomb_repulsion(Key, Value, Vs, F0), F2 = hooke_attraction(Key, Value, Vs, Es, F1), F3 = point_attraction(Key, Value, Pa, F2), {Key, force_step(Key, Value, F3) }; (Node) -> Node end, Vs). force_step(_Key, #fg_v{ p = {Px, Py, Pz}, v = {Vx, Vy, Vz}} = Value, {Fx, Fy, Fz}) -> Vx1 = (Vx + ?fg_th*Fx)*?fg_damp, Vy1 = (Vy + ?fg_th*Fy)*?fg_damp, Vz1 = (Vz + ?fg_th*Fz)*?fg_damp, Px1 = Px + ?fg_th*Vx1, Py1 = Py + ?fg_th*Vy1, Pz1 = Pz + ?fg_th*Vz1, Value#fg_v{ p = {Px1, Py1, Pz1}, v = {Vx1, Vy1, Vz1}}; force_step(_Key, #fg_v{ p = {Px, Py}, v = {Vx, Vy}} = Value, {Fx, Fy}) -> Vx1 = (Vx + ?fg_th*Fx)*?fg_damp, Vy1 = (Vy + ?fg_th*Fy)*?fg_damp, Px1 = Px + ?fg_th*Vx1, Py1 = Py + ?fg_th*Vy1, Value#fg_v{ p = {Px1, Py1}, v = {Vx1, Vy1}}. point_attraction(_, #fg_v{ p = P0 }, Pa, {Fx, Fy, Fz}) when is_float(Fx), is_float(Fy), is_float(Fz) -> K = 20, L = 150, {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, Pa), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F}; point_attraction(_, #fg_v{ p = P0 }, Pa, {Fx, Fy}) when is_float(Fx), is_float(Fy) -> K = 20, L = 150, {R, {Cx,Cy}} = ?MODULE:composition(P0, Pa), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F}. coulomb_repulsion(K0, #fg_v{ p = P0, q = Q0}, Vs, {Fx0, Fy0,Fz0}) when is_float(Fx0), is_float(Fy0), is_float(Fz0) -> ?MODULE:foldl(fun ({K1, _}, F) when K1 == K0 -> F; ({_, #fg_v{ p = P1, q = Q1}}, {Fx, Fy, Fz}) -> {R, {Cx, Cy,Cz}} = ?MODULE:composition(P0, P1), F = ?fg_kc*(Q1*Q0)/(R*R+?fg_sqrt_eps), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F}; (_, F) -> F end, {Fx0, Fy0, Fz0}, Vs); coulomb_repulsion(K0, #fg_v{ p = P0, q = Q0}, Vs, {Fx0, Fy0}) when is_float(Fx0), is_float(Fy0) -> ?MODULE:foldl(fun ({K1, _}, F) when K1 == K0 -> F; ({_, #fg_v{ p = P1, q = Q1}}, {Fx, Fy}) -> {R, {Cx, Cy}} = ?MODULE:composition(P0, P1), F = ?fg_kc*(Q1*Q0)/(R*R+?fg_sqrt_eps), {Fx + Cx*F, Fy + Cy*F}; (_, F) -> F end, {Fx0, Fy0}, Vs). hooke_attraction(Key0, #fg_v{ p = P0 }, Vs, Es, {Fx0, Fy0, Fz0}=F0) when is_float(Fx0), is_float(Fy0), is_float(Fz0) -> ?MODULE:foldl(fun ({{Key1,Key1}, _}, F) -> F; ({{Key1,Key2}, #fg_e{ l = L, k = K}}, {Fx, Fy, Fz}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy, Fz} end; ({{Key2,Key1}, #fg_e{ l = L, k = K}}, {Fx, Fy, Fz}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy,Cz}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F, Fz + Cz*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy, Fz} end; (_, F) -> F end, F0, Es); hooke_attraction(Key0, #fg_v{ p = P0 }, Vs, Es, {Fx0, Fy0}) when is_float(Fx0), is_float(Fy0) -> ?MODULE:foldl(fun ({{Key1,Key1}, _}, F) -> F; ({{Key1,Key2}, #fg_e{ l = L, k = K}}, {Fx, Fy}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy} end; ({{Key2,Key1}, #fg_e{ l = L, k = K}}, {Fx, Fy}) when Key1 =:= Key0-> try #fg_v{ p = P1} = ?MODULE:get(Key2, Vs), {R, {Cx,Cy}} = ?MODULE:composition(P0, P1), F = -K*?fg_stretch*(R - L), {Fx + Cx*F, Fy + Cy*F} catch C:E -> io:format("{~p,~p} : bad key ~p ~n", [C,E,Key2]), {Fx, Fy} end; (_, F) -> F end, {Fx0, Fy0}, Es). composition({Px1, Py1, Pz1}, {Px0, Py0, Pz0}) when is_float(Px1), is_float(Py1), is_float(Pz1), is_float(Px0), is_float(Py0), is_float(Pz0) -> Dx = Px1 - Px0, Dy = Py1 - Py0, Dz = Pz1 - Pz0, R = qsqrt(Dx*Dx + Dy*Dy + Dz*Dz + ?fg_sqrt_eps), {R, {Dx/R, Dy/R, Dz/R}}; composition({Px1, Py1}, {Px0, Py0}) when is_float(Px1), is_float(Py1), is_float(Px0), is_float(Py0) -> Dx = Px1 - Px0, Dy = Py1 - Py0, R = qsqrt(Dx*Dx + Dy*Dy + ?fg_sqrt_eps), {R, {Dx/R, Dy/R}}. qsqrt(X) -> X2 = X*0.5, <<I:32>> = <<X:32/float>>, Trick = 16#5f3759df - ( I bsr 1 ), <<Inv:32/float>> = <<Trick:32>>, Inv0 = Inv*(1.50 - (X2 * Inv * Inv)), 1/Inv0. load_provisual_nif() -> case code:priv_dir(provisual) of {error, bad_name} -> SoName = filename:join("priv", provisual_drv); Dir -> SoName = filename:join(Dir, provisual_drv) end, erlang:load_nif(SoName, 0).
ea51d1e369247d697531bf5b3cc6cfabfff94380e5ce9e55e79783e7602290e3
Datomic/ion-starter
attributes.clj
Copyright ( c ) Cognitect , Inc. ;; All rights reserved. (ns datomic.ion.starter.attributes) (defn valid-sku? [s] (boolean (re-matches #"SKU-(\d+)" s)))
null
https://raw.githubusercontent.com/Datomic/ion-starter/295e69df0850dee9ff75b355c546b68e33207f95/src/datomic/ion/starter/attributes.clj
clojure
All rights reserved.
Copyright ( c ) Cognitect , Inc. (ns datomic.ion.starter.attributes) (defn valid-sku? [s] (boolean (re-matches #"SKU-(\d+)" s)))
4f48cc8a85df9c3fb765bca321660d36b00ed0d1dc41b8bbe5900c53fd8e05e9
macourtney/Conjure
template_flow.clj
(ns flows.test.template-flow (:use clojure.test flows.template-flow) (:require [conjure.util.request :as request])) (deftest test-model-name (let [test-service "foo"] (request/set-request-map { :service test-service } (is (= (model-name) test-service)))))
null
https://raw.githubusercontent.com/macourtney/Conjure/1d6cb22d321ea75af3a6abe2a5bc140ad36e20d1/conjure_scaffold/test/flows/test/template_flow.clj
clojure
(ns flows.test.template-flow (:use clojure.test flows.template-flow) (:require [conjure.util.request :as request])) (deftest test-model-name (let [test-service "foo"] (request/set-request-map { :service test-service } (is (= (model-name) test-service)))))
689e7b34c3ef5c988fd43010ea37e9f1fd57f61692b32220ce8e004e88f34503
markbastian/partsbin
core.clj
(ns partsbin.aleph.http.core (:require [partsbin.aleph.http.alpha :as web] [integrant.core :as ig])) (derive ::server ::web/server) (def config {::server {:host "0.0.0.0" :port 3000 :handler (constantly {:status 200 :body "OK"})}}) (comment (defonce system (ig/init config)) (ig/halt! system))
null
https://raw.githubusercontent.com/markbastian/partsbin/8dc159327f296c9625d129b5943ec79433019e54/src/partsbin/aleph/http/core.clj
clojure
(ns partsbin.aleph.http.core (:require [partsbin.aleph.http.alpha :as web] [integrant.core :as ig])) (derive ::server ::web/server) (def config {::server {:host "0.0.0.0" :port 3000 :handler (constantly {:status 200 :body "OK"})}}) (comment (defonce system (ig/init config)) (ig/halt! system))
f5ac1cd0b91fd4485d50dc58c9f424759a0d13dd54315d0bf6fa7e8db6ecf9f7
skanev/playground
30.scm
EOPL exercise 2.30 ; ; The procedure parse-expression as defined above is fragile: it does not ; detect several possible syntactic errors, such as (a b c), and aborts with ; inappropriate error messages for other expressions, such as (lambda). Modify ; it so that it is robust, accepting any s-exp and issuing an appropriate ; error message if the s-exp does not represent a lambda-calculus expression. (load-relative "23.scm") (define (parse datum) (cond ((symbol? datum) (when (eqv? datum 'lambda) (eopl:error 'parse "lambda is not a valid identifier")) (var-exp datum)) ((and (pair? datum) (eqv? (car datum) 'lambda)) (unless (= (length datum) 3) (eopl:error 'parse "lambda requires two components. given: ~s" datum)) (when (symbol? (cadr datum)) (eopl:error 'parse "lambda requires an arglist. given: ~s" (cadr datum))) (unless (= (length (cadr datum)) 1) (eopl:error 'parse "lambda requires exactly one argument. given: ~s" (cadr datum))) (lambda-exp (car (cadr datum)) (parse (caddr datum)))) ((pair? datum) (unless (= (length datum) 2) (eopl:error 'parse "application requires two components. given: ~s" datum)) (app-exp (parse (car datum)) (parse (cadr datum)))) (else (eopl:error 'parse "Invalid syntax: ~s" datum))))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/02/30.scm
scheme
The procedure parse-expression as defined above is fragile: it does not detect several possible syntactic errors, such as (a b c), and aborts with inappropriate error messages for other expressions, such as (lambda). Modify it so that it is robust, accepting any s-exp and issuing an appropriate error message if the s-exp does not represent a lambda-calculus expression.
EOPL exercise 2.30 (load-relative "23.scm") (define (parse datum) (cond ((symbol? datum) (when (eqv? datum 'lambda) (eopl:error 'parse "lambda is not a valid identifier")) (var-exp datum)) ((and (pair? datum) (eqv? (car datum) 'lambda)) (unless (= (length datum) 3) (eopl:error 'parse "lambda requires two components. given: ~s" datum)) (when (symbol? (cadr datum)) (eopl:error 'parse "lambda requires an arglist. given: ~s" (cadr datum))) (unless (= (length (cadr datum)) 1) (eopl:error 'parse "lambda requires exactly one argument. given: ~s" (cadr datum))) (lambda-exp (car (cadr datum)) (parse (caddr datum)))) ((pair? datum) (unless (= (length datum) 2) (eopl:error 'parse "application requires two components. given: ~s" datum)) (app-exp (parse (car datum)) (parse (cadr datum)))) (else (eopl:error 'parse "Invalid syntax: ~s" datum))))
f79235a07ec834e06512b2f47b007acce1f3f30312292263d4802bf5501e685a
haguenau/wyrd
interface_draw.ml
-- a curses - based front - end for Remind * Copyright ( C ) 2005 , 2006 , 2007 , 2008 , 2010 , 2011 - 2013 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License , Version 2 , * as published by the Free Software Foundation . * * 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 * * Bug reports can be entered at . * For anything else , feel free to contact at < > . * Copyright (C) 2005, 2006, 2007, 2008, 2010, 2011-2013 Paul Pelzl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, Version 2, * as published by the Free Software Foundation. * * 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 * * Bug reports can be entered at . * For anything else, feel free to contact Paul Pelzl at <>. *) (* interface_draw.ml * All drawing operations are found here. *) open Interface open Curses open Remind open Utility (* sort timed lineinfo entries by starting timestamp *) let sort_lineinfo line1 line2 = ~- (Pervasives.compare line1.tl_start line2.tl_start) Word - wrap a string -- split the string at whitespace boundaries * to form a list of strings , each of which has length less than * ' len ' . * to form a list of strings, each of which has length less than * 'len'. *) let word_wrap (s : string) (len : int) = let ws = Str.regexp "[\t ]+" in let split_words = Str.split ws s in let rec process_words words lines = match words with |[] -> List.rev lines |word :: remaining_words -> let word_len = utf8_len word in begin match lines with |[] -> process_words words [""] |line :: remaining_lines -> let line_len = utf8_len line in if word_len + line_len + 1 <= len then if line_len = 0 then process_words remaining_words (word :: remaining_lines) else process_words remaining_words ((line ^ " " ^ word) :: remaining_lines) else if word_len <= len then process_words remaining_words (word :: line :: remaining_lines) else (* No choice but to break the word apart *) let front = utf8_string_before word len and back = utf8_string_after word len in process_words (back :: remaining_words) (front :: line :: remaining_lines) end in process_words split_words [] Generate a 12 - hour clock representation of a time record let twelve_hour_string tm = if tm.Unix.tm_hour >= 12 then let hour = tm.Unix.tm_hour - 12 in if hour = 0 then Printf.sprintf "12:%.2dpm" tm.Unix.tm_min else Printf.sprintf "%d:%.2dpm" hour tm.Unix.tm_min else if tm.Unix.tm_hour = 0 then Printf.sprintf "12:%.2dam" tm.Unix.tm_min else Printf.sprintf "%d:%.2dam" tm.Unix.tm_hour tm.Unix.tm_min Generate a 12 - hour clock representation of a time record , with whitespace padding let twelve_hour_string_pad tm = if tm.Unix.tm_hour >= 12 then let hour = tm.Unix.tm_hour - 12 in if hour = 0 then Printf.sprintf "12:%.2dpm" tm.Unix.tm_min else Printf.sprintf "%2d:%.2dpm" hour tm.Unix.tm_min else if tm.Unix.tm_hour = 0 then Printf.sprintf "12:%.2dam" tm.Unix.tm_min else Printf.sprintf "%2d:%.2dam" tm.Unix.tm_hour tm.Unix.tm_min Generate a 24 - hour clock representation of a time record let twentyfour_hour_string tm = Printf.sprintf "%.2d:%.2d" tm.Unix.tm_hour tm.Unix.tm_min (* Draw a string in a specified window and location, using exactly 'len' * characters and truncating with ellipses if necessary. *) let trunc_mvwaddstr win line col len s = let fixed_s = let s_len = utf8_len s in if s_len <= len then let pad = String.make (len - s_len) ' ' in s ^ pad else if len >= 3 then (utf8_string_before s (len - 3)) ^ "..." else if len >= 0 then utf8_string_before s len else "" in assert (mvwaddstr win line col fixed_s) Draw the one - line help window at the top of the screen let draw_help (iface : interface_state_t) = Rcfile.color_on iface.scr.help_win Rcfile.Help; wattron iface.scr.help_win (A.bold lor A.underline); let rec build_help_line operations s = match operations with |[] -> s |(op, op_string) :: tail -> try let key_string = Rcfile.key_of_command op in build_help_line tail (s ^ key_string ^ ":" ^ op_string ^ " ") with Not_found -> build_help_line tail s in let help_string = build_help_line [(Rcfile.ViewKeybindings, "help"); (Rcfile.NewTimed, "new timed"); (Rcfile.NewUntimed, "new untimed"); (Rcfile.Edit, "edit"); (Rcfile.Home, "home"); (Rcfile.Zoom, "zoom"); (Rcfile.BeginSearch, "search"); (Rcfile.Quit, "quit")] "" in trunc_mvwaddstr iface.scr.help_win 0 0 iface.scr.hw_cols help_string; assert (wnoutrefresh iface.scr.help_win) Draw the vertical date strip at the left of the timed window . * Note : non - trivial . * The first date stamp is a special case ; it is drawn at the top * of the screen and truncated at the beginning to fit before the * first date change . The remaining date stamps are all drawn immediately * after any date changes , and truncated at the end to fit in the * window . * Step 1 : determine the line numbers on which the dates change * Step 2 : create a string to represent the vertical strip * Step 3 : draw each of the characters of the string onto the window * Note: non-trivial. * The first date stamp is a special case; it is drawn at the top * of the screen and truncated at the beginning to fit before the * first date change. The remaining date stamps are all drawn immediately * after any date changes, and truncated at the end to fit in the * window. * Step 1: determine the line numbers on which the dates change * Step 2: create a string to represent the vertical strip * Step 3: draw each of the characters of the string onto the window *) let draw_date_strip (iface : interface_state_t) = (* draw the vertical line to the right of the date string *) let acs = get_acs_codes () in Rcfile.color_on iface.scr.timed_win Rcfile.Left_divider; wattron iface.scr.timed_win A.bold; mvwvline iface.scr.timed_win 0 1 acs.Acs.vline iface.scr.tw_lines; Rcfile.color_off iface.scr.timed_win Rcfile.Left_divider; (* determine the line numbers and timestamps of any date changes within the * timed window *) let rec check_timestamp date_changes timestamp line = if line >= iface.scr.tw_lines then date_changes else let timestamp_tm = Unix.localtime timestamp in let next_timestamp = timestamp +. (time_inc iface) in let temp = { timestamp_tm with Unix.tm_sec = 0; Unix.tm_min = ~- (time_inc_min iface); Unix.tm_hour = 0 } in let (_, before_midnight) = Unix.mktime temp in if timestamp_tm.Unix.tm_min = before_midnight.Unix.tm_min && timestamp_tm.Unix.tm_hour = before_midnight.Unix.tm_hour then check_timestamp ((line, timestamp) :: date_changes) next_timestamp (succ line) else check_timestamp date_changes next_timestamp (succ line) in let date_changes = List.rev (check_timestamp [] iface.top_timestamp 0) in (* generate a string to represent the vertical strip *) let date_chars = if List.length date_changes > 0 then begin (* special case for the top date string, which is always at the * top of the screen *) let (line, timestamp) = List.hd date_changes in let tm = Unix.localtime timestamp in let top_date_str = if line >= 7 then (* the date will fit completely *) (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) ^ (String.make (line - 7) ' ') else (* there's not enough room for the date, so truncate it *) Str.last_chars (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) line in (* all other dates are just rendered at the top of their respective windows *) let rec add_date date_str changes = match changes with | [] -> date_str | (line, timestamp) :: tail -> let tm = Unix.localtime timestamp in let temp = { tm with Unix.tm_mday = succ tm.Unix.tm_mday } in let (_, next_day) = Unix.mktime temp in let s_len = if List.length tail > 0 then let (next_line, _) = List.hd tail in next_line - line else iface.scr.tw_lines - line in let temp_s = (Printf.sprintf "-%s %.2d" (string_of_tm_mon next_day.Unix.tm_mon) next_day.Unix.tm_mday) ^ (String.make 100 ' ') in add_date (date_str ^ (Str.string_before temp_s s_len)) tail in add_date top_date_str date_changes end else (* if there are no date changes (e.g. for small window) then just grab the proper * date from the top_timestamp *) let tm = Unix.localtime iface.top_timestamp in (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) ^ (String.make (iface.scr.tw_lines - 6) ' ') in draw the date string vertically , one character at a time for i = 0 to pred iface.scr.tw_lines do if date_chars.[i] = '-' then begin wattron iface.scr.timed_win A.underline; Rcfile.color_on iface.scr.timed_win Rcfile.Timed_date; assert (mvwaddch iface.scr.timed_win i 0 acs.Acs.hline); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_date; Rcfile.color_on iface.scr.timed_win Rcfile.Left_divider; assert (mvwaddch iface.scr.timed_win i 1 acs.Acs.rtee); Rcfile.color_off iface.scr.timed_win Rcfile.Left_divider; wattroff iface.scr.timed_win A.underline; end else begin Rcfile.color_on iface.scr.timed_win Rcfile.Timed_date; assert (mvwaddch iface.scr.timed_win i 0 (int_of_char date_chars.[i])); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_date; end done; wattroff iface.scr.timed_win (A.bold lor A.underline); assert (wnoutrefresh iface.scr.timed_win) Draw a portion of the timed schedule . The algorithm iterates across all * reminders in a three month period , and draws them in one by one . An array * is used to keep track of which lines have not yet been drawn , so that these * can be filled in later . * * This routine also updates iface.timed_lineinfo . * reminders in a three month period, and draws them in one by one. An array * is used to keep track of which lines have not yet been drawn, so that these * can be filled in later. * * This routine also updates iface.timed_lineinfo. *) let draw_timed_window iface reminders top lines = let round_down x = if x >= 0.0 then int_of_float x else pred (int_of_float x) in let indent_colors = [| Rcfile.Timed_reminder1; Rcfile.Timed_reminder2; Rcfile.Timed_reminder3; Rcfile.Timed_reminder4 |] in let acs = get_acs_codes () in let blank = String.make iface.scr.tw_cols ' ' in let top_timestamp = timestamp_of_line iface top in let top_tm = Unix.localtime top_timestamp in let temp = { top_tm with Unix.tm_sec = 0; Unix.tm_min = ~- (time_inc_min iface); Unix.tm_hour = 0 } in let (_, before_midnight) = Unix.mktime temp in let string_of_tm = if !Rcfile.schedule_12_hour then twelve_hour_string_pad else twentyfour_hour_string in (* this ensures that if there are multiple reminder descriptions * displayed simultaneously, the dashes between start and end times * will line up properly *) let (desc_string_of_tm1, desc_string_of_tm2) = if !Rcfile.description_12_hour then (twelve_hour_string_pad, twelve_hour_string) else (twentyfour_hour_string, twentyfour_hour_string) in Rcfile.color_on iface.scr.timed_win Rcfile.Timed_default; (* draw in the blank timeslots *) for i = top to pred (top + lines) do iface.timed_lineinfo.(i) <- []; if i = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; let ts = timestamp_of_line iface i in let tm = Unix.localtime ts in let ts_str = string_of_tm tm in let curr_ts = Unix.time () in (* the current time is highlighted *) if curr_ts >= ts && curr_ts < (timestamp_of_line iface (succ i)) then begin Rcfile.color_on iface.scr.timed_win Rcfile.Timed_current; wattron iface.scr.timed_win A.bold end else (); if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; assert (mvwaddstr iface.scr.timed_win i 2 ts_str); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_current; wattroff iface.scr.timed_win A.bold; Rcfile.color_on iface.scr.timed_win Rcfile.Timed_default; let s = Str.string_before blank (iface.scr.tw_cols - 7) in assert (mvwaddstr iface.scr.timed_win i 7 s) done; Rcfile.color_off iface.scr.timed_win Rcfile.Timed_default; wattroff iface.scr.timed_win (A.reverse lor A.underline); (* draw in the timed reminders *) let rec process_reminders rem_list indent = Rcfile.color_on iface.scr.timed_win indent_colors.(indent); wattron iface.scr.timed_win A.bold; begin match rem_list with |[] -> () |rem :: tail -> let rem_top_line = round_down ((rem.tr_start -. iface.top_timestamp) /. (time_inc iface)) in let get_time_str () = if rem.tr_end > rem.tr_start then (desc_string_of_tm1 (Unix.localtime rem.tr_start)) ^ "-" ^ (desc_string_of_tm2 (Unix.localtime rem.tr_end)) ^ " " else (desc_string_of_tm1 (Unix.localtime rem.tr_start)) ^ " " in (* draw the top line of a reminder *) let clock_pad = if !Rcfile.schedule_12_hour then 10 else 8 in if rem_top_line >= top && rem_top_line < top + lines then begin let time_str = get_time_str () in let ts = timestamp_of_line iface rem_top_line in let tm = Unix.localtime ts in if rem_top_line = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; let curr_lineinfo = { tl_filename = rem.tr_filename; tl_linenum = rem.tr_linenum; tl_timestr = time_str; tl_msg = rem.tr_msg; tl_start = rem.tr_start } in iface.timed_lineinfo.(rem_top_line) <- (curr_lineinfo :: iface.timed_lineinfo.(rem_top_line)); trunc_mvwaddstr iface.scr.timed_win rem_top_line (clock_pad + (9 * indent)) (iface.scr.tw_cols - clock_pad - (9 * indent)) (" " ^ rem.tr_msg); assert (mvwaddch iface.scr.timed_win rem_top_line (clock_pad + (9 * indent)) acs.Acs.vline) end else (); (* draw any remaining lines of this reminder, as determined by the duration *) let count = ref 1 in while ((timestamp_of_line iface (rem_top_line + !count)) < rem.tr_end) && (rem_top_line + !count < top + lines) do if rem_top_line + !count >= top then begin let time_str = get_time_str () in let ts = timestamp_of_line iface (rem_top_line + !count) in let tm = Unix.localtime ts in if rem_top_line + !count = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; let curr_lineinfo = { tl_filename = rem.tr_filename; tl_linenum = rem.tr_linenum; tl_timestr = time_str; tl_msg = rem.tr_msg; tl_start = rem.tr_start } in iface.timed_lineinfo.(rem_top_line + !count) <- (curr_lineinfo :: iface.timed_lineinfo.(rem_top_line + !count)); trunc_mvwaddstr iface.scr.timed_win (rem_top_line + !count) (clock_pad + (9 * indent)) (iface.scr.tw_cols - clock_pad - (9 * indent)) " "; assert (mvwaddch iface.scr.timed_win (rem_top_line + !count) (clock_pad + (9 * indent)) acs.Acs.vline) end else (); count := succ !count done; (* The reminders list is sorted chronologically, so once we hit a reminder * that falls after the end of the calendar window we can stop. *) if rem_top_line < top + lines then process_reminders tail indent else () end; Rcfile.color_off iface.scr.timed_win indent_colors.(indent) in (* reminders are rendered in order of indentation level, so the reminders with * higher indentation overlap those with lower indentation *) for indent = 0 to pred (Array.length reminders) do process_reminders reminders.(indent) indent done; wattroff iface.scr.timed_win (A.bold lor A.reverse); assert (wnoutrefresh iface.scr.timed_win) (* Draw the entire timed reminders window *) let draw_timed iface reminders = draw_timed_window iface reminders 0 iface.scr.tw_lines; {iface with last_timed_refresh = Unix.time ()} (* Draw just a portion of the timed window when possible. If * iface.last_timed_refresh indicates that the display is stale, * then do a whole-window update. This is to make sure that the * current timeslot gets highlighted properly, and old highlights * get erased. *) let draw_timed_try_window iface reminders top lines = let curr_tm = Unix.localtime (Unix.time ()) in let timeslot = round_time iface.zoom_level curr_tm in let (ts, _) = Unix.mktime timeslot in if iface.last_timed_refresh < ts then draw_timed iface reminders else begin draw_timed_window iface reminders top lines; iface end (* render a calendar for the given reminders record *) let draw_calendar (iface : interface_state_t) (reminders : three_month_rem_t) : unit = let sel_tm = Unix.localtime (timestamp_of_line iface iface.left_selection) and today_tm = Unix.localtime (Unix.time()) in let cal = reminders.curr_cal in let acs = get_acs_codes () in Rcfile.color_on iface.scr.calendar_win Rcfile.Right_divider; wattron iface.scr.calendar_win A.bold; mvwvline iface.scr.calendar_win 0 0 acs.Acs.vline iface.scr.cw_lines; Rcfile.color_off iface.scr.calendar_win Rcfile.Right_divider; let hspacer = (iface.scr.cw_cols - 20) / 2 in let vspacer = (iface.scr.cw_lines - 8) / 2 in assert (wmove iface.scr.calendar_win vspacer hspacer); wclrtoeol iface.scr.calendar_win; Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_labels; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win cal.Cal.title); wattroff iface.scr.calendar_win A.bold; assert (wmove iface.scr.calendar_win (vspacer + 1) hspacer); wclrtoeol iface.scr.calendar_win; assert (waddstr iface.scr.calendar_win cal.Cal.weekdays); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_labels; (* draw the day numbers *) let ws = Str.regexp " " in let rec draw_week weeks line = match weeks with | [] -> assert (wmove iface.scr.calendar_win line hspacer); wclrtoeol iface.scr.calendar_win | week :: tail -> let split_week = Str.full_split ws week in assert (wmove iface.scr.calendar_win line hspacer); wclrtoeol iface.scr.calendar_win; let rec draw_el elements = match elements with | [] -> () | el :: days -> begin match el with |Str.Delim s -> assert (waddstr iface.scr.calendar_win s) |Str.Text d -> let day = pred (int_of_string d) in if succ day = sel_tm.Unix.tm_mday then begin (* highlight selected day in reverse video *) wattron iface.scr.calendar_win A.reverse; assert ( waddstr iface.scr.calendar_win d ) ; end else (); if today_tm.Unix.tm_year = sel_tm.Unix.tm_year && today_tm.Unix.tm_mon = sel_tm.Unix.tm_mon && succ day = today_tm.Unix.tm_mday then begin highlight today 's date Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_today; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_today; wattroff iface.scr.calendar_win A.bold end else if reminders.curr_counts.(day) <= !Rcfile.busy_level1 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level1; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level1 end else if reminders.curr_counts.(day) <= !Rcfile.busy_level2 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level2; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level2 end else if reminders.curr_counts.(day) <= !Rcfile.busy_level3 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level2; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level2; wattroff iface.scr.calendar_win A.bold end else if reminders.curr_counts.(day) <= !Rcfile.busy_level4 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level3; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level3 end else begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level3; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level3; wattroff iface.scr.calendar_win A.bold end; wattroff iface.scr.calendar_win A.reverse end; draw_el days in draw_el split_week; draw_week tail (succ line) in draw_week cal.Cal.days (vspacer + 2); draw the week numbers if !Rcfile.number_weeks then begin let weeknum_col = hspacer + (utf8_len cal.Cal.weekdays) + 2 in Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_labels; assert (wmove iface.scr.calendar_win (vspacer + 1) weeknum_col); assert (waddch iface.scr.calendar_win acs.Acs.vline); assert (waddstr iface.scr.calendar_win "Wk#"); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_labels; let rec print_weeknum weeknums line = match weeknums with | [] -> () | weeknum :: tail -> assert (wmove iface.scr.calendar_win (vspacer + line) weeknum_col); assert (waddch iface.scr.calendar_win acs.Acs.vline); assert (waddstr iface.scr.calendar_win weeknum); print_weeknum tail (succ line); in print_weeknum cal.Cal.weeknums 2; end else (); assert (wnoutrefresh iface.scr.calendar_win) (* Draw the untimed reminders window *) let draw_untimed (iface : interface_state_t) reminders = let lineinfo = Array.make iface.scr.uw_lines None in let blank = String.make iface.scr.uw_cols ' ' in let curr_ts = timestamp_of_line iface iface.left_selection in let today_reminders = Remind.get_untimed_reminders_for_day reminders curr_ts in werase iface.scr.untimed_win; let acs = get_acs_codes () in Rcfile.color_on iface.scr.untimed_win Rcfile.Right_divider; wattron iface.scr.untimed_win A.bold; assert (mvwaddch iface.scr.untimed_win 0 0 acs.Acs.ltee); mvwhline iface.scr.untimed_win 0 1 acs.Acs.hline (pred iface.scr.uw_cols); mvwvline iface.scr.untimed_win 1 0 acs.Acs.vline (pred iface.scr.uw_lines); Rcfile.color_off iface.scr.untimed_win Rcfile.Right_divider; if not !Rcfile.untimed_bold then wattroff iface.scr.untimed_win A.bold else (); Rcfile.color_on iface.scr.untimed_win Rcfile.Untimed_reminder; (* make sure the cursor doesn't unexpectedly disappear *) let iface = if iface.selected_side = Right && iface.right_selection > List.length today_reminders then if List.length today_reminders = 0 then { iface with right_selection = 1; } else { iface with right_selection = List.length today_reminders } else iface in let rec render_lines rem_list n line = match rem_list with |[] -> if n = 0 && iface.selected_side = Right then begin wattron iface.scr.untimed_win A.reverse; trunc_mvwaddstr iface.scr.untimed_win line 2 (iface.scr.uw_cols - 3) blank; wattroff iface.scr.untimed_win A.reverse end else () |rem :: tail -> if line < iface.scr.uw_lines then if n >= iface.top_untimed then begin if line = iface.right_selection && iface.selected_side = Right then wattron iface.scr.untimed_win A.reverse else wattroff iface.scr.untimed_win A.reverse; trunc_mvwaddstr iface.scr.untimed_win line 2 (iface.scr.uw_cols - 3) ("* " ^ rem.ur_msg); let curr_lineinfo = { ul_filename = rem.ur_filename; ul_linenum = rem.ur_linenum; ul_msg = rem.ur_msg } in lineinfo.(line) <- Some curr_lineinfo; render_lines tail (succ n) (succ line) end else render_lines tail (succ n) line else () in render_lines today_reminders 0 1; Rcfile.color_off iface.scr.untimed_win Rcfile.Untimed_reminder; wattroff iface.scr.untimed_win (A.bold lor A.reverse); (* if there's not enough window space to display all untimed reminders, display * arrows to indicate scrolling ability *) if iface.top_untimed > 0 then begin assert (mvwaddch iface.scr.untimed_win 1 (pred iface.scr.uw_cols) (int_of_char '^')); assert (mvwaddch iface.scr.untimed_win 2 (pred iface.scr.uw_cols) (int_of_char '^')) end else (); if List.length today_reminders > pred iface.scr.uw_lines + iface.top_untimed then begin assert (mvwaddch iface.scr.untimed_win (pred iface.scr.uw_lines) (pred iface.scr.uw_cols) (int_of_char 'v')); assert (mvwaddch iface.scr.untimed_win (iface.scr.uw_lines - 2) (pred iface.scr.uw_cols) (int_of_char 'v')) end else (); assert (wnoutrefresh iface.scr.untimed_win); {iface with untimed_lineinfo = lineinfo; len_untimed = List.length today_reminders} (* Draw the message window *) let draw_msg iface = let sel_tm = Unix.localtime (timestamp_of_line iface iface.left_selection) in let day_s = Printf.sprintf "%s, %s %.2d" (full_string_of_tm_wday sel_tm.Unix.tm_wday) (full_string_of_tm_mon sel_tm.Unix.tm_mon) sel_tm.Unix.tm_mday in let day_time_s = match iface.selected_side with |Left -> day_s ^ " at " ^ if !Rcfile.selection_12_hour then twelve_hour_string sel_tm else twentyfour_hour_string sel_tm |Right -> day_s in for i = 0 to pred iface.scr.mw_lines do assert (wmove iface.scr.msg_win i 0); wclrtoeol iface.scr.msg_win done; (* draw the date stamp *) Rcfile.color_on iface.scr.msg_win Rcfile.Selection_info; wattron iface.scr.msg_win (A.bold lor A.underline); trunc_mvwaddstr iface.scr.msg_win 0 0 iface.scr.mw_cols day_time_s; Rcfile.color_off iface.scr.msg_win Rcfile.Selection_info; wattroff iface.scr.msg_win (A.bold lor A.underline); (* draw the current date *) let curr_tm = Unix.localtime (Unix.time ()) in Rcfile.color_on iface.scr.msg_win Rcfile.Status; wattron iface.scr.msg_win A.bold; let curr_tm_str = if !Rcfile.status_12_hour then twelve_hour_string curr_tm else twentyfour_hour_string curr_tm in let s = Printf.sprintf "Wyrd v%s Currently: %s, %s %.2d at %s" Version.version (full_string_of_tm_wday curr_tm.Unix.tm_wday) (full_string_of_tm_mon curr_tm.Unix.tm_mon) curr_tm.Unix.tm_mday curr_tm_str in trunc_mvwaddstr iface.scr.msg_win (pred iface.scr.mw_lines) 0 iface.scr.mw_cols s; Rcfile.color_off iface.scr.msg_win Rcfile.Status; wattroff iface.scr.msg_win A.bold; (* draw the full MSG string, word wrapping as necessary *) let pad = String.make 16 ' ' in let rec render_desc times descriptions output = let rec render_line lines temp_output = match lines with |[] -> temp_output |line :: lines_tail -> render_line lines_tail ((pad ^ line) :: temp_output) in match descriptions with |[] -> List.rev output |desc :: desc_tail -> let time_str = Str.string_before ((List.hd times) ^ pad) 16 in let first_line = time_str ^ (List.hd desc) in render_desc (List.tl times) desc_tail ((render_line (List.tl desc) []) @ first_line :: output) in let (times, descriptions) = match iface.selected_side with |Left -> begin match iface.timed_lineinfo.(iface.left_selection) with |[] -> ([""], [["(no reminder selected)"]]) |rem_list -> let sorted_rem_list = List.fast_sort sort_lineinfo rem_list in let get_times tline = tline.tl_timestr in let get_lines tline = word_wrap tline.tl_msg (iface.scr.mw_cols - 24) in (List.rev_map get_times sorted_rem_list, List.rev_map get_lines sorted_rem_list) end |Right -> begin match iface.untimed_lineinfo.(iface.right_selection) with |None -> ([""], [["(no reminder selected)"]]) |Some uline -> ([""], [word_wrap uline.ul_msg (iface.scr.mw_cols - 24)]) end in let desc_lines = render_desc times descriptions [] in (* draw the pre-rendered lines to the screen *) Rcfile.color_on iface.scr.msg_win Rcfile.Description; let rec draw_desc_lines lines start line_num = match lines with |[] -> () |line :: tail -> if start > 0 then draw_desc_lines tail (pred start) line_num else if line_num < pred iface.scr.mw_lines then begin assert (mvwaddstr iface.scr.msg_win line_num 5 line); draw_desc_lines tail start (succ line_num) end else () in let adjusted_top = let max_top = max ((List.length desc_lines) - iface.scr.mw_lines + 2) 0 in min iface.top_desc max_top in draw_desc_lines desc_lines adjusted_top 1; if adjusted_top > 0 then begin assert (mvwaddch iface.scr.msg_win 1 (iface.scr.mw_cols - 1) (int_of_char '^')); assert (mvwaddch iface.scr.msg_win 2 (iface.scr.mw_cols - 1) (int_of_char '^')) end else (); if adjusted_top < List.length desc_lines - iface.scr.mw_lines + 2 then begin assert (mvwaddch iface.scr.msg_win (iface.scr.mw_lines - 2) (iface.scr.mw_cols - 1) (int_of_char 'v')); assert (mvwaddch iface.scr.msg_win (iface.scr.mw_lines - 3) (iface.scr.mw_cols - 1) (int_of_char 'v')) end else (); Rcfile.color_off iface.scr.msg_win Rcfile.Description; assert (wnoutrefresh iface.scr.msg_win); {iface with top_desc = adjusted_top} (* Draw a message in the error window. If draw_cursor = true, then * add a blinking cursor at the end of the message. *) let draw_error iface err draw_cursor = werase iface.scr.err_win; trunc_mvwaddstr iface.scr.err_win 0 0 iface.scr.ew_cols err; let len = utf8_len err in if draw_cursor && len <= pred iface.scr.ew_cols then begin wattron iface.scr.err_win A.blink; assert (mvwaddch iface.scr.err_win 0 len (int_of_char '_')); wattroff iface.scr.err_win A.blink end else (); assert (wnoutrefresh iface.scr.err_win) (* Draw a selection dialog. *) let draw_selection_dialog (iface : interface_state_t) (title : string) (elements : string list) (selection : int) (top : int) = erase (); (* draw the title *) Rcfile.color_on iface.scr.stdscr Rcfile.Help; attron A.bold; trunc_mvwaddstr iface.scr.stdscr 0 0 iface.scr.cols title; Rcfile.color_off iface.scr.stdscr Rcfile.Help; attroff A.bold; (* draw the list elements *) Rcfile.color_on iface.scr.stdscr Rcfile.Untimed_reminder; let rec draw_element el_list line count = match el_list with | [] -> () | el :: tail -> if count >= top && line < iface.scr.lines then begin if count = selection then begin attron A.reverse; trunc_mvwaddstr iface.scr.stdscr line 2 (iface.scr.cols - 4) el; attroff A.reverse; end else trunc_mvwaddstr iface.scr.stdscr line 2 (iface.scr.cols - 4) el; draw_element tail (succ line) (succ count) end else draw_element tail line (succ count) in draw_element elements 1 0; (* if there's not enough window space to display all reminder files, display * arrows to indicate scrolling ability *) if top > 0 then begin assert (mvaddch 1 (iface.scr.cols - 2) (int_of_char '^')); assert (mvaddch 2 (iface.scr.cols - 2) (int_of_char '^')) end else (); if List.length elements > pred iface.scr.lines + top then begin assert (mvaddch (pred iface.scr.lines) (iface.scr.cols - 2) (int_of_char 'v')); assert (mvaddch (iface.scr.lines - 2) (iface.scr.cols - 2) (int_of_char 'v')) end else (); Rcfile.color_off iface.scr.stdscr Rcfile.Untimed_reminder; assert (refresh ()) arch - tag : - 410f-8fcf-6dfcf94b346a
null
https://raw.githubusercontent.com/haguenau/wyrd/490ce39ad9ecf36969eb74b9f882f85a1ef14ba3/interface_draw.ml
ocaml
interface_draw.ml * All drawing operations are found here. sort timed lineinfo entries by starting timestamp No choice but to break the word apart Draw a string in a specified window and location, using exactly 'len' * characters and truncating with ellipses if necessary. draw the vertical line to the right of the date string determine the line numbers and timestamps of any date changes within the * timed window generate a string to represent the vertical strip special case for the top date string, which is always at the * top of the screen the date will fit completely there's not enough room for the date, so truncate it all other dates are just rendered at the top of their respective windows if there are no date changes (e.g. for small window) then just grab the proper * date from the top_timestamp this ensures that if there are multiple reminder descriptions * displayed simultaneously, the dashes between start and end times * will line up properly draw in the blank timeslots the current time is highlighted draw in the timed reminders draw the top line of a reminder draw any remaining lines of this reminder, as determined by the duration The reminders list is sorted chronologically, so once we hit a reminder * that falls after the end of the calendar window we can stop. reminders are rendered in order of indentation level, so the reminders with * higher indentation overlap those with lower indentation Draw the entire timed reminders window Draw just a portion of the timed window when possible. If * iface.last_timed_refresh indicates that the display is stale, * then do a whole-window update. This is to make sure that the * current timeslot gets highlighted properly, and old highlights * get erased. render a calendar for the given reminders record draw the day numbers highlight selected day in reverse video Draw the untimed reminders window make sure the cursor doesn't unexpectedly disappear if there's not enough window space to display all untimed reminders, display * arrows to indicate scrolling ability Draw the message window draw the date stamp draw the current date draw the full MSG string, word wrapping as necessary draw the pre-rendered lines to the screen Draw a message in the error window. If draw_cursor = true, then * add a blinking cursor at the end of the message. Draw a selection dialog. draw the title draw the list elements if there's not enough window space to display all reminder files, display * arrows to indicate scrolling ability
-- a curses - based front - end for Remind * Copyright ( C ) 2005 , 2006 , 2007 , 2008 , 2010 , 2011 - 2013 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License , Version 2 , * as published by the Free Software Foundation . * * 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 * * Bug reports can be entered at . * For anything else , feel free to contact at < > . * Copyright (C) 2005, 2006, 2007, 2008, 2010, 2011-2013 Paul Pelzl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, Version 2, * as published by the Free Software Foundation. * * 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 * * Bug reports can be entered at . * For anything else, feel free to contact Paul Pelzl at <>. *) open Interface open Curses open Remind open Utility let sort_lineinfo line1 line2 = ~- (Pervasives.compare line1.tl_start line2.tl_start) Word - wrap a string -- split the string at whitespace boundaries * to form a list of strings , each of which has length less than * ' len ' . * to form a list of strings, each of which has length less than * 'len'. *) let word_wrap (s : string) (len : int) = let ws = Str.regexp "[\t ]+" in let split_words = Str.split ws s in let rec process_words words lines = match words with |[] -> List.rev lines |word :: remaining_words -> let word_len = utf8_len word in begin match lines with |[] -> process_words words [""] |line :: remaining_lines -> let line_len = utf8_len line in if word_len + line_len + 1 <= len then if line_len = 0 then process_words remaining_words (word :: remaining_lines) else process_words remaining_words ((line ^ " " ^ word) :: remaining_lines) else if word_len <= len then process_words remaining_words (word :: line :: remaining_lines) else let front = utf8_string_before word len and back = utf8_string_after word len in process_words (back :: remaining_words) (front :: line :: remaining_lines) end in process_words split_words [] Generate a 12 - hour clock representation of a time record let twelve_hour_string tm = if tm.Unix.tm_hour >= 12 then let hour = tm.Unix.tm_hour - 12 in if hour = 0 then Printf.sprintf "12:%.2dpm" tm.Unix.tm_min else Printf.sprintf "%d:%.2dpm" hour tm.Unix.tm_min else if tm.Unix.tm_hour = 0 then Printf.sprintf "12:%.2dam" tm.Unix.tm_min else Printf.sprintf "%d:%.2dam" tm.Unix.tm_hour tm.Unix.tm_min Generate a 12 - hour clock representation of a time record , with whitespace padding let twelve_hour_string_pad tm = if tm.Unix.tm_hour >= 12 then let hour = tm.Unix.tm_hour - 12 in if hour = 0 then Printf.sprintf "12:%.2dpm" tm.Unix.tm_min else Printf.sprintf "%2d:%.2dpm" hour tm.Unix.tm_min else if tm.Unix.tm_hour = 0 then Printf.sprintf "12:%.2dam" tm.Unix.tm_min else Printf.sprintf "%2d:%.2dam" tm.Unix.tm_hour tm.Unix.tm_min Generate a 24 - hour clock representation of a time record let twentyfour_hour_string tm = Printf.sprintf "%.2d:%.2d" tm.Unix.tm_hour tm.Unix.tm_min let trunc_mvwaddstr win line col len s = let fixed_s = let s_len = utf8_len s in if s_len <= len then let pad = String.make (len - s_len) ' ' in s ^ pad else if len >= 3 then (utf8_string_before s (len - 3)) ^ "..." else if len >= 0 then utf8_string_before s len else "" in assert (mvwaddstr win line col fixed_s) Draw the one - line help window at the top of the screen let draw_help (iface : interface_state_t) = Rcfile.color_on iface.scr.help_win Rcfile.Help; wattron iface.scr.help_win (A.bold lor A.underline); let rec build_help_line operations s = match operations with |[] -> s |(op, op_string) :: tail -> try let key_string = Rcfile.key_of_command op in build_help_line tail (s ^ key_string ^ ":" ^ op_string ^ " ") with Not_found -> build_help_line tail s in let help_string = build_help_line [(Rcfile.ViewKeybindings, "help"); (Rcfile.NewTimed, "new timed"); (Rcfile.NewUntimed, "new untimed"); (Rcfile.Edit, "edit"); (Rcfile.Home, "home"); (Rcfile.Zoom, "zoom"); (Rcfile.BeginSearch, "search"); (Rcfile.Quit, "quit")] "" in trunc_mvwaddstr iface.scr.help_win 0 0 iface.scr.hw_cols help_string; assert (wnoutrefresh iface.scr.help_win) Draw the vertical date strip at the left of the timed window . * Note : non - trivial . * The first date stamp is a special case ; it is drawn at the top * of the screen and truncated at the beginning to fit before the * first date change . The remaining date stamps are all drawn immediately * after any date changes , and truncated at the end to fit in the * window . * Step 1 : determine the line numbers on which the dates change * Step 2 : create a string to represent the vertical strip * Step 3 : draw each of the characters of the string onto the window * Note: non-trivial. * The first date stamp is a special case; it is drawn at the top * of the screen and truncated at the beginning to fit before the * first date change. The remaining date stamps are all drawn immediately * after any date changes, and truncated at the end to fit in the * window. * Step 1: determine the line numbers on which the dates change * Step 2: create a string to represent the vertical strip * Step 3: draw each of the characters of the string onto the window *) let draw_date_strip (iface : interface_state_t) = let acs = get_acs_codes () in Rcfile.color_on iface.scr.timed_win Rcfile.Left_divider; wattron iface.scr.timed_win A.bold; mvwvline iface.scr.timed_win 0 1 acs.Acs.vline iface.scr.tw_lines; Rcfile.color_off iface.scr.timed_win Rcfile.Left_divider; let rec check_timestamp date_changes timestamp line = if line >= iface.scr.tw_lines then date_changes else let timestamp_tm = Unix.localtime timestamp in let next_timestamp = timestamp +. (time_inc iface) in let temp = { timestamp_tm with Unix.tm_sec = 0; Unix.tm_min = ~- (time_inc_min iface); Unix.tm_hour = 0 } in let (_, before_midnight) = Unix.mktime temp in if timestamp_tm.Unix.tm_min = before_midnight.Unix.tm_min && timestamp_tm.Unix.tm_hour = before_midnight.Unix.tm_hour then check_timestamp ((line, timestamp) :: date_changes) next_timestamp (succ line) else check_timestamp date_changes next_timestamp (succ line) in let date_changes = List.rev (check_timestamp [] iface.top_timestamp 0) in let date_chars = if List.length date_changes > 0 then begin let (line, timestamp) = List.hd date_changes in let tm = Unix.localtime timestamp in let top_date_str = if line >= 7 then (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) ^ (String.make (line - 7) ' ') else Str.last_chars (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) line in let rec add_date date_str changes = match changes with | [] -> date_str | (line, timestamp) :: tail -> let tm = Unix.localtime timestamp in let temp = { tm with Unix.tm_mday = succ tm.Unix.tm_mday } in let (_, next_day) = Unix.mktime temp in let s_len = if List.length tail > 0 then let (next_line, _) = List.hd tail in next_line - line else iface.scr.tw_lines - line in let temp_s = (Printf.sprintf "-%s %.2d" (string_of_tm_mon next_day.Unix.tm_mon) next_day.Unix.tm_mday) ^ (String.make 100 ' ') in add_date (date_str ^ (Str.string_before temp_s s_len)) tail in add_date top_date_str date_changes end else let tm = Unix.localtime iface.top_timestamp in (Printf.sprintf " %s %.2d" (string_of_tm_mon tm.Unix.tm_mon) tm.Unix.tm_mday) ^ (String.make (iface.scr.tw_lines - 6) ' ') in draw the date string vertically , one character at a time for i = 0 to pred iface.scr.tw_lines do if date_chars.[i] = '-' then begin wattron iface.scr.timed_win A.underline; Rcfile.color_on iface.scr.timed_win Rcfile.Timed_date; assert (mvwaddch iface.scr.timed_win i 0 acs.Acs.hline); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_date; Rcfile.color_on iface.scr.timed_win Rcfile.Left_divider; assert (mvwaddch iface.scr.timed_win i 1 acs.Acs.rtee); Rcfile.color_off iface.scr.timed_win Rcfile.Left_divider; wattroff iface.scr.timed_win A.underline; end else begin Rcfile.color_on iface.scr.timed_win Rcfile.Timed_date; assert (mvwaddch iface.scr.timed_win i 0 (int_of_char date_chars.[i])); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_date; end done; wattroff iface.scr.timed_win (A.bold lor A.underline); assert (wnoutrefresh iface.scr.timed_win) Draw a portion of the timed schedule . The algorithm iterates across all * reminders in a three month period , and draws them in one by one . An array * is used to keep track of which lines have not yet been drawn , so that these * can be filled in later . * * This routine also updates iface.timed_lineinfo . * reminders in a three month period, and draws them in one by one. An array * is used to keep track of which lines have not yet been drawn, so that these * can be filled in later. * * This routine also updates iface.timed_lineinfo. *) let draw_timed_window iface reminders top lines = let round_down x = if x >= 0.0 then int_of_float x else pred (int_of_float x) in let indent_colors = [| Rcfile.Timed_reminder1; Rcfile.Timed_reminder2; Rcfile.Timed_reminder3; Rcfile.Timed_reminder4 |] in let acs = get_acs_codes () in let blank = String.make iface.scr.tw_cols ' ' in let top_timestamp = timestamp_of_line iface top in let top_tm = Unix.localtime top_timestamp in let temp = { top_tm with Unix.tm_sec = 0; Unix.tm_min = ~- (time_inc_min iface); Unix.tm_hour = 0 } in let (_, before_midnight) = Unix.mktime temp in let string_of_tm = if !Rcfile.schedule_12_hour then twelve_hour_string_pad else twentyfour_hour_string in let (desc_string_of_tm1, desc_string_of_tm2) = if !Rcfile.description_12_hour then (twelve_hour_string_pad, twelve_hour_string) else (twentyfour_hour_string, twentyfour_hour_string) in Rcfile.color_on iface.scr.timed_win Rcfile.Timed_default; for i = top to pred (top + lines) do iface.timed_lineinfo.(i) <- []; if i = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; let ts = timestamp_of_line iface i in let tm = Unix.localtime ts in let ts_str = string_of_tm tm in let curr_ts = Unix.time () in if curr_ts >= ts && curr_ts < (timestamp_of_line iface (succ i)) then begin Rcfile.color_on iface.scr.timed_win Rcfile.Timed_current; wattron iface.scr.timed_win A.bold end else (); if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; assert (mvwaddstr iface.scr.timed_win i 2 ts_str); Rcfile.color_off iface.scr.timed_win Rcfile.Timed_current; wattroff iface.scr.timed_win A.bold; Rcfile.color_on iface.scr.timed_win Rcfile.Timed_default; let s = Str.string_before blank (iface.scr.tw_cols - 7) in assert (mvwaddstr iface.scr.timed_win i 7 s) done; Rcfile.color_off iface.scr.timed_win Rcfile.Timed_default; wattroff iface.scr.timed_win (A.reverse lor A.underline); let rec process_reminders rem_list indent = Rcfile.color_on iface.scr.timed_win indent_colors.(indent); wattron iface.scr.timed_win A.bold; begin match rem_list with |[] -> () |rem :: tail -> let rem_top_line = round_down ((rem.tr_start -. iface.top_timestamp) /. (time_inc iface)) in let get_time_str () = if rem.tr_end > rem.tr_start then (desc_string_of_tm1 (Unix.localtime rem.tr_start)) ^ "-" ^ (desc_string_of_tm2 (Unix.localtime rem.tr_end)) ^ " " else (desc_string_of_tm1 (Unix.localtime rem.tr_start)) ^ " " in let clock_pad = if !Rcfile.schedule_12_hour then 10 else 8 in if rem_top_line >= top && rem_top_line < top + lines then begin let time_str = get_time_str () in let ts = timestamp_of_line iface rem_top_line in let tm = Unix.localtime ts in if rem_top_line = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; let curr_lineinfo = { tl_filename = rem.tr_filename; tl_linenum = rem.tr_linenum; tl_timestr = time_str; tl_msg = rem.tr_msg; tl_start = rem.tr_start } in iface.timed_lineinfo.(rem_top_line) <- (curr_lineinfo :: iface.timed_lineinfo.(rem_top_line)); trunc_mvwaddstr iface.scr.timed_win rem_top_line (clock_pad + (9 * indent)) (iface.scr.tw_cols - clock_pad - (9 * indent)) (" " ^ rem.tr_msg); assert (mvwaddch iface.scr.timed_win rem_top_line (clock_pad + (9 * indent)) acs.Acs.vline) end else (); let count = ref 1 in while ((timestamp_of_line iface (rem_top_line + !count)) < rem.tr_end) && (rem_top_line + !count < top + lines) do if rem_top_line + !count >= top then begin let time_str = get_time_str () in let ts = timestamp_of_line iface (rem_top_line + !count) in let tm = Unix.localtime ts in if rem_top_line + !count = iface.left_selection && iface.selected_side = Left then wattron iface.scr.timed_win A.reverse else wattroff iface.scr.timed_win A.reverse; if tm.Unix.tm_hour = before_midnight.Unix.tm_hour && tm.Unix.tm_min = before_midnight.Unix.tm_min then wattron iface.scr.timed_win A.underline else wattroff iface.scr.timed_win A.underline; let curr_lineinfo = { tl_filename = rem.tr_filename; tl_linenum = rem.tr_linenum; tl_timestr = time_str; tl_msg = rem.tr_msg; tl_start = rem.tr_start } in iface.timed_lineinfo.(rem_top_line + !count) <- (curr_lineinfo :: iface.timed_lineinfo.(rem_top_line + !count)); trunc_mvwaddstr iface.scr.timed_win (rem_top_line + !count) (clock_pad + (9 * indent)) (iface.scr.tw_cols - clock_pad - (9 * indent)) " "; assert (mvwaddch iface.scr.timed_win (rem_top_line + !count) (clock_pad + (9 * indent)) acs.Acs.vline) end else (); count := succ !count done; if rem_top_line < top + lines then process_reminders tail indent else () end; Rcfile.color_off iface.scr.timed_win indent_colors.(indent) in for indent = 0 to pred (Array.length reminders) do process_reminders reminders.(indent) indent done; wattroff iface.scr.timed_win (A.bold lor A.reverse); assert (wnoutrefresh iface.scr.timed_win) let draw_timed iface reminders = draw_timed_window iface reminders 0 iface.scr.tw_lines; {iface with last_timed_refresh = Unix.time ()} let draw_timed_try_window iface reminders top lines = let curr_tm = Unix.localtime (Unix.time ()) in let timeslot = round_time iface.zoom_level curr_tm in let (ts, _) = Unix.mktime timeslot in if iface.last_timed_refresh < ts then draw_timed iface reminders else begin draw_timed_window iface reminders top lines; iface end let draw_calendar (iface : interface_state_t) (reminders : three_month_rem_t) : unit = let sel_tm = Unix.localtime (timestamp_of_line iface iface.left_selection) and today_tm = Unix.localtime (Unix.time()) in let cal = reminders.curr_cal in let acs = get_acs_codes () in Rcfile.color_on iface.scr.calendar_win Rcfile.Right_divider; wattron iface.scr.calendar_win A.bold; mvwvline iface.scr.calendar_win 0 0 acs.Acs.vline iface.scr.cw_lines; Rcfile.color_off iface.scr.calendar_win Rcfile.Right_divider; let hspacer = (iface.scr.cw_cols - 20) / 2 in let vspacer = (iface.scr.cw_lines - 8) / 2 in assert (wmove iface.scr.calendar_win vspacer hspacer); wclrtoeol iface.scr.calendar_win; Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_labels; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win cal.Cal.title); wattroff iface.scr.calendar_win A.bold; assert (wmove iface.scr.calendar_win (vspacer + 1) hspacer); wclrtoeol iface.scr.calendar_win; assert (waddstr iface.scr.calendar_win cal.Cal.weekdays); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_labels; let ws = Str.regexp " " in let rec draw_week weeks line = match weeks with | [] -> assert (wmove iface.scr.calendar_win line hspacer); wclrtoeol iface.scr.calendar_win | week :: tail -> let split_week = Str.full_split ws week in assert (wmove iface.scr.calendar_win line hspacer); wclrtoeol iface.scr.calendar_win; let rec draw_el elements = match elements with | [] -> () | el :: days -> begin match el with |Str.Delim s -> assert (waddstr iface.scr.calendar_win s) |Str.Text d -> let day = pred (int_of_string d) in if succ day = sel_tm.Unix.tm_mday then begin wattron iface.scr.calendar_win A.reverse; assert ( waddstr iface.scr.calendar_win d ) ; end else (); if today_tm.Unix.tm_year = sel_tm.Unix.tm_year && today_tm.Unix.tm_mon = sel_tm.Unix.tm_mon && succ day = today_tm.Unix.tm_mday then begin highlight today 's date Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_today; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_today; wattroff iface.scr.calendar_win A.bold end else if reminders.curr_counts.(day) <= !Rcfile.busy_level1 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level1; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level1 end else if reminders.curr_counts.(day) <= !Rcfile.busy_level2 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level2; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level2 end else if reminders.curr_counts.(day) <= !Rcfile.busy_level3 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level2; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level2; wattroff iface.scr.calendar_win A.bold end else if reminders.curr_counts.(day) <= !Rcfile.busy_level4 then begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level3; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level3 end else begin Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_level3; wattron iface.scr.calendar_win A.bold; assert (waddstr iface.scr.calendar_win d); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_level3; wattroff iface.scr.calendar_win A.bold end; wattroff iface.scr.calendar_win A.reverse end; draw_el days in draw_el split_week; draw_week tail (succ line) in draw_week cal.Cal.days (vspacer + 2); draw the week numbers if !Rcfile.number_weeks then begin let weeknum_col = hspacer + (utf8_len cal.Cal.weekdays) + 2 in Rcfile.color_on iface.scr.calendar_win Rcfile.Calendar_labels; assert (wmove iface.scr.calendar_win (vspacer + 1) weeknum_col); assert (waddch iface.scr.calendar_win acs.Acs.vline); assert (waddstr iface.scr.calendar_win "Wk#"); Rcfile.color_off iface.scr.calendar_win Rcfile.Calendar_labels; let rec print_weeknum weeknums line = match weeknums with | [] -> () | weeknum :: tail -> assert (wmove iface.scr.calendar_win (vspacer + line) weeknum_col); assert (waddch iface.scr.calendar_win acs.Acs.vline); assert (waddstr iface.scr.calendar_win weeknum); print_weeknum tail (succ line); in print_weeknum cal.Cal.weeknums 2; end else (); assert (wnoutrefresh iface.scr.calendar_win) let draw_untimed (iface : interface_state_t) reminders = let lineinfo = Array.make iface.scr.uw_lines None in let blank = String.make iface.scr.uw_cols ' ' in let curr_ts = timestamp_of_line iface iface.left_selection in let today_reminders = Remind.get_untimed_reminders_for_day reminders curr_ts in werase iface.scr.untimed_win; let acs = get_acs_codes () in Rcfile.color_on iface.scr.untimed_win Rcfile.Right_divider; wattron iface.scr.untimed_win A.bold; assert (mvwaddch iface.scr.untimed_win 0 0 acs.Acs.ltee); mvwhline iface.scr.untimed_win 0 1 acs.Acs.hline (pred iface.scr.uw_cols); mvwvline iface.scr.untimed_win 1 0 acs.Acs.vline (pred iface.scr.uw_lines); Rcfile.color_off iface.scr.untimed_win Rcfile.Right_divider; if not !Rcfile.untimed_bold then wattroff iface.scr.untimed_win A.bold else (); Rcfile.color_on iface.scr.untimed_win Rcfile.Untimed_reminder; let iface = if iface.selected_side = Right && iface.right_selection > List.length today_reminders then if List.length today_reminders = 0 then { iface with right_selection = 1; } else { iface with right_selection = List.length today_reminders } else iface in let rec render_lines rem_list n line = match rem_list with |[] -> if n = 0 && iface.selected_side = Right then begin wattron iface.scr.untimed_win A.reverse; trunc_mvwaddstr iface.scr.untimed_win line 2 (iface.scr.uw_cols - 3) blank; wattroff iface.scr.untimed_win A.reverse end else () |rem :: tail -> if line < iface.scr.uw_lines then if n >= iface.top_untimed then begin if line = iface.right_selection && iface.selected_side = Right then wattron iface.scr.untimed_win A.reverse else wattroff iface.scr.untimed_win A.reverse; trunc_mvwaddstr iface.scr.untimed_win line 2 (iface.scr.uw_cols - 3) ("* " ^ rem.ur_msg); let curr_lineinfo = { ul_filename = rem.ur_filename; ul_linenum = rem.ur_linenum; ul_msg = rem.ur_msg } in lineinfo.(line) <- Some curr_lineinfo; render_lines tail (succ n) (succ line) end else render_lines tail (succ n) line else () in render_lines today_reminders 0 1; Rcfile.color_off iface.scr.untimed_win Rcfile.Untimed_reminder; wattroff iface.scr.untimed_win (A.bold lor A.reverse); if iface.top_untimed > 0 then begin assert (mvwaddch iface.scr.untimed_win 1 (pred iface.scr.uw_cols) (int_of_char '^')); assert (mvwaddch iface.scr.untimed_win 2 (pred iface.scr.uw_cols) (int_of_char '^')) end else (); if List.length today_reminders > pred iface.scr.uw_lines + iface.top_untimed then begin assert (mvwaddch iface.scr.untimed_win (pred iface.scr.uw_lines) (pred iface.scr.uw_cols) (int_of_char 'v')); assert (mvwaddch iface.scr.untimed_win (iface.scr.uw_lines - 2) (pred iface.scr.uw_cols) (int_of_char 'v')) end else (); assert (wnoutrefresh iface.scr.untimed_win); {iface with untimed_lineinfo = lineinfo; len_untimed = List.length today_reminders} let draw_msg iface = let sel_tm = Unix.localtime (timestamp_of_line iface iface.left_selection) in let day_s = Printf.sprintf "%s, %s %.2d" (full_string_of_tm_wday sel_tm.Unix.tm_wday) (full_string_of_tm_mon sel_tm.Unix.tm_mon) sel_tm.Unix.tm_mday in let day_time_s = match iface.selected_side with |Left -> day_s ^ " at " ^ if !Rcfile.selection_12_hour then twelve_hour_string sel_tm else twentyfour_hour_string sel_tm |Right -> day_s in for i = 0 to pred iface.scr.mw_lines do assert (wmove iface.scr.msg_win i 0); wclrtoeol iface.scr.msg_win done; Rcfile.color_on iface.scr.msg_win Rcfile.Selection_info; wattron iface.scr.msg_win (A.bold lor A.underline); trunc_mvwaddstr iface.scr.msg_win 0 0 iface.scr.mw_cols day_time_s; Rcfile.color_off iface.scr.msg_win Rcfile.Selection_info; wattroff iface.scr.msg_win (A.bold lor A.underline); let curr_tm = Unix.localtime (Unix.time ()) in Rcfile.color_on iface.scr.msg_win Rcfile.Status; wattron iface.scr.msg_win A.bold; let curr_tm_str = if !Rcfile.status_12_hour then twelve_hour_string curr_tm else twentyfour_hour_string curr_tm in let s = Printf.sprintf "Wyrd v%s Currently: %s, %s %.2d at %s" Version.version (full_string_of_tm_wday curr_tm.Unix.tm_wday) (full_string_of_tm_mon curr_tm.Unix.tm_mon) curr_tm.Unix.tm_mday curr_tm_str in trunc_mvwaddstr iface.scr.msg_win (pred iface.scr.mw_lines) 0 iface.scr.mw_cols s; Rcfile.color_off iface.scr.msg_win Rcfile.Status; wattroff iface.scr.msg_win A.bold; let pad = String.make 16 ' ' in let rec render_desc times descriptions output = let rec render_line lines temp_output = match lines with |[] -> temp_output |line :: lines_tail -> render_line lines_tail ((pad ^ line) :: temp_output) in match descriptions with |[] -> List.rev output |desc :: desc_tail -> let time_str = Str.string_before ((List.hd times) ^ pad) 16 in let first_line = time_str ^ (List.hd desc) in render_desc (List.tl times) desc_tail ((render_line (List.tl desc) []) @ first_line :: output) in let (times, descriptions) = match iface.selected_side with |Left -> begin match iface.timed_lineinfo.(iface.left_selection) with |[] -> ([""], [["(no reminder selected)"]]) |rem_list -> let sorted_rem_list = List.fast_sort sort_lineinfo rem_list in let get_times tline = tline.tl_timestr in let get_lines tline = word_wrap tline.tl_msg (iface.scr.mw_cols - 24) in (List.rev_map get_times sorted_rem_list, List.rev_map get_lines sorted_rem_list) end |Right -> begin match iface.untimed_lineinfo.(iface.right_selection) with |None -> ([""], [["(no reminder selected)"]]) |Some uline -> ([""], [word_wrap uline.ul_msg (iface.scr.mw_cols - 24)]) end in let desc_lines = render_desc times descriptions [] in Rcfile.color_on iface.scr.msg_win Rcfile.Description; let rec draw_desc_lines lines start line_num = match lines with |[] -> () |line :: tail -> if start > 0 then draw_desc_lines tail (pred start) line_num else if line_num < pred iface.scr.mw_lines then begin assert (mvwaddstr iface.scr.msg_win line_num 5 line); draw_desc_lines tail start (succ line_num) end else () in let adjusted_top = let max_top = max ((List.length desc_lines) - iface.scr.mw_lines + 2) 0 in min iface.top_desc max_top in draw_desc_lines desc_lines adjusted_top 1; if adjusted_top > 0 then begin assert (mvwaddch iface.scr.msg_win 1 (iface.scr.mw_cols - 1) (int_of_char '^')); assert (mvwaddch iface.scr.msg_win 2 (iface.scr.mw_cols - 1) (int_of_char '^')) end else (); if adjusted_top < List.length desc_lines - iface.scr.mw_lines + 2 then begin assert (mvwaddch iface.scr.msg_win (iface.scr.mw_lines - 2) (iface.scr.mw_cols - 1) (int_of_char 'v')); assert (mvwaddch iface.scr.msg_win (iface.scr.mw_lines - 3) (iface.scr.mw_cols - 1) (int_of_char 'v')) end else (); Rcfile.color_off iface.scr.msg_win Rcfile.Description; assert (wnoutrefresh iface.scr.msg_win); {iface with top_desc = adjusted_top} let draw_error iface err draw_cursor = werase iface.scr.err_win; trunc_mvwaddstr iface.scr.err_win 0 0 iface.scr.ew_cols err; let len = utf8_len err in if draw_cursor && len <= pred iface.scr.ew_cols then begin wattron iface.scr.err_win A.blink; assert (mvwaddch iface.scr.err_win 0 len (int_of_char '_')); wattroff iface.scr.err_win A.blink end else (); assert (wnoutrefresh iface.scr.err_win) let draw_selection_dialog (iface : interface_state_t) (title : string) (elements : string list) (selection : int) (top : int) = erase (); Rcfile.color_on iface.scr.stdscr Rcfile.Help; attron A.bold; trunc_mvwaddstr iface.scr.stdscr 0 0 iface.scr.cols title; Rcfile.color_off iface.scr.stdscr Rcfile.Help; attroff A.bold; Rcfile.color_on iface.scr.stdscr Rcfile.Untimed_reminder; let rec draw_element el_list line count = match el_list with | [] -> () | el :: tail -> if count >= top && line < iface.scr.lines then begin if count = selection then begin attron A.reverse; trunc_mvwaddstr iface.scr.stdscr line 2 (iface.scr.cols - 4) el; attroff A.reverse; end else trunc_mvwaddstr iface.scr.stdscr line 2 (iface.scr.cols - 4) el; draw_element tail (succ line) (succ count) end else draw_element tail line (succ count) in draw_element elements 1 0; if top > 0 then begin assert (mvaddch 1 (iface.scr.cols - 2) (int_of_char '^')); assert (mvaddch 2 (iface.scr.cols - 2) (int_of_char '^')) end else (); if List.length elements > pred iface.scr.lines + top then begin assert (mvaddch (pred iface.scr.lines) (iface.scr.cols - 2) (int_of_char 'v')); assert (mvaddch (iface.scr.lines - 2) (iface.scr.cols - 2) (int_of_char 'v')) end else (); Rcfile.color_off iface.scr.stdscr Rcfile.Untimed_reminder; assert (refresh ()) arch - tag : - 410f-8fcf-6dfcf94b346a
de937b8c5aa3dc25041a9519da20b6dd42780ff13eed68d68b3379faed2121df
facebook/duckling
Corpus.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. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.KN.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale KN Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "ಸೊನ್ನೆ" , "೦" ] , examples (NumeralValue 1) [ "ಒಂದು" , "೧" ] , examples (NumeralValue 2) [ "ಎರಡು" , "೨" ] , examples (NumeralValue 3) [ "ಮೂರು" , "೩" ] , examples (NumeralValue 4) [ "ನಾಲ್ಕು" , "೪" ] , examples (NumeralValue 5) [ "ಐದು" , "೫" ] , examples (NumeralValue 6) [ "ಆರು" , "೬" ] , examples (NumeralValue 7) [ "ಏಳು" , "೭" ] , examples (NumeralValue 8) [ "ಎಂಟು" , "೮" ] , examples (NumeralValue 9) [ "ಒಂಬತ್ತು" , "೯" ] ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Numeral/KN/Corpus.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. # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Numeral.KN.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale KN Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "ಸೊನ್ನೆ" , "೦" ] , examples (NumeralValue 1) [ "ಒಂದು" , "೧" ] , examples (NumeralValue 2) [ "ಎರಡು" , "೨" ] , examples (NumeralValue 3) [ "ಮೂರು" , "೩" ] , examples (NumeralValue 4) [ "ನಾಲ್ಕು" , "೪" ] , examples (NumeralValue 5) [ "ಐದು" , "೫" ] , examples (NumeralValue 6) [ "ಆರು" , "೬" ] , examples (NumeralValue 7) [ "ಏಳು" , "೭" ] , examples (NumeralValue 8) [ "ಎಂಟು" , "೮" ] , examples (NumeralValue 9) [ "ಒಂಬತ್ತು" , "೯" ] ]
11a22774ce9552fc0a4ba6535ace113ee5e1a98fe13fb8946ec1bdcc05aa7b28
brownplt/Resugarer
racket-stepper.rkt
(module racket-stepper racket (provide (all-defined-out)) ;(provide test-eval profile-eval test-term expand unexpand) (require "term.rkt") (require "utility.rkt") (require "convert.rkt") (require profile) (define expand (make-parameter #f)) (define unexpand (make-parameter #f)) ; See debug-racket-3.rkt ; for a much cleaner presentation of the debugging approach. ; This code is OK to run in sequence; not so good concurrently. ; call/cc must be spelt call/cc, and not call-with-current-continuation (define resugarer-dir "../confection/Confection") (define-struct Var (name value) #:transparent) (define-struct Func (func term) #:property prop:procedure (λ (self . args) (apply (Func-func self) args))) (define-struct Cont (stk)) (define undefined (letrec [[x x]] x)) (define (undefined? x) (eq? x undefined)) (define-setting SHOW_PROC_NAMES set-show-proc-names! #t) (define-setting SHOW_CONTINUATIONS set-show-continuations! #t) (define-setting DEBUG_VARS set-debug-vars! #f) (define-setting HIDE_EXTERNAL_CALLS set-hide-external-calls! #t) (define-setting DEBUG_STEPS set-debug-steps! #f) (define-setting DEBUG_TAGS set-debug-tags! #f) (define-setting HIDE_UNDEFINED set-hide-undefined! #t) (define-setting SILENCE set-silence! #f) (define-setting UNEXPAND_VARS set-unexpand-vars! #f) ;;; Keeping track of the stack ;;; (define $emit 'gremlin) (define $val 'gremlin) (define $stk (list)) (define ($set-val! v) (set! $val v)) (define ($push! x) (set! $stk (cons x $stk))) (define ($pop!) (set! $stk (cdr $stk))) (define ($reset! [stk (list)]) (set! $stk stk)) ;;; Emitting Terms ;;; (define (term->sexpr t [keep-tags #t]) (let [[rec (lambda (t) (term->sexpr t keep-tags))]] (match t [(TermList os ts) (if (and keep-tags (not (empty? os))) (Tagged os (map rec ts)) (map rec ts))] [(TermAtom os t) (if (and keep-tags (not (empty? os))) (Tagged os (rec t)) (rec t))] [t t]))) (define (sexpr->term x) (match x [(Tagged os x) (if (list? x) (TermList os (map sexpr->term x)) (TermAtom os (sexpr->term x)))] [(list xs ...) (TermList (list) (map sexpr->term xs))] [x x])) (define (pretty-term t [keep-tags #f]) (let [[str (format "~v" (term->sexpr t keep-tags))]] (if (and (> (string-length str) 0) (char=? (string-ref str 0) #\')) (substring str 1) str))) (define (reconstruct-stack x [stk $stk]) (if (empty? stk) x (reconstruct-stack ((car stk) x) (cdr stk)))) (define (display-skip t) (when DEBUG_STEPS (display (format "SKIP: ~a\n\n" (pretty-term t DEBUG_TAGS))))) (define (display-step t) (display (format "~a\n" (pretty-term t DEBUG_TAGS))) (when DEBUG_STEPS (newline))) (define (emit x [id #f]) (if SILENCE (void) (if id (let* [[name (Var-name x)] [term (value->term (Var-value x))] [u ((unexpand) (term->sexpr term))]] (if (CouldNotUnexpand? u) (emit x) (void))) (let* [[t (value->term (reconstruct-stack x))] [u ((unexpand) (term->sexpr t))]] (if (CouldNotUnexpand? u) (display-skip t) (display-step u)))))) ; TODO: It seems we would want to unexpand variables here, ; but doing so breaks everything. Why? (define (value->term x) (define (rec x) (value->term x)) (cond [(Func? x) (rec (Func-term x))] [(TermList? x) (TermList (TermList-tags x) (map rec (TermList-terms x)))] [(Var? x) (if UNEXPAND_VARS (let* [[name (Var-name x)] [term (rec (Var-value x))] [u ((unexpand) (term->sexpr term))]] (if DEBUG_VARS (TermList (list) (list name ':= term)) (if (or (and HIDE_UNDEFINED (undefined? u)) (CouldNotUnexpand? u)) name u))) (Var-name x))] [(Cont? x) (let [[stk (rec (reconstruct-stack '__ (Cont-stk x)))]] (TermList (list) (list '*cont* stk)))] [(and SHOW_PROC_NAMES (procedure? x)) (or (object-name x) 'cont)] [else x])) ;;; Annotating Racket Programs to Emit ;;; ; Top level (define (annotate-terms terms [emit emit]) (set! $emit emit) (with-syntax [[(ts* ...) (map annot/eval terms)]] #'(begin ($reset!) (let [[$result (let [] ts* ...)]] ($emit $result) $result)))) ; Push a frame onto the stack (and pop it after) (define (annot/frame expr_ os_ frame_) (with-syntax [[expr* expr_] [frame* (make-frame os_ frame_)]] #'(begin ($push! frame*) ($set-val! expr*) ($pop!) $val))) (define (make-frame os_ body_) (with-syntax [[(os* ...) os_] [body* body_]] #'(λ (__) (TermList (list os* ...) body*)))) (define (annot/term os_ term_) (with-syntax [[(os* ...) os_] [term* term_]] #'(TermList (list os* ...) term*))) ; Annotate function argument expressions (define (annot/args xs_ os_ fv_ xvs0_ xvs_ xts_) (if (empty? xs_) empty (with-syntax [[fv* fv_] [(xvs0* ...) xvs0_] [(xts* ...) (cdr xts_)]] (cons (annot/frame (annot/eval (car xs_)) os_ #'(list fv* xvs0* ... __ xts* ...)) (annot/args (cdr xs_) os_ fv_ (append xvs0_ (list (car xvs_))) (cdr xvs_) (cdr xts_)))))) ; Call external code (define (annot/extern-call func_ args_) (with-syntax [[func* func_] [(args* ...) args_]] (annot/frame #'(func* args* ...) (list (Alien)) #'(list __)))) ; Call a function, which may have been annotated or not. (define (annot/call func_ args_) (with-syntax [[func* func_] [(args* ...) args_] [extern-call* (annot/extern-call func_ args_)]] (if HIDE_EXTERNAL_CALLS #'(cond [(Func? func*) (func* args* ...)] [else extern-call*]) #'(func* args* ...)))) ; Prepare a term to be shown (define (adorn term_) (match term_ [(TermAtom os_ x_) (with-syntax [[(os* ...) os_] [x* x_]] #'(TermAtom (list os* ...) x*))] ; (begin x) [(TermList os_ (list 'begin x_)) (with-syntax [[x* (adorn x_)]] (annot/term os_ #'(list 'begin x*)))] ; (begin x y ys ...) [(TermList os_ (list 'begin x_ y_ ys_ ...)) (with-syntax [[x* (adorn x_)] [y* (adorn y_)] [(ys* ...) (map adorn ys_)]] (annot/term os_ #'(list 'begin x* y* ys* ...)))] ; (if x y z) [(TermList os_ (list 'if x_ y_ z_)) (with-syntax [[x* (adorn x_)] [y* (adorn y_)] [z* (adorn z_)]] (annot/term os_ #'(list 'if x* y* z*)))] ; (λ (v ...) x) [(TermList os_ (cons 'λ rest)) (adorn (TermList os_ (cons 'lambda rest)))] ; (lambda (v ...) x) [(TermList os_ (list 'lambda (TermList os2_ (list (? symbol? vs_) ...)) xs_ ...)) (with-syntax [[(vs* ...) vs_] [(xs* ...) (map adorn xs_)]] (with-syntax [[args* (annot/term os2_ #'(list vs* ...))]] (with-syntax [[lambda* (annot/term os_ #'(list 'lambda args* xs* ...))]] #'(let [[vs* 'vs*] ...] lambda*))))] ; (define v x) [(TermList os_ (list 'define (? symbol? v_) x_)) (with-syntax [[v* v_] [x* (adorn x_)]] (annot/term os_ #'(list 'define 'v* x*)))] ; (define (f v ...) x) [(TermList os_ (list 'define (TermList os2_ (list (? symbol? f_) (? symbol? vs_) ...)) x_)) (with-syntax [[f* f_] [(vs* ...) vs_] [x* (adorn x_)]] (with-syntax [[decl* (annot/term os2_ #'(list 'f* 'vs* ...))]] (annot/term os_ #'(list 'define decl* x*))))] ; (set! v x) [(TermList os_ (list 'set! (? symbol? v_) x_)) (with-syntax [[v* v_] [x* (adorn x_)]] (annot/term os_ #'(list 'set! 'v* x*)))] ; (f xs ...) [(TermList os_ (list f_ xs_ ...)) (with-syntax [[f* (adorn f_)] [(xs* ...) (map adorn xs_)]] (annot/term os_ #'(list f* xs* ...)))] ; value c [c_ (with-syntax [[c* c_]] (if (symbol? c_) (if (symbol=? c_ '^) #''^ #'(Var 'c* c*)) #'c*))])) (define (adorn/close x_ vs_) (with-syntax [[x* (adorn x_)] [(vs* ...) vs_]] #'(let [[vs* 'vs*] ...] x*))) (define (annot/eval term_) (match term_ [(TermAtom os_ x_) (with-syntax [[x* (adorn x_)]] (annot/frame (annot/eval x_) os_ #'(list x*)))] ; (begin x) [(TermList os_ (list 'begin x_)) (annot/eval x_)] ; (begin x y ys ...) [(TermList os_ (list 'begin x_ y_ ys_ ...)) (with-syntax [[(yts* ...) (map adorn (cons y_ ys_))] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'begin __ yts* ...))] [ys* (annot/eval (TermList os_ (cons 'begin (cons y_ ys_))))] [term* (annot/term os_ #'(list 'begin xv* yts* ...))]] #'(let [[xv* x*]] ($emit term*) ys*)))] ; (if x y z) [(TermList os_ (list 'if x_ y_ z_)) (with-syntax [[yt* (adorn y_)] [zt* (adorn z_)] [y* (annot/eval y_)] [z* (annot/eval z_)] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[test* (annot/frame (annot/eval x_) os_ #'(list 'if __ yt* zt*))] [term* (annot/term os_ #'(list 'if xv* yt* zt*))]] #'(let [[xv* test*]] ($emit term*) (if xv* y* z*))))] ; (lambda (v) x) [(TermList os_ (cons 'lambda rest)) (annot/eval (TermList os_ (cons 'λ rest)))] ; (λ (v ...) x) [(TermList os_ (list 'λ (TermList os2_ (list (? symbol? vs_) ...)) x_)) (with-syntax [[(fv*) (generate-temporaries #'(f))] [(vs* ...) vs_]] (with-syntax [[body* (annot/eval x_)] [term* (adorn term_)]] #'(Func (λ (vs* ...) body*) term*)))] ; (define (f v ...) x) [(TermList os_ (list 'define (TermList os2_ (list (? symbol? f_) (? symbol? vs_) ...)) x_)) (with-syntax [[f* f_] [(vs* ...) vs_] [xt* (adorn/close x_ vs_)] [x* (annot/eval (TermList os_ (list 'λ (TermList os2_ vs_) x_)))] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[decl* (annot/term os2_ #'(list 'f* 'vs* ...))]] (with-syntax [[term* (annot/term os_ #'(list 'define decl* xt*))]] #'(define f* (let [[xv* x*]] ($emit term*) xv*)))))] ; (define v x) [(TermList os_ (list 'define (? symbol? v_) x_)) (with-syntax [[(xv*) (generate-temporaries #'(x))] [v* v_]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'define 'v* __))] [term* (annot/term os_ #'(list 'define 'v* xv*))]] #'(define v* (let [[xv* x*]] ($emit term*) xv*))))] ; (set! v x) [(TermList os_ (list 'set! (? symbol? v_) x_)) (with-syntax [[v* v_] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'set! 'v* __))] [term* (annot/term os_ #'(list 'set! 'v* xv*))]] #'(let [[xv* x*]] ($emit term*) (set! v* xv*))))] ; (f xs ...) [(TermList os_ (list f_ xs_ ...)) (let [[xvs_ (map (λ (_) (with-syntax [[(v) (generate-temporaries #'(x))]] #'v)) xs_)]] (with-syntax [[(fv*) (generate-temporaries #'(f))] [(xvs* ...) xvs_] [ft* (adorn f_)] [(xts* ...) (map adorn xs_)]] (with-syntax [[f* (annot/frame (annot/eval f_) os_ #'(list __ xts* ...))] [(xs* ...) (annot/args xs_ os_ #'fv* (list) xvs_ (syntax->datum #'(xts* ...)))] [body* (annot/call #'fv* #'(xvs* ...))] [term* (annot/term os_ #'(list fv* xvs* ...))]] #'(let* [[fv* f*] [xvs* xs*] ...] ($emit term*) body*))))] ; value x [x_ (with-syntax [[x* x_]] (if (symbol? x_) #'(begin ($emit (Var 'x* x*) #t) x*) #'x*))] )) (define (call/cc f) (let [[old-stk $stk]] (call-with-current-continuation (λ (k) (let [[cont (Func (λ args ($reset! old-stk) (apply k args)) (if SHOW_CONTINUATIONS (Cont old-stk) (gensym 'cont_)))]] (f cont)))))) Communication ; ; ; (define (send-command cmd out) (when DEBUG_COMMUNICATION (display cmd)) (display cmd out) (flush-output out)) (define (read-port port [str ""]) (let [[line (read-line port)]] (if (eof-object? line) str (read-port port (string-append str line))))) (define (receive-response in err) (let [[response (read-line in)]] (when DEBUG_COMMUNICATION (display response) (newline) (newline)) (cond [(eof-object? response) (display (read-port err)) (newline) (fail "Received EOF")] [(strip-prefix "success: " response) => (λ (t) (term->sexpr (read-term t)))] [(strip-prefix "failure: " response) => (λ (_) (CouldNotUnexpand))] [(strip-prefix "error: " response) => (λ (msg) (fail msg))]))) (define-syntax-rule (with-resugaring expr ...) (begin (current-locale "en_US.UTF-8") ; How to make Racket read in unicode? (let-values [[(resugarer in out err) (subprocess #f #f #f resugarer-dir "racket.grammar")]] (parameterize [[expand (λ (t) (send-command (format "desugar Expr ~a\n" (show-term t)) out) (receive-response in err))] [unexpand (λ (t) (send-command (format "resugar Expr ~a\n" (show-term t)) out) (receive-response in err))]] (let [[result (begin expr ...)]] (subprocess-kill resugarer #t) result))))) (define-syntax-rule (without-resugaring expr ...) (parameterize [[expand (λ (t) t)] [unexpand (λ (t) t)]] expr ...)) ;;; Testing ;;; (define-syntax-rule (test-term ts ...) (syntax->datum (annotate-terms (list 'ts ...)))) (define-syntax-rule (test-expand ts ...) (syntax->datum (annotate-terms (list (sexpr->term ((expand) 'ts)) ...)))) (define-syntax-rule (test-eval ts ...) (begin (newline) (eval (annotate-terms (list (sexpr->term ((expand) 'ts)) ...)) (current-namespace)))) (define-syntax-rule (profile-eval t) (with-syntax [[prog* (annotate-term (expand (make-term t)) (λ x (void)))]] (eval #'(profile-thunk (λ () prog*)) (current-namespace)))) (define (my-external-function f) (f (f 17))) (define (string-first x) (substring x 0 1)) (define (string-rest x) (substring x 1)) )
null
https://raw.githubusercontent.com/brownplt/Resugarer/1353b4309c101f0f1ac2df2cba7f3cba1f0a3a37/racket/racket-stepper.rkt
racket
(provide test-eval profile-eval test-term expand unexpand) See debug-racket-3.rkt for a much cleaner presentation of the debugging approach. This code is OK to run in sequence; not so good concurrently. call/cc must be spelt call/cc, and not call-with-current-continuation Keeping track of the stack ;;; Emitting Terms ;;; TODO: It seems we would want to unexpand variables here, but doing so breaks everything. Why? Annotating Racket Programs to Emit ;;; Top level Push a frame onto the stack (and pop it after) Annotate function argument expressions Call external code Call a function, which may have been annotated or not. Prepare a term to be shown (begin x) (begin x y ys ...) (if x y z) (λ (v ...) x) (lambda (v ...) x) (define v x) (define (f v ...) x) (set! v x) (f xs ...) value c (begin x) (begin x y ys ...) (if x y z) (lambda (v) x) (λ (v ...) x) (define (f v ...) x) (define v x) (set! v x) (f xs ...) value x ; ; How to make Racket read in unicode? Testing ;;;
(module racket-stepper racket (provide (all-defined-out)) (require "term.rkt") (require "utility.rkt") (require "convert.rkt") (require profile) (define expand (make-parameter #f)) (define unexpand (make-parameter #f)) (define resugarer-dir "../confection/Confection") (define-struct Var (name value) #:transparent) (define-struct Func (func term) #:property prop:procedure (λ (self . args) (apply (Func-func self) args))) (define-struct Cont (stk)) (define undefined (letrec [[x x]] x)) (define (undefined? x) (eq? x undefined)) (define-setting SHOW_PROC_NAMES set-show-proc-names! #t) (define-setting SHOW_CONTINUATIONS set-show-continuations! #t) (define-setting DEBUG_VARS set-debug-vars! #f) (define-setting HIDE_EXTERNAL_CALLS set-hide-external-calls! #t) (define-setting DEBUG_STEPS set-debug-steps! #f) (define-setting DEBUG_TAGS set-debug-tags! #f) (define-setting HIDE_UNDEFINED set-hide-undefined! #t) (define-setting SILENCE set-silence! #f) (define-setting UNEXPAND_VARS set-unexpand-vars! #f) (define $emit 'gremlin) (define $val 'gremlin) (define $stk (list)) (define ($set-val! v) (set! $val v)) (define ($push! x) (set! $stk (cons x $stk))) (define ($pop!) (set! $stk (cdr $stk))) (define ($reset! [stk (list)]) (set! $stk stk)) (define (term->sexpr t [keep-tags #t]) (let [[rec (lambda (t) (term->sexpr t keep-tags))]] (match t [(TermList os ts) (if (and keep-tags (not (empty? os))) (Tagged os (map rec ts)) (map rec ts))] [(TermAtom os t) (if (and keep-tags (not (empty? os))) (Tagged os (rec t)) (rec t))] [t t]))) (define (sexpr->term x) (match x [(Tagged os x) (if (list? x) (TermList os (map sexpr->term x)) (TermAtom os (sexpr->term x)))] [(list xs ...) (TermList (list) (map sexpr->term xs))] [x x])) (define (pretty-term t [keep-tags #f]) (let [[str (format "~v" (term->sexpr t keep-tags))]] (if (and (> (string-length str) 0) (char=? (string-ref str 0) #\')) (substring str 1) str))) (define (reconstruct-stack x [stk $stk]) (if (empty? stk) x (reconstruct-stack ((car stk) x) (cdr stk)))) (define (display-skip t) (when DEBUG_STEPS (display (format "SKIP: ~a\n\n" (pretty-term t DEBUG_TAGS))))) (define (display-step t) (display (format "~a\n" (pretty-term t DEBUG_TAGS))) (when DEBUG_STEPS (newline))) (define (emit x [id #f]) (if SILENCE (void) (if id (let* [[name (Var-name x)] [term (value->term (Var-value x))] [u ((unexpand) (term->sexpr term))]] (if (CouldNotUnexpand? u) (emit x) (void))) (let* [[t (value->term (reconstruct-stack x))] [u ((unexpand) (term->sexpr t))]] (if (CouldNotUnexpand? u) (display-skip t) (display-step u)))))) (define (value->term x) (define (rec x) (value->term x)) (cond [(Func? x) (rec (Func-term x))] [(TermList? x) (TermList (TermList-tags x) (map rec (TermList-terms x)))] [(Var? x) (if UNEXPAND_VARS (let* [[name (Var-name x)] [term (rec (Var-value x))] [u ((unexpand) (term->sexpr term))]] (if DEBUG_VARS (TermList (list) (list name ':= term)) (if (or (and HIDE_UNDEFINED (undefined? u)) (CouldNotUnexpand? u)) name u))) (Var-name x))] [(Cont? x) (let [[stk (rec (reconstruct-stack '__ (Cont-stk x)))]] (TermList (list) (list '*cont* stk)))] [(and SHOW_PROC_NAMES (procedure? x)) (or (object-name x) 'cont)] [else x])) (define (annotate-terms terms [emit emit]) (set! $emit emit) (with-syntax [[(ts* ...) (map annot/eval terms)]] #'(begin ($reset!) (let [[$result (let [] ts* ...)]] ($emit $result) $result)))) (define (annot/frame expr_ os_ frame_) (with-syntax [[expr* expr_] [frame* (make-frame os_ frame_)]] #'(begin ($push! frame*) ($set-val! expr*) ($pop!) $val))) (define (make-frame os_ body_) (with-syntax [[(os* ...) os_] [body* body_]] #'(λ (__) (TermList (list os* ...) body*)))) (define (annot/term os_ term_) (with-syntax [[(os* ...) os_] [term* term_]] #'(TermList (list os* ...) term*))) (define (annot/args xs_ os_ fv_ xvs0_ xvs_ xts_) (if (empty? xs_) empty (with-syntax [[fv* fv_] [(xvs0* ...) xvs0_] [(xts* ...) (cdr xts_)]] (cons (annot/frame (annot/eval (car xs_)) os_ #'(list fv* xvs0* ... __ xts* ...)) (annot/args (cdr xs_) os_ fv_ (append xvs0_ (list (car xvs_))) (cdr xvs_) (cdr xts_)))))) (define (annot/extern-call func_ args_) (with-syntax [[func* func_] [(args* ...) args_]] (annot/frame #'(func* args* ...) (list (Alien)) #'(list __)))) (define (annot/call func_ args_) (with-syntax [[func* func_] [(args* ...) args_] [extern-call* (annot/extern-call func_ args_)]] (if HIDE_EXTERNAL_CALLS #'(cond [(Func? func*) (func* args* ...)] [else extern-call*]) #'(func* args* ...)))) (define (adorn term_) (match term_ [(TermAtom os_ x_) (with-syntax [[(os* ...) os_] [x* x_]] #'(TermAtom (list os* ...) x*))] [(TermList os_ (list 'begin x_)) (with-syntax [[x* (adorn x_)]] (annot/term os_ #'(list 'begin x*)))] [(TermList os_ (list 'begin x_ y_ ys_ ...)) (with-syntax [[x* (adorn x_)] [y* (adorn y_)] [(ys* ...) (map adorn ys_)]] (annot/term os_ #'(list 'begin x* y* ys* ...)))] [(TermList os_ (list 'if x_ y_ z_)) (with-syntax [[x* (adorn x_)] [y* (adorn y_)] [z* (adorn z_)]] (annot/term os_ #'(list 'if x* y* z*)))] [(TermList os_ (cons 'λ rest)) (adorn (TermList os_ (cons 'lambda rest)))] [(TermList os_ (list 'lambda (TermList os2_ (list (? symbol? vs_) ...)) xs_ ...)) (with-syntax [[(vs* ...) vs_] [(xs* ...) (map adorn xs_)]] (with-syntax [[args* (annot/term os2_ #'(list vs* ...))]] (with-syntax [[lambda* (annot/term os_ #'(list 'lambda args* xs* ...))]] #'(let [[vs* 'vs*] ...] lambda*))))] [(TermList os_ (list 'define (? symbol? v_) x_)) (with-syntax [[v* v_] [x* (adorn x_)]] (annot/term os_ #'(list 'define 'v* x*)))] [(TermList os_ (list 'define (TermList os2_ (list (? symbol? f_) (? symbol? vs_) ...)) x_)) (with-syntax [[f* f_] [(vs* ...) vs_] [x* (adorn x_)]] (with-syntax [[decl* (annot/term os2_ #'(list 'f* 'vs* ...))]] (annot/term os_ #'(list 'define decl* x*))))] [(TermList os_ (list 'set! (? symbol? v_) x_)) (with-syntax [[v* v_] [x* (adorn x_)]] (annot/term os_ #'(list 'set! 'v* x*)))] [(TermList os_ (list f_ xs_ ...)) (with-syntax [[f* (adorn f_)] [(xs* ...) (map adorn xs_)]] (annot/term os_ #'(list f* xs* ...)))] [c_ (with-syntax [[c* c_]] (if (symbol? c_) (if (symbol=? c_ '^) #''^ #'(Var 'c* c*)) #'c*))])) (define (adorn/close x_ vs_) (with-syntax [[x* (adorn x_)] [(vs* ...) vs_]] #'(let [[vs* 'vs*] ...] x*))) (define (annot/eval term_) (match term_ [(TermAtom os_ x_) (with-syntax [[x* (adorn x_)]] (annot/frame (annot/eval x_) os_ #'(list x*)))] [(TermList os_ (list 'begin x_)) (annot/eval x_)] [(TermList os_ (list 'begin x_ y_ ys_ ...)) (with-syntax [[(yts* ...) (map adorn (cons y_ ys_))] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'begin __ yts* ...))] [ys* (annot/eval (TermList os_ (cons 'begin (cons y_ ys_))))] [term* (annot/term os_ #'(list 'begin xv* yts* ...))]] #'(let [[xv* x*]] ($emit term*) ys*)))] [(TermList os_ (list 'if x_ y_ z_)) (with-syntax [[yt* (adorn y_)] [zt* (adorn z_)] [y* (annot/eval y_)] [z* (annot/eval z_)] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[test* (annot/frame (annot/eval x_) os_ #'(list 'if __ yt* zt*))] [term* (annot/term os_ #'(list 'if xv* yt* zt*))]] #'(let [[xv* test*]] ($emit term*) (if xv* y* z*))))] [(TermList os_ (cons 'lambda rest)) (annot/eval (TermList os_ (cons 'λ rest)))] [(TermList os_ (list 'λ (TermList os2_ (list (? symbol? vs_) ...)) x_)) (with-syntax [[(fv*) (generate-temporaries #'(f))] [(vs* ...) vs_]] (with-syntax [[body* (annot/eval x_)] [term* (adorn term_)]] #'(Func (λ (vs* ...) body*) term*)))] [(TermList os_ (list 'define (TermList os2_ (list (? symbol? f_) (? symbol? vs_) ...)) x_)) (with-syntax [[f* f_] [(vs* ...) vs_] [xt* (adorn/close x_ vs_)] [x* (annot/eval (TermList os_ (list 'λ (TermList os2_ vs_) x_)))] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[decl* (annot/term os2_ #'(list 'f* 'vs* ...))]] (with-syntax [[term* (annot/term os_ #'(list 'define decl* xt*))]] #'(define f* (let [[xv* x*]] ($emit term*) xv*)))))] [(TermList os_ (list 'define (? symbol? v_) x_)) (with-syntax [[(xv*) (generate-temporaries #'(x))] [v* v_]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'define 'v* __))] [term* (annot/term os_ #'(list 'define 'v* xv*))]] #'(define v* (let [[xv* x*]] ($emit term*) xv*))))] [(TermList os_ (list 'set! (? symbol? v_) x_)) (with-syntax [[v* v_] [(xv*) (generate-temporaries #'(x))]] (with-syntax [[x* (annot/frame (annot/eval x_) os_ #'(list 'set! 'v* __))] [term* (annot/term os_ #'(list 'set! 'v* xv*))]] #'(let [[xv* x*]] ($emit term*) (set! v* xv*))))] [(TermList os_ (list f_ xs_ ...)) (let [[xvs_ (map (λ (_) (with-syntax [[(v) (generate-temporaries #'(x))]] #'v)) xs_)]] (with-syntax [[(fv*) (generate-temporaries #'(f))] [(xvs* ...) xvs_] [ft* (adorn f_)] [(xts* ...) (map adorn xs_)]] (with-syntax [[f* (annot/frame (annot/eval f_) os_ #'(list __ xts* ...))] [(xs* ...) (annot/args xs_ os_ #'fv* (list) xvs_ (syntax->datum #'(xts* ...)))] [body* (annot/call #'fv* #'(xvs* ...))] [term* (annot/term os_ #'(list fv* xvs* ...))]] #'(let* [[fv* f*] [xvs* xs*] ...] ($emit term*) body*))))] [x_ (with-syntax [[x* x_]] (if (symbol? x_) #'(begin ($emit (Var 'x* x*) #t) x*) #'x*))] )) (define (call/cc f) (let [[old-stk $stk]] (call-with-current-continuation (λ (k) (let [[cont (Func (λ args ($reset! old-stk) (apply k args)) (if SHOW_CONTINUATIONS (Cont old-stk) (gensym 'cont_)))]] (f cont)))))) (define (send-command cmd out) (when DEBUG_COMMUNICATION (display cmd)) (display cmd out) (flush-output out)) (define (read-port port [str ""]) (let [[line (read-line port)]] (if (eof-object? line) str (read-port port (string-append str line))))) (define (receive-response in err) (let [[response (read-line in)]] (when DEBUG_COMMUNICATION (display response) (newline) (newline)) (cond [(eof-object? response) (display (read-port err)) (newline) (fail "Received EOF")] [(strip-prefix "success: " response) => (λ (t) (term->sexpr (read-term t)))] [(strip-prefix "failure: " response) => (λ (_) (CouldNotUnexpand))] [(strip-prefix "error: " response) => (λ (msg) (fail msg))]))) (define-syntax-rule (with-resugaring expr ...) (begin (let-values [[(resugarer in out err) (subprocess #f #f #f resugarer-dir "racket.grammar")]] (parameterize [[expand (λ (t) (send-command (format "desugar Expr ~a\n" (show-term t)) out) (receive-response in err))] [unexpand (λ (t) (send-command (format "resugar Expr ~a\n" (show-term t)) out) (receive-response in err))]] (let [[result (begin expr ...)]] (subprocess-kill resugarer #t) result))))) (define-syntax-rule (without-resugaring expr ...) (parameterize [[expand (λ (t) t)] [unexpand (λ (t) t)]] expr ...)) (define-syntax-rule (test-term ts ...) (syntax->datum (annotate-terms (list 'ts ...)))) (define-syntax-rule (test-expand ts ...) (syntax->datum (annotate-terms (list (sexpr->term ((expand) 'ts)) ...)))) (define-syntax-rule (test-eval ts ...) (begin (newline) (eval (annotate-terms (list (sexpr->term ((expand) 'ts)) ...)) (current-namespace)))) (define-syntax-rule (profile-eval t) (with-syntax [[prog* (annotate-term (expand (make-term t)) (λ x (void)))]] (eval #'(profile-thunk (λ () prog*)) (current-namespace)))) (define (my-external-function f) (f (f 17))) (define (string-first x) (substring x 0 1)) (define (string-rest x) (substring x 1)) )
dbd826a93cf47c0eb82df53fb4e4fadf4930233328277aaf26b3463f9be57c2e
v-kolesnikov/sicp
2_38_test.clj
(ns sicp.chapter02.2-38-test (:require [clojure.test :refer [deftest]] [sicp.chapter02.2-38 :as sicp-2-38] [sicp.common :as sicp] [sicp.test-helper :refer [assert-equal]])) (deftest test-fold-right (let [fold-right sicp/accumulate] (assert-equal 3/2 (fold-right / 1 (list 1 2 3))) (assert-equal '(1 (2 (3 nil))) (fold-right list nil (list 1 2 3))))) (deftest test-fold-left-v1 (let [fold-left sicp-2-38/fold-left-v1] (assert-equal 1/6 (fold-left / 1 (list 1 2 3))) (assert-equal '(((nil 1) 2) 3) (fold-left list nil (list 1 2 3))))) (deftest test-fold-left-v2 (let [fold-left sicp-2-38/fold-left-v2] (assert-equal 1/6 (fold-left / 1 (list 1 2 3))) (assert-equal '(((nil 1) 2) 3) (fold-left list nil (list 1 2 3)))))
null
https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/test/sicp/chapter02/2_38_test.clj
clojure
(ns sicp.chapter02.2-38-test (:require [clojure.test :refer [deftest]] [sicp.chapter02.2-38 :as sicp-2-38] [sicp.common :as sicp] [sicp.test-helper :refer [assert-equal]])) (deftest test-fold-right (let [fold-right sicp/accumulate] (assert-equal 3/2 (fold-right / 1 (list 1 2 3))) (assert-equal '(1 (2 (3 nil))) (fold-right list nil (list 1 2 3))))) (deftest test-fold-left-v1 (let [fold-left sicp-2-38/fold-left-v1] (assert-equal 1/6 (fold-left / 1 (list 1 2 3))) (assert-equal '(((nil 1) 2) 3) (fold-left list nil (list 1 2 3))))) (deftest test-fold-left-v2 (let [fold-left sicp-2-38/fold-left-v2] (assert-equal 1/6 (fold-left / 1 (list 1 2 3))) (assert-equal '(((nil 1) 2) 3) (fold-left list nil (list 1 2 3)))))
666295475a236d7a188015240572acb3078a1854ebf4f1c0da7f9b2ac5fa7a9a
astampoulis/makam
pegQuote.ml
open Camlp4 ;; open Camlp4.PreCast ;; let myparser : (UChannel.loc -> string -> Obj.t) ref = ref (fun loc s -> Obj.magic s) ;; let conv_loc _loc = let file = Loc.file_name _loc in let lineno = string_of_int (Loc.start_line _loc) in let colno = string_of_int (Loc.start_off _loc - Loc.start_bol _loc) in <:expr< let open UChannel in { description = $str:file$ ; charno = $int:colno$ ; lineno = $int:lineno$ ; offset = 0 } >> ;; let expand_myquot _loc _ s = let loc = conv_loc _loc in <:expr< Obj.magic (!PegQuote.myparser $loc$ $str:s$) >> ;; let expand_myquot_stritem _loc _ s = let loc = conv_loc _loc in <:str_item< Obj.magic (!PegQuote.myparser $loc$ $str:s$) >> ;; Syntax.Quotation.add "myparser" Syntax.Quotation.DynAst.expr_tag expand_myquot;; Syntax.Quotation.add "myparser" Syntax.Quotation.DynAst.str_item_tag expand_myquot_stritem;; Syntax.Quotation.default := "myparser" ;; let install parsefunc = myparser := (fun loc s -> Obj.magic (Peg.parse_of_string ~initloc:loc parsefunc s)) ;;
null
https://raw.githubusercontent.com/astampoulis/makam/bf7ed7592c21e0439484d7464e659eca5be3b2f9/parsing/pegQuote.ml
ocaml
open Camlp4 ;; open Camlp4.PreCast ;; let myparser : (UChannel.loc -> string -> Obj.t) ref = ref (fun loc s -> Obj.magic s) ;; let conv_loc _loc = let file = Loc.file_name _loc in let lineno = string_of_int (Loc.start_line _loc) in let colno = string_of_int (Loc.start_off _loc - Loc.start_bol _loc) in <:expr< let open UChannel in { description = $str:file$ ; charno = $int:colno$ ; lineno = $int:lineno$ ; offset = 0 } >> ;; let expand_myquot _loc _ s = let loc = conv_loc _loc in <:expr< Obj.magic (!PegQuote.myparser $loc$ $str:s$) >> ;; let expand_myquot_stritem _loc _ s = let loc = conv_loc _loc in <:str_item< Obj.magic (!PegQuote.myparser $loc$ $str:s$) >> ;; Syntax.Quotation.add "myparser" Syntax.Quotation.DynAst.expr_tag expand_myquot;; Syntax.Quotation.add "myparser" Syntax.Quotation.DynAst.str_item_tag expand_myquot_stritem;; Syntax.Quotation.default := "myparser" ;; let install parsefunc = myparser := (fun loc s -> Obj.magic (Peg.parse_of_string ~initloc:loc parsefunc s)) ;;
b80dc8f365515e97e75668375e8309a045dc82fc0ba17066b467a3f53d9ea5df
ghcjs/jsaddle-dom
BlobCallback.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.BlobCallback (newBlobCallback, newBlobCallbackSync, newBlobCallbackAsync, BlobCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallback :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallback callback = liftDOM (BlobCallback . Callback <$> function (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob')) | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallbackSync :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallbackSync callback = liftDOM (BlobCallback . Callback <$> function (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob')) | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallbackAsync :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallbackAsync callback = liftDOM (BlobCallback . Callback <$> asyncFunction (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob'))
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/BlobCallback.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.BlobCallback (newBlobCallback, newBlobCallbackSync, newBlobCallbackAsync, BlobCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallback :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallback callback = liftDOM (BlobCallback . Callback <$> function (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob')) | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallbackSync :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallbackSync callback = liftDOM (BlobCallback . Callback <$> function (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob')) | < -US/docs/Web/API/BlobCallback Mozilla BlobCallback documentation > newBlobCallbackAsync :: (MonadDOM m) => (Maybe Blob -> JSM ()) -> m BlobCallback newBlobCallbackAsync callback = liftDOM (BlobCallback . Callback <$> asyncFunction (\ _ _ [blob] -> fromJSVal blob >>= \ blob' -> callback blob'))
b4dbdde480943a346b9588431ef5dba62839d949731b31974f844f48f21454a7
PacktPublishing/Haskell-High-Performance-Programming
fundeps.hs
# LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # import qualified Data.Text as T import qualified Data.ByteString as BS import Data.Word (Word8) -- class Index container index elem where class Index container index elem | container -> elem where index :: container -> index -> elem instance Index String Int Char where index = (!!) instance Index T.Text Int Char where index = T.index instance Index BS.ByteString Int Word8 where index = BS.index
null
https://raw.githubusercontent.com/PacktPublishing/Haskell-High-Performance-Programming/2b1bfdb8102129be41e8d79c7e9caf12100c5556/Chapter04/fundeps.hs
haskell
class Index container index elem where
# LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # import qualified Data.Text as T import qualified Data.ByteString as BS import Data.Word (Word8) class Index container index elem | container -> elem where index :: container -> index -> elem instance Index String Int Char where index = (!!) instance Index T.Text Int Char where index = T.index instance Index BS.ByteString Int Word8 where index = BS.index
b3fb16aa147d5ca86a05e1650bb6315d7a2f6b19e01865f2a8e002eb1c23a682
basho/clique
clique_handler.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . %% 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. %% %% ------------------------------------------------------------------- -module(clique_handler). -callback register_cli() -> ok.
null
https://raw.githubusercontent.com/basho/clique/01a99227a4eb546a9beda763bb5aea6189285a4f/src/clique_handler.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file 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. -------------------------------------------------------------------
Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(clique_handler). -callback register_cli() -> ok.
14cec55e92dbcd3ca47978068e5f71aa13868578149101c75d5b6b5e1dd6e004
acieroid/scala-am
eta-1.scm
(letrec ((do-something (lambda () 10)) (id (lambda (y) (letrec ((tmp1 (do-something))) y))) (tmp2 ((id (lambda (a) a)) #t))) ((id (lambda (c) c)) #f))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/changesBenevolPaper/eta-1.scm
scheme
(letrec ((do-something (lambda () 10)) (id (lambda (y) (letrec ((tmp1 (do-something))) y))) (tmp2 ((id (lambda (a) a)) #t))) ((id (lambda (c) c)) #f))
b18b45432da86db7bbf6e85b669a1c5b23f2e31e518b42578a75ce74d5d2066c
ijvcms/chuanqi_dev
ui_function_config.erl
%%%------------------------------------------------------------------- @author zhengsiying %%% @doc %%% 自动生成文件,不要手动修改 %%% @end Created : 2016/10/12 %%%------------------------------------------------------------------- -module(ui_function_config). -include("common.hrl"). -include("config.hrl"). -compile([export_all]). get_list_conf() -> [ ui_function_config:get(X) || X <- get_list() ]. get_list() -> [1]. get(1) -> #ui_function_conf{ id = 1, state = 1 }; get(_Key) -> ?ERR("undefined key from ui_function_config ~p", [_Key]).
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/config/ui_function_config.erl
erlang
------------------------------------------------------------------- @doc 自动生成文件,不要手动修改 @end -------------------------------------------------------------------
@author zhengsiying Created : 2016/10/12 -module(ui_function_config). -include("common.hrl"). -include("config.hrl"). -compile([export_all]). get_list_conf() -> [ ui_function_config:get(X) || X <- get_list() ]. get_list() -> [1]. get(1) -> #ui_function_conf{ id = 1, state = 1 }; get(_Key) -> ?ERR("undefined key from ui_function_config ~p", [_Key]).
863f3c0ec6bf92855dc352169cc80ee0488ba68363c31248eefeaf0efe20bdc4
caiorss/Functional-Programming
funcrecs.hs
| Our usual CustomColor type to play with data CustomColor = CustomColor {red :: Int, green :: Int, blue :: Int} deriving (Eq, Show, Read) | A new type that stores a name and a function . The function takes an Int , applies some computation to it , and returns an Int along with a CustomColor The function takes an Int, applies some computation to it, and returns an Int along with a CustomColor -} data FuncRec = FuncRec {name :: String, colorCalc :: Int -> (CustomColor, Int)} plus5func color x = (color, x + 5) purple = CustomColor 255 0 255 plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple} always0 = FuncRec {name = "always0", colorCalc = \_ -> (purple, 0)}
null
https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/haskell/rwh/ch13/funcrecs.hs
haskell
| Our usual CustomColor type to play with data CustomColor = CustomColor {red :: Int, green :: Int, blue :: Int} deriving (Eq, Show, Read) | A new type that stores a name and a function . The function takes an Int , applies some computation to it , and returns an Int along with a CustomColor The function takes an Int, applies some computation to it, and returns an Int along with a CustomColor -} data FuncRec = FuncRec {name :: String, colorCalc :: Int -> (CustomColor, Int)} plus5func color x = (color, x + 5) purple = CustomColor 255 0 255 plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple} always0 = FuncRec {name = "always0", colorCalc = \_ -> (purple, 0)}
93ebb4b6caa5fa9c11025009ba70de95345a6cc23bdb6e3577403dd3682bd952
0xd34df00d/coformat
Language.hs
# LANGUAGE TupleSections # module Language.Coformat.Language where import qualified Data.HashMap.Strict as HM import Data.List.NonEmpty import Data.Maybe import System.FilePath.Posix data Language = Cpp deriving (Eq, Ord, Show) guessLanguage :: NonEmpty FilePath -> Either String Language guessLanguage files = case langs of [] -> Left "Could not detect any languages" [lang] -> Right lang _ -> Left "More than one language detected" where langs = mapMaybe extToFile $ toList $ takeExtension <$> files extToFile :: String -> Maybe Language extToFile ext = HM.lookup ext exts where exts = HM.fromList $ (, Cpp) <$> cpps cpps = ["cpp", "c", "h", "cxx", "hpp", "hxx"]
null
https://raw.githubusercontent.com/0xd34df00d/coformat/5ea8cf57d9df08e6b72d341e4c73f9933cad8a3d/src/Language/Coformat/Language.hs
haskell
# LANGUAGE TupleSections # module Language.Coformat.Language where import qualified Data.HashMap.Strict as HM import Data.List.NonEmpty import Data.Maybe import System.FilePath.Posix data Language = Cpp deriving (Eq, Ord, Show) guessLanguage :: NonEmpty FilePath -> Either String Language guessLanguage files = case langs of [] -> Left "Could not detect any languages" [lang] -> Right lang _ -> Left "More than one language detected" where langs = mapMaybe extToFile $ toList $ takeExtension <$> files extToFile :: String -> Maybe Language extToFile ext = HM.lookup ext exts where exts = HM.fromList $ (, Cpp) <$> cpps cpps = ["cpp", "c", "h", "cxx", "hpp", "hxx"]
624b81f23eae2deb5f72545508f752bc52ebe5e06c9c08e6a02736f55b17c611
ygmpkk/house
ResumeReader.hs
import Unstable.Control.Monad.Transformers import Unstable.Control.Monad.Identity type R = (String,String,String) t1,t2,t3 :: (MonadReader String m, MonadResume m) => m R t1 = do e1 <- ask e2 <- local ('a':) ask e3 <- ask return (e1,e2,e3) t1_1 = ("x","ax","x") t1_2 = ("x","ax","x") t2 = do e1 <- ask e2 <- delay ask e3 <- ask return (e1,e2,e3) t2_1 = ("x","x","x") t2_2 = ("x","x","x") t3 = do e1 <- ask e2 <- local ('a':) $ delay ask e3 <- ask return (e1,e2,e3) t3_1 = ("x","x","x") t3_2 = ("x","ax","x") {- t4 = do e1 <- ask e2 <- local ('a':) $ delay ask e3 <- ask return (e1,e2,e3) -} run1 m = runIdentity $ runReader "x" $ hyper $ m run2 m = runIdentity $ hyper $ runReader "x" $ m test' :: (forall m. (MonadReader String m, MonadResume m) => m R) -> R -> R -> Bool test' m r1 r2 = run1 m == r1 && run2 m == r2 tests = [ test' t1 t1_1 t1_2, test' t2 t2_1 t2_2, test' t3 t3_1 t3_2 ] main = print (and tests)
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/monads/Unstable/Control/Monad/tests/ResumeReader.hs
haskell
t4 = do e1 <- ask e2 <- local ('a':) $ delay ask e3 <- ask return (e1,e2,e3)
import Unstable.Control.Monad.Transformers import Unstable.Control.Monad.Identity type R = (String,String,String) t1,t2,t3 :: (MonadReader String m, MonadResume m) => m R t1 = do e1 <- ask e2 <- local ('a':) ask e3 <- ask return (e1,e2,e3) t1_1 = ("x","ax","x") t1_2 = ("x","ax","x") t2 = do e1 <- ask e2 <- delay ask e3 <- ask return (e1,e2,e3) t2_1 = ("x","x","x") t2_2 = ("x","x","x") t3 = do e1 <- ask e2 <- local ('a':) $ delay ask e3 <- ask return (e1,e2,e3) t3_1 = ("x","x","x") t3_2 = ("x","ax","x") run1 m = runIdentity $ runReader "x" $ hyper $ m run2 m = runIdentity $ hyper $ runReader "x" $ m test' :: (forall m. (MonadReader String m, MonadResume m) => m R) -> R -> R -> Bool test' m r1 r2 = run1 m == r1 && run2 m == r2 tests = [ test' t1 t1_1 t1_2, test' t2 t2_1 t2_2, test' t3 t3_1 t3_2 ] main = print (and tests)
bd77cbf3f83c59289e2b86ce22918cce4f3f41e4aec8c42ce4c4e967be9861bf
fulcrologic/fulcro-rad-kvstore
alter_remove_test.clj
(ns test.com.example.components.alter-remove-test (:require [clojure.test :refer :all] [com.fulcrologic.rad.database-adapters.key-value :as key-value] [com.fulcrologic.rad.database-adapters.key-value.key-store :as kv-key-store] [com.example.components.seeded-connection :refer [kv-connections]] [com.example.components.seed :refer [all-tables! all-entities!]] [mount.core :as mount] [com.fulcrologic.rad.database-adapters.key-value.write :as kv-write] [com.fulcrologic.rad.ids :refer [new-uuid]] [clojure.core.async :as async :refer [<!! <! chan go go-loop]] [konserve.core :as k] [com.fulcrologic.rad.database-adapters.strict-entity :as strict-entity] [com.fulcrologic.rad.database-adapters.key-value-options :as kvo])) (defn env-key-store [] (mount/start) (let [key-store (:main kv-connections)] [{kvo/databases {:production (atom key-store)}} key-store])) (defn my-rand-nth "Helps tests to fail rather than error" [xs] (if (empty? xs) nil (rand-nth xs))) (deftest alter-account (let [[env {::kv-key-store/keys [store table->rows] :as key-store}] (env-key-store) active-accounts-1 (->> (table->rows :account/id) (filter :account/active?)) altered-account (assoc (my-rand-nth active-accounts-1) :account/active? false) num-active-1 (count active-accounts-1)] (<!! (k/assoc-in store (strict-entity/entity->ident altered-account) altered-account)) (let [active-accounts-2 (->> (table->rows :account/id) (filter :account/active?)) num-active-2 (count active-accounts-2)] (is (= (- num-active-1 1) num-active-2)) (kv-write/import key-store (all-tables!) (all-entities!))))) (deftest remove1 (let [[env {::kv-key-store/keys [store table->rows table->ident-rows] :as key-store}] (env-key-store) accounts-1 (table->ident-rows :account/id) [table id :as candidate-ident] (my-rand-nth accounts-1) num-1 (count accounts-1)] (<!! (k/update store table dissoc id)) (let [accounts-2 (table->rows :account/id) num-2 (count accounts-2)] (is (= (dec num-1) num-2)) (kv-write/import key-store (all-tables!) (all-entities!))))) (deftest remove-all (let [[env {::kv-key-store/keys [store table->rows] :as key-store}] (env-key-store) accounts-1 (table->rows :account/id) candidate-account (my-rand-nth accounts-1)] (kv-write/remove-table-rows key-store env :account/id) (let [accounts-2 (table->rows :account/id) num-1 (count accounts-1) num-2 (count accounts-2)] (is (nil? (<!! (k/get-in store (strict-entity/entity->ident candidate-account))))) (is (zero? num-2)) (is ((complement zero?) num-1)) (kv-write/import key-store (all-tables!) (all-entities!)))))
null
https://raw.githubusercontent.com/fulcrologic/fulcro-rad-kvstore/686331880682777a4d1739eb399e20f33ed725fe/src/test/test/com/example/components/alter_remove_test.clj
clojure
(ns test.com.example.components.alter-remove-test (:require [clojure.test :refer :all] [com.fulcrologic.rad.database-adapters.key-value :as key-value] [com.fulcrologic.rad.database-adapters.key-value.key-store :as kv-key-store] [com.example.components.seeded-connection :refer [kv-connections]] [com.example.components.seed :refer [all-tables! all-entities!]] [mount.core :as mount] [com.fulcrologic.rad.database-adapters.key-value.write :as kv-write] [com.fulcrologic.rad.ids :refer [new-uuid]] [clojure.core.async :as async :refer [<!! <! chan go go-loop]] [konserve.core :as k] [com.fulcrologic.rad.database-adapters.strict-entity :as strict-entity] [com.fulcrologic.rad.database-adapters.key-value-options :as kvo])) (defn env-key-store [] (mount/start) (let [key-store (:main kv-connections)] [{kvo/databases {:production (atom key-store)}} key-store])) (defn my-rand-nth "Helps tests to fail rather than error" [xs] (if (empty? xs) nil (rand-nth xs))) (deftest alter-account (let [[env {::kv-key-store/keys [store table->rows] :as key-store}] (env-key-store) active-accounts-1 (->> (table->rows :account/id) (filter :account/active?)) altered-account (assoc (my-rand-nth active-accounts-1) :account/active? false) num-active-1 (count active-accounts-1)] (<!! (k/assoc-in store (strict-entity/entity->ident altered-account) altered-account)) (let [active-accounts-2 (->> (table->rows :account/id) (filter :account/active?)) num-active-2 (count active-accounts-2)] (is (= (- num-active-1 1) num-active-2)) (kv-write/import key-store (all-tables!) (all-entities!))))) (deftest remove1 (let [[env {::kv-key-store/keys [store table->rows table->ident-rows] :as key-store}] (env-key-store) accounts-1 (table->ident-rows :account/id) [table id :as candidate-ident] (my-rand-nth accounts-1) num-1 (count accounts-1)] (<!! (k/update store table dissoc id)) (let [accounts-2 (table->rows :account/id) num-2 (count accounts-2)] (is (= (dec num-1) num-2)) (kv-write/import key-store (all-tables!) (all-entities!))))) (deftest remove-all (let [[env {::kv-key-store/keys [store table->rows] :as key-store}] (env-key-store) accounts-1 (table->rows :account/id) candidate-account (my-rand-nth accounts-1)] (kv-write/remove-table-rows key-store env :account/id) (let [accounts-2 (table->rows :account/id) num-1 (count accounts-1) num-2 (count accounts-2)] (is (nil? (<!! (k/get-in store (strict-entity/entity->ident candidate-account))))) (is (zero? num-2)) (is ((complement zero?) num-1)) (kv-write/import key-store (all-tables!) (all-entities!)))))
028ca0fce58322a83df589494c9e42854da69a12aaddfaec21f33b0a90b60eab
serokell/ariadne
Update.hs
-- | UPDATE operations on the wallet-spec state module Ariadne.Wallet.Cardano.Kernel.DB.Spec.Update ( -- * Errors NewPendingFailed(..) -- * Updates , newPending , cancelPending , applyBlock , switchToFork -- * Testing , observableRollbackUseInTestsOnly ) where import Data.SafeCopy (base, deriveSafeCopySimple) import Test.QuickCheck (Arbitrary(..)) import qualified Data.Text.Buildable import Formatting (bprint, (%)) import Serokell.Util (listJsonIndent) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map import qualified Data.Set as Set import Control.Lens (each) import qualified Pos.Core as Core import Pos.Core.Chrono (OldestFirst(..)) import qualified Pos.Core.Txp as Txp import Pos.Crypto (hash) import Pos.Txp (Utxo) import Ariadne.Wallet.Cardano.Kernel.PrefilterTx (PrefilteredBlock(..), pfbInputs, pfbOutputs) import Ariadne.Wallet.Cardano.Kernel.DB.BlockMeta import Ariadne.Wallet.Cardano.Kernel.DB.InDb import Ariadne.Wallet.Cardano.Kernel.DB.Spec import Ariadne.Wallet.Cardano.Kernel.DB.Spec.Util import Ariadne.Wallet.Cardano.Kernel.DB.Util.AcidState {------------------------------------------------------------------------------- Errors -------------------------------------------------------------------------------} -- | Errors thrown by 'newPending' data NewPendingFailed = -- | Some inputs are not in the wallet utxo NewPendingInputsUnavailable (Set (InDb Txp.TxIn)) deriving Show deriveSafeCopySimple 1 'base ''NewPendingFailed instance Buildable NewPendingFailed where build (NewPendingInputsUnavailable inputs) = let curatedInputs = map (view fromDb) (Set.toList inputs) in bprint ("NewPendingInputsUnavailable { inputs = " % listJsonIndent 4 % " }") curatedInputs -- NOTE(adn) Short-circuiting the rabbit-hole with this instance by generating -- an empty set, thus avoiding the extra dependency on @cardano-sl-core-test@. instance Arbitrary NewPendingFailed where arbitrary = pure . NewPendingInputsUnavailable $ mempty {------------------------------------------------------------------------------- Wallet spec mandated updates -------------------------------------------------------------------------------} class UpdatableWalletState state where -- | Insert new pending transaction into the specified wallet -- -- NOTE: Transactions to be inserted must be fully constructed and signed; we do -- not offer input selection at this layer. Instead, callers must get a snapshot -- of the database, construct a transaction asynchronously, and then finally -- submit the transaction. It is of course possible that the state of the -- database has changed at this point, possibly making the generated transaction -- invalid; 'newPending' therefore returns whether or not the transaction could -- be inserted. If this fails, the process must be started again. This is -- important for a number of reasons: -- -- * Input selection may be an expensive computation, and we don't want to -- lock the database while input selection is ongoing. -- * Transactions may be signed off-site (on a different machine or on a -- a specialized hardware device). -- * We do not actually have access to the key storage inside the DB layer -- (and do not store private keys) so we cannot actually sign transactions. newPending :: InDb Txp.TxAux -> Update' state NewPendingFailed () -- | Cancel the input set of cancelled transactions from @all@ the 'Checkpoints' -- of an 'Account'. cancelPending :: Set Txp.TxId -> state -> state -- | Apply the prefiltered block to the specified wallet applyBlock :: PrefilteredBlock -> state -> state -- | Rollback -- -- For the base case, see section "Rollback -- Omitting checkpoints" in the -- formal specification. -- -- This is an internal function only, and not exported. See 'switchToFork'. rollback :: state -> state -- | Observable rollback, used in testing only -- -- See 'switchToFork' for production use. observableRollbackUseInTestsOnly :: state -> state observableRollbackUseInTestsOnly = rollback -- | Switch to a fork switchToFork :: Int -- ^ Number of blocks to rollback -> OldestFirst [] PrefilteredBlock -- ^ Blocks to apply -> state -> state switchToFork = \n bs -> applyBlocks (getOldestFirst bs) . rollbacks n where applyBlocks :: [PrefilteredBlock] -> state -> state applyBlocks [] = identity applyBlocks (b:bs) = applyBlocks bs . applyBlock b rollbacks :: Int -> state -> state rollbacks 0 = identity rollbacks n = rollbacks (n - 1) . rollback updateBlockMeta :: PrefilteredBlock -> BlockMeta -> BlockMeta updateBlockMeta PrefilteredBlock{..} meta = meta `mappend` pfbMeta | Update ( utxo , balance ) with the given prefiltered block updateUtxo :: PrefilteredBlock -> (Utxo, Core.Coin) -> (Utxo, Core.Coin) updateUtxo pfb (currentUtxo', currentBalance') = (utxo', balance') where inputs = pfbInputs pfb outputs = pfbOutputs pfb unionUtxo = Map.union outputs currentUtxo' utxo' = utxoRemoveInputs unionUtxo inputs unionUtxoRestricted = utxoRestrictToInputs unionUtxo inputs balanceDelta = balanceI outputs - balanceI unionUtxoRestricted currentBalanceI = Core.coinToInteger currentBalance' balance' = Core.unsafeIntegerToCoin $ currentBalanceI + balanceDelta -- | Update the pending transactions with the given prefiltered block updatePending :: PrefilteredBlock -> PendingTxs -> PendingTxs updatePending pfb = Map.filter (\t -> disjoint (txAuxInputSet t) (pfbInputs pfb)) instance UpdatableWalletState AccCheckpoints where newPending tx = do checkpoints <- get let available' = available (checkpoints ^. currentAccUtxo) (checkpoints ^. currentAccPendingTxs) if isValidPendingTx tx' available' then put (insertPending checkpoints) else inputUnavailableErr available' where tx' = tx ^. fromDb insertPending :: AccCheckpoints -> AccCheckpoints insertPending cs = cs & currentAccPendingTxs %~ Map.insert txId tx' where txId = hash $ Txp.taTx tx' inputUnavailableErr available_ = do let unavailableInputs = txAuxInputSet tx' `Set.difference` utxoInputs available_ throwError $ NewPendingInputsUnavailable (Set.map InDb unavailableInputs) cancelPending txids checkpoints = checkpoints & over each (\ckpoint -> ckpoint & over accCheckpointPending (removePending txids) ) applyBlock prefBlock checkpoints = AccCheckpoint { _accCheckpointUtxo = InDb utxo'' , _accCheckpointUtxoBalance = InDb balance'' , _accCheckpointPending = Pending . InDb $ pending'' , _accCheckpointBlockMeta = blockMeta'' } NE.<| checkpoints where utxo' = checkpoints ^. currentAccUtxo utxoBalance' = checkpoints ^. currentAccUtxoBalance (utxo'', balance'') = updateUtxo prefBlock (utxo', utxoBalance') pending'' = updatePending prefBlock (checkpoints ^. currentAccPendingTxs) blockMeta'' = updateBlockMeta prefBlock (checkpoints ^. currentAccBlockMeta) rollback (c :| []) = c :| [] rollback (c :| c' : cs) = AccCheckpoint { _accCheckpointUtxo = c' ^. accCheckpointUtxo , _accCheckpointUtxoBalance = c' ^. accCheckpointUtxoBalance , _accCheckpointBlockMeta = c' ^. accCheckpointBlockMeta , _accCheckpointPending = unionPending (c ^. accCheckpointPending) (c' ^. accCheckpointPending) } :| cs instance UpdatableWalletState AddrCheckpoints where newPending _tx = pass cancelPending _txids checkpoints = checkpoints applyBlock prefBlock checkpoints = AddrCheckpoint { _addrCheckpointUtxo = InDb utxo'' , _addrCheckpointUtxoBalance = InDb balance'' } NE.<| checkpoints where utxo' = checkpoints ^. currentAddrUtxo utxoBalance' = checkpoints ^. currentAddrUtxoBalance (utxo'', balance'') = updateUtxo prefBlock (utxo', utxoBalance') rollback (c :| []) = c :| [] rollback (_ :| c' : cs) = AddrCheckpoint { _addrCheckpointUtxo = c' ^. addrCheckpointUtxo , _addrCheckpointUtxoBalance = c' ^. addrCheckpointUtxoBalance } :| cs
null
https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Wallet/Cardano/Kernel/DB/Spec/Update.hs
haskell
| UPDATE operations on the wallet-spec state * Errors * Updates * Testing ------------------------------------------------------------------------------ Errors ------------------------------------------------------------------------------ | Errors thrown by 'newPending' | Some inputs are not in the wallet utxo NOTE(adn) Short-circuiting the rabbit-hole with this instance by generating an empty set, thus avoiding the extra dependency on @cardano-sl-core-test@. ------------------------------------------------------------------------------ Wallet spec mandated updates ------------------------------------------------------------------------------ | Insert new pending transaction into the specified wallet NOTE: Transactions to be inserted must be fully constructed and signed; we do not offer input selection at this layer. Instead, callers must get a snapshot of the database, construct a transaction asynchronously, and then finally submit the transaction. It is of course possible that the state of the database has changed at this point, possibly making the generated transaction invalid; 'newPending' therefore returns whether or not the transaction could be inserted. If this fails, the process must be started again. This is important for a number of reasons: * Input selection may be an expensive computation, and we don't want to lock the database while input selection is ongoing. * Transactions may be signed off-site (on a different machine or on a a specialized hardware device). * We do not actually have access to the key storage inside the DB layer (and do not store private keys) so we cannot actually sign transactions. | Cancel the input set of cancelled transactions from @all@ the 'Checkpoints' of an 'Account'. | Apply the prefiltered block to the specified wallet | Rollback For the base case, see section "Rollback -- Omitting checkpoints" in the formal specification. This is an internal function only, and not exported. See 'switchToFork'. | Observable rollback, used in testing only See 'switchToFork' for production use. | Switch to a fork ^ Number of blocks to rollback ^ Blocks to apply | Update the pending transactions with the given prefiltered block
module Ariadne.Wallet.Cardano.Kernel.DB.Spec.Update NewPendingFailed(..) , newPending , cancelPending , applyBlock , switchToFork , observableRollbackUseInTestsOnly ) where import Data.SafeCopy (base, deriveSafeCopySimple) import Test.QuickCheck (Arbitrary(..)) import qualified Data.Text.Buildable import Formatting (bprint, (%)) import Serokell.Util (listJsonIndent) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map import qualified Data.Set as Set import Control.Lens (each) import qualified Pos.Core as Core import Pos.Core.Chrono (OldestFirst(..)) import qualified Pos.Core.Txp as Txp import Pos.Crypto (hash) import Pos.Txp (Utxo) import Ariadne.Wallet.Cardano.Kernel.PrefilterTx (PrefilteredBlock(..), pfbInputs, pfbOutputs) import Ariadne.Wallet.Cardano.Kernel.DB.BlockMeta import Ariadne.Wallet.Cardano.Kernel.DB.InDb import Ariadne.Wallet.Cardano.Kernel.DB.Spec import Ariadne.Wallet.Cardano.Kernel.DB.Spec.Util import Ariadne.Wallet.Cardano.Kernel.DB.Util.AcidState data NewPendingFailed = NewPendingInputsUnavailable (Set (InDb Txp.TxIn)) deriving Show deriveSafeCopySimple 1 'base ''NewPendingFailed instance Buildable NewPendingFailed where build (NewPendingInputsUnavailable inputs) = let curatedInputs = map (view fromDb) (Set.toList inputs) in bprint ("NewPendingInputsUnavailable { inputs = " % listJsonIndent 4 % " }") curatedInputs instance Arbitrary NewPendingFailed where arbitrary = pure . NewPendingInputsUnavailable $ mempty class UpdatableWalletState state where newPending :: InDb Txp.TxAux -> Update' state NewPendingFailed () cancelPending :: Set Txp.TxId -> state -> state applyBlock :: PrefilteredBlock -> state -> state rollback :: state -> state observableRollbackUseInTestsOnly :: state -> state observableRollbackUseInTestsOnly = rollback switchToFork -> state -> state switchToFork = \n bs -> applyBlocks (getOldestFirst bs) . rollbacks n where applyBlocks :: [PrefilteredBlock] -> state -> state applyBlocks [] = identity applyBlocks (b:bs) = applyBlocks bs . applyBlock b rollbacks :: Int -> state -> state rollbacks 0 = identity rollbacks n = rollbacks (n - 1) . rollback updateBlockMeta :: PrefilteredBlock -> BlockMeta -> BlockMeta updateBlockMeta PrefilteredBlock{..} meta = meta `mappend` pfbMeta | Update ( utxo , balance ) with the given prefiltered block updateUtxo :: PrefilteredBlock -> (Utxo, Core.Coin) -> (Utxo, Core.Coin) updateUtxo pfb (currentUtxo', currentBalance') = (utxo', balance') where inputs = pfbInputs pfb outputs = pfbOutputs pfb unionUtxo = Map.union outputs currentUtxo' utxo' = utxoRemoveInputs unionUtxo inputs unionUtxoRestricted = utxoRestrictToInputs unionUtxo inputs balanceDelta = balanceI outputs - balanceI unionUtxoRestricted currentBalanceI = Core.coinToInteger currentBalance' balance' = Core.unsafeIntegerToCoin $ currentBalanceI + balanceDelta updatePending :: PrefilteredBlock -> PendingTxs -> PendingTxs updatePending pfb = Map.filter (\t -> disjoint (txAuxInputSet t) (pfbInputs pfb)) instance UpdatableWalletState AccCheckpoints where newPending tx = do checkpoints <- get let available' = available (checkpoints ^. currentAccUtxo) (checkpoints ^. currentAccPendingTxs) if isValidPendingTx tx' available' then put (insertPending checkpoints) else inputUnavailableErr available' where tx' = tx ^. fromDb insertPending :: AccCheckpoints -> AccCheckpoints insertPending cs = cs & currentAccPendingTxs %~ Map.insert txId tx' where txId = hash $ Txp.taTx tx' inputUnavailableErr available_ = do let unavailableInputs = txAuxInputSet tx' `Set.difference` utxoInputs available_ throwError $ NewPendingInputsUnavailable (Set.map InDb unavailableInputs) cancelPending txids checkpoints = checkpoints & over each (\ckpoint -> ckpoint & over accCheckpointPending (removePending txids) ) applyBlock prefBlock checkpoints = AccCheckpoint { _accCheckpointUtxo = InDb utxo'' , _accCheckpointUtxoBalance = InDb balance'' , _accCheckpointPending = Pending . InDb $ pending'' , _accCheckpointBlockMeta = blockMeta'' } NE.<| checkpoints where utxo' = checkpoints ^. currentAccUtxo utxoBalance' = checkpoints ^. currentAccUtxoBalance (utxo'', balance'') = updateUtxo prefBlock (utxo', utxoBalance') pending'' = updatePending prefBlock (checkpoints ^. currentAccPendingTxs) blockMeta'' = updateBlockMeta prefBlock (checkpoints ^. currentAccBlockMeta) rollback (c :| []) = c :| [] rollback (c :| c' : cs) = AccCheckpoint { _accCheckpointUtxo = c' ^. accCheckpointUtxo , _accCheckpointUtxoBalance = c' ^. accCheckpointUtxoBalance , _accCheckpointBlockMeta = c' ^. accCheckpointBlockMeta , _accCheckpointPending = unionPending (c ^. accCheckpointPending) (c' ^. accCheckpointPending) } :| cs instance UpdatableWalletState AddrCheckpoints where newPending _tx = pass cancelPending _txids checkpoints = checkpoints applyBlock prefBlock checkpoints = AddrCheckpoint { _addrCheckpointUtxo = InDb utxo'' , _addrCheckpointUtxoBalance = InDb balance'' } NE.<| checkpoints where utxo' = checkpoints ^. currentAddrUtxo utxoBalance' = checkpoints ^. currentAddrUtxoBalance (utxo'', balance'') = updateUtxo prefBlock (utxo', utxoBalance') rollback (c :| []) = c :| [] rollback (_ :| c' : cs) = AddrCheckpoint { _addrCheckpointUtxo = c' ^. addrCheckpointUtxo , _addrCheckpointUtxoBalance = c' ^. addrCheckpointUtxoBalance } :| cs
e17a3ce7828be73433e2b15dc5d64e6af994ca42e0fe33d2100d9b1dee23be76
manuel-serrano/bigloo
rgc_insert.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / recette / rgc - insert.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Thu Sep 3 12:29:48 2009 * / * Last change : Thu Sep 3 14:10:30 2009 ( serrano ) * / * Copyright : 2009 * / ;* ------------------------------------------------------------- */ ;* Some rgc-buffer-insert-string tests */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module rgc-insert (import (main "main.scm")) (include "test.sch") (export (test-rgc-insert))) (define *number* (regular-grammar () ((: (submatch (+ digit)) "." (submatch (+ digit))) (cons (string->integer (the-submatch 1)) (string->integer (the-submatch 2)))))) (define *number2* (regular-grammar () ((: (submatch (* digit)) "." (submatch (* digit))) (cons (string->integer (the-submatch 1)) (string->integer (the-submatch 2)))))) (define (test-rgc-insert) (test-module "rgc-insert" "rgc-insert.scm") (test "unread-string-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-string! "ab" p)) (str1 (read-chars 3 p)) ;; ab1 (dummy2 (unread-string! "cdefghijklmnop" p)) cdef (str3 (read-chars 10 p)) ;; g-p 23456 (dummy3 (unread-string! "qr" p)) qr789 (c-ready? (char-ready? p)) (dummy4 (unread-string! "st" p)) (str6 (read-chars 1 p)) ;; s (c-ready?2 (char-ready? p)) (str7 (read-chars 1 p)) ;; t (c-ready?3 (char-ready? p)) (str8 (read p))) (and (equal? str1 "ab1") (equal? str2 "cdef") (equal? str3 "ghijklmnop") (equal? str4 "23456") (equal? str5 "qr789") (not c-ready?) (equal? str6 "s") c-ready?2 (equal? str7 "t") (not c-ready?3) (eof-object? str8))) #t) (test "unread-string-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-string! " " p)) (c0 (read-char p)) ;; space (dummy0b (unread-string! "" p)) (sym (read p)) ;; a ( ( tprint ( read - char p ) ) ) (dummy1 (unread-string! "b" p)) (sym2 (read p)) ;; b (dummy2 (begin (read-char p) ;; the space (unread-string! "2" p))) 21 (char (read p)) (dummy3 (unread-string! "\"\"" p)) (str1 (read p)) (dummy4 (begin (read-char p) ;; the space (unread-string! "#\\" p))) (char2 (read p)) ;; #\" (dummy5 (unread-string! "\"" p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-string-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-char! #\space p)) (c0 (read-char p)) ;; space (sym (read p)) ;; a (dummy1 (unread-char! #\b p)) (sym2 (read p)) ;; b (dummy2 (begin (read-char p) ;; the space (unread-char! #\2 p))) 21 (char (read p)) (dummy3 (begin (unread-char! #\" p) (unread-char! #\" p))) (str1 (read p)) (dummy4 (begin (read-char p) ;; the space (unread-char! #\\ p) (unread-char! #\# p))) (char2 (read p)) ;; #\" (dummy5 (unread-char! #\" p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-char-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-char! #\a p)) (str1 (read-chars 2 p)) ;; a1 (dummy2 (unread-char! #\c p)) (str2 (read-chars 1 p))) ;; c (and (equal? str1 "a1") (equal? str2 "c"))) #t) (test "unread-substring-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-substring! "0ab1" 1 3 p)) (str1 (read-chars 3 p)) ;; ab1 (dummy2 (unread-substring! "1234cdefghijklmnop11" 4 18 p)) cdef (str3 (read-chars 10 p)) ;; g-p 23456 (dummy3 (unread-substring! "qr1" 0 2 p)) qr789 (c-ready? (char-ready? p)) (dummy4 (unread-substring! "0st" 1 3 p)) (str6 (read-chars 1 p)) ;; s (c-ready?2 (char-ready? p)) (str7 (read-chars 1 p)) ;; t (c-ready?3 (char-ready? p)) (str8 (read p))) (and (equal? str1 "ab1") (equal? str2 "cdef") (equal? str3 "ghijklmnop") (equal? str4 "23456") (equal? str5 "qr789") (not c-ready?) (equal? str6 "s") c-ready?2 (equal? str7 "t") (not c-ready?3) (eof-object? str8))) #t) (test "unread-substring-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-substring! "1 2" 1 2 p)) (c0 (read-char p)) ;; space (dummy0b (unread-substring! "1234" 2 2 p)) (sym (read p)) ;; a ( ( tprint ( read - char p ) ) ) (dummy1 (unread-substring! "1b2222" 1 2 p)) (sym2 (read p)) ;; b (dummy2 (begin (read-char p) ;; the space (unread-substring! "02" 1 2 p))) 21 (char (read p)) (dummy3 (unread-substring! "\"\"124332" 0 2 p)) (str1 (read p)) (dummy4 (begin (read-char p) ;; the space (unread-substring! "1234567890#\\" 10 12 p))) (char2 (read p)) ;; #\" (dummy5 (unread-substring! "\"" 0 1 p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-substring-error1" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "" 0 2 p) #f)) #t) (test "unread-substring-error2" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "aoeu" -1 0 p) #f)) #t) (test "unread-substring-error3" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "oaeu" 2 0 p) #f)) #t) (test "unread-substring-error4" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (close-input-port p) (unread-substring! "oaeu" 0 2 p) #f)) #t))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/recette/rgc_insert.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * Some rgc-buffer-insert-string tests */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ ab1 g-p s t space a b the space the space #\" space a b the space the space #\" a1 c ab1 g-p s t space a b the space the space #\"
* serrano / prgm / project / bigloo / recette / rgc - insert.scm * / * Author : * / * Creation : Thu Sep 3 12:29:48 2009 * / * Last change : Thu Sep 3 14:10:30 2009 ( serrano ) * / * Copyright : 2009 * / (module rgc-insert (import (main "main.scm")) (include "test.sch") (export (test-rgc-insert))) (define *number* (regular-grammar () ((: (submatch (+ digit)) "." (submatch (+ digit))) (cons (string->integer (the-submatch 1)) (string->integer (the-submatch 2)))))) (define *number2* (regular-grammar () ((: (submatch (* digit)) "." (submatch (* digit))) (cons (string->integer (the-submatch 1)) (string->integer (the-submatch 2)))))) (define (test-rgc-insert) (test-module "rgc-insert" "rgc-insert.scm") (test "unread-string-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-string! "ab" p)) (dummy2 (unread-string! "cdefghijklmnop" p)) cdef 23456 (dummy3 (unread-string! "qr" p)) qr789 (c-ready? (char-ready? p)) (dummy4 (unread-string! "st" p)) (c-ready?2 (char-ready? p)) (c-ready?3 (char-ready? p)) (str8 (read p))) (and (equal? str1 "ab1") (equal? str2 "cdef") (equal? str3 "ghijklmnop") (equal? str4 "23456") (equal? str5 "qr789") (not c-ready?) (equal? str6 "s") c-ready?2 (equal? str7 "t") (not c-ready?3) (eof-object? str8))) #t) (test "unread-string-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-string! " " p)) (dummy0b (unread-string! "" p)) ( ( tprint ( read - char p ) ) ) (dummy1 (unread-string! "b" p)) (dummy2 (begin (unread-string! "2" p))) 21 (char (read p)) (dummy3 (unread-string! "\"\"" p)) (str1 (read p)) (dummy4 (begin (unread-string! "#\\" p))) (dummy5 (unread-string! "\"" p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-string-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-char! #\space p)) (dummy1 (unread-char! #\b p)) (dummy2 (begin (unread-char! #\2 p))) 21 (char (read p)) (dummy3 (begin (unread-char! #\" p) (unread-char! #\" p))) (str1 (read p)) (dummy4 (begin (unread-char! #\\ p) (unread-char! #\# p))) (dummy5 (unread-char! #\" p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-char-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-char! #\a p)) (dummy2 (unread-char! #\c p)) (and (equal? str1 "a1") (equal? str2 "c"))) #t) (test "unread-substring-readchars" (let* ((p (open-input-string "123456789")) (dummy1 (unread-substring! "0ab1" 1 3 p)) (dummy2 (unread-substring! "1234cdefghijklmnop11" 4 18 p)) cdef 23456 (dummy3 (unread-substring! "qr1" 0 2 p)) qr789 (c-ready? (char-ready? p)) (dummy4 (unread-substring! "0st" 1 3 p)) (c-ready?2 (char-ready? p)) (c-ready?3 (char-ready? p)) (str8 (read p))) (and (equal? str1 "ab1") (equal? str2 "cdef") (equal? str3 "ghijklmnop") (equal? str4 "23456") (equal? str5 "qr789") (not c-ready?) (equal? str6 "s") c-ready?2 (equal? str7 "t") (not c-ready?3) (eof-object? str8))) #t) (test "unread-substring-read" (let* ((p (open-input-string "a 1 #\\x \"str\"")) (dummy0 (unread-substring! "1 2" 1 2 p)) (dummy0b (unread-substring! "1234" 2 2 p)) ( ( tprint ( read - char p ) ) ) (dummy1 (unread-substring! "1b2222" 1 2 p)) (dummy2 (begin (unread-substring! "02" 1 2 p))) 21 (char (read p)) (dummy3 (unread-substring! "\"\"124332" 0 2 p)) (str1 (read p)) (dummy4 (begin (unread-substring! "1234567890#\\" 10 12 p))) (dummy5 (unread-substring! "\"" 0 1 p)) (str2 (read p))) ( tprint sym " " sym2 " " nb " " char " " str1 " " char2 " " str2 ) (and (equal? c0 #\space) (eq? sym 'a) (eq? sym2 'b) (=fx nb 21) (char=? char #\x) (string=? str1 "") (char=? char2 #\") (string=? str2 "str"))) #t) (test "unread-substring-error1" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "" 0 2 p) #f)) #t) (test "unread-substring-error2" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "aoeu" -1 0 p) #f)) #t) (test "unread-substring-error3" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (unread-substring! "oaeu" 2 0 p) #f)) #t) (test "unread-substring-error4" (with-handler (lambda (e) #t) (let ((p (open-input-string "A"))) (close-input-port p) (unread-substring! "oaeu" 0 2 p) #f)) #t))
e91f84c21bfaad06d0c3d8570b897766d64bf352f5a9ab30e5043abf02ad9a8b
LexiFi/menhir
coqBackend.mli
(******************************************************************************) (* *) (* *) , Paris , PPS , Université Paris Diderot (* *) . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the (* file LICENSE. *) (* *) (******************************************************************************) The coq code generator . module Run (T: sig end) : sig val write_all: out_channel -> unit end
null
https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/src/coqBackend.mli
ocaml
**************************************************************************** file LICENSE. ****************************************************************************
, Paris , PPS , Université Paris Diderot . All rights reserved . This file is distributed under the terms of the GNU General Public License version 2 , as described in the The coq code generator . module Run (T: sig end) : sig val write_all: out_channel -> unit end
9842d0d1ef0ec0a6b61fbe517cf6277b6508767b0adc614e115288eb1adf03d2
uw-unsat/jitsynth
sltu.rkt
#lang rosette (require "../riscv/test-macros.rkt") (provide run-riscv-sltu-tests) (define (run-riscv-sltu-tests) ; See LICENSE for license details. ;***************************************************************************** ; 'sltu.S ;----------------------------------------------------------------------------- ; ; Test 'sltu instruction. ; ;include "riscv_test.h" ;include "test_macros.h" ;------------------------------------------------------------- ; Arithmetic tests ;------------------------------------------------------------- (TEST_RR_OP 2 'sltu 0 #x00000000 #x00000000 ); (TEST_RR_OP 3 'sltu 0 #x00000001 #x00000001 ); (TEST_RR_OP 4 'sltu 1 #x00000003 #x00000007 ); (TEST_RR_OP 5 'sltu 0 #x00000007 #x00000003 ); (TEST_RR_OP 6 'sltu 1 #x00000000 #xffff8000 ); (TEST_RR_OP 7 'sltu 0 #x80000000 #x00000000 ); (TEST_RR_OP 8 'sltu 1 #x80000000 #xffff8000 ); (TEST_RR_OP 9 'sltu 1 #x00000000 #x00007fff ); (TEST_RR_OP 10 'sltu 0 #x7fffffff #x00000000 ); (TEST_RR_OP 11 'sltu 0 #x7fffffff #x00007fff ); (TEST_RR_OP 12 'sltu 0 #x80000000 #x00007fff ); (TEST_RR_OP 13 'sltu 1 #x7fffffff #xffff8000 ); (TEST_RR_OP 14 'sltu 1 #x00000000 #xffffffff ); (TEST_RR_OP 15 'sltu 0 #xffffffff #x00000001 ); (TEST_RR_OP 16 'sltu 0 #xffffffff #xffffffff ); ;------------------------------------------------------------- ; Source/Destination tests ;------------------------------------------------------------- (TEST_RR_SRC1_EQ_DEST 17 'sltu 0 14 13 ); (TEST_RR_SRC2_EQ_DEST 18 'sltu 1 11 13 ); (TEST_RR_SRC12_EQ_DEST 19 'sltu 0 13 ); ;------------------------------------------------------------- ; Bypassing tests ;------------------------------------------------------------- (TEST_RR_DEST_BYPASS 20 0 'sltu 1 11 13 ); (TEST_RR_DEST_BYPASS 21 1 'sltu 0 14 13 ); (TEST_RR_DEST_BYPASS 22 2 'sltu 1 12 13 ); (TEST_RR_SRC12_BYPASS 23 0 0 'sltu 0 14 13 ); (TEST_RR_SRC12_BYPASS 24 0 1 'sltu 1 11 13 ); (TEST_RR_SRC12_BYPASS 25 0 2 'sltu 0 15 13 ); (TEST_RR_SRC12_BYPASS 26 1 0 'sltu 1 10 13 ); (TEST_RR_SRC12_BYPASS 27 1 1 'sltu 0 16 13 ); (TEST_RR_SRC12_BYPASS 28 2 0 'sltu 1 9 13 ); (TEST_RR_SRC21_BYPASS 29 0 0 'sltu 0 17 13 ); (TEST_RR_SRC21_BYPASS 30 0 1 'sltu 1 8 13 ); (TEST_RR_SRC21_BYPASS 31 0 2 'sltu 0 18 13 ); (TEST_RR_SRC21_BYPASS 32 1 0 'sltu 1 7 13 ); (TEST_RR_SRC21_BYPASS 33 1 1 'sltu 0 19 13 ); (TEST_RR_SRC21_BYPASS 34 2 0 'sltu 1 6 13 ); (TEST_RR_ZEROSRC1 35 'sltu 1 -1 ); (TEST_RR_ZEROSRC2 36 'sltu 0 -1 ); (TEST_RR_ZEROSRC12 37 'sltu 0 ); (TEST_RR_ZERODEST 38 'sltu 16 30 ); )
null
https://raw.githubusercontent.com/uw-unsat/jitsynth/69529e18d4a8d4dace884bfde91aa26b549523fa/test/rv64ui/sltu.rkt
racket
See LICENSE for license details. ***************************************************************************** 'sltu.S ----------------------------------------------------------------------------- Test 'sltu instruction. include "riscv_test.h" include "test_macros.h" ------------------------------------------------------------- Arithmetic tests ------------------------------------------------------------- ------------------------------------------------------------- Source/Destination tests ------------------------------------------------------------- ------------------------------------------------------------- Bypassing tests -------------------------------------------------------------
#lang rosette (require "../riscv/test-macros.rkt") (provide run-riscv-sltu-tests) (define (run-riscv-sltu-tests) )
aad9680b717c363ddfcfc811bd8fcf49b5e0e4f4a316f457cda08a7fe506807e
fosskers/aura
Records.hs
-- | Module : . . Records Copyright : ( c ) , 2012 - 2021 -- License : GPL3 Maintainer : < > -- Handle the storing of PKGBUILDs . module Aura.Pkgbuild.Records ( hasPkgbuildStored , storePkgbuilds , pkgbuildPath ) where import Aura.Types import RIO import RIO.Directory import RIO.FilePath import qualified RIO.Text as T --- -- | The default location: \/var\/cache\/aura\/pkgbuilds\/ pkgbuildCache :: FilePath pkgbuildCache = "/var/cache/aura/pkgbuilds/" | The expected path to a stored PKGBUILD , given some package name . pkgbuildPath :: PkgName -> FilePath pkgbuildPath (PkgName p) = pkgbuildCache </> T.unpack p <.> "pb" | Does a given package has a PKGBUILD stored ? -- This is `True` when a package has been built successfully once before. hasPkgbuildStored :: PkgName -> IO Bool hasPkgbuildStored = doesFileExist . pkgbuildPath | Write the PKGBUILDs of some ` Buildable`s to disk . storePkgbuilds :: NonEmpty Buildable -> IO () storePkgbuilds bs = do createDirectoryIfMissing True pkgbuildCache traverse_ (\p -> writePkgbuild (bName p) (bPkgbuild p)) bs writePkgbuild :: PkgName -> Pkgbuild -> IO () writePkgbuild pn (Pkgbuild pb) = writeFileBinary (pkgbuildPath pn) pb
null
https://raw.githubusercontent.com/fosskers/aura/08cd46eaa598094f7395455d66690d3d8c59e965/haskell/aura/lib/Aura/Pkgbuild/Records.hs
haskell
| License : GPL3 - | The default location: \/var\/cache\/aura\/pkgbuilds\/ This is `True` when a package has been built successfully once before.
Module : . . Records Copyright : ( c ) , 2012 - 2021 Maintainer : < > Handle the storing of PKGBUILDs . module Aura.Pkgbuild.Records ( hasPkgbuildStored , storePkgbuilds , pkgbuildPath ) where import Aura.Types import RIO import RIO.Directory import RIO.FilePath import qualified RIO.Text as T pkgbuildCache :: FilePath pkgbuildCache = "/var/cache/aura/pkgbuilds/" | The expected path to a stored PKGBUILD , given some package name . pkgbuildPath :: PkgName -> FilePath pkgbuildPath (PkgName p) = pkgbuildCache </> T.unpack p <.> "pb" | Does a given package has a PKGBUILD stored ? hasPkgbuildStored :: PkgName -> IO Bool hasPkgbuildStored = doesFileExist . pkgbuildPath | Write the PKGBUILDs of some ` Buildable`s to disk . storePkgbuilds :: NonEmpty Buildable -> IO () storePkgbuilds bs = do createDirectoryIfMissing True pkgbuildCache traverse_ (\p -> writePkgbuild (bName p) (bPkgbuild p)) bs writePkgbuild :: PkgName -> Pkgbuild -> IO () writePkgbuild pn (Pkgbuild pb) = writeFileBinary (pkgbuildPath pn) pb
5cac8ffd9736e49709de8c8227920e19b357791e1c6987b6f80f4da0af089fd0
ymyzk/lambda-dti
test_pp.ml
open Format open OUnit2 open Lambda_dti open Syntax open Pp let id x = x let parse str = Parser.toplevel Lexer.main @@ Lexing.from_string str let test_pp_ty = let test (expected, u) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_ty u in List.map test [ "int -> bool", TyFun (TyInt, TyBool); "int -> bool -> ?", TyFun (TyInt, TyFun (TyBool, TyDyn)); "(int -> bool) -> ?", TyFun (TyFun (TyInt, TyBool), TyDyn); "(int -> bool) -> ? -> int", TyFun (TyFun (TyInt, TyBool), TyFun (TyDyn, TyInt)); " ' x1 - > ' x2 " , TyFun ( TyVar 1 , TyVar 2 ) ; ] let test_pp_ty2 = let test (expected, u) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_ty2 u in let a, b, c = Typing.fresh_tyvar (), Typing.fresh_tyvar (), Typing.fresh_tyvar () in List.map test [ "int -> bool", TyFun (TyInt, TyBool); "int -> bool -> ?", TyFun (TyInt, TyFun (TyBool, TyDyn)); "(int -> bool) -> ?", TyFun (TyFun (TyInt, TyBool), TyDyn); "(int -> bool) -> ? -> int", TyFun (TyFun (TyInt, TyBool), TyFun (TyDyn, TyInt)); "'a -> 'b", TyFun (a, b); "'a -> 'b", TyFun (b, a); "('a -> 'b) -> 'a", TyFun (TyFun (c, b), c); ] module ITGL = struct open Pp.ITGL let test_pp_program = let test (e) = e >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id e @@ asprintf "%a" pp_program @@ parse (e ^ ";;") in List.map test [ "fun (x: ?) -> fun (y: ?) -> fun (z: ?) -> z"; "x (y z)"; "x y z"; "1 * 2 + 3 * 4"; "(1 + 2) * (3 + 4)"; "(fun (x: ?) -> x) (fun (y: ?) -> y)"; "1 + (2 : ?)"; ] let suite = [ "test_pp_program">::: test_pp_program; ] end module CC = struct open Pp.CC open Syntax.CC let r = Utils.Error.dummy_range let test_pp_exp = let test (expected, f) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_exp f in let x, y, z = Var (r, "x", []), Var (r, "y", []), Var (r, "z", []) in List.map test [ "x y z", AppExp (r, AppExp (r, x, y), z); "x (y z)", AppExp (r, x, AppExp (r, y, z)); "x * y + z * x", BinOp (r, Plus, BinOp (r, Mult, x, y), BinOp (r, Mult, z, x)); "(x + y) * (z + x)", BinOp (r, Mult, BinOp (r, Plus, x, y), BinOp (r, Plus, z, x)); "(fun (x: ?) -> x): ? -> ? => ?", CastExp (r, FunExp (r, "x", TyDyn, x), TyFun (TyDyn, TyDyn), TyDyn, Pos); "x: int => ?", CastExp (r, x, TyInt, TyDyn, Pos); "x: int => ? => bool", CastExp (r, CastExp (r, x, TyInt, TyDyn, Pos), TyDyn, TyBool, Pos); "(fun (x: ?) -> x) (fun (y: ?) -> y)", AppExp (r, FunExp (r, "x", TyDyn, x), FunExp (r, "y", TyDyn, y)); "x y: int => ?", CastExp (r, AppExp (r, x, y), TyInt, TyDyn, Pos); "x (y: int => ?)", AppExp (r, x, CastExp (r, y, TyInt, TyDyn, Pos)); ] let suite = [ "test_pp_exp">::: test_pp_exp; ] end let suite = [ "test_pp_ty">::: test_pp_ty; "test_pp_ty2">::: test_pp_ty2; "test_ITGL">::: ITGL.suite; "test_CC">::: CC.suite; ]
null
https://raw.githubusercontent.com/ymyzk/lambda-dti/f476c0094832cbaaa336dc1bc86babfb8b652f14/test/test_pp.ml
ocaml
open Format open OUnit2 open Lambda_dti open Syntax open Pp let id x = x let parse str = Parser.toplevel Lexer.main @@ Lexing.from_string str let test_pp_ty = let test (expected, u) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_ty u in List.map test [ "int -> bool", TyFun (TyInt, TyBool); "int -> bool -> ?", TyFun (TyInt, TyFun (TyBool, TyDyn)); "(int -> bool) -> ?", TyFun (TyFun (TyInt, TyBool), TyDyn); "(int -> bool) -> ? -> int", TyFun (TyFun (TyInt, TyBool), TyFun (TyDyn, TyInt)); " ' x1 - > ' x2 " , TyFun ( TyVar 1 , TyVar 2 ) ; ] let test_pp_ty2 = let test (expected, u) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_ty2 u in let a, b, c = Typing.fresh_tyvar (), Typing.fresh_tyvar (), Typing.fresh_tyvar () in List.map test [ "int -> bool", TyFun (TyInt, TyBool); "int -> bool -> ?", TyFun (TyInt, TyFun (TyBool, TyDyn)); "(int -> bool) -> ?", TyFun (TyFun (TyInt, TyBool), TyDyn); "(int -> bool) -> ? -> int", TyFun (TyFun (TyInt, TyBool), TyFun (TyDyn, TyInt)); "'a -> 'b", TyFun (a, b); "'a -> 'b", TyFun (b, a); "('a -> 'b) -> 'a", TyFun (TyFun (c, b), c); ] module ITGL = struct open Pp.ITGL let test_pp_program = let test (e) = e >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id e @@ asprintf "%a" pp_program @@ parse (e ^ ";;") in List.map test [ "fun (x: ?) -> fun (y: ?) -> fun (z: ?) -> z"; "x (y z)"; "x y z"; "1 * 2 + 3 * 4"; "(1 + 2) * (3 + 4)"; "(fun (x: ?) -> x) (fun (y: ?) -> y)"; "1 + (2 : ?)"; ] let suite = [ "test_pp_program">::: test_pp_program; ] end module CC = struct open Pp.CC open Syntax.CC let r = Utils.Error.dummy_range let test_pp_exp = let test (expected, f) = expected >:: fun ctxt -> assert_equal ~ctxt:ctxt ~printer:id expected @@ asprintf "%a" pp_exp f in let x, y, z = Var (r, "x", []), Var (r, "y", []), Var (r, "z", []) in List.map test [ "x y z", AppExp (r, AppExp (r, x, y), z); "x (y z)", AppExp (r, x, AppExp (r, y, z)); "x * y + z * x", BinOp (r, Plus, BinOp (r, Mult, x, y), BinOp (r, Mult, z, x)); "(x + y) * (z + x)", BinOp (r, Mult, BinOp (r, Plus, x, y), BinOp (r, Plus, z, x)); "(fun (x: ?) -> x): ? -> ? => ?", CastExp (r, FunExp (r, "x", TyDyn, x), TyFun (TyDyn, TyDyn), TyDyn, Pos); "x: int => ?", CastExp (r, x, TyInt, TyDyn, Pos); "x: int => ? => bool", CastExp (r, CastExp (r, x, TyInt, TyDyn, Pos), TyDyn, TyBool, Pos); "(fun (x: ?) -> x) (fun (y: ?) -> y)", AppExp (r, FunExp (r, "x", TyDyn, x), FunExp (r, "y", TyDyn, y)); "x y: int => ?", CastExp (r, AppExp (r, x, y), TyInt, TyDyn, Pos); "x (y: int => ?)", AppExp (r, x, CastExp (r, y, TyInt, TyDyn, Pos)); ] let suite = [ "test_pp_exp">::: test_pp_exp; ] end let suite = [ "test_pp_ty">::: test_pp_ty; "test_pp_ty2">::: test_pp_ty2; "test_ITGL">::: ITGL.suite; "test_CC">::: CC.suite; ]
f131e7ae90d59fafeb9e88f6623a5d3249cb33ad335af0982e1aab80cafd5b02
NetComposer/nksip
nksip_unparse.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2019 . All Rights Reserved . %% 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 General SIP message generation functions -module(nksip_unparse). -author('Carlos Gonzalez <>'). -include_lib("nklib/include/nklib.hrl"). -include("nksip.hrl"). -export([header/1, packet/1, response/3, error_reason/1]). %% =================================================================== %% Public %% =================================================================== %% @doc -spec header(nksip:header_value()) -> binary(). header([]) -> <<>>; header([First|_]=List) when not is_integer(First) -> nklib_util:bjoin([header(Term) || Term <- List]); header(#via{}=Via) -> list_to_binary(raw_via(Via)); header(Other) -> nklib_unparse:header(Other). % header(Value) -> % case unparse_header(Value) of % Binary when is_binary(Binary) -> Binary; IoList - > list_to_binary(IoList ) % end. % %% @private % unparse_header(Value) when is_binary(Value) -> % Value; % unparse_header(#uri{}=Uri) -> nklib_unparse : uri(Uri ) ; unparse_header({Name , } ) when is_list(Opts ) - > nklib_unparse : token({Name , } ) ; % unparse_header([H|_]=String) when is_integer(H) -> % String; % unparse_header(List) when is_list(List) -> % join([unparse_header(Term) || Term <- List], []); % unparse_header(Value) when is_integer(Value); is_atom(Value) -> % nklib_util:to_binary(Value). @private Generates a binary packet for a request or response -spec packet(nksip:request() | nksip:response()) -> binary(). packet(#sipmsg{class={resp, Code, Reason}}=Response) -> list_to_binary([<<"SIP/2.0 ">>, nklib_util:to_binary(Code), 32, case Reason of <<>> -> response_phrase(Code); RespText -> RespText end, <<"\r\n">>, serialize(Response)]); packet(#sipmsg{class={req, Method}, ruri=RUri}=Request) -> list_to_binary([ nklib_util:to_binary(Method), 32, nklib_unparse:uri3(RUri), <<" SIP/2.0\r\n">>, serialize(Request) ]). %% @doc Generates an error response -spec response([{binary(), term()}], nksip:sip_code(), binary()) -> binary(). response(Headers, Code, Reason) -> list_to_binary([ "SIP/2.0 ", nklib_util:to_list(Code), 32, case Reason of <<>> -> response_phrase(Code); _ -> Reason end, "\r\n", "Via: ", nklib_util:get_binary(<<"via">>, Headers), "\r\n", "From: ", nklib_util:get_binary(<<"from">>, Headers), "\r\n", "To: ", nklib_util:get_binary(<<"to">>, Headers), "\r\n", "Call-ID: ", nklib_util:get_binary(<<"call-id">>, Headers), "\r\n", "CSeq: ", nklib_util:get_binary(<<"cseq">>, Headers), "\r\n", "Max-Forwards: ", nklib_util:get_binary(<<"max-forwards">>, Headers), "\r\n", "Content-Length: 0\r\n", "\r\n" ]). @doc Serializes a ' reason ' header -spec error_reason(nksip:error_reason()) -> binary() | error. error_reason({sip, Code}) -> error_reason({sip, Code, response_phrase(Code)}); error_reason({q850, Code}) -> error_reason({q850, Code, q850_prase(Code)}); error_reason({sip, Code, Text}) -> do_error_reason({<<"SIP">>, Code, Text}); error_reason({q850, Code, Text}) -> do_error_reason({<<"Q.850">>, Code, Text}); error_reason(_) -> error. @private do_error_reason({Name, Code, Text}) -> Token = {nklib_util:to_binary(Name), [ {<<"cause">>, nklib_util:to_binary(Code)}, {<<"text">>, <<$", (nklib_util:to_binary(Text))/binary, $">>} ]}, nklib_unparse:token(Token). % % @doc Serializes an ` uri ( ) ' into a ` optslist ( ) ' . % % The first options in the list will be ` scheme ' , ` user ' and ` domain ' . % % The rest will be present only if they are present in the % -spec uri2proplist(nksip:uri()) -> [Opts] when % Opts :: {scheme, nksip:scheme()} | {user, binary()} | {domain, binary()} | % {disp, binary()} | {pass, binary()} | {port, inet:port_number()} | { opts , nksip : optslist ( ) } | { headers , [ binary()|nksip : header ( ) ] } | { ext_opts , nksip : optslist ( ) } | { ext_headers , [ binary()|nksip : header ( ) ] } . % uri2proplist(#uri{ % disp = Disp, % scheme = Scheme, % user = User, % pass = Pass, % domain = Domain, % port = Port, opts = Opts , % headers = Headers, % ext_opts = ExtOpts, % ext_headers = ExtHeaders}) -> % lists:flatten([ % {scheme, Scheme}, % {user, User}, % {domain, Domain}, % case Disp of <<>> -> []; _ -> {disp, Disp} end, % case Pass of <<>> -> []; _ -> {pass, Pass} end, case Port of 0 - > [ ] ; _ - > { port , Port } end , case of [ ] - > [ ] ; _ - > { opts , Opts } end , % case Headers of [] -> []; _ -> {headers, Headers} end, % case ExtOpts of [] -> []; _ -> {ext_opts, ExtOpts} end, case ExtHeaders of [ ] - > [ ] ; _ - > { ext_headers , Headers } end % ]). % % @doc Serializes a ` nksip : via ( ) ' % -spec via(nksip:via()) -> % binary(). % via(#via{}=Via) -> % list_to_binary(raw_via(Via)). % % @doc Serializes a list of ` token ( ) ' % -spec token(nksip:token() | [nksip:token()] | undefined) -> % binary(). token(undefined ) - > % <<>>; token({Token , } ) - > % token([{Token, Opts}]); % token(Tokens) when is_list(Tokens) -> % list_to_binary(raw_tokens(Tokens)). % %% @doc Adds a "+sip_instance" media feature tag to a Contact % -spec add_sip_instance(nkserver:id(), nksip:uri()) -> % {ok, nksip:uri()} | {error, service_not_found}. add_sip_instance(SrvId , # uri{ext_opts = ExtOpts}=Uri ) - > case : uuid(SrvId ) of % {ok, UUID} -> ExtOpts1 = nklib_util : store_value(<<"+sip.instance " > > , UUID , ExtOpts ) , { ok , Uri#uri{ext_opts = ExtOpts1 } } ; % {error, not_found} -> % {error, service_not_found} % end. %% =================================================================== %% Private %% =================================================================== % %% @private Serializes an `nksip:uri()', using `<' and `>' as delimiters % -spec raw_uri(nksip:uri()) -> % iolist(). % raw_uri(#uri{domain=(<<"*">>)}) -> % [<<"*">>]; % raw_uri(#uri{}=Uri) -> % [ Uri#uri.disp , $ < , nklib_util : to_binary(Uri#uri.scheme ) , $ : , % case Uri#uri.user of % <<>> -> <<>>; % User -> case Uri#uri.pass of % <<>> -> [User, $@]; % Pass -> [User, $:, Pass, $@] % end % end, % Uri#uri.domain, case Uri#uri.port of % 0 -> []; % Port -> [$:, integer_to_list(Port)] % end, % gen_opts(Uri#uri.opts), % gen_headers(Uri#uri.headers), % $>, % gen_opts(Uri#uri.ext_opts), % gen_headers(Uri#uri.ext_headers) % ]. % %% @private Serializes an `nksip:uri()' without `<' and `>' as delimiters % -spec raw_ruri(nksip:uri()) -> % iolist(). % raw_ruri(#uri{}=Uri) -> % [ nklib_util : to_binary(Uri#uri.scheme ) , $ : , % case Uri#uri.user of % <<>> -> <<>>; % User -> case Uri#uri.pass of % <<>> -> [User, $@]; % Pass -> [User, $:, Pass, $@] % end % end, % Uri#uri.domain, case Uri#uri.port of % 0 -> []; % Port -> [$:, integer_to_list(Port)] % end, % gen_opts(Uri#uri.opts) % ]. @private Serializes a ` nksip : via ( ) ' -spec raw_via(nksip:via()) -> iolist(). raw_via(#via{}=Via) -> [ <<"SIP/2.0/">>, string:to_upper(nklib_util:to_list(Via#via.transp)), 32, Via#via.domain, case Via#via.port of 0 -> []; Port -> [$:, integer_to_list(Port)] end, nklib_unparse:gen_opts(Via#via.opts) ]. % % @private Serializes a list of ` token ( ) ' % -spec raw_tokens(nksip:token() | [nksip:token()]) -> % iolist(). % raw_tokens([]) -> % []; raw_tokens({Name , } ) - > raw_tokens([{Name , } ] ) ; raw_tokens(Tokens ) - > raw_tokens(Tokens , [ ] ) . % %% @private % -spec raw_tokens([nksip:token()], iolist()) -> % iolist(). raw_tokens([{Head , } , Second | Rest ] , Acc ) - > Head1 = nklib_util : to_binary(Head ) , raw_tokens([Second|Rest ] , [ [ , gen_opts(Opts ) , $ , ] |Acc ] ) ; raw_tokens([{Head , } ] , Acc ) - > Head1 = nklib_util : to_binary(Head ) , lists : reverse([[Head1 , gen_opts(Opts)]|Acc ] ) . @private Serializes a request or response . If ` body ' is a ` nksip_sdp : sdp ( ) ' it will be %% serialized also. -spec serialize(nksip:request() | nksip:response()) -> iolist(). serialize(#sipmsg{ vias = Vias, from = {From, _}, to = {To, _}, call_id = CallId, cseq = {CSeq, Method}, forwards = Forwards, routes = Routes, contacts = Contacts, headers = Headers, content_type = ContentType, require = Require, supported = Supported, expires = Expires, event = Event, body = Body }) -> Body1 = case Body of _ when is_binary(Body) -> Body; [F|_]=Body when is_integer(F) -> Body; #sdp{} -> nksip_sdp:unparse(Body); _ -> base64:encode(term_to_binary(Body)) end, Headers1 = [ [{<<"Via">>, Via} || Via <- Vias], {<<"From">>, From}, {<<"To">>, To}, {<<"Call-ID">>, CallId}, {<<"CSeq">>, <<(nklib_util:to_binary(CSeq))/binary, " ", (nklib_util:to_binary(Method))/binary>>}, {<<"Max-Forwards">>, Forwards}, {<<"Content-Length">>, byte_size(Body1)}, [{<<"Route">>, Route} || Route <- Routes], [{<<"Contact">>, Contact} || Contact <- Contacts], {<<"Content-Type">>, ContentType}, {<<"Require">>, Require}, {<<"Supported">>, Supported}, {<<"Expires">>, Expires}, {<<"Event">>, Event} | Headers ], [ [ [nklib_util:capitalize(Name), $:, 32, header(Value), 13, 10] || {Name, Value} <- lists:flatten(Headers1), Value /= [], Value /= <<>>, Value /= undefined ], "\r\n", Body1 ]. % %% @private % join([], Acc) -> Acc ; join([A , B | Rest ] , Acc ) - > % join([B|Rest], [$,, A | Acc]); join([A ] , Acc ) - > % lists:reverse([A|Acc]). @private -spec response_phrase(nksip:sip_code()) -> binary(). response_phrase(Code) -> case Code of 100 -> <<"Trying">>; 180 -> <<"Ringing">>; 181 -> <<"Call Is Being Forwarded">>; 182 -> <<"Queued">>; 183 -> <<"Session Progress">>; 199 -> <<"Early Dialog Terminated">>; 200 -> <<"OK">>; 202 -> <<"Accepted">>; 204 -> <<"No Notification">>; 300 -> <<"Multiple Choices">>; 301 -> <<"Moved Permanently">>; 302 -> <<"Moved Temporarily">>; 305 -> <<"Use Proxy">>; 380 -> <<"Alternative Service">>; 400 -> <<"Bad Request">>; 401 -> <<"Unauthorized">>; 402 -> <<"Payment Required">>; 403 -> <<"Forbidden">>; 404 -> <<"Not Found">>; 405 -> <<"Method Not Allowed">>; 406 -> <<"Not Acceptable">>; 407 -> <<"Proxy Authentication Required">>; 408 -> <<"Request Timeout">>; 410 -> <<"Gone">>; 412 -> <<"Conditional Request Failed">>; 413 -> <<"Request Entity Too Large">>; 414 -> <<"Request-URI Too Long">>; 415 -> <<"Unsupported Media Type">>; 416 -> <<"Unsupported URI Scheme">>; 417 -> <<"Unknown Resource Priority">>; 420 -> <<"Bad Extension">>; 421 -> <<"Extension Required">>; 422 -> <<"Session Interval Too Small">>; 423 -> <<"Interval Too Brief">>; 424 -> <<"Bad Location Information">>; 428 -> <<"Use Identity Header">>; 429 -> <<"Provide Referrer Identity">>; 430 -> <<"Flow Failed">>; 433 -> <<"Anonymity Disallowed">>; 436 -> <<"Bad Identity-Info">>; 437 -> <<"Unsupported Certificate">>; 438 -> <<"Invalid Identity Header">>; 439 -> <<"First Hop Lacks Outbound Support">>; 440 -> <<"Max-Breadth Exceeded">>; 469 -> <<"Bad Info Package">>; 470 -> <<"Consent Needed">>; 480 -> <<"Temporarily Unavailable">>; 481 -> <<"Call/Transaction Does Not Exist">>; 482 -> <<"Loop Detected">>; 483 -> <<"Too Many Hops">>; 484 -> <<"Address Incomplete">>; 485 -> <<"Ambiguous">>; 486 -> <<"Busy Here">>; 487 -> <<"Request Terminated">>; 488 -> <<"Not Acceptable Here">>; 489 -> <<"Bad Event">>; 491 -> <<"Request Pending">>; 493 -> <<"Undecipherable">>; 494 -> <<"Security Agreement Required">>; 500 -> <<"Server Internal Error">>; 501 -> <<"Not Implemented">>; 502 -> <<"Bad Gateway">>; 503 -> <<"Service Unavailable">>; % Network error 504 -> <<"Server Time-out">>; 505 -> <<"Version Not Supported">>; 513 -> <<"Message Too Large">>; 580 -> <<"Precondition Faillure">>; 600 -> <<"Busy Everywhere">>; 603 -> <<"Decline">>; 604 -> <<"Does Not Exist Anywhere">>; 606 -> <<"Not Acceptable">>; _ -> <<"Unknown Code">> end. % %% @private % gen_opts(Opts) -> % gen_opts(Opts, []). % %% @private % gen_opts([], Acc) -> % lists:reverse(Acc); gen_opts([{K , V}|Rest ] , Acc ) - > gen_opts(Rest , [ [ $ ; , nklib_util : ) , $ = , nklib_util : ) ] | Acc ] ) ; gen_opts([K|Rest ] , Acc ) - > gen_opts(Rest , [ [ $ ; , nklib_util : ) ] | Acc ] ) . % %% @private % gen_headers(Hds) -> % gen_headers(Hds, []). % %% @private % gen_headers([], []) -> % []; % gen_headers([], Acc) -> % [[_|R1]|R2] = lists:reverse(Acc), % [$?, R1|R2]; gen_headers([{K , V}|Rest ] , Acc ) - > gen_headers(Rest , [ [ $ & , nklib_util : ) , $ = , nklib_util : ) ] | Acc ] ) ; gen_headers([K|Rest ] , Acc ) - > gen_headers(Rest , [ [ $ & , nklib_util : ) ] | Acc ] ) . @private %% q850_prase(Code) -> case Code of 0 -> <<"UNSPECIFIED">>; 1 -> <<"UNALLOCATED_NUMBER">>; 2 -> <<"NO_ROUTE_TRANSIT_NET">>; 3 -> <<"NO_ROUTE_DESTINATION">>; 6 -> <<"CHANNEL_UNACCEPTABLE">>; 7 -> <<"CALL_AWARDED_DELIVERED">>; 16 -> <<"NORMAL_CLEARING">>; 17 -> <<"USER_BUSY">>; 18 -> <<"NO_USER_RESPONSE">>; 19 -> <<"NO_ANSWER">>; 20 -> <<"SUBSCRIBER_ABSENT">>; 21 -> <<"CALL_REJECTED">>; 22 -> <<"NUMBER_CHANGED">>; 23 -> <<"REDIRECTION_TO_NEW_DESTINATION">>; 25 -> <<"EXCHANGE_ROUTING_ERROR">>; 27 -> <<"DESTINATION_OUT_OF_ORDER">>; 28 -> <<"INVALID_NUMBER_FORMAT">>; 29 -> <<"FACILITY_REJECTED">>; 30 -> <<"RESPONSE_TO_STATUS_ENQUIRY">>; 31 -> <<"NORMAL_UNSPECIFIED">>; 34 -> <<"NORMAL_CIRCUIT_CONGESTION">>; 38 -> <<"NETWORK_OUT_OF_ORDER">>; 41 -> <<"NORMAL_TEMPORARY_FAILURE">>; 42 -> <<"SWITCH_CONGESTION">>; 43 -> <<"ACCESS_INFO_DISCARDED">>; 44 -> <<"REQUESTED_CHAN_UNAVAIL">>; 45 -> <<"PRE_EMPTED">>; 47 -> <<"RESOURCE_UNAVAILABLE">>; 50 -> <<"FACILITY_NOT_SUBSCRIBED">>; 52 -> <<"OUTGOING_CALL_BARRED">>; 54 -> <<"INCOMING_CALL_BARRED">>; 57 -> <<"BEARERCAPABILITY_NOTAUTH">>; 58 -> <<"BEARERCAPABILITY_NOTAVAIL">>; 63 -> <<"SERVICE_UNAVAILABLE">>; 65 -> <<"BEARERCAPABILITY_NOTIMPL">>; 66 -> <<"CHAN_NOT_IMPLEMENTED">>; 69 -> <<"FACILITY_NOT_IMPLEMENTED">>; 79 -> <<"SERVICE_NOT_IMPLEMENTED">>; 81 -> <<"INVALID_CALL_REFERENCE">>; 88 -> <<"INCOMPATIBLE_DESTINATION">>; 95 -> <<"INVALID_MSG_UNSPECIFIED">>; 96 -> <<"MANDATORY_IE_MISSING">>; 97 -> <<"MESSAGE_TYPE_NONEXIST">>; 99 -> <<"IE_NONEXIST">>; 100 -> <<"INVALID_IE_CONTENTS">>; 101 -> <<"WRONG_CALL_STATE">>; 102 -> <<"RECOVERY_ON_TIMER_EXPIRE">>; 103 -> <<"MANDATORY_IE_LENGTH_ERROR">>; 111 -> <<"PROTOCOL_ERROR">>; 127 -> <<"INTERWORKING">>; 487 -> <<"ORIGINATOR_CANCEL">>; 500 -> <<"CRASH">>; 501 -> <<"SYSTEM_SHUTDOWN">>; 502 -> <<"LOSE_RACE">>; 503 -> <<"MANAGER_REQUEST">>; 600 -> <<"BLIND_TRANSFER">>; 601 -> <<"ATTENDED_TRANSFER">>; 602 -> <<"ALLOTTED_TIMEOUT">>; 603 -> <<"USER_CHALLENGE">>; 604 -> <<"MEDIA_TIMEOUT">>; 605 -> <<"PICKED_OFF">>; 606 -> <<"USER_NOT_REGISTERED">>; 607 -> <<"PROGRESS_TIMEOUT">>; 609 -> <<"GATEWAY_DOWN">>; _ -> <<"UNDEFINED">> end.
null
https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/src/nksip_unparse.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file 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. ------------------------------------------------------------------- @doc General SIP message generation functions =================================================================== Public =================================================================== @doc header(Value) -> case unparse_header(Value) of Binary when is_binary(Binary) -> Binary; end. %% @private unparse_header(Value) when is_binary(Value) -> Value; unparse_header(#uri{}=Uri) -> unparse_header([H|_]=String) when is_integer(H) -> String; unparse_header(List) when is_list(List) -> join([unparse_header(Term) || Term <- List], []); unparse_header(Value) when is_integer(Value); is_atom(Value) -> nklib_util:to_binary(Value). @doc Generates an error response % @doc Serializes an ` uri ( ) ' into a ` optslist ( ) ' . % The first options in the list will be ` scheme ' , ` user ' and ` domain ' . % The rest will be present only if they are present in the -spec uri2proplist(nksip:uri()) -> [Opts] when Opts :: {scheme, nksip:scheme()} | {user, binary()} | {domain, binary()} | {disp, binary()} | {pass, binary()} | {port, inet:port_number()} | uri2proplist(#uri{ disp = Disp, scheme = Scheme, user = User, pass = Pass, domain = Domain, port = Port, headers = Headers, ext_opts = ExtOpts, ext_headers = ExtHeaders}) -> lists:flatten([ {scheme, Scheme}, {user, User}, {domain, Domain}, case Disp of <<>> -> []; _ -> {disp, Disp} end, case Pass of <<>> -> []; _ -> {pass, Pass} end, case Headers of [] -> []; _ -> {headers, Headers} end, case ExtOpts of [] -> []; _ -> {ext_opts, ExtOpts} end, ]). % @doc Serializes a ` nksip : via ( ) ' -spec via(nksip:via()) -> binary(). via(#via{}=Via) -> list_to_binary(raw_via(Via)). % @doc Serializes a list of ` token ( ) ' -spec token(nksip:token() | [nksip:token()] | undefined) -> binary(). <<>>; token([{Token, Opts}]); token(Tokens) when is_list(Tokens) -> list_to_binary(raw_tokens(Tokens)). %% @doc Adds a "+sip_instance" media feature tag to a Contact -spec add_sip_instance(nkserver:id(), nksip:uri()) -> {ok, nksip:uri()} | {error, service_not_found}. {ok, UUID} -> {error, not_found} -> {error, service_not_found} end. =================================================================== Private =================================================================== %% @private Serializes an `nksip:uri()', using `<' and `>' as delimiters -spec raw_uri(nksip:uri()) -> iolist(). raw_uri(#uri{domain=(<<"*">>)}) -> [<<"*">>]; raw_uri(#uri{}=Uri) -> [ case Uri#uri.user of <<>> -> <<>>; User -> <<>> -> [User, $@]; Pass -> [User, $:, Pass, $@] end end, Uri#uri.domain, 0 -> []; Port -> [$:, integer_to_list(Port)] end, gen_opts(Uri#uri.opts), gen_headers(Uri#uri.headers), $>, gen_opts(Uri#uri.ext_opts), gen_headers(Uri#uri.ext_headers) ]. %% @private Serializes an `nksip:uri()' without `<' and `>' as delimiters -spec raw_ruri(nksip:uri()) -> iolist(). raw_ruri(#uri{}=Uri) -> [ case Uri#uri.user of <<>> -> <<>>; User -> <<>> -> [User, $@]; Pass -> [User, $:, Pass, $@] end end, Uri#uri.domain, 0 -> []; Port -> [$:, integer_to_list(Port)] end, gen_opts(Uri#uri.opts) ]. % @private Serializes a list of ` token ( ) ' -spec raw_tokens(nksip:token() | [nksip:token()]) -> iolist(). raw_tokens([]) -> []; %% @private -spec raw_tokens([nksip:token()], iolist()) -> iolist(). serialized also. %% @private join([], Acc) -> join([B|Rest], [$,, A | Acc]); lists:reverse([A|Acc]). Network error %% @private gen_opts(Opts) -> gen_opts(Opts, []). %% @private gen_opts([], Acc) -> lists:reverse(Acc); %% @private gen_headers(Hds) -> gen_headers(Hds, []). %% @private gen_headers([], []) -> []; gen_headers([], Acc) -> [[_|R1]|R2] = lists:reverse(Acc), [$?, R1|R2];
Copyright ( c ) 2019 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(nksip_unparse). -author('Carlos Gonzalez <>'). -include_lib("nklib/include/nklib.hrl"). -include("nksip.hrl"). -export([header/1, packet/1, response/3, error_reason/1]). -spec header(nksip:header_value()) -> binary(). header([]) -> <<>>; header([First|_]=List) when not is_integer(First) -> nklib_util:bjoin([header(Term) || Term <- List]); header(#via{}=Via) -> list_to_binary(raw_via(Via)); header(Other) -> nklib_unparse:header(Other). IoList - > list_to_binary(IoList ) nklib_unparse : uri(Uri ) ; unparse_header({Name , } ) when is_list(Opts ) - > nklib_unparse : token({Name , } ) ; @private Generates a binary packet for a request or response -spec packet(nksip:request() | nksip:response()) -> binary(). packet(#sipmsg{class={resp, Code, Reason}}=Response) -> list_to_binary([<<"SIP/2.0 ">>, nklib_util:to_binary(Code), 32, case Reason of <<>> -> response_phrase(Code); RespText -> RespText end, <<"\r\n">>, serialize(Response)]); packet(#sipmsg{class={req, Method}, ruri=RUri}=Request) -> list_to_binary([ nklib_util:to_binary(Method), 32, nklib_unparse:uri3(RUri), <<" SIP/2.0\r\n">>, serialize(Request) ]). -spec response([{binary(), term()}], nksip:sip_code(), binary()) -> binary(). response(Headers, Code, Reason) -> list_to_binary([ "SIP/2.0 ", nklib_util:to_list(Code), 32, case Reason of <<>> -> response_phrase(Code); _ -> Reason end, "\r\n", "Via: ", nklib_util:get_binary(<<"via">>, Headers), "\r\n", "From: ", nklib_util:get_binary(<<"from">>, Headers), "\r\n", "To: ", nklib_util:get_binary(<<"to">>, Headers), "\r\n", "Call-ID: ", nklib_util:get_binary(<<"call-id">>, Headers), "\r\n", "CSeq: ", nklib_util:get_binary(<<"cseq">>, Headers), "\r\n", "Max-Forwards: ", nklib_util:get_binary(<<"max-forwards">>, Headers), "\r\n", "Content-Length: 0\r\n", "\r\n" ]). @doc Serializes a ' reason ' header -spec error_reason(nksip:error_reason()) -> binary() | error. error_reason({sip, Code}) -> error_reason({sip, Code, response_phrase(Code)}); error_reason({q850, Code}) -> error_reason({q850, Code, q850_prase(Code)}); error_reason({sip, Code, Text}) -> do_error_reason({<<"SIP">>, Code, Text}); error_reason({q850, Code, Text}) -> do_error_reason({<<"Q.850">>, Code, Text}); error_reason(_) -> error. @private do_error_reason({Name, Code, Text}) -> Token = {nklib_util:to_binary(Name), [ {<<"cause">>, nklib_util:to_binary(Code)}, {<<"text">>, <<$", (nklib_util:to_binary(Text))/binary, $">>} ]}, nklib_unparse:token(Token). { opts , nksip : optslist ( ) } | { headers , [ binary()|nksip : header ( ) ] } | { ext_opts , nksip : optslist ( ) } | { ext_headers , [ binary()|nksip : header ( ) ] } . opts = Opts , case Port of 0 - > [ ] ; _ - > { port , Port } end , case of [ ] - > [ ] ; _ - > { opts , Opts } end , case ExtHeaders of [ ] - > [ ] ; _ - > { ext_headers , Headers } end token(undefined ) - > token({Token , } ) - > add_sip_instance(SrvId , # uri{ext_opts = ExtOpts}=Uri ) - > case : uuid(SrvId ) of ExtOpts1 = nklib_util : store_value(<<"+sip.instance " > > , UUID , ExtOpts ) , { ok , Uri#uri{ext_opts = ExtOpts1 } } ; Uri#uri.disp , $ < , nklib_util : to_binary(Uri#uri.scheme ) , $ : , case Uri#uri.pass of case Uri#uri.port of nklib_util : to_binary(Uri#uri.scheme ) , $ : , case Uri#uri.pass of case Uri#uri.port of @private Serializes a ` nksip : via ( ) ' -spec raw_via(nksip:via()) -> iolist(). raw_via(#via{}=Via) -> [ <<"SIP/2.0/">>, string:to_upper(nklib_util:to_list(Via#via.transp)), 32, Via#via.domain, case Via#via.port of 0 -> []; Port -> [$:, integer_to_list(Port)] end, nklib_unparse:gen_opts(Via#via.opts) ]. raw_tokens({Name , } ) - > raw_tokens([{Name , } ] ) ; raw_tokens(Tokens ) - > raw_tokens(Tokens , [ ] ) . raw_tokens([{Head , } , Second | Rest ] , Acc ) - > Head1 = nklib_util : to_binary(Head ) , raw_tokens([Second|Rest ] , [ [ , gen_opts(Opts ) , $ , ] |Acc ] ) ; raw_tokens([{Head , } ] , Acc ) - > Head1 = nklib_util : to_binary(Head ) , lists : reverse([[Head1 , gen_opts(Opts)]|Acc ] ) . @private Serializes a request or response . If ` body ' is a ` nksip_sdp : sdp ( ) ' it will be -spec serialize(nksip:request() | nksip:response()) -> iolist(). serialize(#sipmsg{ vias = Vias, from = {From, _}, to = {To, _}, call_id = CallId, cseq = {CSeq, Method}, forwards = Forwards, routes = Routes, contacts = Contacts, headers = Headers, content_type = ContentType, require = Require, supported = Supported, expires = Expires, event = Event, body = Body }) -> Body1 = case Body of _ when is_binary(Body) -> Body; [F|_]=Body when is_integer(F) -> Body; #sdp{} -> nksip_sdp:unparse(Body); _ -> base64:encode(term_to_binary(Body)) end, Headers1 = [ [{<<"Via">>, Via} || Via <- Vias], {<<"From">>, From}, {<<"To">>, To}, {<<"Call-ID">>, CallId}, {<<"CSeq">>, <<(nklib_util:to_binary(CSeq))/binary, " ", (nklib_util:to_binary(Method))/binary>>}, {<<"Max-Forwards">>, Forwards}, {<<"Content-Length">>, byte_size(Body1)}, [{<<"Route">>, Route} || Route <- Routes], [{<<"Contact">>, Contact} || Contact <- Contacts], {<<"Content-Type">>, ContentType}, {<<"Require">>, Require}, {<<"Supported">>, Supported}, {<<"Expires">>, Expires}, {<<"Event">>, Event} | Headers ], [ [ [nklib_util:capitalize(Name), $:, 32, header(Value), 13, 10] || {Name, Value} <- lists:flatten(Headers1), Value /= [], Value /= <<>>, Value /= undefined ], "\r\n", Body1 ]. Acc ; join([A , B | Rest ] , Acc ) - > join([A ] , Acc ) - > @private -spec response_phrase(nksip:sip_code()) -> binary(). response_phrase(Code) -> case Code of 100 -> <<"Trying">>; 180 -> <<"Ringing">>; 181 -> <<"Call Is Being Forwarded">>; 182 -> <<"Queued">>; 183 -> <<"Session Progress">>; 199 -> <<"Early Dialog Terminated">>; 200 -> <<"OK">>; 202 -> <<"Accepted">>; 204 -> <<"No Notification">>; 300 -> <<"Multiple Choices">>; 301 -> <<"Moved Permanently">>; 302 -> <<"Moved Temporarily">>; 305 -> <<"Use Proxy">>; 380 -> <<"Alternative Service">>; 400 -> <<"Bad Request">>; 401 -> <<"Unauthorized">>; 402 -> <<"Payment Required">>; 403 -> <<"Forbidden">>; 404 -> <<"Not Found">>; 405 -> <<"Method Not Allowed">>; 406 -> <<"Not Acceptable">>; 407 -> <<"Proxy Authentication Required">>; 408 -> <<"Request Timeout">>; 410 -> <<"Gone">>; 412 -> <<"Conditional Request Failed">>; 413 -> <<"Request Entity Too Large">>; 414 -> <<"Request-URI Too Long">>; 415 -> <<"Unsupported Media Type">>; 416 -> <<"Unsupported URI Scheme">>; 417 -> <<"Unknown Resource Priority">>; 420 -> <<"Bad Extension">>; 421 -> <<"Extension Required">>; 422 -> <<"Session Interval Too Small">>; 423 -> <<"Interval Too Brief">>; 424 -> <<"Bad Location Information">>; 428 -> <<"Use Identity Header">>; 429 -> <<"Provide Referrer Identity">>; 430 -> <<"Flow Failed">>; 433 -> <<"Anonymity Disallowed">>; 436 -> <<"Bad Identity-Info">>; 437 -> <<"Unsupported Certificate">>; 438 -> <<"Invalid Identity Header">>; 439 -> <<"First Hop Lacks Outbound Support">>; 440 -> <<"Max-Breadth Exceeded">>; 469 -> <<"Bad Info Package">>; 470 -> <<"Consent Needed">>; 480 -> <<"Temporarily Unavailable">>; 481 -> <<"Call/Transaction Does Not Exist">>; 482 -> <<"Loop Detected">>; 483 -> <<"Too Many Hops">>; 484 -> <<"Address Incomplete">>; 485 -> <<"Ambiguous">>; 486 -> <<"Busy Here">>; 487 -> <<"Request Terminated">>; 488 -> <<"Not Acceptable Here">>; 489 -> <<"Bad Event">>; 491 -> <<"Request Pending">>; 493 -> <<"Undecipherable">>; 494 -> <<"Security Agreement Required">>; 500 -> <<"Server Internal Error">>; 501 -> <<"Not Implemented">>; 502 -> <<"Bad Gateway">>; 504 -> <<"Server Time-out">>; 505 -> <<"Version Not Supported">>; 513 -> <<"Message Too Large">>; 580 -> <<"Precondition Faillure">>; 600 -> <<"Busy Everywhere">>; 603 -> <<"Decline">>; 604 -> <<"Does Not Exist Anywhere">>; 606 -> <<"Not Acceptable">>; _ -> <<"Unknown Code">> end. gen_opts([{K , V}|Rest ] , Acc ) - > gen_opts(Rest , [ [ $ ; , nklib_util : ) , $ = , nklib_util : ) ] | Acc ] ) ; gen_opts([K|Rest ] , Acc ) - > gen_opts(Rest , [ [ $ ; , nklib_util : ) ] | Acc ] ) . gen_headers([{K , V}|Rest ] , Acc ) - > gen_headers(Rest , [ [ $ & , nklib_util : ) , $ = , nklib_util : ) ] | Acc ] ) ; gen_headers([K|Rest ] , Acc ) - > gen_headers(Rest , [ [ $ & , nklib_util : ) ] | Acc ] ) . @private q850_prase(Code) -> case Code of 0 -> <<"UNSPECIFIED">>; 1 -> <<"UNALLOCATED_NUMBER">>; 2 -> <<"NO_ROUTE_TRANSIT_NET">>; 3 -> <<"NO_ROUTE_DESTINATION">>; 6 -> <<"CHANNEL_UNACCEPTABLE">>; 7 -> <<"CALL_AWARDED_DELIVERED">>; 16 -> <<"NORMAL_CLEARING">>; 17 -> <<"USER_BUSY">>; 18 -> <<"NO_USER_RESPONSE">>; 19 -> <<"NO_ANSWER">>; 20 -> <<"SUBSCRIBER_ABSENT">>; 21 -> <<"CALL_REJECTED">>; 22 -> <<"NUMBER_CHANGED">>; 23 -> <<"REDIRECTION_TO_NEW_DESTINATION">>; 25 -> <<"EXCHANGE_ROUTING_ERROR">>; 27 -> <<"DESTINATION_OUT_OF_ORDER">>; 28 -> <<"INVALID_NUMBER_FORMAT">>; 29 -> <<"FACILITY_REJECTED">>; 30 -> <<"RESPONSE_TO_STATUS_ENQUIRY">>; 31 -> <<"NORMAL_UNSPECIFIED">>; 34 -> <<"NORMAL_CIRCUIT_CONGESTION">>; 38 -> <<"NETWORK_OUT_OF_ORDER">>; 41 -> <<"NORMAL_TEMPORARY_FAILURE">>; 42 -> <<"SWITCH_CONGESTION">>; 43 -> <<"ACCESS_INFO_DISCARDED">>; 44 -> <<"REQUESTED_CHAN_UNAVAIL">>; 45 -> <<"PRE_EMPTED">>; 47 -> <<"RESOURCE_UNAVAILABLE">>; 50 -> <<"FACILITY_NOT_SUBSCRIBED">>; 52 -> <<"OUTGOING_CALL_BARRED">>; 54 -> <<"INCOMING_CALL_BARRED">>; 57 -> <<"BEARERCAPABILITY_NOTAUTH">>; 58 -> <<"BEARERCAPABILITY_NOTAVAIL">>; 63 -> <<"SERVICE_UNAVAILABLE">>; 65 -> <<"BEARERCAPABILITY_NOTIMPL">>; 66 -> <<"CHAN_NOT_IMPLEMENTED">>; 69 -> <<"FACILITY_NOT_IMPLEMENTED">>; 79 -> <<"SERVICE_NOT_IMPLEMENTED">>; 81 -> <<"INVALID_CALL_REFERENCE">>; 88 -> <<"INCOMPATIBLE_DESTINATION">>; 95 -> <<"INVALID_MSG_UNSPECIFIED">>; 96 -> <<"MANDATORY_IE_MISSING">>; 97 -> <<"MESSAGE_TYPE_NONEXIST">>; 99 -> <<"IE_NONEXIST">>; 100 -> <<"INVALID_IE_CONTENTS">>; 101 -> <<"WRONG_CALL_STATE">>; 102 -> <<"RECOVERY_ON_TIMER_EXPIRE">>; 103 -> <<"MANDATORY_IE_LENGTH_ERROR">>; 111 -> <<"PROTOCOL_ERROR">>; 127 -> <<"INTERWORKING">>; 487 -> <<"ORIGINATOR_CANCEL">>; 500 -> <<"CRASH">>; 501 -> <<"SYSTEM_SHUTDOWN">>; 502 -> <<"LOSE_RACE">>; 503 -> <<"MANAGER_REQUEST">>; 600 -> <<"BLIND_TRANSFER">>; 601 -> <<"ATTENDED_TRANSFER">>; 602 -> <<"ALLOTTED_TIMEOUT">>; 603 -> <<"USER_CHALLENGE">>; 604 -> <<"MEDIA_TIMEOUT">>; 605 -> <<"PICKED_OFF">>; 606 -> <<"USER_NOT_REGISTERED">>; 607 -> <<"PROGRESS_TIMEOUT">>; 609 -> <<"GATEWAY_DOWN">>; _ -> <<"UNDEFINED">> end.
9e404fceb715dd57ec21e5bb9cdc48b65366b7b9828570ca6f9373ac560435de
dharmatech/abstracting
1.scm
(case scheme-implementation ((ypsilon) (: loader 'lib "srfi/1/ypsilon")) ((larceny) (: loader 'lib "srfi/1/larceny")) ((chicken) (: loader 'lib "srfi/1/chicken")))
null
https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/src/srfi/1/1.scm
scheme
(case scheme-implementation ((ypsilon) (: loader 'lib "srfi/1/ypsilon")) ((larceny) (: loader 'lib "srfi/1/larceny")) ((chicken) (: loader 'lib "srfi/1/chicken")))
fb56b9a37a159f81331448b104d6c5b76b9ec5274d994265a1bbe7d508af2005
webnf/webnf
promise.cljs
(ns webnf.promise (:require [webnf.channel :refer [serve-read-waiters]] [cljs.core.async.impl.dispatch :as dispatch] [cljs.core.async.impl.protocols :as async] [cljs.core.async :refer [<!]]) (:require-macros [cljs.core.async.macros :refer [go]])) (defn- wrap-error [e] (if (instance? js/Error e) e (js/Error e))) (defprotocol IPromise (-deliver [p val]) (-deliver-error [p e]) (-on-deliver [p value-cb] [p value-cb error-cb])) (deftype Promise [^:mutable value ^:mutable error ^:mutable waiters] Object (toString [_] (str "Promise:" (case value :webnf.promise/pending "Pending" :webnf.promise/error error (str "Delivered: " value)))) async/ReadPort (take! [p handler] (when (async/active? handler) (case value :webnf.promise/pending (do (set! waiters (cons handler waiters)) nil) :webnf.promise/error (do (async/commit handler) (volatile! error)) (do (async/commit handler) (volatile! value))))) IDeref (-deref [p] (case value :webnf.promise/pending (throw (ex-info "Can't deref a pending promise in cljs, sorry" {:webnf/promise p})) :webnf.promise/error (throw error) value)) IPromise (-deliver-error [p e] (when-not (= value :webnf.promise/pending) (throw (ex-info "Can't deliver on a promise more than once" {:webnf/promise p :new-value val}))) (set! value :webnf.promise/error) (set! error (wrap-error e)) (serve-read-waiters waiters error) (set! waiters nil) nil) (-deliver [p val] (when-not (= value :webnf.promise/pending) (throw (ex-info "Can't deliver on a promise more than once" {:webnf/promise p :new-value val}))) (set! value val) (serve-read-waiters waiters val) (set! waiters nil) nil)) (defn deliver "Deliver on a promise akin to clojure.core/deliver" [p val] (-deliver p val)) (defn deliver-error "Deliver an error to a promise" [p e] (-deliver-error p e)) (defn promise "Create a promise, which can be used much like a read channel, except that reads always return immediately, once the promise has been delivered on." ([] (Promise. :webnf.promise/pending nil nil)) ([source-ch] (let [p (promise)] (go (try (deliver p (<! source-ch)) (catch js/Error e (deliver-error p e)))) p)))
null
https://raw.githubusercontent.com/webnf/webnf/6a2ccaa755e6e40528eb13a5c36bae16ba4947e7/cljs/src/webnf/promise.cljs
clojure
(ns webnf.promise (:require [webnf.channel :refer [serve-read-waiters]] [cljs.core.async.impl.dispatch :as dispatch] [cljs.core.async.impl.protocols :as async] [cljs.core.async :refer [<!]]) (:require-macros [cljs.core.async.macros :refer [go]])) (defn- wrap-error [e] (if (instance? js/Error e) e (js/Error e))) (defprotocol IPromise (-deliver [p val]) (-deliver-error [p e]) (-on-deliver [p value-cb] [p value-cb error-cb])) (deftype Promise [^:mutable value ^:mutable error ^:mutable waiters] Object (toString [_] (str "Promise:" (case value :webnf.promise/pending "Pending" :webnf.promise/error error (str "Delivered: " value)))) async/ReadPort (take! [p handler] (when (async/active? handler) (case value :webnf.promise/pending (do (set! waiters (cons handler waiters)) nil) :webnf.promise/error (do (async/commit handler) (volatile! error)) (do (async/commit handler) (volatile! value))))) IDeref (-deref [p] (case value :webnf.promise/pending (throw (ex-info "Can't deref a pending promise in cljs, sorry" {:webnf/promise p})) :webnf.promise/error (throw error) value)) IPromise (-deliver-error [p e] (when-not (= value :webnf.promise/pending) (throw (ex-info "Can't deliver on a promise more than once" {:webnf/promise p :new-value val}))) (set! value :webnf.promise/error) (set! error (wrap-error e)) (serve-read-waiters waiters error) (set! waiters nil) nil) (-deliver [p val] (when-not (= value :webnf.promise/pending) (throw (ex-info "Can't deliver on a promise more than once" {:webnf/promise p :new-value val}))) (set! value val) (serve-read-waiters waiters val) (set! waiters nil) nil)) (defn deliver "Deliver on a promise akin to clojure.core/deliver" [p val] (-deliver p val)) (defn deliver-error "Deliver an error to a promise" [p e] (-deliver-error p e)) (defn promise "Create a promise, which can be used much like a read channel, except that reads always return immediately, once the promise has been delivered on." ([] (Promise. :webnf.promise/pending nil nil)) ([source-ch] (let [p (promise)] (go (try (deliver p (<! source-ch)) (catch js/Error e (deliver-error p e)))) p)))
d8709ce59f8087a583841bf9566f80083f71a65d05c064c28060cc56c7a05bdd
Andromedans/andromeda
eqchk.ml
(** Type-directed equality checking based on user-provided rules. *) open Eqchk_common (** Types and functions for manipulation of rules. *) (* An equality checker is given by beta rules and extensionality rules. We organize them as maps taking a symbol to a list of rules which have that symbol at the head. This allows us to quickly determine which rules are potentially applicable. *) type checker = { normalizer : Eqchk_normalizer.normalizer ; ext_rules : Eqchk_extensionality.equation list SymbolMap.t ; } let empty_checker = { normalizer = Eqchk_normalizer.empty_normalizer ; ext_rules = SymbolMap.empty } (** The [add_XYZ] functions add a new rule, computed from the given derivation, to the given checker, or raise [Invalid_rule] if not possible. *) let add_type_computation' checker drv = let sym, bt, normalizer = Eqchk_normalizer.add_type_computation checker.normalizer drv in sym, bt, {checker with normalizer} let add_type_computation checker drv = match add_type_computation' checker drv with | _, _, checker -> checker let add_term_computation' checker drv = let sym, bt, normalizer = Eqchk_normalizer.add_term_computation checker.normalizer drv in sym, bt, {checker with normalizer} let add_term_computation checker drv = match add_term_computation' checker drv with | (_, _, checker) -> checker let add_extensionality' checker drv = let sym, bt = Eqchk_extensionality.make_equation drv in let rls = match SymbolMap.find_opt sym checker.ext_rules with | None -> [bt] | Some rls -> rls @ [bt] in (sym, {checker with ext_rules = SymbolMap.add sym rls checker.ext_rules}) let add_extensionality checker drv = match add_extensionality' checker drv with | (_, checker) -> checker (** General equality checking functions *) (** An equality to be proved is given by a (possibly abstracted) equality boundary. The functions [prove_XYZ] receive such a boundary and attempt to prove the corresponding equality. *) let rec prove_eq_type_abstraction chk sgn abstr = let rec fold abstr = match Nucleus.invert_eq_type_boundary_abstraction abstr with | Nucleus.Stump_NotAbstract eq -> Nucleus.(abstract_not_abstract ((prove_eq_type chk sgn eq))) | Nucleus.Stump_Abstract (atm, abstr) -> let abstr = fold abstr in Nucleus.abstract_eq_type atm abstr in fold abstr and prove_eq_term_abstraction chk sgn abstr = let rec fold abstr = match Nucleus.invert_eq_term_boundary_abstraction abstr with | Nucleus.Stump_NotAbstract bdry -> Nucleus.(abstract_not_abstract ((prove_eq_term ~ext:true chk sgn bdry))) | Nucleus.Stump_Abstract (atm, abstr) -> let abstr = fold abstr in Nucleus.abstract_eq_term atm abstr in fold abstr and prove_eq_type chk sgn (ty1, ty2) = let ty1_eq_ty1', ty1' = Eqchk_normalizer.normalize_type ~strong:true sgn chk.normalizer ty1 and ty2_eq_ty2', ty2' = Eqchk_normalizer.normalize_type ~strong:true sgn chk.normalizer ty2 in let ty1'_eq_ty2' = check_normal_type chk sgn ty1' ty2' in Nucleus.transitivity_type (Nucleus.transitivity_type ty1_eq_ty1' ty1'_eq_ty2') (Nucleus.symmetry_type ty2_eq_ty2') and prove_eq_term ~ext chk sgn bdry = let normalization_phase bdry = let (e1, e2, t) = Nucleus.invert_eq_term_boundary bdry in let e1_eq_e1', Normal e1' = Eqchk_normalizer.normalize_term ~strong:true sgn chk.normalizer e1 and e2_eq_e2', Normal e2' = Eqchk_normalizer.normalize_term ~strong:true sgn chk.normalizer e2 in let e1'_eq_e2' = check_normal_term chk sgn (Normal e1') (Normal e2') in Nucleus.transitivity_term (Nucleus.transitivity_term e1_eq_e1' e1'_eq_e2') (Nucleus.symmetry_term e2_eq_e2') in if not ext then normalization_phase bdry else let (e1, e2, t) = Nucleus.invert_eq_term_boundary bdry in let t_eq_t', Normal t' = Eqchk_normalizer.normalize_type ~strong:false sgn chk.normalizer t in let e1' = Nucleus.(form_is_term_convert sgn e1 t_eq_t') and e2' = Nucleus.(form_is_term_convert sgn e2 t_eq_t')in let bdry' = Nucleus.(form_eq_term_boundary sgn e1' e2') in let bdry = match Nucleus.(as_eq_term_boundary bdry' ) with | Some bdry -> bdry | None -> assert false in let eq_jdg = match Eqchk_extensionality.find chk.ext_rules sgn bdry with | Some rap -> (* reduce the problem to an application of an extensionality rule *) resolve_rap chk sgn IntSet.empty rap | None -> normalization_phase bdry in let t'_eq_t = Nucleus.(symmetry_type t_eq_t') in Nucleus.(form_eq_term_convert eq_jdg t'_eq_t) and check_normal_type chk sgn (Normal ty1) (Normal ty2) = match Nucleus.congruence_is_type sgn ty1 ty2 with | None -> raise (EqchkError(Equality_fail (NoCongruenceTypes (ty1, ty2)) )) | Some rap -> let sym = head_symbol_type (Nucleus.expose_is_type ty1) in let hs = Eqchk_normalizer.get_type_heads chk.normalizer sym in resolve_rap chk sgn hs rap (* We assume that [e1] and [e2] have the same type. *) and check_normal_term chk sgn (Normal e1) (Normal e2) = match Nucleus.congruence_is_term sgn e1 e2 with | None -> raise (EqchkError (Equality_fail (NoCongruenceTerms (e1, e2)))) | Some rap -> let sym = head_symbol_term (Nucleus.expose_is_term e1) in let hs = Eqchk_normalizer.get_term_heads chk.normalizer sym in resolve_rap chk sgn hs rap (** Given a rule application, fill in the missing premises, as long as they are equations. *) and resolve_rap : 'a . checker -> Nucleus.signature -> IntSet.t -> 'a Nucleus.rule_application -> 'a = fun chk sgn heads rap -> let rec fold k = function | Nucleus.RapDone ty1_eq_ty2 -> ty1_eq_ty2 | Nucleus.RapMore (bdry, rap) -> let eq = prove_boundary_abstraction ~ext:(not (IntSet.mem k heads)) chk sgn bdry in fold (k+1) (rap eq) in fold 0 rap (* Prove an abstracted equality boundary. The [ext] flag tells us whether we should proceed wither with the type-directed phase or or the normalization-phase. *) and prove_boundary_abstraction ~ext chk sgn bdry = let rec prove bdry = match Nucleus.invert_boundary_abstraction bdry with | Nucleus.(Stump_NotAbstract (BoundaryEqType eq)) -> Nucleus.(abstract_not_abstract (JudgementEqType (prove_eq_type chk sgn eq))) | Nucleus.(Stump_NotAbstract (BoundaryEqTerm eq)) -> Nucleus.(abstract_not_abstract (JudgementEqTerm (prove_eq_term ~ext chk sgn eq))) | Nucleus.Stump_Abstract (atm, bdry) -> let eq_abstr = prove bdry in Nucleus.abstract_judgement atm eq_abstr | Nucleus.(Stump_NotAbstract (BoundaryIsTerm _ | BoundaryIsType _)) -> raise (Fatal_error ("cannot prove an object boundary")) in prove bdry (** The exported form of normalization for types *) let normalize_type ~strong chk sgn t = let eq, Normal t = Eqchk_normalizer.normalize_type ~strong sgn chk.normalizer t in eq, t (** The exported form of normalization for terms *) let normalize_term ~strong chk sgn e = let eq, Normal e = Eqchk_normalizer.normalize_term ~strong sgn chk.normalizer e in eq, e let set_type_heads ({normalizer; _} as chk) s hs = { chk with normalizer = Eqchk_normalizer.set_type_heads normalizer (Ident s) (IntSet.of_list hs) } let set_term_heads ({normalizer; _} as chk) s hs = { chk with normalizer = Eqchk_normalizer.set_term_heads normalizer (Ident s) (IntSet.of_list hs) } let add ~quiet ~penv chk drv = try match add_extensionality' chk drv with | (sym, chk) -> if not quiet then Format.printf "Extensionality rule for %t:@ %t@." (print_symbol ~penv sym) (Nucleus.print_derivation ~penv drv) ; chk with | EqchkError ( Invalid_rule _ ) -> try begin match add_type_computation' chk drv with | (sym, ((patt, _), _), chk) -> let heads = heads_type patt in let chk = { chk with normalizer = Eqchk_normalizer.set_type_heads chk.normalizer sym heads } in if not quiet then Format.printf "@[<hov 2>Type computation rule for %t (heads at [%t]):@\n%t@.@]" (print_symbol ~penv sym) (Print.sequence (fun k ppf -> Format.fprintf ppf "%d" k) "," (IntSet.elements heads)) (Nucleus.print_derivation ~penv drv) ; chk end with | EqchkError ( Invalid_rule _ ) -> begin match add_term_computation' chk drv with | (sym, ((patt, _), _), chk) -> let heads = heads_term patt in let chk = { chk with normalizer = Eqchk_normalizer.set_term_heads chk.normalizer sym heads } in if not quiet then Format.printf "@[<hov 2>Term computation rule for %t (heads at [%t]):@\n%t\n@.@]" (print_symbol ~penv sym) (Print.sequence (fun k ppf -> Format.fprintf ppf "%d" k) "," (IntSet.elements heads)) (Nucleus.print_derivation ~penv drv) ; chk end
null
https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/src/equality/eqchk.ml
ocaml
* Type-directed equality checking based on user-provided rules. * Types and functions for manipulation of rules. An equality checker is given by beta rules and extensionality rules. We organize them as maps taking a symbol to a list of rules which have that symbol at the head. This allows us to quickly determine which rules are potentially applicable. * The [add_XYZ] functions add a new rule, computed from the given derivation, to the given checker, or raise [Invalid_rule] if not possible. * General equality checking functions * An equality to be proved is given by a (possibly abstracted) equality boundary. The functions [prove_XYZ] receive such a boundary and attempt to prove the corresponding equality. reduce the problem to an application of an extensionality rule We assume that [e1] and [e2] have the same type. * Given a rule application, fill in the missing premises, as long as they are equations. Prove an abstracted equality boundary. The [ext] flag tells us whether we should proceed wither with the type-directed phase or or the normalization-phase. * The exported form of normalization for types * The exported form of normalization for terms
open Eqchk_common type checker = { normalizer : Eqchk_normalizer.normalizer ; ext_rules : Eqchk_extensionality.equation list SymbolMap.t ; } let empty_checker = { normalizer = Eqchk_normalizer.empty_normalizer ; ext_rules = SymbolMap.empty } let add_type_computation' checker drv = let sym, bt, normalizer = Eqchk_normalizer.add_type_computation checker.normalizer drv in sym, bt, {checker with normalizer} let add_type_computation checker drv = match add_type_computation' checker drv with | _, _, checker -> checker let add_term_computation' checker drv = let sym, bt, normalizer = Eqchk_normalizer.add_term_computation checker.normalizer drv in sym, bt, {checker with normalizer} let add_term_computation checker drv = match add_term_computation' checker drv with | (_, _, checker) -> checker let add_extensionality' checker drv = let sym, bt = Eqchk_extensionality.make_equation drv in let rls = match SymbolMap.find_opt sym checker.ext_rules with | None -> [bt] | Some rls -> rls @ [bt] in (sym, {checker with ext_rules = SymbolMap.add sym rls checker.ext_rules}) let add_extensionality checker drv = match add_extensionality' checker drv with | (_, checker) -> checker let rec prove_eq_type_abstraction chk sgn abstr = let rec fold abstr = match Nucleus.invert_eq_type_boundary_abstraction abstr with | Nucleus.Stump_NotAbstract eq -> Nucleus.(abstract_not_abstract ((prove_eq_type chk sgn eq))) | Nucleus.Stump_Abstract (atm, abstr) -> let abstr = fold abstr in Nucleus.abstract_eq_type atm abstr in fold abstr and prove_eq_term_abstraction chk sgn abstr = let rec fold abstr = match Nucleus.invert_eq_term_boundary_abstraction abstr with | Nucleus.Stump_NotAbstract bdry -> Nucleus.(abstract_not_abstract ((prove_eq_term ~ext:true chk sgn bdry))) | Nucleus.Stump_Abstract (atm, abstr) -> let abstr = fold abstr in Nucleus.abstract_eq_term atm abstr in fold abstr and prove_eq_type chk sgn (ty1, ty2) = let ty1_eq_ty1', ty1' = Eqchk_normalizer.normalize_type ~strong:true sgn chk.normalizer ty1 and ty2_eq_ty2', ty2' = Eqchk_normalizer.normalize_type ~strong:true sgn chk.normalizer ty2 in let ty1'_eq_ty2' = check_normal_type chk sgn ty1' ty2' in Nucleus.transitivity_type (Nucleus.transitivity_type ty1_eq_ty1' ty1'_eq_ty2') (Nucleus.symmetry_type ty2_eq_ty2') and prove_eq_term ~ext chk sgn bdry = let normalization_phase bdry = let (e1, e2, t) = Nucleus.invert_eq_term_boundary bdry in let e1_eq_e1', Normal e1' = Eqchk_normalizer.normalize_term ~strong:true sgn chk.normalizer e1 and e2_eq_e2', Normal e2' = Eqchk_normalizer.normalize_term ~strong:true sgn chk.normalizer e2 in let e1'_eq_e2' = check_normal_term chk sgn (Normal e1') (Normal e2') in Nucleus.transitivity_term (Nucleus.transitivity_term e1_eq_e1' e1'_eq_e2') (Nucleus.symmetry_term e2_eq_e2') in if not ext then normalization_phase bdry else let (e1, e2, t) = Nucleus.invert_eq_term_boundary bdry in let t_eq_t', Normal t' = Eqchk_normalizer.normalize_type ~strong:false sgn chk.normalizer t in let e1' = Nucleus.(form_is_term_convert sgn e1 t_eq_t') and e2' = Nucleus.(form_is_term_convert sgn e2 t_eq_t')in let bdry' = Nucleus.(form_eq_term_boundary sgn e1' e2') in let bdry = match Nucleus.(as_eq_term_boundary bdry' ) with | Some bdry -> bdry | None -> assert false in let eq_jdg = match Eqchk_extensionality.find chk.ext_rules sgn bdry with | Some rap -> resolve_rap chk sgn IntSet.empty rap | None -> normalization_phase bdry in let t'_eq_t = Nucleus.(symmetry_type t_eq_t') in Nucleus.(form_eq_term_convert eq_jdg t'_eq_t) and check_normal_type chk sgn (Normal ty1) (Normal ty2) = match Nucleus.congruence_is_type sgn ty1 ty2 with | None -> raise (EqchkError(Equality_fail (NoCongruenceTypes (ty1, ty2)) )) | Some rap -> let sym = head_symbol_type (Nucleus.expose_is_type ty1) in let hs = Eqchk_normalizer.get_type_heads chk.normalizer sym in resolve_rap chk sgn hs rap and check_normal_term chk sgn (Normal e1) (Normal e2) = match Nucleus.congruence_is_term sgn e1 e2 with | None -> raise (EqchkError (Equality_fail (NoCongruenceTerms (e1, e2)))) | Some rap -> let sym = head_symbol_term (Nucleus.expose_is_term e1) in let hs = Eqchk_normalizer.get_term_heads chk.normalizer sym in resolve_rap chk sgn hs rap and resolve_rap : 'a . checker -> Nucleus.signature -> IntSet.t -> 'a Nucleus.rule_application -> 'a = fun chk sgn heads rap -> let rec fold k = function | Nucleus.RapDone ty1_eq_ty2 -> ty1_eq_ty2 | Nucleus.RapMore (bdry, rap) -> let eq = prove_boundary_abstraction ~ext:(not (IntSet.mem k heads)) chk sgn bdry in fold (k+1) (rap eq) in fold 0 rap and prove_boundary_abstraction ~ext chk sgn bdry = let rec prove bdry = match Nucleus.invert_boundary_abstraction bdry with | Nucleus.(Stump_NotAbstract (BoundaryEqType eq)) -> Nucleus.(abstract_not_abstract (JudgementEqType (prove_eq_type chk sgn eq))) | Nucleus.(Stump_NotAbstract (BoundaryEqTerm eq)) -> Nucleus.(abstract_not_abstract (JudgementEqTerm (prove_eq_term ~ext chk sgn eq))) | Nucleus.Stump_Abstract (atm, bdry) -> let eq_abstr = prove bdry in Nucleus.abstract_judgement atm eq_abstr | Nucleus.(Stump_NotAbstract (BoundaryIsTerm _ | BoundaryIsType _)) -> raise (Fatal_error ("cannot prove an object boundary")) in prove bdry let normalize_type ~strong chk sgn t = let eq, Normal t = Eqchk_normalizer.normalize_type ~strong sgn chk.normalizer t in eq, t let normalize_term ~strong chk sgn e = let eq, Normal e = Eqchk_normalizer.normalize_term ~strong sgn chk.normalizer e in eq, e let set_type_heads ({normalizer; _} as chk) s hs = { chk with normalizer = Eqchk_normalizer.set_type_heads normalizer (Ident s) (IntSet.of_list hs) } let set_term_heads ({normalizer; _} as chk) s hs = { chk with normalizer = Eqchk_normalizer.set_term_heads normalizer (Ident s) (IntSet.of_list hs) } let add ~quiet ~penv chk drv = try match add_extensionality' chk drv with | (sym, chk) -> if not quiet then Format.printf "Extensionality rule for %t:@ %t@." (print_symbol ~penv sym) (Nucleus.print_derivation ~penv drv) ; chk with | EqchkError ( Invalid_rule _ ) -> try begin match add_type_computation' chk drv with | (sym, ((patt, _), _), chk) -> let heads = heads_type patt in let chk = { chk with normalizer = Eqchk_normalizer.set_type_heads chk.normalizer sym heads } in if not quiet then Format.printf "@[<hov 2>Type computation rule for %t (heads at [%t]):@\n%t@.@]" (print_symbol ~penv sym) (Print.sequence (fun k ppf -> Format.fprintf ppf "%d" k) "," (IntSet.elements heads)) (Nucleus.print_derivation ~penv drv) ; chk end with | EqchkError ( Invalid_rule _ ) -> begin match add_term_computation' chk drv with | (sym, ((patt, _), _), chk) -> let heads = heads_term patt in let chk = { chk with normalizer = Eqchk_normalizer.set_term_heads chk.normalizer sym heads } in if not quiet then Format.printf "@[<hov 2>Term computation rule for %t (heads at [%t]):@\n%t\n@.@]" (print_symbol ~penv sym) (Print.sequence (fun k ppf -> Format.fprintf ppf "%d" k) "," (IntSet.elements heads)) (Nucleus.print_derivation ~penv drv) ; chk end
253093d5f82181d0c1c1120a227accbc6d1e4c456da8d8a418ed324d22ca7a81
icicle-lang/icicle-ambiata
Statement.hs
-- | Turn Core primitives into Flat - removing the folds -- The input statements must be in A-normal form. # LANGUAGE NoImplicitPrelude # # LANGUAGE PatternGuards # module Icicle.Avalanche.Statement.Flatten.Statement ( flatten ) where import Icicle.Avalanche.Statement.Flatten.Base import Icicle.Avalanche.Statement.Flatten.Exp import Icicle.Avalanche.Statement.Statement import qualified Icicle.Avalanche.Statement.Simp.Freshen as Freshen import qualified Icicle.Common.Fresh as Fresh import qualified Icicle.Core.Exp.Prim as Core import Icicle.Internal.Pretty hiding (flatten) import P import qualified Data.List as List import Data.Hashable (Hashable) import Data.String (IsString) flatten :: (Pretty n, Hashable n, Eq n, IsString n, Show n, Show a) => a -> Statement a n Core.Prim -> FlatM a n flatten a_fresh s = do s' <- flattenS a_fresh s s'' <- Fresh.runFreshIdentity $ Freshen.freshen a_fresh s' return s'' -- | Flatten the primitives in a statement. -- This just calls @flatX@ for every expression, wrapping the statement. flattenS :: (Pretty n, Hashable n, Eq n, IsString n, Show n, Show a) => a -> Statement a n Core.Prim -> FlatM a n flattenS a_fresh s = case s of If x ts es -> flatX a_fresh x $ \x' -> If x' <$> flattenS a_fresh ts <*> flattenS a_fresh es Let n x ss -> flatX a_fresh x $ \x' -> Let n x' <$> flattenS a_fresh ss While t n nt to ss -> flatX a_fresh to $ \to' -> While t n nt to' <$> flattenS a_fresh ss ForeachInts t n from to ss -> flatX a_fresh from $ \from' -> flatX a_fresh to $ \to' -> ForeachInts t n from' to' <$> flattenS a_fresh ss ForeachFacts binds vt ss Input binds can not contain Buffers , so no need to flatten the types -> ForeachFacts binds vt <$> flattenS a_fresh ss Block ss -> Block <$> mapM (flattenS a_fresh) ss InitAccumulator acc ss -> flatX a_fresh (accInit acc) $ \x' -> InitAccumulator acc { accInit = x' } <$> flattenS a_fresh ss Read n m vt ss -> Read n m vt <$> flattenS a_fresh ss Write n x -> flatX a_fresh x (return . Write n) Output n t xts | (xs,ts) <- List.unzip xts -> flatXS a_fresh xs [] $ \xs' -> return $ Output n t (List.zip xs' ts)
null
https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-compiler/src/Icicle/Avalanche/Statement/Flatten/Statement.hs
haskell
| Turn Core primitives into Flat - removing the folds The input statements must be in A-normal form. | Flatten the primitives in a statement. This just calls @flatX@ for every expression, wrapping the statement.
# LANGUAGE NoImplicitPrelude # # LANGUAGE PatternGuards # module Icicle.Avalanche.Statement.Flatten.Statement ( flatten ) where import Icicle.Avalanche.Statement.Flatten.Base import Icicle.Avalanche.Statement.Flatten.Exp import Icicle.Avalanche.Statement.Statement import qualified Icicle.Avalanche.Statement.Simp.Freshen as Freshen import qualified Icicle.Common.Fresh as Fresh import qualified Icicle.Core.Exp.Prim as Core import Icicle.Internal.Pretty hiding (flatten) import P import qualified Data.List as List import Data.Hashable (Hashable) import Data.String (IsString) flatten :: (Pretty n, Hashable n, Eq n, IsString n, Show n, Show a) => a -> Statement a n Core.Prim -> FlatM a n flatten a_fresh s = do s' <- flattenS a_fresh s s'' <- Fresh.runFreshIdentity $ Freshen.freshen a_fresh s' return s'' flattenS :: (Pretty n, Hashable n, Eq n, IsString n, Show n, Show a) => a -> Statement a n Core.Prim -> FlatM a n flattenS a_fresh s = case s of If x ts es -> flatX a_fresh x $ \x' -> If x' <$> flattenS a_fresh ts <*> flattenS a_fresh es Let n x ss -> flatX a_fresh x $ \x' -> Let n x' <$> flattenS a_fresh ss While t n nt to ss -> flatX a_fresh to $ \to' -> While t n nt to' <$> flattenS a_fresh ss ForeachInts t n from to ss -> flatX a_fresh from $ \from' -> flatX a_fresh to $ \to' -> ForeachInts t n from' to' <$> flattenS a_fresh ss ForeachFacts binds vt ss Input binds can not contain Buffers , so no need to flatten the types -> ForeachFacts binds vt <$> flattenS a_fresh ss Block ss -> Block <$> mapM (flattenS a_fresh) ss InitAccumulator acc ss -> flatX a_fresh (accInit acc) $ \x' -> InitAccumulator acc { accInit = x' } <$> flattenS a_fresh ss Read n m vt ss -> Read n m vt <$> flattenS a_fresh ss Write n x -> flatX a_fresh x (return . Write n) Output n t xts | (xs,ts) <- List.unzip xts -> flatXS a_fresh xs [] $ \xs' -> return $ Output n t (List.zip xs' ts)
a5360c406491c2b0f807a1f7c46de5253caf58a202d944f56a0c084436655096
ucsd-progsys/dsolve
mymapfoo.ml
let m0 = Mymap.make 1 0 let m1 = Mymap.sett m0 2 3 let m2 = Mymap.sett m1 3 3 let _ = assert ( Mymap.gett m2 3 = 3 ) let _ = assert ( Mymap.gett m2 2 = 3 ) let _ = assert ( Mymap.gett m2 1 = 0 ) let _ = assert (Mymap.gett m2 3 = 3) let _ = assert (Mymap.gett m2 2 = 3) let _ = assert (Mymap.gett m2 1 = 0)*)
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/tests/POPL2008/mymapfoo.ml
ocaml
let m0 = Mymap.make 1 0 let m1 = Mymap.sett m0 2 3 let m2 = Mymap.sett m1 3 3 let _ = assert ( Mymap.gett m2 3 = 3 ) let _ = assert ( Mymap.gett m2 2 = 3 ) let _ = assert ( Mymap.gett m2 1 = 0 ) let _ = assert (Mymap.gett m2 3 = 3) let _ = assert (Mymap.gett m2 2 = 3) let _ = assert (Mymap.gett m2 1 = 0)*)
6597fbe50100444630c582d4f0c5dbc3e2a7446749a15abc14de5136ac2fa339
synduce/Synduce
mts.ml
* @synduce -s 2 -NB type 'a clist = | CNil | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Nil | Cons of 'a * 'a list let rec mts = function | Nil -> 0, 0 | Cons (hd, tl) -> let amts, asum = mts tl in let new_sum = asum + hd in max amts new_sum, new_sum ;; let rec clist_to_list = function | CNil -> Nil | Single a -> Cons (a, Nil) | Concat (x, y) -> dec y x and dec l1 = function | CNil -> clist_to_list l1 | Single a -> Cons (a, clist_to_list l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec hom = function | CNil -> [%synt s0] | Single a -> [%synt f0] | Concat (x, y) -> [%synt join] ;; assert (hom = clist_to_list @@ mts)
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/list/mts.ml
ocaml
* @synduce -s 2 -NB type 'a clist = | CNil | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Nil | Cons of 'a * 'a list let rec mts = function | Nil -> 0, 0 | Cons (hd, tl) -> let amts, asum = mts tl in let new_sum = asum + hd in max amts new_sum, new_sum ;; let rec clist_to_list = function | CNil -> Nil | Single a -> Cons (a, Nil) | Concat (x, y) -> dec y x and dec l1 = function | CNil -> clist_to_list l1 | Single a -> Cons (a, clist_to_list l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec hom = function | CNil -> [%synt s0] | Single a -> [%synt f0] | Concat (x, y) -> [%synt join] ;; assert (hom = clist_to_list @@ mts)