_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
3eb41c0662663455b8ae249484e653f250757026f9e1967ae91989244a1fb26b
xebia/VisualReview
analysis.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Copyright 2015 Xebia B.V. ; Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; -2.0 ; ; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.analysis (:require [com.xebia.visualreview.util :refer :all] [com.xebia.visualreview.service.persistence.util :as putil] [com.xebia.visualreview.service.service-util :as sutil])) ;; Analysis (defn create-analysis! "Returns the generated analysis id" [conn baseline-node run-id] (putil/insert-single! conn :analysis {:baseline-node baseline-node :run-id run-id})) (defn get-analysis [conn run-id] (putil/query-single conn ["SELECT analysis.*, project.id project_id, project.name project_name, suite.id suite_id, suite.name suite_name FROM analysis JOIN run ON run.id = analysis.run_id JOIN suite ON suite.id = run.suite_id JOIN project ON project.id = suite.project_id WHERE run_id = ?" run-id] :row-fn sutil/format-dates)) (defn get-full-analysis [conn run-id] (let [analysis (get-analysis conn run-id) diffs (putil/query conn ["SELECT diff.*, sbefore.size before_size, sbefore.meta before_meta, sbefore.properties before_properties, sbefore.screenshot_name before_name, sbefore.image_id before_image_id, safter.size after_size, safter.meta after_meta, safter.properties after_properties, safter.screenshot_name after_name, safter.image_id after_image_id FROM analysis JOIN diff ON diff.analysis_id = analysis.id JOIN screenshot safter ON safter.id = diff.after LEFT JOIN screenshot sbefore ON sbefore.id = diff.before WHERE analysis.run_id = ?" run-id] :row-fn (comp (putil/parse-json-fields :before-meta :before-properties :after-meta :after-properties) sutil/format-dates) :result-set-fn vec)] {:analysis analysis :diffs diffs})) ;; Diffs (defn save-diff! "Stores a new diff. Returns the new diff's id." [conn image-id mask-image-id before after percentage analysis-id] (putil/insert-single! conn :diff {:before before :after after :percentage percentage :status "pending" :analysis-id analysis-id :image-id image-id :mask-image-id mask-image-id})) (defn get-diff [conn run-id diff-id] (putil/query-single conn ["SELECT diff.* FROM diff JOIN analysis ON analysis.id = diff.analysis_id JOIN run ON run.id = analysis.run_id WHERE run.id = ? AND diff.id = ?" run-id diff-id])) (defn update-diff-status! [conn diff-id status] (putil/update! conn :diff {:status status} ["id = ?" diff-id])) (defn get-analysis-compound-status "Returns 'accepted' when all screenshots in the analysis have the status 'accepted'. Returns 'rejected' when one of the screenshots in the analysis has the status 'rejected' Returns 'pending' when none of the screenshots in the analysis has the status 'rejected' and at least one has 'pending'" [conn run-id] (let [diffs (:diffs (get-full-analysis conn run-id)) nr-of-rejected (count (filter (fn [diff] (= (:status diff) "rejected")) diffs)) nr-of-pending (count (filter (fn [diff] (= (:status diff) "pending")) diffs))] (if (< (count diffs) 1) "empty" (if (> nr-of-rejected 0) "rejected" (if (> nr-of-pending 0) "pending" "accepted" )))))
null
https://raw.githubusercontent.com/xebia/VisualReview/c74c18ff73cbf11ece23203cb7a7768e626a03e2/src/main/clojure/com/xebia/visualreview/service/analysis.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Analysis Diffs
Copyright 2015 Xebia B.V. Licensed under the Apache License , Version 2.0 ( the " License " ) distributed under the License is distributed on an " AS IS " BASIS , (ns com.xebia.visualreview.service.analysis (:require [com.xebia.visualreview.util :refer :all] [com.xebia.visualreview.service.persistence.util :as putil] [com.xebia.visualreview.service.service-util :as sutil])) (defn create-analysis! "Returns the generated analysis id" [conn baseline-node run-id] (putil/insert-single! conn :analysis {:baseline-node baseline-node :run-id run-id})) (defn get-analysis [conn run-id] (putil/query-single conn ["SELECT analysis.*, project.id project_id, project.name project_name, suite.id suite_id, suite.name suite_name FROM analysis JOIN run ON run.id = analysis.run_id JOIN suite ON suite.id = run.suite_id JOIN project ON project.id = suite.project_id WHERE run_id = ?" run-id] :row-fn sutil/format-dates)) (defn get-full-analysis [conn run-id] (let [analysis (get-analysis conn run-id) diffs (putil/query conn ["SELECT diff.*, sbefore.size before_size, sbefore.meta before_meta, sbefore.properties before_properties, sbefore.screenshot_name before_name, sbefore.image_id before_image_id, safter.size after_size, safter.meta after_meta, safter.properties after_properties, safter.screenshot_name after_name, safter.image_id after_image_id FROM analysis JOIN diff ON diff.analysis_id = analysis.id JOIN screenshot safter ON safter.id = diff.after LEFT JOIN screenshot sbefore ON sbefore.id = diff.before WHERE analysis.run_id = ?" run-id] :row-fn (comp (putil/parse-json-fields :before-meta :before-properties :after-meta :after-properties) sutil/format-dates) :result-set-fn vec)] {:analysis analysis :diffs diffs})) (defn save-diff! "Stores a new diff. Returns the new diff's id." [conn image-id mask-image-id before after percentage analysis-id] (putil/insert-single! conn :diff {:before before :after after :percentage percentage :status "pending" :analysis-id analysis-id :image-id image-id :mask-image-id mask-image-id})) (defn get-diff [conn run-id diff-id] (putil/query-single conn ["SELECT diff.* FROM diff JOIN analysis ON analysis.id = diff.analysis_id JOIN run ON run.id = analysis.run_id WHERE run.id = ? AND diff.id = ?" run-id diff-id])) (defn update-diff-status! [conn diff-id status] (putil/update! conn :diff {:status status} ["id = ?" diff-id])) (defn get-analysis-compound-status "Returns 'accepted' when all screenshots in the analysis have the status 'accepted'. Returns 'rejected' when one of the screenshots in the analysis has the status 'rejected' Returns 'pending' when none of the screenshots in the analysis has the status 'rejected' and at least one has 'pending'" [conn run-id] (let [diffs (:diffs (get-full-analysis conn run-id)) nr-of-rejected (count (filter (fn [diff] (= (:status diff) "rejected")) diffs)) nr-of-pending (count (filter (fn [diff] (= (:status diff) "pending")) diffs))] (if (< (count diffs) 1) "empty" (if (> nr-of-rejected 0) "rejected" (if (> nr-of-pending 0) "pending" "accepted" )))))
9ffa48ce49b70558f02ec32b40e9cd3b8dd1484b960e4c6c42367a93ef2c9c55
alanzplus/EOPL
a8.rkt
#lang racket (provide ack-reg-driver) (provide depth-reg-driver) (provide fact-reg-driver) (provide pascal-reg-driver) (provide fib) (provide fib-ramp-driver) (provide bi-tramp-driver) (define ack-reg-driver (letrec ([m* 'uninit] [n* 'uninit] [k* 'uninit] [v* 'uninit] [empty-k (lambda () '(empty-k))] [ack-k (lambda (m k) `(ack-k ,m ,k))] [ack (lambda () (cond [(zero? m*) (begin (set! v* (add1 n*)) (apply-k))] [(zero? n*) (begin (set! m* (sub1 m*)) (set! n* 1) (ack))] [else (begin (set! k* (ack-k m* k*)) (set! n* (sub1 n*)) (ack))]))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(ack-k ,m ,k) (begin (set! m* (sub1 m)) (set! n* v*) (set! k* k) (ack))]))]) (lambda (m n) (begin (set! m* m) (set! n* n) (set! k* (empty-k)) (ack))))) (define depth-reg-driver (letrec ([ls* 'uninit] [k* 'uninit] [v* 'unint] [empty-k (lambda () '(empty-k))] [big-k (lambda (ls k) `(big-k ,ls ,k))] [small-k (lambda (l k) `(small-k ,l ,k))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(big-k ,ls ,k) (begin (set! ls* (cdr ls)) (set! k* (small-k v* k)) (depth))] [`(small-k ,l ,k) (let ([l (add1 l)]) (if (< l v*) (begin (set! k* k) (apply-k)) (begin (set! k* k) (set! v* l) (apply-k))))]))] [depth (lambda () (cond [(null? ls*) (begin (set! v* 1) (apply-k))] [(pair? (car ls*)) (begin (set! k* (big-k ls* k*)) (set! ls* (car ls*)) (depth))] [else (begin (set! ls* (cdr ls*)) (depth))]))]) (lambda (ls) (begin (set! ls* ls) (set! k* (empty-k)) (depth))))) (define fact-reg-driver (letrec ([n* 'uninit] [k* 'uninit] [v* 'uninit] [empty-k (lambda () '(empty-k))] [cont (lambda (k n) `(cont ,k ,n))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(cont ,saved-k ,n) (begin (set! k* saved-k) (set! v* (* n v*)) (apply-k))]))] [fact (lambda () (cond [(zero? n*) (begin (set! v* 1) (apply-k))] [else (begin (set! k* (cont k* n*)) (set! n* (sub1 n*)) (fact))]))]) (lambda (n) (begin (set! n* n) (set! k* (empty-k)) (fact))))) (define pascal-reg-driver (letrec ([n* 'uninit] [k* 'uninit] [v* 'uninit] [m* 'uninit] [a* 'uninit] [empty-k (lambda () '(empty-k))] [init-k (lambda (saved-k) `(init-k ,saved-k))] [big-k (lambda (a m saved-k) `(big-k ,a ,m ,saved-k))] [small-k (lambda (a saved-k) `(small-k ,a ,saved-k))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(init-k ,saved-k) (begin (set! m* 1) (set! a* 0) (set! k* saved-k) (v*))] [`(big-k ,a ,m ,saved-k) (begin (set! m* (add1 m)) (set! a* a) (set! k* (small-k a saved-k)) (v*))] [`(small-k ,a ,saved-k) (begin (set! k* saved-k) (set! v* (cons a v*)) (apply-k))]))] [f (lambda () (cond [(> m* n*) (begin (set! v* '()) (apply-k))] [else (let ([a (+ a* m*)]) (begin (set! k* (big-k a m* k*)) (apply-k)))]))]) (lambda (n) (begin (set! n* n) (set! k* (init-k (empty-k))) (set! v* f) (apply-k))))) (define fib (letrec ([pc* 'unint] [n* 'uninit] [k* 'uninit] [v* 'uninit] [trampoline (lambda () (pc*) (trampoline))] [empty-k (lambda (exit-k) `(empty-k ,exit-k))] [big-k (lambda (n saved-k) `(big-k ,n ,saved-k))] [small-k (lambda (v saved-k) `(small-k ,v ,saved-k))] [apply-k (lambda () (match k* [`(big-k ,n ,saved-k) (begin (set! n* (sub1 n)) (set! k* (small-k v* saved-k)) (set! pc* f))] [`(small-k ,v1 ,saved-k) (begin (set! k* saved-k) (set! v* (+ v1 v*)) (set! pc* apply-k))] [`(empty-k ,exit-k) (exit-k v*)]))] [f (lambda () (cond [(and (not (negative? n*)) (< n* 2)) (begin (set! v* n*) (set! pc* apply-k))] [else (begin (set! k* (big-k (sub1 n*) k*)) (set! n* (sub1 n*)) (set! pc* f))]))]) (lambda (n) (call/cc (lambda (exit-cont) (begin (set! n* n) (set! k* (empty-k exit-cont)) (set! pc* f) (trampoline))))))) (define fib-trampoline (lambda (n k) (lambda () (cond [(and (not (negative? n)) (< n 2)) (k n)] [else (fib-trampoline (sub1 n) (lambda (v1) (fib-trampoline (sub1 (sub1 n)) (lambda (v2) (k (+ v1 v2))))))])))) (define fib-ramp-driver (letrec ([rampoline (lambda (th1 th2 th3) (let ([thunks (shuffle (list th1 th2 th3))]) (rampoline ((car thunks)) ((cadr thunks)) ((caddr thunks)))))] [ramp-empty-k (lambda (k) (lambda (v) (k v)))]) (lambda (n1 n2 n3) (let/cc jumpout (rampoline (lambda () (fib-trampoline n1 (ramp-empty-k jumpout))) (lambda () (fib-trampoline n2 (ramp-empty-k jumpout))) (lambda () (fib-trampoline n3 (ramp-empty-k jumpout)))))))) (define trib (lambda (n k) (lambda () (cond [(< n 3) (k 1)] [else (trib (- n 3) (lambda (v1) (trib (- n 2) (lambda (v2) (trib (- n 1) (lambda (v3) (k (+ v1 v2 v3))))))))])))) (define bi-tramp-driver (letrec ([trampline (lambda (th1 th2) (let ([nth1 (th1)] [nth2 (th2)]) (cond [(and (number? nth1) (number? nth2)) (list nth1 nth2)] [(number? nth1) (trampline (lambda () nth1) nth2)] [(number? nth2) (trampline (lambda () nth2) nth1)] [else (trampline nth1 nth2)])))] [empty-k (lambda (v) v)]) (lambda (n1 n2) (trampline (lambda () (trib n1 empty-k)) (lambda () (trib n2 empty-k))))))
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/Indiana-CS311/a8-Registerization/a8.rkt
racket
#lang racket (provide ack-reg-driver) (provide depth-reg-driver) (provide fact-reg-driver) (provide pascal-reg-driver) (provide fib) (provide fib-ramp-driver) (provide bi-tramp-driver) (define ack-reg-driver (letrec ([m* 'uninit] [n* 'uninit] [k* 'uninit] [v* 'uninit] [empty-k (lambda () '(empty-k))] [ack-k (lambda (m k) `(ack-k ,m ,k))] [ack (lambda () (cond [(zero? m*) (begin (set! v* (add1 n*)) (apply-k))] [(zero? n*) (begin (set! m* (sub1 m*)) (set! n* 1) (ack))] [else (begin (set! k* (ack-k m* k*)) (set! n* (sub1 n*)) (ack))]))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(ack-k ,m ,k) (begin (set! m* (sub1 m)) (set! n* v*) (set! k* k) (ack))]))]) (lambda (m n) (begin (set! m* m) (set! n* n) (set! k* (empty-k)) (ack))))) (define depth-reg-driver (letrec ([ls* 'uninit] [k* 'uninit] [v* 'unint] [empty-k (lambda () '(empty-k))] [big-k (lambda (ls k) `(big-k ,ls ,k))] [small-k (lambda (l k) `(small-k ,l ,k))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(big-k ,ls ,k) (begin (set! ls* (cdr ls)) (set! k* (small-k v* k)) (depth))] [`(small-k ,l ,k) (let ([l (add1 l)]) (if (< l v*) (begin (set! k* k) (apply-k)) (begin (set! k* k) (set! v* l) (apply-k))))]))] [depth (lambda () (cond [(null? ls*) (begin (set! v* 1) (apply-k))] [(pair? (car ls*)) (begin (set! k* (big-k ls* k*)) (set! ls* (car ls*)) (depth))] [else (begin (set! ls* (cdr ls*)) (depth))]))]) (lambda (ls) (begin (set! ls* ls) (set! k* (empty-k)) (depth))))) (define fact-reg-driver (letrec ([n* 'uninit] [k* 'uninit] [v* 'uninit] [empty-k (lambda () '(empty-k))] [cont (lambda (k n) `(cont ,k ,n))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(cont ,saved-k ,n) (begin (set! k* saved-k) (set! v* (* n v*)) (apply-k))]))] [fact (lambda () (cond [(zero? n*) (begin (set! v* 1) (apply-k))] [else (begin (set! k* (cont k* n*)) (set! n* (sub1 n*)) (fact))]))]) (lambda (n) (begin (set! n* n) (set! k* (empty-k)) (fact))))) (define pascal-reg-driver (letrec ([n* 'uninit] [k* 'uninit] [v* 'uninit] [m* 'uninit] [a* 'uninit] [empty-k (lambda () '(empty-k))] [init-k (lambda (saved-k) `(init-k ,saved-k))] [big-k (lambda (a m saved-k) `(big-k ,a ,m ,saved-k))] [small-k (lambda (a saved-k) `(small-k ,a ,saved-k))] [apply-k (lambda () (match k* ['(empty-k) v*] [`(init-k ,saved-k) (begin (set! m* 1) (set! a* 0) (set! k* saved-k) (v*))] [`(big-k ,a ,m ,saved-k) (begin (set! m* (add1 m)) (set! a* a) (set! k* (small-k a saved-k)) (v*))] [`(small-k ,a ,saved-k) (begin (set! k* saved-k) (set! v* (cons a v*)) (apply-k))]))] [f (lambda () (cond [(> m* n*) (begin (set! v* '()) (apply-k))] [else (let ([a (+ a* m*)]) (begin (set! k* (big-k a m* k*)) (apply-k)))]))]) (lambda (n) (begin (set! n* n) (set! k* (init-k (empty-k))) (set! v* f) (apply-k))))) (define fib (letrec ([pc* 'unint] [n* 'uninit] [k* 'uninit] [v* 'uninit] [trampoline (lambda () (pc*) (trampoline))] [empty-k (lambda (exit-k) `(empty-k ,exit-k))] [big-k (lambda (n saved-k) `(big-k ,n ,saved-k))] [small-k (lambda (v saved-k) `(small-k ,v ,saved-k))] [apply-k (lambda () (match k* [`(big-k ,n ,saved-k) (begin (set! n* (sub1 n)) (set! k* (small-k v* saved-k)) (set! pc* f))] [`(small-k ,v1 ,saved-k) (begin (set! k* saved-k) (set! v* (+ v1 v*)) (set! pc* apply-k))] [`(empty-k ,exit-k) (exit-k v*)]))] [f (lambda () (cond [(and (not (negative? n*)) (< n* 2)) (begin (set! v* n*) (set! pc* apply-k))] [else (begin (set! k* (big-k (sub1 n*) k*)) (set! n* (sub1 n*)) (set! pc* f))]))]) (lambda (n) (call/cc (lambda (exit-cont) (begin (set! n* n) (set! k* (empty-k exit-cont)) (set! pc* f) (trampoline))))))) (define fib-trampoline (lambda (n k) (lambda () (cond [(and (not (negative? n)) (< n 2)) (k n)] [else (fib-trampoline (sub1 n) (lambda (v1) (fib-trampoline (sub1 (sub1 n)) (lambda (v2) (k (+ v1 v2))))))])))) (define fib-ramp-driver (letrec ([rampoline (lambda (th1 th2 th3) (let ([thunks (shuffle (list th1 th2 th3))]) (rampoline ((car thunks)) ((cadr thunks)) ((caddr thunks)))))] [ramp-empty-k (lambda (k) (lambda (v) (k v)))]) (lambda (n1 n2 n3) (let/cc jumpout (rampoline (lambda () (fib-trampoline n1 (ramp-empty-k jumpout))) (lambda () (fib-trampoline n2 (ramp-empty-k jumpout))) (lambda () (fib-trampoline n3 (ramp-empty-k jumpout)))))))) (define trib (lambda (n k) (lambda () (cond [(< n 3) (k 1)] [else (trib (- n 3) (lambda (v1) (trib (- n 2) (lambda (v2) (trib (- n 1) (lambda (v3) (k (+ v1 v2 v3))))))))])))) (define bi-tramp-driver (letrec ([trampline (lambda (th1 th2) (let ([nth1 (th1)] [nth2 (th2)]) (cond [(and (number? nth1) (number? nth2)) (list nth1 nth2)] [(number? nth1) (trampline (lambda () nth1) nth2)] [(number? nth2) (trampline (lambda () nth2) nth1)] [else (trampline nth1 nth2)])))] [empty-k (lambda (v) v)]) (lambda (n1 n2) (trampline (lambda () (trib n1 empty-k)) (lambda () (trib n2 empty-k))))))
828809eafa313bd1cccdd9d21e7adf85dd50b56dee6bfa029d4f0f421e5952de
Decentralized-Pictures/T4L3NT
long_test.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) type alert_config = { default_slack_webhook_url : Uri.t; team_slack_webhook_urls : Uri.t String_map.t; max_total : int; max_by_test : int; gitlab_project_url : Uri.t option; timeout : float; } type config = { alerts : alert_config option; influxdb : InfluxDB.config option; grafana : Grafana.config option; } let default default = Option.value ~default let as_alert_config json = let slack_webhook_urls = JSON.(json |-> "slack_webhook_urls") in let team_slack_webhook_urls = JSON.as_object slack_webhook_urls |> List.filter_map (fun (name, url) -> if name = "default" then None else Some (name, JSON.(url |> as_string |> Uri.of_string))) |> List.fold_left (fun acc (k, v) -> String_map.add k v acc) String_map.empty in { default_slack_webhook_url = JSON.(slack_webhook_urls |-> "default" |> as_string |> Uri.of_string); team_slack_webhook_urls; max_total = JSON.(json |-> "max_total" |> as_int_opt |> default 100); max_by_test = JSON.(json |-> "max_by_test" |> as_int_opt |> default 2); gitlab_project_url = JSON.( json |-> "gitlab_project_url" |> as_string_opt |> Option.map Uri.of_string); timeout = JSON.(json |-> "timeout" |> as_float_opt |> Option.value ~default:20.); } let read_config_file filename = let json = JSON.parse_file filename in { alerts = JSON.(json |-> "alerts" |> as_opt |> Option.map as_alert_config); influxdb = JSON.(json |-> "influxdb" |> as_opt |> Option.map InfluxDB.config_of_json); grafana = JSON.(json |-> "grafana" |> as_opt |> Option.map Grafana.config_of_json); } let config = match match Sys.getenv_opt "TEZT_CONFIG" with | Some "" | None -> ( if Sys.file_exists "tezt_config.json" then Some "tezt_config.json" else match Sys.getenv_opt "HOME" with | Some home -> let filename = home // ".tezt_config.json" in if Sys.file_exists filename then Some filename else None | None -> None) | Some _ as x -> x with | None -> Log.warn "No configuration file found, using default configuration." ; {alerts = None; influxdb = None; grafana = None} | Some filename -> ( Log.info "Using configuration file: %s" filename ; try read_config_file filename with JSON.Error error -> Log.error "Failed to read configuration file: %s" (JSON.show_error error) ; exit 1) let () = if config.alerts = None then Log.warn "Alerts are not configured and will thus not be sent." ; if config.influxdb = None then Log.warn "InfluxDB is not configured: data points will not be sent and previous \ data points will not be read. Also, Grafana dashboards will not be \ updated." ; if config.grafana = None then Log.warn "Grafana is not configured: Grafana dashboards will not be updated." type timeout = Seconds of int | Minutes of int | Hours of int | Days of int let with_timeout timeout promise () = let timeout = match timeout with | Seconds x -> x | Minutes x -> x * 60 | Hours x -> x * 60 * 60 | Days x -> x * 60 * 60 * 24 in Lwt.pick [ promise; (let* () = Lwt_unix.sleep (float timeout) in Test.fail "test did not finish before its timeout"); ] (* [data_points] is a map from measurement to lists. The order of those lists is unspecified. *) type current_test = { title : string; filename : string; team : string option; mutable data_points : InfluxDB.data_point list String_map.t; mutable alert_count : int; } (* Using a global variable will make it hard to refactor to run multiple tests concurrently if we want to. But, running multiple tests would affect time measurements so it is not advisable anyway. *) let current_test = ref None let total_alert_count = ref 0 let http ~timeout method_ ?headers ?body url = let http_call = let headers = Option.map Cohttp.Header.of_list headers in let body = Option.map (fun s -> `String s) body in Cohttp_lwt_unix.Client.call ?headers ?body method_ url in let timeout = let* () = Lwt_unix.sleep timeout in failwith "timeout" in Lwt.pick [http_call; timeout] let http_post_json url body = http `POST ~headers:[("Content-Type", "application/json")] ~body:(JSON.encode_u body) url let with_buffer size f = let buffer = Buffer.create size in f buffer ; Buffer.contents buffer module Slack = struct let encode_entities buffer s = for i = 0 to String.length s - 1 do match s.[i] with | '&' -> Buffer.add_string buffer "&amp;" | '<' -> Buffer.add_string buffer "&lt;" | '>' -> Buffer.add_string buffer ">gt;" | c -> Buffer.add_char buffer c done type message_item = | Text of string | Newline | Link of {url : Uri.t; text : string} type message = message_item list let encode_message_item buffer = function | Text s -> encode_entities buffer s | Newline -> Buffer.add_char buffer '\n' | Link {url; text} -> Buffer.add_char buffer '<' ; Buffer.add_string buffer (Uri.to_string url) ; Buffer.add_char buffer '|' ; encode_entities buffer text ; Buffer.add_char buffer '>' let send_message ~timeout webhook_url message = let message = with_buffer 256 @@ fun buffer -> List.iter (encode_message_item buffer) message in let body = `O [("text", `String message)] in let send () = let* (response, body) = http_post_json ~timeout webhook_url body in match response.status with | #Cohttp.Code.success_status -> Cohttp_lwt.Body.drain_body body | status -> let* body = Cohttp_lwt.Body.to_string body in Log.debug "Response body from Slack: %s" body ; Log.warn "Failed to send message: Slack responded with %s" (Cohttp.Code.string_of_status status) ; unit in Lwt.catch send @@ fun exn -> Log.warn "Failed to send message to Slack: %s" (Printexc.to_string exn) ; unit end let alert_s ~log message = if log then Log.error "Alert: %s" message ; match config.alerts with | None -> () | Some alert_cfg -> let may_send = !total_alert_count < alert_cfg.max_total && match !current_test with | None -> true | Some {alert_count; _} -> alert_count < alert_cfg.max_by_test in if may_send then let slack_webhook_url = match !current_test with | Some {team = Some team; _} -> ( match String_map.find_opt team alert_cfg.team_slack_webhook_urls with | None -> Log.warn "No Slack webhook configured for team %S, will use the \ default." team ; alert_cfg.default_slack_webhook_url | Some url -> url) | _ -> alert_cfg.default_slack_webhook_url in let message : Slack.message = match !current_test with | None -> [Text "Alert: "; Text message] | Some {title; filename; _} -> ( let text = let message = (* If [message] is multi-line, put "Alert from test" on its own line. *) if String.contains message '\n' then "\n" ^ message else message in Slack.Text (sf "Alert from test %S: %s" title message) in match alert_cfg.gitlab_project_url with | None -> [text] | Some gitlab_project_url -> let new_issue_url = let issue_title = sf "Fix test: %s" title in let issue_description = sf "Test: %s\nFile: %s\nAlert: %s" title filename message in let url = let path = Uri.path gitlab_project_url in Uri.with_path gitlab_project_url (path ^ "/-/issues/new") in Uri.add_query_params' url [ ("issue[title]", issue_title); ("issue[description]", issue_description); ] in [ text; Newline; Link {url = new_issue_url; text = "create issue"}; ]) in (* Using [Background.register] is not just about returning type [unit] instead of a promise, it also prevents the timeout of the test from canceling the alert. *) Background.register @@ Slack.send_message ~timeout:alert_cfg.timeout slack_webhook_url message let alert x = Printf.ksprintf (alert_s ~log:true) x let alert_exn exn x = Printf.ksprintf (fun s -> Log.error "Alert: %s: %s" s (Printexc.to_string exn) ; alert_s ~log:false s) x let add_data_point data_point = match !current_test with | None -> invalid_arg "Long_test.add_data_point: not running a test registered with Long_test" | Some test -> (* Title has already been checked for newline characters in [register]. *) let data_point = InfluxDB.add_tag "test" test.title data_point in Log.debug "Data point: %s" (InfluxDB.show_data_point data_point) ; let previous_data_points = String_map.find_opt data_point.measurement test.data_points |> Option.value ~default:[] in test.data_points <- String_map.add data_point.measurement (data_point :: previous_data_points) test.data_points let send_data_points () = match (!current_test, config.influxdb) with | (None, _) | (_, None) -> unit | (Some test, Some config) -> let write () = let data_points = test.data_points |> String_map.bindings |> List.map snd |> List.flatten in test.data_points <- String_map.empty ; match data_points with | [] -> unit | _ -> let* () = InfluxDB.write config data_points in Log.debug "Successfully sent %d data points." (List.length data_points) ; unit in Lwt.catch write (fun exn -> alert_exn exn "failed to send data points to InfluxDB" ; unit) let unsafe_query select extract_data = match config.influxdb with | None -> Log.debug "InfluxDB is not configured, will not perform query: %s" (InfluxDB.show_select select) ; none | Some config -> let query () = let* result = InfluxDB.query config select in some (extract_data result) in Lwt.catch query (fun exn -> Log.debug "Query: %s" (InfluxDB.show_select select) ; alert_exn exn "failed to perform InfluxDB query" ; none) let log_unsafe_query select = let* result = unsafe_query select Fun.id in Option.iter (fun result -> Log.debug "Query: %s" (InfluxDB.show_select select) ; match result with | [] -> Log.debug "No results for this query." | _ -> Log.debug "%s" (InfluxDB.show_query_result result)) result ; unit let query select extract_data = match !current_test with | None -> invalid_arg "Long_test.query: not running a test registered with Long_test" | Some {title; _} -> let rec add_clause (select : InfluxDB.select) = match select.from with | Select sub_select -> {select with from = Select (add_clause sub_select)} | Measurement _ -> ( let where_test : InfluxDB.where = Tag ("test", EQ, title) in match select.where with | None -> {select with where = Some where_test} | Some where -> {select with where = Some (And (where, where_test))} ) in unsafe_query (add_clause select) extract_data module Stats = struct type _ t = | Int : InfluxDB.func -> int t | Float : InfluxDB.func -> float t | Pair : 'a t * 'b t -> ('a * 'b) t | Convert : 'a t * ('b -> 'a) * ('a -> 'b) -> 'b t let count = Int COUNT let mean = Float MEAN let median = Float MEDIAN let stddev = Float STDDEV let _2 a b = Pair (a, b) let _3 a b c = Convert ( Pair (a, Pair (b, c)), (fun (a, b, c) -> (a, (b, c))), fun (a, (b, c)) -> (a, b, c) ) let rec functions : 'a. 'a t -> _ = fun (type a) (stats : a t) -> match stats with | Int func | Float func -> [func] | Pair (a, b) -> functions a @ functions b | Convert (stats, _, _) -> functions stats let rec get : 'a. _ -> 'a t -> 'a = fun (type a) result_data_point (stats : a t) -> let result : a = match stats with | Int func -> InfluxDB.get (InfluxDB.column_name_of_func func) JSON.as_int result_data_point | Float func -> InfluxDB.get (InfluxDB.column_name_of_func func) JSON.as_float result_data_point | Pair (a, b) -> (get result_data_point a, get result_data_point b) | Convert (stats, _, decode) -> decode (get result_data_point stats) in result let show stats values = let rec gather : 'a. 'a t -> 'a -> _ = fun (type a) (stats : a t) (values : a) -> match stats with | Int func -> [(InfluxDB.column_name_of_func func, string_of_int values)] | Float func -> [(InfluxDB.column_name_of_func func, string_of_float values)] | Pair (a, b) -> let (v, w) = values in gather a v @ gather b w | Convert (stats, encode, _) -> gather stats (encode values) in gather stats values |> List.map (fun (name, value) -> sf "%s = %s" name value) |> String.concat ", " end let get_previous_stats ?limit ?(minimum_count = 3) ?(tags = []) measurement field stats = Option.iter (fun limit -> if limit < minimum_count then invalid_arg @@ sf "Long_test.get_previous_stats: limit = %d must be at least equal \ to minimum_count = %d" limit minimum_count) limit ; let stats = Stats.(_2 count) stats in let select = let where = match tags with | [] -> None | head :: tail -> let where_tag (tag, value) = InfluxDB.Tag (tag, EQ, value) in let where = List.fold_left (fun acc tag -> InfluxDB.And (acc, where_tag tag)) (where_tag head) tail in Some where in InfluxDB.( select (List.map (fun func -> Function (func, Field field)) (Stats.functions stats)) ~from: (Select (select [Field field] ?where ~from:(Measurement measurement) ~order_by:Time_desc ?limit)) ~order_by:Time_desc) in let* result = query select @@ fun result -> match result with | [] -> None | _ :: _ :: _ -> failwith "InfluxDB result contains multiple series" | [[]] -> failwith "InfluxDB result contains no values" | [(_ :: _ :: _)] -> failwith "InfluxDB result contains multiple values" | [[value]] -> let ((count, _) as stats) = Stats.get value stats in if count < minimum_count then None else Some stats in return (Option.join result) let has_tags (tags : (InfluxDB.tag * string) list) (data_point : InfluxDB.data_point) = let has_tag (tag, expected_value) = match List.assoc_opt tag data_point.tags with | None -> false | Some value -> String.equal value expected_value in List.for_all has_tag tags let get_pending_data_points ?(tags = []) measurement = match !current_test with | None -> invalid_arg "Long_test.get_pending_data_points: not running a test registered with \ Long_test" | Some test -> test.data_points |> String_map.find_opt measurement |> Option.value ~default:[] |> List.filter (has_tags tags) type check = Mean | Median let check_regression ?(previous_count = 10) ?(minimum_previous_count = 3) ?(margin = 0.2) ?(check = Mean) ?(stddev = false) ?data_points ?(tags = []) measurement field = if !current_test = None then invalid_arg "Long_test.check_regression: not running a test registered with Long_test" ; let current_values = let data_points = match data_points with | Some list -> List.filter (has_tags tags) list | None -> get_pending_data_points ~tags measurement in let get_field (data_point : InfluxDB.data_point) = match List.assoc_opt field (data_point.first_field :: data_point.other_fields) with | None | Some (String _) -> None | Some (Float f) -> Some f in List.filter_map get_field data_points in match current_values with | [] -> unit | _ :: _ -> ( let current_value = match check with | Mean -> Statistics.mean current_values | Median -> Statistics.median current_values in let get_previous stats handle_values = let* values = get_previous_stats ~limit:previous_count ~minimum_count:minimum_previous_count ~tags measurement field stats in match values with | None -> Log.debug "Not enough previous data points." ; unit | Some values -> Log.debug "Previous data points: %s" (Stats.show Stats.(_2 count stats) values) ; handle_values values ; unit in let get_previous_with_stddev stats handle_values = if stddev then get_previous Stats.(_2 stats stddev) @@ fun (count, (values, _)) -> handle_values (count, values) else get_previous stats handle_values in let get_previous_and_check name stats = get_previous_with_stddev stats @@ fun (previous_count, previous_value) -> if current_value > previous_value *. (1. +. margin) then let tags = match tags with | [] -> "" | _ -> "[" ^ (List.map (fun (k, v) -> sf "%S = %S" k v) tags |> String.concat ", ") ^ "]" in alert "New measurement: %s(%S%s.%S) = %g\n\ Previous %d measurements: %s = %g\n\ Difference: +%d%% (alert threshold: %d%%)" name measurement tags field current_value previous_count name previous_value (int_of_float ((current_value *. 100. /. previous_value) -. 100.)) (int_of_float (margin *. 100.)) in match check with | Mean -> get_previous_and_check "mean" Stats.mean | Median -> get_previous_and_check "median" Stats.median) let check_time_preconditions measurement = if !current_test = None then invalid_arg "Long_test.time: not running a test registered with Long_test" ; if String.contains measurement '\n' then invalid_arg "Long_test.time: newline character in measurement" let time ?previous_count ?minimum_previous_count ?margin ?check ?stddev ?(repeat = 1) measurement f = check_time_preconditions measurement ; if repeat <= 0 then unit else let data_points = ref [] in for _ = 1 to repeat do let start = Unix.gettimeofday () in f () ; let duration = Unix.gettimeofday () -. start in let data_point = InfluxDB.data_point measurement ("duration", Float duration) in add_data_point data_point ; data_points := data_point :: !data_points done ; check_regression ?previous_count ?minimum_previous_count ?margin ?check ?stddev ~data_points:!data_points measurement "duration" let time_lwt ?previous_count ?minimum_previous_count ?margin ?check ?stddev ?(repeat = 1) measurement f = check_time_preconditions measurement ; if repeat <= 0 then unit else let data_points = ref [] in let* () = Base.repeat repeat @@ fun () -> let start = Unix.gettimeofday () in let* () = f () in let duration = Unix.gettimeofday () -. start in let data_point = InfluxDB.data_point measurement ("duration", Float duration) in add_data_point data_point ; data_points := data_point :: !data_points ; unit in check_regression ?previous_count ?minimum_previous_count ?margin ?check ?stddev ~data_points:!data_points measurement "duration" (* Executors are just test tags. But the type is abstract so that users of this module cannot use an inexistent executor by mistake. And inside this module we use a type constructor to avoid mistakes too. *) type executor = Executor of string [@@unboxed] let x86_executor1 = Executor "x86_executor1" let x86_executor2 = Executor "x86_executor2" let make_tags team executors tags = let misc_tags = match team with | None -> "long" :: tags | Some team -> "long" :: team :: tags in let executor_tags = List.map (fun (Executor x) -> x) executors in executor_tags @ misc_tags (* Warning: [argument] must not be applied at registration. *) let wrap_body title filename team timeout body argument = let test = {title; filename; team; data_points = String_map.empty; alert_count = 0} in current_test := Some test ; Lwt.finalize (fun () -> Lwt.catch (fun () -> Lwt.finalize (with_timeout timeout (body argument)) send_data_points) (fun exn -> alert_s ~log:false (Printexc.to_string exn) ; raise exn)) (fun () -> current_test := None ; unit) let register ~__FILE__ ~title ~tags ?team ~executors ~timeout body = if String.contains title '\n' then invalid_arg "Long_test.register: long test titles cannot contain newline characters" ; let tags = make_tags team executors tags in Test.register ~__FILE__ ~title ~tags (wrap_body title __FILE__ team timeout body) let register_with_protocol ~__FILE__ ~title ~tags ?team ~executors ~timeout body = if String.contains title '\n' then invalid_arg "Long_test.register_with_protocol: long test titles cannot contain \ newline characters" ; let tags = make_tags team executors tags in Protocol.register_test ~__FILE__ ~title ~tags (wrap_body title __FILE__ team timeout body) let update_grafana_dashboard (dashboard : Grafana.dashboard) = Lwt_main.run @@ match config with | {influxdb = Some influxdb_config; grafana = Some grafana_config; _} -> let dashboard = (* Prefix measurements in queries with the InfluxDB measurement prefix. *) let update_panel = function | Grafana.Row _ as x -> x | Graph graph -> Graph { graph with queries = List.map (InfluxDB.prefix_measurement influxdb_config) graph.queries; } in {dashboard with panels = List.map update_panel dashboard.panels} in Grafana.update_dashboard grafana_config dashboard | _ -> unit
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/tezt/long_tests/long_test.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** [data_points] is a map from measurement to lists. The order of those lists is unspecified. Using a global variable will make it hard to refactor to run multiple tests concurrently if we want to. But, running multiple tests would affect time measurements so it is not advisable anyway. If [message] is multi-line, put "Alert from test" on its own line. Using [Background.register] is not just about returning type [unit] instead of a promise, it also prevents the timeout of the test from canceling the alert. Title has already been checked for newline characters in [register]. Executors are just test tags. But the type is abstract so that users of this module cannot use an inexistent executor by mistake. And inside this module we use a type constructor to avoid mistakes too. Warning: [argument] must not be applied at registration. Prefix measurements in queries with the InfluxDB measurement prefix.
Copyright ( c ) 2021 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING type alert_config = { default_slack_webhook_url : Uri.t; team_slack_webhook_urls : Uri.t String_map.t; max_total : int; max_by_test : int; gitlab_project_url : Uri.t option; timeout : float; } type config = { alerts : alert_config option; influxdb : InfluxDB.config option; grafana : Grafana.config option; } let default default = Option.value ~default let as_alert_config json = let slack_webhook_urls = JSON.(json |-> "slack_webhook_urls") in let team_slack_webhook_urls = JSON.as_object slack_webhook_urls |> List.filter_map (fun (name, url) -> if name = "default" then None else Some (name, JSON.(url |> as_string |> Uri.of_string))) |> List.fold_left (fun acc (k, v) -> String_map.add k v acc) String_map.empty in { default_slack_webhook_url = JSON.(slack_webhook_urls |-> "default" |> as_string |> Uri.of_string); team_slack_webhook_urls; max_total = JSON.(json |-> "max_total" |> as_int_opt |> default 100); max_by_test = JSON.(json |-> "max_by_test" |> as_int_opt |> default 2); gitlab_project_url = JSON.( json |-> "gitlab_project_url" |> as_string_opt |> Option.map Uri.of_string); timeout = JSON.(json |-> "timeout" |> as_float_opt |> Option.value ~default:20.); } let read_config_file filename = let json = JSON.parse_file filename in { alerts = JSON.(json |-> "alerts" |> as_opt |> Option.map as_alert_config); influxdb = JSON.(json |-> "influxdb" |> as_opt |> Option.map InfluxDB.config_of_json); grafana = JSON.(json |-> "grafana" |> as_opt |> Option.map Grafana.config_of_json); } let config = match match Sys.getenv_opt "TEZT_CONFIG" with | Some "" | None -> ( if Sys.file_exists "tezt_config.json" then Some "tezt_config.json" else match Sys.getenv_opt "HOME" with | Some home -> let filename = home // ".tezt_config.json" in if Sys.file_exists filename then Some filename else None | None -> None) | Some _ as x -> x with | None -> Log.warn "No configuration file found, using default configuration." ; {alerts = None; influxdb = None; grafana = None} | Some filename -> ( Log.info "Using configuration file: %s" filename ; try read_config_file filename with JSON.Error error -> Log.error "Failed to read configuration file: %s" (JSON.show_error error) ; exit 1) let () = if config.alerts = None then Log.warn "Alerts are not configured and will thus not be sent." ; if config.influxdb = None then Log.warn "InfluxDB is not configured: data points will not be sent and previous \ data points will not be read. Also, Grafana dashboards will not be \ updated." ; if config.grafana = None then Log.warn "Grafana is not configured: Grafana dashboards will not be updated." type timeout = Seconds of int | Minutes of int | Hours of int | Days of int let with_timeout timeout promise () = let timeout = match timeout with | Seconds x -> x | Minutes x -> x * 60 | Hours x -> x * 60 * 60 | Days x -> x * 60 * 60 * 24 in Lwt.pick [ promise; (let* () = Lwt_unix.sleep (float timeout) in Test.fail "test did not finish before its timeout"); ] type current_test = { title : string; filename : string; team : string option; mutable data_points : InfluxDB.data_point list String_map.t; mutable alert_count : int; } let current_test = ref None let total_alert_count = ref 0 let http ~timeout method_ ?headers ?body url = let http_call = let headers = Option.map Cohttp.Header.of_list headers in let body = Option.map (fun s -> `String s) body in Cohttp_lwt_unix.Client.call ?headers ?body method_ url in let timeout = let* () = Lwt_unix.sleep timeout in failwith "timeout" in Lwt.pick [http_call; timeout] let http_post_json url body = http `POST ~headers:[("Content-Type", "application/json")] ~body:(JSON.encode_u body) url let with_buffer size f = let buffer = Buffer.create size in f buffer ; Buffer.contents buffer module Slack = struct let encode_entities buffer s = for i = 0 to String.length s - 1 do match s.[i] with | '&' -> Buffer.add_string buffer "&amp;" | '<' -> Buffer.add_string buffer "&lt;" | '>' -> Buffer.add_string buffer ">gt;" | c -> Buffer.add_char buffer c done type message_item = | Text of string | Newline | Link of {url : Uri.t; text : string} type message = message_item list let encode_message_item buffer = function | Text s -> encode_entities buffer s | Newline -> Buffer.add_char buffer '\n' | Link {url; text} -> Buffer.add_char buffer '<' ; Buffer.add_string buffer (Uri.to_string url) ; Buffer.add_char buffer '|' ; encode_entities buffer text ; Buffer.add_char buffer '>' let send_message ~timeout webhook_url message = let message = with_buffer 256 @@ fun buffer -> List.iter (encode_message_item buffer) message in let body = `O [("text", `String message)] in let send () = let* (response, body) = http_post_json ~timeout webhook_url body in match response.status with | #Cohttp.Code.success_status -> Cohttp_lwt.Body.drain_body body | status -> let* body = Cohttp_lwt.Body.to_string body in Log.debug "Response body from Slack: %s" body ; Log.warn "Failed to send message: Slack responded with %s" (Cohttp.Code.string_of_status status) ; unit in Lwt.catch send @@ fun exn -> Log.warn "Failed to send message to Slack: %s" (Printexc.to_string exn) ; unit end let alert_s ~log message = if log then Log.error "Alert: %s" message ; match config.alerts with | None -> () | Some alert_cfg -> let may_send = !total_alert_count < alert_cfg.max_total && match !current_test with | None -> true | Some {alert_count; _} -> alert_count < alert_cfg.max_by_test in if may_send then let slack_webhook_url = match !current_test with | Some {team = Some team; _} -> ( match String_map.find_opt team alert_cfg.team_slack_webhook_urls with | None -> Log.warn "No Slack webhook configured for team %S, will use the \ default." team ; alert_cfg.default_slack_webhook_url | Some url -> url) | _ -> alert_cfg.default_slack_webhook_url in let message : Slack.message = match !current_test with | None -> [Text "Alert: "; Text message] | Some {title; filename; _} -> ( let text = let message = if String.contains message '\n' then "\n" ^ message else message in Slack.Text (sf "Alert from test %S: %s" title message) in match alert_cfg.gitlab_project_url with | None -> [text] | Some gitlab_project_url -> let new_issue_url = let issue_title = sf "Fix test: %s" title in let issue_description = sf "Test: %s\nFile: %s\nAlert: %s" title filename message in let url = let path = Uri.path gitlab_project_url in Uri.with_path gitlab_project_url (path ^ "/-/issues/new") in Uri.add_query_params' url [ ("issue[title]", issue_title); ("issue[description]", issue_description); ] in [ text; Newline; Link {url = new_issue_url; text = "create issue"}; ]) in Background.register @@ Slack.send_message ~timeout:alert_cfg.timeout slack_webhook_url message let alert x = Printf.ksprintf (alert_s ~log:true) x let alert_exn exn x = Printf.ksprintf (fun s -> Log.error "Alert: %s: %s" s (Printexc.to_string exn) ; alert_s ~log:false s) x let add_data_point data_point = match !current_test with | None -> invalid_arg "Long_test.add_data_point: not running a test registered with Long_test" | Some test -> let data_point = InfluxDB.add_tag "test" test.title data_point in Log.debug "Data point: %s" (InfluxDB.show_data_point data_point) ; let previous_data_points = String_map.find_opt data_point.measurement test.data_points |> Option.value ~default:[] in test.data_points <- String_map.add data_point.measurement (data_point :: previous_data_points) test.data_points let send_data_points () = match (!current_test, config.influxdb) with | (None, _) | (_, None) -> unit | (Some test, Some config) -> let write () = let data_points = test.data_points |> String_map.bindings |> List.map snd |> List.flatten in test.data_points <- String_map.empty ; match data_points with | [] -> unit | _ -> let* () = InfluxDB.write config data_points in Log.debug "Successfully sent %d data points." (List.length data_points) ; unit in Lwt.catch write (fun exn -> alert_exn exn "failed to send data points to InfluxDB" ; unit) let unsafe_query select extract_data = match config.influxdb with | None -> Log.debug "InfluxDB is not configured, will not perform query: %s" (InfluxDB.show_select select) ; none | Some config -> let query () = let* result = InfluxDB.query config select in some (extract_data result) in Lwt.catch query (fun exn -> Log.debug "Query: %s" (InfluxDB.show_select select) ; alert_exn exn "failed to perform InfluxDB query" ; none) let log_unsafe_query select = let* result = unsafe_query select Fun.id in Option.iter (fun result -> Log.debug "Query: %s" (InfluxDB.show_select select) ; match result with | [] -> Log.debug "No results for this query." | _ -> Log.debug "%s" (InfluxDB.show_query_result result)) result ; unit let query select extract_data = match !current_test with | None -> invalid_arg "Long_test.query: not running a test registered with Long_test" | Some {title; _} -> let rec add_clause (select : InfluxDB.select) = match select.from with | Select sub_select -> {select with from = Select (add_clause sub_select)} | Measurement _ -> ( let where_test : InfluxDB.where = Tag ("test", EQ, title) in match select.where with | None -> {select with where = Some where_test} | Some where -> {select with where = Some (And (where, where_test))} ) in unsafe_query (add_clause select) extract_data module Stats = struct type _ t = | Int : InfluxDB.func -> int t | Float : InfluxDB.func -> float t | Pair : 'a t * 'b t -> ('a * 'b) t | Convert : 'a t * ('b -> 'a) * ('a -> 'b) -> 'b t let count = Int COUNT let mean = Float MEAN let median = Float MEDIAN let stddev = Float STDDEV let _2 a b = Pair (a, b) let _3 a b c = Convert ( Pair (a, Pair (b, c)), (fun (a, b, c) -> (a, (b, c))), fun (a, (b, c)) -> (a, b, c) ) let rec functions : 'a. 'a t -> _ = fun (type a) (stats : a t) -> match stats with | Int func | Float func -> [func] | Pair (a, b) -> functions a @ functions b | Convert (stats, _, _) -> functions stats let rec get : 'a. _ -> 'a t -> 'a = fun (type a) result_data_point (stats : a t) -> let result : a = match stats with | Int func -> InfluxDB.get (InfluxDB.column_name_of_func func) JSON.as_int result_data_point | Float func -> InfluxDB.get (InfluxDB.column_name_of_func func) JSON.as_float result_data_point | Pair (a, b) -> (get result_data_point a, get result_data_point b) | Convert (stats, _, decode) -> decode (get result_data_point stats) in result let show stats values = let rec gather : 'a. 'a t -> 'a -> _ = fun (type a) (stats : a t) (values : a) -> match stats with | Int func -> [(InfluxDB.column_name_of_func func, string_of_int values)] | Float func -> [(InfluxDB.column_name_of_func func, string_of_float values)] | Pair (a, b) -> let (v, w) = values in gather a v @ gather b w | Convert (stats, encode, _) -> gather stats (encode values) in gather stats values |> List.map (fun (name, value) -> sf "%s = %s" name value) |> String.concat ", " end let get_previous_stats ?limit ?(minimum_count = 3) ?(tags = []) measurement field stats = Option.iter (fun limit -> if limit < minimum_count then invalid_arg @@ sf "Long_test.get_previous_stats: limit = %d must be at least equal \ to minimum_count = %d" limit minimum_count) limit ; let stats = Stats.(_2 count) stats in let select = let where = match tags with | [] -> None | head :: tail -> let where_tag (tag, value) = InfluxDB.Tag (tag, EQ, value) in let where = List.fold_left (fun acc tag -> InfluxDB.And (acc, where_tag tag)) (where_tag head) tail in Some where in InfluxDB.( select (List.map (fun func -> Function (func, Field field)) (Stats.functions stats)) ~from: (Select (select [Field field] ?where ~from:(Measurement measurement) ~order_by:Time_desc ?limit)) ~order_by:Time_desc) in let* result = query select @@ fun result -> match result with | [] -> None | _ :: _ :: _ -> failwith "InfluxDB result contains multiple series" | [[]] -> failwith "InfluxDB result contains no values" | [(_ :: _ :: _)] -> failwith "InfluxDB result contains multiple values" | [[value]] -> let ((count, _) as stats) = Stats.get value stats in if count < minimum_count then None else Some stats in return (Option.join result) let has_tags (tags : (InfluxDB.tag * string) list) (data_point : InfluxDB.data_point) = let has_tag (tag, expected_value) = match List.assoc_opt tag data_point.tags with | None -> false | Some value -> String.equal value expected_value in List.for_all has_tag tags let get_pending_data_points ?(tags = []) measurement = match !current_test with | None -> invalid_arg "Long_test.get_pending_data_points: not running a test registered with \ Long_test" | Some test -> test.data_points |> String_map.find_opt measurement |> Option.value ~default:[] |> List.filter (has_tags tags) type check = Mean | Median let check_regression ?(previous_count = 10) ?(minimum_previous_count = 3) ?(margin = 0.2) ?(check = Mean) ?(stddev = false) ?data_points ?(tags = []) measurement field = if !current_test = None then invalid_arg "Long_test.check_regression: not running a test registered with Long_test" ; let current_values = let data_points = match data_points with | Some list -> List.filter (has_tags tags) list | None -> get_pending_data_points ~tags measurement in let get_field (data_point : InfluxDB.data_point) = match List.assoc_opt field (data_point.first_field :: data_point.other_fields) with | None | Some (String _) -> None | Some (Float f) -> Some f in List.filter_map get_field data_points in match current_values with | [] -> unit | _ :: _ -> ( let current_value = match check with | Mean -> Statistics.mean current_values | Median -> Statistics.median current_values in let get_previous stats handle_values = let* values = get_previous_stats ~limit:previous_count ~minimum_count:minimum_previous_count ~tags measurement field stats in match values with | None -> Log.debug "Not enough previous data points." ; unit | Some values -> Log.debug "Previous data points: %s" (Stats.show Stats.(_2 count stats) values) ; handle_values values ; unit in let get_previous_with_stddev stats handle_values = if stddev then get_previous Stats.(_2 stats stddev) @@ fun (count, (values, _)) -> handle_values (count, values) else get_previous stats handle_values in let get_previous_and_check name stats = get_previous_with_stddev stats @@ fun (previous_count, previous_value) -> if current_value > previous_value *. (1. +. margin) then let tags = match tags with | [] -> "" | _ -> "[" ^ (List.map (fun (k, v) -> sf "%S = %S" k v) tags |> String.concat ", ") ^ "]" in alert "New measurement: %s(%S%s.%S) = %g\n\ Previous %d measurements: %s = %g\n\ Difference: +%d%% (alert threshold: %d%%)" name measurement tags field current_value previous_count name previous_value (int_of_float ((current_value *. 100. /. previous_value) -. 100.)) (int_of_float (margin *. 100.)) in match check with | Mean -> get_previous_and_check "mean" Stats.mean | Median -> get_previous_and_check "median" Stats.median) let check_time_preconditions measurement = if !current_test = None then invalid_arg "Long_test.time: not running a test registered with Long_test" ; if String.contains measurement '\n' then invalid_arg "Long_test.time: newline character in measurement" let time ?previous_count ?minimum_previous_count ?margin ?check ?stddev ?(repeat = 1) measurement f = check_time_preconditions measurement ; if repeat <= 0 then unit else let data_points = ref [] in for _ = 1 to repeat do let start = Unix.gettimeofday () in f () ; let duration = Unix.gettimeofday () -. start in let data_point = InfluxDB.data_point measurement ("duration", Float duration) in add_data_point data_point ; data_points := data_point :: !data_points done ; check_regression ?previous_count ?minimum_previous_count ?margin ?check ?stddev ~data_points:!data_points measurement "duration" let time_lwt ?previous_count ?minimum_previous_count ?margin ?check ?stddev ?(repeat = 1) measurement f = check_time_preconditions measurement ; if repeat <= 0 then unit else let data_points = ref [] in let* () = Base.repeat repeat @@ fun () -> let start = Unix.gettimeofday () in let* () = f () in let duration = Unix.gettimeofday () -. start in let data_point = InfluxDB.data_point measurement ("duration", Float duration) in add_data_point data_point ; data_points := data_point :: !data_points ; unit in check_regression ?previous_count ?minimum_previous_count ?margin ?check ?stddev ~data_points:!data_points measurement "duration" type executor = Executor of string [@@unboxed] let x86_executor1 = Executor "x86_executor1" let x86_executor2 = Executor "x86_executor2" let make_tags team executors tags = let misc_tags = match team with | None -> "long" :: tags | Some team -> "long" :: team :: tags in let executor_tags = List.map (fun (Executor x) -> x) executors in executor_tags @ misc_tags let wrap_body title filename team timeout body argument = let test = {title; filename; team; data_points = String_map.empty; alert_count = 0} in current_test := Some test ; Lwt.finalize (fun () -> Lwt.catch (fun () -> Lwt.finalize (with_timeout timeout (body argument)) send_data_points) (fun exn -> alert_s ~log:false (Printexc.to_string exn) ; raise exn)) (fun () -> current_test := None ; unit) let register ~__FILE__ ~title ~tags ?team ~executors ~timeout body = if String.contains title '\n' then invalid_arg "Long_test.register: long test titles cannot contain newline characters" ; let tags = make_tags team executors tags in Test.register ~__FILE__ ~title ~tags (wrap_body title __FILE__ team timeout body) let register_with_protocol ~__FILE__ ~title ~tags ?team ~executors ~timeout body = if String.contains title '\n' then invalid_arg "Long_test.register_with_protocol: long test titles cannot contain \ newline characters" ; let tags = make_tags team executors tags in Protocol.register_test ~__FILE__ ~title ~tags (wrap_body title __FILE__ team timeout body) let update_grafana_dashboard (dashboard : Grafana.dashboard) = Lwt_main.run @@ match config with | {influxdb = Some influxdb_config; grafana = Some grafana_config; _} -> let dashboard = let update_panel = function | Grafana.Row _ as x -> x | Graph graph -> Graph { graph with queries = List.map (InfluxDB.prefix_measurement influxdb_config) graph.queries; } in {dashboard with panels = List.map update_panel dashboard.panels} in Grafana.update_dashboard grafana_config dashboard | _ -> unit
c7436bb99364952d88189f455ac3e8d86d8324980cf1624eea657b13af4ac447
ericclack/overtone-loops
semiquavers.clj
(ns overtone-loops.proto.semiquavers (:use [overtone.live] [overtone.inst.piano] [overtone-loops.loops] [overtone-loops.samples])) (set-up) ;; Patterns ------------------------------------------------------------ ;; Instruments ;; Function to play piano notes (defn fpiano [anote] (piano :note (note anote) :vel 70 :sustain 0.2 :decay 0.1)) ;; Patterns ------------------------------------------------------------ 1 2 3 4 (defloop pat1 1 finger [6 6 6 6 ]) (defloop pat2 1/4 finger [7 _ 4 _ 7 _ 4 _ 7 _ 4 _ 7 _ 4 _]) (defloop melody 1/4 fpiano [:f4 _ _ _ :bb4 _ _ _ :a4 _ :c4 _ :bb4 _ _ _ ]) ;; (cymbal-closed) ;; --------------------------------------------------------------------- (bpm 130) (beats-in-bar 4) (at-bar 1 (pat1) (melody) ) (at-bar 5 (silence pat1) (pat2) (melody [:f4 _ _ _ :bb4 _ _ _ :a4 _ _ _ :bb4 _ _ _ ])) (comment ; all play for only a few phrases ;; Play these with Ctrl-X Ctrl-E (silence (metro) pat1) (pat2 (on-next-bar)) (pat2 (metro) [3 _ 7 _ 3 _ 7 _ 3 _ 7 _ 3 _ 7 _]) (pat2 (metro) [_ _ 7 _ _ _ 7 2 4 _ 7 _ _ _ 7 _]) (pat2 (metro) [_ 7 _ _ _ 7 _ _ _ 7 _ _ _ 7 _ _]) (pat2 (metro) :first) (melody (metro) [:f4 _ :d4 :d#4 :f4 _ _ _ :f4 :g4 :bb4 :g4 :c4 _ _ _ ]) (melody (metro) :pop) ) ;;(stop)
null
https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/proto/semiquavers.clj
clojure
Patterns ------------------------------------------------------------ Instruments Function to play piano notes Patterns ------------------------------------------------------------ (cymbal-closed) --------------------------------------------------------------------- all play for only a few phrases Play these with Ctrl-X Ctrl-E (stop)
(ns overtone-loops.proto.semiquavers (:use [overtone.live] [overtone.inst.piano] [overtone-loops.loops] [overtone-loops.samples])) (set-up) (defn fpiano [anote] (piano :note (note anote) :vel 70 :sustain 0.2 :decay 0.1)) 1 2 3 4 (defloop pat1 1 finger [6 6 6 6 ]) (defloop pat2 1/4 finger [7 _ 4 _ 7 _ 4 _ 7 _ 4 _ 7 _ 4 _]) (defloop melody 1/4 fpiano [:f4 _ _ _ :bb4 _ _ _ :a4 _ :c4 _ :bb4 _ _ _ ]) (bpm 130) (beats-in-bar 4) (at-bar 1 (pat1) (melody) ) (at-bar 5 (silence pat1) (pat2) (melody [:f4 _ _ _ :bb4 _ _ _ :a4 _ _ _ :bb4 _ _ _ ])) (silence (metro) pat1) (pat2 (on-next-bar)) (pat2 (metro) [3 _ 7 _ 3 _ 7 _ 3 _ 7 _ 3 _ 7 _]) (pat2 (metro) [_ _ 7 _ _ _ 7 2 4 _ 7 _ _ _ 7 _]) (pat2 (metro) [_ 7 _ _ _ 7 _ _ _ 7 _ _ _ 7 _ _]) (pat2 (metro) :first) (melody (metro) [:f4 _ :d4 :d#4 :f4 _ _ _ :f4 :g4 :bb4 :g4 :c4 _ _ _ ]) (melody (metro) :pop) )
58964ef3b577b5db8715c47ec21e0bee03e12d7ed8c9e5924e44cb93505bad11
Cantido/clj-bittorrent
tcp.clj
(ns clj-bittorrent.net.tcp "Functions for creating a threaded TCP server. Yanked from -server" (:require [clojure.java.io :as io]) (:import [java.net InetAddress ServerSocket SocketException Socket])) (defn- server-socket ^ServerSocket [server] (ServerSocket. (:port server) (:backlog server) (InetAddress/getByName (:host server)))) (defn tcp-server "Create a new TCP server. Takes the following keyword arguments: :host - the host to bind to (defaults to 127.0.0.1) :port - the port to bind to :handler - a function to handle incoming connections, expects a socket as an argument :backlog - the maximum backlog of connections to keep (defaults to 50)" [& {:as options}] {:pre [(:port options) (:handler options)]} (merge {:host "127.0.0.1" :backlog 50 :socket (atom nil) :connections (atom #{})} options)) (defn close-socket [server ^ServerSocket socket] (swap! (:connections server) disj socket) (when-not (.isClosed socket) (.close socket))) (defn- open-server-socket [server] (reset! (:socket server) (server-socket server))) (defn- accept-connection [{:keys [handler connections socket] :as server}] (let [^Socket conn (.accept @socket)] (swap! connections conj conn) (future (try (handler conn) (finally (close-socket server conn)))))) (defn running? "True if the server is running." [server] (if-let [socket @(:socket server)] (not (.isClosed socket)))) (defn start "Start a TCP server going." [server] (open-server-socket server) (future (while (running? server) (try (accept-connection server) (catch SocketException _))))) (defn stop "Stop the TCP server and close all open connections." [server] (doseq [socket @(:connections server)] (close-socket server socket)) (.close @(:socket server))) (defn wrap-io "Wrap a handler so that it expects a Reader and Writer as arguments, rather than a raw Socket." [handler] (fn [^Socket socket] (with-open [reader (io/reader socket) writer (io/writer socket)] (handler reader writer))))
null
https://raw.githubusercontent.com/Cantido/clj-bittorrent/5fea93e318f9d07e4bbee6aced12e10ae0f46f2a/src/clj_bittorrent/net/tcp.clj
clojure
(ns clj-bittorrent.net.tcp "Functions for creating a threaded TCP server. Yanked from -server" (:require [clojure.java.io :as io]) (:import [java.net InetAddress ServerSocket SocketException Socket])) (defn- server-socket ^ServerSocket [server] (ServerSocket. (:port server) (:backlog server) (InetAddress/getByName (:host server)))) (defn tcp-server "Create a new TCP server. Takes the following keyword arguments: :host - the host to bind to (defaults to 127.0.0.1) :port - the port to bind to :handler - a function to handle incoming connections, expects a socket as an argument :backlog - the maximum backlog of connections to keep (defaults to 50)" [& {:as options}] {:pre [(:port options) (:handler options)]} (merge {:host "127.0.0.1" :backlog 50 :socket (atom nil) :connections (atom #{})} options)) (defn close-socket [server ^ServerSocket socket] (swap! (:connections server) disj socket) (when-not (.isClosed socket) (.close socket))) (defn- open-server-socket [server] (reset! (:socket server) (server-socket server))) (defn- accept-connection [{:keys [handler connections socket] :as server}] (let [^Socket conn (.accept @socket)] (swap! connections conj conn) (future (try (handler conn) (finally (close-socket server conn)))))) (defn running? "True if the server is running." [server] (if-let [socket @(:socket server)] (not (.isClosed socket)))) (defn start "Start a TCP server going." [server] (open-server-socket server) (future (while (running? server) (try (accept-connection server) (catch SocketException _))))) (defn stop "Stop the TCP server and close all open connections." [server] (doseq [socket @(:connections server)] (close-socket server socket)) (.close @(:socket server))) (defn wrap-io "Wrap a handler so that it expects a Reader and Writer as arguments, rather than a raw Socket." [handler] (fn [^Socket socket] (with-open [reader (io/reader socket) writer (io/writer socket)] (handler reader writer))))
a354665df2cb72d4e8ca33893dcc5d290708b45451c66c6ae270966fe08240cf
NetComposer/nkpacket
nkpacket_dns.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 NkPACKET DNS cache and utilities with RFC3263 support , including NAPTR and -module(nkpacket_dns). -author('Carlos Gonzalez <>'). -behaviour(gen_server). -export([resolve/1, resolve/2]). -export([ips/1, ips/2, srvs/1, srvs/2, naptr/3, transp/1]). -export([clear/1, clear/0]). -export([start_link/0, init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2, handle_info/2]). -define(CHECK_INTERVAL, 60). % secs -include_lib("nklib/include/nklib.hrl"). -include("nkpacket.hrl"). -type opts() :: #{ no_dns_cache => boolean(), protocol => nkpacket:protocol(), resolve_type => listen | connect }. -type uri_transp() :: nkpacket:transport()|undefined|binary(). %% =================================================================== %% Public %% =================================================================== %% @doc Equivalent to resolve(Uri, #{}) -spec resolve(nklib:user_uri()|[nklib:user_uri()])-> {ok, [{uri_transp(), inet:ip_address(), inet:port_number()}]} | {error, term()}. resolve(Uri) -> resolve(Uri, #{}). @doc Finds transports , ips and ports to try for ` Uri ' , following RFC3263 %% %% %% If the option 'protocol' is used, it must be a NkPACKET protocol, and will %% be used for: %% %% - get default transports %% - function Protocol:transports(Scheme) must return a list of valid transports %% - supplied "transport" options must fit - if no transport is found , the first of the list is selected % - if function is not exported, but the scheme is a valid transport, it is used as so %% - get default ports %% - function Protocol:default_port(Transp) is called if no port is used in url - perform NAPTR queries %% If resolve_type = listen , no NAPTR o SRV address resolution is attempted -spec resolve(nklib:user_uri(), opts()) -> {ok, [{uri_transp(), inet:ip_address(), inet:port_number()}]} | {error, term()}. resolve([], _Opts) -> {ok, []}; resolve(List, Opts) when is_list(List), not is_integer(hd(List)) -> resolve(List, Opts, []); resolve(Other, Opts) -> resolve([Other], Opts). @private resolve([], _Opts, Acc) -> {ok, Acc}; resolve([#uri{}=Uri|Rest], Opts, Acc) -> #uri{ scheme = Scheme, domain = Host, opts = UriOpts, ext_opts = ExtOpts, port = Port } = Uri, Host1 = case Host of <<"all">> -> "0.0.0.0"; <<"all6">> -> "0:0:0:0:0:0:0:0"; <<"node">> -> get_node(); _ -> Host end, Target = nklib_util:get_list(<<"maddr">>, UriOpts, Host1), Target2 = case nklib_util:to_ip(Target) of {ok, IP} -> IP; _ -> Target end, RawTransp = case nklib_util:get_value(<<"transport">>, UriOpts) of undefined -> nklib_util:get_value(<<"transport">>, ExtOpts); RawTransp0 -> RawTransp0 end, Transp = transp(RawTransp), try resolve(Scheme, Target2, Port, Transp, Opts) of Res -> resolve(Rest, Opts, Acc++Res) catch throw:Throw -> {error, Throw} end; resolve([Uri|Rest], Opts, Acc) -> case nklib_parse:uris(Uri) of error -> throw({invalid_uri, Uri}); Uris -> resolve(Uris++Rest, Opts, Acc) end. @private resolve(Scheme, Host, 0, Transp, #{resolve_type:=listen}=Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), case is_tuple(Host) of true -> [{Transp1, Host, 0}]; false -> Addrs = ips(Host, Opts), [{Transp1, Addr, 0} || Addr <- Addrs] end; resolve(Scheme, Ip, Port, Transp, Opts) when is_tuple(Ip) -> Transp1 = get_transp(Scheme, Transp, Opts), Port1 = get_port(Port, Transp1, Opts), [{Transp1, Ip, Port1}]; resolve(Scheme, Host, 0, undefined, Opts) -> case naptr(Scheme, Host, Opts) of [] -> case get_transp(Scheme, undefined, Opts) of undefined -> Addrs = ips(Host, Opts), [{undefined, Addr, 0} || Addr <- Addrs]; Transp -> resolve(Scheme, Host, 0, Transp, Opts) end; Res -> Res end; resolve(Scheme, Host, 0, Transp, Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), SrvDomain = make_srv_domain(Scheme, Transp1, Host), case srvs(SrvDomain, Opts) of [] -> Port1 = get_port(0, Transp1, Opts), Addrs = ips(Host, Opts), [{Transp1, Addr, Port1} || Addr <- Addrs]; Srvs -> [{Transp1, Addr, Port1} || {Addr, Port1} <- Srvs] end; resolve(Scheme, Host, Port, Transp, Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), Addrs = ips(Host, Opts), Port1 = get_port(Port, Transp1, Opts), [{Transp1, Addr, Port1} || Addr <- Addrs]. @private get_node() -> [_, Node] = binary:split(atom_to_binary(node(), utf8), <<"@">>), Node. @doc Finds published services using DNS NAPTR search . -spec naptr(nklib:scheme(), string()|binary(), opts()) -> [{nkpacket:transport(), inet:ip_address(), inet:port_number()}]. naptr(Scheme, Domain, #{protocol:=Protocol}=Opts) when Protocol/=undefined -> case erlang:function_exported(Protocol, naptr, 2) of true -> Domain1 = nklib_util:to_list(Domain), case get_cache({naptr, Domain1}, Opts) of undefined -> Naptr = lists:sort(inet_res:lookup(Domain1, in, naptr)), save_cache({naptr, Domain1}, Naptr), lager:debug("Naptr: ~p", [Naptr]), naptr(Scheme, Naptr, Protocol, Opts, []); Naptr -> naptr(Scheme, Naptr, Protocol, Opts, []) end; false -> [] end; naptr(_Scheme, _Domain, _Opts) -> []. @private naptr(_Scheme, [], _Proto, _Opts, Acc) -> Acc; %% Type "s", no regular expression naptr(Scheme, [{_Pref, _Order, "s", Service, "", Target}|Rest], Proto, Opts, Acc) -> case Proto:naptr(Scheme, Service) of {ok, Transp} -> Addrs = srvs(Target, Opts), Acc2 = [{Transp, Addr, Port} || {Addr, Port} <- Addrs], naptr(Scheme, Rest, Proto, Opts, Acc++Acc2); _ -> naptr(Scheme, Rest, Proto, Opts, Acc) end; We do n't yet support other NAPTR expressions naptr(Scheme, [_|Rest], Proto, Opts, Acc) -> naptr(Scheme, Rest, Proto, Opts, Acc). %% @doc Equivalent to srvs(Domain, #{}) -spec srvs(string()|binary()) -> [{inet:ip_address(), inet:port_number()}]. srvs(Domain) -> srvs(Domain, #{}). @doc Gets all hosts for a SRV domain , sorting the result according to RFC2782 %% Domain mast be of the type "_sip._tcp.sip2sip.info" -spec srvs(string()|binary(), opts()) -> [{inet:ip_address(), inet:port_number()}]. srvs(Domain, Opts) -> Domain1 = nklib_util:to_list(Domain), List = case get_cache({srvs, Domain1}, Opts) of undefined -> Srvs = case inet_res:lookup(Domain1, in, srv) of [] -> []; Res -> [{O, W, {D, P}} || {O, W, P, D} <- Res] end, save_cache({srvs, Domain1}, Srvs), rfc2782_sort(Srvs); Srvs -> rfc2782_sort(Srvs) end, case List of [] -> []; _ -> lager:debug("Srvs: ~p", [List]), lists:flatten([ [{Addr, Port} || Addr <- ips(Host, Opts)] || {Host, Port} <- List ]) end. %% @doc Equivalent to ips(Host, #{}) -spec ips(string()|binary()) -> [inet:ip_address()]. ips(Host) -> ips(Host, #{}). %% @doc Gets all IPs for this host, or `[]' if not found. It will first try to get it form the cache . %% Each new invocation rotates the list of IPs. -spec ips(string(), opts()) -> [inet:ip_address()]. ips(Host, Opts) -> Host1 = nklib_util:to_list(Host), case get_cache({ips, Host1}, Opts) of undefined -> case inet:getaddrs(Host1, inet) of {ok, [Ip, Ip]} -> lager:debug("Duplicted IP from inet:getaddrs/2"), Ips = [Ip]; {ok, Ips} -> ok; {error, _} -> case inet:getaddrs(Host1, inet6) of {ok, Ips} -> ok; {error, _} -> Ips = [] end end, save_cache({ips, Host1}, Ips), nklib_util:randomize(Ips); Ips -> nklib_util:randomize(Ips) end. %% @doc Clear all info about `Domain' in the cache. -spec clear(string()) -> ok. clear(Domain) -> del_cache({ips, Domain}), del_cache({srvs, Domain}), del_cache({naptr, Domain}), ok. %% @doc Clear all stored information in the cache. -spec clear() -> ok. clear() -> ets:delete_all_objects(?MODULE), ok. %% =================================================================== %% gen_server %% =================================================================== -record(state, {}). @private start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private -spec init(term()) -> {ok, #state{}} | {stop, term()}. init([]) -> ?MODULE = ets:new(?MODULE, [named_table, public]), erlang:start_timer(1000*?CHECK_INTERVAL, self(), check_ttl), {ok, #state{}}. @private -spec handle_call(term(), {pid(), term()}, #state{}) -> {reply, term(), #state{}} | {noreply, #state{}} | {stop, term(), #state{}} | {stop, term(), term(), #state{}}. handle_call(Msg, _From, State) -> lager:error("Module ~p received unexpected call ~p", [?MODULE, Msg]), {noreply, State}. @private -spec handle_cast(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. handle_cast(Msg, State) -> lager:error("Module ~p received unexpected cast ~p", [?MODULE, Msg]), {noreply, State}. @private -spec handle_info(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. handle_info({timeout, _, check_ttl}, State) -> % Remove old, non read entries Now = nklib_util:timestamp(), Spec = [{{'_', '_', '$1'}, [{'<', '$1', Now}], [true]}], _Deleted = ets:select_delete(?MODULE, Spec), erlang:start_timer(1000*?CHECK_INTERVAL, self(), check_ttl), {noreply, State}; handle_info(Info, State) -> lager:warning("Module ~p received unexpected info: ~p", [?MODULE, Info]), {noreply, State}. @private -spec code_change(term(), #state{}, term()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. @private -spec terminate(term(), #state{}) -> ok. terminate(_Reason, _State) -> ok. %% =================================================================== Utils %% =================================================================== @private transp(udp) -> udp; transp(tcp) -> tcp; transp(tls) -> tls; transp(sctp) -> sctp; transp(ws) -> ws; transp(wss) -> wss; transp(http) -> http; transp(https) -> https; transp(undefined) -> undefined; transp(Other) when is_atom(Other) -> atom_to_binary(Other, latin1); transp(Other) -> Transp = string:to_lower(nklib_util:to_list(Other)), case catch list_to_existing_atom(Transp) of {'EXIT', _} -> nklib_util:to_binary(Other); Atom -> transp(Atom) end. @private %% If we set no transport, and the scheme is valid transport, use it get_transp(Scheme, undefined, Opts) when Scheme==udp; Scheme==tcp; Scheme==tls; Scheme==sctp; Scheme==http; Scheme==https; Scheme==ws; Scheme==wss -> get_transp(Scheme, Scheme, Opts); @private get_transp(Scheme, Transp, #{protocol:=Protocol}) when Protocol/=undefined -> case erlang:function_exported(Protocol, transports, 1) of true -> % We have a set of valid transports case catch Protocol:transports(Scheme) of {'EXIT', _} -> throw({invalid_scheme, Scheme}); Valid when Transp==undefined -> If no transports ( and no standard scheme ) use the first valid one case Valid of [Transp1|_] -> Transp1; [] -> undefined end; Valid -> case lists:member(Transp, Valid) of true -> Transp; false -> case lists:keyfind(Transp, 1, Valid) of {Transp, NewTransp} -> NewTransp; _ -> throw({invalid_transport, Transp}) end end end; false -> Transp end; get_transp(_Scheme, Transp, _Opts) -> Transp. @private get_standard_transp(udp ) - > udp ; %%get_standard_transp(tcp) -> tcp; get_standard_transp(tls ) - > tls ; ) - > sctp ; %%get_standard_transp(http) -> http; ) - > https ; %%get_standard_transp(ws) -> ws; get_standard_transp(wss ) - > wss ; get_standard_transp ( _ ) - > undefined . @private get_port(0, Transp, #{protocol:=Protocol}) when Protocol/=undefined -> case erlang:function_exported(Protocol, default_port, 1) of true -> case Protocol:default_port(Transp) of Port when is_integer(Port) -> lager : warning("P : ~p , ~p : ~p " , [ Protocol , Transp , Port ] ) , Port; _ -> throw({invalid_transport, Transp}) end; false -> 0 end; get_port(Port, _Transp, _Opts)-> Port. @private make_srv_domain(Scheme, Transp, Domain) -> binary_to_list( list_to_binary([ $_, nklib_util:to_binary(Scheme), $., $_, nklib_util:to_binary(Transp), $., nklib_util:to_binary(Domain) ]) ). @private -spec get_cache(term(), map()) -> undefined | term(). get_cache(_Key, #{no_dns_cache:=true}) -> undefined; get_cache(Key, _Opts) -> case ets:lookup(?MODULE, Key) of [] -> undefined; [{_, Value, Expire}] -> case nklib_util:timestamp() > Expire of true -> del_cache(Key), undefined; false -> Value end end. @private -spec save_cache(term(), term()) -> ok. save_cache(Key, Value) -> case nkpacket_config:dns_cache_ttl() of TTL when is_integer(TTL), TTL > 0 -> Now = nklib_util:timestamp(), Secs = TTL div 1000, true = ets:insert(?MODULE, {Key, Value, Now+Secs}), ok; _ -> ok end. @private -spec del_cache(term()) -> ok. del_cache(Key) -> true = ets:delete(?MODULE, Key), ok. @private Extracts and groups records with the same priority -spec groups([{Prio::integer(), Weight::integer(), Target::term()}]) -> [Group] when Group :: [{Weight::integer(), Target::term()}]. groups(Srvs) -> groups(lists:sort(Srvs), [], []). @private groups([{Prio, _, _}=N|Rest], [{Prio, _, _}|_]=Acc1, Acc2) -> groups(Rest, [N|Acc1], Acc2); groups([N|Rest], [], Acc2) -> groups(Rest, [N], Acc2); groups([N|Rest], Acc1, Acc2) -> LAcc1 = [{W, T} || {_, W, T} <- Acc1], groups(Rest, [N], [LAcc1|Acc2]); groups([], [], Acc2) -> lists:reverse(Acc2); groups([], Acc1, Acc2) -> LAcc1 = [{W, T} || {_, W, T} <- Acc1], lists:reverse([LAcc1|Acc2]). %% =================================================================== %% Weight algorithm %% =================================================================== @private Applies RFC2782 weight sorting algorithm -spec rfc2782_sort([{Prio, Weight, Target}]) -> [Target] when Prio::integer(), Weight::integer(), Target::term(). rfc2782_sort([]) -> []; rfc2782_sort(List) -> Groups = groups(List), lists:flatten([do_sort(Group, []) || Group <- Groups]). @private do_sort([], Acc) -> lists:reverse(Acc); do_sort(List, Acc) -> {Pos, Sum} = sort_sum(List), ? : ~p , Sum : ~p " , [ Pos , Sum ] ) , {Current, Rest} = sort_select(Pos, Sum, []), % ?P("Current: ~p", [Current]), do_sort(Rest, [Current|Acc]). @private -spec sort_sum([{Weight, Target}]) -> {Pos, [{AccWeight, Target}]} when Weight::integer(), Target::term(), Pos::integer(), AccWeight::integer(). sort_sum(List) -> Total = lists:foldl( fun({W, _}, Acc) -> W+Acc end, 0, List), Sum = lists:foldl( fun({W, T}, Acc) -> case Acc of [{OldW, _}|_] -> [{OldW+W, T}|Acc]; [] -> [{W, T}] end end, [], lists:sort(List)), Pos = case Total >= 1 of true -> rand:uniform(Total)-1; %% 0 <= x < Total false -> 0 end, {Pos, lists:reverse(Sum)}. @private -spec sort_select(Pos, [{AccWeight, Target}], [{AccWeight, Target}]) -> Target when Pos::integer(), AccWeight::integer(), Target::term(). sort_select(Pos, [{W, T}|Rest], Acc) when Pos =< W -> {T, Rest++Acc}; sort_select(Pos, [C|Rest], Acc) -> sort_select(Pos, Rest, [C|Acc]). %% =================================================================== EUnit tests %% =================================================================== %-define(TEST, true). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). basic_test_() -> {setup, fun() -> ?debugFmt("Starting ~p", [?MODULE]), nkpacket_app:start() end, fun(_) -> ok end, [ {timeout, 60, fun basic/0}, {timeout, 60, fun weight/0} ] }. basic() -> Opts = #{no_dns_cache=>true}, {ok, [ {http, {1,2,3,4}, 0}, {tcp, {4,3,2,1}, 25}, {http, {0,0,0,0}, 1200}, {tls, {1,0,0,0,0,0,0,5}, 0} ]} = resolve(", :25;transport=tcp," ":1200, <http://[1::5]>;transport=tls", Opts), Opts2 = Opts#{protocol=>nkpacket_protocol}, {ok, [ {http, {1,2,3,4}, 80}, {https, {1,2,3,4}, 443}, { tcp , { 4,3,2,1 } , 25 } , {http, {0,0,0,0}, 1200}, {https, {1,0,0,0,0,0,0,5}, 443} ]} = resolve( [ "", "", ":1200", "<https://[1::5]>;transport=https" ], Opts2), %% {error, {invalid_transport, tcp}} = resolve(":25;transport = tcp " , Opts2 ) , {ok, [ {http, {127,0,0,1}, 0}, {https, {127,0,0,1}, 0}, {http, {127,0,0,1}, 25}, {tls, {127,0,0,1}, 0}, {udp, {127,0,0,1}, 1234} ]} = resolve(", , :25, " ";transport=tls, :1234;transport=udp", Opts2#{resolve_type=>listen}), % Allow tls with 0 (not in protocol) {ok, [ {http, {127,0,0,1}, 80}, {https, {127,0,0,1}, 443}, {http, {127,0,0,1}, 25} ]} = resolve(", , :25", Opts2), {error, {invalid_transport, tls}} = resolve(";transport=tls", Opts2), ok. weight() -> ?debugMsg("DNS Weight Test"), []= groups([]), [[{1,a}]] = groups([{1,1,a}]), [[{1,a}],[{2,b}]] = groups([{2,2,b}, {1,1,a}]), [[{2,b},{1,a}],[{3,c}]] = groups([{1,1,a}, {1,2,b}, {2,3,c}]), [[{1,a}],[{3,c},{2,b}]] = groups([{1,1,a}, {2,2,b}, {2,3,c}]), [[{2,b},{1,a}],[{4,d},{3,c}],[{5,e}]] = groups([{1,1,a}, {1,2,b}, {2,3,c}, {2,4,d}, {3,5,e}]), {_, [{0,c},{0,f},{5,a},{15,b},{25,e},{50,d}]} = sort_sum([{5,a}, {10,b}, {0,c}, {25,d}, {10,e}, {0,f}]), {b,[{4,c},{1,a}]} = sort_select(3, [{1,a}, {3,b}, {4,c}], []), Total = [ begin [A, B, C] = do_sort([{1,a}, {9,b}, {90,c}], []), false = A==B, false = A==C, false = B==C, A end || _ <- lists:seq(0,1000) ], As = length([true || a <-Total]), Bs = length([true || b <-Total]), Cs = length([true || c <-Total]), ? P("As : ~p vs 1 % , Bs : ~p vs 9 % , Cs : ~p vs 90 % " , [ As/10 , Bs/10 , Cs/10 ] ) , true = Cs > Bs andalso Bs > As, [] = rfc2782_sort([]), [a] = rfc2782_sort([{1,1,a}]), [b, a, c] = rfc2782_sort([{2,2,a}, {1,1,b}, {3,3,c}]), [b, A1, A2, c] = rfc2782_sort([{2,10,a}, {1,1,b}, {3,3,c}, {2,10,d}]), true = A1==a orelse A1==d, true = A1/=A2, ok. -endif.
null
https://raw.githubusercontent.com/NetComposer/nkpacket/4d74ab31b20ba7a1449f1f72c1c51829f18d2d5c/src/nkpacket_dns.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. ------------------------------------------------------------------- secs =================================================================== Public =================================================================== @doc Equivalent to resolve(Uri, #{}) If the option 'protocol' is used, it must be a NkPACKET protocol, and will be used for: - get default transports - function Protocol:transports(Scheme) must return a list of valid transports - supplied "transport" options must fit - if function is not exported, but the scheme is a valid transport, it is used as so - get default ports - function Protocol:default_port(Transp) is called if no port is used in url Type "s", no regular expression @doc Equivalent to srvs(Domain, #{}) Domain mast be of the type "_sip._tcp.sip2sip.info" @doc Equivalent to ips(Host, #{}) @doc Gets all IPs for this host, or `[]' if not found. Each new invocation rotates the list of IPs. @doc Clear all info about `Domain' in the cache. @doc Clear all stored information in the cache. =================================================================== gen_server =================================================================== Remove old, non read entries =================================================================== =================================================================== If we set no transport, and the scheme is valid transport, use it We have a set of valid transports get_standard_transp(tcp) -> tcp; get_standard_transp(http) -> http; get_standard_transp(ws) -> ws; =================================================================== Weight algorithm =================================================================== ?P("Current: ~p", [Current]), 0 <= x < Total =================================================================== =================================================================== -define(TEST, true). {error, {invalid_transport, tcp}} = Allow tls with 0 (not in protocol)
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 @doc NkPACKET DNS cache and utilities with RFC3263 support , including NAPTR and -module(nkpacket_dns). -author('Carlos Gonzalez <>'). -behaviour(gen_server). -export([resolve/1, resolve/2]). -export([ips/1, ips/2, srvs/1, srvs/2, naptr/3, transp/1]). -export([clear/1, clear/0]). -export([start_link/0, init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2, handle_info/2]). -include_lib("nklib/include/nklib.hrl"). -include("nkpacket.hrl"). -type opts() :: #{ no_dns_cache => boolean(), protocol => nkpacket:protocol(), resolve_type => listen | connect }. -type uri_transp() :: nkpacket:transport()|undefined|binary(). -spec resolve(nklib:user_uri()|[nklib:user_uri()])-> {ok, [{uri_transp(), inet:ip_address(), inet:port_number()}]} | {error, term()}. resolve(Uri) -> resolve(Uri, #{}). @doc Finds transports , ips and ports to try for ` Uri ' , following RFC3263 - if no transport is found , the first of the list is selected - perform NAPTR queries If resolve_type = listen , no NAPTR o SRV address resolution is attempted -spec resolve(nklib:user_uri(), opts()) -> {ok, [{uri_transp(), inet:ip_address(), inet:port_number()}]} | {error, term()}. resolve([], _Opts) -> {ok, []}; resolve(List, Opts) when is_list(List), not is_integer(hd(List)) -> resolve(List, Opts, []); resolve(Other, Opts) -> resolve([Other], Opts). @private resolve([], _Opts, Acc) -> {ok, Acc}; resolve([#uri{}=Uri|Rest], Opts, Acc) -> #uri{ scheme = Scheme, domain = Host, opts = UriOpts, ext_opts = ExtOpts, port = Port } = Uri, Host1 = case Host of <<"all">> -> "0.0.0.0"; <<"all6">> -> "0:0:0:0:0:0:0:0"; <<"node">> -> get_node(); _ -> Host end, Target = nklib_util:get_list(<<"maddr">>, UriOpts, Host1), Target2 = case nklib_util:to_ip(Target) of {ok, IP} -> IP; _ -> Target end, RawTransp = case nklib_util:get_value(<<"transport">>, UriOpts) of undefined -> nklib_util:get_value(<<"transport">>, ExtOpts); RawTransp0 -> RawTransp0 end, Transp = transp(RawTransp), try resolve(Scheme, Target2, Port, Transp, Opts) of Res -> resolve(Rest, Opts, Acc++Res) catch throw:Throw -> {error, Throw} end; resolve([Uri|Rest], Opts, Acc) -> case nklib_parse:uris(Uri) of error -> throw({invalid_uri, Uri}); Uris -> resolve(Uris++Rest, Opts, Acc) end. @private resolve(Scheme, Host, 0, Transp, #{resolve_type:=listen}=Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), case is_tuple(Host) of true -> [{Transp1, Host, 0}]; false -> Addrs = ips(Host, Opts), [{Transp1, Addr, 0} || Addr <- Addrs] end; resolve(Scheme, Ip, Port, Transp, Opts) when is_tuple(Ip) -> Transp1 = get_transp(Scheme, Transp, Opts), Port1 = get_port(Port, Transp1, Opts), [{Transp1, Ip, Port1}]; resolve(Scheme, Host, 0, undefined, Opts) -> case naptr(Scheme, Host, Opts) of [] -> case get_transp(Scheme, undefined, Opts) of undefined -> Addrs = ips(Host, Opts), [{undefined, Addr, 0} || Addr <- Addrs]; Transp -> resolve(Scheme, Host, 0, Transp, Opts) end; Res -> Res end; resolve(Scheme, Host, 0, Transp, Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), SrvDomain = make_srv_domain(Scheme, Transp1, Host), case srvs(SrvDomain, Opts) of [] -> Port1 = get_port(0, Transp1, Opts), Addrs = ips(Host, Opts), [{Transp1, Addr, Port1} || Addr <- Addrs]; Srvs -> [{Transp1, Addr, Port1} || {Addr, Port1} <- Srvs] end; resolve(Scheme, Host, Port, Transp, Opts) -> Transp1 = get_transp(Scheme, Transp, Opts), Addrs = ips(Host, Opts), Port1 = get_port(Port, Transp1, Opts), [{Transp1, Addr, Port1} || Addr <- Addrs]. @private get_node() -> [_, Node] = binary:split(atom_to_binary(node(), utf8), <<"@">>), Node. @doc Finds published services using DNS NAPTR search . -spec naptr(nklib:scheme(), string()|binary(), opts()) -> [{nkpacket:transport(), inet:ip_address(), inet:port_number()}]. naptr(Scheme, Domain, #{protocol:=Protocol}=Opts) when Protocol/=undefined -> case erlang:function_exported(Protocol, naptr, 2) of true -> Domain1 = nklib_util:to_list(Domain), case get_cache({naptr, Domain1}, Opts) of undefined -> Naptr = lists:sort(inet_res:lookup(Domain1, in, naptr)), save_cache({naptr, Domain1}, Naptr), lager:debug("Naptr: ~p", [Naptr]), naptr(Scheme, Naptr, Protocol, Opts, []); Naptr -> naptr(Scheme, Naptr, Protocol, Opts, []) end; false -> [] end; naptr(_Scheme, _Domain, _Opts) -> []. @private naptr(_Scheme, [], _Proto, _Opts, Acc) -> Acc; naptr(Scheme, [{_Pref, _Order, "s", Service, "", Target}|Rest], Proto, Opts, Acc) -> case Proto:naptr(Scheme, Service) of {ok, Transp} -> Addrs = srvs(Target, Opts), Acc2 = [{Transp, Addr, Port} || {Addr, Port} <- Addrs], naptr(Scheme, Rest, Proto, Opts, Acc++Acc2); _ -> naptr(Scheme, Rest, Proto, Opts, Acc) end; We do n't yet support other NAPTR expressions naptr(Scheme, [_|Rest], Proto, Opts, Acc) -> naptr(Scheme, Rest, Proto, Opts, Acc). -spec srvs(string()|binary()) -> [{inet:ip_address(), inet:port_number()}]. srvs(Domain) -> srvs(Domain, #{}). @doc Gets all hosts for a SRV domain , sorting the result according to RFC2782 -spec srvs(string()|binary(), opts()) -> [{inet:ip_address(), inet:port_number()}]. srvs(Domain, Opts) -> Domain1 = nklib_util:to_list(Domain), List = case get_cache({srvs, Domain1}, Opts) of undefined -> Srvs = case inet_res:lookup(Domain1, in, srv) of [] -> []; Res -> [{O, W, {D, P}} || {O, W, P, D} <- Res] end, save_cache({srvs, Domain1}, Srvs), rfc2782_sort(Srvs); Srvs -> rfc2782_sort(Srvs) end, case List of [] -> []; _ -> lager:debug("Srvs: ~p", [List]), lists:flatten([ [{Addr, Port} || Addr <- ips(Host, Opts)] || {Host, Port} <- List ]) end. -spec ips(string()|binary()) -> [inet:ip_address()]. ips(Host) -> ips(Host, #{}). It will first try to get it form the cache . -spec ips(string(), opts()) -> [inet:ip_address()]. ips(Host, Opts) -> Host1 = nklib_util:to_list(Host), case get_cache({ips, Host1}, Opts) of undefined -> case inet:getaddrs(Host1, inet) of {ok, [Ip, Ip]} -> lager:debug("Duplicted IP from inet:getaddrs/2"), Ips = [Ip]; {ok, Ips} -> ok; {error, _} -> case inet:getaddrs(Host1, inet6) of {ok, Ips} -> ok; {error, _} -> Ips = [] end end, save_cache({ips, Host1}, Ips), nklib_util:randomize(Ips); Ips -> nklib_util:randomize(Ips) end. -spec clear(string()) -> ok. clear(Domain) -> del_cache({ips, Domain}), del_cache({srvs, Domain}), del_cache({naptr, Domain}), ok. -spec clear() -> ok. clear() -> ets:delete_all_objects(?MODULE), ok. -record(state, {}). @private start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private -spec init(term()) -> {ok, #state{}} | {stop, term()}. init([]) -> ?MODULE = ets:new(?MODULE, [named_table, public]), erlang:start_timer(1000*?CHECK_INTERVAL, self(), check_ttl), {ok, #state{}}. @private -spec handle_call(term(), {pid(), term()}, #state{}) -> {reply, term(), #state{}} | {noreply, #state{}} | {stop, term(), #state{}} | {stop, term(), term(), #state{}}. handle_call(Msg, _From, State) -> lager:error("Module ~p received unexpected call ~p", [?MODULE, Msg]), {noreply, State}. @private -spec handle_cast(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. handle_cast(Msg, State) -> lager:error("Module ~p received unexpected cast ~p", [?MODULE, Msg]), {noreply, State}. @private -spec handle_info(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. handle_info({timeout, _, check_ttl}, State) -> Now = nklib_util:timestamp(), Spec = [{{'_', '_', '$1'}, [{'<', '$1', Now}], [true]}], _Deleted = ets:select_delete(?MODULE, Spec), erlang:start_timer(1000*?CHECK_INTERVAL, self(), check_ttl), {noreply, State}; handle_info(Info, State) -> lager:warning("Module ~p received unexpected info: ~p", [?MODULE, Info]), {noreply, State}. @private -spec code_change(term(), #state{}, term()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. @private -spec terminate(term(), #state{}) -> ok. terminate(_Reason, _State) -> ok. Utils @private transp(udp) -> udp; transp(tcp) -> tcp; transp(tls) -> tls; transp(sctp) -> sctp; transp(ws) -> ws; transp(wss) -> wss; transp(http) -> http; transp(https) -> https; transp(undefined) -> undefined; transp(Other) when is_atom(Other) -> atom_to_binary(Other, latin1); transp(Other) -> Transp = string:to_lower(nklib_util:to_list(Other)), case catch list_to_existing_atom(Transp) of {'EXIT', _} -> nklib_util:to_binary(Other); Atom -> transp(Atom) end. @private get_transp(Scheme, undefined, Opts) when Scheme==udp; Scheme==tcp; Scheme==tls; Scheme==sctp; Scheme==http; Scheme==https; Scheme==ws; Scheme==wss -> get_transp(Scheme, Scheme, Opts); @private get_transp(Scheme, Transp, #{protocol:=Protocol}) when Protocol/=undefined -> case erlang:function_exported(Protocol, transports, 1) of true -> case catch Protocol:transports(Scheme) of {'EXIT', _} -> throw({invalid_scheme, Scheme}); Valid when Transp==undefined -> If no transports ( and no standard scheme ) use the first valid one case Valid of [Transp1|_] -> Transp1; [] -> undefined end; Valid -> case lists:member(Transp, Valid) of true -> Transp; false -> case lists:keyfind(Transp, 1, Valid) of {Transp, NewTransp} -> NewTransp; _ -> throw({invalid_transport, Transp}) end end end; false -> Transp end; get_transp(_Scheme, Transp, _Opts) -> Transp. @private get_standard_transp(udp ) - > udp ; get_standard_transp(tls ) - > tls ; ) - > sctp ; ) - > https ; get_standard_transp(wss ) - > wss ; get_standard_transp ( _ ) - > undefined . @private get_port(0, Transp, #{protocol:=Protocol}) when Protocol/=undefined -> case erlang:function_exported(Protocol, default_port, 1) of true -> case Protocol:default_port(Transp) of Port when is_integer(Port) -> lager : warning("P : ~p , ~p : ~p " , [ Protocol , Transp , Port ] ) , Port; _ -> throw({invalid_transport, Transp}) end; false -> 0 end; get_port(Port, _Transp, _Opts)-> Port. @private make_srv_domain(Scheme, Transp, Domain) -> binary_to_list( list_to_binary([ $_, nklib_util:to_binary(Scheme), $., $_, nklib_util:to_binary(Transp), $., nklib_util:to_binary(Domain) ]) ). @private -spec get_cache(term(), map()) -> undefined | term(). get_cache(_Key, #{no_dns_cache:=true}) -> undefined; get_cache(Key, _Opts) -> case ets:lookup(?MODULE, Key) of [] -> undefined; [{_, Value, Expire}] -> case nklib_util:timestamp() > Expire of true -> del_cache(Key), undefined; false -> Value end end. @private -spec save_cache(term(), term()) -> ok. save_cache(Key, Value) -> case nkpacket_config:dns_cache_ttl() of TTL when is_integer(TTL), TTL > 0 -> Now = nklib_util:timestamp(), Secs = TTL div 1000, true = ets:insert(?MODULE, {Key, Value, Now+Secs}), ok; _ -> ok end. @private -spec del_cache(term()) -> ok. del_cache(Key) -> true = ets:delete(?MODULE, Key), ok. @private Extracts and groups records with the same priority -spec groups([{Prio::integer(), Weight::integer(), Target::term()}]) -> [Group] when Group :: [{Weight::integer(), Target::term()}]. groups(Srvs) -> groups(lists:sort(Srvs), [], []). @private groups([{Prio, _, _}=N|Rest], [{Prio, _, _}|_]=Acc1, Acc2) -> groups(Rest, [N|Acc1], Acc2); groups([N|Rest], [], Acc2) -> groups(Rest, [N], Acc2); groups([N|Rest], Acc1, Acc2) -> LAcc1 = [{W, T} || {_, W, T} <- Acc1], groups(Rest, [N], [LAcc1|Acc2]); groups([], [], Acc2) -> lists:reverse(Acc2); groups([], Acc1, Acc2) -> LAcc1 = [{W, T} || {_, W, T} <- Acc1], lists:reverse([LAcc1|Acc2]). @private Applies RFC2782 weight sorting algorithm -spec rfc2782_sort([{Prio, Weight, Target}]) -> [Target] when Prio::integer(), Weight::integer(), Target::term(). rfc2782_sort([]) -> []; rfc2782_sort(List) -> Groups = groups(List), lists:flatten([do_sort(Group, []) || Group <- Groups]). @private do_sort([], Acc) -> lists:reverse(Acc); do_sort(List, Acc) -> {Pos, Sum} = sort_sum(List), ? : ~p , Sum : ~p " , [ Pos , Sum ] ) , {Current, Rest} = sort_select(Pos, Sum, []), do_sort(Rest, [Current|Acc]). @private -spec sort_sum([{Weight, Target}]) -> {Pos, [{AccWeight, Target}]} when Weight::integer(), Target::term(), Pos::integer(), AccWeight::integer(). sort_sum(List) -> Total = lists:foldl( fun({W, _}, Acc) -> W+Acc end, 0, List), Sum = lists:foldl( fun({W, T}, Acc) -> case Acc of [{OldW, _}|_] -> [{OldW+W, T}|Acc]; [] -> [{W, T}] end end, [], lists:sort(List)), Pos = case Total >= 1 of false -> 0 end, {Pos, lists:reverse(Sum)}. @private -spec sort_select(Pos, [{AccWeight, Target}], [{AccWeight, Target}]) -> Target when Pos::integer(), AccWeight::integer(), Target::term(). sort_select(Pos, [{W, T}|Rest], Acc) when Pos =< W -> {T, Rest++Acc}; sort_select(Pos, [C|Rest], Acc) -> sort_select(Pos, Rest, [C|Acc]). EUnit tests -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). basic_test_() -> {setup, fun() -> ?debugFmt("Starting ~p", [?MODULE]), nkpacket_app:start() end, fun(_) -> ok end, [ {timeout, 60, fun basic/0}, {timeout, 60, fun weight/0} ] }. basic() -> Opts = #{no_dns_cache=>true}, {ok, [ {http, {1,2,3,4}, 0}, {tcp, {4,3,2,1}, 25}, {http, {0,0,0,0}, 1200}, {tls, {1,0,0,0,0,0,0,5}, 0} ]} = resolve(", :25;transport=tcp," ":1200, <http://[1::5]>;transport=tls", Opts), Opts2 = Opts#{protocol=>nkpacket_protocol}, {ok, [ {http, {1,2,3,4}, 80}, {https, {1,2,3,4}, 443}, { tcp , { 4,3,2,1 } , 25 } , {http, {0,0,0,0}, 1200}, {https, {1,0,0,0,0,0,0,5}, 443} ]} = resolve( [ "", "", ":1200", "<https://[1::5]>;transport=https" ], Opts2), resolve(":25;transport = tcp " , Opts2 ) , {ok, [ {http, {127,0,0,1}, 0}, {https, {127,0,0,1}, 0}, {http, {127,0,0,1}, 25}, {tls, {127,0,0,1}, 0}, {udp, {127,0,0,1}, 1234} ]} = resolve(", , :25, " ";transport=tls, :1234;transport=udp", {ok, [ {http, {127,0,0,1}, 80}, {https, {127,0,0,1}, 443}, {http, {127,0,0,1}, 25} ]} = resolve(", , :25", Opts2), {error, {invalid_transport, tls}} = resolve(";transport=tls", Opts2), ok. weight() -> ?debugMsg("DNS Weight Test"), []= groups([]), [[{1,a}]] = groups([{1,1,a}]), [[{1,a}],[{2,b}]] = groups([{2,2,b}, {1,1,a}]), [[{2,b},{1,a}],[{3,c}]] = groups([{1,1,a}, {1,2,b}, {2,3,c}]), [[{1,a}],[{3,c},{2,b}]] = groups([{1,1,a}, {2,2,b}, {2,3,c}]), [[{2,b},{1,a}],[{4,d},{3,c}],[{5,e}]] = groups([{1,1,a}, {1,2,b}, {2,3,c}, {2,4,d}, {3,5,e}]), {_, [{0,c},{0,f},{5,a},{15,b},{25,e},{50,d}]} = sort_sum([{5,a}, {10,b}, {0,c}, {25,d}, {10,e}, {0,f}]), {b,[{4,c},{1,a}]} = sort_select(3, [{1,a}, {3,b}, {4,c}], []), Total = [ begin [A, B, C] = do_sort([{1,a}, {9,b}, {90,c}], []), false = A==B, false = A==C, false = B==C, A end || _ <- lists:seq(0,1000) ], As = length([true || a <-Total]), Bs = length([true || b <-Total]), Cs = length([true || c <-Total]), ? P("As : ~p vs 1 % , Bs : ~p vs 9 % , Cs : ~p vs 90 % " , [ As/10 , Bs/10 , Cs/10 ] ) , true = Cs > Bs andalso Bs > As, [] = rfc2782_sort([]), [a] = rfc2782_sort([{1,1,a}]), [b, a, c] = rfc2782_sort([{2,2,a}, {1,1,b}, {3,3,c}]), [b, A1, A2, c] = rfc2782_sort([{2,10,a}, {1,1,b}, {3,3,c}, {2,10,d}]), true = A1==a orelse A1==d, true = A1/=A2, ok. -endif.
ba57d9cabece2709357bb73bbb8704a90e1a058c7ba05fb890736ebb0dd5f421
kupl/LearnML
patch.ml
type lambda = V of var | P of (var * lambda) | C of (lambda * lambda) and var = string let rec __s3 (__s4 : lambda) : string list = match __s4 with | V __s5 -> [ __s5 ] | P (__s6, __s7) -> List.filter (fun (__s8 : string) -> not (__s6 = __s8)) (__s3 __s7) | C (__s9, __s10) -> __s3 __s9 @ __s3 __s10 let rec check (e : lambda) : bool = let rec checkp ((va : string), (ex : lambda)) : bool = match ex with | V va2 -> if va = va2 then true else false | P (va2, ex2) -> ( match ex2 with | C (ex3, ex4) -> if (checkp (va, ex3) || checkp (va2, ex3)) && (checkp (va, ex4) || checkp (va2, ex4)) then true else false | _ -> if checkp (va, ex2) || checkp (va2, ex2) then true else false ) | C (ex2, ex3) -> if checkp (va, ex2) && checkp (va, ex3) then true else false in List.length (__s3 e) = 0
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/lambda/sub74/patch.ml
ocaml
type lambda = V of var | P of (var * lambda) | C of (lambda * lambda) and var = string let rec __s3 (__s4 : lambda) : string list = match __s4 with | V __s5 -> [ __s5 ] | P (__s6, __s7) -> List.filter (fun (__s8 : string) -> not (__s6 = __s8)) (__s3 __s7) | C (__s9, __s10) -> __s3 __s9 @ __s3 __s10 let rec check (e : lambda) : bool = let rec checkp ((va : string), (ex : lambda)) : bool = match ex with | V va2 -> if va = va2 then true else false | P (va2, ex2) -> ( match ex2 with | C (ex3, ex4) -> if (checkp (va, ex3) || checkp (va2, ex3)) && (checkp (va, ex4) || checkp (va2, ex4)) then true else false | _ -> if checkp (va, ex2) || checkp (va2, ex2) then true else false ) | C (ex2, ex3) -> if checkp (va, ex2) && checkp (va, ex3) then true else false in List.length (__s3 e) = 0
40f9a04b76712b944b4d60aa58fc49da023718e8920551121320cd5e4ed4c02b
gheber/kenzo
cat-init.lisp
;;; FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES ;;; FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES ;;; FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES (IN-PACKAGE "COMMON-LISP-USER") ( DEFUN common - graphics - user::npppp ( ) ;;; (in-package :user)) (DEFUN KENZO-VERSION () (format t "~%*** Kenzo-Version 8 ***~2%") (values)) (PROCLAIM '(OPTIMIZE (speed 3) (safety 1) (space 0) (debug 0))) (DEFCONSTANT +FILE-LIST+ '("macros" "various" "classes" "combinations" "chain-complexes" "chcm-elementary-op" "effective-homology" "homology-groups" "searching-homology" "cones" "bicones" "tensor-products" "coalgebras" "cobar" "algebras" "bar" "simplicial-sets" "simplicial-mrphs" "delta" "special-smsts" "suspensions" "disk-pasting" "cartesian-products" "eilenberg-zilber" "kan" "simplicial-groups" "fibrations" "loop-spaces" "ls-twisted-products" "lp-space-efhm" "classifying-spaces" "k-pi-n" "serre" "cs-twisted-products" "cl-space-efhm" "whitehead" "smith" )) (DO ((i 1 (1+ i)) (mark +file-list+ (cdr mark))) ((endp mark) (terpri)) (format t "~% FILE ~2D: ~A" i (car mark))) (DEFCONSTANT +SOURCE-EXTENSION+ #+(or allegro clisp lispworks sbcl) "lisp" #-(or allegro clisp lispworks sbcl) (error "Not an Allegro or CLisp or LispWorks environment.")) (DEFCONSTANT +COMPILED-EXTENSION+ #+allegro "fasl" #+clisp "fas" #+lispworks "ofasl" #+sbcl "sfasl") (DEFUN LOAD-SFILES () (mapc #'(lambda (file-name) (load (concatenate 'string file-name "." +source-extension+))) +file-list+)) (DEFVAR *CMBN-CONTROL*) (SETF *CMBN-CONTROL* T) (DEFUN COMPILE-FILES () (format t "~%*CMBN-CONTROL* = ~A~2%" *cmbn-control*) (mapc #'(lambda (file-name) (compile-file (concatenate 'string file-name "." +source-extension+) :output-file (concatenate 'string file-name "." +compiled-extension+)) (load (concatenate 'string file-name "." +compiled-extension+))) +file-list+)) (DEFUN LOAD-CFILES () (mapc #'(lambda (file-name) (load (concatenate 'string file-name "." +compiled-extension+))) +file-list+))
null
https://raw.githubusercontent.com/gheber/kenzo/48e2ea398b80f39d3b5954157a7df57e07a362d7/archive/Kenzo-8/cat-init.lisp
lisp
FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES FILES (in-package :user))
(IN-PACKAGE "COMMON-LISP-USER") ( DEFUN common - graphics - user::npppp ( ) (DEFUN KENZO-VERSION () (format t "~%*** Kenzo-Version 8 ***~2%") (values)) (PROCLAIM '(OPTIMIZE (speed 3) (safety 1) (space 0) (debug 0))) (DEFCONSTANT +FILE-LIST+ '("macros" "various" "classes" "combinations" "chain-complexes" "chcm-elementary-op" "effective-homology" "homology-groups" "searching-homology" "cones" "bicones" "tensor-products" "coalgebras" "cobar" "algebras" "bar" "simplicial-sets" "simplicial-mrphs" "delta" "special-smsts" "suspensions" "disk-pasting" "cartesian-products" "eilenberg-zilber" "kan" "simplicial-groups" "fibrations" "loop-spaces" "ls-twisted-products" "lp-space-efhm" "classifying-spaces" "k-pi-n" "serre" "cs-twisted-products" "cl-space-efhm" "whitehead" "smith" )) (DO ((i 1 (1+ i)) (mark +file-list+ (cdr mark))) ((endp mark) (terpri)) (format t "~% FILE ~2D: ~A" i (car mark))) (DEFCONSTANT +SOURCE-EXTENSION+ #+(or allegro clisp lispworks sbcl) "lisp" #-(or allegro clisp lispworks sbcl) (error "Not an Allegro or CLisp or LispWorks environment.")) (DEFCONSTANT +COMPILED-EXTENSION+ #+allegro "fasl" #+clisp "fas" #+lispworks "ofasl" #+sbcl "sfasl") (DEFUN LOAD-SFILES () (mapc #'(lambda (file-name) (load (concatenate 'string file-name "." +source-extension+))) +file-list+)) (DEFVAR *CMBN-CONTROL*) (SETF *CMBN-CONTROL* T) (DEFUN COMPILE-FILES () (format t "~%*CMBN-CONTROL* = ~A~2%" *cmbn-control*) (mapc #'(lambda (file-name) (compile-file (concatenate 'string file-name "." +source-extension+) :output-file (concatenate 'string file-name "." +compiled-extension+)) (load (concatenate 'string file-name "." +compiled-extension+))) +file-list+)) (DEFUN LOAD-CFILES () (mapc #'(lambda (file-name) (load (concatenate 'string file-name "." +compiled-extension+))) +file-list+))
04bddf28e211a44e58b636f89e8eec3d443bbfc9c7cfbb981cc75b75d8a04926
technomancy/leiningen
utils.clj
(ns leiningen.core.utils (:require [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.string :as str]) (:import (com.hypirion.io RevivableInputStream) (clojure.lang LineNumberingPushbackReader) (java.io ByteArrayOutputStream PrintStream File FileDescriptor FileOutputStream FileInputStream InputStreamReader) (java.net URL) (java.nio.file Files) (java.nio.file.attribute PosixFilePermissions))) (defn create-tmpdir "Creates a temporary directory in parent (something clojure.java.io/as-path can handle) with the specified permissions string (something PosixFilePermissions/asFileAttribute can handle i.e. \"rw-------\") and returns its Path." [parent prefix permissions] (let [nio-path (.toPath (io/as-file parent)) perms (PosixFilePermissions/fromString permissions) attr (PosixFilePermissions/asFileAttribute perms)] (Files/createTempDirectory nio-path prefix (into-array [attr])))) (def rebound-io? (atom false)) (defn rebind-io! [] (when-not @rebound-io? (let [new-in (-> FileDescriptor/in FileInputStream. RevivableInputStream.)] (System/setIn new-in) (.bindRoot #'*in* (-> new-in InputStreamReader. LineNumberingPushbackReader.))) (reset! rebound-io? true))) (defn build-url "Creates java.net.URL from string" [url] (try (URL. url) (catch java.net.MalformedURLException _ (URL. (str "http://" url))))) (defmacro with-write-permissions "Runs body only if path is writeable, or - if it does not already exist - can be created." [path & body] `(let [p# ~path f# (new File p#)] (if (or (and (.exists f#) (.canWrite f#)) (and (not (.exists f#)) (some-> f# .getParentFile .canWrite))) (do ~@body) (throw (java.io.IOException. (str "Permission denied. Please check your access rights for " p#)))))) (defn read-file "Returns the first Clojure form in a file if it exists." [file] (if (.exists file) (try (read-string (slurp file)) (catch Exception e TODO : use main / warn for this in 3.0 (println "Error reading" (.getName file) "from" (.getParent file)) (if (zero? (.length file)) (println "File cannot be empty") (if (.contains (.getMessage e) "EOF while reading") (println "Invalid content was found") (println (.getMessage e))))))))) (defn symlink? "Checks if a File is a symbolic link or points to another file." [file] (let [canon (if-not (.getParent file) file (-> (.. file getParentFile getCanonicalFile) (File. (.getName file))))] (not= (.getCanonicalFile canon) (.getAbsoluteFile canon)))) (defn mkdirs "Make a given directory and its parents, but throw an Exception on failure." [f] ; whyyyyy does .mkdirs fail silently ugh (when f ; (io/file nil) returns nil, so we mimic a similar API instead of failing eagerly on nil inputs. (when-not (or (.mkdirs (io/file f)) (.exists (io/file f))) (throw (Exception. (str "Couldn't create directories: " (io/file f))))))) (defn relativize "Makes the filepath path relative to base. Assumes base is an ancestor to path, and that the path contains no '..'." [base path] TODO : When moving to Java 1.7 , use Path 's relativize instead (let [base-uri (.toURI (io/file base)) path-uri (.toURI (io/file path))] (.. base-uri (relativize path-uri) (getPath)))) (defn ns-exists? [namespace] (or (find-ns (symbol namespace)) (some (fn [suffix] (-> (#'clojure.core/root-resource namespace) (subs 1) (str suffix) io/resource)) [".clj" ".cljc" (str clojure.lang.RT/LOADER_SUFFIX ".class")]))) (defn error [& args] TODO : use main / warn for this in 3.0 (apply println "Error:" args))) (defn require-resolve "Resolve a fully qualified symbol by first requiring its namespace." ([sym] (if-let [ns (namespace sym)] (when (ns-exists? ns) (let [ns (symbol ns)] (when-not (find-ns ns) (require ns))) (resolve sym)) (resolve sym))) ([ns sym] (require-resolve (symbol ns sym)))) # OS detection (defn- get-by-pattern "Gets a value from map m, but uses the keys as regex patterns, trying to match against k instead of doing an exact match." [m k] (m (first (drop-while #(nil? (re-find (re-pattern %) k)) (keys m))))) (defn- get-with-pattern-fallback "Gets a value from map m, but if it doesn't exist, fallback to use get-by-pattern." [m k] (let [exact-match (m k)] (if (nil? exact-match) (get-by-pattern m k) exact-match))) (def ^:private native-names {"Mac OS X" :macosx "Windows" :windows "Linux" :linux "FreeBSD" :freebsd "OpenBSD" :openbsd "amd64" :x86_64 "x86_64" :x86_64 "x86" :x86 "i386" :x86 "arm" :arm "SunOS" :solaris "sparc" :sparc "Darwin" :macosx "aarch64" :aarch_64}) (defn get-os "Returns a keyword naming the host OS." [] (get-with-pattern-fallback native-names (System/getProperty "os.name"))) (defn get-arch "Returns a keyword naming the host architecture" [] (get-with-pattern-fallback native-names (System/getProperty "os.arch"))) (defn platform-nullsink "Returns a file destination that will discard output." [] (io/file (if (= :windows (get-os)) "NUL" "/dev/null"))) ;; The ordering on map-vals and filter-vals may seem strange, but it helps out ;; if you want to do stuff like (update m :foo map-vals f extra-args) (defn map-vals "Like 'update', but for all values in a map." [m f & args] (zipmap (keys m) (map #(apply f % args) (vals m)))) (defn filter-vals "Like filter, but for values over a map: If pred is satisfied on a value in m, then its entry is preserved, otherwise it is removed." [m pred] (->> (filter #(pred (val %)) m) (into {}))) ;; # Git ;; This is very similar to the read-file function above. The only differences ;; are the error messages and the transformations done on the content. (defn- git-file-contents "Returns the (trimmed) contents by the given git path, or nil if it is inacessible or nonexisting. If it exists and is not readable, a warning is printed." [git-dir ref-path] (let [ref (io/file git-dir ref-path)] (if (.canRead ref) (.trim (slurp ref)) (do (when (.exists ref) TODO : use main / warn for this in 3.0 (println "Warning: Contents of git file" (str ".git/" ref-path) "is not readable.") (println "(Check that you have the right permissions to read" "the .git repo)"))) nil)))) (defn ^:internal resolve-git-dir [project] (let [alternate-git-root (io/file (get-in project [:scm :dir])) git-dir-file (io/file (or alternate-git-root (:root project)) ".git")] (if (and (.isFile git-dir-file) (.canRead git-dir-file)) (io/file (second (re-find #"gitdir: (\S+)" (slurp (str git-dir-file))))) git-dir-file))) (defn- read-git-ref "Reads the commit SHA1 for a git ref path, or nil if no commit exist." [git-dir ref-path] (git-file-contents git-dir ref-path)) (defn- read-git-head-file "Reads the current value of HEAD by attempting to read .git/HEAD, returning the SHA1 or nil if none exists." [git-dir] (some->> (git-file-contents git-dir "HEAD") (re-find #"ref: (\S+)") (second) (read-git-ref git-dir))) ;; TODO: de-dupe with pom namespace (3.0?) (defn ^:internal read-git-head "Reads the value of HEAD and returns a commit SHA1, or nil if no commit exist." [git-dir] (try (let [git-ref (sh/sh "git" "rev-parse" "HEAD" :dir git-dir)] (if (= (:exit git-ref) 0) (.trim (:out git-ref)) (read-git-head-file git-dir))) (catch java.io.IOException e (read-git-head-file git-dir)))) (defn last-distinct "Like distinct, but retains the last version instead of the first version of a duplicate." [coll] (reverse (distinct (reverse coll)))) Inspired by distinct - by from medley ( ) , ;; also under the EPL 1.0. (defn last-distinct-by "Returns a lazy sequence of the elements of coll, removing any elements that return duplicate values when passed to a function f. Only the last element that is a duplicate is preserved." [f coll] (let [step (fn step [xs seen] (lazy-seq ((fn [[x :as xs] seen] (when-let [s (seq xs)] (let [fx (f x)] (if (contains? seen fx) (recur (rest s) seen) (cons x (step (rest s) (conj seen fx))))))) xs seen)))] (reverse (step (reverse coll) #{})))) (defn ancestor? "Is a an ancestor of b?" [a b] (let [hypothetical-ancestor (.getCanonicalPath (io/file a)) hypothetical-descendant (.getCanonicalPath (io/file b))] (and (.startsWith hypothetical-descendant hypothetical-ancestor) (not (= hypothetical-descendant hypothetical-ancestor))))) (defmacro with-system-out-str "Like with-out-str, but for System/out." [& body] `(try (let [o# (ByteArrayOutputStream.)] (System/setOut (PrintStream. o#)) ~@body (.toString o#)) (finally (System/setOut (-> FileDescriptor/out FileOutputStream. PrintStream.))))) (defmacro with-system-err-str "Like with-out-str, but for System/err." [& body] `(try (let [o# (ByteArrayOutputStream.)] (System/setErr (PrintStream. o#)) ~@body (.toString o#)) (finally (System/setErr (-> FileDescriptor/err FileOutputStream. PrintStream.))))) (defn strip-properties-comments "Takes a string containing serialized java.util.Properties and removes all the comment lines (those beginning with #)" [s] (str/replace s #"(\A|\R)(#.+(\R|\z))+" "$1"))
null
https://raw.githubusercontent.com/technomancy/leiningen/24fb93936133bd7fc30c393c127e9e69bb5f2392/leiningen-core/src/leiningen/core/utils.clj
clojure
whyyyyy does .mkdirs fail silently ugh (io/file nil) returns nil, so we mimic a similar API instead of failing eagerly on nil inputs. The ordering on map-vals and filter-vals may seem strange, but it helps out if you want to do stuff like (update m :foo map-vals f extra-args) # Git This is very similar to the read-file function above. The only differences are the error messages and the transformations done on the content. TODO: de-dupe with pom namespace (3.0?) also under the EPL 1.0.
(ns leiningen.core.utils (:require [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.string :as str]) (:import (com.hypirion.io RevivableInputStream) (clojure.lang LineNumberingPushbackReader) (java.io ByteArrayOutputStream PrintStream File FileDescriptor FileOutputStream FileInputStream InputStreamReader) (java.net URL) (java.nio.file Files) (java.nio.file.attribute PosixFilePermissions))) (defn create-tmpdir "Creates a temporary directory in parent (something clojure.java.io/as-path can handle) with the specified permissions string (something PosixFilePermissions/asFileAttribute can handle i.e. \"rw-------\") and returns its Path." [parent prefix permissions] (let [nio-path (.toPath (io/as-file parent)) perms (PosixFilePermissions/fromString permissions) attr (PosixFilePermissions/asFileAttribute perms)] (Files/createTempDirectory nio-path prefix (into-array [attr])))) (def rebound-io? (atom false)) (defn rebind-io! [] (when-not @rebound-io? (let [new-in (-> FileDescriptor/in FileInputStream. RevivableInputStream.)] (System/setIn new-in) (.bindRoot #'*in* (-> new-in InputStreamReader. LineNumberingPushbackReader.))) (reset! rebound-io? true))) (defn build-url "Creates java.net.URL from string" [url] (try (URL. url) (catch java.net.MalformedURLException _ (URL. (str "http://" url))))) (defmacro with-write-permissions "Runs body only if path is writeable, or - if it does not already exist - can be created." [path & body] `(let [p# ~path f# (new File p#)] (if (or (and (.exists f#) (.canWrite f#)) (and (not (.exists f#)) (some-> f# .getParentFile .canWrite))) (do ~@body) (throw (java.io.IOException. (str "Permission denied. Please check your access rights for " p#)))))) (defn read-file "Returns the first Clojure form in a file if it exists." [file] (if (.exists file) (try (read-string (slurp file)) (catch Exception e TODO : use main / warn for this in 3.0 (println "Error reading" (.getName file) "from" (.getParent file)) (if (zero? (.length file)) (println "File cannot be empty") (if (.contains (.getMessage e) "EOF while reading") (println "Invalid content was found") (println (.getMessage e))))))))) (defn symlink? "Checks if a File is a symbolic link or points to another file." [file] (let [canon (if-not (.getParent file) file (-> (.. file getParentFile getCanonicalFile) (File. (.getName file))))] (not= (.getCanonicalFile canon) (.getAbsoluteFile canon)))) (defn mkdirs "Make a given directory and its parents, but throw an Exception on failure." (when-not (or (.mkdirs (io/file f)) (.exists (io/file f))) (throw (Exception. (str "Couldn't create directories: " (io/file f))))))) (defn relativize "Makes the filepath path relative to base. Assumes base is an ancestor to path, and that the path contains no '..'." [base path] TODO : When moving to Java 1.7 , use Path 's relativize instead (let [base-uri (.toURI (io/file base)) path-uri (.toURI (io/file path))] (.. base-uri (relativize path-uri) (getPath)))) (defn ns-exists? [namespace] (or (find-ns (symbol namespace)) (some (fn [suffix] (-> (#'clojure.core/root-resource namespace) (subs 1) (str suffix) io/resource)) [".clj" ".cljc" (str clojure.lang.RT/LOADER_SUFFIX ".class")]))) (defn error [& args] TODO : use main / warn for this in 3.0 (apply println "Error:" args))) (defn require-resolve "Resolve a fully qualified symbol by first requiring its namespace." ([sym] (if-let [ns (namespace sym)] (when (ns-exists? ns) (let [ns (symbol ns)] (when-not (find-ns ns) (require ns))) (resolve sym)) (resolve sym))) ([ns sym] (require-resolve (symbol ns sym)))) # OS detection (defn- get-by-pattern "Gets a value from map m, but uses the keys as regex patterns, trying to match against k instead of doing an exact match." [m k] (m (first (drop-while #(nil? (re-find (re-pattern %) k)) (keys m))))) (defn- get-with-pattern-fallback "Gets a value from map m, but if it doesn't exist, fallback to use get-by-pattern." [m k] (let [exact-match (m k)] (if (nil? exact-match) (get-by-pattern m k) exact-match))) (def ^:private native-names {"Mac OS X" :macosx "Windows" :windows "Linux" :linux "FreeBSD" :freebsd "OpenBSD" :openbsd "amd64" :x86_64 "x86_64" :x86_64 "x86" :x86 "i386" :x86 "arm" :arm "SunOS" :solaris "sparc" :sparc "Darwin" :macosx "aarch64" :aarch_64}) (defn get-os "Returns a keyword naming the host OS." [] (get-with-pattern-fallback native-names (System/getProperty "os.name"))) (defn get-arch "Returns a keyword naming the host architecture" [] (get-with-pattern-fallback native-names (System/getProperty "os.arch"))) (defn platform-nullsink "Returns a file destination that will discard output." [] (io/file (if (= :windows (get-os)) "NUL" "/dev/null"))) (defn map-vals "Like 'update', but for all values in a map." [m f & args] (zipmap (keys m) (map #(apply f % args) (vals m)))) (defn filter-vals "Like filter, but for values over a map: If pred is satisfied on a value in m, then its entry is preserved, otherwise it is removed." [m pred] (->> (filter #(pred (val %)) m) (into {}))) (defn- git-file-contents "Returns the (trimmed) contents by the given git path, or nil if it is inacessible or nonexisting. If it exists and is not readable, a warning is printed." [git-dir ref-path] (let [ref (io/file git-dir ref-path)] (if (.canRead ref) (.trim (slurp ref)) (do (when (.exists ref) TODO : use main / warn for this in 3.0 (println "Warning: Contents of git file" (str ".git/" ref-path) "is not readable.") (println "(Check that you have the right permissions to read" "the .git repo)"))) nil)))) (defn ^:internal resolve-git-dir [project] (let [alternate-git-root (io/file (get-in project [:scm :dir])) git-dir-file (io/file (or alternate-git-root (:root project)) ".git")] (if (and (.isFile git-dir-file) (.canRead git-dir-file)) (io/file (second (re-find #"gitdir: (\S+)" (slurp (str git-dir-file))))) git-dir-file))) (defn- read-git-ref "Reads the commit SHA1 for a git ref path, or nil if no commit exist." [git-dir ref-path] (git-file-contents git-dir ref-path)) (defn- read-git-head-file "Reads the current value of HEAD by attempting to read .git/HEAD, returning the SHA1 or nil if none exists." [git-dir] (some->> (git-file-contents git-dir "HEAD") (re-find #"ref: (\S+)") (second) (read-git-ref git-dir))) (defn ^:internal read-git-head "Reads the value of HEAD and returns a commit SHA1, or nil if no commit exist." [git-dir] (try (let [git-ref (sh/sh "git" "rev-parse" "HEAD" :dir git-dir)] (if (= (:exit git-ref) 0) (.trim (:out git-ref)) (read-git-head-file git-dir))) (catch java.io.IOException e (read-git-head-file git-dir)))) (defn last-distinct "Like distinct, but retains the last version instead of the first version of a duplicate." [coll] (reverse (distinct (reverse coll)))) Inspired by distinct - by from medley ( ) , (defn last-distinct-by "Returns a lazy sequence of the elements of coll, removing any elements that return duplicate values when passed to a function f. Only the last element that is a duplicate is preserved." [f coll] (let [step (fn step [xs seen] (lazy-seq ((fn [[x :as xs] seen] (when-let [s (seq xs)] (let [fx (f x)] (if (contains? seen fx) (recur (rest s) seen) (cons x (step (rest s) (conj seen fx))))))) xs seen)))] (reverse (step (reverse coll) #{})))) (defn ancestor? "Is a an ancestor of b?" [a b] (let [hypothetical-ancestor (.getCanonicalPath (io/file a)) hypothetical-descendant (.getCanonicalPath (io/file b))] (and (.startsWith hypothetical-descendant hypothetical-ancestor) (not (= hypothetical-descendant hypothetical-ancestor))))) (defmacro with-system-out-str "Like with-out-str, but for System/out." [& body] `(try (let [o# (ByteArrayOutputStream.)] (System/setOut (PrintStream. o#)) ~@body (.toString o#)) (finally (System/setOut (-> FileDescriptor/out FileOutputStream. PrintStream.))))) (defmacro with-system-err-str "Like with-out-str, but for System/err." [& body] `(try (let [o# (ByteArrayOutputStream.)] (System/setErr (PrintStream. o#)) ~@body (.toString o#)) (finally (System/setErr (-> FileDescriptor/err FileOutputStream. PrintStream.))))) (defn strip-properties-comments "Takes a string containing serialized java.util.Properties and removes all the comment lines (those beginning with #)" [s] (str/replace s #"(\A|\R)(#.+(\R|\z))+" "$1"))
05aeb9f51678686409d62157147fdba22865b802b6d457d3866bda9d57bf92a0
ddssff/refact-global-hse
FoldM.hs
-- | 'foldModule' is a utility function used to implement the clean, split, and merge operations. # LANGUAGE BangPatterns , CPP , FlexibleContexts , FlexibleInstances , ScopedTypeVariables , StandaloneDeriving # # OPTIONS_GHC -Wall -fno - warn - orphans # module FoldM ( foldModuleM , foldHeaderM , foldExportsM , foldImportsM , foldDeclsM , echoM , echo2M , ignoreM , ignore2M ) where import Control.Monad (when) import Control.Monad.State (get, put, runState, runStateT, State, StateT) import Control.Monad.Trans (lift) import Data.Char (isSpace) import Data.List (tails) import Data.Monoid ((<>)) import Data.Sequence (Seq, (|>)) import qualified Language.Haskell.Exts.Annotated.Syntax (Annotated(..), Decl, ExportSpec, ExportSpec(..), ExportSpecList(ExportSpecList), ImportDecl, Module(..), ModuleHead(..), ModuleName, ModulePragma, WarningText) import Language.Haskell.Exts.Comments (Comment(..)) import Language.Haskell.Exts.SrcLoc (SrcLoc(..), SrcSpan(..), SrcSpanInfo(..)) import SrcLoc (increaseSrcLoc, srcPairText) import Types (ModuleInfo(ModuleInfo, _module, _moduleComments, _moduleText)) type Module = A.Module SrcSpanInfo type ModuleHead = A.ModuleHead SrcSpanInfo type ModulePragma = A.ModulePragma SrcSpanInfo type ModuleName = A.ModuleName SrcSpanInfo type WarningText = A.WarningText SrcSpanInfo type ExportSpec = A.ExportSpec SrcSpanInfo type ImportDecl = A.ImportDecl SrcSpanInfo type Decl = A.Decl SrcSpanInfo class Spans a where spans :: a -> [SrcSpanInfo] instance Spans (A.Module SrcSpanInfo) where spans (A.Module _sp mh ps is ds) = concatMap spans ps ++ maybe [] spans mh ++ concatMap spans is ++ concatMap spans ds spans _ = error "spans XML module" instance Spans (A.ModuleHead SrcSpanInfo) where spans (A.ModuleHead _ n mw me) = spans n ++ maybe [] spans mw ++ maybe [] spans me instance Spans (A.ExportSpecList SrcSpanInfo) where spans (A.ExportSpecList _ es) = concatMap spans es instance Spans (A.ExportSpec SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ModulePragma SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ImportDecl SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.Decl SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ModuleName SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.WarningText SrcSpanInfo) where spans x = [A.ann x] data St = St { loc_ :: SrcLoc , text_ :: String , comms_ :: [Comment] , sps_ :: [SrcSpanInfo] } deriving (Show) srcLoc' :: SrcSpanInfo -> SrcLoc srcLoc' = srcLoc'' . srcInfoSpan endLoc' :: SrcSpanInfo -> SrcLoc endLoc' = endLoc'' . srcInfoSpan srcLoc'' :: SrcSpan -> SrcLoc srcLoc'' (SrcSpan f b e _ _) = SrcLoc f b e endLoc'' :: SrcSpan -> SrcLoc endLoc'' (SrcSpan f _ _ b e) = SrcLoc f b e setSpanEnd :: SrcLoc -> SrcSpan -> SrcSpan setSpanEnd loc sp = sp {srcSpanEndLine = srcLine loc, srcSpanEndColumn = srcColumn loc} -- setSpanStart :: SrcLoc -> SrcSpan -> SrcSpan setSpanStart loc sp = sp { srcSpanStartLine = , srcSpanStartColumn = srcColumn loc } | The spans returned by may put comments and -- whitespace in the suffix string of a declaration, we want them in -- the prefix string of the following declaration where possible. adjustSpans :: String -> [Comment] -> [SrcSpanInfo] -> [SrcSpanInfo] adjustSpans _ _ [] = [] adjustSpans _ _ [x] = [x] adjustSpans text comments sps@(x : _) = fst $ runState f (St (SrcLoc (srcFilename (srcLoc' x)) 1 1) text comments sps) where f = do st <- get let b = loc_ st case sps_ st of (ss1 : ssis) -> do skip st' <- get let e = loc_ st' case e >= endLoc' ss1 of True -> -- We reached the end of ss1, so the segment from b to e is -- trailing comments and space, some of which may belong in -- the following span. do put (st' {sps_ = ssis}) sps' <- f let ss1' = ss1 {srcInfoSpan = setSpanEnd b (srcInfoSpan ss1)} return (ss1' : sps') False -> -- If we weren't able to skip to the end of -- the span, we encountered real text. Move past one char and try again . do case text_ st' of "" -> return (sps_ st') -- error $ "Ran out of text\n st=" ++ show st ++ "\n st'=" ++ show st' (c : t') -> do put (st' {text_ = t', loc_ = increaseSrcLoc [c] e}) f sss -> return sss loc is the current position in the input file , text -- is the text starting at that location. skip :: State St () skip = do loc1 <- loc_ <$> get skipWhite skipComment loc2 <- loc_ <$> get -- Repeat until failure when (loc1 /= loc2) skip skipWhite :: State St () skipWhite = do st <- get case span isSpace (text_ st) of ("", _) -> return () (space, t') -> let loc' = increaseSrcLoc space (loc_ st) in put (st {loc_ = loc', text_ = t'}) skipComment :: State St () skipComment = do st <- get case comms_ st of (Comment _ csp _ : cs) | srcLoc'' csp <= loc_ st -> -- We reached the comment, skip past it and discard case srcPairText (loc_ st, endLoc'' csp) (text_ st) of ("", _) -> return () (comm, t') -> let loc' = increaseSrcLoc comm (loc_ st) in put (st {loc_ = loc', text_ = t', comms_ = cs}) _ -> return () -- No comments, or we didn't reach it -- | Given the result of parseModuleWithComments and the original -- module text, this does a fold over the parsed module contents, calling the seven argument functions in order . Each function is passed the AST value , the text of the space and comments leading up -- to the element, and the text for the element. Note that not -- everything passed to the "pre" argument of the functions will be -- comments and space - for example, the "module" keyword will be passed in the pre argument to the ModuleName function . foldModuleM :: forall m r. (Monad m, Functor m, Show r) => ^ Receives the space before the first pragma . ^ Called once for each pragma . In this and the similar arguments below , the three string arguments contain -- the comments and space preceding the construct, the text of the construct and the space following it. -> (ModuleName -> String -> String -> String -> r -> m r) -- ^ Called with the module name. -> (WarningText -> String -> String -> String -> r -> m r) -- ^ Called with the warning text between module name and export list -> (String -> r -> m r) -- ^ Called with the export list open paren -> (ExportSpec -> String -> String -> String -> r -> m r) -- ^ Called with each export specifier ^ Called with the export list close paren and " where " keyword -> (ImportDecl -> String -> String -> String -> r -> m r) -- ^ Called with each import declarator -> (Decl -> String -> String -> String -> r -> m r) -- ^ Called with each top level declaration -> (String -> r -> m r) -- ^ Called with comments following the last declaration ^ module -> r -- ^ Fold initialization value -> m r -- ^ Result foldModuleM _ _ _ _ _ _ _ _ _ _ (ModuleInfo {_module = A.XmlPage _ _ _ _ _ _ _}) _ = error "XmlPage: unsupported" foldModuleM _ _ _ _ _ _ _ _ _ _ (ModuleInfo {_module = A.XmlHybrid _ _ _ _ _ _ _ _ _}) _ = error "XmlHybrid: unsupported" foldModuleM topf pragmaf namef warnf pref exportf postf importf declf sepf (ModuleInfo {_module = m@(A.Module (SrcSpanInfo (SrcSpan path _ _ _ _) _) mh ps is ds), _moduleText = text, _moduleComments = comments}) r0 = (\ (_, (_, _, _, r)) -> r) <$> runStateT doModule (text, (SrcLoc path 1 1), spans m, r0) where doModule :: Monad m => StateT (String, SrcLoc, [SrcSpanInfo], r) m () doModule = do doSep topf doList pragmaf ps maybe (pure ()) doHeader mh (tl, l, sps, r) <- get put (tl, l, adjustSpans text comments sps, r) doList importf is doList declf ds doTail sepf doHeader :: Monad m => A.ModuleHead SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doHeader (A.ModuleHead sp n mw me) = do doItem namef n maybe (pure ()) (doItem warnf) mw doSep pref maybe (pure ()) (\ (A.ExportSpecList _ es) -> doList exportf es) me doClose postf sp doClose :: Monad m => (String -> r -> m r) -> SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doClose f sp = do (tl, l, sps, r) <- get case l < endLoc' sp of True -> do let (p, s) = srcPairText (l, endLoc' sp) tl r' <- lift $ f p r put (s, endLoc' sp, sps, r') False -> pure () doTail :: Monad m => (String -> r -> m r) -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doTail f = do (tl, l, sps, r) <- get r' <- lift $ f tl r put (tl, l, sps, r') doSep :: Monad m => (String -> r -> m r) -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doSep f = do p <- get case p of (tl, l, sps@(sp : _), r) -> do let l' = srcLoc' sp case l <= l' of True -> do let (b, a) = srcPairText (l, l') tl r' <- lift $ f b r put (a, l', sps, r') False -> pure () _ -> error $ "foldModule - out of spans: " ++ show p doList :: (A.Annotated a, Show (a SrcSpanInfo)) => (a SrcSpanInfo -> String -> String -> String -> r -> m r) -> [a SrcSpanInfo] -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doList _ [] = pure () doList f (x : xs) = doItem f x >> doList f xs doItem :: (A.Annotated a, Show (a SrcSpanInfo)) => (a SrcSpanInfo -> String -> String -> String -> r -> m r) -> a SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doItem f x = do (tl, l, (sp : sps'), r) <- get bug ? If a module ends -- with no newline, endLoc will be at the beginning -- of the following (nonexistant) line. (pre, tl') = srcPairText (l, srcLoc' sp) tl l' = endLoc' sp (s, tl'') = srcPairText (srcLoc' sp, l') tl' l'' = adjust1 tl'' l' (post, tl''') = srcPairText (l', l'') tl'' r' <- lift $ f x pre s post r put (tl''', l'', sps', r') -- Move to just past the last newline in the leading whitespace adjust " \n \n hello\n " ( SrcLoc " < unknown>.hs " 5 5 ) - > ( SrcLoc " < unknown>.hs " 7 1 ) _adjust :: String -> SrcLoc -> SrcLoc _adjust a l = l' where w = takeWhile isSpace a w' = take (length (takeWhile (elem '\n') (tails w))) w l' = increaseSrcLoc w' l Move to just past the first newline in the leading whitespace adjust " \n \n hello\n " ( SrcLoc " < unknown>.hs " 5 5 ) - > ( SrcLoc " < unknown>.hs " 6 1 ) adjust1 :: String -> SrcLoc -> SrcLoc adjust1 a l = l' where w = takeWhile isSpace a w' = case span (/= '\n') w of (w'', '\n' : _) -> w'' ++ ['\n'] (w'', "") -> w'' _ -> error "Impossible: span stopped on the wrong char" l' = increaseSrcLoc w' l -- | Do just the header portion of 'foldModule'. foldHeaderM :: forall m r. (Monad m, Show r) => (String -> r -> m r) -> (ModulePragma -> String -> String -> String -> r -> m r) -> (ModuleName -> String -> String -> String -> r -> m r) -> (WarningText -> String -> String -> String -> r -> m r) -> ModuleInfo -> r -> m r foldHeaderM topf pragmaf namef warnf m r0 = foldModuleM topf pragmaf namef warnf ignore2M ignoreM ignore2M ignoreM ignoreM ignore2M m r0 -- | Do just the exports portion of 'foldModule'. foldExportsM :: forall m r. (Monad m, Show r) => (String -> r -> m r) -> (ExportSpec -> String -> String -> String -> r -> m r) -> (String -> r -> m r) -> ModuleInfo -> r -> m r foldExportsM pref exportf postf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM pref exportf postf ignoreM ignoreM ignore2M m r0 -- | Do just the imports portion of 'foldModule'. foldImportsM :: forall m r. (Monad m, Show r) => (ImportDecl -> String -> String -> String -> r -> m r) -> ModuleInfo -> r -> m r foldImportsM importf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM ignore2M ignoreM ignore2M importf ignoreM ignore2M m r0 -- | Do just the declarations portion of 'foldModule'. foldDeclsM :: forall m r. (Monad m, Show r) => (Decl -> String -> String -> String -> r -> m r) -> (String -> r -> m r) -> ModuleInfo -> r -> m r foldDeclsM declf sepf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM ignore2M ignoreM ignore2M ignoreM declf sepf m r0 -- | This can be passed to foldModule to include the original text in the result echoM :: (Monoid s, Monad m) => t -> s -> s -> s -> Seq s -> m (Seq s) echoM _ pref s suff r = pure $ r |> pref <> s <> suff | Similar to ' echo ' , but used for the two argument separator functions echo2M :: (Monoid s, Monad m) => s -> Seq s -> m (Seq s) echo2M s r = pure $ r |> s -- | This can be passed to foldModule to omit the original text from the result. ignoreM :: forall t s m r. Monad m => t -> s -> s -> s -> r -> m r ignoreM _ _ _ _ r = pure r | Similar to ' ignore ' , but used for the two argument separator functions ignore2M :: forall s m r. Monad m => s -> r -> m r ignore2M _ r = pure r -- | Update a SrcLoc to move it from l past the string argument. increaseSrcLoc :: String -> SrcLoc -> SrcLoc increaseSrcLoc "" l = l increaseSrcLoc ('\n' : s) (SrcLoc f y _) = increaseSrcLoc s (SrcLoc f (y + 1) 1) increaseSrcLoc (_ : s) (SrcLoc f y x) = increaseSrcLoc s (SrcLoc f y (x + 1))
null
https://raw.githubusercontent.com/ddssff/refact-global-hse/519a017009cae8aa1a3db1b46eb560d76bd9895d/old/FoldM.hs
haskell
| 'foldModule' is a utility function used to implement the clean, split, and merge operations. setSpanStart :: SrcLoc -> SrcSpan -> SrcSpan whitespace in the suffix string of a declaration, we want them in the prefix string of the following declaration where possible. We reached the end of ss1, so the segment from b to e is trailing comments and space, some of which may belong in the following span. If we weren't able to skip to the end of the span, we encountered real text. error $ "Ran out of text\n st=" ++ show st ++ "\n st'=" ++ show st' is the text starting at that location. Repeat until failure We reached the comment, skip past it and discard No comments, or we didn't reach it | Given the result of parseModuleWithComments and the original module text, this does a fold over the parsed module contents, to the element, and the text for the element. Note that not everything passed to the "pre" argument of the functions will be comments and space - for example, the "module" keyword will be the comments and space preceding the construct, the text of the construct and the space following it. ^ Called with the module name. ^ Called with the warning text between module name and export list ^ Called with the export list open paren ^ Called with each export specifier ^ Called with each import declarator ^ Called with each top level declaration ^ Called with comments following the last declaration ^ Fold initialization value ^ Result with no newline, endLoc will be at the beginning of the following (nonexistant) line. Move to just past the last newline in the leading whitespace | Do just the header portion of 'foldModule'. | Do just the exports portion of 'foldModule'. | Do just the imports portion of 'foldModule'. | Do just the declarations portion of 'foldModule'. | This can be passed to foldModule to include the original text in the result | This can be passed to foldModule to omit the original text from the result. | Update a SrcLoc to move it from l past the string argument.
# LANGUAGE BangPatterns , CPP , FlexibleContexts , FlexibleInstances , ScopedTypeVariables , StandaloneDeriving # # OPTIONS_GHC -Wall -fno - warn - orphans # module FoldM ( foldModuleM , foldHeaderM , foldExportsM , foldImportsM , foldDeclsM , echoM , echo2M , ignoreM , ignore2M ) where import Control.Monad (when) import Control.Monad.State (get, put, runState, runStateT, State, StateT) import Control.Monad.Trans (lift) import Data.Char (isSpace) import Data.List (tails) import Data.Monoid ((<>)) import Data.Sequence (Seq, (|>)) import qualified Language.Haskell.Exts.Annotated.Syntax (Annotated(..), Decl, ExportSpec, ExportSpec(..), ExportSpecList(ExportSpecList), ImportDecl, Module(..), ModuleHead(..), ModuleName, ModulePragma, WarningText) import Language.Haskell.Exts.Comments (Comment(..)) import Language.Haskell.Exts.SrcLoc (SrcLoc(..), SrcSpan(..), SrcSpanInfo(..)) import SrcLoc (increaseSrcLoc, srcPairText) import Types (ModuleInfo(ModuleInfo, _module, _moduleComments, _moduleText)) type Module = A.Module SrcSpanInfo type ModuleHead = A.ModuleHead SrcSpanInfo type ModulePragma = A.ModulePragma SrcSpanInfo type ModuleName = A.ModuleName SrcSpanInfo type WarningText = A.WarningText SrcSpanInfo type ExportSpec = A.ExportSpec SrcSpanInfo type ImportDecl = A.ImportDecl SrcSpanInfo type Decl = A.Decl SrcSpanInfo class Spans a where spans :: a -> [SrcSpanInfo] instance Spans (A.Module SrcSpanInfo) where spans (A.Module _sp mh ps is ds) = concatMap spans ps ++ maybe [] spans mh ++ concatMap spans is ++ concatMap spans ds spans _ = error "spans XML module" instance Spans (A.ModuleHead SrcSpanInfo) where spans (A.ModuleHead _ n mw me) = spans n ++ maybe [] spans mw ++ maybe [] spans me instance Spans (A.ExportSpecList SrcSpanInfo) where spans (A.ExportSpecList _ es) = concatMap spans es instance Spans (A.ExportSpec SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ModulePragma SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ImportDecl SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.Decl SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.ModuleName SrcSpanInfo) where spans x = [A.ann x] instance Spans (A.WarningText SrcSpanInfo) where spans x = [A.ann x] data St = St { loc_ :: SrcLoc , text_ :: String , comms_ :: [Comment] , sps_ :: [SrcSpanInfo] } deriving (Show) srcLoc' :: SrcSpanInfo -> SrcLoc srcLoc' = srcLoc'' . srcInfoSpan endLoc' :: SrcSpanInfo -> SrcLoc endLoc' = endLoc'' . srcInfoSpan srcLoc'' :: SrcSpan -> SrcLoc srcLoc'' (SrcSpan f b e _ _) = SrcLoc f b e endLoc'' :: SrcSpan -> SrcLoc endLoc'' (SrcSpan f _ _ b e) = SrcLoc f b e setSpanEnd :: SrcLoc -> SrcSpan -> SrcSpan setSpanEnd loc sp = sp {srcSpanEndLine = srcLine loc, srcSpanEndColumn = srcColumn loc} setSpanStart loc sp = sp { srcSpanStartLine = , srcSpanStartColumn = srcColumn loc } | The spans returned by may put comments and adjustSpans :: String -> [Comment] -> [SrcSpanInfo] -> [SrcSpanInfo] adjustSpans _ _ [] = [] adjustSpans _ _ [x] = [x] adjustSpans text comments sps@(x : _) = fst $ runState f (St (SrcLoc (srcFilename (srcLoc' x)) 1 1) text comments sps) where f = do st <- get let b = loc_ st case sps_ st of (ss1 : ssis) -> do skip st' <- get let e = loc_ st' case e >= endLoc' ss1 of True -> do put (st' {sps_ = ssis}) sps' <- f let ss1' = ss1 {srcInfoSpan = setSpanEnd b (srcInfoSpan ss1)} return (ss1' : sps') False -> Move past one char and try again . do case text_ st' of (c : t') -> do put (st' {text_ = t', loc_ = increaseSrcLoc [c] e}) f sss -> return sss loc is the current position in the input file , text skip :: State St () skip = do loc1 <- loc_ <$> get skipWhite skipComment loc2 <- loc_ <$> get when (loc1 /= loc2) skip skipWhite :: State St () skipWhite = do st <- get case span isSpace (text_ st) of ("", _) -> return () (space, t') -> let loc' = increaseSrcLoc space (loc_ st) in put (st {loc_ = loc', text_ = t'}) skipComment :: State St () skipComment = do st <- get case comms_ st of (Comment _ csp _ : cs) | srcLoc'' csp <= loc_ st -> case srcPairText (loc_ st, endLoc'' csp) (text_ st) of ("", _) -> return () (comm, t') -> let loc' = increaseSrcLoc comm (loc_ st) in put (st {loc_ = loc', text_ = t', comms_ = cs}) calling the seven argument functions in order . Each function is passed the AST value , the text of the space and comments leading up passed in the pre argument to the ModuleName function . foldModuleM :: forall m r. (Monad m, Functor m, Show r) => ^ Receives the space before the first pragma . ^ Called once for each pragma . In this and the similar arguments below , the three string arguments contain ^ Called with the export list close paren and " where " keyword ^ module foldModuleM _ _ _ _ _ _ _ _ _ _ (ModuleInfo {_module = A.XmlPage _ _ _ _ _ _ _}) _ = error "XmlPage: unsupported" foldModuleM _ _ _ _ _ _ _ _ _ _ (ModuleInfo {_module = A.XmlHybrid _ _ _ _ _ _ _ _ _}) _ = error "XmlHybrid: unsupported" foldModuleM topf pragmaf namef warnf pref exportf postf importf declf sepf (ModuleInfo {_module = m@(A.Module (SrcSpanInfo (SrcSpan path _ _ _ _) _) mh ps is ds), _moduleText = text, _moduleComments = comments}) r0 = (\ (_, (_, _, _, r)) -> r) <$> runStateT doModule (text, (SrcLoc path 1 1), spans m, r0) where doModule :: Monad m => StateT (String, SrcLoc, [SrcSpanInfo], r) m () doModule = do doSep topf doList pragmaf ps maybe (pure ()) doHeader mh (tl, l, sps, r) <- get put (tl, l, adjustSpans text comments sps, r) doList importf is doList declf ds doTail sepf doHeader :: Monad m => A.ModuleHead SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doHeader (A.ModuleHead sp n mw me) = do doItem namef n maybe (pure ()) (doItem warnf) mw doSep pref maybe (pure ()) (\ (A.ExportSpecList _ es) -> doList exportf es) me doClose postf sp doClose :: Monad m => (String -> r -> m r) -> SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doClose f sp = do (tl, l, sps, r) <- get case l < endLoc' sp of True -> do let (p, s) = srcPairText (l, endLoc' sp) tl r' <- lift $ f p r put (s, endLoc' sp, sps, r') False -> pure () doTail :: Monad m => (String -> r -> m r) -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doTail f = do (tl, l, sps, r) <- get r' <- lift $ f tl r put (tl, l, sps, r') doSep :: Monad m => (String -> r -> m r) -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doSep f = do p <- get case p of (tl, l, sps@(sp : _), r) -> do let l' = srcLoc' sp case l <= l' of True -> do let (b, a) = srcPairText (l, l') tl r' <- lift $ f b r put (a, l', sps, r') False -> pure () _ -> error $ "foldModule - out of spans: " ++ show p doList :: (A.Annotated a, Show (a SrcSpanInfo)) => (a SrcSpanInfo -> String -> String -> String -> r -> m r) -> [a SrcSpanInfo] -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doList _ [] = pure () doList f (x : xs) = doItem f x >> doList f xs doItem :: (A.Annotated a, Show (a SrcSpanInfo)) => (a SrcSpanInfo -> String -> String -> String -> r -> m r) -> a SrcSpanInfo -> StateT (String, SrcLoc, [SrcSpanInfo], r) m () doItem f x = do (tl, l, (sp : sps'), r) <- get bug ? If a module ends (pre, tl') = srcPairText (l, srcLoc' sp) tl l' = endLoc' sp (s, tl'') = srcPairText (srcLoc' sp, l') tl' l'' = adjust1 tl'' l' (post, tl''') = srcPairText (l', l'') tl'' r' <- lift $ f x pre s post r put (tl''', l'', sps', r') adjust " \n \n hello\n " ( SrcLoc " < unknown>.hs " 5 5 ) - > ( SrcLoc " < unknown>.hs " 7 1 ) _adjust :: String -> SrcLoc -> SrcLoc _adjust a l = l' where w = takeWhile isSpace a w' = take (length (takeWhile (elem '\n') (tails w))) w l' = increaseSrcLoc w' l Move to just past the first newline in the leading whitespace adjust " \n \n hello\n " ( SrcLoc " < unknown>.hs " 5 5 ) - > ( SrcLoc " < unknown>.hs " 6 1 ) adjust1 :: String -> SrcLoc -> SrcLoc adjust1 a l = l' where w = takeWhile isSpace a w' = case span (/= '\n') w of (w'', '\n' : _) -> w'' ++ ['\n'] (w'', "") -> w'' _ -> error "Impossible: span stopped on the wrong char" l' = increaseSrcLoc w' l foldHeaderM :: forall m r. (Monad m, Show r) => (String -> r -> m r) -> (ModulePragma -> String -> String -> String -> r -> m r) -> (ModuleName -> String -> String -> String -> r -> m r) -> (WarningText -> String -> String -> String -> r -> m r) -> ModuleInfo -> r -> m r foldHeaderM topf pragmaf namef warnf m r0 = foldModuleM topf pragmaf namef warnf ignore2M ignoreM ignore2M ignoreM ignoreM ignore2M m r0 foldExportsM :: forall m r. (Monad m, Show r) => (String -> r -> m r) -> (ExportSpec -> String -> String -> String -> r -> m r) -> (String -> r -> m r) -> ModuleInfo -> r -> m r foldExportsM pref exportf postf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM pref exportf postf ignoreM ignoreM ignore2M m r0 foldImportsM :: forall m r. (Monad m, Show r) => (ImportDecl -> String -> String -> String -> r -> m r) -> ModuleInfo -> r -> m r foldImportsM importf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM ignore2M ignoreM ignore2M importf ignoreM ignore2M m r0 foldDeclsM :: forall m r. (Monad m, Show r) => (Decl -> String -> String -> String -> r -> m r) -> (String -> r -> m r) -> ModuleInfo -> r -> m r foldDeclsM declf sepf m r0 = foldModuleM ignore2M ignoreM ignoreM ignoreM ignore2M ignoreM ignore2M ignoreM declf sepf m r0 echoM :: (Monoid s, Monad m) => t -> s -> s -> s -> Seq s -> m (Seq s) echoM _ pref s suff r = pure $ r |> pref <> s <> suff | Similar to ' echo ' , but used for the two argument separator functions echo2M :: (Monoid s, Monad m) => s -> Seq s -> m (Seq s) echo2M s r = pure $ r |> s ignoreM :: forall t s m r. Monad m => t -> s -> s -> s -> r -> m r ignoreM _ _ _ _ r = pure r | Similar to ' ignore ' , but used for the two argument separator functions ignore2M :: forall s m r. Monad m => s -> r -> m r ignore2M _ r = pure r increaseSrcLoc :: String -> SrcLoc -> SrcLoc increaseSrcLoc "" l = l increaseSrcLoc ('\n' : s) (SrcLoc f y _) = increaseSrcLoc s (SrcLoc f (y + 1) 1) increaseSrcLoc (_ : s) (SrcLoc f y x) = increaseSrcLoc s (SrcLoc f y (x + 1))
84f46c5221763aa91f0212c12dbbc449beee3bffcba9750635a60fedd82bce0f
theobat/massalia
UtilsGQL.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE NoImplicitPrelude # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE FlexibleInstances # -- | Module : Massalia . UtilsGQL -- Description : A standard interface for query arguments (including pagination). module Massalia.UtilsGQL ( -- TEXT Paginated(..), defaultPaginated, OrderByWay (..), OrderingBy (..), NullsOrder (..), ) where import Data.Morpheus.Types (GQLType) import Data.Aeson (FromJSON, ToJSON) import Protolude | A normalized API for all paginated query . -- The filtered is for a simple filter, data Paginated filterType = Paginated | A filter applied _ _ before _ _ . unionFilter :: Maybe [filterType], | A filter applied _ _ before _ _ . unionFilterPaginated :: Maybe [Paginated filterType], -- | A filter applied __around__ the union of unionFilter effects globalFilter :: Maybe filterType, -- | The limit in the query first :: Maybe Int, -- | The offset in the query offset :: Maybe Int } deriving (Eq, Show, Generic, GQLType, FromJSON, ToJSON) defaultPaginated :: Paginated filterType defaultPaginated = Paginated Nothing Nothing Nothing Nothing Nothing data OrderByWay = ASC | DESC deriving (Eq, Show, Generic, GQLType) | Nulls first or nulls last . data NullsOrder = NFirst | NLast deriving (Eq, Show, Generic, GQLType) data OrderingBy a = OrderingBy { way :: OrderByWay, column :: a, nullsOrd :: Maybe NullsOrder } deriving (Eq, Show, Generic, GQLType)
null
https://raw.githubusercontent.com/theobat/massalia/66d65c3431132091107d07e041f33c907f9d08cb/src/Massalia/UtilsGQL.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # # LANGUAGE TypeSynonymInstances # | Description : A standard interface for query arguments (including pagination). TEXT The filtered is for a simple filter, | A filter applied __around__ the union of unionFilter effects | The limit in the query | The offset in the query
# LANGUAGE DeriveGeneric # # LANGUAGE NoImplicitPrelude # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # Module : Massalia . UtilsGQL module Massalia.UtilsGQL Paginated(..), defaultPaginated, OrderByWay (..), OrderingBy (..), NullsOrder (..), ) where import Data.Morpheus.Types (GQLType) import Data.Aeson (FromJSON, ToJSON) import Protolude | A normalized API for all paginated query . data Paginated filterType = Paginated | A filter applied _ _ before _ _ . unionFilter :: Maybe [filterType], | A filter applied _ _ before _ _ . unionFilterPaginated :: Maybe [Paginated filterType], globalFilter :: Maybe filterType, first :: Maybe Int, offset :: Maybe Int } deriving (Eq, Show, Generic, GQLType, FromJSON, ToJSON) defaultPaginated :: Paginated filterType defaultPaginated = Paginated Nothing Nothing Nothing Nothing Nothing data OrderByWay = ASC | DESC deriving (Eq, Show, Generic, GQLType) | Nulls first or nulls last . data NullsOrder = NFirst | NLast deriving (Eq, Show, Generic, GQLType) data OrderingBy a = OrderingBy { way :: OrderByWay, column :: a, nullsOrd :: Maybe NullsOrder } deriving (Eq, Show, Generic, GQLType)
844ee4c215a23d4996b9f6e3002b04cd20ce57ccda441353382161afcfa05824
noss/erlang-gettext
gettext_server.erl
%%%------------------------------------------------------------------- %%% File : gettext_server.erl Author : < > Desc . : Internationalization support . Created : 28 Oct 2003 by < > %%%------------------------------------------------------------------- -module(gettext_server). -behaviour(gen_server). %%-------------------------------------------------------------------- %% Include files %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- %% External exports -export([start_link/0, start_link/1, start_link/2, start/0, start/1, start/2]). %% Default callback functions -export([custom_dir/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("gettext.hrl"). -define(elog(X,Y), error_logger:info_msg("*elog ~p:~p: " X, [?MODULE, ?LINE | Y])). -define(SERVER, ?MODULE). -define(TABLE_NAME, gettext_server_db). -define(KEY(Lang,Key), {Key,Lang}). -define(ENTRY(Lang, Key, Val), {?KEY(Lang,Key), Val}). -record(state, { cbmod = ?MODULE, % callback module cache = [], % list_of( #cache{} ) gettext_dir, % Dir where all the data are stored table_name = ?TABLE_NAME % If several gettext_servers start then }). % tables must have different names %%% %%% Hold info about the languages stored. %%% -record(cache, { language = ?DEFAULT_LANG, charset = ?DEFAULT_CHARSET }). %%==================================================================== %% External functions %%==================================================================== %%-------------------------------------------------------------------- Function : start_link/0 %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> start_link(?MODULE). start_link(CallBackMod) -> start_link(CallBackMod, ?SERVER). start_link(CallBackMod, Name) -> gen_server:start_link({local, Name}, ?MODULE, [CallBackMod, Name],[]). %%-------------------------------------------------------------------- start() -> start(?MODULE). start(CallBackMod) -> start(CallBackMod, ?SERVER). start(CallBackMod, Name) -> gen_server:start({local, Name}, ?MODULE, [CallBackMod, Name], []). %%==================================================================== %% Server functions %%==================================================================== %%-------------------------------------------------------------------- %% Function: init/1 %% Description: Initiates the server %% Returns: {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %%-------------------------------------------------------------------- init([CallBackMod0, Name]) -> CallBackMod = get_callback_mod(CallBackMod0), GettextDir = get_gettext_dir(CallBackMod), TableNameStr = atom_to_list(Name) ++ "_db", TableName = list_to_atom(TableNameStr), Cache = create_db(TableName, GettextDir), {ok, #state{cache = Cache, cbmod = CallBackMod, gettext_dir = GettextDir, table_name = TableName}}. %%% %%% The GETTEXT_CBMOD environment variable takes precedence! %%% get_callback_mod(CallBackMod0) -> case os:getenv("GETTEXT_CBMOD") of false -> CallBackMod0; CbMod -> list_to_atom(CbMod) end. %%% The GETTEXT_DIR environment variable takes precedence ! %%% Next we will try to get hold of the value from the callback. %%% get_gettext_dir(CallBackMod) -> case os:getenv("GETTEXT_DIR") of false -> case catch CallBackMod:gettext_dir() of Dir when is_list(Dir) -> Dir; _ -> code:priv_dir(gettext) % fallback end; Dir -> Dir end. %% Default callback function custom_dir() -> code:priv_dir(gettext). %%-------------------------------------------------------------------- Function : handle_call/3 %% Description: Handling call messages %% Returns: {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | (terminate/2 is called) %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_call({key2str, Key, Lang}, _From, State) -> TableName = State#state.table_name, Reply = lookup(TableName, Lang, Key), {reply, Reply, State}; %% handle_call({lang2cset, Lang}, _From, State) -> Reply = case lists:keysearch(Lang, #cache.language, State#state.cache) of false -> {error, "not found"}; {value, C} -> {ok, C#cache.charset} end, {reply, Reply, State}; %% handle_call({store_pofile, Lang, File}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, case do_store_pofile(TableName, Lang, File, GettextDir, State#state.cache) of {ok, NewCache} -> {reply, ok, State#state{cache = NewCache}}; Else -> {reply, Else, State} end; handle_call(all_lcs, _From, State) -> TableName = State#state.table_name, Reply = all_lcs_internal(TableName), {reply, Reply, State}; %% handle_call({reload_custom_lang, Lang}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, case do_reload_custom_lang(TableName, GettextDir, Lang) of ok -> {reply, ok, State}; Else -> {reply, Else, State} end; %% handle_call({unload_custom_lang, Lang}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, {reply, do_unload_custom_lang(TableName, GettextDir, Lang), State}; %% handle_call(recreate_db, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, Fname = filename:join(GettextDir, atom_to_list(TableName) ++ "_db.dets"), dets:close(TableName), file:delete(Fname), create_db(TableName, GettextDir, Fname), {reply, ok, State}. %%-------------------------------------------------------------------- %% Function: handle_cast/2 %% Description: Handling cast messages Returns : { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: handle_info/2 %% Description: Handling all non call/cast messages Returns : { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate/2 %% Description: Shutdown the server %% Returns: any (ignored by gen_server) %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- %% Func: code_change/3 %% Purpose: Convert process state when code is changed %% Returns: {ok, NewState} %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- create_db(TableName, GettextDir) -> Fname = filename:join(GettextDir, atom_to_list(TableName) ++ ".dets"), create_db(TableName, GettextDir, Fname). create_db(TableName, GettextDir, Fname) -> filelib:ensure_dir(Fname), init_db_table(TableName, GettextDir, Fname). do_unload_custom_lang(TableName, GettextDir, Lang) -> Fname = filename:join([GettextDir, "lang", "custom", Lang, "gettext.po"]), case filelib:is_file(Fname) of true -> dets:match_delete(TableName, {{'_',Lang},'_'}), ok; false -> {error, "no lang"} end. do_reload_custom_lang(TableName, GettextDir, Lang) -> dets:match_delete(TableName, {{'_',Lang},'_'}), Dir = filename:join([GettextDir, "lang", "custom", Lang]), Fname = filename:join([Dir, "gettext.po"]), insert_po_file(TableName, Lang, Fname), ok. do_store_pofile(TableName, Lang, File, GettextDir, Cache) -> Dir = filename:join([GettextDir, "lang", "custom", Lang]), Fname = filename:join([Dir, "gettext.po"]), filelib:ensure_dir(Fname), case file:write_file(Fname, File) of ok -> case lists:keymember(Lang, #cache.language, Cache) of true -> delete_lc(TableName, Lang); false -> false end, insert_po_file(TableName, Lang, Fname), {ok, [set_charset(TableName, #cache{language = Lang}) | Cache]}; _ -> {error, "failed to write PO file to disk"} end. set_charset(TableName, C) -> case lookup(TableName, C#cache.language, ?GETTEXT_HEADER_INFO) of ?GETTEXT_HEADER_INFO -> % nothing found... C#cache{charset = ?DEFAULT_CHARSET}; % fallback Pfinfo -> CharSet = get_charset(Pfinfo), C#cache{charset = CharSet} end. get_charset(Pfinfo) -> g_charset(string:tokens(Pfinfo,[$\n])). g_charset(["Content-Type:" ++ Rest|_]) -> g_cset(Rest); g_charset([_H|T]) -> g_charset(T); g_charset([]) -> ?DEFAULT_CHARSET. g_cset("charset=" ++ Charset) -> rm_trailing_stuff(Charset); g_cset([_|T]) -> g_cset(T); g_cset([]) -> ?DEFAULT_CHARSET. rm_trailing_stuff(Charset) -> lists:reverse(eat_dust(lists:reverse(Charset))). eat_dust([$\s|T]) -> eat_dust(T); eat_dust([$\n|T]) -> eat_dust(T); eat_dust([$\r|T]) -> eat_dust(T); eat_dust([$\t|T]) -> eat_dust(T); eat_dust(T) -> T. init_db_table(TableName, GettextDir, TableFile) -> case filelib:is_regular(TableFile) of false -> create_and_populate(TableName, GettextDir, TableFile); true -> %% If the dets file is broken, dets may not be able to repair it itself ( it may be only half - written ) . So check and recreate %% if needed instead. case open_dets_file(TableName, TableFile) of ok -> create_cache(TableName); _ -> create_and_populate(TableName, GettextDir, TableFile) end end. create_cache(TableName) -> F = fun(LC, Acc) -> case lookup(TableName, LC, ?GETTEXT_HEADER_INFO) of ?GETTEXT_HEADER_INFO -> %% nothing found... ?elog("Could not find header info for lang: ~s~n",[LC]), Acc; Pfinfo -> CS = get_charset(Pfinfo), [#cache{language = LC, charset = CS}|Acc] end end, lists:foldl(F, [], all_lcs_internal(TableName)). create_and_populate(TableName, GettextDir, TableFile) -> ?elog("TableFile = ~p~n", [TableFile]), %% Need to create and populate the DB. {ok, _} = dets:open_file(TableName, [{file, TableFile}, %% creating on disk, esp w auto_save, %% takes "forever" on flash disk {ram_file, true}]), L = populate_db(TableName, GettextDir), dets:close(TableName), % flush to disk {ok, _} = dets:open_file(TableName, [{file, TableFile}]), L. open_dets_file(Tname, Fname) -> Opts = [{file, Fname}, {repair, false}], case dets:open_file(Tname, Opts) of {ok, _} -> ok; _ -> file:delete(Fname), error end. %%% %%% Insert the given languages into the DB. %%% NB : It is important to insert the ' predefiend ' language definitions first since a custom language should be %%% able to 'shadow' the the same predefined language. %%% populate_db(TableName, GettextDir) -> L = insert_predefined(TableName, GettextDir, []), insert_custom(TableName, GettextDir, L). insert_predefined(TableName, GettextDir, L) -> Dir = filename:join([GettextDir, "lang", "default"]), insert_data(TableName, Dir, L). insert_data(TableName, Dir, L) -> case file:list_dir(Dir) of {ok, Dirs} -> F = fun([$.|_], Acc) -> Acc; % ignore in a local inst. env. ("CVS" ++ _, Acc) -> Acc; % ignore in a local inst. env. (LC, Acc) -> Fname = filename:join([Dir, LC, "gettext.po"]), insert_po_file(TableName, LC, Fname), [#cache{language = LC} | Acc] end, lists:foldl(F, L, Dirs); _ -> L end. insert_po_file(TableName, LC, Fname) -> case file:read_file_info(Fname) of {ok, _} -> insert(TableName, LC, gettext:parse_po(Fname)); _ -> ?elog("gettext_server: Could not read ~s~n", [Fname]), {error, "could not read PO file"} end. insert_custom(TableName, GettextDir, L) -> Dir = filename:join([GettextDir, "lang", "custom"]), insert_data(TableName, Dir, L). insert(TableName, LC, L) -> F = fun({Key, Val}) -> dets:insert(TableName, ?ENTRY(LC, Key, Val)) end, lists:foreach(F, L). lookup(TableName, Lang, Key) -> case dets:lookup(TableName, ?KEY(Lang, Key)) of [] -> Key; [{_,Str}|_] -> Str end. delete_lc(TableName, LC) -> dets:match_delete(TableName, ?ENTRY(LC, '_', '_')). all_lcs_internal(TableName) -> L = dets:match(TableName, {{header_info, '$1'}, '_'}), [hd(X) || X <- L].
null
https://raw.githubusercontent.com/noss/erlang-gettext/c895be9dcc6fc699b2e1e8bd731ccee4f78b1cdc/src/gettext_server.erl
erlang
------------------------------------------------------------------- File : gettext_server.erl ------------------------------------------------------------------- -------------------------------------------------------------------- Include files -------------------------------------------------------------------- -------------------------------------------------------------------- External exports Default callback functions gen_server callbacks callback module list_of( #cache{} ) Dir where all the data are stored If several gettext_servers start then tables must have different names Hold info about the languages stored. ==================================================================== External functions ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- -------------------------------------------------------------------- ==================================================================== Server functions ==================================================================== -------------------------------------------------------------------- Function: init/1 Description: Initiates the server Returns: {ok, State} | ignore | {stop, Reason} -------------------------------------------------------------------- The GETTEXT_CBMOD environment variable takes precedence! Next we will try to get hold of the value from the callback. fallback Default callback function -------------------------------------------------------------------- Description: Handling call messages Returns: {reply, Reply, State} | {stop, Reason, Reply, State} | (terminate/2 is called) {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: handle_cast/2 Description: Handling cast messages {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: handle_info/2 Description: Handling all non call/cast messages {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate/2 Description: Shutdown the server Returns: any (ignored by gen_server) -------------------------------------------------------------------- -------------------------------------------------------------------- Func: code_change/3 Purpose: Convert process state when code is changed Returns: {ok, NewState} -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- nothing found... fallback If the dets file is broken, dets may not be able to repair it if needed instead. nothing found... Need to create and populate the DB. creating on disk, esp w auto_save, takes "forever" on flash disk flush to disk Insert the given languages into the DB. able to 'shadow' the the same predefined language. ignore in a local inst. env. ignore in a local inst. env.
Author : < > Desc . : Internationalization support . Created : 28 Oct 2003 by < > -module(gettext_server). -behaviour(gen_server). -export([start_link/0, start_link/1, start_link/2, start/0, start/1, start/2]). -export([custom_dir/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("gettext.hrl"). -define(elog(X,Y), error_logger:info_msg("*elog ~p:~p: " X, [?MODULE, ?LINE | Y])). -define(SERVER, ?MODULE). -define(TABLE_NAME, gettext_server_db). -define(KEY(Lang,Key), {Key,Lang}). -define(ENTRY(Lang, Key, Val), {?KEY(Lang,Key), Val}). -record(state, { -record(cache, { language = ?DEFAULT_LANG, charset = ?DEFAULT_CHARSET }). Function : start_link/0 start_link() -> start_link(?MODULE). start_link(CallBackMod) -> start_link(CallBackMod, ?SERVER). start_link(CallBackMod, Name) -> gen_server:start_link({local, Name}, ?MODULE, [CallBackMod, Name],[]). start() -> start(?MODULE). start(CallBackMod) -> start(CallBackMod, ?SERVER). start(CallBackMod, Name) -> gen_server:start({local, Name}, ?MODULE, [CallBackMod, Name], []). { ok , State , Timeout } | init([CallBackMod0, Name]) -> CallBackMod = get_callback_mod(CallBackMod0), GettextDir = get_gettext_dir(CallBackMod), TableNameStr = atom_to_list(Name) ++ "_db", TableName = list_to_atom(TableNameStr), Cache = create_db(TableName, GettextDir), {ok, #state{cache = Cache, cbmod = CallBackMod, gettext_dir = GettextDir, table_name = TableName}}. get_callback_mod(CallBackMod0) -> case os:getenv("GETTEXT_CBMOD") of false -> CallBackMod0; CbMod -> list_to_atom(CbMod) end. The GETTEXT_DIR environment variable takes precedence ! get_gettext_dir(CallBackMod) -> case os:getenv("GETTEXT_DIR") of false -> case catch CallBackMod:gettext_dir() of Dir when is_list(Dir) -> Dir; end; Dir -> Dir end. custom_dir() -> code:priv_dir(gettext). Function : handle_call/3 { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({key2str, Key, Lang}, _From, State) -> TableName = State#state.table_name, Reply = lookup(TableName, Lang, Key), {reply, Reply, State}; handle_call({lang2cset, Lang}, _From, State) -> Reply = case lists:keysearch(Lang, #cache.language, State#state.cache) of false -> {error, "not found"}; {value, C} -> {ok, C#cache.charset} end, {reply, Reply, State}; handle_call({store_pofile, Lang, File}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, case do_store_pofile(TableName, Lang, File, GettextDir, State#state.cache) of {ok, NewCache} -> {reply, ok, State#state{cache = NewCache}}; Else -> {reply, Else, State} end; handle_call(all_lcs, _From, State) -> TableName = State#state.table_name, Reply = all_lcs_internal(TableName), {reply, Reply, State}; handle_call({reload_custom_lang, Lang}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, case do_reload_custom_lang(TableName, GettextDir, Lang) of ok -> {reply, ok, State}; Else -> {reply, Else, State} end; handle_call({unload_custom_lang, Lang}, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, {reply, do_unload_custom_lang(TableName, GettextDir, Lang), State}; handle_call(recreate_db, _From, State) -> GettextDir = State#state.gettext_dir, TableName = State#state.table_name, Fname = filename:join(GettextDir, atom_to_list(TableName) ++ "_db.dets"), dets:close(TableName), file:delete(Fname), create_db(TableName, GettextDir, Fname), {reply, ok, State}. Returns : { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Returns : { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions create_db(TableName, GettextDir) -> Fname = filename:join(GettextDir, atom_to_list(TableName) ++ ".dets"), create_db(TableName, GettextDir, Fname). create_db(TableName, GettextDir, Fname) -> filelib:ensure_dir(Fname), init_db_table(TableName, GettextDir, Fname). do_unload_custom_lang(TableName, GettextDir, Lang) -> Fname = filename:join([GettextDir, "lang", "custom", Lang, "gettext.po"]), case filelib:is_file(Fname) of true -> dets:match_delete(TableName, {{'_',Lang},'_'}), ok; false -> {error, "no lang"} end. do_reload_custom_lang(TableName, GettextDir, Lang) -> dets:match_delete(TableName, {{'_',Lang},'_'}), Dir = filename:join([GettextDir, "lang", "custom", Lang]), Fname = filename:join([Dir, "gettext.po"]), insert_po_file(TableName, Lang, Fname), ok. do_store_pofile(TableName, Lang, File, GettextDir, Cache) -> Dir = filename:join([GettextDir, "lang", "custom", Lang]), Fname = filename:join([Dir, "gettext.po"]), filelib:ensure_dir(Fname), case file:write_file(Fname, File) of ok -> case lists:keymember(Lang, #cache.language, Cache) of true -> delete_lc(TableName, Lang); false -> false end, insert_po_file(TableName, Lang, Fname), {ok, [set_charset(TableName, #cache{language = Lang}) | Cache]}; _ -> {error, "failed to write PO file to disk"} end. set_charset(TableName, C) -> case lookup(TableName, C#cache.language, ?GETTEXT_HEADER_INFO) of Pfinfo -> CharSet = get_charset(Pfinfo), C#cache{charset = CharSet} end. get_charset(Pfinfo) -> g_charset(string:tokens(Pfinfo,[$\n])). g_charset(["Content-Type:" ++ Rest|_]) -> g_cset(Rest); g_charset([_H|T]) -> g_charset(T); g_charset([]) -> ?DEFAULT_CHARSET. g_cset("charset=" ++ Charset) -> rm_trailing_stuff(Charset); g_cset([_|T]) -> g_cset(T); g_cset([]) -> ?DEFAULT_CHARSET. rm_trailing_stuff(Charset) -> lists:reverse(eat_dust(lists:reverse(Charset))). eat_dust([$\s|T]) -> eat_dust(T); eat_dust([$\n|T]) -> eat_dust(T); eat_dust([$\r|T]) -> eat_dust(T); eat_dust([$\t|T]) -> eat_dust(T); eat_dust(T) -> T. init_db_table(TableName, GettextDir, TableFile) -> case filelib:is_regular(TableFile) of false -> create_and_populate(TableName, GettextDir, TableFile); true -> itself ( it may be only half - written ) . So check and recreate case open_dets_file(TableName, TableFile) of ok -> create_cache(TableName); _ -> create_and_populate(TableName, GettextDir, TableFile) end end. create_cache(TableName) -> F = fun(LC, Acc) -> case lookup(TableName, LC, ?GETTEXT_HEADER_INFO) of ?GETTEXT_HEADER_INFO -> ?elog("Could not find header info for lang: ~s~n",[LC]), Acc; Pfinfo -> CS = get_charset(Pfinfo), [#cache{language = LC, charset = CS}|Acc] end end, lists:foldl(F, [], all_lcs_internal(TableName)). create_and_populate(TableName, GettextDir, TableFile) -> ?elog("TableFile = ~p~n", [TableFile]), {ok, _} = dets:open_file(TableName, [{file, TableFile}, {ram_file, true}]), L = populate_db(TableName, GettextDir), {ok, _} = dets:open_file(TableName, [{file, TableFile}]), L. open_dets_file(Tname, Fname) -> Opts = [{file, Fname}, {repair, false}], case dets:open_file(Tname, Opts) of {ok, _} -> ok; _ -> file:delete(Fname), error end. NB : It is important to insert the ' predefiend ' language definitions first since a custom language should be populate_db(TableName, GettextDir) -> L = insert_predefined(TableName, GettextDir, []), insert_custom(TableName, GettextDir, L). insert_predefined(TableName, GettextDir, L) -> Dir = filename:join([GettextDir, "lang", "default"]), insert_data(TableName, Dir, L). insert_data(TableName, Dir, L) -> case file:list_dir(Dir) of {ok, Dirs} -> (LC, Acc) -> Fname = filename:join([Dir, LC, "gettext.po"]), insert_po_file(TableName, LC, Fname), [#cache{language = LC} | Acc] end, lists:foldl(F, L, Dirs); _ -> L end. insert_po_file(TableName, LC, Fname) -> case file:read_file_info(Fname) of {ok, _} -> insert(TableName, LC, gettext:parse_po(Fname)); _ -> ?elog("gettext_server: Could not read ~s~n", [Fname]), {error, "could not read PO file"} end. insert_custom(TableName, GettextDir, L) -> Dir = filename:join([GettextDir, "lang", "custom"]), insert_data(TableName, Dir, L). insert(TableName, LC, L) -> F = fun({Key, Val}) -> dets:insert(TableName, ?ENTRY(LC, Key, Val)) end, lists:foreach(F, L). lookup(TableName, Lang, Key) -> case dets:lookup(TableName, ?KEY(Lang, Key)) of [] -> Key; [{_,Str}|_] -> Str end. delete_lc(TableName, LC) -> dets:match_delete(TableName, ?ENTRY(LC, '_', '_')). all_lcs_internal(TableName) -> L = dets:match(TableName, {{header_info, '$1'}, '_'}), [hd(X) || X <- L].
14af9e893fcef8404ea4f722d791859af3c0ab2033539ac2d4108eccdf0e53fc
erlangonrails/devdb
transaction_api.erl
Copyright 2007 - 2010 fuer Informationstechnik Berlin % Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. %%%------------------------------------------------------------------- %%% File : transaction_api.erl Author : < > %%% Description : API for transactions %%% Created : 17 Sep 2007 by < > %%%------------------------------------------------------------------- -module(transaction_api). -author(''). -vsn('$Id: transaction_api.erl 956 2010-08-03 13:53:06Z $'). -include("trecords.hrl"). -export([write/3, read/2, write2/3, read2/2, parallel_reads/2, abort/0, quorum_read/1, parallel_quorum_reads/2, single_write/2, do_transaction/3, do_transaction_wo_rp/3, commit/1, jWrite/3, jRead/2, jParallel_reads/2, delete/2]). %%=================================================================== HOWTO do a transaction : To execute a transaction including a readphase use do_transaction TFun : provide a function that gets a transaction log as parameter %% it has to return: 1 ) in case of success { { ok , Value } , NewTransLog } %% 2) in case you want to abort the transaction after the readphase { { abort , Value } , NewTranslog } 3 ) in a failure case { { fail , Reason } , NewTransLog } %% %% After the readphase For 2 ) the SuccessFun({user_abort , Value } ) will be called For 3 ) the FailureFun(not_found | timeout | fail ) will be called %% For 1 ) the commit phase will be started %% it calls 1.1 ) SuccessFun({commit , Value } ) if successful 1.2 ) FailureFun(abort ) if failed %% A transaction without a readphase behaves according to 1.1 ) and 1.2 ) %% where Value = empty %%=================================================================== %%==================================================================== %% transaction API - using transactions from outside %%==================================================================== %% Use this function to do a quorum read without a commit phase %% returns: %% {Value, Version} | {fail, not_found} | {fail, timeout} | %% {fail, fail} %% * for {fail, fail} the reason is currently unknown, should %% not occur quorum_read(Key)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), RTO = config:read(quorum_read_timeout), transaction:quorum_read(Key, comm:this()), receive {single_read_return, {value, empty_val, _Version}}-> ?TLOG2("single read return fail", [Page]), {fail, not_found}; {single_read_return, {value, Page, Version}}-> ?TLOG2("read_page returned", [Page]), {Page, Version}; {single_read_return, {fail, Reason}}-> ?TLOG("single read return fail"), {fail, Reason}; _X -> ?TLOG2("read_page got the message ~p~n", [_X]), {fail, fail} after RTO -> ?TLOG("single read return fail - timeout"), {fail, timeout} end. %% Use this function to do parallel quorum reads on a list of keys with a commit phase -spec parallel_quorum_reads(Keys::[iodata() | integer()], Par::any()) -> {fail} | {fail, timeout} | any(). parallel_quorum_reads(Keys, _Par)-> % ?TLOGN("starting quorum reads on ~p", [Keys]), {Flag, LocalDHTNode} = process_dictionary:find_dht_node(), RTO = config:read(parallel_quorum_read_timeout), if Flag =/= ok-> fail; true -> LocalDHTNode ! {parallel_reads, comm:this(), Keys, []}, receive {parallel_reads_return, fail} -> {fail}; {parallel_reads_return, NewTransLog} -> NewTransLog after RTO -> {fail, timeout} end end. %% returns: %% commit | userabort | {fail, not_found} | {fail, timeout} | {fail, fail} | {fail, abort} %% * for {fail, fail} the reason is currently unknown, should %% not occur single_write(Key, Value)-> %% ?TLOGN("starting a single write function on ~p, value ~p", [Key, Value]), TFun = fun(TLog)-> {Result, TLog2} = write(Key, Value, TLog), case Result of ok -> {{ok, Value}, TLog2}; _ -> {Result, TLog2} end end, SuccessFun = fun({Result, _ReadPhaseResult}) -> Result end, FailureFun = fun(Reason) -> {fail, Reason} end, do_transaction(TFun, SuccessFun, FailureFun). %% use this function to do a full transaction including a readphase do_transaction(TFun, SuccessFun, FailureFun)-> LocalDHTNodes = process_dictionary:find_all_dht_nodes(), LocalDHTNode = lists:nth(random:uniform(length(LocalDHTNodes)), LocalDHTNodes), %{_, LocalDHTNode} = process_dictionary:find_dht_node(), LocalDHTNode ! {do_transaction, TFun, SuccessFun, FailureFun, comm:this()}, receive {trans, Message}-> Message end. %% Use this function to do a transaction without a read phase Thus it is necessary to provide a proper list with items for TMItems do_transaction_wo_rp([], _SuccessFun, _FailureFun)-> {ok}; do_transaction_wo_rp(TMItems, SuccessFun, FailureFun)-> {Flag, LocalDHTNode} = process_dictionary:find_dht_node(), if Flag =/= ok-> fail; true -> LocalDHTNode ! {do_transaction_wo_rp, TMItems, nil, SuccessFun, FailureFun, comm:this()}, receive {trans, Message}-> ? ( " received ~p ~ n " , [ Message ] ) , Message end end. %%-------------------------------------------------------------------- %% Function: commit(TransLog) -> {ok} | {fail, Reason} Description : Commits all operations contained in the TransLog . %%-------------------------------------------------------------------- commit(TransLog)-> SuccessFun = fun(_) -> {ok} end, FailureFun = fun(X) -> {fail, X} end, do_transaction_wo_rp(trecords:create_items(TransLog), SuccessFun, FailureFun). %%==================================================================== transaction API - Functions that can be used within a Transaction Fun %%==================================================================== %%-------------------------------------------------------------------- Function : write(Key , Value , TransLog ) - > { { fail , not_found } , TransLog } | %% {{fail, timeout}, TransLog} | %% {{fail, fail}, TransLog} | { ok , NewTransLog } %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- write(Key, Value, TransLog) -> transaction:write(Key, Value, TransLog). %%-------------------------------------------------------------------- Function : read(Key , TransLog ) - > { { fail , not_found } , TransLog } | %% {{fail, timeout}, TransLog} | %% {{fail, fail}, TransLog} | { { value , Value } , NewTransLog } %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- read(Key, TransLog)-> TLog = transaction:read(Key, TransLog), case TLog of {{value, empty_val}, NTlog} -> {{fail, not_found}, NTlog}; _ -> TLog end. %%-------------------------------------------------------------------- Function : parallel_reads(Keys , TransLog ) - > { fail , NewTransLog } , { [ { value , Value } ] , NewTransLog } : [ Keys ] - List with keys %% TransLog %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- parallel_reads(Keys, TransLog)-> transaction:parallel_reads(Keys, TransLog). read2(translog ( ) , term ( ) ) - > { term ( ) , translog ( ) } % @throws {abort, {fail, translog()}} read2(TransLog, Key) -> case read(Key, TransLog) of {{fail, _Details}, _TransLog1} = Result -> throw({abort, Result}); {{value, Value}, TransLog1} -> {Value, TransLog1} end. % @spec write2(translog(), term(), term()) -> translog() % @throws {abort, {fail, translog()}} write2(TransLog, Key, Value) -> case write(Key, Value, TransLog) of {{fail, _Reason}, _TransLog1} = Result -> throw ({abort, Result}); {ok, TransLog1} -> TransLog1 end. %%-------------------------------------------------------------------- %% Function: abort() -> {abort} %% Description: Signals a user decision to abort a transaction %% PREMATURE %%-------------------------------------------------------------------- abort()-> abort. %% @doc tries to delete the given key and returns the number of %% replicas successfully deleted. %% WARNING: this function can lead to inconsistencies -spec(delete/2 :: (any(), pos_integer()) -> {ok, pos_integer(), list()} | {fail, timeout} | {fail, timeout, pos_integer(), list()} | {fail, node_not_found}). delete(Key, Timeout) -> case process_dictionary:find_dht_node() of {ok, LocalDHTNode} -> LocalDHTNode ! {delete, comm:this(), Key}, receive {delete_result, Result} -> Result after Timeout -> {fail, timeout} end; _ -> {fail, node_not_found} end. %%==================================================================== %% transaction API - Wrapper functions to be used from the java transaction api %%==================================================================== %%-------------------------------------------------------------------- Function : jWrite(Key , Value , TransLog ) - > { { fail , not_found } , TransLog } | %% {{fail, timeout}, TransLog} | %% {{fail, fail}, TransLog} | { ok , NewTransLog } %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- jWrite(Key, Value, TransLog)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), write(Key, Value, TransLog). %%-------------------------------------------------------------------- Function : jRead(Key , TransLog ) - > { { fail , not_found } , TransLog } | %% {{fail, timeout}, TransLog} | %% {{fail, fail}, TransLog} | { { value , Value } , NewTransLog } %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- jRead(Key, TransLog)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), read(Key, TransLog). %%-------------------------------------------------------------------- Function : jParallel_reads(Keys , TransLog ) - > { fail , NewTransLog } , { [ { value , Value } ] , NewTransLog } : [ Keys ] - List with keys %% TransLog %% Description: Needs a TransLog to collect all operations %% that are part of the transaction %%-------------------------------------------------------------------- jParallel_reads(Keys, TransLog)-> io:format("~p~n", [TransLog]), erlang:put(instance_id, process_dictionary:find_group(dht_node)), A = parallel_reads(Keys, TransLog), io:format("~p~n", [A]), A.
null
https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/scalaris/src/transstore/transaction_api.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- File : transaction_api.erl Description : API for transactions ------------------------------------------------------------------- =================================================================== it has to return: 2) in case you want to abort the transaction after the After the readphase it calls where Value = empty =================================================================== ==================================================================== transaction API - using transactions from outside ==================================================================== Use this function to do a quorum read without a commit phase returns: {Value, Version} | {fail, not_found} | {fail, timeout} | {fail, fail} * for {fail, fail} the reason is currently unknown, should not occur Use this function to do parallel quorum reads on a list of keys with a commit phase ?TLOGN("starting quorum reads on ~p", [Keys]), returns: commit | userabort | {fail, not_found} | {fail, timeout} | {fail, fail} | {fail, abort} * for {fail, fail} the reason is currently unknown, should not occur ?TLOGN("starting a single write function on ~p, value ~p", [Key, Value]), use this function to do a full transaction including a readphase {_, LocalDHTNode} = process_dictionary:find_dht_node(), Use this function to do a transaction without a read phase -------------------------------------------------------------------- Function: commit(TransLog) -> {ok} | {fail, Reason} -------------------------------------------------------------------- ==================================================================== ==================================================================== -------------------------------------------------------------------- {{fail, timeout}, TransLog} | {{fail, fail}, TransLog} | Description: Needs a TransLog to collect all operations that are part of the transaction -------------------------------------------------------------------- -------------------------------------------------------------------- {{fail, timeout}, TransLog} | {{fail, fail}, TransLog} | Description: Needs a TransLog to collect all operations that are part of the transaction -------------------------------------------------------------------- -------------------------------------------------------------------- TransLog Description: Needs a TransLog to collect all operations that are part of the transaction -------------------------------------------------------------------- @throws {abort, {fail, translog()}} @spec write2(translog(), term(), term()) -> translog() @throws {abort, {fail, translog()}} -------------------------------------------------------------------- Function: abort() -> {abort} Description: Signals a user decision to abort a transaction PREMATURE -------------------------------------------------------------------- @doc tries to delete the given key and returns the number of replicas successfully deleted. WARNING: this function can lead to inconsistencies ==================================================================== transaction API - Wrapper functions to be used from the java transaction api ==================================================================== -------------------------------------------------------------------- {{fail, timeout}, TransLog} | {{fail, fail}, TransLog} | Description: Needs a TransLog to collect all operations that are part of the transaction -------------------------------------------------------------------- -------------------------------------------------------------------- {{fail, timeout}, TransLog} | {{fail, fail}, TransLog} | Description: Needs a TransLog to collect all operations that are part of the transaction -------------------------------------------------------------------- -------------------------------------------------------------------- TransLog Description: Needs a TransLog to collect all operations that are part of the transaction --------------------------------------------------------------------
Copyright 2007 - 2010 fuer Informationstechnik Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Author : < > Created : 17 Sep 2007 by < > -module(transaction_api). -author(''). -vsn('$Id: transaction_api.erl 956 2010-08-03 13:53:06Z $'). -include("trecords.hrl"). -export([write/3, read/2, write2/3, read2/2, parallel_reads/2, abort/0, quorum_read/1, parallel_quorum_reads/2, single_write/2, do_transaction/3, do_transaction_wo_rp/3, commit/1, jWrite/3, jRead/2, jParallel_reads/2, delete/2]). HOWTO do a transaction : To execute a transaction including a readphase use do_transaction TFun : provide a function that gets a transaction log as parameter 1 ) in case of success { { ok , Value } , NewTransLog } readphase { { abort , Value } , NewTranslog } 3 ) in a failure case { { fail , Reason } , NewTransLog } For 2 ) the SuccessFun({user_abort , Value } ) will be called For 3 ) the FailureFun(not_found | timeout | fail ) will be called For 1 ) the commit phase will be started 1.1 ) SuccessFun({commit , Value } ) if successful 1.2 ) FailureFun(abort ) if failed A transaction without a readphase behaves according to 1.1 ) and 1.2 ) quorum_read(Key)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), RTO = config:read(quorum_read_timeout), transaction:quorum_read(Key, comm:this()), receive {single_read_return, {value, empty_val, _Version}}-> ?TLOG2("single read return fail", [Page]), {fail, not_found}; {single_read_return, {value, Page, Version}}-> ?TLOG2("read_page returned", [Page]), {Page, Version}; {single_read_return, {fail, Reason}}-> ?TLOG("single read return fail"), {fail, Reason}; _X -> ?TLOG2("read_page got the message ~p~n", [_X]), {fail, fail} after RTO -> ?TLOG("single read return fail - timeout"), {fail, timeout} end. -spec parallel_quorum_reads(Keys::[iodata() | integer()], Par::any()) -> {fail} | {fail, timeout} | any(). parallel_quorum_reads(Keys, _Par)-> {Flag, LocalDHTNode} = process_dictionary:find_dht_node(), RTO = config:read(parallel_quorum_read_timeout), if Flag =/= ok-> fail; true -> LocalDHTNode ! {parallel_reads, comm:this(), Keys, []}, receive {parallel_reads_return, fail} -> {fail}; {parallel_reads_return, NewTransLog} -> NewTransLog after RTO -> {fail, timeout} end end. single_write(Key, Value)-> TFun = fun(TLog)-> {Result, TLog2} = write(Key, Value, TLog), case Result of ok -> {{ok, Value}, TLog2}; _ -> {Result, TLog2} end end, SuccessFun = fun({Result, _ReadPhaseResult}) -> Result end, FailureFun = fun(Reason) -> {fail, Reason} end, do_transaction(TFun, SuccessFun, FailureFun). do_transaction(TFun, SuccessFun, FailureFun)-> LocalDHTNodes = process_dictionary:find_all_dht_nodes(), LocalDHTNode = lists:nth(random:uniform(length(LocalDHTNodes)), LocalDHTNodes), LocalDHTNode ! {do_transaction, TFun, SuccessFun, FailureFun, comm:this()}, receive {trans, Message}-> Message end. Thus it is necessary to provide a proper list with items for TMItems do_transaction_wo_rp([], _SuccessFun, _FailureFun)-> {ok}; do_transaction_wo_rp(TMItems, SuccessFun, FailureFun)-> {Flag, LocalDHTNode} = process_dictionary:find_dht_node(), if Flag =/= ok-> fail; true -> LocalDHTNode ! {do_transaction_wo_rp, TMItems, nil, SuccessFun, FailureFun, comm:this()}, receive {trans, Message}-> ? ( " received ~p ~ n " , [ Message ] ) , Message end end. Description : Commits all operations contained in the TransLog . commit(TransLog)-> SuccessFun = fun(_) -> {ok} end, FailureFun = fun(X) -> {fail, X} end, do_transaction_wo_rp(trecords:create_items(TransLog), SuccessFun, FailureFun). transaction API - Functions that can be used within a Transaction Fun Function : write(Key , Value , TransLog ) - > { { fail , not_found } , TransLog } | { ok , NewTransLog } write(Key, Value, TransLog) -> transaction:write(Key, Value, TransLog). Function : read(Key , TransLog ) - > { { fail , not_found } , TransLog } | { { value , Value } , NewTransLog } read(Key, TransLog)-> TLog = transaction:read(Key, TransLog), case TLog of {{value, empty_val}, NTlog} -> {{fail, not_found}, NTlog}; _ -> TLog end. Function : parallel_reads(Keys , TransLog ) - > { fail , NewTransLog } , { [ { value , Value } ] , NewTransLog } : [ Keys ] - List with keys parallel_reads(Keys, TransLog)-> transaction:parallel_reads(Keys, TransLog). read2(translog ( ) , term ( ) ) - > { term ( ) , translog ( ) } read2(TransLog, Key) -> case read(Key, TransLog) of {{fail, _Details}, _TransLog1} = Result -> throw({abort, Result}); {{value, Value}, TransLog1} -> {Value, TransLog1} end. write2(TransLog, Key, Value) -> case write(Key, Value, TransLog) of {{fail, _Reason}, _TransLog1} = Result -> throw ({abort, Result}); {ok, TransLog1} -> TransLog1 end. abort()-> abort. -spec(delete/2 :: (any(), pos_integer()) -> {ok, pos_integer(), list()} | {fail, timeout} | {fail, timeout, pos_integer(), list()} | {fail, node_not_found}). delete(Key, Timeout) -> case process_dictionary:find_dht_node() of {ok, LocalDHTNode} -> LocalDHTNode ! {delete, comm:this(), Key}, receive {delete_result, Result} -> Result after Timeout -> {fail, timeout} end; _ -> {fail, node_not_found} end. Function : jWrite(Key , Value , TransLog ) - > { { fail , not_found } , TransLog } | { ok , NewTransLog } jWrite(Key, Value, TransLog)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), write(Key, Value, TransLog). Function : jRead(Key , TransLog ) - > { { fail , not_found } , TransLog } | { { value , Value } , NewTransLog } jRead(Key, TransLog)-> erlang:put(instance_id, process_dictionary:find_group(dht_node)), read(Key, TransLog). Function : jParallel_reads(Keys , TransLog ) - > { fail , NewTransLog } , { [ { value , Value } ] , NewTransLog } : [ Keys ] - List with keys jParallel_reads(Keys, TransLog)-> io:format("~p~n", [TransLog]), erlang:put(instance_id, process_dictionary:find_group(dht_node)), A = parallel_reads(Keys, TransLog), io:format("~p~n", [A]), A.
157a5227cd5e6fecc40004704cf15d9dca8673bb7edd8058e9f2bdec05d3bdf7
fakedata-haskell/fakedata
OnePiece.hs
# LANGUAGE TemplateHaskell # {-# LANGUAGE OverloadedStrings #-} module Faker.JapaneseMedia.OnePiece where import Data.Text import Faker import Faker.Internal import Faker.Provider.OnePiece import Faker.TH $(generateFakeField "onePiece" "characters") $(generateFakeField "onePiece" "seas") $(generateFakeField "onePiece" "islands") $(generateFakeField "onePiece" "locations") $(generateFakeField "onePiece" "quotes") $(generateFakeField "onePiece" "akumas_no_mi")
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/JapaneseMedia/OnePiece.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # module Faker.JapaneseMedia.OnePiece where import Data.Text import Faker import Faker.Internal import Faker.Provider.OnePiece import Faker.TH $(generateFakeField "onePiece" "characters") $(generateFakeField "onePiece" "seas") $(generateFakeField "onePiece" "islands") $(generateFakeField "onePiece" "locations") $(generateFakeField "onePiece" "quotes") $(generateFakeField "onePiece" "akumas_no_mi")
3d1a0b914ec2cddf0be198ba470cc64982ed38aa54edda8c4bfca1e4fc4fc4ee
sKabYY/palestra
gcd.scm
(load "machine.scm") (define gcd-machine (make-machine '(a b t) (list (list 'rem remainder) (list '= =)) '(test-b (test (op =) (reg b) (const 0)) (branch (label gcd-done)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) (goto (label test-b)) gcd-done))) (define (println x) (begin (display x) (newline))) (println (set-register-contents! gcd-machine 'a 206)) (println (set-register-contents! gcd-machine 'b 40)) (println (start gcd-machine)) (println (get-register-contents gcd-machine 'a))
null
https://raw.githubusercontent.com/sKabYY/palestra/0906cc3a1fb786093a388d5ae7d59120f5aae16c/old1/sicp/5/gcd.scm
scheme
(load "machine.scm") (define gcd-machine (make-machine '(a b t) (list (list 'rem remainder) (list '= =)) '(test-b (test (op =) (reg b) (const 0)) (branch (label gcd-done)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) (goto (label test-b)) gcd-done))) (define (println x) (begin (display x) (newline))) (println (set-register-contents! gcd-machine 'a 206)) (println (set-register-contents! gcd-machine 'b 40)) (println (start gcd-machine)) (println (get-register-contents gcd-machine 'a))
7b1bfb400157ef000ea4a2952682d49de7d7ff535d1e2a837f4f4100f647139c
mirage/ocaml-git
smart.ml
let ( <.> ) f g x = f (g x) module Capability = Capability include struct open Protocol module Proto_request = Proto_request module Advertised_refs = Advertised_refs module Want = Want module Result = Result module Negotiation = Negotiation module Shallow = Shallow module Commands = Commands module Status = Status end module Witness = struct type 'a send = | Proto_request : Proto_request.t send | Want : (string, string) Want.t send | Done : unit send | Flush : unit send | Commands : (string, string) Commands.t send | Send_pack : { side_band : bool; stateless : bool } -> string send | Advertised_refs : (string, string) Advertised_refs.t send type 'a recv = | Advertised_refs : (string, string) Advertised_refs.t recv | Result : string Result.t recv | Status : bool -> string Status.t recv | Packet : bool -> string recv | Commands : (string, string) Commands.t option recv | Recv_pack : { side_band : bool; push_stdout : string -> unit; push_stderr : string -> unit; } -> [ `Payload of string * int * int | `End_of_transmission | `Stdout | `Stderr ] recv | Ack : string Negotiation.t recv | Flush : unit recv | Shallows : string Shallow.t list recv end module Value = struct open Pkt_line type encoder = Encoder.encoder type decoder = Decoder.decoder include Witness type error = [ Protocol.Encoder.error | Protocol.Decoder.error ] let encode : type a. encoder -> a send -> a -> (unit, [> Encoder.error ]) State.t = fun encoder w v -> let encoder_state = let open Protocol.Encoder in match w with | Proto_request -> encode_proto_request encoder v | Want -> encode_want encoder v | Done -> encode_done encoder | Commands -> encode_commands encoder v | Send_pack { side_band; stateless } -> encode_pack ~side_band ~stateless encoder v | Flush -> encode_flush encoder | Advertised_refs -> encode_advertised_refs encoder v in let rec translate_to_state_t = function | Encoder.Done -> State.Return () | Write { continue; buffer; off; len } -> State.Write { k = translate_to_state_t <.> continue; buffer; off; len } | Error err -> State.Error (err :> error) in translate_to_state_t encoder_state let decode : type a. decoder -> a recv -> (a, [> Decoder.error ]) State.t = fun decoder w -> let rec transl : (a, [> Protocol.Decoder.error ]) Decoder.state -> (a, [> Decoder.error ]) State.t = function | Decoder.Done v -> State.Return v | Read { buffer; off; len; continue; eof } -> State.Read { k = transl <.> continue; buffer; off; len; eof = transl <.> eof } | Error { error; _ } -> State.Error error in transl (let open Protocol.Decoder in match w with | Advertised_refs -> decode_advertised_refs decoder | Result -> decode_result decoder | Commands -> decode_commands decoder | Recv_pack { side_band; push_stdout; push_stderr } -> decode_pack ~side_band ~push_stdout ~push_stderr decoder | Ack -> decode_negotiation decoder | Status sideband -> decode_status ~sideband decoder | Flush -> decode_flush decoder | Shallows -> decode_shallows decoder | Packet trim -> decode_packet ~trim decoder) end type ('a, 'err) t = ('a, 'err) State.t = | Read of { buffer : bytes; off : int; len : int; k : int -> ('a, 'err) t; eof : unit -> ('a, 'err) t; } | Write of { buffer : string; off : int; len : int; k : int -> ('a, 'err) t } | Return of 'a | Error of 'err module Context = struct type t = State.Context.t type capabilities = State.Context.capabilities = { client_caps : Capability.t list; server_caps : Capability.t list; } let make = State.Context.make let with_decoder = State.Context.with_decoder let replace_server_caps = State.Context.replace_server_caps let is_cap_shared = State.Context.is_cap_shared let capabilities = State.Context.capabilities end include Witness let proto_request = Proto_request let advertised_refs = Advertised_refs let want = Want let negotiation_done = Done let negotiation_result = Result let commands : _ send = Commands let recv_pack ?(push_stdout = ignore) ?(push_stderr = ignore) side_band = Recv_pack { side_band; push_stdout; push_stderr } let recv_flush : _ recv = Flush let status sideband = Status sideband let flush : _ send = Flush let ack = Ack let shallows = Shallows let send_pack ?(stateless = false) side_band = Send_pack { side_band; stateless } let packet ~trim = Packet trim let send_advertised_refs : _ send = Advertised_refs let recv_commands : _ recv = Commands include State.Scheduler (State.Context) (Value) let pp_error ppf = function | #Protocol.Encoder.error as err -> Protocol.Encoder.pp_error ppf err | #Protocol.Decoder.error as err -> Protocol.Decoder.pp_error ppf err module Unsafe = struct let write context packet = let encoder = State.Context.encoder context in Protocol.Encoder.unsafe_encode_packet encoder ~packet end
null
https://raw.githubusercontent.com/mirage/ocaml-git/37c9ef41944b5b19117c34eee83ca672bb63f482/src/not-so-smart/smart.ml
ocaml
let ( <.> ) f g x = f (g x) module Capability = Capability include struct open Protocol module Proto_request = Proto_request module Advertised_refs = Advertised_refs module Want = Want module Result = Result module Negotiation = Negotiation module Shallow = Shallow module Commands = Commands module Status = Status end module Witness = struct type 'a send = | Proto_request : Proto_request.t send | Want : (string, string) Want.t send | Done : unit send | Flush : unit send | Commands : (string, string) Commands.t send | Send_pack : { side_band : bool; stateless : bool } -> string send | Advertised_refs : (string, string) Advertised_refs.t send type 'a recv = | Advertised_refs : (string, string) Advertised_refs.t recv | Result : string Result.t recv | Status : bool -> string Status.t recv | Packet : bool -> string recv | Commands : (string, string) Commands.t option recv | Recv_pack : { side_band : bool; push_stdout : string -> unit; push_stderr : string -> unit; } -> [ `Payload of string * int * int | `End_of_transmission | `Stdout | `Stderr ] recv | Ack : string Negotiation.t recv | Flush : unit recv | Shallows : string Shallow.t list recv end module Value = struct open Pkt_line type encoder = Encoder.encoder type decoder = Decoder.decoder include Witness type error = [ Protocol.Encoder.error | Protocol.Decoder.error ] let encode : type a. encoder -> a send -> a -> (unit, [> Encoder.error ]) State.t = fun encoder w v -> let encoder_state = let open Protocol.Encoder in match w with | Proto_request -> encode_proto_request encoder v | Want -> encode_want encoder v | Done -> encode_done encoder | Commands -> encode_commands encoder v | Send_pack { side_band; stateless } -> encode_pack ~side_band ~stateless encoder v | Flush -> encode_flush encoder | Advertised_refs -> encode_advertised_refs encoder v in let rec translate_to_state_t = function | Encoder.Done -> State.Return () | Write { continue; buffer; off; len } -> State.Write { k = translate_to_state_t <.> continue; buffer; off; len } | Error err -> State.Error (err :> error) in translate_to_state_t encoder_state let decode : type a. decoder -> a recv -> (a, [> Decoder.error ]) State.t = fun decoder w -> let rec transl : (a, [> Protocol.Decoder.error ]) Decoder.state -> (a, [> Decoder.error ]) State.t = function | Decoder.Done v -> State.Return v | Read { buffer; off; len; continue; eof } -> State.Read { k = transl <.> continue; buffer; off; len; eof = transl <.> eof } | Error { error; _ } -> State.Error error in transl (let open Protocol.Decoder in match w with | Advertised_refs -> decode_advertised_refs decoder | Result -> decode_result decoder | Commands -> decode_commands decoder | Recv_pack { side_band; push_stdout; push_stderr } -> decode_pack ~side_band ~push_stdout ~push_stderr decoder | Ack -> decode_negotiation decoder | Status sideband -> decode_status ~sideband decoder | Flush -> decode_flush decoder | Shallows -> decode_shallows decoder | Packet trim -> decode_packet ~trim decoder) end type ('a, 'err) t = ('a, 'err) State.t = | Read of { buffer : bytes; off : int; len : int; k : int -> ('a, 'err) t; eof : unit -> ('a, 'err) t; } | Write of { buffer : string; off : int; len : int; k : int -> ('a, 'err) t } | Return of 'a | Error of 'err module Context = struct type t = State.Context.t type capabilities = State.Context.capabilities = { client_caps : Capability.t list; server_caps : Capability.t list; } let make = State.Context.make let with_decoder = State.Context.with_decoder let replace_server_caps = State.Context.replace_server_caps let is_cap_shared = State.Context.is_cap_shared let capabilities = State.Context.capabilities end include Witness let proto_request = Proto_request let advertised_refs = Advertised_refs let want = Want let negotiation_done = Done let negotiation_result = Result let commands : _ send = Commands let recv_pack ?(push_stdout = ignore) ?(push_stderr = ignore) side_band = Recv_pack { side_band; push_stdout; push_stderr } let recv_flush : _ recv = Flush let status sideband = Status sideband let flush : _ send = Flush let ack = Ack let shallows = Shallows let send_pack ?(stateless = false) side_band = Send_pack { side_band; stateless } let packet ~trim = Packet trim let send_advertised_refs : _ send = Advertised_refs let recv_commands : _ recv = Commands include State.Scheduler (State.Context) (Value) let pp_error ppf = function | #Protocol.Encoder.error as err -> Protocol.Encoder.pp_error ppf err | #Protocol.Decoder.error as err -> Protocol.Decoder.pp_error ppf err module Unsafe = struct let write context packet = let encoder = State.Context.encoder context in Protocol.Encoder.unsafe_encode_packet encoder ~packet end
235da00383cffcf71d6404174400facb9f5735bbd446089677413ea00972ea04
travisbrady/flajolet
topk.ml
* Reads lines on stdin and then prints the top 5 most common strings * to stdout along with their count * Similar to : * cat somefile.txt | sort | uniq -c | sort -nr * Reads lines on stdin and then prints the top 5 most common strings * to stdout along with their count * Similar to: * cat somefile.txt | sort | uniq -c | sort -nr *) open Core.Std let printf = Printf.printf module String_ss = Stream_summary.Ss(String) let () = let ks = if Array.length Sys.argv > 1 then Sys.argv.(1) else "10" in let k = Int.of_string ks in let ss = String_ss.empty (k*2) in In_channel.iter_lines stdin ~f:(fun line -> String_ss.offer ss line 1 ); let topk = String_ss.top_k ss k in List.iter topk ~f:(fun (key, ct) -> printf "%s,%d,%d\n" key ct.String_ss.count ct.String_ss.error )
null
https://raw.githubusercontent.com/travisbrady/flajolet/a6c530bf1dd73b9fa8b7185d84a5e20458a3d8af/examples/topk.ml
ocaml
* Reads lines on stdin and then prints the top 5 most common strings * to stdout along with their count * Similar to : * cat somefile.txt | sort | uniq -c | sort -nr * Reads lines on stdin and then prints the top 5 most common strings * to stdout along with their count * Similar to: * cat somefile.txt | sort | uniq -c | sort -nr *) open Core.Std let printf = Printf.printf module String_ss = Stream_summary.Ss(String) let () = let ks = if Array.length Sys.argv > 1 then Sys.argv.(1) else "10" in let k = Int.of_string ks in let ss = String_ss.empty (k*2) in In_channel.iter_lines stdin ~f:(fun line -> String_ss.offer ss line 1 ); let topk = String_ss.top_k ss k in List.iter topk ~f:(fun (key, ct) -> printf "%s,%d,%d\n" key ct.String_ss.count ct.String_ss.error )
e895d72199f2812acb72d7675ab4e550f94ab38f15a63bed1641b4e641abc835
racket/handin
web-status-server.rkt
#lang racket/base (require racket/list racket/path racket/file racket/date racket/match net/uri-codec web-server/servlet web-server/compat/0/coerce web-server/compat/0/http/response-structs handin-server/private/md5 handin-server/private/logger handin-server/private/config handin-server/private/hooker "run-servlet.rkt") (define (aget alist key) (cond [(assq key alist) => cdr] [else #f])) (define (clean-str s) (regexp-replace #rx" +$" (regexp-replace #rx"^ +" s "") "")) (define (make-page title . body) `(html (head (title ,title)) (body ([bgcolor "white"]) (h1 ((align "center")) ,title) ,@body))) (define get-user-data (let ([users-file (build-path server-dir "users.rktd")]) (unless (file-exists? users-file) (log-line "WARNING: users file missing on startup: ~a" users-file)) (lambda (user) (and user (get-preference (string->symbol user) (lambda () #f) 'timestamp users-file))))) (define (relativize-path p) (path->string (find-relative-path (normalize-path server-dir) p))) (define (make-k k tag #:mode [mode "download"]) (let ([sep (if (regexp-match? #rx"^[^#]*[?]" k) "&" "?")]) (format "~a~atag=~a~amode=~a" k sep (uri-encode tag) ";" (uri-encode mode)))) ;; `look-for' can be a username as a string (will find "bar+foo" for "foo"), or ;; a regexp that should match the whole directory name (used with "^solution" ;; below) (define (find-handin-entry hi look-for) (let ([dir (assignment<->dir hi)]) (and (directory-exists? dir) (ormap (lambda (d) (let ([d (path->string d)]) (and (cond [(string? look-for) (member look-for (regexp-split #rx" *[+] *" d))] [(regexp? look-for) (regexp-match? look-for d)] [else (error 'find-handin-entry "internal error: ~e" look-for)]) (build-path dir d)))) (directory-list dir))))) (define (handin-link k user hi upload-suffixes) (let* ([dir (find-handin-entry hi user)] [l (and dir (with-handlers ([exn:fail? (lambda (x) null)]) (parameterize ([current-directory dir]) (sort (filter (lambda (f) (and (not (equal? f "grade")) (file-exists? f))) (map path->string (directory-list))) string<?))))]) (append (if (pair? l) (cdr (append-map (lambda (f) (let ([hi (build-path dir f)]) `((br) (a ([href ,(make-k k (relativize-path hi))]) ,f) " (" ,(date->string (seconds->date (file-or-directory-modify-seconds hi)) #t) ")"))) l)) (list (format "No handins accepted so far for user ~s, assignment ~s" user hi))) (if upload-suffixes (let ([dir (or dir (build-path (assignment<->dir hi) user))]) (list '(br) `(a ([href ,(make-k k (relativize-path dir) #:mode "upload")]) "Upload..."))) null)))) (define (solution-link k hi) (let ([soln (and (member (assignment<->dir hi) (get-conf 'inactive-dirs)) (find-handin-entry hi #rx"^solution"))] [none `((i "---"))]) (cond [(not soln) none] [(file-exists? soln) `((a ((href ,(make-k k (relativize-path soln)))) "Solution"))] [(directory-exists? soln) (parameterize ([current-directory soln]) (let ([files (sort (map path->string (filter file-exists? (directory-list))) string<?)]) (if (null? files) none (apply append (map (lambda (f) `((a ([href ,(make-k k (relativize-path (build-path soln f)))]) (tt ,f)) (br))) files)))))] [else none]))) (define (handin-grade user hi) (let* ([dir (find-handin-entry hi user)] [grade (and dir (let ([filename (build-path dir "grade")]) (and (file-exists? filename) (with-input-from-file filename (lambda () (read-string (file-size filename)))))))]) (or grade "--"))) (define (one-status-page user for-handin) (let* ([next (send/suspend (lambda (k) (make-page (format "User: ~a, Handin: ~a" user for-handin) `(p ,@(handin-link k user for-handin #f)) `(p "Grade: " ,(handin-grade user for-handin)) `(p ,@(solution-link k for-handin)) `(p (a ([href ,(make-k k "allofthem")]) ,(format "All handins for ~a" user))))))]) (handle-status-request user next null))) (define (all-status-page user) (define (cell . texts) `(td ([bgcolor "white"]) ,@texts)) (define (rcell . texts) `(td ([bgcolor "white"] [align "right"]) ,@texts)) (define (header . texts) `(td ([bgcolor "#f0f0f0"]) (big (strong ,@texts)))) (define ((row k active? upload-suffixes) dir) (let ([hi (assignment<->dir dir)]) `(tr ([valign "top"]) ,(apply header hi (if active? `((br) (small (small "[active]"))) '())) ,(apply cell (handin-link k user hi upload-suffixes)) ,(rcell (handin-grade user hi)) ,(apply cell (solution-link k hi))))) (define upload-suffixes (get-conf 'allow-web-upload)) (let* ([next (send/suspend (lambda (k) (make-page (format "All Handins for ~a" user) `(table ([bgcolor "#ddddff"] [cellpadding "6"] [align "center"]) (tr () ,@(map header '(nbsp "Files" "Grade" "Solution"))) ,@(append (map (row k #t upload-suffixes) (get-conf 'active-dirs)) (map (row k #f #f) (get-conf 'inactive-dirs)))))))]) (handle-status-request user next upload-suffixes))) (define (handle-status-request user next upload-suffixes) (let* ([mode (aget (request-bindings next) 'mode)] [tag (aget (request-bindings next) 'tag)]) (cond [(string=? mode "download") (download user tag)] [(string=? mode "upload") (upload user tag upload-suffixes)] [else (error 'status "unknown mode: ~s" mode)]))) (define (check path elts allow-active? allow-inactive?) (let loop ([path path] [elts (reverse elts)]) (let*-values ([(base name dir?) (split-path path)] [(name) (path->string name)] [(check) (and (pair? elts) (car elts))]) (if (null? elts) ;; must be rooted in a submission directory (why build-path instead ;; of using `path'? -- because path will have a trailing slash) (member (build-path base name) (cond [(and allow-active? allow-inactive?) (get-conf 'all-dirs)] [allow-inactive? (get-conf 'inactive-dirs)] [allow-active? (get-conf 'active-dirs)] [else null])) (and (cond [(eq? '* check) #t] [(regexp? check) (regexp-match? check name)] [(string? check) (or (equal? name check) (member check (regexp-split #rx" *[+] *" name)))] [else #f]) (loop base (cdr elts))))))) (define (download who tag) (define file (build-path server-dir tag)) (with-handlers ([exn:fail? (lambda (exn) (log-line "Status exception: ~a" (exn-message exn)) (make-page "Error" "Illegal file access"))]) ;; Make sure the user is allowed to read the requested file: (or (check file `(,who *) #t #t) (check file `(#rx"^solution") #f #t) (check file `(#rx"^solution" *) #f #t) (error 'download "bad file access for ~s: ~a" who file)) (log-line "Status file-get: ~s ~a" who file) (hook 'status-file-get `([username ,(string->symbol who)] [file ,file])) ;; Return the downloaded file (let* ([data (file->bytes file)] [html? (regexp-match? #rx"[.]html?$" (string-foldcase tag))] [wxme? (regexp-match? #rx#"^(?:#reader[(]lib\"read.(?:ss|rkt)\"\"wxme\"[)])?WXME" data)]) (make-response/full 200 #"Okay" (current-seconds) (cond [html? #"text/html"] [wxme? #"application/data"] [else #"text/plain"]) (list (make-header #"Content-Length" (string->bytes/latin-1 (number->string (bytes-length data)))) (make-header #"Content-Disposition" (string->bytes/utf-8 (format "~a; filename=~s" (if wxme? "attachment" "inline") (let-values ([(base name dir?) (split-path file)]) (path->string name)))))) (list data))))) (define (upload who tag suffixes) (define next (send/suspend (lambda (k) (make-page "Handin Upload" `(form ([action ,k] [method "post"] [enctype "multipart/form-data"]) (table ([align "center"]) (tr (td "File:") (td (input ([type "file"] [name "file"])))) (tr (td ([colspan "2"] [align "center"]) (input ([type "submit"] [name "post"] [value "Upload"])))))) `(p "The uploaded file will replace any existing file with the same name.") `(p "Allowed file extensions:" ,@(for/list ([s (in-list suffixes)] [n (in-naturals)]) `(span " " (tt ,(bytes->string/utf-8 s)))) ". " "If the uploaded file has no extension or a different extension, " (tt ,(bytes->string/utf-8 (first suffixes))) " is added automatically."))))) (let ([fb (for/first ([b (in-list (request-bindings/raw next))] #:when (binding:file? b)) b)]) (if (and fb (not (equal? #"" (binding:file-filename fb)))) (let* ([fn (binding:file-filename fb)] [base-fn (if (for/or ([suffix (in-list suffixes)]) (regexp-match? (bytes-append (regexp-quote suffix) #"$") fn)) (bytes->path fn) (path-add-suffix (bytes->path fn) (if (null? suffixes) #".txt" (car suffixes))))] [hw-dir (build-path server-dir tag)] [fn (build-path hw-dir (file-name-from-path base-fn))]) (unless (check fn `(,who *) #t #f) (error 'download "bad upload access for ~s: ~a" who fn)) (make-directory* hw-dir) (with-output-to-file fn #:exists 'truncate/replace (lambda () (display (binding:file-content fb)))) (all-status-page who)) (error "no file provided")))) (define (status-page user for-handin) (log-line "Status access: ~s" user) (hook 'status-login `([username ,(string->symbol user)])) (if for-handin (one-status-page user for-handin) (all-status-page user))) (define (login-page for-handin errmsg) (let* ([request (send/suspend (lambda (k) (make-page "Handin Status Login" `(form ([action ,k] [method "post"]) (table ([align "center"]) (tr (td ([colspan "2"] [align "center"]) (font ([color "red"]) ,(or errmsg 'nbsp)))) (tr (td "Username") (td (input ([type "text"] [name "user"] [size "20"] [value ""])))) (tr (td nbsp)) (tr (td "Password") (td (input ([type "password"] [name "passwd"] [size "20"] [value ""])))) (tr (td ([colspan "2"] [align "center"]) (input ([type "submit"] [name "post"] [value "Login"])))))))))] [bindings (request-bindings request)] [user (aget bindings 'user)] [passwd (aget bindings 'passwd)] [user (and user (clean-str user))] [user (and user (if (get-conf 'username-case-sensitive) user (string-foldcase user)))] [user-data (get-user-data user)]) (redirect/get) (cond [(and user-data (string? passwd) (let ([pw (md5 passwd)] [correct-pw (match (car user-data) [`(plaintext ,passwd) (md5 passwd)] [else else])]) (or (equal? pw correct-pw) (equal? pw (get-conf 'master-password))))) (status-page user for-handin)] [else (login-page for-handin "Bad username or password")]))) (define web-counter (let ([sema (make-semaphore 1)] [count 0]) (lambda () (dynamic-wind (lambda () (semaphore-wait sema)) (lambda () (set! count (add1 count)) (format "w~a" count)) (lambda () (semaphore-post sema)))))) (define default-context-length (error-print-context-length)) (define (dispatcher request) (error-print-context-length default-context-length) (parameterize ([current-session (web-counter)]) (login-page (aget (request-bindings request) 'handin) #f))) (provide run) (define (run) (if (get-conf 'use-https) (begin0 (parameterize ([error-print-context-length 0]) (run-servlet dispatcher #:log-file (get-conf 'web-log-file))) (log-line "*** embedded web server started")) ;; simple "server" so it's known that there is no server (lambda (msg . args) (when (eq? 'connect msg) (for-each (lambda (x) (display x (cadr args))) '(#"HTTP/1.0 200 OK\r\n" #"Content-Type: text/html\r\n" #"\r\n" #"<html><body><h1>" #"Please use the handin plugin" #"</h1></body></html>")) (close-input-port (car args)) (close-output-port (cadr args)) (semaphore-post (caddr args))))))
null
https://raw.githubusercontent.com/racket/handin/a01b9cce0c2397d3e1049d4e6932b48b51e65b13/handin-server/web-status-server.rkt
racket
`look-for' can be a username as a string (will find "bar+foo" for "foo"), or a regexp that should match the whole directory name (used with "^solution" below) must be rooted in a submission directory (why build-path instead of using `path'? -- because path will have a trailing slash) Make sure the user is allowed to read the requested file: Return the downloaded file simple "server" so it's known that there is no server
#lang racket/base (require racket/list racket/path racket/file racket/date racket/match net/uri-codec web-server/servlet web-server/compat/0/coerce web-server/compat/0/http/response-structs handin-server/private/md5 handin-server/private/logger handin-server/private/config handin-server/private/hooker "run-servlet.rkt") (define (aget alist key) (cond [(assq key alist) => cdr] [else #f])) (define (clean-str s) (regexp-replace #rx" +$" (regexp-replace #rx"^ +" s "") "")) (define (make-page title . body) `(html (head (title ,title)) (body ([bgcolor "white"]) (h1 ((align "center")) ,title) ,@body))) (define get-user-data (let ([users-file (build-path server-dir "users.rktd")]) (unless (file-exists? users-file) (log-line "WARNING: users file missing on startup: ~a" users-file)) (lambda (user) (and user (get-preference (string->symbol user) (lambda () #f) 'timestamp users-file))))) (define (relativize-path p) (path->string (find-relative-path (normalize-path server-dir) p))) (define (make-k k tag #:mode [mode "download"]) (let ([sep (if (regexp-match? #rx"^[^#]*[?]" k) "&" "?")]) (format "~a~atag=~a~amode=~a" k sep (uri-encode tag) ";" (uri-encode mode)))) (define (find-handin-entry hi look-for) (let ([dir (assignment<->dir hi)]) (and (directory-exists? dir) (ormap (lambda (d) (let ([d (path->string d)]) (and (cond [(string? look-for) (member look-for (regexp-split #rx" *[+] *" d))] [(regexp? look-for) (regexp-match? look-for d)] [else (error 'find-handin-entry "internal error: ~e" look-for)]) (build-path dir d)))) (directory-list dir))))) (define (handin-link k user hi upload-suffixes) (let* ([dir (find-handin-entry hi user)] [l (and dir (with-handlers ([exn:fail? (lambda (x) null)]) (parameterize ([current-directory dir]) (sort (filter (lambda (f) (and (not (equal? f "grade")) (file-exists? f))) (map path->string (directory-list))) string<?))))]) (append (if (pair? l) (cdr (append-map (lambda (f) (let ([hi (build-path dir f)]) `((br) (a ([href ,(make-k k (relativize-path hi))]) ,f) " (" ,(date->string (seconds->date (file-or-directory-modify-seconds hi)) #t) ")"))) l)) (list (format "No handins accepted so far for user ~s, assignment ~s" user hi))) (if upload-suffixes (let ([dir (or dir (build-path (assignment<->dir hi) user))]) (list '(br) `(a ([href ,(make-k k (relativize-path dir) #:mode "upload")]) "Upload..."))) null)))) (define (solution-link k hi) (let ([soln (and (member (assignment<->dir hi) (get-conf 'inactive-dirs)) (find-handin-entry hi #rx"^solution"))] [none `((i "---"))]) (cond [(not soln) none] [(file-exists? soln) `((a ((href ,(make-k k (relativize-path soln)))) "Solution"))] [(directory-exists? soln) (parameterize ([current-directory soln]) (let ([files (sort (map path->string (filter file-exists? (directory-list))) string<?)]) (if (null? files) none (apply append (map (lambda (f) `((a ([href ,(make-k k (relativize-path (build-path soln f)))]) (tt ,f)) (br))) files)))))] [else none]))) (define (handin-grade user hi) (let* ([dir (find-handin-entry hi user)] [grade (and dir (let ([filename (build-path dir "grade")]) (and (file-exists? filename) (with-input-from-file filename (lambda () (read-string (file-size filename)))))))]) (or grade "--"))) (define (one-status-page user for-handin) (let* ([next (send/suspend (lambda (k) (make-page (format "User: ~a, Handin: ~a" user for-handin) `(p ,@(handin-link k user for-handin #f)) `(p "Grade: " ,(handin-grade user for-handin)) `(p ,@(solution-link k for-handin)) `(p (a ([href ,(make-k k "allofthem")]) ,(format "All handins for ~a" user))))))]) (handle-status-request user next null))) (define (all-status-page user) (define (cell . texts) `(td ([bgcolor "white"]) ,@texts)) (define (rcell . texts) `(td ([bgcolor "white"] [align "right"]) ,@texts)) (define (header . texts) `(td ([bgcolor "#f0f0f0"]) (big (strong ,@texts)))) (define ((row k active? upload-suffixes) dir) (let ([hi (assignment<->dir dir)]) `(tr ([valign "top"]) ,(apply header hi (if active? `((br) (small (small "[active]"))) '())) ,(apply cell (handin-link k user hi upload-suffixes)) ,(rcell (handin-grade user hi)) ,(apply cell (solution-link k hi))))) (define upload-suffixes (get-conf 'allow-web-upload)) (let* ([next (send/suspend (lambda (k) (make-page (format "All Handins for ~a" user) `(table ([bgcolor "#ddddff"] [cellpadding "6"] [align "center"]) (tr () ,@(map header '(nbsp "Files" "Grade" "Solution"))) ,@(append (map (row k #t upload-suffixes) (get-conf 'active-dirs)) (map (row k #f #f) (get-conf 'inactive-dirs)))))))]) (handle-status-request user next upload-suffixes))) (define (handle-status-request user next upload-suffixes) (let* ([mode (aget (request-bindings next) 'mode)] [tag (aget (request-bindings next) 'tag)]) (cond [(string=? mode "download") (download user tag)] [(string=? mode "upload") (upload user tag upload-suffixes)] [else (error 'status "unknown mode: ~s" mode)]))) (define (check path elts allow-active? allow-inactive?) (let loop ([path path] [elts (reverse elts)]) (let*-values ([(base name dir?) (split-path path)] [(name) (path->string name)] [(check) (and (pair? elts) (car elts))]) (if (null? elts) (member (build-path base name) (cond [(and allow-active? allow-inactive?) (get-conf 'all-dirs)] [allow-inactive? (get-conf 'inactive-dirs)] [allow-active? (get-conf 'active-dirs)] [else null])) (and (cond [(eq? '* check) #t] [(regexp? check) (regexp-match? check name)] [(string? check) (or (equal? name check) (member check (regexp-split #rx" *[+] *" name)))] [else #f]) (loop base (cdr elts))))))) (define (download who tag) (define file (build-path server-dir tag)) (with-handlers ([exn:fail? (lambda (exn) (log-line "Status exception: ~a" (exn-message exn)) (make-page "Error" "Illegal file access"))]) (or (check file `(,who *) #t #t) (check file `(#rx"^solution") #f #t) (check file `(#rx"^solution" *) #f #t) (error 'download "bad file access for ~s: ~a" who file)) (log-line "Status file-get: ~s ~a" who file) (hook 'status-file-get `([username ,(string->symbol who)] [file ,file])) (let* ([data (file->bytes file)] [html? (regexp-match? #rx"[.]html?$" (string-foldcase tag))] [wxme? (regexp-match? #rx#"^(?:#reader[(]lib\"read.(?:ss|rkt)\"\"wxme\"[)])?WXME" data)]) (make-response/full 200 #"Okay" (current-seconds) (cond [html? #"text/html"] [wxme? #"application/data"] [else #"text/plain"]) (list (make-header #"Content-Length" (string->bytes/latin-1 (number->string (bytes-length data)))) (make-header #"Content-Disposition" (string->bytes/utf-8 (format "~a; filename=~s" (if wxme? "attachment" "inline") (let-values ([(base name dir?) (split-path file)]) (path->string name)))))) (list data))))) (define (upload who tag suffixes) (define next (send/suspend (lambda (k) (make-page "Handin Upload" `(form ([action ,k] [method "post"] [enctype "multipart/form-data"]) (table ([align "center"]) (tr (td "File:") (td (input ([type "file"] [name "file"])))) (tr (td ([colspan "2"] [align "center"]) (input ([type "submit"] [name "post"] [value "Upload"])))))) `(p "The uploaded file will replace any existing file with the same name.") `(p "Allowed file extensions:" ,@(for/list ([s (in-list suffixes)] [n (in-naturals)]) `(span " " (tt ,(bytes->string/utf-8 s)))) ". " "If the uploaded file has no extension or a different extension, " (tt ,(bytes->string/utf-8 (first suffixes))) " is added automatically."))))) (let ([fb (for/first ([b (in-list (request-bindings/raw next))] #:when (binding:file? b)) b)]) (if (and fb (not (equal? #"" (binding:file-filename fb)))) (let* ([fn (binding:file-filename fb)] [base-fn (if (for/or ([suffix (in-list suffixes)]) (regexp-match? (bytes-append (regexp-quote suffix) #"$") fn)) (bytes->path fn) (path-add-suffix (bytes->path fn) (if (null? suffixes) #".txt" (car suffixes))))] [hw-dir (build-path server-dir tag)] [fn (build-path hw-dir (file-name-from-path base-fn))]) (unless (check fn `(,who *) #t #f) (error 'download "bad upload access for ~s: ~a" who fn)) (make-directory* hw-dir) (with-output-to-file fn #:exists 'truncate/replace (lambda () (display (binding:file-content fb)))) (all-status-page who)) (error "no file provided")))) (define (status-page user for-handin) (log-line "Status access: ~s" user) (hook 'status-login `([username ,(string->symbol user)])) (if for-handin (one-status-page user for-handin) (all-status-page user))) (define (login-page for-handin errmsg) (let* ([request (send/suspend (lambda (k) (make-page "Handin Status Login" `(form ([action ,k] [method "post"]) (table ([align "center"]) (tr (td ([colspan "2"] [align "center"]) (font ([color "red"]) ,(or errmsg 'nbsp)))) (tr (td "Username") (td (input ([type "text"] [name "user"] [size "20"] [value ""])))) (tr (td nbsp)) (tr (td "Password") (td (input ([type "password"] [name "passwd"] [size "20"] [value ""])))) (tr (td ([colspan "2"] [align "center"]) (input ([type "submit"] [name "post"] [value "Login"])))))))))] [bindings (request-bindings request)] [user (aget bindings 'user)] [passwd (aget bindings 'passwd)] [user (and user (clean-str user))] [user (and user (if (get-conf 'username-case-sensitive) user (string-foldcase user)))] [user-data (get-user-data user)]) (redirect/get) (cond [(and user-data (string? passwd) (let ([pw (md5 passwd)] [correct-pw (match (car user-data) [`(plaintext ,passwd) (md5 passwd)] [else else])]) (or (equal? pw correct-pw) (equal? pw (get-conf 'master-password))))) (status-page user for-handin)] [else (login-page for-handin "Bad username or password")]))) (define web-counter (let ([sema (make-semaphore 1)] [count 0]) (lambda () (dynamic-wind (lambda () (semaphore-wait sema)) (lambda () (set! count (add1 count)) (format "w~a" count)) (lambda () (semaphore-post sema)))))) (define default-context-length (error-print-context-length)) (define (dispatcher request) (error-print-context-length default-context-length) (parameterize ([current-session (web-counter)]) (login-page (aget (request-bindings request) 'handin) #f))) (provide run) (define (run) (if (get-conf 'use-https) (begin0 (parameterize ([error-print-context-length 0]) (run-servlet dispatcher #:log-file (get-conf 'web-log-file))) (log-line "*** embedded web server started")) (lambda (msg . args) (when (eq? 'connect msg) (for-each (lambda (x) (display x (cadr args))) '(#"HTTP/1.0 200 OK\r\n" #"Content-Type: text/html\r\n" #"\r\n" #"<html><body><h1>" #"Please use the handin plugin" #"</h1></body></html>")) (close-input-port (car args)) (close-output-port (cadr args)) (semaphore-post (caddr args))))))
01b2a05e83d171e4d09265eba59efbae3e2f6fc46487eec8e0c8f80059fde97d
dmvianna/haskellbook
Ch08Ex.hs
module Arith4 where roundTrip :: (Show a, Read b) => a -> b roundTrip = read . show main = do print (roundTrip 4 :: Int) print (id 4) incTimes :: (Eq a, Num a) => a -> a -> a incTimes 0 n = n incTimes times n = 1 + (incTimes (times - 1) n) applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b applyTimes 0 f b = b applyTimes n f b = f . applyTimes (n-1) f $ b fibonacci :: Integral a => a -> a fibonacci 0 = 0 fibonacci 1 = 1 fibonacci x = fibonacci (x - 1) + fibonacci (x - 2) cattyConny :: String -> String -> String cattyConny x y = x ++ " mrow " ++ y flippy :: String -> String -> String flippy = flip cattyConny appedCatty :: String -> String appedCatty = cattyConny "woops" frappe :: String -> String frappe = flippy "haha" sums :: (Eq a, Ord a, Num a) => a -> a sums 1 = 1 sums n = if n > 0 then n + sums (n - 1) else n + sums (n + 1) data DividedResult = Result (Integer, Integer) | DividedByZero deriving Show dividedBy :: Integer -> Integer -> DividedResult dividedBy num 0 = DividedByZero dividedBy num denom = go num denom 0 where go n d count | n < d = Result (count, n) | otherwise = go (n - d) d (count + 1) divBy :: Integer -> Integer -> DividedResult divBy num 0 = DividedByZero divBy num denom = go (abs num) (abs denom) 0 where go n d count | n < d && num > 0 && denom > 0 = Result (count, n) | n < d && num < 0 && denom > 0 = Result (negate count, negate n) | n < d && num < 0 && denom < 0 = Result (count, negate n) | n < d && num > 0 && denom < 0 = Result (negate count, n) | otherwise = go (n - d) d (count + 1) mc91 :: Integral a => a -> a mc91 a | a > 100 = a - 10 | otherwise = mc91 $ mc91 $ a + 11
null
https://raw.githubusercontent.com/dmvianna/haskellbook/b1fdce66283ccf3e740db0bb1ad9730a7669d1fc/src/Ch08Ex.hs
haskell
module Arith4 where roundTrip :: (Show a, Read b) => a -> b roundTrip = read . show main = do print (roundTrip 4 :: Int) print (id 4) incTimes :: (Eq a, Num a) => a -> a -> a incTimes 0 n = n incTimes times n = 1 + (incTimes (times - 1) n) applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b applyTimes 0 f b = b applyTimes n f b = f . applyTimes (n-1) f $ b fibonacci :: Integral a => a -> a fibonacci 0 = 0 fibonacci 1 = 1 fibonacci x = fibonacci (x - 1) + fibonacci (x - 2) cattyConny :: String -> String -> String cattyConny x y = x ++ " mrow " ++ y flippy :: String -> String -> String flippy = flip cattyConny appedCatty :: String -> String appedCatty = cattyConny "woops" frappe :: String -> String frappe = flippy "haha" sums :: (Eq a, Ord a, Num a) => a -> a sums 1 = 1 sums n = if n > 0 then n + sums (n - 1) else n + sums (n + 1) data DividedResult = Result (Integer, Integer) | DividedByZero deriving Show dividedBy :: Integer -> Integer -> DividedResult dividedBy num 0 = DividedByZero dividedBy num denom = go num denom 0 where go n d count | n < d = Result (count, n) | otherwise = go (n - d) d (count + 1) divBy :: Integer -> Integer -> DividedResult divBy num 0 = DividedByZero divBy num denom = go (abs num) (abs denom) 0 where go n d count | n < d && num > 0 && denom > 0 = Result (count, n) | n < d && num < 0 && denom > 0 = Result (negate count, negate n) | n < d && num < 0 && denom < 0 = Result (count, negate n) | n < d && num > 0 && denom < 0 = Result (negate count, n) | otherwise = go (n - d) d (count + 1) mc91 :: Integral a => a -> a mc91 a | a > 100 = a - 10 | otherwise = mc91 $ mc91 $ a + 11
6c5ad936655f84c8a18d28fe0eac5574bb265982323219b690c7d857ec9ce32b
sgbj/MaximaSharp
expintegral.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Exponential Integrals ;;; This file contains the following Maxima User functions : ;;; ;;; $expintegral_e (n,z) - Exponential Integral En(z) $ expintegral_e1 ( z ) - Exponential Integral E1(z ) $ expintegral_ei ( z ) - Exponential Integral Ei(z ) ;;; ;;; $expintegral_li (z) - Logarithmic Integral Li(z) ;;; $ expintegral_si ( z ) - Exponential Integral Si(z ) $ expintegral_ci ( z ) - Exponential Integral Ci(z ) ;;; $ expintegral_shi ( z ) - Exponential Integral Shi(z ) $ expintegral_chi ( z ) - Exponential Integral Chi(z ) ;;; ;;; $expint (x) - Exponential Integral E1(x) (depreciated) ;;; Global variables for the Maxima User : ;;; $ expintrep - Change the representation of the Exponential Integral to gamma_incomplete , expintegral_e1 , expintegral_ei , ;;; expintegral_li, expintegral_trig, expintegral_hyp ;;; $ expintexpand - Expand the Exponential Integral E[n](z ) for half integral values in terms of or Erf and ;;; for positive integers in terms of Ei ;;; ;;; The following features are implemented: ;;; 1 . Numerical evaluation for complex and Bigfloat numbers ;;; using an expansion in a power series or continued fractions. The numerical support is fully implemented for the E[n](z ) function . All other functions call E[n](z ) for numerical evaluation . ;;; 2 . For a negative integer parameter E[n](z ) is automatically expanded in ;;; a finite series in terms of powers and the Exponential function. ;;; 3 . When $ expintexpand is set to TRUE or ERF E[n](z ) expands a ) for n a half integral number in terms of ( TRUE ) or Erf ( ERF ) ;;; b) for n a positive integer number in terms of Ei ;;; 3 . Simplifications for special values : Ev(0 ) , E[0](z ) , Li(0 ) , ) , ... ;;; 4 . Derivatives of the Exponential Integrals ;;; 5 . Change the representation of every Exponential Integral through other Exponential Integrals or the Incomplete Gamma function . ;;; 6 . Mirror symmetry for all functions and reflection symmetry for and are implemented . ;;; 7 . Handling of expansions as argument . ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This library 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 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 Library General Public License for more details . ;;; You should have received a copy of the GNU General Public License along ;;; with this library; if not, write to the Free Software Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . ;;; Copyright ( C ) 2008 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Globals to help debugging the code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *debug-expintegral* nil "When enabled print debug information.") (defvar *debug-expint-maxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-fracmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-bfloatmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-fracbfloatmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Globals for the Maxima Users ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar $expintexpand nil "When not nil we expand for a half integral parameter of the Exponetial Integral in a series in terms of the Erfc or Erf function and for positive integer in terms of the Ei function.") (defvar $expintrep nil "Change the representation of the Exponential Integral. Values are: gamma_incomplete, expintegral_e1, expintegral_ei, expintegral_li, expintegral_trig, expintegral_hyp.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Global to this file ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *expintflag* '(%expintegral_e1 %expintegral_ei %expintegral_li $expintegral_trig $expintegral_hyp %gamma_incomplete) "Allowed flags to transform the Exponential Integral.") (defun simp-domain-error (&rest args) (if errorsw (throw 'errorsw t) (apply #'merror args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 1 : The implementation of the Exponential Integral En ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_e (v z) (simplify (list '(%expintegral_e) v z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_e %expintegral_e alias) (defprop $expintegral_e %expintegral_e verb) (defprop %expintegral_e $expintegral_e reversealias) (defprop %expintegral_e $expintegral_e noun) Exponential Integral E is a simplifying function (defprop %expintegral_e simp-expintegral-e operators) Exponential Integral E distributes over bags (defprop %expintegral_e (mlist $matrix mequal) distribute_over) Exponential Integral E has mirror symmetry , ;;; but not on the real negative axis. (defprop %expintegral_e conjugate-expintegral-e conjugate-function) (defun conjugate-expintegral-e (args) (let ((n (first args)) (z (second args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_e) (take '($conjugate) n) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_e) n z)))))) ;;; Differentiation of Exponential Integral E (defprop %expintegral_e ((n z) ;; The derivative wrt the parameter n is expressed in terms of the function 2F2 ( see functions.wolfram.com ) ((mplus) ((mtimes) -1 (($hypergeometric_regularized) ((mlist) ((mplus) 1 ((mtimes) -1 n)) ((mplus) 1 ((mtimes) -1 n))) ((mlist) ((mplus) 2 ((mtimes) -1 n)) ((mplus) 2 ((mtimes) -1 n))) ((mtimes) -1 z)) ((mexpt) ((%gamma) ((mplus) 1 ((mtimes) -1 n))) 2)) ((mtimes) ((%gamma) ((mplus) 1 ((mtimes) -1 n))) ((mexpt) z ((mplus) -1 n)) ((mplus) ((mtimes) -1 ((mqapply) (($psi array) 0) ((mplus) 1 ((mtimes) -1 n)))) ((%log) z)))) ;; The derivative wrt the argument of the function ((mtimes) -1 ((%expintegral_e) ((mplus) -1 n) z))) grad) Integral of Exponential Integral E (defprop %expintegral_e ((n z) nil ((mtimes) -1 ((%expintegral_e) ((mplus) 1 n) z))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_e simplim%expintegral_e simplim%function) (defun simplim%expintegral_e (expr var val) ;; Look for the limit of the arguments. (let ((a (limit (cadr expr) var val 'think)) (z (limit (caddr expr) var val 'think))) (cond ((and (onep1 a) (or (eq z '$zeroa) (eq z '$zerob) (zerop1 z))) ;; Special case order a=1 '$inf) ((member ($sign (add ($realpart a) -1)) '($neg $nz $zero)) realpart of order < 1 (cond ((eq z '$zeroa) ;; from above, always inf '$inf) ((eq z '$zerob) ;; this can be further improved to give a directed infinity '$infinity) ((zerop1 z) ;; no direction, return infinity '$infinity) (t ($expintegral_e a z)))) (t ;; All other cases are handled by the simplifier of the function. ($expintegral_e a z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-e (expr ignored z) (declare (ignore ignored)) (twoargcheck expr) (let ((order (simpcheck (cadr expr) z)) (arg (simpcheck (caddr expr) z)) (ratorder)) (cond ;; Check for special values ((or (eq arg '$inf) (alike1 arg '((mtimes) -1 $minf))) arg is inf or -minf , return zero 0) ((zerop1 arg) (let ((sgn ($sign (add ($realpart order) -1)))) (cond ((eq sgn '$pos) ;; we handle the special case E[v](0) = 1/(v-1), for realpart(v)>1 (inv (add order -1))) ((member sgn '($neg $nz $zero)) (simp-domain-error (intl:gettext "expintegral_e: expintegral_e(~:M,~:M) is undefined.") order arg)) (t (eqtest (list '(%expintegral_e) order arg) expr))))) ((or (and (symbolp order) (member order infinities)) (and (symbolp arg) (member arg infinities))) ;; order or arg is one of the infinities, we return a noun form, ;; but we have already handled the special value inf for arg. (eqtest (list '(%expintegral_e) order arg) expr)) ((and (numberp order) (integerp order)) ;; The parameter of the Exponential integral is an integer. For this ;; case we can do further simplifications or numerical evaluation. (cond ((= order 0) ;; Special case E[0](z) = %e^(-z)/z, z<>0 The case z=0 is already handled . (div (power '$%e (mul -1 arg)) arg)) ((= order -1) Special case ) = ( ( z+1)*%e^(-z))/z^2 , z<>0 The case z=0 is already handled . (div (mul (power '$%e (mul -1 arg)) (add arg 1)) (mul arg arg))) ((< order -1) ;; We expand in a series, z<>0 (mul (factorial (- order)) (power arg (+ order -1)) (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg index) (take '(mfactorial) index)) index 0 (- order) t)))) ((and (> order 0) (complex-float-numerical-eval-p arg)) ;; Numerical evaluation for double float real or complex arg order is an integer > 0 and arg < > 0 for order < 2 (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e order carg)))) ((and (> order 0) (complex-bigfloat-numerical-eval-p arg)) Numerical evaluation for Bigfloat real or complex arg . (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e order carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ((and $expintexpand (> order 0)) We only expand in terms of the Exponential Integral Ei ;; if the expand flag is set. (sub (mul -1 (power (mul -1 arg) (- order 1)) (inv (factorial (- order 1))) (add (take '(%expintegral_ei) (mul -1 arg)) (mul (inv 2) (sub (take '(%log) (mul -1 (inv arg))) (take '(%log) (mul -1 arg)))) (take '(%log) arg))) (mul (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index -1)) (take '($pochhammer) (- 1 order) index)) index 1 (- order 1) t))))) ((eq $expintrep '%gamma_incomplete) ;; We transform to the Incomplete Gamma function. (mul (power arg (- order 1)) (take '(%gamma_incomplete) (- 1 order) arg))) (t (eqtest (list '(%expintegral_e) order arg) expr)))) ((complex-float-numerical-eval-p order arg) (cond ((and (setq z (integer-representation-p order)) (plusp z)) We have a pure real positive order and the realpart is a float ;; representation of an integer value. ;; We call the routine for an integer order. (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e z carg)))) (t ;; The general case, order and arg are complex or real. (let ((corder (complex ($float ($realpart order)) ($float ($imagpart order)))) (carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (frac-expintegral-e corder carg)))))) ((complex-bigfloat-numerical-eval-p order arg) (cond ((and (setq z (integer-representation-p order)) (plusp z)) We have a real positive order and the realpart is a Float or Bigfloat representation of an integer value . ;; We call the routine for an integer order. (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e z carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) (t the general case , order and arg are bigfloat or complex (let* (($ratprint nil) (corder (add ($bfloat ($realpart order)) (mul '$%i ($bfloat ($imagpart order))))) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (frac-bfloat-expintegral-e corder carg))) (add ($realpart result) (mul '$%i ($imagpart result))))))) ((and $expintexpand (setq ratorder (max-numeric-ratio-p order 2))) We have a half integral order and $ expintexpand is not NIL . We expand in a series in terms of the or Erf function . (let ((func (cond ((eq $expintexpand '%erf) (sub 1 ($erf (power arg '((rat simp) 1 2))))) (t ($erfc (power arg '((rat simp) 1 2))))))) (cond ((= ratorder 1/2) (mul (power '$%pi '((rat simp) 1 2)) (power arg '((rat simp) -1 2)) func)) ((= ratorder -1/2) (add (mul (power '$%pi '((rat simp) 1 2)) (inv (mul 2 (power arg '((rat simp) 3 2)))) func) (div (power '$%e (mul -1 arg)) arg))) (t (let ((n (- ratorder 1/2))) (mul (power arg (sub n '((rat simp) 1 2))) (add (mul func (take '(%gamma) (sub '((rat simp) 1 2) n))) (mul (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index '((rat simp) 1 2))) (take '($pochhammer) (sub '((rat simp) 1 2) n) (add index n 1))) index 0 (mul -1 (add n 1)) t))) (mul -1 (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index '((rat simp) 1 2))) (take '($pochhammer) (sub '((rat simp) 1 2) n) (add index n 1))) index (- n) -1 t)))))))))) ((eq $expintrep '%gamma_incomplete) ;; We transform to the Incomplete Gamma function. (mul (power arg (sub order 1)) (take '(%gamma_incomplete) (sub 1 order) arg))) (t (eqtest (list '(%expintegral_e) order arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral En(z ) ;;; ;;; The following numerical routines are implemented: ;;; ;;; expintegral-e - n positive integer, z real or complex ;;; frac-expintegral-e - n,z real or complex; n not a positive integer ;;; bfloat-expintegral-e - n positive integer, z Bigfloat or Complex Bigfloat frac - bfloat - expintegral - e - n Bigfloat , or Complex Bigfloat ;;; The algorithm are implemented for full support of and real or Complex parameter and argument of the Exponential Integral . Because we have no support for Complex Bigfloat arguments of the Gamma ;;; function the evaluation for a Complex Bigfloat parameter don't give ;;; the desiered accuracy. ;;; The flonum versions return a CL complex number . The Bigfloat versions a Maxima Complex Bigfloat number . It is assumed that the calling routine ;;; check the values. We don't handle any special case. This has to be done by ;;; the calling routine. ;;; ;;; The evaluation uses an expansion in continued fractions for arguments with realpart(z ) > 0 and abs(z ) > 1.0 ( A&S 5.1.22 ) . This expansion works for every Real or Complex numbers including Bigfloat numbers for the parameter n ;;; and the argument z: ;;; 1 n 1 n+1 2 ;;; En(z) = e^(-z) * ( --- --- --- --- --- ... ) ;;; z+ 1+ z+ 1+ z+ ;;; The continued fraction is evaluated by the modified 's method ;;; for the more rapidly converging even form. ;;; ;;; For the parameter n an positive integer we do an expansion in a power series ;;; (A&S 5.1.12): ;;; inf ;;; === ;;; (-z)^(n-1) \ (-z)^m ;;; En(z) = --------- * (-log(z)+psi(n)) * > ---------- ; n an integer ;;; (n-1)! / (m-n+1)*m! ;;; === ;;; m=0 (m <> n-1) ;;; ;;; For an parameter n not an integer we expand in the following series ;;; (functions.wolfram.com ): ;;; inf ;;; === \ ( -1)^m * z^m ;;; Ev(z) = gamma(1-v) * z^(v-1) * > ------------- ; n not an integer ;;; / (m-v+1)*m! ;;; === ;;; m=0 ;;; ;;; The evaluation stops if an accuracy better than *expint-eps* is achived. If the expansion do n't converge within * expint - maxit * steps a Maxima ;;; Error is thrown. ;;; The algorithm is based on technics desribed in Numerical Recipes , 2nd . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants to terminate the numerical evaluation ;;; The accuracy * expint - eps * is fixed to 1.0e-15 for double float calculations . The variable is declared global , so we can later give the Maxima User access to the variable . The routine for Bigfloat numerical evaluation change this ;;; value to the desired precision of the global $fpprec. The maximum number of iterations is arbitrary set to 1000 . For ;;; evaluation this number is for very Big numbers too small. ;;; ;;; The maximum iterations counted for the test file rtest-expintegral.mac are 101 for Complex Flonum and 1672 for Complex Bigfloat evaluation . (defvar *expint-eps* 1.0e-15) (defvar *expint-maxit* 1000) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-e (n z) (declare (type integer n)) (let ((*expint-eps* *expint-eps*) (*expint-maxit* *expint-maxit*) ;; Add (complex) 0 to get rid of any signed zeroes, and make z ;; be a complex number. (z (+ (coerce 0 '(complex flonum)) z))) (declare (type (complex flonum) z)) (when *debug-expintegral* (format t "~&EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((or (and (> (abs z) 2.0) (< (abs (phase z)) (* pi 0.9))) ;; (abs z)>2.0 is necessary since there is a point -1.700598 - 0.612828*%i which 1<(abs z)<2 , phase z < 0.9pi and ;; still c-f expansion does not converge. (and (>= (realpart z) 0) (> (abs z) 1.0))) ;; We expand in continued fractions. (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (+ z n)) (c (/ 1.0 (* *expint-eps* *expint-eps*))) (d (/ 1.0 b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (+ b 2.0)) (setq d (/ 1.0 (+ (* a d) b))) (setq c (+ b (/ a c))) (setq e (* c d)) (setq h (* h e)) (when (< (abs (- e 1.0)) *expint-eps*) (when *debug-expintegral* (setq *debug-expint-maxit* (max *debug-expint-maxit* i))) (return (* h (exp (- z)))))))) (t ;; We expand in a power series. (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) (euler (mget '$%gamma '$numer)) (r (if (= n1 0) (- (- euler) (log z)) (/ 1.0 n1))) (f 1.0) (e 0.0)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (* -1 f (/ z i))) (cond ((= i n1) (let ((psi (- euler))) (dotimes (ii n1) (setq psi (+ psi (/ 1.0 (+ ii 1))))) (setq e (* f (- psi (log z)))))) (t (setq e (/ (- f) (- i n1))))) (setq r (+ r e)) (when (< (abs e) (* (abs r) *expint-eps*)) (when *debug-expintegral* (setq *debug-expint-maxit* (max *debug-expint-maxit* i))) (return r)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Numerical evaluation for a real or complex parameter. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun frac-expintegral-e (n z) (declare (type (complex flonum) n) (type (complex flonum) z)) (let ((*expint-eps* *expint-eps*) (*expint-maxit* *expint-maxit*)) (when *debug-expintegral* (format t "~&FRAC-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((and (> (realpart z) 0) (> (abs z) 1.0)) ;; We expand in continued fractions. (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (+ z n)) (c (/ 1.0 (* *expint-eps* *expint-eps*))) (d (/ 1.0 b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (+ b 2.0)) (setq d (/ 1.0 (+ (* a d) b))) (setq c (+ b (/ a c))) (setq e (* c d)) (setq h (* h e)) (when (< (abs (- e 1.0)) *expint-eps*) (when *debug-expintegral* (setq *debug-expint-fracmaxit* (max *debug-expint-fracmaxit* i))) (return (* h (exp (- z)))))))) ((and (= (imagpart n) 0) (> (realpart n) 0) (= (nth-value 1 (truncate (realpart n))) 0)) ;; We have a positive integer n or an float representation of an ;; integer. We call expintegral-e which does this calculation. (when *debug-expintegral* (format t "~&We call expintegral-e.~%")) (expintegral-e (truncate (realpart n)) z)) (t ;; At this point the parameter n is a real (not an float representation ;; of an integer) or complex. We expand in a power series. (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) ;; It would be possible to call the numerical implementation gamm - lanczos directly . But then the code would depend on the ;; details of the implementation. (gm (let ((tmp (take '(%gamma) (complexify (- 1 n))))) (complex ($realpart tmp) ($imagpart tmp)))) (r (- (* (expt z n1) gm) (/ 1.0 (- 1 n)))) (f 1.0) (e 0.0)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (* -1 f (/ z (float i)))) (setq e (/ (- f) (- (float i) n1))) (setq r (+ r e)) (when (< (abs e) (* (abs r) *expint-eps*)) (when *debug-expintegral* (setq *debug-expint-fracmaxit* (max *debug-expint-fracmaxit* i))) (return r)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Helper functions for Bigfloat numerical evaluation . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun cmul (x y) ($rectform (mul x y))) (defun cdiv (x y) ($rectform (div x y))) (defun cpower (x y) ($rectform (power x y))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We have not changed the above algorithm, but generalized it to handle complex and real Bigfloat numbers . By carefully examination of the ;;; algorithm some of the additional calls to $rectform can be eliminated. ;;; But the algorithm works and so we leave the extra calls for later work ;;; in the code. ;;; The accuracy of the result is determined by *expint-eps*. The value is ;;; chosen to correspond to the value of $fpprec. We don't give any extra digits to fpprec , so we loose 1 to 2 digits of precision . One problem is to chose a sufficient big * expint - maxit * . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun bfloat-expintegral-e (n z) (let ((*expint-eps* (power ($bfloat 10.0) (- $fpprec))) (*expint-maxit* 5000) ; arbitrarily chosen, we need a better choice (bigfloattwo (add bigfloatone bigfloatone)) (bigfloat%e ($bfloat '$%e)) (bigfloat%gamma ($bfloat '$%gamma)) (flz (complex ($float ($realpart z)) ($float ($imagpart z))))) (when *debug-expintegral* (format t "~&BFLOAT-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" flz)) (cond ((or (and (> (abs flz) 2) (< (abs (phase flz)) (* pi 0.9))) ;; The same condition as you see in expintegral-e() (and (>= (realpart flz) 0) (> (abs flz) 1.0))) ;; We expand in continued fractions. (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (add z n)) (c (div bigfloatone (mul *expint-eps* *expint-eps*))) (d (cdiv bigfloatone b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (add b bigfloattwo)) (setq d (cdiv bigfloatone (add (mul a d) b))) (setq c (add b (cdiv a c))) (setq e (cmul c d)) (setq h (cmul h e)) (when (eq ($sign (sub (cabs (sub e bigfloatone)) *expint-eps*)) '$neg) (when *debug-expintegral* (setq *debug-expint-bfloatmaxit* (max *debug-expint-bfloatmaxit* i))) (return (cmul h (cpower bigfloat%e (mul -1 z)))))))) (t ;; We expand in a power series. (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) (meuler (mul -1 bigfloat%gamma)) (r (if (= n1 0) (sub meuler ($log z)) (div bigfloatone n1))) (f bigfloatone) (e bigfloatzero)) (do* ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (mul -1 (cmul f (cdiv z i)))) (cond ((= i n1) (let ((psi meuler)) (dotimes (ii n1) (setq psi (add psi (cdiv bigfloatone (+ ii 1))))) (setq e (cmul f (sub psi ($log z)))))) (t (setq e (cdiv (mul -1 f) (- i n1))))) (setq r (add r e)) (when (eq ($sign (sub (cabs e) (cmul (cabs r) *expint-eps*))) '$neg) (when *debug-expintegral* (setq *debug-expint-bfloatmaxit* (max *debug-expint-bfloatmaxit* i))) (return r)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical Bigfloat evaluation for a real ( Bigfloat ) parameter . ;;; The algorithm would work for a Complex Bigfloat paramter too. But we need the values of Gamma for Complex Bigfloats . This is at this time ( 2008 ) not implemented in Maxima . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun frac-bfloat-expintegral-e (n z) (let ((*expint-eps* (power ($bfloat 10.0) (- $fpprec))) (*expint-maxit* 5000) ; arbitrarily chosen, we need a better choice (bigfloattwo (add bigfloatone bigfloatone)) (bigfloat%e ($bfloat '$%e)) (bigfloat%gamma ($bfloat '$%gamma))) (when *debug-expintegral* (format t "~&FRAC-BFLOAT-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((and (or (eq ($sign ($realpart z)) '$pos) (eq ($sign ($realpart z)) '$zero)) (eq ($sign (sub (cabs z) bigfloatone)) '$pos)) ;; We expand in continued fractions. (when *debug-expintegral* (format t "We expand in continued fractions.~%")) (let* ((b (add z n)) (c (div bigfloatone (mul *expint-eps* *expint-eps*))) (d (cdiv bigfloatone b)) (n1 (sub n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (mul -1 n) (cmul (- i) (add n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (add b bigfloattwo)) (setq d (cdiv bigfloatone (add (mul a d) b))) (setq c (add b (cdiv a c))) (setq e (cmul c d)) (setq h (cmul h e)) (when (eq ($sign (sub (cabs (sub e bigfloatone)) *expint-eps*)) '$neg) (when *debug-expintegral* (setq *debug-expint-fracbfloatmaxit* (max *debug-expint-fracbfloatmaxit* i))) (return (cmul h (cpower bigfloat%e (mul -1 z)))))))) ((or (and (numberp n) (= ($imagpart n) 0) (> ($realpart n) 0) (= (nth-value 1 (truncate ($realpart n))) 0)) (and ($bfloatp n) (eq ($sign n) '$pos) (equal (sub (mul 2 ($fix n)) (mul 2 n)) bigfloatzero))) We have a Float or Bigfloat representation of positive integer . ;; We call bfloat-expintegral-e. (when *debug-expintegral* (format t "frac-Bigfloat with integer ~A~%" n)) (bfloat-expintegral-e ($fix ($realpart n)) z)) (t ;; At this point the parameter n is a real (not a float representation ;; of an integer) or complex. We expand in a power series. (when *debug-expintegral* (format t "We expand in a power series.~%")) (let* ((n1 (sub n bigfloatone)) (n2 (sub bigfloatone n)) (gm (take '(%gamma) n2)) (r (sub (cmul (cpower z n1) gm) (cdiv bigfloatone n2))) (f bigfloatone) (e bigfloatzero)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (cmul (mul -1 bigfloatone) (cmul f (cdiv z i)))) (setq e (cdiv (mul -1 f) (sub i n1))) (setq r (add r e)) (when (eq ($sign (sub (cabs e) (cmul (cabs r) *expint-eps*))) '$neg) (when *debug-expintegral* (setq *debug-expint-fracbfloatmaxit* (max *debug-expint-fracbfloatmaxit* i))) (return r)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 2 : The implementation of the Exponential Integral E1 ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_e1 (z) (simplify (list '(%expintegral_e1) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_e1 %expintegral_e1 alias) (defprop $expintegral_e1 %expintegral_e1 verb) (defprop %expintegral_e1 $expintegral_e1 reversealias) (defprop %expintegral_e1 $expintegral_e1 noun) Exponential Integral E1 is a simplifying function (defprop %expintegral_e1 simp-expintegral_e1 operators) Exponential Integral E1 distributes over bags (defprop %expintegral_e1 (mlist $matrix mequal) distribute_over) Exponential Integral E1 has mirror symmetry , ;;; but not on the real negative axis. (defprop %expintegral_e1 conjugate-expintegral-e1 conjugate-function) (defun conjugate-expintegral-e1 (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_e1) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_e1) z)))))) ;;; Differentiation of Exponential Integral E1 (defprop %expintegral_e1 ((x) ((mtimes) -1 ((mexpt) x -1) ((mexpt) $%e ((mtimes) -1 x)))) grad) Integral of Exponential Integral E1 (defprop %expintegral_e1 ((z) ((mtimes) -1 ((%expintegral_e) 2 z))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_e1 simplim%expintegral_e1 simplim%function) (defun simplim%expintegral_e1 (expr var val) ;; Look for the limit of the argument. (let ((z (limit (cadr expr) var val 'think))) (cond ;; Handle an argument 0 at this place ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) ;; limit is inf from both sides '$inf) (t ;; All other cases are handled by the simplifier of the function. (take '(%expintegral_e1) z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral_e1 (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check for special values ((or (eq arg '$inf) (alike1 arg '((mtimes) -1 $minf))) 0) ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_e1: expintegral_e1(~:M) is undefined.") arg)) ;; Check for numerical evaluation ((complex-float-numerical-eval-p arg) ;; For E1 we call En(z) with n=1 directly. (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e 1 carg)))) ((complex-bigfloat-numerical-eval-p arg) ;; For E1 we call En(z) with n=1 directly. (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e 1 carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ;; Check argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag* :test #'eq) (not (eq $expintrep '%expintegral_e1))) (case $expintrep (%gamma_incomplete (take '(%gamma_incomplete) 0 arg)) (%expintegral_ei (add (mul -1 (take '(%expintegral_ei) (mul -1 arg))) (mul (inv 2) (sub (take '(%log) (mul -1 arg)) (take '(%log) (mul -1 (inv arg))))) (mul -1 (take '(%log) arg)))) (%expintegral_li (add (mul -1 (take '(%expintegral_li) (power '$%e (mul -1 arg)))) (mul -1 (take '(%log) arg)) (mul (inv 2) (sub (take '(%log) (mul -1 arg)) (take '(%log) (mul -1 (inv arg))))))) ($expintegral_trig (add (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg))) (mul -1 (take '(%expintegral_ci) (mul '$%i arg))) (take '(%log) (mul '$%i arg)) (mul -1 (take '(%log) arg)))) ($expintegral_hyp (sub (take '(%expintegral_shi) arg) (take '(%expintegral_chi) arg))) (t (eqtest (list '(%expintegral_e1) arg) expr)))) (t (eqtest (list '(%expintegral_e1) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 3 : The implementation of the Exponential Integral Ei ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_ei (z) (simplify (list '(%expintegral_ei) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_ei %expintegral_ei alias) (defprop $expintegral_ei %expintegral_ei verb) (defprop %expintegral_ei $expintegral_ei reversealias) (defprop %expintegral_ei $expintegral_ei noun) Exponential Integral Ei is a simplifying function (defprop %expintegral_ei simp-expintegral-ei operators) Exponential Integral Ei distributes over bags (defprop %expintegral_ei (mlist $matrix mequal) distribute_over) Exponential Integral Ei has mirror symmetry (defprop %expintegral_ei t commutes-with-conjugate) ;;; Differentiation of Exponential Integral Ei (defprop %expintegral_ei ((x) ((mtimes) ((mexpt) x -1) ((mexpt) $%e x))) grad) Integral of Exponential Ei (defprop %expintegral_ei ((x) ((mplus) ((mtimes) -1 ((mexpt) $%e x)) ((mtimes) x ((%expintegral_ei) x)))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_ei simplim%expintegral_ei simplim%function) (defun simplim%expintegral_ei (expr var val) ;; Look for the limit of the arguments. (let ((z (limit (cadr expr) var val 'think))) (cond ;; Handle an argument 0 at this place ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t ;; All other cases are handled by the simplifier of the function. (take '(%expintegral_ei) z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-ei (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check special values ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_ei: expintegral_ei(~:M) is undefined.") arg)) ((eq arg '$inf) '$inf) ((or (eq arg '$minf) (alike1 arg '((mtimes) -1 $inf))) 0) ((alike1 arg '((mtimes) $%i $inf)) (mul '$%i '$%pi)) ((alike1 arg '((mtimes) -1 $%i $inf)) (mul -1 '$%i '$%pi)) ;; Check numerical evaluation ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-ei carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-ei carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ;; Check argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '%expintegral_ei))) (case $expintrep (%gamma_incomplete (add (mul -1 (take '(%gamma_incomplete) 0 (mul -1 arg))) (mul (inv 2) (sub (take '(%log) arg) (take '(%log) (inv arg)))) (mul -1 (take '(%log) (mul -1 arg))))) (%expintegral_e1 (add (mul -1 (take '(%expintegral_e1) (mul -1 arg))) (mul (inv 2) (sub (take '(%log) arg) (take '(%log) (inv arg)))) (mul -1 (take '(%log) (mul -1 arg))))) (%expintegral_li (take '(%expintegral_li) (power '$%e arg))) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i arg)) (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg))) (mul (inv -2) (sub (take '(%log) (inv arg)) (take '(%log) arg))) (mul -1 (take '(%log) (mul '$%i arg))))) ($expintegral_hyp (add (take '(%expintegral_chi) arg) (take '(%expintegral_shi) arg) (mul (inv -2) (add (take '(%log) (inv arg)) (take '(%log) arg))))))) (t (eqtest (list '(%expintegral_ei) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral Ei(z ): ;;; ;;; We use the following representation (see functions.wolfram.com): ;;; Ei(z ) = -E1(-z ) + 0.5*(log(z)-log(1 / z))-log(-z ) ;;; z is a CL Complex number . Because we evaluate for Complex values we have to take into account the complete Complex phase factors . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-ei (z) (+ (- (expintegral-e 1 (- z))) Carefully compute 1/2*(log(z)-log(1 / z))-log(-z ) , using the branch cuts that we want , not the one that wants . ( Mostly an issue with that support signed zeroes . ) (cond ((> (imagpart z) 0) ;; Positive imaginary part. Add phase %i*%pi. (complex 0 (float pi))) ((< (imagpart z) 0) ;; Negative imaginary part. Add phase -%i*%pi. (complex 0 (- (float pi)))) ((> (realpart z) 0) ;; Positive real value. Add phase -%i*pi. (complex 0 (- (float pi)))) ;; Negative real value. No phase factor. (t 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; We have not modified the algorithm for Bigfloat numbers . It is only generalized for Bigfloats . The calcualtion of the complex phase factor can be simplified to conditions about the sign of the realpart and imagpart . We leave this for further work to optimize the speed of the ;;; calculation. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun bfloat-expintegral-ei (z) (let ((mz (mul -1 z))) (add (cmul (mul -1 bigfloatone) (bfloat-expintegral-e 1 mz)) (sub (cmul (div bigfloatone 2) (sub (take '(%log) z) (take '(%log) (cdiv bigfloatone z)))) (take '(%log) mz))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Part 4: The implementation of the Logarithmic integral li(z) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_li (z) (simplify (list '(%expintegral_li) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_li %expintegral_li alias) (defprop $expintegral_li %expintegral_li verb) (defprop %expintegral_li $expintegral_li reversealias) (defprop %expintegral_li $expintegral_li noun) Exponential Integral Li is a simplifying function (defprop %expintegral_li simp-expintegral-li operators) Exponential Integral Li distributes over bags (defprop %expintegral_li (mlist $matrix mequal) distribute_over) Exponential Integral Li has mirror symmetry , ;;; but not on the real negative axis. (defprop %expintegral_li conjugate-expintegral-li conjugate-function) (defun conjugate-expintegral-li (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_li) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_li) z)))))) ;;; Differentiation of Exponential Integral Li (defprop %expintegral_li ((x) ((mtimes) ((mexpt) ((%log) x) -1))) grad) Integral of Exponential Li (defprop %expintegral_li ((x) ((mplus) ((mtimes) x ((%expintegral_li) x)) ((mtimes) -1 ((%expintegral_ei) ((mtimes) 2 ((%log) x)))))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_li simplim%expintegral_li simplim%function) (defun simplim%expintegral_li (expr var val) ;; Look for the limit of the argument. (let ((z (limit (cadr expr) var val 'think))) (cond ;; Handle an argument 1 at this place ((onep1 z) '$minf) (t ;; All other cases are handled by the simplifier of the function. (take '(%expintegral_li) z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-li (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) arg) ((onep1 arg) (simp-domain-error (intl:gettext "expintegral_li: expintegral_li(~:M) is undefined.") arg)) ((eq arg '$inf) '$inf) ((eq arg '$infinity) '$infinity) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-li carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-li carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ;; Check for argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '%expintegral_li))) (let ((logarg (take '(%log) arg))) (case $expintrep (%gamma_incomplete (add (mul -1 (take '(%gamma_incomplete) 0 (mul -1 logarg))) (mul (inv 2) (sub (take '(%log) logarg) (take '(%log) (inv logarg)))) (mul -1 (take '(%log) (mul -1 logarg))))) (%expintegral_e1 (add (mul -1 (take '(%expintegral_e1) (mul -1 logarg))) (mul (inv 2) (sub (take '(%log) logarg) (take '(%log) (inv logarg)))) (mul -1 (take '(%log) (mul -1 logarg))))) (%expintegral_ei ($expintegral_ei logarg)) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i logarg)) (mul -1 '$%i (take '(%expintegral_si) (mul '$%i logarg))) (mul (inv -2) (sub (take '(%log) (inv logarg)) (take '(%log) logarg))) (mul -1 (take '(%log) (mul '$%i logarg))))) ($expintegral_hyp (add (take '(%expintegral_chi) logarg) (take '(%expintegral_shi) logarg) (mul (inv -2) (add (take '(%log) (inv logarg)) (take '(%log) logarg)))))))) (t (eqtest (list '(%expintegral_li) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the ;;; ;;; We use the representation: ;;; Li(z ) = Ei(log(z ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-li (z) (expintegral-ei (log z))) (defun bfloat-expintegral-li (z) (bfloat-expintegral-ei ($log z))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 5 : The implementation of the Exponential Integral Si ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_si (z) (simplify (list '(%expintegral_si) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_si %expintegral_si alias) (defprop $expintegral_si %expintegral_si verb) (defprop %expintegral_si $expintegral_si reversealias) (defprop %expintegral_si $expintegral_si noun) Exponential Integral Si is a simplifying function (defprop %expintegral_si simp-expintegral-si operators) Exponential Integral Si distributes over bags (defprop %expintegral_si (mlist $matrix mequal) distribute_over) Exponential Integral Si has mirror symmetry (defprop %expintegral_si t commutes-with-conjugate) Exponential Integral Si is a odd function (defprop %expintegral_si odd-function-reflect reflection-rule) ;;; Differentiation of Exponential Integral Si (defprop %expintegral_si ((x) ((mtimes) ((%sin) x) ((mexpt) x -1))) grad) Integral of Exponential Si (defprop %expintegral_si ((x) ((mplus) ((%cos) x) ((mtimes) x ((%expintegral_si) x)))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-si (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check for special values ((zerop1 arg) arg) ((eq arg '$inf) (div '$%pi 2)) ((eq arg '$minf) (mul -1 (div '$%pi 2))) ((alike1 arg '((mtimes) -1 $inf)) (mul -1 (div '$%pi 2))) ;; Check for numerical evaluation ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-si carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-si carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ;; Check for argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((apply-reflection-simp (mop expr) arg $trigsign)) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_trig))) (case $expintrep (%gamma_incomplete (mul (div '$%i 2) (add (take '(%gamma_incomplete) 0 (mul -1 '$%i arg)) (mul -1 (take '(%gamma_incomplete) 0 (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg)))))) (%expintegral_e1 (mul (div '$%i 2) (add (take '(%expintegral_e1) (mul -1 '$%i arg)) (mul -1 (take '(%expintegral_e1) (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg)))))) (%expintegral_ei (mul (div '$%i 4) (add (mul 2 (sub (take '(%expintegral_ei) (mul -1 '$%i arg)) (take '(%expintegral_ei) (mul '$%i arg)))) (take '(%log) (div '$%i arg)) (mul -1 (take '(%log) (mul -1 (div '$%i arg)))) (mul -1 (take '(%log) (mul -1 '$%i arg))) (take '(%log) (mul '$%i arg))))) (%expintegral_li (mul (inv (mul 2 '$%i)) (add (take '(%expintegral_li) (power '$%e (mul '$%i arg))) (mul -1 (take '(%expintegral_li) (power '$%e (mul -1 '$%e arg)))) (mul (div '$%pi -2) (take '(%signum) ($realpart arg)))))) ($expintegral_hyp (mul -1 '$%i (take '(%expintegral_shi) (mul '$%i arg)))))) (t (eqtest (list '(%expintegral_si) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral Si ;;; ;;; We use the representation: ;;; ;;; Si(z) = %i/2 * (E1(-%i*z) - E1(*%i*z) + log(%i*z) - log(-%i*z)) ;;; For the Sin , Cos , Sinh and Cosh Exponential Integrals we have to call the ;;; numerical evaluation twice. In principle we could use a direct expansion ;;; in a power series or continued fractions to optimize the speed of the code. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-si (z) (let ((z (coerce z '(complex flonum)))) (* (complex 0 0.5) (+ (expintegral-e 1 (* (complex 0 -1) z)) (- (expintegral-e 1 (* (complex 0 1) z))) (log (* (complex 0 -1) z)) (- (log (* (complex 0 1) z))))))) (defun bfloat-expintegral-si (z) (let ((z*%i (cmul '$%i z)) (mz*%i (cmul (mul -1 '$%i) z))) (cmul (mul 0.5 '$%i) (add (bfloat-expintegral-e 1 mz*%i) (mul -1 (bfloat-expintegral-e 1 z*%i)) ($log mz*%i) (mul -1 ($log z*%i)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 6 : The implementation of the Exponential Integral Shi ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_shi (z) (simplify (list '(%expintegral_shi) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_shi %expintegral_shi alias) (defprop $expintegral_shi %expintegral_shi verb) (defprop %expintegral_shi $expintegral_shi reversealias) (defprop %expintegral_shi $expintegral_shi noun) Exponential Integral Shi is a simplifying function (defprop %expintegral_shi simp-expintegral-shi operators) Exponential Integral Shi distributes over bags (defprop %expintegral_shi (mlist $matrix mequal) distribute_over) Exponential Integral Shi has mirror symmetry (defprop %expintegral_si t commutes-with-conjugate) Exponential Integral Shi is a odd function (defprop %expintegral_si odd-function-reflect reflection-rule) ;;; Differentiation of Exponential Integral Shi (defprop %expintegral_shi ((x) ((mtimes) ((%sinh) x) ((mexpt) x -1))) grad) Integral of Exponential Shi (defprop %expintegral_shi ((x) ((mplus) ((mtimes) -1 ((%cosh) x)) ((mtimes) x ((%expintegral_shi) x)))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-shi (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check for special values ((zerop1 arg) arg) ((alike1 arg '((mtimes) '$%i $inf)) (div (mul '$%i '$%pi) 2)) ((alike1 arg '((mtimes) -1 '$%i $inf)) (div (mul -1 '$%i '$%pi) 2)) ;; Check for numrical evaluation ((float-numerical-eval-p arg) (realpart (expintegral-shi arg))) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-shi carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-shi carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ;; Check for argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((apply-reflection-simp (mop expr) arg $trigsign)) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_hyp))) (case $expintrep (%gamma_incomplete (mul (inv 2) (add (take '(%gamma_incomplete) 0 arg) (mul -1 (take '(%gamma_incomplete) 0 (mul -1 arg))) (mul -1 (take '(%log) (mul -1 arg))) (take '(%log) arg)))) (%expintegral_e1 (mul (inv 2) (add (take '(%expintegral_e1) arg) (mul -1 (take '(%expintegral_e1) (mul -1 arg))) (mul -1 (take '(%log) (mul -1 arg))) (take '(%log) arg)))) (%expintegral_ei (mul (inv 4) (add (mul 2 (sub (take '(%expintegral_ei) arg) (take '(%expintegral_ei) (mul -1 arg)))) (take '(%log) (inv arg)) (mul -1 (take '(%log) (mul -1 (inv arg)))) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_li (add (mul (inv 2) (sub (take '(%expintegral_li) (power '$%e arg)) (take '(%expintegral_li) (power '$%e (mul -1 arg))))) (mul (div (mul '$%i '$%pi) -2) (take '(%signum) ($imagpart arg))))) ($expintegral_trig (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg)))))) (t (eqtest (list '(%expintegral_shi) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral Shi ;;; ;;; We use the representation: ;;; Shi(z ) = 1/2 * ( E1(z ) - E1(-z ) - log(-z ) + log(z ) ) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-shi (z) (* 0.5 (+ (expintegral-e 1 z) (- (expintegral-e 1 (- z))) (- (log (- z))) (log z)))) (defun bfloat-expintegral-shi (z) (let ((mz (mul -1 z))) (mul 0.5 (add (bfloat-expintegral-e 1 z) (mul -1 (bfloat-expintegral-e 1 mz)) (mul -1 ($log mz)) ($log z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Part 7 : The implementation of the Exponential Integral Ci ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_ci (z) (simplify (list '(%expintegral_ci) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_ci %expintegral_ci alias) (defprop $expintegral_ci %expintegral_ci verb) (defprop %expintegral_ci $expintegral_ci reversealias) (defprop %expintegral_ci $expintegral_ci noun) Exponential Integral Ci is a simplifying function (defprop %expintegral_ci simp-expintegral-ci operators) Exponential Integral Ci distributes over bags (defprop %expintegral_ci (mlist $matrix mequal) distribute_over) Exponential Integral Ci has mirror symmetry , ;;; but not on the real negative axis. (defprop %expintegral_ci conjugate-expintegral-ci conjugate-function) (defun conjugate-expintegral-ci (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_ci) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_ci) z)))))) ;;; Differentiation of Exponential Integral Ci (defprop %expintegral_ci ((x) ((mtimes) ((%cos) x) ((mexpt) x -1))) grad) Integral of Exponential Ci (defprop %expintegral_ci ((x) ((mplus) ((mtimes) x ((%expintegral_ci) x)) ((mtimes) -1 ((%sin) x)))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_ci simplim%expintegral_ci simplim%function) (defun simplim%expintegral_ci (expr var val) ;; Look for the limit of the argument. (let ((z (limit (cadr expr) var val 'think))) (cond ;; Handle an argument 0 at this place ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t ;; All other cases are handled by the simplifier of the function. (take '(%expintegral_ci) z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-ci (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check for special values ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_ci: expintegral_ci(~:M) is undefined.") arg)) ((eq arg '$inf) 0) ((eq arg '$minf) (mul '$%i '$%pi)) ((alike1 arg '((mtimes) -1 $inf)) (mul '$%pi '$%pi)) ;; Check for numerical evaluation ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-ci carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-ci carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ;; Check for argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_trig))) (case $expintrep (%gamma_incomplete (sub (take '(%log) arg) (mul (inv 2) (add (take '(%gamma_incomplete) 0 (mul -1 '$%i arg)) (take '(%gamma_incomplete) 0 (mul '$%i arg)) (take '(%log) (mul -1 '$%i arg)) (take '(%log) (mul '$%i arg)))))) (%expintegral_e1 (add (mul (inv -2) (add (take '(%expintegral_e1) (mul -1 '$%i arg)) (take '(%expintegral_e1) (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (take '(%log) (mul '$%i arg))) (take '(%log) arg))) (%expintegral_ei (add (mul (inv 4) (add (mul 2 (add (take '(%expintegral_ei) (mul -1 '$%i arg)) (take '(%expintegral_ei) (mul '$%i arg)))) (take '(%log) (div '$%i arg)) (take '(%log) (mul -1 '$%i (inv arg))) (mul -1 (take '(%log) (mul -1 '$%i arg))) (mul -1 (take '(%log) (mul '$%i arg))))) (take '(%log) arg))) (%expintegral_li (add (mul (inv 2) (add (take '(%expintegral_li) (power '$%e (mul -1 '$%i arg))) (take '(%expintegral_li) (power '$%e (mul '$%i arg))))) (mul (div (mul '$%i '$%pi) 2) (take '(%signum) ($imagpart arg))) (sub 1 (take '(%signum) ($realpart arg))))) ($expintegral_hyp (add (take '(%expintegral_chi) (mul '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg))) (take '(%log) arg))))) (t (eqtest (list '(%expintegral_ci) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral Ci ;;; ;;; We use the representation: ;;; ;;; Ci(z) = -1/2 * (E1(-%i*z) + E1(%i*z) + log(-%i*z) + log(%i*z)) + log(z) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-ci (z) (let ((z (coerce z '(complex flonum)))) (+ (* -0.5 (+ (expintegral-e 1 (* (complex 0 -1) z)) (expintegral-e 1 (* (complex 0 1) z)) (log (* (complex 0 -1) z)) (log (* (complex 0 1) z)))) (log z)))) (defun bfloat-expintegral-ci (z) (let ((z*%i (cmul '$%i z)) (mz*%i (cmul (mul -1 '$%i) z))) (add (cmul -0.5 (add (bfloat-expintegral-e 1 mz*%i) (bfloat-expintegral-e 1 z*%i) ($log mz*%i) ($log z*%i))) ($log z)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Part 8: The implementation of the Exponential Integral Chi ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun $expintegral_chi (z) (simplify (list '(%expintegral_chi) z))) ;;; Set properties to give full support to the parser and display (defprop $expintegral_chi %expintegral_chi alias) (defprop $expintegral_chi %expintegral_chi verb) (defprop %expintegral_chi $expintegral_chi reversealias) (defprop %expintegral_chi $expintegral_chi noun) Exponential Integral Chi is a simplifying function (defprop %expintegral_chi simp-expintegral-chi operators) Exponential Integral Chi distributes over bags (defprop %expintegral_chi (mlist $matrix mequal) distribute_over) Exponential Integral Chi has mirror symmetry , ;;; but not on the real negative axis. (defprop %expintegral_chi conjugate-expintegral-chi conjugate-function) (defun conjugate-expintegral-chi (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_chi) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_chi) z)))))) ;;; Differentiation of Exponential Integral Chi (defprop %expintegral_chi ((x) ((mtimes) ((%cosh) x) ((mexpt) x -1))) grad) Integral of Exponential Chi (defprop %expintegral_chi ((x) ((mplus) ((mtimes) x ((%expintegral_chi) x)) ((mtimes) -1 ((%sinh) x)))) integral) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; We support a simplim%function. The function is looked up in simplimit and ;;; handles specific values of the function. (defprop %expintegral_chi simplim%expintegral_chi simplim%function) (defun simplim%expintegral_chi (expr var val) ;; Look for the limit of the argument. (let ((z (limit (cadr expr) var val 'think))) (cond ;; Handle an argument 0 at this place ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t ;; All other cases are handled by the simplifier of the function. (take '(%expintegral_chi) z))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun simp-expintegral-chi (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ;; Check for special values ((zerop1 arg) First check for zero argument . Throw Maxima error . (simp-domain-error (intl:gettext "expintegral_chi: expintegral_chi(~:M) is undefined.") arg)) ((alike1 arg '((mtimes) $%i $inf)) (div (mul '$%pi '$%i) 2)) ((alike1 arg '((mtimes) -1 $%i $inf)) (div (mul -1 '$%pi '$%i) 2)) ;; Check for numerical evaluation ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-chi carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-chi carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ;; Check for argument simplifications and transformations ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_hyp))) (case $expintrep (%gamma_incomplete (mul (inv -2) (add (take '(%gamma_incomplete) 0 (mul -1 arg)) (take '(%gamma_incomplete) 0 arg) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_e1 (mul (inv -2) (add (take '(%expintegral_e1) (mul -1 arg)) (take '(%expintegral_e1) arg) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_ei (mul (inv 4) (add (mul 2 (add (take '(%expintegral_ei) (mul -1 arg)) (take '(%expintegral_ei) arg))) (take '(%log) (inv arg)) (take '(%log) (mul -1 (inv arg))) (mul -1 (take '(%log) (mul -1 arg))) (mul 3 (take '(%log) arg))))) (%expintegral_li (add (mul (inv 2) (add (take '(%expintegral_li) (power '$%e (mul -1 arg))) (take '(%expintegral_li) (power '$%e arg)))) (mul (div (mul '$%i '$%pi) 2) (take '(%signum) ($imagpart arg))) (mul (inv 2) (add (take '(%log) (inv arg)) (take '(%log) arg))))) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i arg)) (take '(%log) arg) (mul -1 (take '(%log) (mul '$%i arg))))))) (t (eqtest (list '(%expintegral_chi) arg) expr))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Numerical evaluation of the Exponential Integral Ci ;;; ;;; We use the representation: ;;; Chi(z ) = -1/2 * ( E1(-z ) + E1(z ) + log(-z ) - log(z ) ) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun expintegral-chi (z) (* -0.5 (+ (expintegral-e 1 z) (expintegral-e 1 (- z)) (log (- z)) (- (log z))))) (defun bfloat-expintegral-chi (z) (let ((mz (mul -1 z))) (mul -0.5 (add (bfloat-expintegral-e 1 z) (bfloat-expintegral-e 1 mz) ($log mz) (mul -1 ($log z)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Moved from bessel.lisp 2008 - 12 - 11 . Consider deleting it . ;; Exponential integral E1(x ) . The Cauchy principal value is used for ;; negative x. (defun $expint (x) (cond ((numberp x) (values (slatec:de1 (float x)))) (t (list '($expint simp) x))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/expintegral.lisp
lisp
$expintegral_e (n,z) - Exponential Integral En(z) $expintegral_li (z) - Logarithmic Integral Li(z) $expint (x) - Exponential Integral E1(x) (depreciated) expintegral_li, expintegral_trig, expintegral_hyp for positive integers in terms of Ei The following features are implemented: using an expansion in a power series or continued fractions. a finite series in terms of powers and the Exponential function. b) for n a positive integer number in terms of Ei This library is free software; you can redistribute it and/or modify it either version 2 of the License , or ( at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU with this library; if not, write to the Free Software Globals to help debugging the code Global to this file Set properties to give full support to the parser and display but not on the real negative axis. Differentiation of Exponential Integral E The derivative wrt the parameter n is expressed in terms of the The derivative wrt the argument of the function We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the arguments. Special case order a=1 from above, always inf this can be further improved to give a directed infinity no direction, return infinity All other cases are handled by the simplifier of the function. Check for special values we handle the special case E[v](0) = 1/(v-1), for realpart(v)>1 order or arg is one of the infinities, we return a noun form, but we have already handled the special value inf for arg. The parameter of the Exponential integral is an integer. For this case we can do further simplifications or numerical evaluation. Special case E[0](z) = %e^(-z)/z, z<>0 We expand in a series, z<>0 Numerical evaluation for double float real or complex arg if the expand flag is set. We transform to the Incomplete Gamma function. representation of an integer value. We call the routine for an integer order. The general case, order and arg are complex or real. We call the routine for an integer order. We transform to the Incomplete Gamma function. The following numerical routines are implemented: expintegral-e - n positive integer, z real or complex frac-expintegral-e - n,z real or complex; n not a positive integer bfloat-expintegral-e - n positive integer, function the evaluation for a Complex Bigfloat parameter don't give the desiered accuracy. check the values. We don't handle any special case. This has to be done by the calling routine. The evaluation uses an expansion in continued fractions for arguments with and the argument z: En(z) = e^(-z) * ( --- --- --- --- --- ... ) z+ 1+ z+ 1+ z+ for the more rapidly converging even form. For the parameter n an positive integer we do an expansion in a power series (A&S 5.1.12): inf === (-z)^(n-1) \ (-z)^m En(z) = --------- * (-log(z)+psi(n)) * > ---------- ; n an integer (n-1)! / (m-n+1)*m! === m=0 (m <> n-1) For an parameter n not an integer we expand in the following series (functions.wolfram.com ): inf === Ev(z) = gamma(1-v) * z^(v-1) * > ------------- ; n not an integer / (m-v+1)*m! === m=0 The evaluation stops if an accuracy better than *expint-eps* is achived. Error is thrown. Constants to terminate the numerical evaluation value to the desired precision of the global $fpprec. evaluation this number is for very Big numbers too small. The maximum iterations counted for the test file rtest-expintegral.mac are Add (complex) 0 to get rid of any signed zeroes, and make z be a complex number. (abs z)>2.0 is necessary since there is a point still c-f expansion does not converge. We expand in continued fractions. We expand in a power series. Numerical evaluation for a real or complex parameter. We expand in continued fractions. We have a positive integer n or an float representation of an integer. We call expintegral-e which does this calculation. At this point the parameter n is a real (not an float representation of an integer) or complex. We expand in a power series. It would be possible to call the numerical implementation details of the implementation. We have not changed the above algorithm, but generalized it to handle algorithm some of the additional calls to $rectform can be eliminated. But the algorithm works and so we leave the extra calls for later work in the code. The accuracy of the result is determined by *expint-eps*. The value is chosen to correspond to the value of $fpprec. We don't give any extra arbitrarily chosen, we need a better choice The same condition as you see in expintegral-e() We expand in continued fractions. We expand in a power series. The algorithm would work for a Complex Bigfloat paramter too. But we arbitrarily chosen, we need a better choice We expand in continued fractions. We call bfloat-expintegral-e. At this point the parameter n is a real (not a float representation of an integer) or complex. We expand in a power series. Set properties to give full support to the parser and display but not on the real negative axis. Differentiation of Exponential Integral E1 We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the argument. Handle an argument 0 at this place limit is inf from both sides All other cases are handled by the simplifier of the function. Check for special values Check for numerical evaluation For E1 we call En(z) with n=1 directly. For E1 we call En(z) with n=1 directly. Check argument simplifications and transformations Set properties to give full support to the parser and display Differentiation of Exponential Integral Ei We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the arguments. Handle an argument 0 at this place All other cases are handled by the simplifier of the function. Check special values Check numerical evaluation Check argument simplifications and transformations We use the following representation (see functions.wolfram.com): Positive imaginary part. Add phase %i*%pi. Negative imaginary part. Add phase -%i*%pi. Positive real value. Add phase -%i*pi. Negative real value. No phase factor. calculation. Part 4: The implementation of the Logarithmic integral li(z) Set properties to give full support to the parser and display but not on the real negative axis. Differentiation of Exponential Integral Li We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the argument. Handle an argument 1 at this place All other cases are handled by the simplifier of the function. Check for argument simplifications and transformations We use the representation: Set properties to give full support to the parser and display Differentiation of Exponential Integral Si Check for special values Check for numerical evaluation Check for argument simplifications and transformations We use the representation: Si(z) = %i/2 * (E1(-%i*z) - E1(*%i*z) + log(%i*z) - log(-%i*z)) numerical evaluation twice. In principle we could use a direct expansion in a power series or continued fractions to optimize the speed of the code. Set properties to give full support to the parser and display Differentiation of Exponential Integral Shi Check for special values Check for numrical evaluation Check for argument simplifications and transformations We use the representation: Set properties to give full support to the parser and display but not on the real negative axis. Differentiation of Exponential Integral Ci We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the argument. Handle an argument 0 at this place All other cases are handled by the simplifier of the function. Check for special values Check for numerical evaluation Check for argument simplifications and transformations We use the representation: Ci(z) = -1/2 * (E1(-%i*z) + E1(%i*z) + log(-%i*z) + log(%i*z)) + log(z) Part 8: The implementation of the Exponential Integral Chi Set properties to give full support to the parser and display but not on the real negative axis. Differentiation of Exponential Integral Chi We support a simplim%function. The function is looked up in simplimit and handles specific values of the function. Look for the limit of the argument. Handle an argument 0 at this place All other cases are handled by the simplifier of the function. Check for special values Check for numerical evaluation Check for argument simplifications and transformations We use the representation: negative x.
Exponential Integrals This file contains the following Maxima User functions : $ expintegral_e1 ( z ) - Exponential Integral E1(z ) $ expintegral_ei ( z ) - Exponential Integral Ei(z ) $ expintegral_si ( z ) - Exponential Integral Si(z ) $ expintegral_ci ( z ) - Exponential Integral Ci(z ) $ expintegral_shi ( z ) - Exponential Integral Shi(z ) $ expintegral_chi ( z ) - Exponential Integral Chi(z ) Global variables for the Maxima User : $ expintrep - Change the representation of the Exponential Integral to gamma_incomplete , expintegral_e1 , expintegral_ei , $ expintexpand - Expand the Exponential Integral E[n](z ) for half integral values in terms of or Erf and 1 . Numerical evaluation for complex and Bigfloat numbers The numerical support is fully implemented for the E[n](z ) function . All other functions call E[n](z ) for numerical evaluation . 2 . For a negative integer parameter E[n](z ) is automatically expanded in 3 . When $ expintexpand is set to TRUE or ERF E[n](z ) expands a ) for n a half integral number in terms of ( TRUE ) or Erf ( ERF ) 3 . Simplifications for special values : Ev(0 ) , E[0](z ) , Li(0 ) , ) , ... 4 . Derivatives of the Exponential Integrals 5 . Change the representation of every Exponential Integral through other Exponential Integrals or the Incomplete Gamma function . 6 . Mirror symmetry for all functions and reflection symmetry for and are implemented . 7 . Handling of expansions as argument . under the terms of the GNU General Public License as published by the Library General Public License for more details . You should have received a copy of the GNU General Public License along Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . Copyright ( C ) 2008 (in-package :maxima) (defvar *debug-expintegral* nil "When enabled print debug information.") (defvar *debug-expint-maxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-fracmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-bfloatmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") (defvar *debug-expint-fracbfloatmaxit* 0 "When in debug mode count the maximum of iterations needed by the algorithm.") Globals for the Maxima Users (defvar $expintexpand nil "When not nil we expand for a half integral parameter of the Exponetial Integral in a series in terms of the Erfc or Erf function and for positive integer in terms of the Ei function.") (defvar $expintrep nil "Change the representation of the Exponential Integral. Values are: gamma_incomplete, expintegral_e1, expintegral_ei, expintegral_li, expintegral_trig, expintegral_hyp.") (defvar *expintflag* '(%expintegral_e1 %expintegral_ei %expintegral_li $expintegral_trig $expintegral_hyp %gamma_incomplete) "Allowed flags to transform the Exponential Integral.") (defun simp-domain-error (&rest args) (if errorsw (throw 'errorsw t) (apply #'merror args))) Part 1 : The implementation of the Exponential Integral En (defun $expintegral_e (v z) (simplify (list '(%expintegral_e) v z))) (defprop $expintegral_e %expintegral_e alias) (defprop $expintegral_e %expintegral_e verb) (defprop %expintegral_e $expintegral_e reversealias) (defprop %expintegral_e $expintegral_e noun) Exponential Integral E is a simplifying function (defprop %expintegral_e simp-expintegral-e operators) Exponential Integral E distributes over bags (defprop %expintegral_e (mlist $matrix mequal) distribute_over) Exponential Integral E has mirror symmetry , (defprop %expintegral_e conjugate-expintegral-e conjugate-function) (defun conjugate-expintegral-e (args) (let ((n (first args)) (z (second args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_e) (take '($conjugate) n) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_e) n z)))))) (defprop %expintegral_e ((n z) function 2F2 ( see functions.wolfram.com ) ((mplus) ((mtimes) -1 (($hypergeometric_regularized) ((mlist) ((mplus) 1 ((mtimes) -1 n)) ((mplus) 1 ((mtimes) -1 n))) ((mlist) ((mplus) 2 ((mtimes) -1 n)) ((mplus) 2 ((mtimes) -1 n))) ((mtimes) -1 z)) ((mexpt) ((%gamma) ((mplus) 1 ((mtimes) -1 n))) 2)) ((mtimes) ((%gamma) ((mplus) 1 ((mtimes) -1 n))) ((mexpt) z ((mplus) -1 n)) ((mplus) ((mtimes) -1 ((mqapply) (($psi array) 0) ((mplus) 1 ((mtimes) -1 n)))) ((%log) z)))) ((mtimes) -1 ((%expintegral_e) ((mplus) -1 n) z))) grad) Integral of Exponential Integral E (defprop %expintegral_e ((n z) nil ((mtimes) -1 ((%expintegral_e) ((mplus) 1 n) z))) integral) (defprop %expintegral_e simplim%expintegral_e simplim%function) (defun simplim%expintegral_e (expr var val) (let ((a (limit (cadr expr) var val 'think)) (z (limit (caddr expr) var val 'think))) (cond ((and (onep1 a) (or (eq z '$zeroa) (eq z '$zerob) (zerop1 z))) '$inf) ((member ($sign (add ($realpart a) -1)) '($neg $nz $zero)) realpart of order < 1 (cond ((eq z '$zeroa) '$inf) ((eq z '$zerob) '$infinity) ((zerop1 z) '$infinity) (t ($expintegral_e a z)))) (t ($expintegral_e a z))))) (defun simp-expintegral-e (expr ignored z) (declare (ignore ignored)) (twoargcheck expr) (let ((order (simpcheck (cadr expr) z)) (arg (simpcheck (caddr expr) z)) (ratorder)) (cond ((or (eq arg '$inf) (alike1 arg '((mtimes) -1 $minf))) arg is inf or -minf , return zero 0) ((zerop1 arg) (let ((sgn ($sign (add ($realpart order) -1)))) (cond ((eq sgn '$pos) (inv (add order -1))) ((member sgn '($neg $nz $zero)) (simp-domain-error (intl:gettext "expintegral_e: expintegral_e(~:M,~:M) is undefined.") order arg)) (t (eqtest (list '(%expintegral_e) order arg) expr))))) ((or (and (symbolp order) (member order infinities)) (and (symbolp arg) (member arg infinities))) (eqtest (list '(%expintegral_e) order arg) expr)) ((and (numberp order) (integerp order)) (cond ((= order 0) The case z=0 is already handled . (div (power '$%e (mul -1 arg)) arg)) ((= order -1) Special case ) = ( ( z+1)*%e^(-z))/z^2 , z<>0 The case z=0 is already handled . (div (mul (power '$%e (mul -1 arg)) (add arg 1)) (mul arg arg))) ((< order -1) (mul (factorial (- order)) (power arg (+ order -1)) (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg index) (take '(mfactorial) index)) index 0 (- order) t)))) ((and (> order 0) (complex-float-numerical-eval-p arg)) order is an integer > 0 and arg < > 0 for order < 2 (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e order carg)))) ((and (> order 0) (complex-bigfloat-numerical-eval-p arg)) Numerical evaluation for Bigfloat real or complex arg . (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e order carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ((and $expintexpand (> order 0)) We only expand in terms of the Exponential Integral Ei (sub (mul -1 (power (mul -1 arg) (- order 1)) (inv (factorial (- order 1))) (add (take '(%expintegral_ei) (mul -1 arg)) (mul (inv 2) (sub (take '(%log) (mul -1 (inv arg))) (take '(%log) (mul -1 arg)))) (take '(%log) arg))) (mul (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index -1)) (take '($pochhammer) (- 1 order) index)) index 1 (- order 1) t))))) ((eq $expintrep '%gamma_incomplete) (mul (power arg (- order 1)) (take '(%gamma_incomplete) (- 1 order) arg))) (t (eqtest (list '(%expintegral_e) order arg) expr)))) ((complex-float-numerical-eval-p order arg) (cond ((and (setq z (integer-representation-p order)) (plusp z)) We have a pure real positive order and the realpart is a float (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e z carg)))) (t (let ((corder (complex ($float ($realpart order)) ($float ($imagpart order)))) (carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (frac-expintegral-e corder carg)))))) ((complex-bigfloat-numerical-eval-p order arg) (cond ((and (setq z (integer-representation-p order)) (plusp z)) We have a real positive order and the realpart is a Float or Bigfloat representation of an integer value . (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e z carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) (t the general case , order and arg are bigfloat or complex (let* (($ratprint nil) (corder (add ($bfloat ($realpart order)) (mul '$%i ($bfloat ($imagpart order))))) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (frac-bfloat-expintegral-e corder carg))) (add ($realpart result) (mul '$%i ($imagpart result))))))) ((and $expintexpand (setq ratorder (max-numeric-ratio-p order 2))) We have a half integral order and $ expintexpand is not NIL . We expand in a series in terms of the or Erf function . (let ((func (cond ((eq $expintexpand '%erf) (sub 1 ($erf (power arg '((rat simp) 1 2))))) (t ($erfc (power arg '((rat simp) 1 2))))))) (cond ((= ratorder 1/2) (mul (power '$%pi '((rat simp) 1 2)) (power arg '((rat simp) -1 2)) func)) ((= ratorder -1/2) (add (mul (power '$%pi '((rat simp) 1 2)) (inv (mul 2 (power arg '((rat simp) 3 2)))) func) (div (power '$%e (mul -1 arg)) arg))) (t (let ((n (- ratorder 1/2))) (mul (power arg (sub n '((rat simp) 1 2))) (add (mul func (take '(%gamma) (sub '((rat simp) 1 2) n))) (mul (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index '((rat simp) 1 2))) (take '($pochhammer) (sub '((rat simp) 1 2) n) (add index n 1))) index 0 (mul -1 (add n 1)) t))) (mul -1 (power '$%e (mul -1 arg)) (let ((index (gensumindex))) (dosum (div (power arg (add index '((rat simp) 1 2))) (take '($pochhammer) (sub '((rat simp) 1 2) n) (add index n 1))) index (- n) -1 t)))))))))) ((eq $expintrep '%gamma_incomplete) (mul (power arg (sub order 1)) (take '(%gamma_incomplete) (sub 1 order) arg))) (t (eqtest (list '(%expintegral_e) order arg) expr))))) Numerical evaluation of the Exponential Integral En(z ) z Bigfloat or Complex Bigfloat frac - bfloat - expintegral - e - n Bigfloat , or Complex Bigfloat The algorithm are implemented for full support of and real or Complex parameter and argument of the Exponential Integral . Because we have no support for Complex Bigfloat arguments of the Gamma The flonum versions return a CL complex number . The Bigfloat versions a Maxima Complex Bigfloat number . It is assumed that the calling routine realpart(z ) > 0 and abs(z ) > 1.0 ( A&S 5.1.22 ) . This expansion works for every Real or Complex numbers including Bigfloat numbers for the parameter n 1 n 1 n+1 2 The continued fraction is evaluated by the modified 's method \ ( -1)^m * z^m If the expansion do n't converge within * expint - maxit * steps a Maxima The algorithm is based on technics desribed in Numerical Recipes , 2nd . The accuracy * expint - eps * is fixed to 1.0e-15 for double float calculations . The variable is declared global , so we can later give the Maxima User access to the variable . The routine for Bigfloat numerical evaluation change this The maximum number of iterations is arbitrary set to 1000 . For 101 for Complex Flonum and 1672 for Complex Bigfloat evaluation . (defvar *expint-eps* 1.0e-15) (defvar *expint-maxit* 1000) (defun expintegral-e (n z) (declare (type integer n)) (let ((*expint-eps* *expint-eps*) (*expint-maxit* *expint-maxit*) (z (+ (coerce 0 '(complex flonum)) z))) (declare (type (complex flonum) z)) (when *debug-expintegral* (format t "~&EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((or (and (> (abs z) 2.0) (< (abs (phase z)) (* pi 0.9))) -1.700598 - 0.612828*%i which 1<(abs z)<2 , phase z < 0.9pi and (and (>= (realpart z) 0) (> (abs z) 1.0))) (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (+ z n)) (c (/ 1.0 (* *expint-eps* *expint-eps*))) (d (/ 1.0 b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (+ b 2.0)) (setq d (/ 1.0 (+ (* a d) b))) (setq c (+ b (/ a c))) (setq e (* c d)) (setq h (* h e)) (when (< (abs (- e 1.0)) *expint-eps*) (when *debug-expintegral* (setq *debug-expint-maxit* (max *debug-expint-maxit* i))) (return (* h (exp (- z)))))))) (t (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) (euler (mget '$%gamma '$numer)) (r (if (= n1 0) (- (- euler) (log z)) (/ 1.0 n1))) (f 1.0) (e 0.0)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (* -1 f (/ z i))) (cond ((= i n1) (let ((psi (- euler))) (dotimes (ii n1) (setq psi (+ psi (/ 1.0 (+ ii 1))))) (setq e (* f (- psi (log z)))))) (t (setq e (/ (- f) (- i n1))))) (setq r (+ r e)) (when (< (abs e) (* (abs r) *expint-eps*)) (when *debug-expintegral* (setq *debug-expint-maxit* (max *debug-expint-maxit* i))) (return r)))))))) (defun frac-expintegral-e (n z) (declare (type (complex flonum) n) (type (complex flonum) z)) (let ((*expint-eps* *expint-eps*) (*expint-maxit* *expint-maxit*)) (when *debug-expintegral* (format t "~&FRAC-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((and (> (realpart z) 0) (> (abs z) 1.0)) (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (+ z n)) (c (/ 1.0 (* *expint-eps* *expint-eps*))) (d (/ 1.0 b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (+ b 2.0)) (setq d (/ 1.0 (+ (* a d) b))) (setq c (+ b (/ a c))) (setq e (* c d)) (setq h (* h e)) (when (< (abs (- e 1.0)) *expint-eps*) (when *debug-expintegral* (setq *debug-expint-fracmaxit* (max *debug-expint-fracmaxit* i))) (return (* h (exp (- z)))))))) ((and (= (imagpart n) 0) (> (realpart n) 0) (= (nth-value 1 (truncate (realpart n))) 0)) (when *debug-expintegral* (format t "~&We call expintegral-e.~%")) (expintegral-e (truncate (realpart n)) z)) (t (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) gamm - lanczos directly . But then the code would depend on the (gm (let ((tmp (take '(%gamma) (complexify (- 1 n))))) (complex ($realpart tmp) ($imagpart tmp)))) (r (- (* (expt z n1) gm) (/ 1.0 (- 1 n)))) (f 1.0) (e 0.0)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (* -1 f (/ z (float i)))) (setq e (/ (- f) (- (float i) n1))) (setq r (+ r e)) (when (< (abs e) (* (abs r) *expint-eps*)) (when *debug-expintegral* (setq *debug-expint-fracmaxit* (max *debug-expint-fracmaxit* i))) (return r)))))))) Helper functions for Bigfloat numerical evaluation . (defun cmul (x y) ($rectform (mul x y))) (defun cdiv (x y) ($rectform (div x y))) (defun cpower (x y) ($rectform (power x y))) complex and real Bigfloat numbers . By carefully examination of the digits to fpprec , so we loose 1 to 2 digits of precision . One problem is to chose a sufficient big * expint - maxit * . (defun bfloat-expintegral-e (n z) (let ((*expint-eps* (power ($bfloat 10.0) (- $fpprec))) (bigfloattwo (add bigfloatone bigfloatone)) (bigfloat%e ($bfloat '$%e)) (bigfloat%gamma ($bfloat '$%gamma)) (flz (complex ($float ($realpart z)) ($float ($imagpart z))))) (when *debug-expintegral* (format t "~&BFLOAT-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" flz)) (cond ((or (and (> (abs flz) 2) (< (abs (phase flz)) (* pi 0.9))) (and (>= (realpart flz) 0) (> (abs flz) 1.0))) (when *debug-expintegral* (format t "~&We expand in continued fractions.~%")) (let* ((b (add z n)) (c (div bigfloatone (mul *expint-eps* *expint-eps*))) (d (cdiv bigfloatone b)) (n1 (- n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (* -1 n) (* (- i) (+ n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (add b bigfloattwo)) (setq d (cdiv bigfloatone (add (mul a d) b))) (setq c (add b (cdiv a c))) (setq e (cmul c d)) (setq h (cmul h e)) (when (eq ($sign (sub (cabs (sub e bigfloatone)) *expint-eps*)) '$neg) (when *debug-expintegral* (setq *debug-expint-bfloatmaxit* (max *debug-expint-bfloatmaxit* i))) (return (cmul h (cpower bigfloat%e (mul -1 z)))))))) (t (when *debug-expintegral* (format t "~&We expand in a power series.~%")) (let* ((n1 (- n 1)) (meuler (mul -1 bigfloat%gamma)) (r (if (= n1 0) (sub meuler ($log z)) (div bigfloatone n1))) (f bigfloatone) (e bigfloatzero)) (do* ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (mul -1 (cmul f (cdiv z i)))) (cond ((= i n1) (let ((psi meuler)) (dotimes (ii n1) (setq psi (add psi (cdiv bigfloatone (+ ii 1))))) (setq e (cmul f (sub psi ($log z)))))) (t (setq e (cdiv (mul -1 f) (- i n1))))) (setq r (add r e)) (when (eq ($sign (sub (cabs e) (cmul (cabs r) *expint-eps*))) '$neg) (when *debug-expintegral* (setq *debug-expint-bfloatmaxit* (max *debug-expint-bfloatmaxit* i))) (return r)))))))) Numerical Bigfloat evaluation for a real ( Bigfloat ) parameter . need the values of Gamma for Complex Bigfloats . This is at this time ( 2008 ) not implemented in Maxima . (defun frac-bfloat-expintegral-e (n z) (let ((*expint-eps* (power ($bfloat 10.0) (- $fpprec))) (bigfloattwo (add bigfloatone bigfloatone)) (bigfloat%e ($bfloat '$%e)) (bigfloat%gamma ($bfloat '$%gamma))) (when *debug-expintegral* (format t "~&FRAC-BFLOAT-EXPINTEGRAL-E called with:~%") (format t "~& : n = ~A~%" n) (format t "~& : z = ~A~%" z)) (cond ((and (or (eq ($sign ($realpart z)) '$pos) (eq ($sign ($realpart z)) '$zero)) (eq ($sign (sub (cabs z) bigfloatone)) '$pos)) (when *debug-expintegral* (format t "We expand in continued fractions.~%")) (let* ((b (add z n)) (c (div bigfloatone (mul *expint-eps* *expint-eps*))) (d (cdiv bigfloatone b)) (n1 (sub n 1)) (h d) (e 0.0)) (do* ((i 1 (+ i 1)) (a (mul -1 n) (cmul (- i) (add n1 i)))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: continued fractions failed."))) (setq b (add b bigfloattwo)) (setq d (cdiv bigfloatone (add (mul a d) b))) (setq c (add b (cdiv a c))) (setq e (cmul c d)) (setq h (cmul h e)) (when (eq ($sign (sub (cabs (sub e bigfloatone)) *expint-eps*)) '$neg) (when *debug-expintegral* (setq *debug-expint-fracbfloatmaxit* (max *debug-expint-fracbfloatmaxit* i))) (return (cmul h (cpower bigfloat%e (mul -1 z)))))))) ((or (and (numberp n) (= ($imagpart n) 0) (> ($realpart n) 0) (= (nth-value 1 (truncate ($realpart n))) 0)) (and ($bfloatp n) (eq ($sign n) '$pos) (equal (sub (mul 2 ($fix n)) (mul 2 n)) bigfloatzero))) We have a Float or Bigfloat representation of positive integer . (when *debug-expintegral* (format t "frac-Bigfloat with integer ~A~%" n)) (bfloat-expintegral-e ($fix ($realpart n)) z)) (t (when *debug-expintegral* (format t "We expand in a power series.~%")) (let* ((n1 (sub n bigfloatone)) (n2 (sub bigfloatone n)) (gm (take '(%gamma) n2)) (r (sub (cmul (cpower z n1) gm) (cdiv bigfloatone n2))) (f bigfloatone) (e bigfloatzero)) (do ((i 1 (+ i 1))) ((> i *expint-maxit*) (merror (intl:gettext "expintegral_e: series failed."))) (setq f (cmul (mul -1 bigfloatone) (cmul f (cdiv z i)))) (setq e (cdiv (mul -1 f) (sub i n1))) (setq r (add r e)) (when (eq ($sign (sub (cabs e) (cmul (cabs r) *expint-eps*))) '$neg) (when *debug-expintegral* (setq *debug-expint-fracbfloatmaxit* (max *debug-expint-fracbfloatmaxit* i))) (return r)))))))) Part 2 : The implementation of the Exponential Integral E1 (defun $expintegral_e1 (z) (simplify (list '(%expintegral_e1) z))) (defprop $expintegral_e1 %expintegral_e1 alias) (defprop $expintegral_e1 %expintegral_e1 verb) (defprop %expintegral_e1 $expintegral_e1 reversealias) (defprop %expintegral_e1 $expintegral_e1 noun) Exponential Integral E1 is a simplifying function (defprop %expintegral_e1 simp-expintegral_e1 operators) Exponential Integral E1 distributes over bags (defprop %expintegral_e1 (mlist $matrix mequal) distribute_over) Exponential Integral E1 has mirror symmetry , (defprop %expintegral_e1 conjugate-expintegral-e1 conjugate-function) (defun conjugate-expintegral-e1 (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_e1) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_e1) z)))))) (defprop %expintegral_e1 ((x) ((mtimes) -1 ((mexpt) x -1) ((mexpt) $%e ((mtimes) -1 x)))) grad) Integral of Exponential Integral E1 (defprop %expintegral_e1 ((z) ((mtimes) -1 ((%expintegral_e) 2 z))) integral) (defprop %expintegral_e1 simplim%expintegral_e1 simplim%function) (defun simplim%expintegral_e1 (expr var val) (let ((z (limit (cadr expr) var val 'think))) (cond ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$inf) (t (take '(%expintegral_e1) z))))) (defun simp-expintegral_e1 (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((or (eq arg '$inf) (alike1 arg '((mtimes) -1 $minf))) 0) ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_e1: expintegral_e1(~:M) is undefined.") arg)) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-e 1 carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-e 1 carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag* :test #'eq) (not (eq $expintrep '%expintegral_e1))) (case $expintrep (%gamma_incomplete (take '(%gamma_incomplete) 0 arg)) (%expintegral_ei (add (mul -1 (take '(%expintegral_ei) (mul -1 arg))) (mul (inv 2) (sub (take '(%log) (mul -1 arg)) (take '(%log) (mul -1 (inv arg))))) (mul -1 (take '(%log) arg)))) (%expintegral_li (add (mul -1 (take '(%expintegral_li) (power '$%e (mul -1 arg)))) (mul -1 (take '(%log) arg)) (mul (inv 2) (sub (take '(%log) (mul -1 arg)) (take '(%log) (mul -1 (inv arg))))))) ($expintegral_trig (add (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg))) (mul -1 (take '(%expintegral_ci) (mul '$%i arg))) (take '(%log) (mul '$%i arg)) (mul -1 (take '(%log) arg)))) ($expintegral_hyp (sub (take '(%expintegral_shi) arg) (take '(%expintegral_chi) arg))) (t (eqtest (list '(%expintegral_e1) arg) expr)))) (t (eqtest (list '(%expintegral_e1) arg) expr))))) Part 3 : The implementation of the Exponential Integral Ei (defun $expintegral_ei (z) (simplify (list '(%expintegral_ei) z))) (defprop $expintegral_ei %expintegral_ei alias) (defprop $expintegral_ei %expintegral_ei verb) (defprop %expintegral_ei $expintegral_ei reversealias) (defprop %expintegral_ei $expintegral_ei noun) Exponential Integral Ei is a simplifying function (defprop %expintegral_ei simp-expintegral-ei operators) Exponential Integral Ei distributes over bags (defprop %expintegral_ei (mlist $matrix mequal) distribute_over) Exponential Integral Ei has mirror symmetry (defprop %expintegral_ei t commutes-with-conjugate) (defprop %expintegral_ei ((x) ((mtimes) ((mexpt) x -1) ((mexpt) $%e x))) grad) Integral of Exponential Ei (defprop %expintegral_ei ((x) ((mplus) ((mtimes) -1 ((mexpt) $%e x)) ((mtimes) x ((%expintegral_ei) x)))) integral) (defprop %expintegral_ei simplim%expintegral_ei simplim%function) (defun simplim%expintegral_ei (expr var val) (let ((z (limit (cadr expr) var val 'think))) (cond ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t (take '(%expintegral_ei) z))))) (defun simp-expintegral-ei (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_ei: expintegral_ei(~:M) is undefined.") arg)) ((eq arg '$inf) '$inf) ((or (eq arg '$minf) (alike1 arg '((mtimes) -1 $inf))) 0) ((alike1 arg '((mtimes) $%i $inf)) (mul '$%i '$%pi)) ((alike1 arg '((mtimes) -1 $%i $inf)) (mul -1 '$%i '$%pi)) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-ei carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-ei carg))) (add ($realpart result) (mul '$%i ($imagpart result))))) ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '%expintegral_ei))) (case $expintrep (%gamma_incomplete (add (mul -1 (take '(%gamma_incomplete) 0 (mul -1 arg))) (mul (inv 2) (sub (take '(%log) arg) (take '(%log) (inv arg)))) (mul -1 (take '(%log) (mul -1 arg))))) (%expintegral_e1 (add (mul -1 (take '(%expintegral_e1) (mul -1 arg))) (mul (inv 2) (sub (take '(%log) arg) (take '(%log) (inv arg)))) (mul -1 (take '(%log) (mul -1 arg))))) (%expintegral_li (take '(%expintegral_li) (power '$%e arg))) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i arg)) (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg))) (mul (inv -2) (sub (take '(%log) (inv arg)) (take '(%log) arg))) (mul -1 (take '(%log) (mul '$%i arg))))) ($expintegral_hyp (add (take '(%expintegral_chi) arg) (take '(%expintegral_shi) arg) (mul (inv -2) (add (take '(%log) (inv arg)) (take '(%log) arg))))))) (t (eqtest (list '(%expintegral_ei) arg) expr))))) Numerical evaluation of the Exponential Integral Ei(z ): Ei(z ) = -E1(-z ) + 0.5*(log(z)-log(1 / z))-log(-z ) z is a CL Complex number . Because we evaluate for Complex values we have to take into account the complete Complex phase factors . (defun expintegral-ei (z) (+ (- (expintegral-e 1 (- z))) Carefully compute 1/2*(log(z)-log(1 / z))-log(-z ) , using the branch cuts that we want , not the one that wants . ( Mostly an issue with that support signed zeroes . ) (cond ((> (imagpart z) 0) (complex 0 (float pi))) ((< (imagpart z) 0) (complex 0 (- (float pi)))) ((> (realpart z) 0) (complex 0 (- (float pi)))) (t 0)))) We have not modified the algorithm for Bigfloat numbers . It is only generalized for Bigfloats . The calcualtion of the complex phase factor can be simplified to conditions about the sign of the realpart and imagpart . We leave this for further work to optimize the speed of the (defun bfloat-expintegral-ei (z) (let ((mz (mul -1 z))) (add (cmul (mul -1 bigfloatone) (bfloat-expintegral-e 1 mz)) (sub (cmul (div bigfloatone 2) (sub (take '(%log) z) (take '(%log) (cdiv bigfloatone z)))) (take '(%log) mz))))) (defun $expintegral_li (z) (simplify (list '(%expintegral_li) z))) (defprop $expintegral_li %expintegral_li alias) (defprop $expintegral_li %expintegral_li verb) (defprop %expintegral_li $expintegral_li reversealias) (defprop %expintegral_li $expintegral_li noun) Exponential Integral Li is a simplifying function (defprop %expintegral_li simp-expintegral-li operators) Exponential Integral Li distributes over bags (defprop %expintegral_li (mlist $matrix mequal) distribute_over) Exponential Integral Li has mirror symmetry , (defprop %expintegral_li conjugate-expintegral-li conjugate-function) (defun conjugate-expintegral-li (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_li) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_li) z)))))) (defprop %expintegral_li ((x) ((mtimes) ((mexpt) ((%log) x) -1))) grad) Integral of Exponential Li (defprop %expintegral_li ((x) ((mplus) ((mtimes) x ((%expintegral_li) x)) ((mtimes) -1 ((%expintegral_ei) ((mtimes) 2 ((%log) x)))))) integral) (defprop %expintegral_li simplim%expintegral_li simplim%function) (defun simplim%expintegral_li (expr var val) (let ((z (limit (cadr expr) var val 'think))) (cond ((onep1 z) '$minf) (t (take '(%expintegral_li) z))))) (defun simp-expintegral-li (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) arg) ((onep1 arg) (simp-domain-error (intl:gettext "expintegral_li: expintegral_li(~:M) is undefined.") arg)) ((eq arg '$inf) '$inf) ((eq arg '$infinity) '$infinity) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-li carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-li carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '%expintegral_li))) (let ((logarg (take '(%log) arg))) (case $expintrep (%gamma_incomplete (add (mul -1 (take '(%gamma_incomplete) 0 (mul -1 logarg))) (mul (inv 2) (sub (take '(%log) logarg) (take '(%log) (inv logarg)))) (mul -1 (take '(%log) (mul -1 logarg))))) (%expintegral_e1 (add (mul -1 (take '(%expintegral_e1) (mul -1 logarg))) (mul (inv 2) (sub (take '(%log) logarg) (take '(%log) (inv logarg)))) (mul -1 (take '(%log) (mul -1 logarg))))) (%expintegral_ei ($expintegral_ei logarg)) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i logarg)) (mul -1 '$%i (take '(%expintegral_si) (mul '$%i logarg))) (mul (inv -2) (sub (take '(%log) (inv logarg)) (take '(%log) logarg))) (mul -1 (take '(%log) (mul '$%i logarg))))) ($expintegral_hyp (add (take '(%expintegral_chi) logarg) (take '(%expintegral_shi) logarg) (mul (inv -2) (add (take '(%log) (inv logarg)) (take '(%log) logarg)))))))) (t (eqtest (list '(%expintegral_li) arg) expr))))) Numerical evaluation of the Li(z ) = Ei(log(z ) ) (defun expintegral-li (z) (expintegral-ei (log z))) (defun bfloat-expintegral-li (z) (bfloat-expintegral-ei ($log z))) Part 5 : The implementation of the Exponential Integral Si (defun $expintegral_si (z) (simplify (list '(%expintegral_si) z))) (defprop $expintegral_si %expintegral_si alias) (defprop $expintegral_si %expintegral_si verb) (defprop %expintegral_si $expintegral_si reversealias) (defprop %expintegral_si $expintegral_si noun) Exponential Integral Si is a simplifying function (defprop %expintegral_si simp-expintegral-si operators) Exponential Integral Si distributes over bags (defprop %expintegral_si (mlist $matrix mequal) distribute_over) Exponential Integral Si has mirror symmetry (defprop %expintegral_si t commutes-with-conjugate) Exponential Integral Si is a odd function (defprop %expintegral_si odd-function-reflect reflection-rule) (defprop %expintegral_si ((x) ((mtimes) ((%sin) x) ((mexpt) x -1))) grad) Integral of Exponential Si (defprop %expintegral_si ((x) ((mplus) ((%cos) x) ((mtimes) x ((%expintegral_si) x)))) integral) (defun simp-expintegral-si (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) arg) ((eq arg '$inf) (div '$%pi 2)) ((eq arg '$minf) (mul -1 (div '$%pi 2))) ((alike1 arg '((mtimes) -1 $inf)) (mul -1 (div '$%pi 2))) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-si carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-si carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ((taylorize (mop expr) (second expr))) ((apply-reflection-simp (mop expr) arg $trigsign)) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_trig))) (case $expintrep (%gamma_incomplete (mul (div '$%i 2) (add (take '(%gamma_incomplete) 0 (mul -1 '$%i arg)) (mul -1 (take '(%gamma_incomplete) 0 (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg)))))) (%expintegral_e1 (mul (div '$%i 2) (add (take '(%expintegral_e1) (mul -1 '$%i arg)) (mul -1 (take '(%expintegral_e1) (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg)))))) (%expintegral_ei (mul (div '$%i 4) (add (mul 2 (sub (take '(%expintegral_ei) (mul -1 '$%i arg)) (take '(%expintegral_ei) (mul '$%i arg)))) (take '(%log) (div '$%i arg)) (mul -1 (take '(%log) (mul -1 (div '$%i arg)))) (mul -1 (take '(%log) (mul -1 '$%i arg))) (take '(%log) (mul '$%i arg))))) (%expintegral_li (mul (inv (mul 2 '$%i)) (add (take '(%expintegral_li) (power '$%e (mul '$%i arg))) (mul -1 (take '(%expintegral_li) (power '$%e (mul -1 '$%e arg)))) (mul (div '$%pi -2) (take '(%signum) ($realpart arg)))))) ($expintegral_hyp (mul -1 '$%i (take '(%expintegral_shi) (mul '$%i arg)))))) (t (eqtest (list '(%expintegral_si) arg) expr))))) Numerical evaluation of the Exponential Integral Si For the Sin , Cos , Sinh and Cosh Exponential Integrals we have to call the (defun expintegral-si (z) (let ((z (coerce z '(complex flonum)))) (* (complex 0 0.5) (+ (expintegral-e 1 (* (complex 0 -1) z)) (- (expintegral-e 1 (* (complex 0 1) z))) (log (* (complex 0 -1) z)) (- (log (* (complex 0 1) z))))))) (defun bfloat-expintegral-si (z) (let ((z*%i (cmul '$%i z)) (mz*%i (cmul (mul -1 '$%i) z))) (cmul (mul 0.5 '$%i) (add (bfloat-expintegral-e 1 mz*%i) (mul -1 (bfloat-expintegral-e 1 z*%i)) ($log mz*%i) (mul -1 ($log z*%i)))))) Part 6 : The implementation of the Exponential Integral Shi (defun $expintegral_shi (z) (simplify (list '(%expintegral_shi) z))) (defprop $expintegral_shi %expintegral_shi alias) (defprop $expintegral_shi %expintegral_shi verb) (defprop %expintegral_shi $expintegral_shi reversealias) (defprop %expintegral_shi $expintegral_shi noun) Exponential Integral Shi is a simplifying function (defprop %expintegral_shi simp-expintegral-shi operators) Exponential Integral Shi distributes over bags (defprop %expintegral_shi (mlist $matrix mequal) distribute_over) Exponential Integral Shi has mirror symmetry (defprop %expintegral_si t commutes-with-conjugate) Exponential Integral Shi is a odd function (defprop %expintegral_si odd-function-reflect reflection-rule) (defprop %expintegral_shi ((x) ((mtimes) ((%sinh) x) ((mexpt) x -1))) grad) Integral of Exponential Shi (defprop %expintegral_shi ((x) ((mplus) ((mtimes) -1 ((%cosh) x)) ((mtimes) x ((%expintegral_shi) x)))) integral) (defun simp-expintegral-shi (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) arg) ((alike1 arg '((mtimes) '$%i $inf)) (div (mul '$%i '$%pi) 2)) ((alike1 arg '((mtimes) -1 '$%i $inf)) (div (mul -1 '$%i '$%pi) 2)) ((float-numerical-eval-p arg) (realpart (expintegral-shi arg))) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-shi carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-shi carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ((taylorize (mop expr) (second expr))) ((apply-reflection-simp (mop expr) arg $trigsign)) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_hyp))) (case $expintrep (%gamma_incomplete (mul (inv 2) (add (take '(%gamma_incomplete) 0 arg) (mul -1 (take '(%gamma_incomplete) 0 (mul -1 arg))) (mul -1 (take '(%log) (mul -1 arg))) (take '(%log) arg)))) (%expintegral_e1 (mul (inv 2) (add (take '(%expintegral_e1) arg) (mul -1 (take '(%expintegral_e1) (mul -1 arg))) (mul -1 (take '(%log) (mul -1 arg))) (take '(%log) arg)))) (%expintegral_ei (mul (inv 4) (add (mul 2 (sub (take '(%expintegral_ei) arg) (take '(%expintegral_ei) (mul -1 arg)))) (take '(%log) (inv arg)) (mul -1 (take '(%log) (mul -1 (inv arg)))) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_li (add (mul (inv 2) (sub (take '(%expintegral_li) (power '$%e arg)) (take '(%expintegral_li) (power '$%e (mul -1 arg))))) (mul (div (mul '$%i '$%pi) -2) (take '(%signum) ($imagpart arg))))) ($expintegral_trig (mul -1 '$%i (take '(%expintegral_si) (mul '$%i arg)))))) (t (eqtest (list '(%expintegral_shi) arg) expr))))) Numerical evaluation of the Exponential Integral Shi Shi(z ) = 1/2 * ( E1(z ) - E1(-z ) - log(-z ) + log(z ) ) (defun expintegral-shi (z) (* 0.5 (+ (expintegral-e 1 z) (- (expintegral-e 1 (- z))) (- (log (- z))) (log z)))) (defun bfloat-expintegral-shi (z) (let ((mz (mul -1 z))) (mul 0.5 (add (bfloat-expintegral-e 1 z) (mul -1 (bfloat-expintegral-e 1 mz)) (mul -1 ($log mz)) ($log z))))) Part 7 : The implementation of the Exponential Integral Ci (defun $expintegral_ci (z) (simplify (list '(%expintegral_ci) z))) (defprop $expintegral_ci %expintegral_ci alias) (defprop $expintegral_ci %expintegral_ci verb) (defprop %expintegral_ci $expintegral_ci reversealias) (defprop %expintegral_ci $expintegral_ci noun) Exponential Integral Ci is a simplifying function (defprop %expintegral_ci simp-expintegral-ci operators) Exponential Integral Ci distributes over bags (defprop %expintegral_ci (mlist $matrix mequal) distribute_over) Exponential Integral Ci has mirror symmetry , (defprop %expintegral_ci conjugate-expintegral-ci conjugate-function) (defun conjugate-expintegral-ci (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_ci) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_ci) z)))))) (defprop %expintegral_ci ((x) ((mtimes) ((%cos) x) ((mexpt) x -1))) grad) Integral of Exponential Ci (defprop %expintegral_ci ((x) ((mplus) ((mtimes) x ((%expintegral_ci) x)) ((mtimes) -1 ((%sin) x)))) integral) (defprop %expintegral_ci simplim%expintegral_ci simplim%function) (defun simplim%expintegral_ci (expr var val) (let ((z (limit (cadr expr) var val 'think))) (cond ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t (take '(%expintegral_ci) z))))) (defun simp-expintegral-ci (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) (simp-domain-error (intl:gettext "expintegral_ci: expintegral_ci(~:M) is undefined.") arg)) ((eq arg '$inf) 0) ((eq arg '$minf) (mul '$%i '$%pi)) ((alike1 arg '((mtimes) -1 $inf)) (mul '$%pi '$%pi)) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-ci carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-ci carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_trig))) (case $expintrep (%gamma_incomplete (sub (take '(%log) arg) (mul (inv 2) (add (take '(%gamma_incomplete) 0 (mul -1 '$%i arg)) (take '(%gamma_incomplete) 0 (mul '$%i arg)) (take '(%log) (mul -1 '$%i arg)) (take '(%log) (mul '$%i arg)))))) (%expintegral_e1 (add (mul (inv -2) (add (take '(%expintegral_e1) (mul -1 '$%i arg)) (take '(%expintegral_e1) (mul '$%i arg))) (take '(%log) (mul -1 '$%i arg)) (take '(%log) (mul '$%i arg))) (take '(%log) arg))) (%expintegral_ei (add (mul (inv 4) (add (mul 2 (add (take '(%expintegral_ei) (mul -1 '$%i arg)) (take '(%expintegral_ei) (mul '$%i arg)))) (take '(%log) (div '$%i arg)) (take '(%log) (mul -1 '$%i (inv arg))) (mul -1 (take '(%log) (mul -1 '$%i arg))) (mul -1 (take '(%log) (mul '$%i arg))))) (take '(%log) arg))) (%expintegral_li (add (mul (inv 2) (add (take '(%expintegral_li) (power '$%e (mul -1 '$%i arg))) (take '(%expintegral_li) (power '$%e (mul '$%i arg))))) (mul (div (mul '$%i '$%pi) 2) (take '(%signum) ($imagpart arg))) (sub 1 (take '(%signum) ($realpart arg))))) ($expintegral_hyp (add (take '(%expintegral_chi) (mul '$%i arg)) (mul -1 (take '(%log) (mul '$%i arg))) (take '(%log) arg))))) (t (eqtest (list '(%expintegral_ci) arg) expr))))) Numerical evaluation of the Exponential Integral Ci (defun expintegral-ci (z) (let ((z (coerce z '(complex flonum)))) (+ (* -0.5 (+ (expintegral-e 1 (* (complex 0 -1) z)) (expintegral-e 1 (* (complex 0 1) z)) (log (* (complex 0 -1) z)) (log (* (complex 0 1) z)))) (log z)))) (defun bfloat-expintegral-ci (z) (let ((z*%i (cmul '$%i z)) (mz*%i (cmul (mul -1 '$%i) z))) (add (cmul -0.5 (add (bfloat-expintegral-e 1 mz*%i) (bfloat-expintegral-e 1 z*%i) ($log mz*%i) ($log z*%i))) ($log z)))) (defun $expintegral_chi (z) (simplify (list '(%expintegral_chi) z))) (defprop $expintegral_chi %expintegral_chi alias) (defprop $expintegral_chi %expintegral_chi verb) (defprop %expintegral_chi $expintegral_chi reversealias) (defprop %expintegral_chi $expintegral_chi noun) Exponential Integral Chi is a simplifying function (defprop %expintegral_chi simp-expintegral-chi operators) Exponential Integral Chi distributes over bags (defprop %expintegral_chi (mlist $matrix mequal) distribute_over) Exponential Integral Chi has mirror symmetry , (defprop %expintegral_chi conjugate-expintegral-chi conjugate-function) (defun conjugate-expintegral-chi (args) (let ((z (first args))) (cond ((off-negative-real-axisp z) Definitly not on the negative real axis for z. Mirror symmetry . (take '(%expintegral_chi) (take '($conjugate) z))) (t On the negative real axis or no information . Unsimplified . (list '($conjugate simp) (take '(%expintegral_chi) z)))))) (defprop %expintegral_chi ((x) ((mtimes) ((%cosh) x) ((mexpt) x -1))) grad) Integral of Exponential Chi (defprop %expintegral_chi ((x) ((mplus) ((mtimes) x ((%expintegral_chi) x)) ((mtimes) -1 ((%sinh) x)))) integral) (defprop %expintegral_chi simplim%expintegral_chi simplim%function) (defun simplim%expintegral_chi (expr var val) (let ((z (limit (cadr expr) var val 'think))) (cond ((or (zerop1 z) (eq z '$zeroa) (eq z '$zerob)) '$minf) (t (take '(%expintegral_chi) z))))) (defun simp-expintegral-chi (expr ignored z) (declare (ignore ignored)) (oneargcheck expr) (let ((arg (simpcheck (cadr expr) z))) (cond ((zerop1 arg) First check for zero argument . Throw Maxima error . (simp-domain-error (intl:gettext "expintegral_chi: expintegral_chi(~:M) is undefined.") arg)) ((alike1 arg '((mtimes) $%i $inf)) (div (mul '$%pi '$%i) 2)) ((alike1 arg '((mtimes) -1 $%i $inf)) (div (mul -1 '$%pi '$%i) 2)) ((complex-float-numerical-eval-p arg) (let ((carg (complex ($float ($realpart arg)) ($float ($imagpart arg))))) (complexify (expintegral-chi carg)))) ((complex-bigfloat-numerical-eval-p arg) (let* (($ratprint nil) (carg (add ($bfloat ($realpart arg)) (mul '$%i ($bfloat ($imagpart arg))))) (result (bfloat-expintegral-chi carg))) (add (mul '$%i ($imagpart result)) ($realpart result)))) ((taylorize (mop expr) (second expr))) ((and $expintrep (member $expintrep *expintflag*) (not (eq $expintrep '$expintegral_hyp))) (case $expintrep (%gamma_incomplete (mul (inv -2) (add (take '(%gamma_incomplete) 0 (mul -1 arg)) (take '(%gamma_incomplete) 0 arg) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_e1 (mul (inv -2) (add (take '(%expintegral_e1) (mul -1 arg)) (take '(%expintegral_e1) arg) (take '(%log) (mul -1 arg)) (mul -1 (take '(%log) arg))))) (%expintegral_ei (mul (inv 4) (add (mul 2 (add (take '(%expintegral_ei) (mul -1 arg)) (take '(%expintegral_ei) arg))) (take '(%log) (inv arg)) (take '(%log) (mul -1 (inv arg))) (mul -1 (take '(%log) (mul -1 arg))) (mul 3 (take '(%log) arg))))) (%expintegral_li (add (mul (inv 2) (add (take '(%expintegral_li) (power '$%e (mul -1 arg))) (take '(%expintegral_li) (power '$%e arg)))) (mul (div (mul '$%i '$%pi) 2) (take '(%signum) ($imagpart arg))) (mul (inv 2) (add (take '(%log) (inv arg)) (take '(%log) arg))))) ($expintegral_trig (add (take '(%expintegral_ci) (mul '$%i arg)) (take '(%log) arg) (mul -1 (take '(%log) (mul '$%i arg))))))) (t (eqtest (list '(%expintegral_chi) arg) expr))))) Numerical evaluation of the Exponential Integral Ci Chi(z ) = -1/2 * ( E1(-z ) + E1(z ) + log(-z ) - log(z ) ) (defun expintegral-chi (z) (* -0.5 (+ (expintegral-e 1 z) (expintegral-e 1 (- z)) (log (- z)) (- (log z))))) (defun bfloat-expintegral-chi (z) (let ((mz (mul -1 z))) (mul -0.5 (add (bfloat-expintegral-e 1 z) (bfloat-expintegral-e 1 mz) ($log mz) (mul -1 ($log z)))))) Moved from bessel.lisp 2008 - 12 - 11 . Consider deleting it . Exponential integral E1(x ) . The Cauchy principal value is used for (defun $expint (x) (cond ((numberp x) (values (slatec:de1 (float x)))) (t (list '($expint simp) x))))
e4b697fe4cc7a86cae7262a2da37cb9a29c048eca1a26c8807f5edeeca850e2e
sentenai/reinforce
PendulumV0.hs
-------------------------------------------------------------------------------- -- | Module : Environment . Gym . ClassicControl . PendulumV0 -- Copyright : (c) Sentenai 2017 -- License : BSD3 Maintainer : -- Stability : experimental -- -- The inverted pendulum swingup problem is a classic problem in the control -- literature. In this version of the problem, the pendulum starts in a random -- position, and the goal is to swing it up so it stays upright. -- -- -v0 -------------------------------------------------------------------------------- # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE InstanceSigs # module Environments.Gym.ClassicControl.PendulumV0 ( Action(..) , I.Runner , State(..) , Environment , EnvironmentT , Environments.Gym.ClassicControl.PendulumV0.runEnvironment , Environments.Gym.ClassicControl.PendulumV0.runEnvironmentT , Environments.Gym.ClassicControl.PendulumV0.runDefaultEnvironment , Environments.Gym.ClassicControl.PendulumV0.runDefaultEnvironmentT ) where import Reinforce . Prelude hiding ( State ) import Control.Monad.IO.Class import Control.Exception.Safe import Data.Hashable import GHC.Generics import Control.MonadEnv (MonadEnv(..), Reward) import Environments.Gym.Internal (GymEnvironmentT) import qualified Environments.Gym.Internal as I import Data.Aeson.Types import OpenAI.Gym (GymEnv(PendulumV0)) import Servant.Client as X (BaseUrl) import Network.HTTP.Client as X (Manager) | State of a PendulumV0 environment -- FIXME: give these semantics or move to a tuple? data State = State { cosTheta :: Float , sinTheta :: Float , thetaDot :: Float } deriving (Show, Eq, Generic, Ord, Hashable) instance FromJSON State where parseJSON :: Value -> Parser State parseJSON arr@(Array _)= do (a, b, c) <- parseJSON arr :: Parser (Float, Float, Float) return $ State a b c parseJSON invalid = typeMismatch "Environment State" invalid -- | Force to exert on the pendulum newtype Action = Action { getAction :: Float } deriving (Ord, Show, Eq, Generic, Hashable) instance ToJSON Action where toJSON :: Action -> Value toJSON = toJSON . getAction -- ========================================================================= -- | to ' Environments . Gym . Internal . GymEnvironmentT ' with PendulumV0 type dependencies type EnvironmentT t = GymEnvironmentT State Action t | to ' EnvironmentT ' in IO type Environment = EnvironmentT IO | to ' Environments . Gym . Internal.runEnvironmentT ' runEnvironmentT :: MonadIO t => Manager -> BaseUrl -> I.RunnerT State Action t x runEnvironmentT = I.runEnvironmentT PendulumV0 | to ' Environments . Gym . Internal.runEnvironment ' in IO runEnvironment :: Manager -> BaseUrl -> I.RunnerT State Action IO x runEnvironment = I.runEnvironmentT PendulumV0 | to ' Environments . Gym . ' runDefaultEnvironmentT :: MonadIO t => I.RunnerT State Action t x runDefaultEnvironmentT = I.runDefaultEnvironmentT PendulumV0 | to ' Environments . Gym . Internal.runDefaultEnvironment ' in IO runDefaultEnvironment :: I.RunnerT State Action IO x runDefaultEnvironment = I.runDefaultEnvironmentT PendulumV0 instance (MonadIO t, MonadThrow t) => MonadEnv (EnvironmentT t) State Action Reward where reset = I._reset step = I._step
null
https://raw.githubusercontent.com/sentenai/reinforce/03fdeea14c606f4fe2390863778c99ebe1f0a7ee/reinforce-environments-gym/src/Environments/Gym/ClassicControl/PendulumV0.hs
haskell
------------------------------------------------------------------------------ | Copyright : (c) Sentenai 2017 License : BSD3 Stability : experimental The inverted pendulum swingup problem is a classic problem in the control literature. In this version of the problem, the pendulum starts in a random position, and the goal is to swing it up so it stays upright. -v0 ------------------------------------------------------------------------------ # LANGUAGE DeriveAnyClass # FIXME: give these semantics or move to a tuple? | Force to exert on the pendulum ========================================================================= --
Module : Environment . Gym . ClassicControl . PendulumV0 Maintainer : # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # # LANGUAGE InstanceSigs # module Environments.Gym.ClassicControl.PendulumV0 ( Action(..) , I.Runner , State(..) , Environment , EnvironmentT , Environments.Gym.ClassicControl.PendulumV0.runEnvironment , Environments.Gym.ClassicControl.PendulumV0.runEnvironmentT , Environments.Gym.ClassicControl.PendulumV0.runDefaultEnvironment , Environments.Gym.ClassicControl.PendulumV0.runDefaultEnvironmentT ) where import Reinforce . Prelude hiding ( State ) import Control.Monad.IO.Class import Control.Exception.Safe import Data.Hashable import GHC.Generics import Control.MonadEnv (MonadEnv(..), Reward) import Environments.Gym.Internal (GymEnvironmentT) import qualified Environments.Gym.Internal as I import Data.Aeson.Types import OpenAI.Gym (GymEnv(PendulumV0)) import Servant.Client as X (BaseUrl) import Network.HTTP.Client as X (Manager) | State of a PendulumV0 environment data State = State { cosTheta :: Float , sinTheta :: Float , thetaDot :: Float } deriving (Show, Eq, Generic, Ord, Hashable) instance FromJSON State where parseJSON :: Value -> Parser State parseJSON arr@(Array _)= do (a, b, c) <- parseJSON arr :: Parser (Float, Float, Float) return $ State a b c parseJSON invalid = typeMismatch "Environment State" invalid newtype Action = Action { getAction :: Float } deriving (Ord, Show, Eq, Generic, Hashable) instance ToJSON Action where toJSON :: Action -> Value toJSON = toJSON . getAction | to ' Environments . Gym . Internal . GymEnvironmentT ' with PendulumV0 type dependencies type EnvironmentT t = GymEnvironmentT State Action t | to ' EnvironmentT ' in IO type Environment = EnvironmentT IO | to ' Environments . Gym . Internal.runEnvironmentT ' runEnvironmentT :: MonadIO t => Manager -> BaseUrl -> I.RunnerT State Action t x runEnvironmentT = I.runEnvironmentT PendulumV0 | to ' Environments . Gym . Internal.runEnvironment ' in IO runEnvironment :: Manager -> BaseUrl -> I.RunnerT State Action IO x runEnvironment = I.runEnvironmentT PendulumV0 | to ' Environments . Gym . ' runDefaultEnvironmentT :: MonadIO t => I.RunnerT State Action t x runDefaultEnvironmentT = I.runDefaultEnvironmentT PendulumV0 | to ' Environments . Gym . Internal.runDefaultEnvironment ' in IO runDefaultEnvironment :: I.RunnerT State Action IO x runDefaultEnvironment = I.runDefaultEnvironmentT PendulumV0 instance (MonadIO t, MonadThrow t) => MonadEnv (EnvironmentT t) State Action Reward where reset = I._reset step = I._step
01d1d90cfb17703021b345f6a9b2e84170856de2b9414fb34dea1c6b9efd43e8
cognitect-labs/day-of-datomic-cloud
query-executing.clj
Copyright ( c ) Cognitect , Inc. 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. ;; The examples below parallel -executing.html ;; sample data at -importer (require '[datomic.client.api :as d]) (def client-cfg (read-string (slurp "config.edn"))) (def client (d/client client-cfg)) (def conn (d/connect client {:db-name "mbrainz-1968-1973"})) (def db (d/db conn)) (def query '[:find ?e :in $ ?name :where [?e :artist/name ?name]]) (d/q query db "The Beatles") (d/q query db "The Who") ;; not an identical query, ?artist-name instead of ?name (def query '[:find ?e :in $ ?artist-name :where [?e :artist/name ?artist-name]])
null
https://raw.githubusercontent.com/cognitect-labs/day-of-datomic-cloud/b1684c8d131942f0451185288ed65bc51ee2b81d/doc-examples/query-executing.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. The examples below parallel -executing.html sample data at -importer not an identical query, ?artist-name instead of ?name
Copyright ( c ) Cognitect , Inc. All rights reserved . (require '[datomic.client.api :as d]) (def client-cfg (read-string (slurp "config.edn"))) (def client (d/client client-cfg)) (def conn (d/connect client {:db-name "mbrainz-1968-1973"})) (def db (d/db conn)) (def query '[:find ?e :in $ ?name :where [?e :artist/name ?name]]) (d/q query db "The Beatles") (d/q query db "The Who") (def query '[:find ?e :in $ ?artist-name :where [?e :artist/name ?artist-name]])
a812a5d42f733728afe4d4d9a032f14436fdbd9efdf8a7cd5d4bda78e1ee4da2
gentoo-haskell/haskell-updater
Output.hs
| Module : Main Description : The haskell - updater executable License : or later Fancy output facility . Module : Main Description : The haskell-updater executable License : GPL-2 or later Fancy output facility. -} module Output ( pkgListPrintLn , printList , say , vsay , Verbosity(..) ) where import System.IO (hPutStrLn, stderr) import Distribution.Gentoo.Packages -- output mode (chattiness) data Verbosity = Quiet | Normal | Verbose deriving (Eq, Ord, Show, Read) say :: Verbosity -> String -> IO () say verb_l msg = case verb_l of Quiet -> return () Normal -> hPutStrLn stderr msg Verbose -> hPutStrLn stderr msg vsay :: Verbosity -> String -> IO () vsay verb_l msg = case verb_l of Quiet -> return () Normal -> return () Verbose -> hPutStrLn stderr msg Print a bullet list of values with one value per line . printList :: Verbosity -> (a -> String) -> [a] -> IO () printList v f = mapM_ (say v . (++) " * " . f) -- Print a list of packages, with a description of what they are. pkgListPrintLn :: Verbosity -> String -> [Package] -> IO () pkgListPrintLn v desc pkgs = do if null pkgs then say v $ unwords ["No", desc, "packages found!"] else do say v $ unwords ["Found the following" , desc, "packages:"] printList v printPkg pkgs say v ""
null
https://raw.githubusercontent.com/gentoo-haskell/haskell-updater/3157ba41ea1793f844218a87b32bcc9f041c028b/Output.hs
haskell
output mode (chattiness) Print a list of packages, with a description of what they are.
| Module : Main Description : The haskell - updater executable License : or later Fancy output facility . Module : Main Description : The haskell-updater executable License : GPL-2 or later Fancy output facility. -} module Output ( pkgListPrintLn , printList , say , vsay , Verbosity(..) ) where import System.IO (hPutStrLn, stderr) import Distribution.Gentoo.Packages data Verbosity = Quiet | Normal | Verbose deriving (Eq, Ord, Show, Read) say :: Verbosity -> String -> IO () say verb_l msg = case verb_l of Quiet -> return () Normal -> hPutStrLn stderr msg Verbose -> hPutStrLn stderr msg vsay :: Verbosity -> String -> IO () vsay verb_l msg = case verb_l of Quiet -> return () Normal -> return () Verbose -> hPutStrLn stderr msg Print a bullet list of values with one value per line . printList :: Verbosity -> (a -> String) -> [a] -> IO () printList v f = mapM_ (say v . (++) " * " . f) pkgListPrintLn :: Verbosity -> String -> [Package] -> IO () pkgListPrintLn v desc pkgs = do if null pkgs then say v $ unwords ["No", desc, "packages found!"] else do say v $ unwords ["Found the following" , desc, "packages:"] printList v printPkg pkgs say v ""
d7a1f77c11ef8305ca41dc7dcc34297315b9b56af9517e0e2b834b94d778af3c
thegeez/w3a
test.clj
(ns net.thegeez.w3a.test (:require [clojure.edn :as edn] [com.stuartsierra.component :as component] [io.pedestal.http :as http] [io.pedestal.interceptor :as interceptor] [io.pedestal.log :as log] [io.pedestal.test :as test] [net.cgrand.enlive-html :as html] [kerodon.core :as kerodon] [peridot.request])) ;; make ring mock not munge edn (let [old-fn (get (methods ring.mock.request/body) java.util.Map)] (remove-method ring.mock.request/body java.util.Map) (defmethod ring.mock.request/body java.util.Map [request body] (if (-> body meta :edn) (ring.mock.request/body request (pr-str body)) (old-fn request body)))) (def csrf-token-in-response-header (interceptor/interceptor {:name ::csrf-token-in-response-header :leave (fn [context] (assoc-in context [:response :headers "X-TEST-HELPER-CSRF"] (or (get-in context [:request :io.pedestal.http.csrf/anti-forgery-token]) (get-in context [:request :session "__anti-forgery-token"]))))})) ;; allow to find the csrf-token to use in testing (defn surface-csrf-token [system] (update-in system [:server :service ::http/interceptors] conj csrf-token-in-response-header)) (defn system->ring-handler [system] (let [system (-> system surface-csrf-token (cond-> (.startsWith ^String (get-in system [:db :db-connect-string] "") "jdbc:derby:memory:") TODO make this an explicit component (update-in [:db :db-connect-string] #(str "jdbc:derby:memory:" (gensym "pertestdb") (subs % (count "jdbc:derby:memory:"))))) (dissoc :jetty)) service-fn (-> system component/start (get-in [:server :server ::http/service-fn]))] (fn [req] (let [method (:request-method req) uri (:uri req) ;; pedestal blows up when it can't figure out scheme / ;; host etc, which is missing as jetty is not running uri (if (not (.startsWith ^String uri "http")) (str "" uri) uri) uri (if-let [qs (:query-string req)] (str uri "?" qs) uri) options (cond-> [] (:body req) (into [:body (slurp (:body req))]) (:headers req) (into [:headers (zipmap (map #(get {"content-type" "Content-Type" "accept" "Accept"} % %) (keys (:headers req))) (vals (:headers req)))])) response (apply test/response-for service-fn method uri options)] (cond-> response (.startsWith ^String (get-in response [:headers "Content-Type"] "") "application/edn") (assoc :edn (try (edn/read-string (get response :body)) (catch Exception e (log/info :unreadable (get response :body)) (throw e))))))))) broken in for text only links when links with nested html ;; on a page (defn follow [state link] (kerodon/follow state (if (string? link) (html/pred #(= (first (:content %)) link)) link))) TODO make same shape as testers (defn at? [res url] (clojure.test/is (= url (str (get-in res [:request :uri]) ;; only check the query string as well ;; when specified by user (when (.contains url "?") (when-let [query-string (get-in res [:request :query-string])] (str "?" query-string)))))) res)
null
https://raw.githubusercontent.com/thegeez/w3a/186e507389628f20381d155d91058a1804d421e3/src/net/thegeez/w3a/test.clj
clojure
make ring mock not munge edn allow to find the csrf-token to use in testing pedestal blows up when it can't figure out scheme / host etc, which is missing as jetty is not running on a page only check the query string as well when specified by user
(ns net.thegeez.w3a.test (:require [clojure.edn :as edn] [com.stuartsierra.component :as component] [io.pedestal.http :as http] [io.pedestal.interceptor :as interceptor] [io.pedestal.log :as log] [io.pedestal.test :as test] [net.cgrand.enlive-html :as html] [kerodon.core :as kerodon] [peridot.request])) (let [old-fn (get (methods ring.mock.request/body) java.util.Map)] (remove-method ring.mock.request/body java.util.Map) (defmethod ring.mock.request/body java.util.Map [request body] (if (-> body meta :edn) (ring.mock.request/body request (pr-str body)) (old-fn request body)))) (def csrf-token-in-response-header (interceptor/interceptor {:name ::csrf-token-in-response-header :leave (fn [context] (assoc-in context [:response :headers "X-TEST-HELPER-CSRF"] (or (get-in context [:request :io.pedestal.http.csrf/anti-forgery-token]) (get-in context [:request :session "__anti-forgery-token"]))))})) (defn surface-csrf-token [system] (update-in system [:server :service ::http/interceptors] conj csrf-token-in-response-header)) (defn system->ring-handler [system] (let [system (-> system surface-csrf-token (cond-> (.startsWith ^String (get-in system [:db :db-connect-string] "") "jdbc:derby:memory:") TODO make this an explicit component (update-in [:db :db-connect-string] #(str "jdbc:derby:memory:" (gensym "pertestdb") (subs % (count "jdbc:derby:memory:"))))) (dissoc :jetty)) service-fn (-> system component/start (get-in [:server :server ::http/service-fn]))] (fn [req] (let [method (:request-method req) uri (:uri req) uri (if (not (.startsWith ^String uri "http")) (str "" uri) uri) uri (if-let [qs (:query-string req)] (str uri "?" qs) uri) options (cond-> [] (:body req) (into [:body (slurp (:body req))]) (:headers req) (into [:headers (zipmap (map #(get {"content-type" "Content-Type" "accept" "Accept"} % %) (keys (:headers req))) (vals (:headers req)))])) response (apply test/response-for service-fn method uri options)] (cond-> response (.startsWith ^String (get-in response [:headers "Content-Type"] "") "application/edn") (assoc :edn (try (edn/read-string (get response :body)) (catch Exception e (log/info :unreadable (get response :body)) (throw e))))))))) broken in for text only links when links with nested html (defn follow [state link] (kerodon/follow state (if (string? link) (html/pred #(= (first (:content %)) link)) link))) TODO make same shape as testers (defn at? [res url] (clojure.test/is (= url (str (get-in res [:request :uri]) (when (.contains url "?") (when-let [query-string (get-in res [:request :query-string])] (str "?" query-string)))))) res)
82348d8cd459a09e84b26f9cc1825b3818aa3fb2097d067f82d7d6a2ae1ec061
VisionsGlobalEmpowerment/webchange
scene.cljs
(ns webchange.interpreter.renderer.state.scene (:require [re-frame.core :as re-frame] [webchange.interpreter.renderer.state.db :refer [path-to-db]] [webchange.interpreter.renderer.scene.components.wrapper-interface :as w] [webchange.logger.index :as logger])) (re-frame/reg-event-fx ::init (fn [{:keys [db]} [_]] (let [objects (get-in db (path-to-db [:objects]) (atom {})) groups (get-in db (path-to-db [:groups]) (atom {}))] (reset! objects {}) (reset! groups {}) {:db (-> db (assoc-in (path-to-db [:objects]) objects) (assoc-in (path-to-db [:groups]) groups))}))) (re-frame/reg-sub ::rendering? (fn [db] (get-in db (path-to-db [:rendering?]) false))) (re-frame/reg-event-fx ::set-rendering-state (fn [{:keys [db]} [_ value]] {:db (assoc-in db (path-to-db [:rendering?]) value)})) (re-frame/reg-fx :add-scene-object (fn [{:keys [objects groups object-wrapper]}] (let [object-name (:name object-wrapper) group-name (:group-name object-wrapper)] (when (contains? @objects object-name) (-> (str "Object with name " object-name " already exists.") js/Error. throw)) (swap! objects assoc object-name object-wrapper) (when-not (nil? group-name) (swap! groups update group-name conj object-name))))) (re-frame/reg-fx :remove-scene-object (fn [{:keys [objects object-name]}] (swap! objects dissoc object-name))) (re-frame/reg-event-fx ::register-object (fn [{:keys [db]} [_ object-wrapper]] {:add-scene-object {:objects (get-in db (path-to-db [:objects])) :groups (get-in db (path-to-db [:groups])) :object-wrapper object-wrapper}})) (re-frame/reg-event-fx ::unregister-object (fn [{:keys [db]} [_ object-name]] {:remove-scene-object {:objects (get-in db (path-to-db [:objects])) :object-name object-name}})) (defn get-scene-object [db name] (if-not (nil? name) (let [objects @(get-in db (path-to-db [:objects]))] (get objects name)) nil)) (defn get-scene-group [db group-name] (let [groups @(get-in db (path-to-db [:groups])) group (get groups group-name)] (when-not (nil? group) (map #(get-scene-object db %) group)))) ;; Change object events (defn- filter-extra-props [props extra-props-names] (->> props (filter (fn [[prop-name]] (not (some #{prop-name} extra-props-names)))) (into {}))) ; Actions matching the template: ; 'handler-name = "set-" + param-name' ; (e.g. ':set-text' wrapper method for ':text' param) ; should be handled by 'generic-handler' ; Here should be defined only actions with different params ; (e.g. ':set-filter' wrapper method for ':brightness' param) (def available-actions [{:action :set-align :params [:align] :to-generic? true} {:action :set-image-size :params [:image-size] :to-generic? true} {:action :set-position :params [:x :y]} {:action :set-scale :params [:scale :scale-x :scale-y]} {:action :set-dashed :params [:dashed] :to-generic? true} {:action :set-show-lines :params [:show-lines] :to-generic? true} {:action :set-visibility :params [:visible]} {:action :set-src :params [:src] :to-generic? true} {:action :reset-video :params [:src]} {:action :set-text :params [:text] :to-generic? true} {:action :clear-area :params []} {:action :set-filter :params [:filter :brightness :eager]} {:action :set-opacity :params [:opacity] :to-generic? true} {:action :set-stroke :params [:stroke] :to-generic? true} {:action :set-data :params [:data] :to-generic? true} {:action :set-path :params [:path] :to-generic? true} {:action :set-fill :params [:fill] :to-generic? true} {:action :set-border-color :params [:border-color] :to-generic? true} {:action :set-highlight :params [:highlight] :to-generic? true} {:action :set-permanent-pulsation :params [:permanent-pulsation] :to-generic? true} {:action :set-alpha-pulsation :params [:alpha-pulsation] :to-generic? true} {:action :set-draggable :params [:draggable] :to-generic? true} {:action :set-children :params [:children]} {:action :set-font-size :params [:font-size] :to-generic? true} {:action :set-font-family :params [:font-family] :to-generic? true} {:action :set-skeleton :params [:name] :accompany-params [:skin :skin-names]} {:action :set-animation-skin :params [:skin]} {:action :set-combined-skin :params [:skin-names]} {:action :set-enable :params [:enable?]} {:action :set-speed :params [:speed]} {:action :set-chunks :params [:chunks]}]) (defn- get-action-params [{:keys [params accompany-params] :or {params [] accompany-params []}} overall-params] ":params - used to get action params and determine if action is needed for current params set :accompany-params - also needed for action but NOT used to determine if action is needed. For example apply params 'name', 'skin' and 'skin-names' to 'set-skeleton' action only if 'name' is defined. If 'skin' is defined but 'name' is undefined, use 'set-animation-skin' action instead." (let [action-params (select-keys overall-params params) action-used? (-> action-params empty? not)] (if action-used? {:action-used? action-used? :action-params (merge action-params (select-keys overall-params accompany-params)) :rest-params (apply dissoc overall-params (concat params accompany-params))} {:action-used? action-used? :action-params {} :rest-params overall-params}))) (declare change-scene-object) (defn set-scene-object-state [db object-name state] (let [filtered-state (filter-extra-props state [:revert :start :target :volume]) [execute-actions not-handled-params] (loop [actions-to-execute [] [{:keys [action to-generic?] :as available-action} & rest-available-actions] available-actions current-state filtered-state] (when to-generic? ;; Remove check when no :to-generic? field in available-actions (logger/warn (str "Change set param handler (" action ") to generic."))) (if (nil? available-action) [actions-to-execute current-state] (let [{:keys [action-used? action-params rest-params]} (get-action-params available-action current-state)] (recur (if action-used? (conj actions-to-execute [action action-params]) actions-to-execute) rest-available-actions rest-params)))) generic-handlers (map (fn [[param-name param-value]] (let [executor-name (->> param-name clojure.core/name (str "set-") keyword)] [executor-name param-value])) not-handled-params) result-actions (cond-> execute-actions (-> generic-handlers empty? not) (conj [:generic-handler generic-handlers]))] (change-scene-object {:db db} [nil object-name result-actions]))) (defn- event-handler [handler {:keys [db]} [_ & params]] (apply handler (concat [db] params))) (re-frame/reg-event-fx ::set-scene-object-state (partial event-handler set-scene-object-state)) (defn get-object-name [db object-name] (or (get-scene-object db object-name) (get-scene-group db object-name))) (defn- apply-to-wrapper [method target & params] (let [targets (if (sequential? target) target [target])] (doseq [wrapper targets] (apply method (concat [wrapper] params))))) (re-frame/reg-fx :add-filter (fn [[object-wrapper filter-data]] (apply-to-wrapper w/add-filter object-wrapper filter-data))) (re-frame/reg-fx :set-filter (fn [[object-wrapper {:keys [filter] :as params}]] (apply-to-wrapper w/set-filter object-wrapper filter params))) (re-frame/reg-fx :set-align (fn [[object-wrapper {:keys [align]}]] (apply-to-wrapper w/set-align object-wrapper align))) (re-frame/reg-fx :set-image-size (fn [[object-wrapper {:keys [image-size]}]] (apply-to-wrapper w/set-image-size object-wrapper image-size))) (re-frame/reg-fx :set-position (fn [[object-wrapper position]] (apply-to-wrapper w/set-position object-wrapper position))) (re-frame/reg-fx :set-scale (fn [[object-wrapper scale]] (apply-to-wrapper w/set-scale object-wrapper (or (:scale scale) scale)))) (re-frame/reg-fx :set-dashed (fn [[object-wrapper {:keys [dashed]}]] (apply-to-wrapper w/set-dashed object-wrapper dashed))) (re-frame/reg-fx :set-show-lines (fn [[object-wrapper {:keys [show-lines]}]] (apply-to-wrapper w/set-show-lines object-wrapper show-lines))) (defn set-visibility [[object-wrapper {:keys [visible]}]] (apply-to-wrapper w/set-visibility object-wrapper visible)) (re-frame/reg-fx :set-visibility set-visibility) (re-frame/reg-fx :set-value (fn [[object-wrapper value]] (apply-to-wrapper w/set-value object-wrapper value))) (re-frame/reg-fx :set-text (fn [[object-wrapper {:keys [text]}]] (apply-to-wrapper w/set-text object-wrapper text))) (re-frame/reg-fx :clear-area (fn [[object-wrapper {:keys [text]}]] (apply-to-wrapper w/clear-area object-wrapper text))) (re-frame/reg-fx :set-font-size (fn [[object-wrapper {:keys [font-size]}]] (apply-to-wrapper w/set-font-size object-wrapper font-size))) (re-frame/reg-fx :set-font-family (fn [[object-wrapper {:keys [font-family]}]] (apply-to-wrapper w/set-font-family object-wrapper font-family))) (re-frame/reg-fx :set-src (fn [[object-wrapper {:keys [src options]}]] (apply-to-wrapper w/set-src object-wrapper src options))) (re-frame/reg-fx :reset-video (fn [[object-wrapper {:keys [src options]}]] (apply-to-wrapper w/reset-video object-wrapper src options))) (re-frame/reg-fx :set-highlight (fn [[object-wrapper {:keys [highlight options]}]] (apply-to-wrapper w/set-highlight object-wrapper highlight options))) (re-frame/reg-fx :set-permanent-pulsation (fn [[object-wrapper {:keys [permanent-pulsation options]}]] (apply-to-wrapper w/set-permanent-pulsation object-wrapper permanent-pulsation options))) (re-frame/reg-fx :set-alpha-pulsation (fn [[object-wrapper {:keys [alpha-pulsation options]}]] (apply-to-wrapper w/set-alpha-pulsation object-wrapper alpha-pulsation options))) (re-frame/reg-fx :set-draggable (fn [[object-wrapper {:keys [draggable options]}]] (apply-to-wrapper w/set-draggable object-wrapper draggable options))) (re-frame/reg-fx :set-children (fn [[object-wrapper {:keys [children options]} db]] (let [object (:object object-wrapper) parent (.-parent (.-parent object)) children (vec (array-seq (.-children object)))] (doseq [child children] (.addChild parent child)) (doseq [child children] (.removeChild object child))) (doseq [child children] (apply-to-wrapper w/set-parent (get-object-name db (keyword child)) object-wrapper options)))) (re-frame/reg-fx :set-opacity (fn [[object-wrapper {:keys [opacity]}]] (apply-to-wrapper w/set-opacity object-wrapper opacity))) (re-frame/reg-fx :set-tool (fn [[object-wrapper {:keys [tool]}]] (apply-to-wrapper w/set-tool object-wrapper tool))) (re-frame/reg-fx :stop (fn [[object-wrapper]] (apply-to-wrapper w/stop object-wrapper))) (re-frame/reg-fx :set-data (fn [[object-wrapper params]] (apply-to-wrapper w/set-data object-wrapper params))) (re-frame/reg-fx :set-path (fn [[object-wrapper {:keys [path]}]] (apply-to-wrapper w/set-path object-wrapper path))) (re-frame/reg-fx :set-fill (fn [[object-wrapper {:keys [fill]}]] (apply-to-wrapper w/set-fill object-wrapper fill))) (re-frame/reg-fx :set-border-color (fn [[object-wrapper {:keys [border-color]}]] (apply-to-wrapper w/set-border-color object-wrapper border-color))) (re-frame/reg-fx :set-stroke (fn [[object-wrapper params]] (apply-to-wrapper w/set-stroke object-wrapper params))) (re-frame/reg-event-fx ::set-traffic-light (fn [{:keys [db]} [_ object-name color]] (let [wrapper (get-scene-object db object-name)] (apply-to-wrapper w/set-traffic-light wrapper color)))) (re-frame/reg-fx :set-animation-skin (fn [[object-wrapper {:keys [skin]}]] (apply-to-wrapper w/set-skin object-wrapper skin))) (re-frame/reg-fx :set-combined-skin (fn [[object-wrapper {:keys [skin-names]}]] (apply-to-wrapper w/set-combined-skin object-wrapper skin-names))) (re-frame/reg-fx :set-enable (fn [[object-wrapper {:keys [enable?]}]] (apply-to-wrapper w/set-enable object-wrapper enable?))) (re-frame/reg-fx :set-speed (fn [[object-wrapper {:keys [speed]}]] (apply-to-wrapper w/set-speed object-wrapper speed))) (re-frame/reg-fx :set-skeleton (fn [[object-wrapper params]] (apply-to-wrapper w/set-skeleton object-wrapper params))) (re-frame/reg-fx :set-chunks (fn [[{:keys [update-chunks]} params]] (update-chunks {:params params}))) (defn- generic-handler [[object-wrapper props _]] (doseq [[method params] props] (apply-to-wrapper w/execute-method object-wrapper method params))) (re-frame/reg-fx :generic-handler generic-handler) ; Methods which can be used as function, not re-frame effect (def fixed-methods {:generic-handler generic-handler :set-visibility set-visibility}) (defn- change-scene-object [{:keys [db]} [_ object-name actions]] (let [wrappers (get-object-name db object-name) handlers (reduce (fn [result [action params]] (if-let [fn-handler (get fixed-methods action)] (update result :fn conj [fn-handler [wrappers params db]]) (update result :fx assoc action [wrappers params db]))) {:fn [] :fx {}} actions)] (doseq [[fn-handler args] (:fn handlers)] (fn-handler args)) (:fx handlers))) (re-frame/reg-event-fx ::change-scene-object change-scene-object)
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/8411352df79289cf755083fe1dab9424d8eb7da6/src/cljs/webchange/interpreter/renderer/state/scene.cljs
clojure
Change object events Actions matching the template: 'handler-name = "set-" + param-name' (e.g. ':set-text' wrapper method for ':text' param) should be handled by 'generic-handler' Here should be defined only actions with different params (e.g. ':set-filter' wrapper method for ':brightness' param) Remove check when no :to-generic? field in available-actions Methods which can be used as function, not re-frame effect
(ns webchange.interpreter.renderer.state.scene (:require [re-frame.core :as re-frame] [webchange.interpreter.renderer.state.db :refer [path-to-db]] [webchange.interpreter.renderer.scene.components.wrapper-interface :as w] [webchange.logger.index :as logger])) (re-frame/reg-event-fx ::init (fn [{:keys [db]} [_]] (let [objects (get-in db (path-to-db [:objects]) (atom {})) groups (get-in db (path-to-db [:groups]) (atom {}))] (reset! objects {}) (reset! groups {}) {:db (-> db (assoc-in (path-to-db [:objects]) objects) (assoc-in (path-to-db [:groups]) groups))}))) (re-frame/reg-sub ::rendering? (fn [db] (get-in db (path-to-db [:rendering?]) false))) (re-frame/reg-event-fx ::set-rendering-state (fn [{:keys [db]} [_ value]] {:db (assoc-in db (path-to-db [:rendering?]) value)})) (re-frame/reg-fx :add-scene-object (fn [{:keys [objects groups object-wrapper]}] (let [object-name (:name object-wrapper) group-name (:group-name object-wrapper)] (when (contains? @objects object-name) (-> (str "Object with name " object-name " already exists.") js/Error. throw)) (swap! objects assoc object-name object-wrapper) (when-not (nil? group-name) (swap! groups update group-name conj object-name))))) (re-frame/reg-fx :remove-scene-object (fn [{:keys [objects object-name]}] (swap! objects dissoc object-name))) (re-frame/reg-event-fx ::register-object (fn [{:keys [db]} [_ object-wrapper]] {:add-scene-object {:objects (get-in db (path-to-db [:objects])) :groups (get-in db (path-to-db [:groups])) :object-wrapper object-wrapper}})) (re-frame/reg-event-fx ::unregister-object (fn [{:keys [db]} [_ object-name]] {:remove-scene-object {:objects (get-in db (path-to-db [:objects])) :object-name object-name}})) (defn get-scene-object [db name] (if-not (nil? name) (let [objects @(get-in db (path-to-db [:objects]))] (get objects name)) nil)) (defn get-scene-group [db group-name] (let [groups @(get-in db (path-to-db [:groups])) group (get groups group-name)] (when-not (nil? group) (map #(get-scene-object db %) group)))) (defn- filter-extra-props [props extra-props-names] (->> props (filter (fn [[prop-name]] (not (some #{prop-name} extra-props-names)))) (into {}))) (def available-actions [{:action :set-align :params [:align] :to-generic? true} {:action :set-image-size :params [:image-size] :to-generic? true} {:action :set-position :params [:x :y]} {:action :set-scale :params [:scale :scale-x :scale-y]} {:action :set-dashed :params [:dashed] :to-generic? true} {:action :set-show-lines :params [:show-lines] :to-generic? true} {:action :set-visibility :params [:visible]} {:action :set-src :params [:src] :to-generic? true} {:action :reset-video :params [:src]} {:action :set-text :params [:text] :to-generic? true} {:action :clear-area :params []} {:action :set-filter :params [:filter :brightness :eager]} {:action :set-opacity :params [:opacity] :to-generic? true} {:action :set-stroke :params [:stroke] :to-generic? true} {:action :set-data :params [:data] :to-generic? true} {:action :set-path :params [:path] :to-generic? true} {:action :set-fill :params [:fill] :to-generic? true} {:action :set-border-color :params [:border-color] :to-generic? true} {:action :set-highlight :params [:highlight] :to-generic? true} {:action :set-permanent-pulsation :params [:permanent-pulsation] :to-generic? true} {:action :set-alpha-pulsation :params [:alpha-pulsation] :to-generic? true} {:action :set-draggable :params [:draggable] :to-generic? true} {:action :set-children :params [:children]} {:action :set-font-size :params [:font-size] :to-generic? true} {:action :set-font-family :params [:font-family] :to-generic? true} {:action :set-skeleton :params [:name] :accompany-params [:skin :skin-names]} {:action :set-animation-skin :params [:skin]} {:action :set-combined-skin :params [:skin-names]} {:action :set-enable :params [:enable?]} {:action :set-speed :params [:speed]} {:action :set-chunks :params [:chunks]}]) (defn- get-action-params [{:keys [params accompany-params] :or {params [] accompany-params []}} overall-params] ":params - used to get action params and determine if action is needed for current params set :accompany-params - also needed for action but NOT used to determine if action is needed. For example apply params 'name', 'skin' and 'skin-names' to 'set-skeleton' action only if 'name' is defined. If 'skin' is defined but 'name' is undefined, use 'set-animation-skin' action instead." (let [action-params (select-keys overall-params params) action-used? (-> action-params empty? not)] (if action-used? {:action-used? action-used? :action-params (merge action-params (select-keys overall-params accompany-params)) :rest-params (apply dissoc overall-params (concat params accompany-params))} {:action-used? action-used? :action-params {} :rest-params overall-params}))) (declare change-scene-object) (defn set-scene-object-state [db object-name state] (let [filtered-state (filter-extra-props state [:revert :start :target :volume]) [execute-actions not-handled-params] (loop [actions-to-execute [] [{:keys [action to-generic?] :as available-action} & rest-available-actions] available-actions current-state filtered-state] (logger/warn (str "Change set param handler (" action ") to generic."))) (if (nil? available-action) [actions-to-execute current-state] (let [{:keys [action-used? action-params rest-params]} (get-action-params available-action current-state)] (recur (if action-used? (conj actions-to-execute [action action-params]) actions-to-execute) rest-available-actions rest-params)))) generic-handlers (map (fn [[param-name param-value]] (let [executor-name (->> param-name clojure.core/name (str "set-") keyword)] [executor-name param-value])) not-handled-params) result-actions (cond-> execute-actions (-> generic-handlers empty? not) (conj [:generic-handler generic-handlers]))] (change-scene-object {:db db} [nil object-name result-actions]))) (defn- event-handler [handler {:keys [db]} [_ & params]] (apply handler (concat [db] params))) (re-frame/reg-event-fx ::set-scene-object-state (partial event-handler set-scene-object-state)) (defn get-object-name [db object-name] (or (get-scene-object db object-name) (get-scene-group db object-name))) (defn- apply-to-wrapper [method target & params] (let [targets (if (sequential? target) target [target])] (doseq [wrapper targets] (apply method (concat [wrapper] params))))) (re-frame/reg-fx :add-filter (fn [[object-wrapper filter-data]] (apply-to-wrapper w/add-filter object-wrapper filter-data))) (re-frame/reg-fx :set-filter (fn [[object-wrapper {:keys [filter] :as params}]] (apply-to-wrapper w/set-filter object-wrapper filter params))) (re-frame/reg-fx :set-align (fn [[object-wrapper {:keys [align]}]] (apply-to-wrapper w/set-align object-wrapper align))) (re-frame/reg-fx :set-image-size (fn [[object-wrapper {:keys [image-size]}]] (apply-to-wrapper w/set-image-size object-wrapper image-size))) (re-frame/reg-fx :set-position (fn [[object-wrapper position]] (apply-to-wrapper w/set-position object-wrapper position))) (re-frame/reg-fx :set-scale (fn [[object-wrapper scale]] (apply-to-wrapper w/set-scale object-wrapper (or (:scale scale) scale)))) (re-frame/reg-fx :set-dashed (fn [[object-wrapper {:keys [dashed]}]] (apply-to-wrapper w/set-dashed object-wrapper dashed))) (re-frame/reg-fx :set-show-lines (fn [[object-wrapper {:keys [show-lines]}]] (apply-to-wrapper w/set-show-lines object-wrapper show-lines))) (defn set-visibility [[object-wrapper {:keys [visible]}]] (apply-to-wrapper w/set-visibility object-wrapper visible)) (re-frame/reg-fx :set-visibility set-visibility) (re-frame/reg-fx :set-value (fn [[object-wrapper value]] (apply-to-wrapper w/set-value object-wrapper value))) (re-frame/reg-fx :set-text (fn [[object-wrapper {:keys [text]}]] (apply-to-wrapper w/set-text object-wrapper text))) (re-frame/reg-fx :clear-area (fn [[object-wrapper {:keys [text]}]] (apply-to-wrapper w/clear-area object-wrapper text))) (re-frame/reg-fx :set-font-size (fn [[object-wrapper {:keys [font-size]}]] (apply-to-wrapper w/set-font-size object-wrapper font-size))) (re-frame/reg-fx :set-font-family (fn [[object-wrapper {:keys [font-family]}]] (apply-to-wrapper w/set-font-family object-wrapper font-family))) (re-frame/reg-fx :set-src (fn [[object-wrapper {:keys [src options]}]] (apply-to-wrapper w/set-src object-wrapper src options))) (re-frame/reg-fx :reset-video (fn [[object-wrapper {:keys [src options]}]] (apply-to-wrapper w/reset-video object-wrapper src options))) (re-frame/reg-fx :set-highlight (fn [[object-wrapper {:keys [highlight options]}]] (apply-to-wrapper w/set-highlight object-wrapper highlight options))) (re-frame/reg-fx :set-permanent-pulsation (fn [[object-wrapper {:keys [permanent-pulsation options]}]] (apply-to-wrapper w/set-permanent-pulsation object-wrapper permanent-pulsation options))) (re-frame/reg-fx :set-alpha-pulsation (fn [[object-wrapper {:keys [alpha-pulsation options]}]] (apply-to-wrapper w/set-alpha-pulsation object-wrapper alpha-pulsation options))) (re-frame/reg-fx :set-draggable (fn [[object-wrapper {:keys [draggable options]}]] (apply-to-wrapper w/set-draggable object-wrapper draggable options))) (re-frame/reg-fx :set-children (fn [[object-wrapper {:keys [children options]} db]] (let [object (:object object-wrapper) parent (.-parent (.-parent object)) children (vec (array-seq (.-children object)))] (doseq [child children] (.addChild parent child)) (doseq [child children] (.removeChild object child))) (doseq [child children] (apply-to-wrapper w/set-parent (get-object-name db (keyword child)) object-wrapper options)))) (re-frame/reg-fx :set-opacity (fn [[object-wrapper {:keys [opacity]}]] (apply-to-wrapper w/set-opacity object-wrapper opacity))) (re-frame/reg-fx :set-tool (fn [[object-wrapper {:keys [tool]}]] (apply-to-wrapper w/set-tool object-wrapper tool))) (re-frame/reg-fx :stop (fn [[object-wrapper]] (apply-to-wrapper w/stop object-wrapper))) (re-frame/reg-fx :set-data (fn [[object-wrapper params]] (apply-to-wrapper w/set-data object-wrapper params))) (re-frame/reg-fx :set-path (fn [[object-wrapper {:keys [path]}]] (apply-to-wrapper w/set-path object-wrapper path))) (re-frame/reg-fx :set-fill (fn [[object-wrapper {:keys [fill]}]] (apply-to-wrapper w/set-fill object-wrapper fill))) (re-frame/reg-fx :set-border-color (fn [[object-wrapper {:keys [border-color]}]] (apply-to-wrapper w/set-border-color object-wrapper border-color))) (re-frame/reg-fx :set-stroke (fn [[object-wrapper params]] (apply-to-wrapper w/set-stroke object-wrapper params))) (re-frame/reg-event-fx ::set-traffic-light (fn [{:keys [db]} [_ object-name color]] (let [wrapper (get-scene-object db object-name)] (apply-to-wrapper w/set-traffic-light wrapper color)))) (re-frame/reg-fx :set-animation-skin (fn [[object-wrapper {:keys [skin]}]] (apply-to-wrapper w/set-skin object-wrapper skin))) (re-frame/reg-fx :set-combined-skin (fn [[object-wrapper {:keys [skin-names]}]] (apply-to-wrapper w/set-combined-skin object-wrapper skin-names))) (re-frame/reg-fx :set-enable (fn [[object-wrapper {:keys [enable?]}]] (apply-to-wrapper w/set-enable object-wrapper enable?))) (re-frame/reg-fx :set-speed (fn [[object-wrapper {:keys [speed]}]] (apply-to-wrapper w/set-speed object-wrapper speed))) (re-frame/reg-fx :set-skeleton (fn [[object-wrapper params]] (apply-to-wrapper w/set-skeleton object-wrapper params))) (re-frame/reg-fx :set-chunks (fn [[{:keys [update-chunks]} params]] (update-chunks {:params params}))) (defn- generic-handler [[object-wrapper props _]] (doseq [[method params] props] (apply-to-wrapper w/execute-method object-wrapper method params))) (re-frame/reg-fx :generic-handler generic-handler) (def fixed-methods {:generic-handler generic-handler :set-visibility set-visibility}) (defn- change-scene-object [{:keys [db]} [_ object-name actions]] (let [wrappers (get-object-name db object-name) handlers (reduce (fn [result [action params]] (if-let [fn-handler (get fixed-methods action)] (update result :fn conj [fn-handler [wrappers params db]]) (update result :fx assoc action [wrappers params db]))) {:fn [] :fx {}} actions)] (doseq [[fn-handler args] (:fn handlers)] (fn-handler args)) (:fx handlers))) (re-frame/reg-event-fx ::change-scene-object change-scene-object)
a9efa3237b70969903ceab6cfcc32aee96925213bc5a1ba63910b74b690111a0
parapluu/Concuerror
processes_leader.erl
-module(processes_leader). -export([test/0]). -export([scenarios/0]). %%------------------------------------------------------------------------------ scenarios() -> [{test, inf, optimal}]. %%------------------------------------------------------------------------------ test() -> group_leader(S = self(), self()), W = fun W(0) -> ok; W(N) -> spawn_monitor(fun () -> W(N - 1) end) end, W(2), [exit(P, kill) || P <- processes(), P =/= S, {group_leader, S} =:= process_info(P, group_leader) ].
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/basic_tests/src/processes_leader.erl
erlang
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
-module(processes_leader). -export([test/0]). -export([scenarios/0]). scenarios() -> [{test, inf, optimal}]. test() -> group_leader(S = self(), self()), W = fun W(0) -> ok; W(N) -> spawn_monitor(fun () -> W(N - 1) end) end, W(2), [exit(P, kill) || P <- processes(), P =/= S, {group_leader, S} =:= process_info(P, group_leader) ].
988bca7efb2bb6387d96cfd00ab24e2c1fc743f9606b2cb88a8802456b8b360b
digikar99/dense-arrays
aref.lisp
(cl:in-package :dense-arrays) (define-compiler-macro array= (array1 array2 &key (test '(function equalp)) &environment env) ;; Turns out merely inlining functions is not sufficient to "preserve" ;; the type declarations; so, we use a compiler macro. See ;; -type-propagation-in-common-lisp-inlined-functions-without-compiler-macr ;; for some details (with-gensyms (array1-sym array2-sym) `(let ((,array1-sym ,array1) (,array2-sym ,array2)) (declare (type ,(primary-form-type array1 env) ,array1-sym) (type ,(primary-form-type array2 env) ,array2-sym)) (and (equalp (narray-dimensions ,array1-sym) (narray-dimensions ,array2-sym)) (loop :for i :below (array-total-size ,array1-sym) :always (funcall ,test (row-major-aref ,array1-sym i) (row-major-aref ,array2-sym i))))))) ;; TODO: These can be optimized slightly, given that AREF and AREF* are now separate. (defpolymorph-compiler-macro aref (dense-array &rest) (&whole form array &rest subscripts &environment env) (let ((original-form `(aref ,@(rest form)))) (compiler-macro-notes:with-notes (original-form env :name (find-polymorph 'aref '(dense-array &rest)) :unwind-on-signal nil :optimization-note-condition optim-speed) ;; The fact that we are here means the type of ARRAY is at least DENSE-ARRAY Therefore , we ignore the second return value of PRIMARY - FORM - TYPE (let* ((array-type (primary-form-type array env)) (class (dense-array-type-class array-type env)) (elt-type (array-type-element-type array-type env)) (rank (array-type-rank array-type env)) FIXME on extensible - compound - types : This should work with simple - dense - array (simple-p (if (member :extensible-compound-types cl:*features*) (subtypep array-type 'simple-array) (subtypep array-type 'simple-dense-array)))) (when (eq 'cl:* class) ;; Don't have much hope of optimization (signal 'backend-failure :form array :form-type array-type) (return-from aref form)) (let* ((storage-accessor (storage-accessor class)) (storage-type (funcall (storage-type-inferrer-from-array-type class) `(%dense-array ,elt-type ,rank))) (subscript-types (mapcar (lm form (primary-form-type form env)) subscripts)) (os (make-gensym-list (length subscripts) "OFFSET")) (ss (make-gensym-list (length subscripts) "STRIDE")) (optim-expansion (once-only (array) (if simple-p `(locally (declare (type dense-array ,array)) (destructuring-lists ((int-index ,ss (array-strides ,array) :dynamic-extent nil)) (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))))) `(locally (declare (type dense-array ,array)) (destructuring-lists ((size ,os (array-offsets ,array) :dynamic-extent nil) (int-index ,ss (array-strides ,array) :dynamic-extent nil)) (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@os ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))))))))) (return-from aref (cond ((eq '* elt-type) (signal 'element-type-failure :form array :form-type array-type) optim-expansion) ((not (integerp rank)) (signal 'rank-failure :form array :form-type array-type) form) ((not (= rank (length subscripts))) (signal 'compiler-macro-notes:optimization-failure-note :datum "Number of subscripts does not match array rank ~D" :args (list rank)) form) ((not (every (lm type (subtypep type '(integer 0))) subscript-types)) (signal 'compiler-macro-notes:optimization-failure-note :datum "Type of subscripts~% ~S~%could not be derived to be non-negative-integers~% ~S" :args (list subscripts subscript-types)) form) (t ELT - TYPE is supplied ;; rank matches the number of subscripts ;; subscripts are declared/derived to be positive integers `(the ,elt-type ,optim-expansion))))))))) (defpolymorph-compiler-macro (setf aref) (t dense-array &rest) (&whole form new-value array &rest subscripts &environment env) (let ((original-form `(funcall #'(setf aref) ,@(rest form)))) (compiler-macro-notes:with-notes (original-form env :name (find-polymorph 'aref '(dense-array &rest)) :unwind-on-signal nil :optimization-note-condition optim-speed) ;; The fact that we are here means the type of ARRAY is at least DENSE-ARRAY Therefore , we ignore the second return value of PRIMARY - FORM - TYPE (let* ((array-type (primary-form-type array env)) (class (dense-array-type-class array-type env)) (elt-type (array-type-element-type array-type env)) (rank (array-type-rank array-type env)) (simple-p (if (member :extensible-compound-types cl:*features*) (subtypep array-type 'simple-array) (subtypep array-type 'simple-dense-array)))) (when (eq 'cl:* class) ;; Don't have much hope of optimization (signal 'backend-failure :form array :form-type array-type) (return-from aref form)) (let* ((storage-accessor (storage-accessor class)) (storage-type (funcall (storage-type-inferrer-from-array-type class) `(%dense-array ,elt-type ,rank))) (subscript-types (mapcar (lm form (primary-form-type form env)) subscripts)) (new-value-type (primary-form-type new-value env)) (os (make-gensym-list (length subscripts) "OFFSET")) (ss (make-gensym-list (length subscripts) "STRIDE")) (optim-expansion (once-only (array) (if simple-p `(locally (declare (type dense-array ,array)) (destructuring-lists ((int-index ,ss (array-strides ,array) :dynamic-extent nil)) (setf (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))) (the ,elt-type ,new-value)))) `(locally (declare (type dense-array ,array)) (destructuring-lists ((size ,os (array-offsets ,array) :dynamic-extent nil) (int-index ,ss (array-strides ,array) :dynamic-extent nil)) (setf (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@os ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))) (the ,elt-type ,new-value)))))))) (return-from aref (cond ((eq '* elt-type) (signal 'element-type-failure :form array :form-type array-type) optim-expansion) ((not (integerp rank)) (signal 'rank-failure :form array :form-type array-type) form) ((not (= rank (length subscripts))) (signal 'compiler-macro-notes:optimization-failure-note :datum "Number of subscripts does not match array rank ~D" :args (list rank)) form) ((not (every (lm type (subtypep type '(integer 0))) subscript-types)) (signal 'compiler-macro-notes:optimization-failure-note :datum "Type of subscripts~% ~S~%could not be derived to be non-negative-integers~% ~S" :args (list subscripts subscript-types)) form) ((not (subtypep new-value-type elt-type env)) (signal 'compiler-macro-notes:note :datum "Type of the new-value form~% ~S~%was derived to be ~S not of type ~S" :args (list new-value new-value-type elt-type)) form) (t `(the ,elt-type ,optim-expansion)))))))))
null
https://raw.githubusercontent.com/digikar99/dense-arrays/f4f2a65c5eb2562caaad88d440136c71c79d754c/optim/aref.lisp
lisp
Turns out merely inlining functions is not sufficient to "preserve" the type declarations; so, we use a compiler macro. See -type-propagation-in-common-lisp-inlined-functions-without-compiler-macr for some details TODO: These can be optimized slightly, given that AREF and AREF* are now separate. The fact that we are here means the type of ARRAY is at least DENSE-ARRAY Don't have much hope of optimization rank matches the number of subscripts subscripts are declared/derived to be positive integers The fact that we are here means the type of ARRAY is at least DENSE-ARRAY Don't have much hope of optimization
(cl:in-package :dense-arrays) (define-compiler-macro array= (array1 array2 &key (test '(function equalp)) &environment env) (with-gensyms (array1-sym array2-sym) `(let ((,array1-sym ,array1) (,array2-sym ,array2)) (declare (type ,(primary-form-type array1 env) ,array1-sym) (type ,(primary-form-type array2 env) ,array2-sym)) (and (equalp (narray-dimensions ,array1-sym) (narray-dimensions ,array2-sym)) (loop :for i :below (array-total-size ,array1-sym) :always (funcall ,test (row-major-aref ,array1-sym i) (row-major-aref ,array2-sym i))))))) (defpolymorph-compiler-macro aref (dense-array &rest) (&whole form array &rest subscripts &environment env) (let ((original-form `(aref ,@(rest form)))) (compiler-macro-notes:with-notes (original-form env :name (find-polymorph 'aref '(dense-array &rest)) :unwind-on-signal nil :optimization-note-condition optim-speed) Therefore , we ignore the second return value of PRIMARY - FORM - TYPE (let* ((array-type (primary-form-type array env)) (class (dense-array-type-class array-type env)) (elt-type (array-type-element-type array-type env)) (rank (array-type-rank array-type env)) FIXME on extensible - compound - types : This should work with simple - dense - array (simple-p (if (member :extensible-compound-types cl:*features*) (subtypep array-type 'simple-array) (subtypep array-type 'simple-dense-array)))) (when (eq 'cl:* class) (signal 'backend-failure :form array :form-type array-type) (return-from aref form)) (let* ((storage-accessor (storage-accessor class)) (storage-type (funcall (storage-type-inferrer-from-array-type class) `(%dense-array ,elt-type ,rank))) (subscript-types (mapcar (lm form (primary-form-type form env)) subscripts)) (os (make-gensym-list (length subscripts) "OFFSET")) (ss (make-gensym-list (length subscripts) "STRIDE")) (optim-expansion (once-only (array) (if simple-p `(locally (declare (type dense-array ,array)) (destructuring-lists ((int-index ,ss (array-strides ,array) :dynamic-extent nil)) (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))))) `(locally (declare (type dense-array ,array)) (destructuring-lists ((size ,os (array-offsets ,array) :dynamic-extent nil) (int-index ,ss (array-strides ,array) :dynamic-extent nil)) (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@os ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))))))))) (return-from aref (cond ((eq '* elt-type) (signal 'element-type-failure :form array :form-type array-type) optim-expansion) ((not (integerp rank)) (signal 'rank-failure :form array :form-type array-type) form) ((not (= rank (length subscripts))) (signal 'compiler-macro-notes:optimization-failure-note :datum "Number of subscripts does not match array rank ~D" :args (list rank)) form) ((not (every (lm type (subtypep type '(integer 0))) subscript-types)) (signal 'compiler-macro-notes:optimization-failure-note :datum "Type of subscripts~% ~S~%could not be derived to be non-negative-integers~% ~S" :args (list subscripts subscript-types)) form) (t ELT - TYPE is supplied `(the ,elt-type ,optim-expansion))))))))) (defpolymorph-compiler-macro (setf aref) (t dense-array &rest) (&whole form new-value array &rest subscripts &environment env) (let ((original-form `(funcall #'(setf aref) ,@(rest form)))) (compiler-macro-notes:with-notes (original-form env :name (find-polymorph 'aref '(dense-array &rest)) :unwind-on-signal nil :optimization-note-condition optim-speed) Therefore , we ignore the second return value of PRIMARY - FORM - TYPE (let* ((array-type (primary-form-type array env)) (class (dense-array-type-class array-type env)) (elt-type (array-type-element-type array-type env)) (rank (array-type-rank array-type env)) (simple-p (if (member :extensible-compound-types cl:*features*) (subtypep array-type 'simple-array) (subtypep array-type 'simple-dense-array)))) (when (eq 'cl:* class) (signal 'backend-failure :form array :form-type array-type) (return-from aref form)) (let* ((storage-accessor (storage-accessor class)) (storage-type (funcall (storage-type-inferrer-from-array-type class) `(%dense-array ,elt-type ,rank))) (subscript-types (mapcar (lm form (primary-form-type form env)) subscripts)) (new-value-type (primary-form-type new-value env)) (os (make-gensym-list (length subscripts) "OFFSET")) (ss (make-gensym-list (length subscripts) "STRIDE")) (optim-expansion (once-only (array) (if simple-p `(locally (declare (type dense-array ,array)) (destructuring-lists ((int-index ,ss (array-strides ,array) :dynamic-extent nil)) (setf (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))) (the ,elt-type ,new-value)))) `(locally (declare (type dense-array ,array)) (destructuring-lists ((size ,os (array-offsets ,array) :dynamic-extent nil) (int-index ,ss (array-strides ,array) :dynamic-extent nil)) (setf (,storage-accessor (the ,storage-type (array-storage ,array)) (the-size (+ ,@os ,@(mapcar (lm ss sub `(the-size (* ,ss ,sub))) ss subscripts)))) (the ,elt-type ,new-value)))))))) (return-from aref (cond ((eq '* elt-type) (signal 'element-type-failure :form array :form-type array-type) optim-expansion) ((not (integerp rank)) (signal 'rank-failure :form array :form-type array-type) form) ((not (= rank (length subscripts))) (signal 'compiler-macro-notes:optimization-failure-note :datum "Number of subscripts does not match array rank ~D" :args (list rank)) form) ((not (every (lm type (subtypep type '(integer 0))) subscript-types)) (signal 'compiler-macro-notes:optimization-failure-note :datum "Type of subscripts~% ~S~%could not be derived to be non-negative-integers~% ~S" :args (list subscripts subscript-types)) form) ((not (subtypep new-value-type elt-type env)) (signal 'compiler-macro-notes:note :datum "Type of the new-value form~% ~S~%was derived to be ~S not of type ~S" :args (list new-value new-value-type elt-type)) form) (t `(the ,elt-type ,optim-expansion)))))))))
90c509237e09d16b03df7ec7093bbbd780e6b7a008095b4061e93746d685e47d
rbkmoney/erlang_capi_v2
capi_client_invoice_templates.erl
-module(capi_client_invoice_templates). -export([create/2]). -export([get_template_by_id/2]). -export([update/3]). -export([delete/2]). -export([create_invoice/3]). -export([get_invoice_payment_methods/2]). -type context() :: capi_client_lib:context(). -spec create(context(), map()) -> {ok, term()} | {error, term()}. create(Context, Request) -> Params = #{body => Request}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:create_invoice_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec get_template_by_id(context(), binary()) -> {ok, term()} | {error, term()}. get_template_by_id(Context, InvoiceTplID) -> Params = #{binding => #{<<"invoiceTemplateID">> => InvoiceTplID}}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:get_invoice_template_by_id(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec update(context(), binary(), map()) -> {ok, term()} | {error, term()}. update(Context, InvoiceTplID, Request) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID}, body => Request }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:update_invoice_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec delete(context(), binary()) -> ok | {error, term()}. delete(Context, InvoiceTplID) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID} }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:delete_invoice_template(Url, PreparedParams, Opts), case capi_client_lib:handle_response(Response) of {ok, _Body} -> ok; {error, Error} -> {error, Error} end. -spec create_invoice(context(), binary(), map()) -> {ok, term()} | {error, term()}. create_invoice(Context, InvoiceTplID, Request) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID}, body => Request }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:create_invoice_with_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec get_invoice_payment_methods(context(), binary()) -> {ok, term()} | {error, term()}. get_invoice_payment_methods(Context, InvoiceTplID) -> Params = #{binding => #{<<"invoiceTemplateID">> => InvoiceTplID}}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:get_invoice_payment_methods_by_template_id(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response).
null
https://raw.githubusercontent.com/rbkmoney/erlang_capi_v2/438d0a603475c57dddade8c419f0d70fdf86438d/apps/capi_client/src/capi_client_invoice_templates.erl
erlang
-module(capi_client_invoice_templates). -export([create/2]). -export([get_template_by_id/2]). -export([update/3]). -export([delete/2]). -export([create_invoice/3]). -export([get_invoice_payment_methods/2]). -type context() :: capi_client_lib:context(). -spec create(context(), map()) -> {ok, term()} | {error, term()}. create(Context, Request) -> Params = #{body => Request}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:create_invoice_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec get_template_by_id(context(), binary()) -> {ok, term()} | {error, term()}. get_template_by_id(Context, InvoiceTplID) -> Params = #{binding => #{<<"invoiceTemplateID">> => InvoiceTplID}}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:get_invoice_template_by_id(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec update(context(), binary(), map()) -> {ok, term()} | {error, term()}. update(Context, InvoiceTplID, Request) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID}, body => Request }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:update_invoice_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec delete(context(), binary()) -> ok | {error, term()}. delete(Context, InvoiceTplID) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID} }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:delete_invoice_template(Url, PreparedParams, Opts), case capi_client_lib:handle_response(Response) of {ok, _Body} -> ok; {error, Error} -> {error, Error} end. -spec create_invoice(context(), binary(), map()) -> {ok, term()} | {error, term()}. create_invoice(Context, InvoiceTplID, Request) -> Params = #{ binding => #{<<"invoiceTemplateID">> => InvoiceTplID}, body => Request }, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:create_invoice_with_template(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response). -spec get_invoice_payment_methods(context(), binary()) -> {ok, term()} | {error, term()}. get_invoice_payment_methods(Context, InvoiceTplID) -> Params = #{binding => #{<<"invoiceTemplateID">> => InvoiceTplID}}, {Url, PreparedParams, Opts} = capi_client_lib:make_request(Context, Params), Response = swag_client_invoice_templates_api:get_invoice_payment_methods_by_template_id(Url, PreparedParams, Opts), capi_client_lib:handle_response(Response).
20935bfb7e763109bead14faa35cdd7b45909fb153992e53514cc26e48b03692
gvolpe/shopping-cart-haskell
Main.hs
# LANGUAGE RecordWildCards # module Main where import Control.Monad.Managed ( with ) import Domain.Cart ( CartExpiration(..) ) import Http.Clients.Payments ( mkPaymentClient ) import Http.Server ( runServer ) import Resources import Programs.Checkout ( mkCheckout ) import Services.Brands ( mkBrands ) import Services.Items ( mkItems ) import Services.Orders ( mkOrders ) import Services.ShoppingCart ( mkShoppingCart ) import Services main :: IO () main = with mkResources $ \Res {..} -> let brands = mkBrands psql items = mkItems psql cart = mkShoppingCart redis items exp' orders = mkOrders psql client = mkPaymentClient checkout = mkCheckout client cart orders exp' = CartExpiration (30 * 60) in runServer (Services brands cart checkout items orders client)
null
https://raw.githubusercontent.com/gvolpe/shopping-cart-haskell/6acc339808d382094ea5302a8e5544dddc209bac/app/Main.hs
haskell
# LANGUAGE RecordWildCards # module Main where import Control.Monad.Managed ( with ) import Domain.Cart ( CartExpiration(..) ) import Http.Clients.Payments ( mkPaymentClient ) import Http.Server ( runServer ) import Resources import Programs.Checkout ( mkCheckout ) import Services.Brands ( mkBrands ) import Services.Items ( mkItems ) import Services.Orders ( mkOrders ) import Services.ShoppingCart ( mkShoppingCart ) import Services main :: IO () main = with mkResources $ \Res {..} -> let brands = mkBrands psql items = mkItems psql cart = mkShoppingCart redis items exp' orders = mkOrders psql client = mkPaymentClient checkout = mkCheckout client cart orders exp' = CartExpiration (30 * 60) in runServer (Services brands cart checkout items orders client)
deb612b8b79454151e19f0bf5672f1af91575b32caa53ff04701d3b5308163d5
1HaskellADay/1HAD
Exercise.hs
module HAD.Y2014.M03.D25.Exercise ( Board , board , getList ) where import Data.List (groupBy) import Test.QuickCheck -- Preamble -- $setup -- >>> import Control.Applicative ((<$>), (<*>)) -- >>> import Data.List (group) -- A board is a "square list of list" -- The "square" form, is ensure by the constructor (board) newtype Board a = Board {getList :: [[a]]} deriving (Eq, Show, Read) -- | Exercise Build an Arbitrary instance for Board of any given size -- -- The external list length is equal to the length of each internal lists prop > ( 1== ) . length . group . ( flip ( :) < * > length ) . map length $ getList bs -- instance Arbitrary a => Arbitrary (Board a) where arbitrary = undefined Just some extra content , it is n't useful for today 's exercise Constructor | board Yesterday 's squareOf , build a square board with initial values board :: Int -> a -> [a] -> [[a]] board n x = take n . map (take n) . iterate (drop n) . (++ repeat x)
null
https://raw.githubusercontent.com/1HaskellADay/1HAD/3b3f9b7448744f9b788034f3aca2d5050d1a5c73/exercises/HAD/Y2014/M03/D25/Exercise.hs
haskell
Preamble $setup >>> import Control.Applicative ((<$>), (<*>)) >>> import Data.List (group) A board is a "square list of list" The "square" form, is ensure by the constructor (board) | Exercise The external list length is equal to the length of each internal lists
module HAD.Y2014.M03.D25.Exercise ( Board , board , getList ) where import Data.List (groupBy) import Test.QuickCheck newtype Board a = Board {getList :: [[a]]} deriving (Eq, Show, Read) Build an Arbitrary instance for Board of any given size prop > ( 1== ) . length . group . ( flip ( :) < * > length ) . map length $ getList bs instance Arbitrary a => Arbitrary (Board a) where arbitrary = undefined Just some extra content , it is n't useful for today 's exercise Constructor | board Yesterday 's squareOf , build a square board with initial values board :: Int -> a -> [a] -> [[a]] board n x = take n . map (take n) . iterate (drop n) . (++ repeat x)
98a5e2cc33ba3a80a424aaab5eb4955f901818f516f5c2d5bfbb94a66b57bad6
OCADml/OSCADml
OSCADml.ml
* { 1 OpenSCAD DSL } module Scad = Scad (** {2 Configuration Types} These modules are provided at the top-level as convenient namespaces for the configuration types taken as parameters to their corresponding model building functions in {!module:Scad}. *) module Color = Color module Text = Text (** {1 Utilities} *) module Export = Export module Debug = Debug
null
https://raw.githubusercontent.com/OCADml/OSCADml/d2f64a3f6454ff37a3c725b619c6a89252af789d/lib/OSCADml.ml
ocaml
* {2 Configuration Types} These modules are provided at the top-level as convenient namespaces for the configuration types taken as parameters to their corresponding model building functions in {!module:Scad}. * {1 Utilities}
* { 1 OpenSCAD DSL } module Scad = Scad module Color = Color module Text = Text module Export = Export module Debug = Debug
ef635c0212ab0232fcafdb834348d2f0b3b88ea52cf705b1a39753bc0b2b5392
roehst/tapl-implementations
core.mli
module Core Core typechecking and evaluation functions Core typechecking and evaluation functions *) open Syntax open Support.Error val typeof : context -> term -> ty val subtype : context -> ty -> ty -> bool val tyeqv : context -> ty -> ty -> bool type store val emptystore : store val shiftstore : int -> store -> store val eval : context -> store -> term -> term * store val evalbinding : context -> store -> binding -> binding * store val lcst : context -> ty -> ty val simplifyty : context -> ty -> ty
null
https://raw.githubusercontent.com/roehst/tapl-implementations/23c0dc505a8c0b0a797201a7e4e3e5b939dd8fdb/fullfsubref/core.mli
ocaml
module Core Core typechecking and evaluation functions Core typechecking and evaluation functions *) open Syntax open Support.Error val typeof : context -> term -> ty val subtype : context -> ty -> ty -> bool val tyeqv : context -> ty -> ty -> bool type store val emptystore : store val shiftstore : int -> store -> store val eval : context -> store -> term -> term * store val evalbinding : context -> store -> binding -> binding * store val lcst : context -> ty -> ty val simplifyty : context -> ty -> ty
cb5c0a24e5e24957b781953ee1077981785bfa0be9b548f0b0d7bb67f5467b16
public-law/nevada-revised-statutes-parser
NRSParser.hs
{-# LANGUAGE OverloadedStrings #-} module NRSParser where import BasicPrelude import qualified Data.HashMap.Lazy as HM import System.FilePath import ChapterFile ( ChapterMap ) import Data.Time import HtmlUtil ( Html , readHtmlFile ) import Models.NRS import TreeParser ( parseTree ) import Year ( toYear ) import FileUtil ( AbsolutePath , listFilesInDirectory , toFilePath , (./) , (//) ) import DateUtil ( todaysDate ) parseFiles :: AbsolutePath -> IO NRS parseFiles dir = do let indexFile = (//) $ toFilePath dir </> "index.html" chapterFilenames <- listFilesInDirectory dir let relativeChapterFilenames = (./) . takeFileName . toFilePath <$> chapterFilenames today <- todaysDate indexHtml <- readHtmlFile indexFile chaptersHtml <- mapM readHtmlFile chapterFilenames let chapterMap = HM.fromList $ zip relativeChapterFilenames chaptersHtml return $ parseNRS indexHtml chapterMap today parseNRS :: Html -> ChapterMap -> Day -> NRS parseNRS indexFile chapterMap currentDate = NRS { statuteTree = parseTree indexFile chapterMap , nominalDate = toYear 2018 , dateAccessed = currentDate }
null
https://raw.githubusercontent.com/public-law/nevada-revised-statutes-parser/88a886debdab6ce5bd6cf5819c846cec1ffb9220/src/NRSParser.hs
haskell
# LANGUAGE OverloadedStrings #
module NRSParser where import BasicPrelude import qualified Data.HashMap.Lazy as HM import System.FilePath import ChapterFile ( ChapterMap ) import Data.Time import HtmlUtil ( Html , readHtmlFile ) import Models.NRS import TreeParser ( parseTree ) import Year ( toYear ) import FileUtil ( AbsolutePath , listFilesInDirectory , toFilePath , (./) , (//) ) import DateUtil ( todaysDate ) parseFiles :: AbsolutePath -> IO NRS parseFiles dir = do let indexFile = (//) $ toFilePath dir </> "index.html" chapterFilenames <- listFilesInDirectory dir let relativeChapterFilenames = (./) . takeFileName . toFilePath <$> chapterFilenames today <- todaysDate indexHtml <- readHtmlFile indexFile chaptersHtml <- mapM readHtmlFile chapterFilenames let chapterMap = HM.fromList $ zip relativeChapterFilenames chaptersHtml return $ parseNRS indexHtml chapterMap today parseNRS :: Html -> ChapterMap -> Day -> NRS parseNRS indexFile chapterMap currentDate = NRS { statuteTree = parseTree indexFile chapterMap , nominalDate = toYear 2018 , dateAccessed = currentDate }
b09177bc5515400d47340e676c9840ae442d0fd54720b4c71b4ecfc52b02588f
numcl/numcl
sbcl-environment.lisp
(in-package :cl-user) (deftype check (tag &environment env) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check :f1))) (declare (type (check :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check f3) b)) (print (list a b c d)) a)) (deftype check2 (tag &environment env) (break) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check2 :f1))) (declare (type (check2 :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check2 f3) b)) (print (list a b c d)) a)) ( deftype element - type - of ( variable & environment env ) ( match ( cdr ( assoc ' type ( nth - value 2 ( cltl2 : variable - information variable env ) ) ) ) ;; ((type-r:array-subtype element-type) ;; element-type) ;; (_ ;; t))) ;; ;; (defun g (a b) ;; (declare (type (array fixnum) a)) ; assume this declaration is generated by macro ;; (declare (type (element-type-of a) b)) ;; a) (in-package :numcl.impl) (deftype check (tag &environment env) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check :f1))) (declare (type (check :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check f3) b)) (print (list a b c d)) a)) ;; didn't work (deftype derive (variable pattern clause &environment env) "A type specifier that derives a new type from the type declaration of other types. This is handy for writing a macro which needs some type propagation: Since the type information is stored into the environment and is retrieved by this macro, you don't need to explicitly pass around the information during macro expansion. For example, suppose you have a macro M that expands to something like: (let ((a ...)) (declare ((type (array fixnum (2 2))))) (M 'fixnum b c d ...)) which expands to (let ((a ...)) (declare ((type (array fixnum (2 2))))) (let ((b ...) (c ...) (d ...)) (declare (type fixnum b c d)) ...)) If you want to make the type of b,c,d same as the element-type of a, you need to adjust the argument to M each time. With DERIVE type, you can write (let ((a ...)) (declare ((type (array fixnum (2 2))))) (M a b c d ...)) then (let ((a ...)) (declare ((type (array fixnum (2 2))))) (let ((b ...) (c ...) (d ...)) (declare (type (derive a (array-subtype element-type) element-type) b c d)) ...)) You also need something similar when the macro is sufficiently complex and needs to be separated into multiple functions and / or multiple layers of macros. Note that this does not provide a runtime checking and unification of type variables. " (derive-type-expander variable pattern clause env)) (defun derive-type-expander (variable pattern clause env) (eval `(ematch ,(nth-value 2 (cltl2:variable-information variable env)) ((assoc (type . ,pattern)) ,clause))))
null
https://raw.githubusercontent.com/numcl/numcl/3dcdb0e24a33943d6c3a188ecbb0c78003bf975c/memos/sbcl-environment.lisp
lisp
((type-r:array-subtype element-type) element-type) (_ t))) (defun g (a b) (declare (type (array fixnum) a)) ; assume this declaration is generated by macro (declare (type (element-type-of a) b)) a) didn't work
(in-package :cl-user) (deftype check (tag &environment env) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check :f1))) (declare (type (check :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check f3) b)) (print (list a b c d)) a)) (deftype check2 (tag &environment env) (break) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check2 :f1))) (declare (type (check2 :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check2 f3) b)) (print (list a b c d)) a)) ( deftype element - type - of ( variable & environment env ) ( match ( cdr ( assoc ' type ( nth - value 2 ( cltl2 : variable - information variable env ) ) ) ) (in-package :numcl.impl) (deftype check (tag &environment env) (format t "~&~5a : ~a" tag (if env t nil)) t) (defun f (a b c) (declare (type (check :f1))) (declare (type (check :f2) a)) (declare (type fixnum b)) (let ((d 0)) (declare (type fixnum d)) (declare (type (check f3) b)) (print (list a b c d)) a)) (deftype derive (variable pattern clause &environment env) "A type specifier that derives a new type from the type declaration of other types. This is handy for writing a macro which needs some type propagation: Since the type information is stored into the environment and is retrieved by this macro, you don't need to explicitly pass around the information during macro expansion. For example, suppose you have a macro M that expands to something like: (let ((a ...)) (declare ((type (array fixnum (2 2))))) (M 'fixnum b c d ...)) which expands to (let ((a ...)) (declare ((type (array fixnum (2 2))))) (let ((b ...) (c ...) (d ...)) (declare (type fixnum b c d)) ...)) If you want to make the type of b,c,d same as the element-type of a, you need to adjust the argument to M each time. With DERIVE type, you can write (let ((a ...)) (declare ((type (array fixnum (2 2))))) (M a b c d ...)) then (let ((a ...)) (declare ((type (array fixnum (2 2))))) (let ((b ...) (c ...) (d ...)) (declare (type (derive a (array-subtype element-type) element-type) b c d)) ...)) You also need something similar when the macro is sufficiently complex and needs to be separated into multiple functions and / or multiple layers of macros. Note that this does not provide a runtime checking and unification of type variables. " (derive-type-expander variable pattern clause env)) (defun derive-type-expander (variable pattern clause env) (eval `(ematch ,(nth-value 2 (cltl2:variable-information variable env)) ((assoc (type . ,pattern)) ,clause))))
3e5f33155e6365e324aa2ea5901c00c154f7a36f0f8884db16efb5763dbf2104
astrada/ocaml-extjs
ext_dom_Element.ml
class type t = object('self) inherit Ext_dom_AbstractElement.t method autoBoxAdjust : bool Js.t Js.prop method originalDisplay : Js.js_string Js.t Js.prop method addClsOnClick : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addClsOnFocus : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addClsOnOver : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addKeyListener : _ Js.t -> _ Js.callback -> _ Js.t Js.optdef -> Ext_util_KeyMap.t Js.t Js.meth method addKeyMap : _ Js.t -> Ext_util_KeyMap.t Js.t Js.meth method addListener : Js.js_string Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method animate : _ Js.t -> 'self Js.t Js.meth method blur : 'self Js.t Js.meth method boxWrap : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method cacheScrollValues : _ Js.callback Js.meth method center : _ Js.t -> unit Js.meth method clean : bool Js.t Js.optdef -> unit Js.meth method clearListeners : 'self Js.t Js.meth method clearOpacity : 'self Js.t Js.meth method clearPositioning : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method clip : 'self Js.t Js.meth method createProxy : _ Js.t -> _ Js.t Js.optdef -> bool Js.t Js.optdef -> 'self Js.t Js.meth method createShim : 'self Js.t Js.meth method enableDisplayMode : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method fadeIn : _ Js.t Js.optdef -> 'self Js.t Js.meth method fadeOut : _ Js.t Js.optdef -> 'self Js.t Js.meth method focus : Js.number Js.t Js.optdef -> 'self Js.t Js.meth method focusable : _ Js.t -> bool Js.t Js.meth method frame : Js.js_string Js.t Js.optdef -> Js.number Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method getAttributeNS : Js.js_string Js.t -> Js.js_string Js.t -> Js.js_string Js.t Js.meth method getColor : Js.js_string Js.t -> Js.js_string Js.t -> Js.js_string Js.t Js.optdef -> unit Js.meth method getComputedHeight : Js.number Js.t Js.meth method getComputedWidth : Js.number Js.t Js.meth method getFrameWidth : Js.js_string Js.t -> Js.number Js.t Js.meth method getLoader : Ext_ElementLoader.t Js.t Js.meth method getLocalX : Js.number Js.t Js.meth method getLocalXY : _ Js.js_array Js.t Js.meth method getLocalY : Js.number Js.t Js.meth method getScroll : _ Js.t Js.meth method getScrollLeft : Js.number Js.t Js.meth method getScrollTop : Js.number Js.t Js.meth method getStyleSize : _ Js.t Js.meth method getTextWidth : Js.js_string Js.t -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.meth method getX : Js.number Js.t Js.meth method getY : Js.number Js.t Js.meth method ghost : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method hide : _ Js.t Js.optdef -> 'self Js.t Js.meth method highlight : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method hover : _ Js.callback -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method initDD : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DD.t Js.t Js.meth method initDDProxy : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DDProxy.t Js.t Js.meth method initDDTarget : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DDTarget.t Js.t Js.meth method isBorderBox : bool Js.t Js.meth method isDisplayed : bool Js.t Js.meth method isFocusable : _ Js.t -> bool Js.t Js.meth method isMasked : bool Js.t Js.meth method isScrollable : bool Js.t Js.meth method isVisible : bool Js.t Js.optdef -> bool Js.t Js.meth method load : _ Js.t -> 'self Js.t Js.meth method mask_element : Js.js_string Js.t Js.optdef -> Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method monitorMouseLeave : Js.number Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.meth method needsTabIndex : unit Js.meth method on : Js.js_string Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method position : Js.js_string Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> unit Js.meth method puff : _ Js.t Js.optdef -> 'self Js.t Js.meth method purgeAllListeners : 'self Js.t Js.meth method relayEvent : Js.js_string Js.t -> _ Js.t -> unit Js.meth method removeAllListeners : 'self Js.t Js.meth method removeListener : Js.js_string Js.t -> _ Js.callback -> _ Js.t -> 'self Js.t Js.meth method scroll : Js.js_string Js.t -> Js.number Js.t -> _ Js.t Js.optdef -> bool Js.t Js.meth method scrollBy : _ Js.t -> _ Js.t -> _ Js.t -> 'self Js.t Js.meth method scrollIntoView : _ Js.t Js.optdef -> bool Js.t Js.optdef -> _ Js.t Js.optdef -> bool Js.t Js.optdef -> 'self Js.t Js.meth method scrollTo : Js.js_string Js.t -> Js.number Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method selectable : 'self Js.t Js.meth method setDisplayed : _ Js.t -> 'self Js.t Js.meth method setOpacity : Js.number Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method setPositioning : _ Js.t -> 'self Js.t Js.meth method setScrollLeft : Js.number Js.t -> 'self Js.t Js.meth method setScrollTop : Js.number Js.t -> 'self Js.t Js.meth method setVisible : bool Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method show : _ Js.t Js.optdef -> 'self Js.t Js.meth method slideIn : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method slideOut : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method swallowEvent : _ Js.t -> bool Js.t Js.optdef -> 'self Js.t Js.meth method switchOff : _ Js.t Js.optdef -> 'self Js.t Js.meth method toggle : _ Js.t Js.optdef -> 'self Js.t Js.meth method un : Js.js_string Js.t -> _ Js.callback -> _ Js.t -> 'self Js.t Js.meth method unclip : 'self Js.t Js.meth method unmask : unit Js.meth method unselectable : 'self Js.t Js.meth method update_html : Js.js_string Js.t -> bool Js.t Js.optdef -> _ Js.callback Js.optdef -> 'self Js.t Js.meth end class type configs = object('self) inherit Ext_dom_AbstractElement.configs end class type events = object inherit Ext_dom_AbstractElement.events method _DOMActivate : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMAttrModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMCharacterDataModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMFocusIn : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMFocusOut : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeInserted : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeInsertedIntoDocument : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeRemoved : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeRemovedFromDocument : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMSubtreeModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method abort : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method blur : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method change : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method click : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method contextmenu : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method dblclick : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method error : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method focus : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keydown : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keypress : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keyup : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method load : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mousedown : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseenter : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseleave : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mousemove : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseout : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseover : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseup : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method reset : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method resize : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method scroll : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method select : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method submit : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method unload : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop end class type statics = object inherit Ext_dom_AbstractElement.statics method select : _ Js.t -> bool Js.t Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.meth end let get_static () = Js.Unsafe.variable "Ext.dom.Element" let static = get_static () let select selector unique root = Js.Unsafe.meth_call static (Js.Unsafe.variable "select") [|Js.Unsafe.inject selector; Js.Unsafe.inject unique; Js.Unsafe.inject root; |] let of_configs c = Js.Unsafe.coerce c let to_configs o = Js.Unsafe.coerce o
null
https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_dom_Element.ml
ocaml
class type t = object('self) inherit Ext_dom_AbstractElement.t method autoBoxAdjust : bool Js.t Js.prop method originalDisplay : Js.js_string Js.t Js.prop method addClsOnClick : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addClsOnFocus : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addClsOnOver : Js.js_string Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method addKeyListener : _ Js.t -> _ Js.callback -> _ Js.t Js.optdef -> Ext_util_KeyMap.t Js.t Js.meth method addKeyMap : _ Js.t -> Ext_util_KeyMap.t Js.t Js.meth method addListener : Js.js_string Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method animate : _ Js.t -> 'self Js.t Js.meth method blur : 'self Js.t Js.meth method boxWrap : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method cacheScrollValues : _ Js.callback Js.meth method center : _ Js.t -> unit Js.meth method clean : bool Js.t Js.optdef -> unit Js.meth method clearListeners : 'self Js.t Js.meth method clearOpacity : 'self Js.t Js.meth method clearPositioning : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method clip : 'self Js.t Js.meth method createProxy : _ Js.t -> _ Js.t Js.optdef -> bool Js.t Js.optdef -> 'self Js.t Js.meth method createShim : 'self Js.t Js.meth method enableDisplayMode : Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method fadeIn : _ Js.t Js.optdef -> 'self Js.t Js.meth method fadeOut : _ Js.t Js.optdef -> 'self Js.t Js.meth method focus : Js.number Js.t Js.optdef -> 'self Js.t Js.meth method focusable : _ Js.t -> bool Js.t Js.meth method frame : Js.js_string Js.t Js.optdef -> Js.number Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method getAttributeNS : Js.js_string Js.t -> Js.js_string Js.t -> Js.js_string Js.t Js.meth method getColor : Js.js_string Js.t -> Js.js_string Js.t -> Js.js_string Js.t Js.optdef -> unit Js.meth method getComputedHeight : Js.number Js.t Js.meth method getComputedWidth : Js.number Js.t Js.meth method getFrameWidth : Js.js_string Js.t -> Js.number Js.t Js.meth method getLoader : Ext_ElementLoader.t Js.t Js.meth method getLocalX : Js.number Js.t Js.meth method getLocalXY : _ Js.js_array Js.t Js.meth method getLocalY : Js.number Js.t Js.meth method getScroll : _ Js.t Js.meth method getScrollLeft : Js.number Js.t Js.meth method getScrollTop : Js.number Js.t Js.meth method getStyleSize : _ Js.t Js.meth method getTextWidth : Js.js_string Js.t -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.meth method getX : Js.number Js.t Js.meth method getY : Js.number Js.t Js.meth method ghost : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method hide : _ Js.t Js.optdef -> 'self Js.t Js.meth method highlight : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method hover : _ Js.callback -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method initDD : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DD.t Js.t Js.meth method initDDProxy : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DDProxy.t Js.t Js.meth method initDDTarget : Js.js_string Js.t -> _ Js.t -> _ Js.t -> Ext_dd_DDTarget.t Js.t Js.meth method isBorderBox : bool Js.t Js.meth method isDisplayed : bool Js.t Js.meth method isFocusable : _ Js.t -> bool Js.t Js.meth method isMasked : bool Js.t Js.meth method isScrollable : bool Js.t Js.meth method isVisible : bool Js.t Js.optdef -> bool Js.t Js.meth method load : _ Js.t -> 'self Js.t Js.meth method mask_element : Js.js_string Js.t Js.optdef -> Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth method monitorMouseLeave : Js.number Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.meth method needsTabIndex : unit Js.meth method on : Js.js_string Js.t -> _ Js.callback -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method position : Js.js_string Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> unit Js.meth method puff : _ Js.t Js.optdef -> 'self Js.t Js.meth method purgeAllListeners : 'self Js.t Js.meth method relayEvent : Js.js_string Js.t -> _ Js.t -> unit Js.meth method removeAllListeners : 'self Js.t Js.meth method removeListener : Js.js_string Js.t -> _ Js.callback -> _ Js.t -> 'self Js.t Js.meth method scroll : Js.js_string Js.t -> Js.number Js.t -> _ Js.t Js.optdef -> bool Js.t Js.meth method scrollBy : _ Js.t -> _ Js.t -> _ Js.t -> 'self Js.t Js.meth method scrollIntoView : _ Js.t Js.optdef -> bool Js.t Js.optdef -> _ Js.t Js.optdef -> bool Js.t Js.optdef -> 'self Js.t Js.meth method scrollTo : Js.js_string Js.t -> Js.number Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method selectable : 'self Js.t Js.meth method setDisplayed : _ Js.t -> 'self Js.t Js.meth method setOpacity : Js.number Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method setPositioning : _ Js.t -> 'self Js.t Js.meth method setScrollLeft : Js.number Js.t -> 'self Js.t Js.meth method setScrollTop : Js.number Js.t -> 'self Js.t Js.meth method setVisible : bool Js.t -> _ Js.t Js.optdef -> 'self Js.t Js.meth method show : _ Js.t Js.optdef -> 'self Js.t Js.meth method slideIn : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method slideOut : Js.js_string Js.t Js.optdef -> _ Js.t Js.optdef -> 'self Js.t Js.meth method swallowEvent : _ Js.t -> bool Js.t Js.optdef -> 'self Js.t Js.meth method switchOff : _ Js.t Js.optdef -> 'self Js.t Js.meth method toggle : _ Js.t Js.optdef -> 'self Js.t Js.meth method un : Js.js_string Js.t -> _ Js.callback -> _ Js.t -> 'self Js.t Js.meth method unclip : 'self Js.t Js.meth method unmask : unit Js.meth method unselectable : 'self Js.t Js.meth method update_html : Js.js_string Js.t -> bool Js.t Js.optdef -> _ Js.callback Js.optdef -> 'self Js.t Js.meth end class type configs = object('self) inherit Ext_dom_AbstractElement.configs end class type events = object inherit Ext_dom_AbstractElement.events method _DOMActivate : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMAttrModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMCharacterDataModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMFocusIn : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMFocusOut : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeInserted : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeInsertedIntoDocument : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeRemoved : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMNodeRemovedFromDocument : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method _DOMSubtreeModified : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method abort : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method blur : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method change : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method click : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method contextmenu : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method dblclick : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method error : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method focus : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keydown : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keypress : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method keyup : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method load : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mousedown : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseenter : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseleave : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mousemove : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseout : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseover : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method mouseup : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method reset : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method resize : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method scroll : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method select : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method submit : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop method unload : (Ext_EventObject.t Js.t -> Dom_html.element Js.t -> _ Js.t -> unit) Js.callback Js.writeonly_prop end class type statics = object inherit Ext_dom_AbstractElement.statics method select : _ Js.t -> bool Js.t Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.meth end let get_static () = Js.Unsafe.variable "Ext.dom.Element" let static = get_static () let select selector unique root = Js.Unsafe.meth_call static (Js.Unsafe.variable "select") [|Js.Unsafe.inject selector; Js.Unsafe.inject unique; Js.Unsafe.inject root; |] let of_configs c = Js.Unsafe.coerce c let to_configs o = Js.Unsafe.coerce o
2315afd77e720e2c92bff62ae5ffb9138a7574e154f2f7a3ce4a131d9c1fa0f5
probprog/anglican
beaver_data.clj
(ns anglib.beaver-data "Beaver data from R") ;; Record field accessors for beaver datasets (def beaver-day #(nth % 0)) (def beaver-time #(nth % 1)) (def beaver-temperature #(nth % 2)) (def beaver-activity #(nth % 3)) (def beaver1 "beaver1 from R datasets" [[346 840 36.33 0] [346 850 36.34 0] [346 900 36.35 0] [346 910 36.42 0] [346 920 36.55 0] [346 930 36.69 0] [346 940 36.71 0] [346 950 36.75 0] [346 1000 36.81 0] [346 1010 36.88 0] [346 1020 36.89 0] [346 1030 36.91 0] [346 1040 36.85 0] [346 1050 36.89 0] [346 1100 36.89 0] [346 1110 36.67 0] [346 1120 36.5 0] [346 1130 36.74 0] [346 1140 36.77 0] [346 1150 36.76 0] [346 1200 36.78 0] [346 1210 36.82 0] [346 1220 36.89 0] [346 1230 36.99 0] [346 1240 36.92 0] [346 1250 36.99 0] [346 1300 36.89 0] [346 1310 36.94 0] [346 1320 36.92 0] [346 1330 36.97 0] [346 1340 36.91 0] [346 1350 36.79 0] [346 1400 36.77 0] [346 1410 36.69 0] [346 1420 36.62 0] [346 1430 36.54 0] [346 1440 36.55 0] [346 1450 36.67 0] [346 1500 36.69 0] [346 1510 36.62 0] [346 1520 36.64 0] [346 1530 36.59 0] [346 1540 36.65 0] [346 1550 36.75 0] [346 1600 36.8 0] [346 1610 36.81 0] [346 1620 36.87 0] [346 1630 36.87 0] [346 1640 36.89 0] [346 1650 36.94 0] [346 1700 36.98 0] [346 1710 36.95 0] [346 1720 37 0] [346 1730 37.07 1] [346 1740 37.05 0] [346 1750 37 0] [346 1800 36.95 0] [346 1810 37 0] [346 1820 36.94 0] [346 1830 36.88 0] [346 1840 36.93 0] [346 1850 36.98 0] [346 1900 36.97 0] [346 1910 36.85 0] [346 1920 36.92 0] [346 1930 36.99 0] [346 1940 37.01 0] [346 1950 37.1 1] [346 2000 37.09 0] [346 2010 37.02 0] [346 2020 36.96 0] [346 2030 36.84 0] [346 2040 36.87 0] [346 2050 36.85 0] [346 2100 36.85 0] [346 2110 36.87 0] [346 2120 36.89 0] [346 2130 36.86 0] [346 2140 36.91 0] [346 2150 37.53 1] [346 2200 37.23 0] [346 2210 37.2 0] [346 2230 37.25 1] [346 2240 37.2 0] [346 2250 37.21 0] [346 2300 37.24 1] [346 2310 37.1 0] [346 2320 37.2 0] [346 2330 37.18 0] [346 2340 36.93 0] [346 2350 36.83 0] [347 0 36.93 0] [347 10 36.83 0] [347 20 36.8 0] [347 30 36.75 0] [347 40 36.71 0] [347 50 36.73 0] [347 100 36.75 0] [347 110 36.72 0] [347 120 36.76 0] [347 130 36.7 0] [347 140 36.82 0] [347 150 36.88 0] [347 200 36.94 0] [347 210 36.79 0] [347 220 36.78 0] [347 230 36.8 0] [347 240 36.82 0] [347 250 36.84 0] [347 300 36.86 0] [347 310 36.88 0] [347 320 36.93 0] [347 330 36.97 0] [347 340 37.15 1]]) (def beaver2 "beaver2 from R datasets" [[307 930 36.58 0] [307 940 36.73 0] [307 950 36.93 0] [307 1000 37.15 0] [307 1010 37.23 0] [307 1020 37.24 0] [307 1030 37.24 0] [307 1040 36.9 0] [307 1050 36.95 0] [307 1100 36.89 0] [307 1110 36.95 0] [307 1120 37 0] [307 1130 36.9 0] [307 1140 36.99 0] [307 1150 36.99 0] [307 1200 37.01 0] [307 1210 37.04 0] [307 1220 37.04 0] [307 1230 37.14 0] [307 1240 37.07 0] [307 1250 36.98 0] [307 1300 37.01 0] [307 1310 36.97 0] [307 1320 36.97 0] [307 1330 37.12 0] [307 1340 37.13 0] [307 1350 37.14 0] [307 1400 37.15 0] [307 1410 37.17 0] [307 1420 37.12 0] [307 1430 37.12 0] [307 1440 37.17 0] [307 1450 37.28 0] [307 1500 37.28 0] [307 1510 37.44 0] [307 1520 37.51 0] [307 1530 37.64 0] [307 1540 37.51 0] [307 1550 37.98 1] [307 1600 38.02 1] [307 1610 38 1] [307 1620 38.24 1] [307 1630 38.1 1] [307 1640 38.24 1] [307 1650 38.11 1] [307 1700 38.02 1] [307 1710 38.11 1] [307 1720 38.01 1] [307 1730 37.91 1] [307 1740 37.96 1] [307 1750 38.03 1] [307 1800 38.17 1] [307 1810 38.19 1] [307 1820 38.18 1] [307 1830 38.15 1] [307 1840 38.04 1] [307 1850 37.96 1] [307 1900 37.84 1] [307 1910 37.83 1] [307 1920 37.84 1] [307 1930 37.74 1] [307 1940 37.76 1] [307 1950 37.76 1] [307 2000 37.64 1] [307 2010 37.63 1] [307 2020 38.06 1] [307 2030 38.19 1] [307 2040 38.35 1] [307 2050 38.25 1] [307 2100 37.86 1] [307 2110 37.95 1] [307 2120 37.95 1] [307 2130 37.76 1] [307 2140 37.6 1] [307 2150 37.89 1] [307 2200 37.86 1] [307 2210 37.71 1] [307 2220 37.78 1] [307 2230 37.82 1] [307 2240 37.76 1] [307 2250 37.81 1] [307 2300 37.84 1] [307 2310 38.01 1] [307 2320 38.1 1] [307 2330 38.15 1] [307 2340 37.92 1] [307 2350 37.64 1] [308 0 37.7 1] [308 10 37.46 1] [308 20 37.41 1] [308 30 37.46 1] [308 40 37.56 1] [308 50 37.55 1] [308 100 37.75 1] [308 110 37.76 1] [308 120 37.73 1] [308 130 37.77 1] [308 140 38.01 1] [308 150 38.04 1] [308 200 38.07 1]])
null
https://raw.githubusercontent.com/probprog/anglican/ab6111d7fa8f68f42ea046feab928ca3eedde1d7/src/anglib/beaver_data.clj
clojure
Record field accessors for beaver datasets
(ns anglib.beaver-data "Beaver data from R") (def beaver-day #(nth % 0)) (def beaver-time #(nth % 1)) (def beaver-temperature #(nth % 2)) (def beaver-activity #(nth % 3)) (def beaver1 "beaver1 from R datasets" [[346 840 36.33 0] [346 850 36.34 0] [346 900 36.35 0] [346 910 36.42 0] [346 920 36.55 0] [346 930 36.69 0] [346 940 36.71 0] [346 950 36.75 0] [346 1000 36.81 0] [346 1010 36.88 0] [346 1020 36.89 0] [346 1030 36.91 0] [346 1040 36.85 0] [346 1050 36.89 0] [346 1100 36.89 0] [346 1110 36.67 0] [346 1120 36.5 0] [346 1130 36.74 0] [346 1140 36.77 0] [346 1150 36.76 0] [346 1200 36.78 0] [346 1210 36.82 0] [346 1220 36.89 0] [346 1230 36.99 0] [346 1240 36.92 0] [346 1250 36.99 0] [346 1300 36.89 0] [346 1310 36.94 0] [346 1320 36.92 0] [346 1330 36.97 0] [346 1340 36.91 0] [346 1350 36.79 0] [346 1400 36.77 0] [346 1410 36.69 0] [346 1420 36.62 0] [346 1430 36.54 0] [346 1440 36.55 0] [346 1450 36.67 0] [346 1500 36.69 0] [346 1510 36.62 0] [346 1520 36.64 0] [346 1530 36.59 0] [346 1540 36.65 0] [346 1550 36.75 0] [346 1600 36.8 0] [346 1610 36.81 0] [346 1620 36.87 0] [346 1630 36.87 0] [346 1640 36.89 0] [346 1650 36.94 0] [346 1700 36.98 0] [346 1710 36.95 0] [346 1720 37 0] [346 1730 37.07 1] [346 1740 37.05 0] [346 1750 37 0] [346 1800 36.95 0] [346 1810 37 0] [346 1820 36.94 0] [346 1830 36.88 0] [346 1840 36.93 0] [346 1850 36.98 0] [346 1900 36.97 0] [346 1910 36.85 0] [346 1920 36.92 0] [346 1930 36.99 0] [346 1940 37.01 0] [346 1950 37.1 1] [346 2000 37.09 0] [346 2010 37.02 0] [346 2020 36.96 0] [346 2030 36.84 0] [346 2040 36.87 0] [346 2050 36.85 0] [346 2100 36.85 0] [346 2110 36.87 0] [346 2120 36.89 0] [346 2130 36.86 0] [346 2140 36.91 0] [346 2150 37.53 1] [346 2200 37.23 0] [346 2210 37.2 0] [346 2230 37.25 1] [346 2240 37.2 0] [346 2250 37.21 0] [346 2300 37.24 1] [346 2310 37.1 0] [346 2320 37.2 0] [346 2330 37.18 0] [346 2340 36.93 0] [346 2350 36.83 0] [347 0 36.93 0] [347 10 36.83 0] [347 20 36.8 0] [347 30 36.75 0] [347 40 36.71 0] [347 50 36.73 0] [347 100 36.75 0] [347 110 36.72 0] [347 120 36.76 0] [347 130 36.7 0] [347 140 36.82 0] [347 150 36.88 0] [347 200 36.94 0] [347 210 36.79 0] [347 220 36.78 0] [347 230 36.8 0] [347 240 36.82 0] [347 250 36.84 0] [347 300 36.86 0] [347 310 36.88 0] [347 320 36.93 0] [347 330 36.97 0] [347 340 37.15 1]]) (def beaver2 "beaver2 from R datasets" [[307 930 36.58 0] [307 940 36.73 0] [307 950 36.93 0] [307 1000 37.15 0] [307 1010 37.23 0] [307 1020 37.24 0] [307 1030 37.24 0] [307 1040 36.9 0] [307 1050 36.95 0] [307 1100 36.89 0] [307 1110 36.95 0] [307 1120 37 0] [307 1130 36.9 0] [307 1140 36.99 0] [307 1150 36.99 0] [307 1200 37.01 0] [307 1210 37.04 0] [307 1220 37.04 0] [307 1230 37.14 0] [307 1240 37.07 0] [307 1250 36.98 0] [307 1300 37.01 0] [307 1310 36.97 0] [307 1320 36.97 0] [307 1330 37.12 0] [307 1340 37.13 0] [307 1350 37.14 0] [307 1400 37.15 0] [307 1410 37.17 0] [307 1420 37.12 0] [307 1430 37.12 0] [307 1440 37.17 0] [307 1450 37.28 0] [307 1500 37.28 0] [307 1510 37.44 0] [307 1520 37.51 0] [307 1530 37.64 0] [307 1540 37.51 0] [307 1550 37.98 1] [307 1600 38.02 1] [307 1610 38 1] [307 1620 38.24 1] [307 1630 38.1 1] [307 1640 38.24 1] [307 1650 38.11 1] [307 1700 38.02 1] [307 1710 38.11 1] [307 1720 38.01 1] [307 1730 37.91 1] [307 1740 37.96 1] [307 1750 38.03 1] [307 1800 38.17 1] [307 1810 38.19 1] [307 1820 38.18 1] [307 1830 38.15 1] [307 1840 38.04 1] [307 1850 37.96 1] [307 1900 37.84 1] [307 1910 37.83 1] [307 1920 37.84 1] [307 1930 37.74 1] [307 1940 37.76 1] [307 1950 37.76 1] [307 2000 37.64 1] [307 2010 37.63 1] [307 2020 38.06 1] [307 2030 38.19 1] [307 2040 38.35 1] [307 2050 38.25 1] [307 2100 37.86 1] [307 2110 37.95 1] [307 2120 37.95 1] [307 2130 37.76 1] [307 2140 37.6 1] [307 2150 37.89 1] [307 2200 37.86 1] [307 2210 37.71 1] [307 2220 37.78 1] [307 2230 37.82 1] [307 2240 37.76 1] [307 2250 37.81 1] [307 2300 37.84 1] [307 2310 38.01 1] [307 2320 38.1 1] [307 2330 38.15 1] [307 2340 37.92 1] [307 2350 37.64 1] [308 0 37.7 1] [308 10 37.46 1] [308 20 37.41 1] [308 30 37.46 1] [308 40 37.56 1] [308 50 37.55 1] [308 100 37.75 1] [308 110 37.76 1] [308 120 37.73 1] [308 130 37.77 1] [308 140 38.01 1] [308 150 38.04 1] [308 200 38.07 1]])
2035f3820dbb76c70b6aa0651a7348650ce0635a25da96a109b483a3adc85ad5
avsm/mirage-duniverse
topkg_install.ml
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) open Topkg_result type move_scheme = { field : [ `Test of bool * Topkg_fpath.t option * Topkg_cmd.t | Topkg_opam.Install.field ]; auto_bin : bool; force : bool; built : bool; exts : Topkg_fexts.t; src : string; dst : string; This a bit hacky , only used by higher - level installs OCamlbuild higher-level installs *) } type t = move_scheme list let nothing = [] let flatten ls = (* We don't care about order *) let rec push acc = function v :: vs -> push (v :: acc) vs | [] -> acc in let rec loop acc = function | l :: ls -> loop (push acc l) ls | [] -> acc in loop [] ls let split_ext s = match Topkg_string.cut ~rev:true s ~sep:'.' with | None -> s, `Ext "" | Some (name, ext) -> name, `Ext (Topkg_string.strf ".%s" ext) let bin_drop_exts native = if native then [] else Topkg_fexts.ext ".native" let lib_drop_exts native native_dynlink = if native then (if native_dynlink then [] else Topkg_fexts.ext ".cmxs") else Topkg_fexts.(c_library @ exts [".cmx"; ".cmxa"; ".cmxs"]) let to_build ?header c os i = let bdir = Topkg_conf.build_dir c in let debugger_support = Topkg_conf.debugger_support c in let build_tests = Topkg_conf.build_tests c in let ocaml_conf = Topkg_conf.OCaml.v c os in let native = Topkg_conf.OCaml.native ocaml_conf in let native_dylink = Topkg_conf.OCaml.native_dynlink ocaml_conf in let ext_to_string = Topkg_fexts.ext_to_string ocaml_conf in let file_to_str (n, ext) = Topkg_string.strf "%s%s" n (ext_to_string ext) in let maybe_build = [ ".cmti"; ".cmt" ] in let bin_drops = List.map ext_to_string (bin_drop_exts native) in let lib_drops = List.map ext_to_string (lib_drop_exts native native_dylink) in let add acc m = if m.debugger_support && not debugger_support then acc else let mv (targets, moves, tests as acc) src dst = let src = file_to_str src in let drop = not m.force && match m.field with | `Bin -> List.exists (Filename.check_suffix src) bin_drops | `Lib -> List.exists (Filename.check_suffix src) lib_drops | _ -> false in if drop then (targets, moves, tests) else let dst = file_to_str dst in let maybe = List.exists (Filename.check_suffix src) maybe_build in let targets = if m.built && not maybe then src :: targets else targets in let src = if m.built then Topkg_string.strf "%s/%s" bdir src else src in match m.field with | `Test (run, dir, args) -> if not build_tests then acc else let test = Topkg_test.v src ~args ~run ~dir in (targets, moves, test :: tests) | #Topkg_opam.Install.field as field -> let move = (field, Topkg_opam.Install.move ~maybe src ~dst) in (targets, move :: moves, tests) in let src, dst = if not m.auto_bin then m.src, m.dst else ((if native then m.src ^ ".native" else m.src ^ ".byte"), m.dst ^ (ext_to_string `Exe)) in if m.exts = [] then mv acc (split_ext src) (split_ext dst) else let expand acc ext = mv acc (src, ext) (dst, ext) in List.fold_left expand acc m.exts in let targets, moves, tests = List.fold_left add ([], [], []) (flatten i) in let tests = if build_tests then Some tests else None in targets, ((`Header header), moves), tests (* Install fields *) type field = ?force:bool -> ?built:bool -> ?cond:bool -> ?exts:Topkg_fexts.t -> ?dst:string -> string -> t let _field field ?(debugger_support = false) ?(auto = true) ?(force = false) ?(built = true) ?(cond = true) ?(exts = []) ?dst src = if not cond then [] else let dst = match dst with | None -> Topkg_fpath.basename src | Some dst -> if Topkg_fpath.is_file_path dst then dst else dst ^ (Topkg_fpath.basename src) in [{ field; auto_bin = auto; force; built; exts; src; dst; debugger_support; }] let field field = _field ~debugger_support:false ~auto:false field let field_exec field ?auto ?force ?built ?cond ?exts ?dst src = _field field ~debugger_support:false ?auto ?force ?built ?cond ?exts ?dst src let bin = field_exec `Bin let doc = field `Doc let etc = field `Etc let lib = field `Lib let lib_root = field `Lib_root let libexec = field_exec `Libexec let libexec_root = field_exec `Libexec_root let man = field `Man let misc = field `Misc let sbin = field_exec `Sbin let share = field `Share let share_root = field `Share_root let stublibs = field `Stublibs let toplevel = field `Toplevel let unknown name = field (`Unknown name) let test ?(run = true) ?dir ?(args = Topkg_cmd.empty) = field_exec (`Test (run, dir, args)) higher - level installs list of module name and path ( for dir / Mod ) let lines = Topkg_string.cuts ~sep:'\n' contents in let add_mod acc l = let path = String.trim @@ match Topkg_string.cut ~sep:'#' l with | None -> l | Some (p, _ (* comment *)) -> p in if path = "" then acc else let mod_name = Topkg_string.capitalize @@ Topkg_fpath.basename path in (mod_name, path) :: acc in List.fold_left add_mod [] lines let field_of_field field = (* hack, recover a field from a field function... *) match (List.hd (field "")).field with | `Test (run, dir, args) -> assert false | #Topkg_opam.Install.field as field -> field let mllib ?(field = lib) ?(cond = true) ?(cma = true) ?(cmxa = true) ?(cmxs = true) ?api ?dst_dir mllib = if not cond then [] else let debugger_support_field = _field ~debugger_support:true ~auto:false (field_of_field field) in let lib_dir = Topkg_fpath.dirname mllib in let lib_base = Topkg_fpath.rem_ext mllib in let dst f = match dst_dir with | None -> None | Some dir -> Some (Topkg_fpath.append dir (Topkg_fpath.basename f)) in let api mllib_content = let mod_names = List.map fst mllib_content in match api with | None -> mod_names (* all the .mllib modules if unspecified *) | Some api -> let in_mllib i = List.mem (Topkg_string.capitalize i) mod_names in let api, orphans = List.partition in_mllib api in let warn o = Topkg_log.warn (fun m -> m "mllib %s: unknown interface %s" mllib o) in List.iter warn orphans; api in let library = let add_if cond v vs = if cond then v :: vs else vs in let exts = add_if cma (`Ext ".cma") @@ add_if cmxa (`Ext ".cmxa") @@ add_if cmxs (`Ext ".cmxs") @@ add_if (cmxa || cmxs) `Lib [] in field ?dst:(dst lib_base) ~exts lib_base in let add_mods acc mllib_content = let api = api mllib_content in let add_mod acc (m, path) = let fname = Topkg_string.uncapitalize (Topkg_fpath.basename path) in let fpath = match Topkg_fpath.dirname path with | "." -> Topkg_fpath.append lib_dir fname | parent -> Topkg_fpath.(append lib_dir (append parent fname)) in let dst = dst fname in let exts, debugger_support_exts = match List.mem m api with | true -> Topkg_fexts.api, Topkg_fexts.exts [".ml"; ".cmt"] | false -> Topkg_fexts.cmx, Topkg_fexts.exts [".ml"; ".cmi"; ".cmt"; ] in field ?dst ~exts fpath :: debugger_support_field ?dst ~exts:debugger_support_exts fpath :: acc in List.fold_left add_mod acc mllib_content in begin Topkg_os.File.read mllib >>= fun contents -> Ok (parse_mllib contents) >>= fun mllib_content -> Ok (flatten @@ add_mods [library] mllib_content) end |> Topkg_log.on_error_msg ~use:(fun () -> []) let parse_clib contents = let lines = Topkg_string.cuts ~sep:'\n' contents in let add_obj_path acc l = let path = String.trim @@ match Topkg_string.cut ~sep:'#' l with | None -> l | Some (p, _ (* comment *)) -> p in if path = "" then acc else path :: acc in List.fold_left add_obj_path [] lines let clib ?(dllfield = stublibs) ?(libfield = lib) ?(cond = true) ?lib_dst_dir clib = if not cond then [] else let debugger_support_field = _field ~debugger_support:true ~auto:false (field_of_field lib) in let lib_dir = Topkg_fpath.dirname clib in let lib_base = let base = Topkg_fpath.(basename @@ rem_ext clib) in if Topkg_string.is_prefix ~affix:"lib" base then Ok (Topkg_string.with_index_range ~first:3 base) else R.error_msgf "%s: OCamlbuild .clib file must start with 'lib'" clib in let lib_dst f = match lib_dst_dir with | None -> None | Some dir -> Some (Topkg_fpath.append dir (Topkg_fpath.basename f)) in let add_debugger_support cobjs = let add_cobj acc path = let fname = Topkg_fpath.(rem_ext @@ basename path) in let fpath = match Topkg_fpath.dirname path with | "." -> Topkg_fpath.append lib_dir fname | parent -> Topkg_fpath.(append lib_dir (append parent fname)) in let dst = lib_dst fname in debugger_support_field ?dst ~exts:(Topkg_fexts.ext ".c") fpath :: acc in List.fold_left add_cobj [] cobjs in begin lib_base >>= fun lib_base -> Topkg_os.File.read clib >>= fun contents -> let cobjs = parse_clib contents in let lib = Topkg_fpath.append lib_dir ("lib" ^ lib_base) in let lib = libfield ~exts:Topkg_fexts.c_library lib ?dst:(lib_dst lib) in let dll = Topkg_fpath.append lib_dir ("dll" ^ lib_base) in let dll = dllfield ~exts:Topkg_fexts.c_dll_library dll in Ok (flatten @@ lib :: dll :: add_debugger_support cobjs) end |> Topkg_log.on_error_msg ~use:(fun () -> []) (* Dummy codec *) let codec : t Topkg_codec.t = (* we don't care *) let fields = (fun _ -> ()), (fun () -> []) in Topkg_codec.version 0 @@ Topkg_codec.(view ~kind:"install" fields unit) --------------------------------------------------------------------------- Copyright ( c ) 2016 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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) 2016 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/topkg/src/topkg_install.ml
ocaml
We don't care about order Install fields comment hack, recover a field from a field function... all the .mllib modules if unspecified comment Dummy codec we don't care
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) open Topkg_result type move_scheme = { field : [ `Test of bool * Topkg_fpath.t option * Topkg_cmd.t | Topkg_opam.Install.field ]; auto_bin : bool; force : bool; built : bool; exts : Topkg_fexts.t; src : string; dst : string; This a bit hacky , only used by higher - level installs OCamlbuild higher-level installs *) } type t = move_scheme list let nothing = [] let rec push acc = function v :: vs -> push (v :: acc) vs | [] -> acc in let rec loop acc = function | l :: ls -> loop (push acc l) ls | [] -> acc in loop [] ls let split_ext s = match Topkg_string.cut ~rev:true s ~sep:'.' with | None -> s, `Ext "" | Some (name, ext) -> name, `Ext (Topkg_string.strf ".%s" ext) let bin_drop_exts native = if native then [] else Topkg_fexts.ext ".native" let lib_drop_exts native native_dynlink = if native then (if native_dynlink then [] else Topkg_fexts.ext ".cmxs") else Topkg_fexts.(c_library @ exts [".cmx"; ".cmxa"; ".cmxs"]) let to_build ?header c os i = let bdir = Topkg_conf.build_dir c in let debugger_support = Topkg_conf.debugger_support c in let build_tests = Topkg_conf.build_tests c in let ocaml_conf = Topkg_conf.OCaml.v c os in let native = Topkg_conf.OCaml.native ocaml_conf in let native_dylink = Topkg_conf.OCaml.native_dynlink ocaml_conf in let ext_to_string = Topkg_fexts.ext_to_string ocaml_conf in let file_to_str (n, ext) = Topkg_string.strf "%s%s" n (ext_to_string ext) in let maybe_build = [ ".cmti"; ".cmt" ] in let bin_drops = List.map ext_to_string (bin_drop_exts native) in let lib_drops = List.map ext_to_string (lib_drop_exts native native_dylink) in let add acc m = if m.debugger_support && not debugger_support then acc else let mv (targets, moves, tests as acc) src dst = let src = file_to_str src in let drop = not m.force && match m.field with | `Bin -> List.exists (Filename.check_suffix src) bin_drops | `Lib -> List.exists (Filename.check_suffix src) lib_drops | _ -> false in if drop then (targets, moves, tests) else let dst = file_to_str dst in let maybe = List.exists (Filename.check_suffix src) maybe_build in let targets = if m.built && not maybe then src :: targets else targets in let src = if m.built then Topkg_string.strf "%s/%s" bdir src else src in match m.field with | `Test (run, dir, args) -> if not build_tests then acc else let test = Topkg_test.v src ~args ~run ~dir in (targets, moves, test :: tests) | #Topkg_opam.Install.field as field -> let move = (field, Topkg_opam.Install.move ~maybe src ~dst) in (targets, move :: moves, tests) in let src, dst = if not m.auto_bin then m.src, m.dst else ((if native then m.src ^ ".native" else m.src ^ ".byte"), m.dst ^ (ext_to_string `Exe)) in if m.exts = [] then mv acc (split_ext src) (split_ext dst) else let expand acc ext = mv acc (src, ext) (dst, ext) in List.fold_left expand acc m.exts in let targets, moves, tests = List.fold_left add ([], [], []) (flatten i) in let tests = if build_tests then Some tests else None in targets, ((`Header header), moves), tests type field = ?force:bool -> ?built:bool -> ?cond:bool -> ?exts:Topkg_fexts.t -> ?dst:string -> string -> t let _field field ?(debugger_support = false) ?(auto = true) ?(force = false) ?(built = true) ?(cond = true) ?(exts = []) ?dst src = if not cond then [] else let dst = match dst with | None -> Topkg_fpath.basename src | Some dst -> if Topkg_fpath.is_file_path dst then dst else dst ^ (Topkg_fpath.basename src) in [{ field; auto_bin = auto; force; built; exts; src; dst; debugger_support; }] let field field = _field ~debugger_support:false ~auto:false field let field_exec field ?auto ?force ?built ?cond ?exts ?dst src = _field field ~debugger_support:false ?auto ?force ?built ?cond ?exts ?dst src let bin = field_exec `Bin let doc = field `Doc let etc = field `Etc let lib = field `Lib let lib_root = field `Lib_root let libexec = field_exec `Libexec let libexec_root = field_exec `Libexec_root let man = field `Man let misc = field `Misc let sbin = field_exec `Sbin let share = field `Share let share_root = field `Share_root let stublibs = field `Stublibs let toplevel = field `Toplevel let unknown name = field (`Unknown name) let test ?(run = true) ?dir ?(args = Topkg_cmd.empty) = field_exec (`Test (run, dir, args)) higher - level installs list of module name and path ( for dir / Mod ) let lines = Topkg_string.cuts ~sep:'\n' contents in let add_mod acc l = let path = String.trim @@ match Topkg_string.cut ~sep:'#' l with | None -> l in if path = "" then acc else let mod_name = Topkg_string.capitalize @@ Topkg_fpath.basename path in (mod_name, path) :: acc in List.fold_left add_mod [] lines match (List.hd (field "")).field with | `Test (run, dir, args) -> assert false | #Topkg_opam.Install.field as field -> field let mllib ?(field = lib) ?(cond = true) ?(cma = true) ?(cmxa = true) ?(cmxs = true) ?api ?dst_dir mllib = if not cond then [] else let debugger_support_field = _field ~debugger_support:true ~auto:false (field_of_field field) in let lib_dir = Topkg_fpath.dirname mllib in let lib_base = Topkg_fpath.rem_ext mllib in let dst f = match dst_dir with | None -> None | Some dir -> Some (Topkg_fpath.append dir (Topkg_fpath.basename f)) in let api mllib_content = let mod_names = List.map fst mllib_content in match api with | Some api -> let in_mllib i = List.mem (Topkg_string.capitalize i) mod_names in let api, orphans = List.partition in_mllib api in let warn o = Topkg_log.warn (fun m -> m "mllib %s: unknown interface %s" mllib o) in List.iter warn orphans; api in let library = let add_if cond v vs = if cond then v :: vs else vs in let exts = add_if cma (`Ext ".cma") @@ add_if cmxa (`Ext ".cmxa") @@ add_if cmxs (`Ext ".cmxs") @@ add_if (cmxa || cmxs) `Lib [] in field ?dst:(dst lib_base) ~exts lib_base in let add_mods acc mllib_content = let api = api mllib_content in let add_mod acc (m, path) = let fname = Topkg_string.uncapitalize (Topkg_fpath.basename path) in let fpath = match Topkg_fpath.dirname path with | "." -> Topkg_fpath.append lib_dir fname | parent -> Topkg_fpath.(append lib_dir (append parent fname)) in let dst = dst fname in let exts, debugger_support_exts = match List.mem m api with | true -> Topkg_fexts.api, Topkg_fexts.exts [".ml"; ".cmt"] | false -> Topkg_fexts.cmx, Topkg_fexts.exts [".ml"; ".cmi"; ".cmt"; ] in field ?dst ~exts fpath :: debugger_support_field ?dst ~exts:debugger_support_exts fpath :: acc in List.fold_left add_mod acc mllib_content in begin Topkg_os.File.read mllib >>= fun contents -> Ok (parse_mllib contents) >>= fun mllib_content -> Ok (flatten @@ add_mods [library] mllib_content) end |> Topkg_log.on_error_msg ~use:(fun () -> []) let parse_clib contents = let lines = Topkg_string.cuts ~sep:'\n' contents in let add_obj_path acc l = let path = String.trim @@ match Topkg_string.cut ~sep:'#' l with | None -> l in if path = "" then acc else path :: acc in List.fold_left add_obj_path [] lines let clib ?(dllfield = stublibs) ?(libfield = lib) ?(cond = true) ?lib_dst_dir clib = if not cond then [] else let debugger_support_field = _field ~debugger_support:true ~auto:false (field_of_field lib) in let lib_dir = Topkg_fpath.dirname clib in let lib_base = let base = Topkg_fpath.(basename @@ rem_ext clib) in if Topkg_string.is_prefix ~affix:"lib" base then Ok (Topkg_string.with_index_range ~first:3 base) else R.error_msgf "%s: OCamlbuild .clib file must start with 'lib'" clib in let lib_dst f = match lib_dst_dir with | None -> None | Some dir -> Some (Topkg_fpath.append dir (Topkg_fpath.basename f)) in let add_debugger_support cobjs = let add_cobj acc path = let fname = Topkg_fpath.(rem_ext @@ basename path) in let fpath = match Topkg_fpath.dirname path with | "." -> Topkg_fpath.append lib_dir fname | parent -> Topkg_fpath.(append lib_dir (append parent fname)) in let dst = lib_dst fname in debugger_support_field ?dst ~exts:(Topkg_fexts.ext ".c") fpath :: acc in List.fold_left add_cobj [] cobjs in begin lib_base >>= fun lib_base -> Topkg_os.File.read clib >>= fun contents -> let cobjs = parse_clib contents in let lib = Topkg_fpath.append lib_dir ("lib" ^ lib_base) in let lib = libfield ~exts:Topkg_fexts.c_library lib ?dst:(lib_dst lib) in let dll = Topkg_fpath.append lib_dir ("dll" ^ lib_base) in let dll = dllfield ~exts:Topkg_fexts.c_dll_library dll in Ok (flatten @@ lib :: dll :: add_debugger_support cobjs) end |> Topkg_log.on_error_msg ~use:(fun () -> []) let fields = (fun _ -> ()), (fun () -> []) in Topkg_codec.version 0 @@ Topkg_codec.(view ~kind:"install" fields unit) --------------------------------------------------------------------------- Copyright ( c ) 2016 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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) 2016 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
30da9b68edb7bf78186730d15162f37f7efc1256185c64dd14ac61a570f0ad7b
rowangithub/DOrder
recHanoi02.ml
* recHanoi.c * * Created on : 17.07.2013 * Author : * recHanoi.c * * Created on: 17.07.2013 * Author: Stefan Wissert *) (* * This function returns the optimal amount of steps, * needed to solve the problem for n-disks *) let rec hanoi n = let result = if (n = 1) then 1 else 2 * (hanoi (n-1)) + 1 in result let main () = let n = Random.int 32 in if (n < 1 || n > 31) then 0 else let result = hanoi n in (assert (result >= 0); result) let _ = main ()
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/recursive/recHanoi02.ml
ocaml
* This function returns the optimal amount of steps, * needed to solve the problem for n-disks
* recHanoi.c * * Created on : 17.07.2013 * Author : * recHanoi.c * * Created on: 17.07.2013 * Author: Stefan Wissert *) let rec hanoi n = let result = if (n = 1) then 1 else 2 * (hanoi (n-1)) + 1 in result let main () = let n = Random.int 32 in if (n < 1 || n > 31) then 0 else let result = hanoi n in (assert (result >= 0); result) let _ = main ()
bcdc5e4b248de3fd733430d5ce45dfafa68a7221811a288959efcf7765b3732e
oliyh/superlifter
api.cljc
(ns superlifter.api (:require [superlifter.core :as core] [promesa.core :as prom] #?(:clj [urania.core :as u]))) (defn unwrap ([p] (unwrap identity p)) ([f p] (if (prom/promise? p) (prom/then p f) (prom/resolved (f p))))) #?(:clj (defmacro def-fetcher [sym bindings do-fetch-fn] `(defrecord ~sym ~bindings u/DataSource (-identity [this#] (:id this#)) (-fetch [this# env#] (unwrap (~do-fetch-fn this# env#)))))) #?(:clj (defmacro def-superfetcher [sym bindings do-fetch-fn] `(defrecord ~sym ~bindings u/DataSource (-identity [this#] (:id this#)) (-fetch [this# env#] (unwrap first (~do-fetch-fn [this#] env#))) u/BatchedSource (-fetch-multi [muse# muses# env#] (let [muses# (cons muse# muses#)] (unwrap (fn [responses#] (zipmap (map u/-identity muses#) responses#)) (~do-fetch-fn muses# env#))))))) (def ^:dynamic *instance*) #?(:clj (defmacro with-superlifter [instance & body] `(binding [*instance* ~instance] ~@body))) (defn enqueue! "Enqueues a muse describing work to be done and returns a promise which will be delivered with the result of the work. The muses in the queue will all be fetched together when the trigger condition is met." {:arglists '([context muse] [context bucket-id muse])} [& args] (apply core/enqueue! *instance* args)) (defn fetch! "Performs a fetch of all muses in the queue for the given bucket, or the default bucket if not specified" {:arglists '([context] [context bucket-id])} [& args] (apply core/fetch! *instance* args)) (defn fetch-all! "Performs a fetch of all muses in the queues of all buckets" {:arglists '([context])} [& args] (apply core/fetch-all! *instance* args)) (defn add-bucket! [p id opts-fn] (unwrap (bound-fn [result] (core/add-bucket! *instance* id (opts-fn result)) result) p)) (defn update-trigger! [p bucket-id trigger-kind opts-fn] (unwrap (bound-fn [result] (core/update-trigger! *instance* bucket-id trigger-kind #(opts-fn % result)) result) p)) (def start! core/start!) (def stop! core/stop!)
null
https://raw.githubusercontent.com/oliyh/superlifter/d0baf9538f1dac712415323a2f2a6578c181bd97/src/superlifter/api.cljc
clojure
(ns superlifter.api (:require [superlifter.core :as core] [promesa.core :as prom] #?(:clj [urania.core :as u]))) (defn unwrap ([p] (unwrap identity p)) ([f p] (if (prom/promise? p) (prom/then p f) (prom/resolved (f p))))) #?(:clj (defmacro def-fetcher [sym bindings do-fetch-fn] `(defrecord ~sym ~bindings u/DataSource (-identity [this#] (:id this#)) (-fetch [this# env#] (unwrap (~do-fetch-fn this# env#)))))) #?(:clj (defmacro def-superfetcher [sym bindings do-fetch-fn] `(defrecord ~sym ~bindings u/DataSource (-identity [this#] (:id this#)) (-fetch [this# env#] (unwrap first (~do-fetch-fn [this#] env#))) u/BatchedSource (-fetch-multi [muse# muses# env#] (let [muses# (cons muse# muses#)] (unwrap (fn [responses#] (zipmap (map u/-identity muses#) responses#)) (~do-fetch-fn muses# env#))))))) (def ^:dynamic *instance*) #?(:clj (defmacro with-superlifter [instance & body] `(binding [*instance* ~instance] ~@body))) (defn enqueue! "Enqueues a muse describing work to be done and returns a promise which will be delivered with the result of the work. The muses in the queue will all be fetched together when the trigger condition is met." {:arglists '([context muse] [context bucket-id muse])} [& args] (apply core/enqueue! *instance* args)) (defn fetch! "Performs a fetch of all muses in the queue for the given bucket, or the default bucket if not specified" {:arglists '([context] [context bucket-id])} [& args] (apply core/fetch! *instance* args)) (defn fetch-all! "Performs a fetch of all muses in the queues of all buckets" {:arglists '([context])} [& args] (apply core/fetch-all! *instance* args)) (defn add-bucket! [p id opts-fn] (unwrap (bound-fn [result] (core/add-bucket! *instance* id (opts-fn result)) result) p)) (defn update-trigger! [p bucket-id trigger-kind opts-fn] (unwrap (bound-fn [result] (core/update-trigger! *instance* bucket-id trigger-kind #(opts-fn % result)) result) p)) (def start! core/start!) (def stop! core/stop!)
5331d04b90388918bcd79ee49b654ded17dcef1fe9b32dc00a1447b13c042ea9
input-output-hk/project-icarus-importer
BlockIndex.hs
-- | Operations with block index db. module Pos.DB.BlockIndex ( getHeader , getTipHeader , putHeadersIndex , deleteHeaderIndex ) where import Universum import Data.ByteArray (convert) import qualified Database.RocksDB as Rocks import Pos.Core (BlockHeader, HeaderHash, headerHash) import Pos.DB.Class (DBTag (BlockIndexDB), MonadBlockDBRead, MonadDB (..)) import Pos.DB.Functions (dbGetBi, dbSerializeValue) import Pos.DB.GState.Common (getTipSomething) | Returns header of block that was requested from Block DB . getHeader :: (MonadBlockDBRead m) => HeaderHash -> m (Maybe BlockHeader) getHeader = dbGetBi BlockIndexDB . blockIndexKey -- | Get 'BlockHeader' corresponding to tip. getTipHeader :: MonadBlockDBRead m => m BlockHeader getTipHeader = getTipSomething "header" getHeader -- | Writes batch of headers into the block index db. putHeadersIndex :: (MonadDB m) => [BlockHeader] -> m () putHeadersIndex = dbWriteBatch BlockIndexDB . map (\h -> Rocks.Put (blockIndexKey $ headerHash h) (dbSerializeValue h)) -- | Deletes header from the index db. deleteHeaderIndex :: MonadDB m => HeaderHash -> m () deleteHeaderIndex = dbDelete BlockIndexDB . blockIndexKey ---------------------------------------------------------------------------- -- Keys ---------------------------------------------------------------------------- blockIndexKey :: HeaderHash -> ByteString blockIndexKey h = "b" <> convert h
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/db/Pos/DB/BlockIndex.hs
haskell
| Operations with block index db. | Get 'BlockHeader' corresponding to tip. | Writes batch of headers into the block index db. | Deletes header from the index db. -------------------------------------------------------------------------- Keys --------------------------------------------------------------------------
module Pos.DB.BlockIndex ( getHeader , getTipHeader , putHeadersIndex , deleteHeaderIndex ) where import Universum import Data.ByteArray (convert) import qualified Database.RocksDB as Rocks import Pos.Core (BlockHeader, HeaderHash, headerHash) import Pos.DB.Class (DBTag (BlockIndexDB), MonadBlockDBRead, MonadDB (..)) import Pos.DB.Functions (dbGetBi, dbSerializeValue) import Pos.DB.GState.Common (getTipSomething) | Returns header of block that was requested from Block DB . getHeader :: (MonadBlockDBRead m) => HeaderHash -> m (Maybe BlockHeader) getHeader = dbGetBi BlockIndexDB . blockIndexKey getTipHeader :: MonadBlockDBRead m => m BlockHeader getTipHeader = getTipSomething "header" getHeader putHeadersIndex :: (MonadDB m) => [BlockHeader] -> m () putHeadersIndex = dbWriteBatch BlockIndexDB . map (\h -> Rocks.Put (blockIndexKey $ headerHash h) (dbSerializeValue h)) deleteHeaderIndex :: MonadDB m => HeaderHash -> m () deleteHeaderIndex = dbDelete BlockIndexDB . blockIndexKey blockIndexKey :: HeaderHash -> ByteString blockIndexKey h = "b" <> convert h
b535366fd7bfa8f7aad045a81a6812ef4c775dd6844beaa8c114e5fd2de44be5
futurice/clojure-workshop
17_runtime_polymorphism.clj
(ns koans.17-runtime-polymorphism (:require [koan-engine.core :refer :all])) (defn hello ([] "Hello World!") ([a] (str "Hello, you silly " a ".")) ([a & more] (str "Hello to this group: " (apply str (interpose ", " (cons a more))) "!"))) (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] __) (defmethod diet :carnivore [a] __) (defmethod diet :default [a] __) (meditations ;; "Some functions can be used in different ways - with no arguments" ;; (= __ (hello)) " With one argument " ;; (= __ (hello "world")) ;; "Or with many arguments" ;; (= __ ( hello " " " " " " ) ) ;; "Multimethods allow more complex dispatching" (= " eats veggies . " ( diet { : species " deer " : name " " : age 1 : eater : herbivore } ) ) ;; "Animals have different names" (= " eats veggies . " ( diet { : species " rabbit " : name " " : age 1 : eater : herbivore } ) ) ;; "Different methods are used depending on the dispatch function result" (= " eats animals . " ( diet { : species " lion " : name " " : age 1 : eater : carnivore } ) ) ;; "You may use a default method when no others match" (= " I do n't know what eats . " ( diet { : name " " } ) ) )
null
https://raw.githubusercontent.com/futurice/clojure-workshop/c1e64a03e1115289898838d4f19f727bc51e2b34/materials/section-1/src/koans/17_runtime_polymorphism.clj
clojure
"Some functions can be used in different ways - with no arguments" (= __ (hello)) (= __ (hello "world")) "Or with many arguments" (= __ "Multimethods allow more complex dispatching" "Animals have different names" "Different methods are used depending on the dispatch function result" "You may use a default method when no others match"
(ns koans.17-runtime-polymorphism (:require [koan-engine.core :refer :all])) (defn hello ([] "Hello World!") ([a] (str "Hello, you silly " a ".")) ([a & more] (str "Hello to this group: " (apply str (interpose ", " (cons a more))) "!"))) (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] __) (defmethod diet :carnivore [a] __) (defmethod diet :default [a] __) (meditations " With one argument " ( hello " " " " " " ) ) (= " eats veggies . " ( diet { : species " deer " : name " " : age 1 : eater : herbivore } ) ) (= " eats veggies . " ( diet { : species " rabbit " : name " " : age 1 : eater : herbivore } ) ) (= " eats animals . " ( diet { : species " lion " : name " " : age 1 : eater : carnivore } ) ) (= " I do n't know what eats . " ( diet { : name " " } ) ) )
0ed75a975658d276383cc20b27a7ed8a2f757a4a3a156f683b97325381c411c8
full-spectrum/influxdb-client
java_time.clj
(ns influxdb.java-time (:require [influxdb.convert :as convert] [java-time])) (defmethod convert/->nano java.time.Instant [^java.time.Instant inst] (+ (* (.getEpochSecond inst) 1000000000) (.getNano inst)))
null
https://raw.githubusercontent.com/full-spectrum/influxdb-client/24ae1e146ac839cd02ace79b9ca89b3937c4fbad/src/influxdb/java_time.clj
clojure
(ns influxdb.java-time (:require [influxdb.convert :as convert] [java-time])) (defmethod convert/->nano java.time.Instant [^java.time.Instant inst] (+ (* (.getEpochSecond inst) 1000000000) (.getNano inst)))
173c9b89d847484a93dd29cdafa9cb2f76324e525688ebed1501bf17c5cf62a1
LuisThiamNye/chic
ui3.clj
(ns chic.ui.ui3 (:require [chic.debug :as debug] [chic.util :as util :refer [<- inline<- loop-zip loopr]] [chic.util.impl.analyzer :as util.ana] [chic.windows :as windows] [clojure.data] [clojure.string :as str] [clojure.tools.analyzer.ast :as ana.ast] [clojure.tools.analyzer.passes :as ana.passes] [clojure.tools.analyzer.jvm :as ana] [insn.core :as insn] [potemkin :refer [doit doary] :as pot] [taoensso.encore :as enc] [chic.bifurcan :as b]) (:import (io.github.humbleui.skija Canvas) (java.lang AutoCloseable) (java.util ArrayList))) ( defn rect->xbounds [ ^Rect rect ] ) ( defn rect->ybounds [ ^Rect rect ] ) (def ^:dynamic *component-ctx* nil) (def *class->cmpt (atom {})) (defn class->cmpt [^Class cls] (@*class->cmpt (.getName cls))) (defn identity-diff [prev v] (or (identical? prev v) (if (number? prev) (== prev v) false))) (defn class-default-value [^Class cls] (when (.isPrimitive cls) (case (.getName cls) "byte" (unchecked-byte 0) "short" (unchecked-short 0) "int" (unchecked-int 0) "long" (unchecked-long 0) "float" (unchecked-float 0) "double" (unchecked-double 0) "boolean" false "char" (unchecked-char 0)))) (def ^Class cmpt3-java-interface (insn/define {:flags #{:public :interface :abstract} :name (util/expand-class-sym 'ICmpt3) :interfaces ['java.lang.AutoCloseable] :version 19 :methods [{:flags #{:public} :name 'close :desc [:void] :emit [[:return]]}]})) (defn -define-cmpt-draw-interface [sym draw-param-sig] (insn/define {:flags #{:public :interface :abstract} :name sym :interfaces [cmpt3-java-interface] :version 19 :methods [{:flags #{:public :abstract} :name "draw" :desc (conj draw-param-sig 'void)}]})) (defn safe-close-ary [resources] (doary [r resources] (when (some? r) (try (.close ^AutoCloseable r) (catch Throwable e (.printStackTrace e)))))) (defn fnlet-widget-to-code* [{:keys [bindings input-chmask-sym c-sym bindings-anas unchanged-intf? i-sym body-ana draw-param-vec raw-input-syms input-syms retexpr draw-env draw-param-sig used-bindings]}] (assert (<= (count input-syms) 32)) (assert (<= (count bindings) 32)) (let [draw-body (next (drop-while (complement vector?) (:draw retexpr))) field-vec (mapv (fn [{:keys [^Class tag sym mutable?]}] (with-meta sym (cond-> {:tag (symbol (.getName tag))} mutable? (assoc :unsynchronized-mutable true)))) used-bindings) field-chmask-sym (gensym "field-chmask") has-draw-body? body-ana expand-ctx {:raw-body-ana body-ana :inputs (vec (sort-by :sym (map-indexed (fn [i sym] {:sym sym :arg-id i}) raw-input-syms))) :fields (vec (eduction (keep (fn [[ana {:keys [unused?]}]] (when (not unused?) {:ana-name (:name ana) :sym (:form ana)}))) (map vector bindings-anas bindings))) :input-chmask-sym input-chmask-sym :field-chmask-sym field-chmask-sym} fch-conds (keep (fn [{:keys [sym vexpr input-depmask field-depmask unused? diff always? close? mutable? i]}] (when mutable? (let [arg-check (when-not (== 0 input-depmask) `(not (== 0 (bit-and ~input-chmask-sym ~input-depmask)))) field-check (when-not (== 0 field-depmask) `(not (== 0 (bit-and ~field-chmask-sym ~field-depmask)))) vexpr (binding [*component-ctx* expand-ctx] (ana/macroexpand-all vexpr draw-env)) runexpr (if unused? `(do ~vexpr ~field-chmask-sym) (let [setexpr (fn [vexpr] `(do ~@(when close? `[(when-not (nil? ~sym) (.close ~sym))]) (set! ~sym ~vexpr) (bit-set ~field-chmask-sym ~i)))] (if diff (let [new-sym (gensym "new")] `(let [~new-sym ~vexpr] (if (~diff ~sym ~new-sym) ~field-chmask-sym ~(setexpr new-sym)))) (setexpr vexpr))))] `(as-> ~field-chmask-sym ~(if always? runexpr `(if ~(if (and arg-check field-check) `(or ~arg-check ~field-check) (or arg-check field-check)) ~runexpr ~field-chmask-sym)))))) bindings) closeable-field-syms (into [] (comp (filter :close?) (map :sym)) used-bindings)] `(binding [*unchecked-math* true] (let* [iface# ~(if unchanged-intf? (list `resolve (list 'quote i-sym)) (list `-define-cmpt-draw-interface (list 'quote i-sym) draw-param-sig)) cls# (eval (quote (deftype ~c-sym ~field-vec ~i-sym (draw ~(into [(gensym)] (map #(with-meta % nil)) draw-param-vec) (let [~field-chmask-sym ~(if (empty? fch-conds) (int 0) (if (seq (filter :always? bindings)) `(-> ~(int 0) ~@fch-conds) `(cond-> ~(int 0) (not (== 0 ~input-chmask-sym)) (-> ~@fch-conds))))] ~(when has-draw-body? (binding [*component-ctx* expand-ctx] (ana/macroexpand-all `(do ~@draw-body) (-> body-ana :env)))))) ~@(when closeable-field-syms `[java.lang.AutoCloseable (close [_#] (safe-close-ary (util/obj-array ~@closeable-field-syms)))]))))] (let* [ret# {:java-draw-interface iface# :java-class cls# :constructor (eval '(fn* [] ~(list 'let* (vec (mapcat (fn [{:keys [mutable? vexpr tag sym]}] [sym (if mutable? (class-default-value tag) vexpr)]) used-bindings)) (list* 'new c-sym (map :sym used-bindings))))) :input-syms '~input-syms}] (ns-unmap *ns* '~(symbol (str "->" c-sym))) (swap! *class->cmpt assoc (.getName ^Class (resolve '~i-sym)) ret#) ret#))))) (defn existing-draw-iface-sig* [^Class existing-iface] (try (let [methods (.getDeclaredMethods existing-iface)] (loopr [method methods] [] (when (= "draw" (.getName method)) (vec (.getParameterTypes method))) nil)) (catch NoClassDefFoundError _ ;; When existing interface is invalid nil))) (defn unchanged-cmpt-iface? [^Class existing-iface draw-param-sig] (when (and existing-iface (isa? existing-iface cmpt3-java-interface)) (= draw-param-sig (existing-draw-iface-sig* existing-iface)))) (defn param-vec->sig* "A type is a class object. Default type is Object." [pv] (mapv util/get-form-tag pv)) (defn fnlet-widget-parse* [fexpr & [&env]] (let [raw-input-syms (first (filter vector? fexpr)) input-syms (vec (sort raw-input-syms)) kebab->pascal (fn [s] (str/replace s #"(?:^|-)([a-z])" (fn [[_ l]] (str/upper-case l)))) nsym (symbol (munge (kebab->pascal (or (second (filter symbol? fexpr)) (gensym "FnletWidget"))))) expr-let (macroexpand-1 (last fexpr)) ;; fn form with destructured let fexpr (concat (butlast fexpr) (list expr-let)) retexpr (last expr-let) input-chmask-sym (gensym "input-chmask") ctx {:input-chmask-sym input-chmask-sym} root-env (assoc (ana/empty-env) :locals &env) method-ana (-> (binding [*component-ctx* (enc/merge ctx {:fake? true}) ana/run-passes (ana.passes/schedule (util.ana/jvm-passes ['uniquify-locals 'infer-tag #_'analyze-host-expr]))] (try (ana/analyze fexpr root-env) (catch Exception e (binding [ana/run-passes (ana.passes/schedule (util.ana/jvm-passes ['validate]))] (ana/analyze fexpr root-env)) (throw e)))) :methods first) bindings-anas (-> method-ana :body #_do :ret #_let :bindings) -visited-binding-names (java.util.HashSet.) -visited-local-syms (java.util.HashSet.) -immutable-binding-names (java.util.HashSet.) bindings (loop-zip [[specified-sym vexpr] (eduction (partition-all 2) (second expr-let)) {:keys [tag init] :as ana} bindings-anas] [i 0 bindings []] (let [tag (util/tag-class tag) sym (if (.contains -visited-local-syms specified-sym) (gensym specified-sym) specified-sym) input-deps (java.util.ArrayList.) field-deps (java.util.ArrayList.) ind-field-deps (java.util.ArrayList.) input-ana-names (set (map :name (:params method-ana))) _ (ana.ast/prewalk init (fn [a] (let [nam (:name a)] (cond (contains? input-ana-names nam) (.add input-deps (:form a)) (.contains -visited-binding-names nam) (if (.contains -immutable-binding-names nam) (.add ind-field-deps (:form a)) (.add field-deps (:form a))))) a)) field-deps (set field-deps) input-deps (set input-deps) close? (isa? tag java.lang.AutoCloseable) independent? (and (empty? input-deps) (empty? field-deps) (empty? ind-field-deps)) mta (meta specified-sym) unused? (and (not close?) (= '_ specified-sym)) mutable? (boolean (or (seq input-deps) (seq field-deps) (:always mta)))] (when (not mutable?) (.add -immutable-binding-names (:name ana))) (.add -visited-binding-names (:name ana)) (.add -visited-local-syms sym) (recur (if unused? i (unchecked-inc i)) (conj bindings {:tag tag :sym sym :i i :vexpr vexpr :independent? independent? :mutable? mutable? :always? (:always mta) :diff (cond (:diff= mta) `= (:diff mta) `identical?) :close? close? :unused? unused? :arg-deps input-deps :field-deps field-deps :input-depmask (reduce (fn [acc input-sym] (bit-set acc (util/index-of input-syms input-sym))) 0 input-deps) :field-depmask (loop-zip [b ^Iterable bindings {:keys [form]} bindings-anas] [acc 0] (recur (cond-> acc (contains? field-deps form) (bit-set (:i b)))) acc)}))) bindings) i-sym (util/expand-class-sym (symbol (str "I" nsym))) canvas-sym (ffirst (filter vector? (:draw retexpr))) draw-param-vec (into (conj [(with-meta canvas-sym {:tag `Canvas})] (with-meta input-chmask-sym {:tag 'int})) (map (fn [{:keys [form tag]}] (with-meta form {:tag tag}))) (sort-by :form (-> method-ana :params))) used-bindings (filterv (complement :unused?) bindings) init-bindings (filterv (every-pred (complement :mutable?) (complement :independent?)) used-bindings) existing-iface (try (resolve i-sym) (catch ClassNotFoundException _)) draw-param-sig (param-vec->sig* draw-param-vec) unchanged-intf? (unchanged-cmpt-iface? existing-iface draw-param-sig) ;; ana of enclosed map. body-ana (-> method-ana :body #_do :ret #_let :body #_do :ret) draw-env (:env body-ana)] (enc/have some? draw-env :data (do (debug/report-error-data {:method-ana method-ana}))) (enc/merge ctx {:body-ana body-ana :draw-env draw-env :c-sym nsym :bindings-anas bindings-anas :retexpr retexpr :bindings bindings :raw-input-syms raw-input-syms :input-syms input-syms :unchanged-intf? unchanged-intf? :existing-iface existing-iface :i-sym i-sym :init-bindings init-bindings :used-bindings used-bindings :draw-param-sig draw-param-sig :draw-param-vec draw-param-vec}))) (defmacro fnlet-widget [fexpr] (fnlet-widget-to-code* (fnlet-widget-parse* fexpr &env))) (defmacro deffnletcmpt [sym params let-expr] `(def ~sym (fnlet-widget (fn ~sym ~params ~let-expr)))) (defn draw-cmpt->code* []) (defn draw-cmpt* [{:keys [raw-body-ana inputs fields input-chmask-sym field-chmask-sym] :as ctx} cmpt canvas-sym cmpt-expr argmap] (util/with-merge-assert-data {:inputs inputs :fields fields 'cmpt (enc/have map? cmpt) 'argmap argmap} (let [param-syms (:input-syms cmpt) specified-param-keys (into #{} (keys (dissoc argmap :-init?))) param-kws (into #{} (map keyword) param-syms) _ (enc/have? true? (= param-kws specified-param-keys) :data {:msg "Specified param keys do not match component" :excess (first (clojure.data/diff specified-param-keys param-kws)) :missing (first (clojure.data/diff param-kws specified-param-keys))}) [cmpt-expr-ana argmap-ana] (let [*ret (volatile! nil) *cmpt-ana (volatile! nil)] (ana.ast/prewalk raw-body-ana (fn [{:keys [form] :as node}] (cond-> (cond (identical? argmap form) (vreset! *ret node) (identical? cmpt-expr form) (vreset! *cmpt-ana node) :else node) (and @*ret @*cmpt-ana) reduced))) [@*cmpt-ana @*ret]) _ (enc/have map? argmap-ana) spc-init-expr (:-init? argmap) input-arg-ids (set (map :arg-id inputs)) field-ana-names (set (map :ana-name fields)) args (mapv (fn [sym] (util/with-merge-assert-data {'sym sym} (let [argmap-idx (some identity (map-indexed (fn [i kana] (when (= (keyword sym) (:val kana)) i)) (-> argmap-ana :keys))) _ (enc/have? integer? argmap-idx) expr-ana (-> argmap-ana :vals (nth argmap-idx)) input-deps (java.util.ArrayList.) field-deps (java.util.ArrayList.) process-subexpr-ana (fn [a] (cond (contains? input-arg-ids (:arg-id a)) (.add input-deps (:form a)) (contains? field-ana-names (:name a)) (.add field-deps (:form a))) a) const? (:const (:op expr-ana)) _ (ana.ast/prewalk expr-ana process-subexpr-ana) ;; _ (when (and (empty? input-deps) (empty? field-deps)) ( process - subexpr - ) ) input-deps (set input-deps) field-deps (set field-deps) make-mask (fn [deps variables] (reduce + (map (fn [i] (let [sym (:sym (nth variables i))] (if (contains? deps sym) (bit-shift-left 1 i) 0))) (range (count variables)))))] {:expr (argmap (keyword sym)) :expr-ana expr-ana :const? const? :sym sym :input-deps input-deps :field-deps field-deps :input-depmask (make-mask input-deps inputs) :field-depmask (make-mask field-deps fields)}))) param-syms) chmask-conds `(-> ~(int 0) ~@(eduction (keep-indexed (fn [i {:keys [input-depmask field-depmask] :as arg}] (let [depmask-expr (reduce (fn ([]) ([acc expr] `(bit-or ~acc ~expr))) (sequence (comp (keep (fn [[sym mask]] (when-not (== 0 mask) `(bit-and ~sym ~mask))))) [[input-chmask-sym input-depmask] [field-chmask-sym field-depmask]]))] (when depmask-expr `(cond-> (not (== 0 ~depmask-expr)) (bit-set ~i)))))) args)) chmask-expr (if spc-init-expr `(if ~spc-init-expr Integer/MAX_VALUE ~chmask-conds) chmask-conds)] (debug/report-data :draw-cmpt {:args args :cmpt-expr-ana cmpt-expr-ana :field-ana-names field-ana-names :ctx ctx :cmpt-expr cmpt-expr}) #_(when (nil? cmpt-expr-ana) (throw (ex-info "Could not find cmpt-expr analysis ast" {}))) (when-not spc-init-expr (doit [{:keys [input-depmask field-depmask sym]} args] (when (== 0 input-depmask field-depmask) (throw (ex-info (format "Arg for %s cannot be independent" sym) {}))))) `(.draw ~(with-meta cmpt-expr {:tag (.getName ^Class (:java-draw-interface cmpt))}) ~canvas-sym ~chmask-expr ~@(map :expr args))))) (defn resolve-cmpt [expr env] (or (let [sym (:cmpt (meta expr)) r (when (symbol? sym) (resolve sym))] (when (var? r) @r)) (when-some [cls (and (symbol? expr) (util/infer-tag expr env))] (class->cmpt cls)) (do (debug/report-error-data {:ctx *component-ctx*}) (enc/have some? nil :data {:msg (str "Could not resolve component: " expr)})))) (defmacro draw-cmpt [cmpt-expr cnv-sym argmap] (let [ctx *component-ctx*] (if (:fake? ctx) `(do ~cmpt-expr ~argmap nil) (let [cmpt (resolve-cmpt cmpt-expr &env)] (draw-cmpt* ctx cmpt cnv-sym cmpt-expr argmap))))) (defn select-from-mask* [mask coll] (into #{} (keep-indexed (fn [i x] (when (bit-test mask i) x))) coll)) (defmacro get-assert* [m k pred] (util/let-macro-syms [k k] `(let [x# (get ~m ~k)] (assert (~pred x#) (str "Invalid data at key: " ~k "\nFrom: " (quote ~m))) x#))) (defmacro get-input-chmask [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) (get-assert* ctx :input-chmask-sym symbol?)))) (defmacro get-changed-input-syms [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) `(select-from-mask* (get-input-chmask) '~(mapv :sym (:inputs ctx)))))) (defmacro get-field-chmask [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) (get-assert* ctx :field-chmask-sym symbol?)))) (defmacro get-changed-field-syms [] (let [ctx *component-ctx*] (when-not (:fake? ctx) `(select-from-mask* (get-field-chmask) '~(mapv :sym (:fields ctx)))))) (defmacro changed? [sym] (let [ctx *component-ctx*] (when-not (:fake? ctx) (<- (let [i (util/index-of (mapv :sym (:fields ctx)) sym)]) (if (<= i 0) `(bit-test (get-field-chmask) ~i)) (let [i (util/index-of (mapv :sym (:inputs ctx)) sym)]) (if (<= i 0) `(bit-test (get-field-chmask) ~i)) (throw (Exception. "Not an input nor field symbol")))))) (defmacro new-cmpt [cmpt-sym] (let [cmpt @(resolve cmpt-sym)] (with-meta `((:constructor ~cmpt-sym)) {:tag (symbol (.getName ^Class (:java-draw-interface cmpt)))}))) (defn draw-cmpt-external* [cmpt cnv cmpt-sym chmask-expr argvec argmap] (let [argmap (reduce (fn [m sym] (let [k (keyword sym)] (if (contains? m k) m (assoc m k sym)))) argmap argvec) param-syms (:input-syms cmpt)] (assert (= (set param-syms) (into (set argvec) (map symbol) (keys argmap))) "All component parameters must be specified exactly") `(.draw ~(with-meta cmpt-sym {:tag (.getName ^Class (:java-draw-interface cmpt))}) ~cnv ~chmask-expr ~@(map (fn [sym] (argmap (keyword sym))) param-syms)))) (defmacro draw-cmpt-ext [cmpt-sym cnv chmask & [a1 a2]] (let [argvec (if (vector? a1) a1 []) argmap (or a2 a1) argmap (if (map? argmap) argmap {}) cmpt (resolve-cmpt cmpt-sym &env)] (draw-cmpt-external* cmpt cnv cmpt-sym chmask argvec argmap))) #_(defn free-variables [expr] (let [*set (proteus.Containers$O. (transient #{}))] (ana/analyze expr (ana/empty-env) {:passes-opts (assoc ana/default-passes-opts :validate/unresolvable-symbol-handler (fn [_ns namesym _ast] (.set *set (conj! (.-x *set) namesym)) {:op :const :env {} :type :nil :literal? true :val nil :form nil :top-level true :o-tag nil :tag nil}))}) (persistent! (.-x *set)))) (defmacro cmpt-ext-input-memory [cmpt-sym] (let [cmpt (resolve-cmpt cmpt-sym &env)] `(object-array ~(count (:input-syms cmpt))))) (defmacro draw-cmpt-ext-memo [cmpt-sym cnv argary argmap] (util/let-macro-syms [argary argary] (let [cmpt (resolve-cmpt cmpt-sym &env) input-syms (:input-syms cmpt) inputs (map-indexed (fn [i sym] (let [vexpr (argmap (keyword sym))] (if (util/analyze-const? vexpr &env) {:const? true :i i} {:i i :sym sym :val-sym (if (symbol? vexpr) vexpr (gensym sym)) :vexpr vexpr :box? (#{"float" "double" "long" "int"} (str (:tag (meta vexpr)))) :equality-sym (cond (:diff= (meta vexpr)) `= (#{"float" "double"} (str (:tag (meta vexpr)))) `util/equals :else `identity-diff) :symbol? (symbol? vexpr)}))) input-syms) init-idx (:i (first (filter :const? inputs))) variable-inputs (remove :const? inputs) varexpr-inputs (remove :symbol? variable-inputs) argmap (reduce (fn [m {:keys [sym val-sym]}] (assoc m (keyword sym) val-sym)) argmap varexpr-inputs) chmask-bindings (mapcat (fn [{:keys [val-sym equality-sym i box?]}] `[chmask## (if (~equality-sym (aget ~argary ~(unchecked-int i)) ~val-sym) chmask## (do (aset ~argary ~(unchecked-int i) ~(if box? `(identity ~val-sym) val-sym)) (bit-set chmask## ~i)))]) variable-inputs)] `(let [~@(mapcat (fn [{:keys [vexpr val-sym]}] [val-sym vexpr]) varexpr-inputs) chmask## ~(if init-idx `(if (nil? (aget ~argary ~init-idx)) (do (aset ~argary ~init-idx true) Integer/MAX_VALUE) ~(unchecked-int 0)) (unchecked-int 0)) ~@chmask-bindings] ~(draw-cmpt-external* cmpt cnv cmpt-sym `chmask## [] argmap))))) (comment (->> (macroexpand-1 '(fnlet-widget (fn [] (let [x ^Image (+)] {:draw (fn [_])})))) (drop 2) first (drop 2) ffirst meta :tag type) (->> (macroexpand-1 '(fnlet-widget (fn [] (let [{:keys [x y]} (+)] {:draw (fn [_])})))) (drop 2) first (drop 2) ffirst meta :tag type) (macroexpand-1 '(let [{:keys [x y]} (+)] {:draw (fn [_])})) (-> (ana/analyze '(fn [x] (let [z x z z] z))) :methods first :body :bindings first keys) (-> (ana/analyze '(fn [^int x])) :methods first :params first :tag type) (-> (ana/analyze '(fn [x] (let [y (+ x)] y))) :methods first :params first :arg-id) (eval (ana/macroexpand-all (util/quoted (let [x [] x []] (util/compile (fn [&env] `(quote ~(do (&env 'x))))))))) (let [x []] (util/compile (fn [&env] `(quote ~(do (.-sym (&env 'x))))))) #! ) #_{:name _ :fields [{:flags #{:public} :name _ :type _ :value nil}] :methods [{:flags #{:public} :name "draw" :desc [_ _ _] :emit (fn [^MethodVisitor mv])}]} #_(binding [*compiler-options* {:disable-locals-clearing false}] (decompiler/disassemble (fn [] (println "Hello, decompiler!"))) #_(decompiler/decompile (fn [] (+ 4)))) (defn get-mouse-pos-mut [] (enc/have some? (:chic.ui/mouse-win-pos (.get windows/*root-ctx)))) (defn get-mouse-pos [] @(get-mouse-pos-mut)) (defn coll-closer ^AutoCloseable [coll] (reify AutoCloseable (close [_] (doit [^AutoCloseable c coll] (.close c)))))
null
https://raw.githubusercontent.com/LuisThiamNye/chic/813633a689f9080731613f788a295604d4d9a510/src/chic/ui/ui3.clj
clojure
When existing interface is invalid fn form with destructured let ana of enclosed map. _ (when (and (empty? input-deps) (empty? field-deps))
(ns chic.ui.ui3 (:require [chic.debug :as debug] [chic.util :as util :refer [<- inline<- loop-zip loopr]] [chic.util.impl.analyzer :as util.ana] [chic.windows :as windows] [clojure.data] [clojure.string :as str] [clojure.tools.analyzer.ast :as ana.ast] [clojure.tools.analyzer.passes :as ana.passes] [clojure.tools.analyzer.jvm :as ana] [insn.core :as insn] [potemkin :refer [doit doary] :as pot] [taoensso.encore :as enc] [chic.bifurcan :as b]) (:import (io.github.humbleui.skija Canvas) (java.lang AutoCloseable) (java.util ArrayList))) ( defn rect->xbounds [ ^Rect rect ] ) ( defn rect->ybounds [ ^Rect rect ] ) (def ^:dynamic *component-ctx* nil) (def *class->cmpt (atom {})) (defn class->cmpt [^Class cls] (@*class->cmpt (.getName cls))) (defn identity-diff [prev v] (or (identical? prev v) (if (number? prev) (== prev v) false))) (defn class-default-value [^Class cls] (when (.isPrimitive cls) (case (.getName cls) "byte" (unchecked-byte 0) "short" (unchecked-short 0) "int" (unchecked-int 0) "long" (unchecked-long 0) "float" (unchecked-float 0) "double" (unchecked-double 0) "boolean" false "char" (unchecked-char 0)))) (def ^Class cmpt3-java-interface (insn/define {:flags #{:public :interface :abstract} :name (util/expand-class-sym 'ICmpt3) :interfaces ['java.lang.AutoCloseable] :version 19 :methods [{:flags #{:public} :name 'close :desc [:void] :emit [[:return]]}]})) (defn -define-cmpt-draw-interface [sym draw-param-sig] (insn/define {:flags #{:public :interface :abstract} :name sym :interfaces [cmpt3-java-interface] :version 19 :methods [{:flags #{:public :abstract} :name "draw" :desc (conj draw-param-sig 'void)}]})) (defn safe-close-ary [resources] (doary [r resources] (when (some? r) (try (.close ^AutoCloseable r) (catch Throwable e (.printStackTrace e)))))) (defn fnlet-widget-to-code* [{:keys [bindings input-chmask-sym c-sym bindings-anas unchanged-intf? i-sym body-ana draw-param-vec raw-input-syms input-syms retexpr draw-env draw-param-sig used-bindings]}] (assert (<= (count input-syms) 32)) (assert (<= (count bindings) 32)) (let [draw-body (next (drop-while (complement vector?) (:draw retexpr))) field-vec (mapv (fn [{:keys [^Class tag sym mutable?]}] (with-meta sym (cond-> {:tag (symbol (.getName tag))} mutable? (assoc :unsynchronized-mutable true)))) used-bindings) field-chmask-sym (gensym "field-chmask") has-draw-body? body-ana expand-ctx {:raw-body-ana body-ana :inputs (vec (sort-by :sym (map-indexed (fn [i sym] {:sym sym :arg-id i}) raw-input-syms))) :fields (vec (eduction (keep (fn [[ana {:keys [unused?]}]] (when (not unused?) {:ana-name (:name ana) :sym (:form ana)}))) (map vector bindings-anas bindings))) :input-chmask-sym input-chmask-sym :field-chmask-sym field-chmask-sym} fch-conds (keep (fn [{:keys [sym vexpr input-depmask field-depmask unused? diff always? close? mutable? i]}] (when mutable? (let [arg-check (when-not (== 0 input-depmask) `(not (== 0 (bit-and ~input-chmask-sym ~input-depmask)))) field-check (when-not (== 0 field-depmask) `(not (== 0 (bit-and ~field-chmask-sym ~field-depmask)))) vexpr (binding [*component-ctx* expand-ctx] (ana/macroexpand-all vexpr draw-env)) runexpr (if unused? `(do ~vexpr ~field-chmask-sym) (let [setexpr (fn [vexpr] `(do ~@(when close? `[(when-not (nil? ~sym) (.close ~sym))]) (set! ~sym ~vexpr) (bit-set ~field-chmask-sym ~i)))] (if diff (let [new-sym (gensym "new")] `(let [~new-sym ~vexpr] (if (~diff ~sym ~new-sym) ~field-chmask-sym ~(setexpr new-sym)))) (setexpr vexpr))))] `(as-> ~field-chmask-sym ~(if always? runexpr `(if ~(if (and arg-check field-check) `(or ~arg-check ~field-check) (or arg-check field-check)) ~runexpr ~field-chmask-sym)))))) bindings) closeable-field-syms (into [] (comp (filter :close?) (map :sym)) used-bindings)] `(binding [*unchecked-math* true] (let* [iface# ~(if unchanged-intf? (list `resolve (list 'quote i-sym)) (list `-define-cmpt-draw-interface (list 'quote i-sym) draw-param-sig)) cls# (eval (quote (deftype ~c-sym ~field-vec ~i-sym (draw ~(into [(gensym)] (map #(with-meta % nil)) draw-param-vec) (let [~field-chmask-sym ~(if (empty? fch-conds) (int 0) (if (seq (filter :always? bindings)) `(-> ~(int 0) ~@fch-conds) `(cond-> ~(int 0) (not (== 0 ~input-chmask-sym)) (-> ~@fch-conds))))] ~(when has-draw-body? (binding [*component-ctx* expand-ctx] (ana/macroexpand-all `(do ~@draw-body) (-> body-ana :env)))))) ~@(when closeable-field-syms `[java.lang.AutoCloseable (close [_#] (safe-close-ary (util/obj-array ~@closeable-field-syms)))]))))] (let* [ret# {:java-draw-interface iface# :java-class cls# :constructor (eval '(fn* [] ~(list 'let* (vec (mapcat (fn [{:keys [mutable? vexpr tag sym]}] [sym (if mutable? (class-default-value tag) vexpr)]) used-bindings)) (list* 'new c-sym (map :sym used-bindings))))) :input-syms '~input-syms}] (ns-unmap *ns* '~(symbol (str "->" c-sym))) (swap! *class->cmpt assoc (.getName ^Class (resolve '~i-sym)) ret#) ret#))))) (defn existing-draw-iface-sig* [^Class existing-iface] (try (let [methods (.getDeclaredMethods existing-iface)] (loopr [method methods] [] (when (= "draw" (.getName method)) (vec (.getParameterTypes method))) nil)) (catch NoClassDefFoundError _ nil))) (defn unchanged-cmpt-iface? [^Class existing-iface draw-param-sig] (when (and existing-iface (isa? existing-iface cmpt3-java-interface)) (= draw-param-sig (existing-draw-iface-sig* existing-iface)))) (defn param-vec->sig* "A type is a class object. Default type is Object." [pv] (mapv util/get-form-tag pv)) (defn fnlet-widget-parse* [fexpr & [&env]] (let [raw-input-syms (first (filter vector? fexpr)) input-syms (vec (sort raw-input-syms)) kebab->pascal (fn [s] (str/replace s #"(?:^|-)([a-z])" (fn [[_ l]] (str/upper-case l)))) nsym (symbol (munge (kebab->pascal (or (second (filter symbol? fexpr)) (gensym "FnletWidget"))))) expr-let (macroexpand-1 (last fexpr)) fexpr (concat (butlast fexpr) (list expr-let)) retexpr (last expr-let) input-chmask-sym (gensym "input-chmask") ctx {:input-chmask-sym input-chmask-sym} root-env (assoc (ana/empty-env) :locals &env) method-ana (-> (binding [*component-ctx* (enc/merge ctx {:fake? true}) ana/run-passes (ana.passes/schedule (util.ana/jvm-passes ['uniquify-locals 'infer-tag #_'analyze-host-expr]))] (try (ana/analyze fexpr root-env) (catch Exception e (binding [ana/run-passes (ana.passes/schedule (util.ana/jvm-passes ['validate]))] (ana/analyze fexpr root-env)) (throw e)))) :methods first) bindings-anas (-> method-ana :body #_do :ret #_let :bindings) -visited-binding-names (java.util.HashSet.) -visited-local-syms (java.util.HashSet.) -immutable-binding-names (java.util.HashSet.) bindings (loop-zip [[specified-sym vexpr] (eduction (partition-all 2) (second expr-let)) {:keys [tag init] :as ana} bindings-anas] [i 0 bindings []] (let [tag (util/tag-class tag) sym (if (.contains -visited-local-syms specified-sym) (gensym specified-sym) specified-sym) input-deps (java.util.ArrayList.) field-deps (java.util.ArrayList.) ind-field-deps (java.util.ArrayList.) input-ana-names (set (map :name (:params method-ana))) _ (ana.ast/prewalk init (fn [a] (let [nam (:name a)] (cond (contains? input-ana-names nam) (.add input-deps (:form a)) (.contains -visited-binding-names nam) (if (.contains -immutable-binding-names nam) (.add ind-field-deps (:form a)) (.add field-deps (:form a))))) a)) field-deps (set field-deps) input-deps (set input-deps) close? (isa? tag java.lang.AutoCloseable) independent? (and (empty? input-deps) (empty? field-deps) (empty? ind-field-deps)) mta (meta specified-sym) unused? (and (not close?) (= '_ specified-sym)) mutable? (boolean (or (seq input-deps) (seq field-deps) (:always mta)))] (when (not mutable?) (.add -immutable-binding-names (:name ana))) (.add -visited-binding-names (:name ana)) (.add -visited-local-syms sym) (recur (if unused? i (unchecked-inc i)) (conj bindings {:tag tag :sym sym :i i :vexpr vexpr :independent? independent? :mutable? mutable? :always? (:always mta) :diff (cond (:diff= mta) `= (:diff mta) `identical?) :close? close? :unused? unused? :arg-deps input-deps :field-deps field-deps :input-depmask (reduce (fn [acc input-sym] (bit-set acc (util/index-of input-syms input-sym))) 0 input-deps) :field-depmask (loop-zip [b ^Iterable bindings {:keys [form]} bindings-anas] [acc 0] (recur (cond-> acc (contains? field-deps form) (bit-set (:i b)))) acc)}))) bindings) i-sym (util/expand-class-sym (symbol (str "I" nsym))) canvas-sym (ffirst (filter vector? (:draw retexpr))) draw-param-vec (into (conj [(with-meta canvas-sym {:tag `Canvas})] (with-meta input-chmask-sym {:tag 'int})) (map (fn [{:keys [form tag]}] (with-meta form {:tag tag}))) (sort-by :form (-> method-ana :params))) used-bindings (filterv (complement :unused?) bindings) init-bindings (filterv (every-pred (complement :mutable?) (complement :independent?)) used-bindings) existing-iface (try (resolve i-sym) (catch ClassNotFoundException _)) draw-param-sig (param-vec->sig* draw-param-vec) unchanged-intf? (unchanged-cmpt-iface? existing-iface draw-param-sig) body-ana (-> method-ana :body #_do :ret #_let :body #_do :ret) draw-env (:env body-ana)] (enc/have some? draw-env :data (do (debug/report-error-data {:method-ana method-ana}))) (enc/merge ctx {:body-ana body-ana :draw-env draw-env :c-sym nsym :bindings-anas bindings-anas :retexpr retexpr :bindings bindings :raw-input-syms raw-input-syms :input-syms input-syms :unchanged-intf? unchanged-intf? :existing-iface existing-iface :i-sym i-sym :init-bindings init-bindings :used-bindings used-bindings :draw-param-sig draw-param-sig :draw-param-vec draw-param-vec}))) (defmacro fnlet-widget [fexpr] (fnlet-widget-to-code* (fnlet-widget-parse* fexpr &env))) (defmacro deffnletcmpt [sym params let-expr] `(def ~sym (fnlet-widget (fn ~sym ~params ~let-expr)))) (defn draw-cmpt->code* []) (defn draw-cmpt* [{:keys [raw-body-ana inputs fields input-chmask-sym field-chmask-sym] :as ctx} cmpt canvas-sym cmpt-expr argmap] (util/with-merge-assert-data {:inputs inputs :fields fields 'cmpt (enc/have map? cmpt) 'argmap argmap} (let [param-syms (:input-syms cmpt) specified-param-keys (into #{} (keys (dissoc argmap :-init?))) param-kws (into #{} (map keyword) param-syms) _ (enc/have? true? (= param-kws specified-param-keys) :data {:msg "Specified param keys do not match component" :excess (first (clojure.data/diff specified-param-keys param-kws)) :missing (first (clojure.data/diff param-kws specified-param-keys))}) [cmpt-expr-ana argmap-ana] (let [*ret (volatile! nil) *cmpt-ana (volatile! nil)] (ana.ast/prewalk raw-body-ana (fn [{:keys [form] :as node}] (cond-> (cond (identical? argmap form) (vreset! *ret node) (identical? cmpt-expr form) (vreset! *cmpt-ana node) :else node) (and @*ret @*cmpt-ana) reduced))) [@*cmpt-ana @*ret]) _ (enc/have map? argmap-ana) spc-init-expr (:-init? argmap) input-arg-ids (set (map :arg-id inputs)) field-ana-names (set (map :ana-name fields)) args (mapv (fn [sym] (util/with-merge-assert-data {'sym sym} (let [argmap-idx (some identity (map-indexed (fn [i kana] (when (= (keyword sym) (:val kana)) i)) (-> argmap-ana :keys))) _ (enc/have? integer? argmap-idx) expr-ana (-> argmap-ana :vals (nth argmap-idx)) input-deps (java.util.ArrayList.) field-deps (java.util.ArrayList.) process-subexpr-ana (fn [a] (cond (contains? input-arg-ids (:arg-id a)) (.add input-deps (:form a)) (contains? field-ana-names (:name a)) (.add field-deps (:form a))) a) const? (:const (:op expr-ana)) _ (ana.ast/prewalk expr-ana process-subexpr-ana) ( process - subexpr - ) ) input-deps (set input-deps) field-deps (set field-deps) make-mask (fn [deps variables] (reduce + (map (fn [i] (let [sym (:sym (nth variables i))] (if (contains? deps sym) (bit-shift-left 1 i) 0))) (range (count variables)))))] {:expr (argmap (keyword sym)) :expr-ana expr-ana :const? const? :sym sym :input-deps input-deps :field-deps field-deps :input-depmask (make-mask input-deps inputs) :field-depmask (make-mask field-deps fields)}))) param-syms) chmask-conds `(-> ~(int 0) ~@(eduction (keep-indexed (fn [i {:keys [input-depmask field-depmask] :as arg}] (let [depmask-expr (reduce (fn ([]) ([acc expr] `(bit-or ~acc ~expr))) (sequence (comp (keep (fn [[sym mask]] (when-not (== 0 mask) `(bit-and ~sym ~mask))))) [[input-chmask-sym input-depmask] [field-chmask-sym field-depmask]]))] (when depmask-expr `(cond-> (not (== 0 ~depmask-expr)) (bit-set ~i)))))) args)) chmask-expr (if spc-init-expr `(if ~spc-init-expr Integer/MAX_VALUE ~chmask-conds) chmask-conds)] (debug/report-data :draw-cmpt {:args args :cmpt-expr-ana cmpt-expr-ana :field-ana-names field-ana-names :ctx ctx :cmpt-expr cmpt-expr}) #_(when (nil? cmpt-expr-ana) (throw (ex-info "Could not find cmpt-expr analysis ast" {}))) (when-not spc-init-expr (doit [{:keys [input-depmask field-depmask sym]} args] (when (== 0 input-depmask field-depmask) (throw (ex-info (format "Arg for %s cannot be independent" sym) {}))))) `(.draw ~(with-meta cmpt-expr {:tag (.getName ^Class (:java-draw-interface cmpt))}) ~canvas-sym ~chmask-expr ~@(map :expr args))))) (defn resolve-cmpt [expr env] (or (let [sym (:cmpt (meta expr)) r (when (symbol? sym) (resolve sym))] (when (var? r) @r)) (when-some [cls (and (symbol? expr) (util/infer-tag expr env))] (class->cmpt cls)) (do (debug/report-error-data {:ctx *component-ctx*}) (enc/have some? nil :data {:msg (str "Could not resolve component: " expr)})))) (defmacro draw-cmpt [cmpt-expr cnv-sym argmap] (let [ctx *component-ctx*] (if (:fake? ctx) `(do ~cmpt-expr ~argmap nil) (let [cmpt (resolve-cmpt cmpt-expr &env)] (draw-cmpt* ctx cmpt cnv-sym cmpt-expr argmap))))) (defn select-from-mask* [mask coll] (into #{} (keep-indexed (fn [i x] (when (bit-test mask i) x))) coll)) (defmacro get-assert* [m k pred] (util/let-macro-syms [k k] `(let [x# (get ~m ~k)] (assert (~pred x#) (str "Invalid data at key: " ~k "\nFrom: " (quote ~m))) x#))) (defmacro get-input-chmask [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) (get-assert* ctx :input-chmask-sym symbol?)))) (defmacro get-changed-input-syms [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) `(select-from-mask* (get-input-chmask) '~(mapv :sym (:inputs ctx)))))) (defmacro get-field-chmask [] (let [ctx *component-ctx*] (when-not (:fake? ctx) (assert (map? ctx)) (get-assert* ctx :field-chmask-sym symbol?)))) (defmacro get-changed-field-syms [] (let [ctx *component-ctx*] (when-not (:fake? ctx) `(select-from-mask* (get-field-chmask) '~(mapv :sym (:fields ctx)))))) (defmacro changed? [sym] (let [ctx *component-ctx*] (when-not (:fake? ctx) (<- (let [i (util/index-of (mapv :sym (:fields ctx)) sym)]) (if (<= i 0) `(bit-test (get-field-chmask) ~i)) (let [i (util/index-of (mapv :sym (:inputs ctx)) sym)]) (if (<= i 0) `(bit-test (get-field-chmask) ~i)) (throw (Exception. "Not an input nor field symbol")))))) (defmacro new-cmpt [cmpt-sym] (let [cmpt @(resolve cmpt-sym)] (with-meta `((:constructor ~cmpt-sym)) {:tag (symbol (.getName ^Class (:java-draw-interface cmpt)))}))) (defn draw-cmpt-external* [cmpt cnv cmpt-sym chmask-expr argvec argmap] (let [argmap (reduce (fn [m sym] (let [k (keyword sym)] (if (contains? m k) m (assoc m k sym)))) argmap argvec) param-syms (:input-syms cmpt)] (assert (= (set param-syms) (into (set argvec) (map symbol) (keys argmap))) "All component parameters must be specified exactly") `(.draw ~(with-meta cmpt-sym {:tag (.getName ^Class (:java-draw-interface cmpt))}) ~cnv ~chmask-expr ~@(map (fn [sym] (argmap (keyword sym))) param-syms)))) (defmacro draw-cmpt-ext [cmpt-sym cnv chmask & [a1 a2]] (let [argvec (if (vector? a1) a1 []) argmap (or a2 a1) argmap (if (map? argmap) argmap {}) cmpt (resolve-cmpt cmpt-sym &env)] (draw-cmpt-external* cmpt cnv cmpt-sym chmask argvec argmap))) #_(defn free-variables [expr] (let [*set (proteus.Containers$O. (transient #{}))] (ana/analyze expr (ana/empty-env) {:passes-opts (assoc ana/default-passes-opts :validate/unresolvable-symbol-handler (fn [_ns namesym _ast] (.set *set (conj! (.-x *set) namesym)) {:op :const :env {} :type :nil :literal? true :val nil :form nil :top-level true :o-tag nil :tag nil}))}) (persistent! (.-x *set)))) (defmacro cmpt-ext-input-memory [cmpt-sym] (let [cmpt (resolve-cmpt cmpt-sym &env)] `(object-array ~(count (:input-syms cmpt))))) (defmacro draw-cmpt-ext-memo [cmpt-sym cnv argary argmap] (util/let-macro-syms [argary argary] (let [cmpt (resolve-cmpt cmpt-sym &env) input-syms (:input-syms cmpt) inputs (map-indexed (fn [i sym] (let [vexpr (argmap (keyword sym))] (if (util/analyze-const? vexpr &env) {:const? true :i i} {:i i :sym sym :val-sym (if (symbol? vexpr) vexpr (gensym sym)) :vexpr vexpr :box? (#{"float" "double" "long" "int"} (str (:tag (meta vexpr)))) :equality-sym (cond (:diff= (meta vexpr)) `= (#{"float" "double"} (str (:tag (meta vexpr)))) `util/equals :else `identity-diff) :symbol? (symbol? vexpr)}))) input-syms) init-idx (:i (first (filter :const? inputs))) variable-inputs (remove :const? inputs) varexpr-inputs (remove :symbol? variable-inputs) argmap (reduce (fn [m {:keys [sym val-sym]}] (assoc m (keyword sym) val-sym)) argmap varexpr-inputs) chmask-bindings (mapcat (fn [{:keys [val-sym equality-sym i box?]}] `[chmask## (if (~equality-sym (aget ~argary ~(unchecked-int i)) ~val-sym) chmask## (do (aset ~argary ~(unchecked-int i) ~(if box? `(identity ~val-sym) val-sym)) (bit-set chmask## ~i)))]) variable-inputs)] `(let [~@(mapcat (fn [{:keys [vexpr val-sym]}] [val-sym vexpr]) varexpr-inputs) chmask## ~(if init-idx `(if (nil? (aget ~argary ~init-idx)) (do (aset ~argary ~init-idx true) Integer/MAX_VALUE) ~(unchecked-int 0)) (unchecked-int 0)) ~@chmask-bindings] ~(draw-cmpt-external* cmpt cnv cmpt-sym `chmask## [] argmap))))) (comment (->> (macroexpand-1 '(fnlet-widget (fn [] (let [x ^Image (+)] {:draw (fn [_])})))) (drop 2) first (drop 2) ffirst meta :tag type) (->> (macroexpand-1 '(fnlet-widget (fn [] (let [{:keys [x y]} (+)] {:draw (fn [_])})))) (drop 2) first (drop 2) ffirst meta :tag type) (macroexpand-1 '(let [{:keys [x y]} (+)] {:draw (fn [_])})) (-> (ana/analyze '(fn [x] (let [z x z z] z))) :methods first :body :bindings first keys) (-> (ana/analyze '(fn [^int x])) :methods first :params first :tag type) (-> (ana/analyze '(fn [x] (let [y (+ x)] y))) :methods first :params first :arg-id) (eval (ana/macroexpand-all (util/quoted (let [x [] x []] (util/compile (fn [&env] `(quote ~(do (&env 'x))))))))) (let [x []] (util/compile (fn [&env] `(quote ~(do (.-sym (&env 'x))))))) #! ) #_{:name _ :fields [{:flags #{:public} :name _ :type _ :value nil}] :methods [{:flags #{:public} :name "draw" :desc [_ _ _] :emit (fn [^MethodVisitor mv])}]} #_(binding [*compiler-options* {:disable-locals-clearing false}] (decompiler/disassemble (fn [] (println "Hello, decompiler!"))) #_(decompiler/decompile (fn [] (+ 4)))) (defn get-mouse-pos-mut [] (enc/have some? (:chic.ui/mouse-win-pos (.get windows/*root-ctx)))) (defn get-mouse-pos [] @(get-mouse-pos-mut)) (defn coll-closer ^AutoCloseable [coll] (reify AutoCloseable (close [_] (doit [^AutoCloseable c coll] (.close c)))))
b61acd8a9d968cd9aa26c0e84ff63132b232db76bc70a56771413701e9745471
NalaGinrut/artanis
utils.scm
-*- indent - tabs - mode : nil ; coding : utf-8 -*- ;; Copyright (C) 2013,2014,2015,2016,2017,2018 " Mu Lei " known as " NalaGinrut " < > Artanis is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License and GNU Lesser General Public License published by the Free Software Foundation , either version 3 of the License , or ( at your option ) ;; any later version. Artanis 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 and GNU Lesser General Public License ;; for more details. You should have received a copy of the GNU General Public License ;; and GNU Lesser General Public License along with this program. ;; If not, see </>. (define-module (artanis utils) #:use-module (artanis crypto md5) #:use-module (artanis crypto sha-1) #:use-module (artanis crypto sha-2) #:use-module (artanis crypto base64) #:use-module (artanis tpl sxml) #:use-module (artanis config) #:use-module (artanis irregex) #:use-module (artanis env) #:use-module (artanis mime) #:use-module (system foreign) #:use-module (ice-9 rdelim) #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw) #:use-module (srfi srfi-1) #:use-module (srfi srfi-19) #:use-module (ice-9 local-eval) #:use-module (ice-9 receive) #:use-module (ice-9 q) #:use-module (ice-9 control) #:use-module (web http) #:use-module (web request) #:use-module (web uri) #:use-module ((rnrs) #:select (get-bytevector-all utf8->string put-bytevector bytevector-u8-ref string->utf8 bytevector-length make-bytevector bytevector-s32-native-ref bytevector? define-record-type record-rtd record-accessor get-string-all)) #:export (regexp-split hash-keys cat bv-cat get-global-time sanitize-response build-response write-response get-local-time string->md5 unsafe-random uri-encode uri-decode response-version response-code response-connection request-headers response-port write-response-body read-request request-uri request-method request-content-length request-port read-request-body response-content-length get-file-ext get-global-date get-local-date string-substitute nfx static-filename remote-info seconds-now local-time-stamp parse-date write-date make-expires export-all-from-module! alist->hashtable expires->time-utc local-eval-string time-expired? valid-method? mmap munmap get-random-from-dev string->byteslist string->sha-1 string->sha-224 string->sha-256 string->sha-384 string->sha-512 list-slice bv-slice uni-basename checkout-the-path make-string-template guess-mime prepare-headers new-stack new-queue stack-slots queue-slots stack-pop! stack-push! stack-top stack-empty? queue-out! queue-in! queue-head queue-tail queue-empty? list->stack list->queue stack-remove! queue-remove! queue->list stack->list queue-length stack-length plist->alist make-db-string-template non-list? keyword->string range oah->handler oah->opts string->keyword alist->klist alist->kblist is-hash-table-empty? symbol-downcase symbol-upcase normalize-column run-before-run! sxml->xml-string run-after-request! run-before-response! make-pipeline HTML-entities-replace eliminate-evil-HTML-entities generate-kv-from-post-qstr handle-proper-owner generate-data-url verify-ENTRY exclude-dbd draw-expander remove-ext scan-app-components cache-this-route! dump-route-from-cache generate-modify-time delete-directory handle-existing-file check-drawing-method DEBUG subbv->string subbv=? bv-read-line bv-read-delimited put-bv bv-u8-index bv-u8-index-right build-bv-lookup-table filesize plist-remove gen-migrate-module-name try-to-load-migrate-cache flush-to-migration-cache gen-local-conf-file with-dbd call-with-sigint define-box-type make-box-type unbox-type ::define did-not-specify-parameter colorize-string-helper colorize-string WARN-TEXT ERROR-TEXT REASON-TEXT NOTIFY-TEXT STATUS-TEXT get-trigger get-family get-addr request-path response-keep-alive? request-keep-alive? procedure-name->string proper-toplevel gen-content-length make-file-sender file-sender? file-sender-size file-sender-thunk get-string-all-with-detected-charset make-unstop-exception-handler artanis-log exception-from-client exception-from-server render-sys-page bv-copy/share bv-backward artanis-list-matches get-syspage artanis-sys-response char-predicate handle-upload is-valid-table-name? is-guile-compatible-server-core?) #:re-export (the-environment)) ;; There's a famous rumor that 'urandom' is safer, so we pick it. (define* (get-random-from-dev #:key (length 8) (uppercase #f)) (call-with-input-file "/dev/urandom" (lambda (port) (let* ((bv ((@ (rnrs) get-bytevector-n) port length)) (str (format #f "~{~2,'0x~}" ((@ (rnrs) bytevector->u8-list) bv)))) (if uppercase (string-upcase str) str))))) (define uri-decode (@ (web uri) uri-decode)) (define uri-encode (@ (web uri) uri-encode)) (define parse-date (@@ (web http) parse-date)) (define write-date (@@ (web http) write-date)) (define build-response (@ (web response) build-response)) (define write-response (@ (web response) write-response)) (define response-version (@ (web response) response-version)) (define response-code (@ (web response) response-code)) (define response-connection (@ (web response) response-connection)) (define response-port (@ (web response) response-port)) (define write-response-body (@ (web response) write-response-body)) (define response-content-length (@ (web response) response-content-length)) (define read-request (@ (web request) read-request)) (define read-request-body (@ (web request) read-request-body)) (define request-uri (@ (web request) request-uri)) (define request-headers (@ (web request) request-headers)) (define request-method (@ (web request) request-method)) (define request-content-length (@ (web request) request-content-length)) (define request-port (@ (web request) request-port)) (define-syntax-rule (local-eval-string str e) (local-eval (call-with-input-string (format #f "(begin ~a)" str) read) e)) (define (alist->hashtable al) (let ((ht (make-hash-table))) (for-each (lambda (x) (hash-set! ht (car x) (cadr x))) al) ht)) (eval-when (eval load compile) (define (export-all-from-module! module-name) (let ((mod (resolve-module module-name))) (module-for-each (lambda (s m) (module-add! (current-module) s m)) mod)))) (define (time-expired? expires) (if expires (let ((t (expires->time-utc expires))) (time>? (current-time) t)) #t)) ;; no expired, means session cookie, which is always expired (define (expires->time-utc str) (date->time-utc (parse-date str))) (define (make-expires sec) (get-local-time (+ (seconds-now) sec))) (define (seconds-now) ((@ (guile) current-time))) ;; This function only used for local logger (define (local-time-stamp) (strftime "%F %T" (localtime (seconds-now)))) ;; default time is #f, get current time (define* (get-global-time #:optional (time #f) (nsec 0)) (call-with-output-string (lambda (port) ;; NOTE: (time-utc->data t 0) to get global time. (write-date (time-utc->date (if time (make-time 'time-utc nsec time) (current-time)) 0) port)))) ;; default time is #f, get current time (define* (get-local-time #:optional (time #f) (nsec 0)) (call-with-output-string (lambda (port) ;; NOTE: (time-utc->data t) to get local time. (write-date (time-utc->date (if time (make-time 'time-utc nsec time) (current-time))) port)))) (define* (regexp-split regex str #:optional (flags 0)) (let ((ret (fold-matches regex str (list '() 0 str) (lambda (m prev) (let* ((ll (car prev)) (start (cadr prev)) (tail (match:suffix m)) (end (match:start m)) (s (substring/shared str start end)) (groups (map (lambda (n) (match:substring m n)) (iota (1- (match:count m)) 1)))) (list `(,@ll ,s ,@groups) (match:end m) tail))) flags))) `(,@(car ret) ,(caddr ret)))) (define (hash-keys ht) (hash-map->list (lambda (k v) k) ht)) ;; WARN: besure that you've already checked the file exists before!!! (define* (cat file/port #:optional (out (current-output-port))) (define get-string-all (@ (rnrs io ports) get-string-all)) (let ((str (if (port? file/port) (get-string-all file/port) (call-with-input-file file/port get-string-all)))) (if out (display str out) str))) ;; WARN: besure that you've already checked the file existtance before!!! (define* (bv-cat file/port #:optional (out (current-output-port))) (define get-bytevector-all (@ (rnrs io ports) get-bytevector-all)) (let ((bv (if (port? file/port) (get-bytevector-all file/port) (call-with-input-file file/port get-bytevector-all)))) (if out (display bv out) bv))) 35147 is the length of in bytes (define* (unsafe-random #:optional (n 35147)) (random n (random-state-from-platform))) (define (string-substitute str re what) (regexp-substitute/global #f re str 'pre what 'post)) (define-syntax get-file-ext (syntax-rules () ((_ filename) (substring/shared filename (1+ (string-index-right filename #\.)))))) (define* (get-global-date #:optional (time #f)) (parse-header 'date (if time (get-global-time (car time) (cdr time)) (get-global-time)))) (define* (get-local-date #:optional (time #f)) (parse-header 'date (if time (get-local-time (car time) (cdr time)) (get-local-time)))) (define (nfx exp) (let lp((rest exp) (result '()) (cur #f)) (cond ((null? rest) result) ((null? result) (let ((e (list (cadr rest) (car rest) (caddr rest)))) (lp (cdddr rest) e (car rest)))) (else (let ((e (list cur result (cadr rest)))) (lp (cddr rest) e #f)))))) (define-syntax-rule (static-filename path) (if (current-toplevel) (format #f "~a/~a" (current-toplevel) path) (format #f "./~a" path))) (define-syntax-rule (request-ip req) TODO : support in the future (if (port-filename (request-port req)) ;; Valid socket port (inet-ntop AF_INET (sockaddr:addr (getpeername (request-port req)))) "localtest")) ; fake hostname for testing (define-syntax-rule (remote-info req) (if (get-conf '(server nginx)) (assoc-ref (request-headers req) 'x-real-ip) (request-ip req))) (define *methods-list* '(HEAD GET POST PUT PATCH DELETE)) (define (allowed-method? method) ;; TODO: check allowed method from config #t) (define (valid-method? method) (if (and (member method *methods-list*) (allowed-method? method)) method (throw 'artanis-err 405 valid-method? "invalid HTTP method `~a'" method))) ;; -------------- mmap --------------------- (define-public ACCESS_COPY #x3) (define-public ACCESS_READ #x1) (define-public ACCESS_WRITE #x2) (define-public ALLOCATIONGRANULARITY #x1000) (define-public PROT_READ #x1) (define-public PROT_WRITE #x2) (define-public PROT_EXEC #x4) (define-public PROT_SEM #x8) (define-public PROT_NONE #x0) (define-public PROT_GROWSDOWN #x01000000) (define-public PROT_GROWSUP #x02000000) (define-public PAGESIZE #x1000) (define-public MAP_ANON #x20) (define-public MAP_DENYWRITE #x800) (define-public MAP_EXECUTABLE #x1000) (define-public MAP_SHARED #x01) (define-public MAP_PRIVATE #x02) (define-public MAP_TYPE #x0f) (define-public MAP_FIXED #x10) (define-public MAP_ANONYMOUS #x20) (define-public MAP_UNINITIALIZED 0) ;; don't support map uninitialized (define *libc-ffi* (dynamic-link)) (define %mmap (pointer->procedure '* (dynamic-func "mmap" *libc-ffi*) (list '* size_t int int int size_t) #:return-errno? #t)) (define %munmap (pointer->procedure int (dynamic-func "munmap" *libc-ffi*) (list '* size_t) #:return-errno? #t)) (define* (mmap size #:key (addr %null-pointer) (fd -1) (prot MAP_SHARED) (flags PROT_READ) (offset 0) (bv? #f)) (let ((ret (if bv? (lambda (p) (pointer->bytevector p size)) identity))) (ret (%mmap addr size prot flags fd offset)))) (define (munmap bv/pointer size) (cond ((bytevector? bv/pointer) (%munmap (bytevector->pointer bv/pointer size) size)) ((pointer? bv/pointer) (%munmap bv/pointer size)))) ;; FIXME: what if len is not even? (define (string->byteslist str step base) (define len (string-length str)) (let lp((ret '()) (i 0)) (cond ((>= i len) (reverse ret)) ((zero? (modulo i step)) (lp (cons (string->number (substring/shared str i (+ i step)) base) ret) (1+ i))) (else (lp ret (1+ i)))))) (define (string->md5 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-1 "need string or bytevector!" str/bv))))) (md5->string (md5 in)))) (define (string->sha-1 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-1 "need string or bytevector!" str/bv))))) (sha-1->string (sha-1 in)))) (define (string->sha-224 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-224 "need string or bytevector!" str/bv))))) (sha-224->string (sha-224 in)))) (define (string->sha-256 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-256 "need string or bytevector!" str/bv))))) (sha-256->string (sha-256 in)))) (define (string->sha-384 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-384 "need string or bytevector!" str/bv))))) (sha-384->string (sha-384 in)))) (define (string->sha-512 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-512 "need string or bytevector!" str/bv))))) (sha-512->string (sha-512 in)))) (define-syntax list-slice (syntax-rules (:) ((_ ll lo : hi) (let ((len (length ll))) (and (<= lo len) (>= len hi) (let lp((rest ll) (result '()) (cnt 1)) (cond ((null? rest) (error "no")) ((<= cnt lo) (lp (cdr rest) result (1+ cnt))) ((> cnt hi) (reverse result)) (else (lp (cdr rest) (cons (car rest) result) (1+ cnt)))))))) ((_ ll lo :) (drop ll lo)) ((_ ll : hi) (take ll hi)))) ;; TODO: 1 . ( > hi ( bytevector - length bv ) ) 2 . ( < lo 0 ) wrap reference (define (%bv-slice bv lo hi) (let* ((len (- hi lo)) (slice ((@ (rnrs) make-bytevector) len))) ((@ (rnrs) bytevector-copy!) bv lo slice 0 len) slice)) NOT SAFE % bytevector - slice for GC , need ;;(define (%bytevector-slice bv lo hi) ;; (and (< hi lo) (error %bytevector-slice "wrong range" lo hi)) ( let * ( ( ptr ( bytevector->pointer bv ) ) ( addr ( pointer - address ptr ) ) ;; (la (+ addr lo)) ;; (len (- hi lo))) ;; (pointer->bytevector (make-pointer la) len))) (define-syntax bv-slice (syntax-rules (:) ((_ bv lo : hi) (%bv-slice bv lo hi)) ((_ bv lo :) (%bv-slice bv lo ((@ (rnrs bytevectors) bytevector-length) bv))) ((_ bv : hi) (%bv-slice bv 0 hi)))) get the unified basename both POSIX and WINDOWS (define (uni-basename filename) (substring filename (1+ (string-index-right filename (lambda (c) (or (char=? c #\\) (char=? c #\/))))))) ;; FIXME: checkout-the-path only support POSIX file path ;; FIXME: what's the proper default mode for the dir? (define* (checkout-the-path path #:optional (mode #o775)) (define (->path p) (let ((pp (irregex-split "/" p))) (if (char=? (string-ref p 0) #\/) (cons (string-append "/" (car pp)) (cdr pp)) pp))) (let ((paths (->path path))) (let lp((next paths) (last "")) (cond ((null? next) #t) ((string-null? (car next)) (lp (cdr next) last)) (else (let ((now-path (string-append last (car next) "/"))) (cond ((file-exists? now-path) (lp (cdr next) now-path)) (else (mkdir now-path mode) (lp (cdr next) now-path))))))))) ;; NOTE: This my original verion of make-string-template ;; (define *stpl-SRE* '(or (=> tilde "~") ;; (=> dollar "$$") ;; (: "${" (=> name (+ (~ #\}))) "}"))) ;; (define* (make-string-template str #:optional (mode #f) . opts) ;; (define ll '()) ; list for all keywords ;; (define lv '()) ; list for default value ;; (define template ;; (irregex-replace/all ;; ;;"(\\$\\{([^$])+\\})" ;; *stpl-SRE* str ;; (lambda (m) ;; (cond ;; ((irregex-match-substring m 'dollar) "$") ;; ((irregex-match-substring m 'tilde) "~~") ;; (else ;; (let* ((var (irregex-match-substring m 1)) ( key ( symbol->keyword ( string->symbol ;; (irregex-match-substring m 'name)))) ;; (v (kw-arg-ref opts key))) ;; (and v (set! lv (cons (cons key v) lv))) ; default value ;; (set! ll (cons key ll)) ;; (set! lk (cons var lk)) ;; "~a")))))) ;; (lambda args ;; (let ((vals (map (lambda (x) ;; (or (kw-arg-ref args x) (assoc-ref lv x) ;; (if mode (assoc-ref lk x) "NONE"))) ll))) ;; (format #f "~?" template (reverse vals))))) ;; NOTE: This is mark_weaver version for efficiency, Thanks mark! (define (%make-string-template mode template . defaults) (define irx (sre->irregex '(or (=> dollar "$$") (: "${" (=> var (+ (~ #\}))) "}")))) (define (->string obj) (if (string? obj) obj (object->string obj))) (define (get-the-val lst key) (let ((str (kw-arg-ref lst key))) (case mode ((normal) str) ((db) (string-concatenate (list "\"" (->string str) "\""))) (else (throw 'artanis-err 500 %make-string-template "invalid mode `~a'" mode))))) (define (optimize rev-items tail) (cond ((null? rev-items) tail) ((not (string? (car rev-items))) (optimize (cdr rev-items) (cons (car rev-items) tail))) (else (receive (strings rest) (span string? rev-items) (let ((s (string-concatenate-reverse strings))) (if (string-null? s) (optimize rest tail) (optimize rest (cons s tail)))))))) (define (match->item m) (or (and (irregex-match-substring m 'dollar) "$") (let* ((name (irregex-match-substring m 'var)) (key (symbol->keyword (string->symbol name)))) (cons key (kw-arg-ref defaults key))))) (let* ((rev-items (irregex-fold irx (lambda (idx m tail) (cons* (match->item m) (substring template idx (irregex-match-start-index m 0)) tail)) '() template (lambda (idx tail) (cons (substring template idx) tail)))) (items (optimize rev-items '()))) (lambda keyword-args (define (item->string item) (if (string? item) item (or (and=> (get-the-val keyword-args (car item)) ->string) (cdr item) ; default value ""))) (string-concatenate (map item->string items))))) ;; the normal mode, no double quotes for vals (define (make-string-template tpl . vals) (apply %make-string-template 'normal tpl vals)) ;; DB str tpl will treat all values with double quotes, for SQL (define (make-db-string-template tpl . vals) (apply %make-string-template 'db tpl vals)) (define (guess-mime filename) (mime-guess (get-file-ext filename))) (define (bytevector-null? bv) ((@ (rnrs bytevectors) bytevector=?) bv #u8())) (define (generate-modify-time t) (get-local-date (cons (time-second t) (time-nanosecond t)))) (define (prepare-headers headers) (define *default-headers* `((content-type . (text/html (charset . ,(get-conf '(server charset))))) (date . ,(get-global-date)))) (lset-union (lambda (x y) (eq? (car x) (car y))) (assq-remove! headers 'last-modified) *default-headers*)) (define new-stack make-q) (define new-queue make-q) (define stack-slots car) (define queue-slots car) (define (%q-remove-with-key! q key) (assoc-remove! (car q) key) (sync-q! q)) (define stack-pop! q-pop!) (define stack-push! q-push!) (define stack-top q-front) (define stack-remove! %q-remove-with-key!) (define stack-empty? q-empty?) (define stack-length q-length) (define (stack->list stk) (list-copy (stack-slots stk))) (define queue-out! q-pop!) (define queue-in! enq!) (define queue-head q-front) (define queue-tail q-rear) (define queue-remove! %q-remove-with-key!) (define queue-empty? q-empty?) (define queue-length q-length) (define (queue->list q) (list-copy (queue-slots q))) NOTE : make - stack exists in (for-each (lambda (x) (stack-push! stk x)) lst) stk) (define* (list->queue lst #:optional (queue (new-queue))) (for-each (lambda (x) (queue-in! queue x)) lst) queue) ;; NOTE: keyword could be the value, so this version is correct. (define (plist->alist lst) (let lp((next lst) (ret '())) (match next (() (reverse ret)) ((k v . rest) (lp (cddr next) (acons (keyword->symbol k) v ret)))))) (define-syntax-rule (non-list? x) (not (list? x))) (define* (keyword->string x #:optional (proc identity)) (proc (symbol->string (keyword->symbol x)))) (define* (range from to #:optional (step 1)) (iota (- to from) from step)) ;; NOTE: handler must be the last element of the list, it's should be error ;; if it's not so. (define (oah->handler opts-and-handler) (let ((handler (and (list? opts-and-handler) (last opts-and-handler)))) (if (or (procedure? handler) (string? handler)) handler (error oah->handler "You have to specify a handler for this rule!")))) ;; get all kw-args from the middle of args (define (oah->opts opts-and-handler) (if (procedure? opts-and-handler) '() ; there's no opts (let lp((next opts-and-handler) (kl '()) (vl '())) (match next (((? keyword? k) v rest ...) (lp rest (cons k kl) (cons v vl))) ((or (? null?) (? procedure?)) ;; no opts left, return the result (list kl vl)) (else (lp (cdr next) kl vl)))))) (define (string->keyword str) (symbol->keyword (string->symbol str))) (define (alist->klist al) (let lp((next al) (ret '())) (cond ((null? next) ret) (else (let ((k (symbol->keyword (car (car next)))) (v (cdr (car next)))) (lp (cdr next) (cons k (cons v ret)))))))) (define (alist->kblist al) (let lp((next al) (ret '())) (cond ((null? next) ret) (else (let ((k (string->keyword (string-append ":" (car (car next))))) (v (cdr (car next)))) (lp (cdr next) (cons k (cons v ret)))))))) (define (is-hash-table-empty? ht) (zero? (hash-count values ht))) (define (symbol-strop proc sym) (string->symbol (proc (symbol->string sym)))) (define (symbol-downcase sym) (symbol-strop string-downcase sym)) (define (symbol-upcase sym) (symbol-strop string-upcase sym)) (define* (normalize-column col #:optional (ci? #f)) (define-syntax-rule (-> c p) (if ci? (p col) col)) (cond ((string? col) (string->symbol (-> c string-downcase))) ((symbol? col) (-> col symbol-downcase)) ((keyword? col) (normalize-column (keyword->string col) ci?)) (else (throw 'artanis-err 500 normalize-column "Invalid type of column `~a'" col)))) (define* (sxml->xml-string sxml #:key (escape? #f)) (call-with-output-string (lambda (port) (sxml->xml sxml port escape?)))) (define (run-after-request! proc) (add-hook! *after-request-hook* proc)) (define (run-before-response! proc) (add-hook! *before-response-hook* proc)) (define (run-before-run! proc) (add-hook! *before-run-hook* proc)) ;; NOTE: For `pipeline' methodology, please read my post: ;; -pipeline-style%21 (define (make-pipeline . procs) (lambda (x) (fold (lambda (y p) (y p)) x procs))) (define (HTML-entities-replace set content) (define in (open-input-string content)) (define (hit? c/str) (assoc-ref set c/str)) (define (get-estr port) (let lp((n 0) (ret '())) (cond ((= n 3) (list->string (reverse! ret))) (else (lp (1+ n) (cons (read-char port) ret)))))) (call-with-output-string (lambda (out) (let lp((c (peek-char in))) (cond ((eof-object? c) #t) ((hit? c) => (lambda (str) (display str out) (read-char in) (lp (peek-char in)))) ((char=? c #\%) (let* ((s (get-estr in)) (e (hit? s))) (if e (display e out) (display s out)) (lp (peek-char in)))) (else (display (read-char in) out) (lp (peek-char in)))))))) (define *terrible-HTML-entities* '((#\< . "&lt;") (#\> . "&gt;") (#\& . "&amp;") (#\" . "&quot;") ("%3C" . "&lt;") ("%3E" . "&gt;") ("%26" . "&amp;") ("%22" . "&quot;"))) NOTE : cooked for anti - XSS . (define (eliminate-evil-HTML-entities content) (HTML-entities-replace *terrible-HTML-entities* content)) (define* (generate-kv-from-post-qstr body #:key (no-evil? #f) (key-converter identity)) (define cook (if no-evil? eliminate-evil-HTML-entities identity)) (define (%convert lst) (match lst ((k v) (list (key-converter k) ((current-encoder) v))) (else (throw 'artanis-err 500 generate-kv-from-post-qstr "Fatal! Can't be here!" lst)))) (define (-> x) (string-trim-both x (lambda (c) (member c '(#\sp #\: #\return))))) (map (lambda (x) (%convert (map -> (string-split (cook x) #\=)))) (string-split (utf8->string body) #\&))) NOTE : We accept warnings , which means if warnings occurred , it 'll be 200(OK ) anyway , but ;; Artanis will throw warnings in the server-side log. NOTE : We * DO NOT * accept errors , which means if errors occurred , Artanis will throw 500 . (define (handle-proper-owner file uid gid) (define-syntax-rule (print-the-warning exe reason) (format (current-error-port) "[WARNING] '~a' encountered system error: ~s~%" exe reason)) (define-syntax-rule (->err-reason exe reason) (format #f "'~a' encoutered system error: ~s" exe reason)) (catch 'system-error (lambda () (chown file (or uid (getuid)) (or gid (getgid)))) (lambda (k . e) (let ((exe (car e)) (reason (caaddr e))) (match (cons k reason) ('(system-error . "Operation not permitted") (print-the-warning exe reason) (display "Maybe you run Artanis as unprivileged user? (say, not as root)\n" (current-error-port))) ('(system-error . "No such file or directory") (throw 'artanis-err 500 handle-proper-owner (->err-reason exe reason) file)) (else (apply throw k e))))))) ;; According to wiki, here's the standard format of data_url_scheme: ;; data:[<MIME-type>][;charset=<encoding>][;base64],<data> (define* (generate-data-url bv/str #:key (mime 'application/octet-stream) (crypto 'base64) (charset 'utf-8)) (define-syntax-rule (->crypto) (match crypto ((or 'base64 "base64") ";base64") (else ""))) (define-syntax-rule (->charset) (if (or (string? charset) (symbol? charset)) (format #f ",charset=~a" charset) "")) (define-syntax-rule (->mime) (match mime (`(guess ,ext) (or (mime-guess ext) 'application/octet-stream)) ((or (? symbol?) (? string?)) (or (and (get-conf 'debug-mode) (mime-check mime) (format #f "~a" mime)) (format #f "~a" mime))) (else (throw 'artanis-err 500 generate-data-url "Invalid MIME! Should be symbol or string" mime)))) (let ((b64 (base64-encode bv/str))) (string-concatenate (list "data:" (->mime) (->crypto) (->charset) "," b64)))) (define (verify-ENTRY entry) (format #t "entry: ~a~%" entry) (cond ((not (file-exists? entry)) (format (artanis-current-output) "ENTRY file is missing!~%") #f) (else (let ((line (call-with-input-file entry read-line))) (string=? line ";; This an Artanis ENTRY file, don't remove it!"))))) (define-syntax draw-expander (syntax-rules (rule options method) ((_ (options options* ...) rest rest* ...) `(,@(list options* ...) ,@(draw-expander rest rest* ...))) ((_ (method method*) rest rest* ...) `((method ,'method*) ,@(draw-expander rest rest* ...))) ((_ (rule url) rest rest* ...) `((rule ,url) ,@(draw-expander rest rest* ...))) ((_ handler) (list handler)))) (define (remove-ext str) (let ((i (string-contains str "."))) (substring str 0 i))) (define (scan-app-components component) (let ((toplevel (current-toplevel))) (map (lambda (f) (string->symbol (remove-ext f))) (scandir (format #f "~a/app/~a/" toplevel component) (lambda (f) (not (or (string=? f ".") (string=? f "..") (string=? f ".gitkeep")))))))) (define (cache-this-route! url meta) (define (write-header port) (format port ";; Do not touch anything!!!~%") (format port ";; All things here should be automatically handled properly!!!~%")) (define route-cache (string-append (current-toplevel) "/tmp/cache/route.cache")) (when (or (not (file-exists? route-cache)) (and (not url) (not meta))) ; for regenerating route cache (format (artanis-current-output) "Route cache is missing, regenerating...~%") (call-with-output-file route-cache (lambda (port) (write-header port) (write '() port)))) (when (and url meta) (let ((rl (call-with-input-file route-cache read))) (delete-file route-cache) (call-with-output-file route-cache (lambda (port) (flock port LOCK_EX) (write-header port) (if (eof-object? rl) (write '() port) (write (assoc-set! rl url (drop-right meta 1)) port)) (flock port LOCK_UN)))))) (define (dump-route-from-cache) (define toplevel (current-toplevel)) (define route-cache (string-append toplevel "/tmp/cache/route.cache")) (define route (string-append toplevel "/.route")) (define (load-customized-router) (let ((croute (string-append toplevel "conf/route"))) (cond ((not (file-exists? croute)) #t) ; No customized route (else black magic to make happy (load croute))))) (when (file-exists? route) (delete-file route)) (when (not (file-exists? route-cache)) (cache-this-route! #f #f) (dump-route-from-cache)) (let ((rl (call-with-input-file route-cache read))) (cond ((eof-object? rl) (cache-this-route! #f #f) (dump-route-from-cache)) (else (call-with-output-file route (lambda (port) (for-each (lambda (r) (let* ((meta (cdr r)) (rule (assq-ref meta 'rule)) (method (assq-ref meta 'method))) (format port "~2t(~a ~s)~%" (if method method 'get) (if rule rule (car r))))) rl))) ;; load customized router (load-customized-router))))) (define* (delete-directory dir #:optional (checkonly? #f)) (cond ((and (file-is-directory? dir) (file-exists? dir)) (system (format #f "rm -f ~a" dir))) (else (and (not checkonly?) (error delete-directory "Not a directory or doesn't exist " dir))))) ;; TODO: handle it more elegantly (define* (handle-existing-file path #:optional (dir? #f)) (let* ((pp (if dir? (dirname path) path)) (component (basename (dirname pp))) (name (car (string-split (basename pp) #\.)))) (cond ((draw:is-force?) (if (file-is-directory? path) (delete-directory path) (delete-file path))) ((draw:is-skip?) (format (artanis-current-output) "skip ~10t app/~a/~a~%" component name)) (else (format (artanis-current-output) "~a `~a' exists! (Use --force/-f to overwrite or --skip/-s to ignore)~%" (string-capitalize component) name) (exit 1))))) ;; Check if all methods are valid (define (check-drawing-method lst) (define errstr "Invalid drawing method, shouldn't contain '/' ") (for-each (lambda (name) (when (not (irregex-match "[^/]+" name)) (error check-drawing-method errstr name))) lst) lst) (define (subbv->string bv encoding start end) (call-with-output-string (lambda (port) (set-port-encoding! port encoding) (put-bytevector port bv start (- end start))))) (define* (bv-u8-index bv u8 #:optional (time 1)) (let ((len (bytevector-length bv))) (let lp((i 0) (t 1)) (cond ((>= i len) #f) ((= (bytevector-u8-ref bv i) u8) (if (= t time) i (lp (1+ i) (1+ t)))) (else (lp (1+ i) t)))))) (define* (bv-u8-index-right bv u8 #:optional (time 1)) (let ((len (bytevector-length bv))) (let lp((i (1- len)) (t 1)) (cond ((< i 0) #f) ((= (bytevector-u8-ref bv i) u8) (if (= t time) i (lp (1- i) (1+ t)))) (else (lp (1- i) t)))))) (define* (subbv=? bv bv2 #:optional (start 0) (end (1- (bytevector-length bv)))) (and (<= (bytevector-length bv2) (bytevector-length bv)) (let lp((i end) (j (1- (bytevector-length bv2)))) (cond ((< i start) #t) ((= (bytevector-u8-ref bv i) (bytevector-u8-ref bv2 j)) (lp (1- i) (1- j))) (else #f))))) return position after (define* (bv-read-delimited bv delim #:optional (start 0) (end (bytevector-length bv))) (define len (- end start -1)) (let lp((i start)) (cond ((> i end) #f) ((= (bytevector-u8-ref bv i) delim) i) (else (lp (1+ i)))))) ;; return position after newline (define* (bv-read-line bv #:optional (start 0) (end (bytevector-length bv))) (bv-read-delimited bv 10 start end)) (define (put-bv port bv from to) (put-bytevector port bv from (- to from 2))) ;; TODO: build a char occurence indexing table (define (build-bv-lookup-table bv) (let ((ht (make-hash-table))) (for-each (lambda (i) (hash-set! ht (bytevector-u8-ref bv i) #t)) (iota (bytevector-length bv))) ht)) (define Gbytes (ash 1 30)) (define Mbytes (ash 1 20)) (define Kbytes (ash 1 10)) (define (filesize size) (cond ((>= size Gbytes) (format #f "~,1fGiB" (/ size Gbytes))) ((>= size Mbytes) (format #f "~,1fMiB" (/ size Mbytes))) ((>= size Kbytes) (format #f "~,1fKiB" (/ size Kbytes))) (else (format #f "~a Bytes" size)))) (define* (plist-remove lst k #:optional (no-value? #f)) (let lp((next lst) (kk '__) (ret '())) (cond ((null? next) (values (reverse ret) kk)) ((eq? (car next) k) (if no-value? (lp (cdr next) (car next) ret) (lp (cddr next) (list (car next) (cadr next)) ret))) (else (lp (cdr next) kk (cons (car next) ret)))))) (define *name-re* (string->irregex "([^.]+)\\.scm")) (define (gen-migrate-module-name f) (cond ((irregex-search *name-re* (basename f)) => (lambda (m) (irregex-match-substring m 1))) (else (throw 'artanis-err 500 gen-migrate-module-name "Wrong parsing of module name, shouldn't be here!" f)))) (define (try-to-load-migrate-cache name) (let ((file (format #f "~a/tmp/cache/migration/~a.scm" (current-toplevel) name))) (cond ((file-exists? file) (load file)) (else (format (artanis-current-output) "[WARN] No cache for migration of `~a'~%" name) (format (artanis-current-output) "Run `art migrate up ~a', then try again!~%" name))))) (define (flush-to-migration-cache name fl) (let ((file (format #f "~a/tmp/cache/migration/~a.scm" (current-toplevel) name))) (when (file-exists? file) (delete-file file)) (call-with-output-file file (lambda (port) (format port "(define-~a~%" name) (for-each (lambda (ft) (format port "~2t~a~%" ft)) fl) (format port "~2t)~%"))))) (define (gen-local-conf-file) (format #f "~a/conf/artanis.conf" (current-toplevel))) (define-syntax-rule (with-dbd dbd0 body ...) (let ((dbd1 (get-conf '(db dbd)))) (cond ((or (and (list? dbd0) (memq dbd1 dbd0)) (eq? dbd1 dbd0)) body ...) (else (throw 'artanis-err 500 'with-dbd "This is only supported by `~a', but the current dbd is `~a'" dbd0 dbd1 'body ...))))) (define-syntax-rule (exclude-dbd dbds body ...) (let ((dbd (get-conf '(db dbd)))) (cond ((memq dbd dbds) (throw 'artanis-err 500 'exclude-dbd "This isn't supported by `~a', please check it out again!" dbds 'body ...)) (else body ...)))) (define-syntax-rule (DEBUG fmt args ...) (when (get-conf 'debug-mode) (format (artanis-current-output) fmt args ...))) (define call-with-sigint (if (not (provided? 'posix)) (lambda (thunk handler-thunk) (thunk)) (lambda (thunk handler-thunk) (let ((handler #f)) (catch 'interrupt (lambda () (dynamic-wind (lambda () (set! handler (sigaction SIGINT (lambda (sig) (throw 'interrupt))))) thunk (lambda () (if handler ;; restore Scheme handler, SIG_IGN or SIG_DFL. (sigaction SIGINT (car handler) (cdr handler)) ;; restore original C handler. (sigaction SIGINT #f))))) (lambda (k . _) (handler-thunk))))))) (define-syntax-rule (define-box-type name) (define-record-type name (fields treasure))) (define-macro (make-box-type bt v) (list (symbol-append 'make- bt) v)) (define-syntax-rule (box-type-treasure t) (record-accessor (record-rtd t) 0)) (define-syntax-rule (unbox-type t) (let ((treasure-getter (box-type-treasure t))) (treasure-getter t))) (define (socket-port? sp) (and (port? sp) (eq? (port-filename sp) 'socket))) (define (detect-type-name o) (define r6rs-record? (@ (rnrs) record?)) (define r6rs-record-type-name (@ (rnrs) record-type-name)) (define guile-specific-record? (@ (guile) record?)) (define (guile-specific-record-name o) ((@ (guile) record-type-name) ((@ (guile) record-type-descriptor) o))) (cond ;; NOTE: record? is for R6RS record-type, but record-type? is not ((r6rs-record? o) (r6rs-record-type-name (record-rtd o))) ((guile-specific-record? o) (guile-specific-record-name o)) ((symbol? o) 'symbol) ((string? o) 'string) ((integer? o) (if (positive? o) '+int '-int)) ((number? o) 'num) ((thunk? o) 'thunk) ((procedure? o) 'proc) ((vector? o) 'vector) ((pair? o) 'pair) ((list? o) 'list) ((bytevector? o) 'bv) ((port? o) 'port) ((boolean? o) 'boolean) (else 'ANY))) (define (check-args-types op args) (define (check-eq? actual-type expect-type) (case expect-type ((+int) (eq? actual-type '+int)) ((-int) (eq? actual-type '-int)) ((int) (memq actual-type '(-int +int))) (else (eq? expect-type actual-type)))) (match (procedure-property op 'type-anno) (((targs ...) '-> (func-types ...)) (for-each (lambda (v e) (or (eq? e 'ANY) (check-eq? (detect-type-name v) e) (begin (DEBUG "(~{~a~^ ~}) =? (~{~a~^ ~})~%" targs args) (throw 'artanis-err 500 check-args-types "~a: Argument ~a is a `~a' type, but I expect type `~a'" op v (detect-type-name v) e)))) args targs)) (else (throw 'artanis-err 500 check-args-types "Invalid type annotation `~a'" (procedure-property op 'type-anno))))) (define (check-function-types op fret) (match (procedure-property op 'type-anno) (((targs ...) '-> (func-types ...)) (for-each (lambda (v e) (or (eq? e 'ANY) (eq? (detect-type-name v) e) (throw 'artanis-err 500 check-function-types "`Return value ~a(~a) is expected to be type `~a'" v (detect-type-name v) e))) fret func-types)) (else (throw 'artanis-err 500 check-function-types "Invalid type annotation `~a'" (procedure-property op 'type-anno))))) (define (detect-and-set-type-anno! op ftypes atypes) (let ((type `(,atypes -> ,ftypes))) (set-procedure-property! op 'type-anno type) type)) ;; NOTE: This macro can detect multi return values. ;; TODO: 1 . support multi - types , say , string / bv , maybe not easy to do it faster ? (define-syntax ::define (syntax-rules (-> :anno:) ((_ (op args ...) (:anno: (targs ...) -> func-types ...) body ...) (begin (define (op args ...) (when (get-conf 'debug-mode) (check-args-types op (list args ...))) (call-with-values (lambda () body ...) (lambda ret (when (get-conf 'debug-mode) (eq? (detect-type-name ret) (check-function-types op ret))) (apply values ret)))) (detect-and-set-type-anno! op '(func-types ...) '(targs ...)))))) (define-syntax-rule (did-not-specify-parameter what) (format #f "`current-~a' isn't specified, it's likely a bug!" what)) ;; Text-coloring helper functions, borrowed from guile-colorized (define *color-list* `((CLEAR . "0") (RESET . "0") (BOLD . "1") (DARK . "2") (UNDERLINE . "4") (UNDERSCORE . "4") (BLINK . "5") (REVERSE . "6") (CONCEALED . "8") (BLACK . "30") (RED . "31") (GREEN . "32") (YELLOW . "33") (BLUE . "34") (MAGENTA . "35") (CYAN . "36") (WHITE . "37") (ON-BLACK . "40") (ON-RED . "41") (ON-GREEN . "42") (ON-YELLOW . "43") (ON-BLUE . "44") (ON-MAGENTA . "45") (ON-CYAN . "46") (ON-WHITE . "47"))) (define (get-color color) (assq-ref *color-list* color)) (define (generate-color colors) (let ((color-list (filter-map get-color colors))) (if (null? color-list) "" (string-append "\x1b[" (string-join color-list ";" 'infix) "m")))) (define* (colorize-string-helper color str control #:optional (rl-ignore #f)) (if rl-ignore (string-append "\x01" (generate-color color) "\x02" str "\x01" (generate-color control) "\x02") (string-append (generate-color color) str (generate-color control)))) (define* (colorize-string str color) "Example: (colorize-string \"hello\" '(BLUE BOLD))" (colorize-string-helper color str '(RESET) (using-readline?))) (define-syntax-rule (WARN-TEXT str) (colorize-string str '(YELLOW))) (define-syntax-rule (ERROR-TEXT str) (colorize-string str '(RED))) (define-syntax-rule (REASON-TEXT str) (colorize-string str '(CYAN))) (define-syntax-rule (NOTIFY-TEXT str) (colorize-string str '(WHITE))) (define-syntax-rule (STATUS-TEXT num) (colorize-string (object->string num)'(WHITE))) (define (get-trigger) (case (get-conf '(server trigger)) ((edge) (@ (artanis server epoll) EPOLLET)) ((level) 0) (else (throw 'artanis-err 500 get-trigger "Invalid (server trigger)!" (get-conf '(server trigger)))))) (define (get-family) (case (get-conf '(host family)) ((ipv4) AF_INET) ((ipv6) AF_INET6) (else (throw 'artanis-err 500 get-family "Invalid (host family)!" (get-conf '(host family)))))) (define (get-addr) (let ((host (get-conf '(host addr))) (family (get-family))) (if (and host (not (string=? host "127.0.0.1"))) (inet-pton family host) INADDR_LOOPBACK))) (define (request-path req) (uri-path (request-uri req))) (define (response-keep-alive? response) (let ((v (response-version response))) (and (or (< (response-code response) 400) (= (response-code response) 404)) (case (car v) ((1) (case (cdr v) ;; NOTE: HTTP/1.1 treat all connection keep-alive ;; unless it requires `close' explicityly ((1) (not (memq 'close (response-connection response)))) HTTP/1.0 needs explicit keep - alive notice ((0) (memq 'keep-alive (response-connection response))))) (else #f))))) ;; NOTE: The order matters (define (request-keep-alive? request) (or (equal? (request-upgrade request) '(websocket)) (equal? (request-connection request) '(keep-alive)) (equal? (request-version request) '(1 . 1)))) (define (procedure-name->string proc) (symbol->string (procedure-name proc))) (define-syntax-rule (proper-toplevel) (or (current-toplevel) "")) (define-record-type file-sender (fields size thunk)) (define (gen-content-length body) (let ((get-length (lambda () (cond ((bytevector? body) (bytevector-length body)) ((file-sender? body) (file-sender-size body)) ((string? body) (throw 'artanis-err 500 gen-content-length "BUG: body should have been converted to bytevector! ~a" body)) (else (throw 'artanis-err 500 gen-content-length "Invalid body ~a" body)))))) `(content-length . ,(if body (get-length) 0)))) (define (get-string-all-with-detected-charset filename) (call-with-input-file filename (lambda (port) (set-port-encoding! port (get-conf '(server charset))) (get-string-all port)))) (define (get-syspage file) (let ((local-syspage (format #f "~a/sys/pages/~a" (current-toplevel) file))) (if (file-exists? local-syspage) local-syspage (format #f "~a/~a" (get-conf '(server syspage path)) file)))) (define (syspage-show file) (bv-cat (get-syspage file) #f)) ;; ENHANCE: use colored output (define* (artanis-log blame-who? status mime #:key (port (current-error-port)) (request #f)) (case blame-who? ((client) (when (not request) (error "artanis-log: Fatal bug! Request shouldn't be #f here!~%")) (let* ((uri (request-uri request)) (path (uri-path uri)) (qstr (uri-query uri)) (method (request-method request))) (format port "[Remote] ~a @ ~a~%" (remote-info request) (local-time-stamp)) (format port "[Request] method: ~a, path: ~a, query: ~a~%" method path qstr) (format port "[Response] status: ~a, MIME: ~a~%~%" status mime))) ((server) (format port "[Server] ~a @ ~a~%" (get-conf '(host addr)) (local-time-stamp)) (format port "[Response] status: ~a, MIME: ~a~%~%" status mime)) (else (error "artanis-log: Fatal BUG here!")))) (define *guile-compatible-server-core* '(guile fibers)) (define (is-guile-compatible-server-core? name) (memq name *guile-compatible-server-core*)) (define (render-sys-page blame-who? status request) (define-syntax-rule (status->page s) (format #f "~a.html" s)) (artanis-log blame-who? status 'text/html #:request request) (let* ((charset (get-conf '(server charset))) (mtime (generate-modify-time (current-time))) (response (build-response #:code status #:headers `((server . ,(get-conf '(server info))) (last-modified . ,mtime) (content-type . (text/html (charset . ,charset)))))) (body (syspage-show (status->page status)))) (if (is-guile-compatible-server-core? (get-conf '(server engine))) (values response body) (values response body 'exception)))) (define (format-status-page/client status request) (format (current-error-port) (ERROR-TEXT "[EXCEPTION] ~a is abnormal request, status: ~a, ") (uri-path (request-uri request)) status) (display "rendering a sys page for it...\n" (current-error-port)) (render-sys-page 'client status request)) (define (format-status-page/server status) (format (current-error-port) "[SERVER ERROR] Internal error from server-side, ") (format (current-error-port) "rendering a ~a page for client ...~%" status) (render-sys-page 'server status #f)) (define (exception-from-client request) (lambda (status) (format-status-page/client status request))) (define (exception-from-server) (lambda (status) (format-status-page/server status))) (define *rf-re* (string->irregex ".*/artanis/artanis/(.*)$")) (define (->reasonable-file filename) (if (string? filename) (let ((m (irregex-search *rf-re* filename))) (if m (format #f "artanis/~a" (irregex-match-substring m 1)) filename)) "In unknown file")) (define-syntax-rule (make-unstop-exception-handler syspage-generator) (let ((port (current-error-port)) (filename (current-filename))) (lambda (k . e) (match e (((? procedure? subr) (? string? msg) . args) (format port "Captured in <~a>~%" (WARN-TEXT (->reasonable-file filename))) (when subr (format port "In procedure ~a :~%" (WARN-TEXT (procedure-name->string subr)))) (apply format port (REASON-TEXT (string-append "[REASON] " msg)) args) (newline port)) (((? integer? status) (or (? symbol? subr) (? procedure? subr)) (? string? msg) . args) (format port "HTTP ~a~%" (STATUS-TEXT status)) (format port "Captured in <~a>~%" (WARN-TEXT (->reasonable-file filename))) (when subr (format port "Threw in procedure ~a :~%" (WARN-TEXT (if (procedure? subr) (procedure-name->string subr) subr)))) (apply format port (REASON-TEXT (string-append "[REASON] " msg)) args) (newline port) (syspage-generator status)) (else (format port "~a - ~a~%" (WARN-TEXT "BUG: invalid exception format, but we throw it anyway!") e) (apply throw k e)))))) (define* (bv-copy/share bv #:key (from 0) (type 'vu8) (size (- (bytevector-length bv) from))) (when (> size (- (bytevector-length bv) from)) (error bv-copy/share (format #f "Size(~a) is larger than the length(~a) - from(~a)!" size (bytevector-length bv) from))) (when (>= from (bytevector-length bv)) (error bv-copy/share (format #f "Can't copy from the end of the bytevector (~a)!" from))) (let* ((ptr (bytevector->pointer bv)) (new-ptr (make-pointer (+ (pointer-address ptr) from)))) (pointer->bytevector new-ptr size 0 type))) (define* (bv-backward bv offset #:key (type 'vu8) (extend 0)) (let* ((ptr (bytevector->pointer bv)) (new-ptr (make-pointer (- (pointer-address ptr) offset))) (len (bytevector-length bv))) (pointer->bytevector new-ptr (+ len extend) 0 type))) (define (artanis-list-matches irx str) (let lp ((start 0) (ret '())) (let ((m (irregex-search irx str start))) (if m (lp (irregex-match-end-index m) (cons m ret)) ret)))) (define (artanis-sys-response status port bv-body) (build-response #:code status #:port port #:headers `((server . ,(get-conf '(server info))) ,(gen-content-length bv-body) (content-type . (text/html))))) (define (char-predicate string) (let ((cs (string->char-set string))) (lambda (c) (and (not (eof-object? c)) (char-set-contains? cs c))))) (define (handle-upload thunk) (catch 'system-error thunk (lambda e (let ((errno (system-error-errno e))) (cond ((= errno ENOMEM) NOTE : Out of memory , call ( gc ) and throw 507 (format (artanis-current-output) "No memory! Run GC now!~%") (gc) (throw 'artanis-err 507 handle-upload "Server is out of RAMs, please extend more RAMs!~%")) ((= errno EIO) NOTE : The storage device was disconnected , just throw 507 (throw 'artanis-err 507 handle-upload "Server is not available, maybe storage media was disconnected?~%")) ((= errno ENOSPC) NOTE : no space for uploading , just throw 507 (throw 'artanis-err 507 handle-upload "Server has insufficient storage space!~%")) (else ;; nothing noticed, re-throw it to next level. (apply throw e))))))) ;;for verify db table name (define invalid-char-set? (char-predicate "*&-{}[]?.\\%$#@!,")) (define is-valid-table-name? (lambda (name) (not (string-any invalid-char-set? name))))
null
https://raw.githubusercontent.com/NalaGinrut/artanis/3412d6eb5b46fde71b0965598ba085bacc2a6c12/artanis/utils.scm
scheme
coding : utf-8 -*- Copyright (C) 2013,2014,2015,2016,2017,2018 any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and GNU Lesser General Public License for more details. and GNU Lesser General Public License along with this program. If not, see </>. There's a famous rumor that 'urandom' is safer, so we pick it. no expired, means session cookie, which is always expired This function only used for local logger default time is #f, get current time NOTE: (time-utc->data t 0) to get global time. default time is #f, get current time NOTE: (time-utc->data t) to get local time. WARN: besure that you've already checked the file exists before!!! WARN: besure that you've already checked the file existtance before!!! Valid socket port fake hostname for testing TODO: check allowed method from config -------------- mmap --------------------- don't support map uninitialized FIXME: what if len is not even? TODO: (define (%bytevector-slice bv lo hi) (and (< hi lo) (error %bytevector-slice "wrong range" lo hi)) (la (+ addr lo)) (len (- hi lo))) (pointer->bytevector (make-pointer la) len))) FIXME: checkout-the-path only support POSIX file path FIXME: what's the proper default mode for the dir? NOTE: This my original verion of make-string-template (define *stpl-SRE* '(or (=> tilde "~") (=> dollar "$$") (: "${" (=> name (+ (~ #\}))) "}"))) (define* (make-string-template str #:optional (mode #f) . opts) (define ll '()) ; list for all keywords (define lv '()) ; list for default value (define template (irregex-replace/all ;;"(\\$\\{([^$])+\\})" *stpl-SRE* str (lambda (m) (cond ((irregex-match-substring m 'dollar) "$") ((irregex-match-substring m 'tilde) "~~") (else (let* ((var (irregex-match-substring m 1)) (irregex-match-substring m 'name)))) (v (kw-arg-ref opts key))) (and v (set! lv (cons (cons key v) lv))) ; default value (set! ll (cons key ll)) (set! lk (cons var lk)) "~a")))))) (lambda args (let ((vals (map (lambda (x) (or (kw-arg-ref args x) (assoc-ref lv x) (if mode (assoc-ref lk x) "NONE"))) ll))) (format #f "~?" template (reverse vals))))) NOTE: This is mark_weaver version for efficiency, Thanks mark! default value the normal mode, no double quotes for vals DB str tpl will treat all values with double quotes, for SQL NOTE: keyword could be the value, so this version is correct. NOTE: handler must be the last element of the list, it's should be error if it's not so. get all kw-args from the middle of args there's no opts no opts left, return the result NOTE: For `pipeline' methodology, please read my post: -pipeline-style%21 ") Artanis will throw warnings in the server-side log. According to wiki, here's the standard format of data_url_scheme: data:[<MIME-type>][;charset=<encoding>][;base64],<data> for regenerating route cache No customized route load customized router TODO: handle it more elegantly Check if all methods are valid return position after newline TODO: build a char occurence indexing table restore Scheme handler, SIG_IGN or SIG_DFL. restore original C handler. NOTE: record? is for R6RS record-type, but record-type? is not NOTE: This macro can detect multi return values. TODO: Text-coloring helper functions, borrowed from guile-colorized NOTE: HTTP/1.1 treat all connection keep-alive unless it requires `close' explicityly NOTE: The order matters ENHANCE: use colored output nothing noticed, re-throw it to next level. for verify db table name
" Mu Lei " known as " NalaGinrut " < > Artanis is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License and GNU Lesser General Public License published by the Free Software Foundation , either version 3 of the License , or ( at your option ) Artanis is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License (define-module (artanis utils) #:use-module (artanis crypto md5) #:use-module (artanis crypto sha-1) #:use-module (artanis crypto sha-2) #:use-module (artanis crypto base64) #:use-module (artanis tpl sxml) #:use-module (artanis config) #:use-module (artanis irregex) #:use-module (artanis env) #:use-module (artanis mime) #:use-module (system foreign) #:use-module (ice-9 rdelim) #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw) #:use-module (srfi srfi-1) #:use-module (srfi srfi-19) #:use-module (ice-9 local-eval) #:use-module (ice-9 receive) #:use-module (ice-9 q) #:use-module (ice-9 control) #:use-module (web http) #:use-module (web request) #:use-module (web uri) #:use-module ((rnrs) #:select (get-bytevector-all utf8->string put-bytevector bytevector-u8-ref string->utf8 bytevector-length make-bytevector bytevector-s32-native-ref bytevector? define-record-type record-rtd record-accessor get-string-all)) #:export (regexp-split hash-keys cat bv-cat get-global-time sanitize-response build-response write-response get-local-time string->md5 unsafe-random uri-encode uri-decode response-version response-code response-connection request-headers response-port write-response-body read-request request-uri request-method request-content-length request-port read-request-body response-content-length get-file-ext get-global-date get-local-date string-substitute nfx static-filename remote-info seconds-now local-time-stamp parse-date write-date make-expires export-all-from-module! alist->hashtable expires->time-utc local-eval-string time-expired? valid-method? mmap munmap get-random-from-dev string->byteslist string->sha-1 string->sha-224 string->sha-256 string->sha-384 string->sha-512 list-slice bv-slice uni-basename checkout-the-path make-string-template guess-mime prepare-headers new-stack new-queue stack-slots queue-slots stack-pop! stack-push! stack-top stack-empty? queue-out! queue-in! queue-head queue-tail queue-empty? list->stack list->queue stack-remove! queue-remove! queue->list stack->list queue-length stack-length plist->alist make-db-string-template non-list? keyword->string range oah->handler oah->opts string->keyword alist->klist alist->kblist is-hash-table-empty? symbol-downcase symbol-upcase normalize-column run-before-run! sxml->xml-string run-after-request! run-before-response! make-pipeline HTML-entities-replace eliminate-evil-HTML-entities generate-kv-from-post-qstr handle-proper-owner generate-data-url verify-ENTRY exclude-dbd draw-expander remove-ext scan-app-components cache-this-route! dump-route-from-cache generate-modify-time delete-directory handle-existing-file check-drawing-method DEBUG subbv->string subbv=? bv-read-line bv-read-delimited put-bv bv-u8-index bv-u8-index-right build-bv-lookup-table filesize plist-remove gen-migrate-module-name try-to-load-migrate-cache flush-to-migration-cache gen-local-conf-file with-dbd call-with-sigint define-box-type make-box-type unbox-type ::define did-not-specify-parameter colorize-string-helper colorize-string WARN-TEXT ERROR-TEXT REASON-TEXT NOTIFY-TEXT STATUS-TEXT get-trigger get-family get-addr request-path response-keep-alive? request-keep-alive? procedure-name->string proper-toplevel gen-content-length make-file-sender file-sender? file-sender-size file-sender-thunk get-string-all-with-detected-charset make-unstop-exception-handler artanis-log exception-from-client exception-from-server render-sys-page bv-copy/share bv-backward artanis-list-matches get-syspage artanis-sys-response char-predicate handle-upload is-valid-table-name? is-guile-compatible-server-core?) #:re-export (the-environment)) (define* (get-random-from-dev #:key (length 8) (uppercase #f)) (call-with-input-file "/dev/urandom" (lambda (port) (let* ((bv ((@ (rnrs) get-bytevector-n) port length)) (str (format #f "~{~2,'0x~}" ((@ (rnrs) bytevector->u8-list) bv)))) (if uppercase (string-upcase str) str))))) (define uri-decode (@ (web uri) uri-decode)) (define uri-encode (@ (web uri) uri-encode)) (define parse-date (@@ (web http) parse-date)) (define write-date (@@ (web http) write-date)) (define build-response (@ (web response) build-response)) (define write-response (@ (web response) write-response)) (define response-version (@ (web response) response-version)) (define response-code (@ (web response) response-code)) (define response-connection (@ (web response) response-connection)) (define response-port (@ (web response) response-port)) (define write-response-body (@ (web response) write-response-body)) (define response-content-length (@ (web response) response-content-length)) (define read-request (@ (web request) read-request)) (define read-request-body (@ (web request) read-request-body)) (define request-uri (@ (web request) request-uri)) (define request-headers (@ (web request) request-headers)) (define request-method (@ (web request) request-method)) (define request-content-length (@ (web request) request-content-length)) (define request-port (@ (web request) request-port)) (define-syntax-rule (local-eval-string str e) (local-eval (call-with-input-string (format #f "(begin ~a)" str) read) e)) (define (alist->hashtable al) (let ((ht (make-hash-table))) (for-each (lambda (x) (hash-set! ht (car x) (cadr x))) al) ht)) (eval-when (eval load compile) (define (export-all-from-module! module-name) (let ((mod (resolve-module module-name))) (module-for-each (lambda (s m) (module-add! (current-module) s m)) mod)))) (define (time-expired? expires) (if expires (let ((t (expires->time-utc expires))) (time>? (current-time) t)) (define (expires->time-utc str) (date->time-utc (parse-date str))) (define (make-expires sec) (get-local-time (+ (seconds-now) sec))) (define (seconds-now) ((@ (guile) current-time))) (define (local-time-stamp) (strftime "%F %T" (localtime (seconds-now)))) (define* (get-global-time #:optional (time #f) (nsec 0)) (call-with-output-string (lambda (port) (write-date (time-utc->date (if time (make-time 'time-utc nsec time) (current-time)) 0) port)))) (define* (get-local-time #:optional (time #f) (nsec 0)) (call-with-output-string (lambda (port) (write-date (time-utc->date (if time (make-time 'time-utc nsec time) (current-time))) port)))) (define* (regexp-split regex str #:optional (flags 0)) (let ((ret (fold-matches regex str (list '() 0 str) (lambda (m prev) (let* ((ll (car prev)) (start (cadr prev)) (tail (match:suffix m)) (end (match:start m)) (s (substring/shared str start end)) (groups (map (lambda (n) (match:substring m n)) (iota (1- (match:count m)) 1)))) (list `(,@ll ,s ,@groups) (match:end m) tail))) flags))) `(,@(car ret) ,(caddr ret)))) (define (hash-keys ht) (hash-map->list (lambda (k v) k) ht)) (define* (cat file/port #:optional (out (current-output-port))) (define get-string-all (@ (rnrs io ports) get-string-all)) (let ((str (if (port? file/port) (get-string-all file/port) (call-with-input-file file/port get-string-all)))) (if out (display str out) str))) (define* (bv-cat file/port #:optional (out (current-output-port))) (define get-bytevector-all (@ (rnrs io ports) get-bytevector-all)) (let ((bv (if (port? file/port) (get-bytevector-all file/port) (call-with-input-file file/port get-bytevector-all)))) (if out (display bv out) bv))) 35147 is the length of in bytes (define* (unsafe-random #:optional (n 35147)) (random n (random-state-from-platform))) (define (string-substitute str re what) (regexp-substitute/global #f re str 'pre what 'post)) (define-syntax get-file-ext (syntax-rules () ((_ filename) (substring/shared filename (1+ (string-index-right filename #\.)))))) (define* (get-global-date #:optional (time #f)) (parse-header 'date (if time (get-global-time (car time) (cdr time)) (get-global-time)))) (define* (get-local-date #:optional (time #f)) (parse-header 'date (if time (get-local-time (car time) (cdr time)) (get-local-time)))) (define (nfx exp) (let lp((rest exp) (result '()) (cur #f)) (cond ((null? rest) result) ((null? result) (let ((e (list (cadr rest) (car rest) (caddr rest)))) (lp (cdddr rest) e (car rest)))) (else (let ((e (list cur result (cadr rest)))) (lp (cddr rest) e #f)))))) (define-syntax-rule (static-filename path) (if (current-toplevel) (format #f "~a/~a" (current-toplevel) path) (format #f "./~a" path))) (define-syntax-rule (request-ip req) TODO : support in the future (if (port-filename (request-port req)) (inet-ntop AF_INET (sockaddr:addr (getpeername (request-port req)))) (define-syntax-rule (remote-info req) (if (get-conf '(server nginx)) (assoc-ref (request-headers req) 'x-real-ip) (request-ip req))) (define *methods-list* '(HEAD GET POST PUT PATCH DELETE)) (define (allowed-method? method) #t) (define (valid-method? method) (if (and (member method *methods-list*) (allowed-method? method)) method (throw 'artanis-err 405 valid-method? "invalid HTTP method `~a'" method))) (define-public ACCESS_COPY #x3) (define-public ACCESS_READ #x1) (define-public ACCESS_WRITE #x2) (define-public ALLOCATIONGRANULARITY #x1000) (define-public PROT_READ #x1) (define-public PROT_WRITE #x2) (define-public PROT_EXEC #x4) (define-public PROT_SEM #x8) (define-public PROT_NONE #x0) (define-public PROT_GROWSDOWN #x01000000) (define-public PROT_GROWSUP #x02000000) (define-public PAGESIZE #x1000) (define-public MAP_ANON #x20) (define-public MAP_DENYWRITE #x800) (define-public MAP_EXECUTABLE #x1000) (define-public MAP_SHARED #x01) (define-public MAP_PRIVATE #x02) (define-public MAP_TYPE #x0f) (define-public MAP_FIXED #x10) (define-public MAP_ANONYMOUS #x20) (define *libc-ffi* (dynamic-link)) (define %mmap (pointer->procedure '* (dynamic-func "mmap" *libc-ffi*) (list '* size_t int int int size_t) #:return-errno? #t)) (define %munmap (pointer->procedure int (dynamic-func "munmap" *libc-ffi*) (list '* size_t) #:return-errno? #t)) (define* (mmap size #:key (addr %null-pointer) (fd -1) (prot MAP_SHARED) (flags PROT_READ) (offset 0) (bv? #f)) (let ((ret (if bv? (lambda (p) (pointer->bytevector p size)) identity))) (ret (%mmap addr size prot flags fd offset)))) (define (munmap bv/pointer size) (cond ((bytevector? bv/pointer) (%munmap (bytevector->pointer bv/pointer size) size)) ((pointer? bv/pointer) (%munmap bv/pointer size)))) (define (string->byteslist str step base) (define len (string-length str)) (let lp((ret '()) (i 0)) (cond ((>= i len) (reverse ret)) ((zero? (modulo i step)) (lp (cons (string->number (substring/shared str i (+ i step)) base) ret) (1+ i))) (else (lp ret (1+ i)))))) (define (string->md5 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-1 "need string or bytevector!" str/bv))))) (md5->string (md5 in)))) (define (string->sha-1 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-1 "need string or bytevector!" str/bv))))) (sha-1->string (sha-1 in)))) (define (string->sha-224 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-224 "need string or bytevector!" str/bv))))) (sha-224->string (sha-224 in)))) (define (string->sha-256 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-256 "need string or bytevector!" str/bv))))) (sha-256->string (sha-256 in)))) (define (string->sha-384 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-384 "need string or bytevector!" str/bv))))) (sha-384->string (sha-384 in)))) (define (string->sha-512 str/bv) (let ((in (cond ((string? str/bv) ((@ (rnrs) string->utf8) str/bv)) (((@ (rnrs) bytevector?) str/bv) str/bv) (else (throw 'artanis-err 500 string->sha-512 "need string or bytevector!" str/bv))))) (sha-512->string (sha-512 in)))) (define-syntax list-slice (syntax-rules (:) ((_ ll lo : hi) (let ((len (length ll))) (and (<= lo len) (>= len hi) (let lp((rest ll) (result '()) (cnt 1)) (cond ((null? rest) (error "no")) ((<= cnt lo) (lp (cdr rest) result (1+ cnt))) ((> cnt hi) (reverse result)) (else (lp (cdr rest) (cons (car rest) result) (1+ cnt)))))))) ((_ ll lo :) (drop ll lo)) ((_ ll : hi) (take ll hi)))) 1 . ( > hi ( bytevector - length bv ) ) 2 . ( < lo 0 ) wrap reference (define (%bv-slice bv lo hi) (let* ((len (- hi lo)) (slice ((@ (rnrs) make-bytevector) len))) ((@ (rnrs) bytevector-copy!) bv lo slice 0 len) slice)) NOT SAFE % bytevector - slice for GC , need ( let * ( ( ptr ( bytevector->pointer bv ) ) ( addr ( pointer - address ptr ) ) (define-syntax bv-slice (syntax-rules (:) ((_ bv lo : hi) (%bv-slice bv lo hi)) ((_ bv lo :) (%bv-slice bv lo ((@ (rnrs bytevectors) bytevector-length) bv))) ((_ bv : hi) (%bv-slice bv 0 hi)))) get the unified basename both POSIX and WINDOWS (define (uni-basename filename) (substring filename (1+ (string-index-right filename (lambda (c) (or (char=? c #\\) (char=? c #\/))))))) (define* (checkout-the-path path #:optional (mode #o775)) (define (->path p) (let ((pp (irregex-split "/" p))) (if (char=? (string-ref p 0) #\/) (cons (string-append "/" (car pp)) (cdr pp)) pp))) (let ((paths (->path path))) (let lp((next paths) (last "")) (cond ((null? next) #t) ((string-null? (car next)) (lp (cdr next) last)) (else (let ((now-path (string-append last (car next) "/"))) (cond ((file-exists? now-path) (lp (cdr next) now-path)) (else (mkdir now-path mode) (lp (cdr next) now-path))))))))) ( key ( symbol->keyword ( string->symbol (define (%make-string-template mode template . defaults) (define irx (sre->irregex '(or (=> dollar "$$") (: "${" (=> var (+ (~ #\}))) "}")))) (define (->string obj) (if (string? obj) obj (object->string obj))) (define (get-the-val lst key) (let ((str (kw-arg-ref lst key))) (case mode ((normal) str) ((db) (string-concatenate (list "\"" (->string str) "\""))) (else (throw 'artanis-err 500 %make-string-template "invalid mode `~a'" mode))))) (define (optimize rev-items tail) (cond ((null? rev-items) tail) ((not (string? (car rev-items))) (optimize (cdr rev-items) (cons (car rev-items) tail))) (else (receive (strings rest) (span string? rev-items) (let ((s (string-concatenate-reverse strings))) (if (string-null? s) (optimize rest tail) (optimize rest (cons s tail)))))))) (define (match->item m) (or (and (irregex-match-substring m 'dollar) "$") (let* ((name (irregex-match-substring m 'var)) (key (symbol->keyword (string->symbol name)))) (cons key (kw-arg-ref defaults key))))) (let* ((rev-items (irregex-fold irx (lambda (idx m tail) (cons* (match->item m) (substring template idx (irregex-match-start-index m 0)) tail)) '() template (lambda (idx tail) (cons (substring template idx) tail)))) (items (optimize rev-items '()))) (lambda keyword-args (define (item->string item) (if (string? item) item (or (and=> (get-the-val keyword-args (car item)) ->string) ""))) (string-concatenate (map item->string items))))) (define (make-string-template tpl . vals) (apply %make-string-template 'normal tpl vals)) (define (make-db-string-template tpl . vals) (apply %make-string-template 'db tpl vals)) (define (guess-mime filename) (mime-guess (get-file-ext filename))) (define (bytevector-null? bv) ((@ (rnrs bytevectors) bytevector=?) bv #u8())) (define (generate-modify-time t) (get-local-date (cons (time-second t) (time-nanosecond t)))) (define (prepare-headers headers) (define *default-headers* `((content-type . (text/html (charset . ,(get-conf '(server charset))))) (date . ,(get-global-date)))) (lset-union (lambda (x y) (eq? (car x) (car y))) (assq-remove! headers 'last-modified) *default-headers*)) (define new-stack make-q) (define new-queue make-q) (define stack-slots car) (define queue-slots car) (define (%q-remove-with-key! q key) (assoc-remove! (car q) key) (sync-q! q)) (define stack-pop! q-pop!) (define stack-push! q-push!) (define stack-top q-front) (define stack-remove! %q-remove-with-key!) (define stack-empty? q-empty?) (define stack-length q-length) (define (stack->list stk) (list-copy (stack-slots stk))) (define queue-out! q-pop!) (define queue-in! enq!) (define queue-head q-front) (define queue-tail q-rear) (define queue-remove! %q-remove-with-key!) (define queue-empty? q-empty?) (define queue-length q-length) (define (queue->list q) (list-copy (queue-slots q))) NOTE : make - stack exists in (for-each (lambda (x) (stack-push! stk x)) lst) stk) (define* (list->queue lst #:optional (queue (new-queue))) (for-each (lambda (x) (queue-in! queue x)) lst) queue) (define (plist->alist lst) (let lp((next lst) (ret '())) (match next (() (reverse ret)) ((k v . rest) (lp (cddr next) (acons (keyword->symbol k) v ret)))))) (define-syntax-rule (non-list? x) (not (list? x))) (define* (keyword->string x #:optional (proc identity)) (proc (symbol->string (keyword->symbol x)))) (define* (range from to #:optional (step 1)) (iota (- to from) from step)) (define (oah->handler opts-and-handler) (let ((handler (and (list? opts-and-handler) (last opts-and-handler)))) (if (or (procedure? handler) (string? handler)) handler (error oah->handler "You have to specify a handler for this rule!")))) (define (oah->opts opts-and-handler) (if (procedure? opts-and-handler) (let lp((next opts-and-handler) (kl '()) (vl '())) (match next (((? keyword? k) v rest ...) (lp rest (cons k kl) (cons v vl))) ((or (? null?) (? procedure?)) (list kl vl)) (else (lp (cdr next) kl vl)))))) (define (string->keyword str) (symbol->keyword (string->symbol str))) (define (alist->klist al) (let lp((next al) (ret '())) (cond ((null? next) ret) (else (let ((k (symbol->keyword (car (car next)))) (v (cdr (car next)))) (lp (cdr next) (cons k (cons v ret)))))))) (define (alist->kblist al) (let lp((next al) (ret '())) (cond ((null? next) ret) (else (let ((k (string->keyword (string-append ":" (car (car next))))) (v (cdr (car next)))) (lp (cdr next) (cons k (cons v ret)))))))) (define (is-hash-table-empty? ht) (zero? (hash-count values ht))) (define (symbol-strop proc sym) (string->symbol (proc (symbol->string sym)))) (define (symbol-downcase sym) (symbol-strop string-downcase sym)) (define (symbol-upcase sym) (symbol-strop string-upcase sym)) (define* (normalize-column col #:optional (ci? #f)) (define-syntax-rule (-> c p) (if ci? (p col) col)) (cond ((string? col) (string->symbol (-> c string-downcase))) ((symbol? col) (-> col symbol-downcase)) ((keyword? col) (normalize-column (keyword->string col) ci?)) (else (throw 'artanis-err 500 normalize-column "Invalid type of column `~a'" col)))) (define* (sxml->xml-string sxml #:key (escape? #f)) (call-with-output-string (lambda (port) (sxml->xml sxml port escape?)))) (define (run-after-request! proc) (add-hook! *after-request-hook* proc)) (define (run-before-response! proc) (add-hook! *before-response-hook* proc)) (define (run-before-run! proc) (add-hook! *before-run-hook* proc)) (define (make-pipeline . procs) (lambda (x) (fold (lambda (y p) (y p)) x procs))) (define (HTML-entities-replace set content) (define in (open-input-string content)) (define (hit? c/str) (assoc-ref set c/str)) (define (get-estr port) (let lp((n 0) (ret '())) (cond ((= n 3) (list->string (reverse! ret))) (else (lp (1+ n) (cons (read-char port) ret)))))) (call-with-output-string (lambda (out) (let lp((c (peek-char in))) (cond ((eof-object? c) #t) ((hit? c) => (lambda (str) (display str out) (read-char in) (lp (peek-char in)))) ((char=? c #\%) (let* ((s (get-estr in)) (e (hit? s))) (if e (display e out) (display s out)) (lp (peek-char in)))) (else (display (read-char in) out) (lp (peek-char in)))))))) (define *terrible-HTML-entities* ("%3C" . "&lt;") ("%3E" . "&gt;") ("%26" . "&amp;") ("%22" . "&quot;"))) NOTE : cooked for anti - XSS . (define (eliminate-evil-HTML-entities content) (HTML-entities-replace *terrible-HTML-entities* content)) (define* (generate-kv-from-post-qstr body #:key (no-evil? #f) (key-converter identity)) (define cook (if no-evil? eliminate-evil-HTML-entities identity)) (define (%convert lst) (match lst ((k v) (list (key-converter k) ((current-encoder) v))) (else (throw 'artanis-err 500 generate-kv-from-post-qstr "Fatal! Can't be here!" lst)))) (define (-> x) (string-trim-both x (lambda (c) (member c '(#\sp #\: #\return))))) (map (lambda (x) (%convert (map -> (string-split (cook x) #\=)))) (string-split (utf8->string body) #\&))) NOTE : We accept warnings , which means if warnings occurred , it 'll be 200(OK ) anyway , but NOTE : We * DO NOT * accept errors , which means if errors occurred , Artanis will throw 500 . (define (handle-proper-owner file uid gid) (define-syntax-rule (print-the-warning exe reason) (format (current-error-port) "[WARNING] '~a' encountered system error: ~s~%" exe reason)) (define-syntax-rule (->err-reason exe reason) (format #f "'~a' encoutered system error: ~s" exe reason)) (catch 'system-error (lambda () (chown file (or uid (getuid)) (or gid (getgid)))) (lambda (k . e) (let ((exe (car e)) (reason (caaddr e))) (match (cons k reason) ('(system-error . "Operation not permitted") (print-the-warning exe reason) (display "Maybe you run Artanis as unprivileged user? (say, not as root)\n" (current-error-port))) ('(system-error . "No such file or directory") (throw 'artanis-err 500 handle-proper-owner (->err-reason exe reason) file)) (else (apply throw k e))))))) (define* (generate-data-url bv/str #:key (mime 'application/octet-stream) (crypto 'base64) (charset 'utf-8)) (define-syntax-rule (->crypto) (match crypto ((or 'base64 "base64") ";base64") (else ""))) (define-syntax-rule (->charset) (if (or (string? charset) (symbol? charset)) (format #f ",charset=~a" charset) "")) (define-syntax-rule (->mime) (match mime (`(guess ,ext) (or (mime-guess ext) 'application/octet-stream)) ((or (? symbol?) (? string?)) (or (and (get-conf 'debug-mode) (mime-check mime) (format #f "~a" mime)) (format #f "~a" mime))) (else (throw 'artanis-err 500 generate-data-url "Invalid MIME! Should be symbol or string" mime)))) (let ((b64 (base64-encode bv/str))) (string-concatenate (list "data:" (->mime) (->crypto) (->charset) "," b64)))) (define (verify-ENTRY entry) (format #t "entry: ~a~%" entry) (cond ((not (file-exists? entry)) (format (artanis-current-output) "ENTRY file is missing!~%") #f) (else (let ((line (call-with-input-file entry read-line))) (string=? line ";; This an Artanis ENTRY file, don't remove it!"))))) (define-syntax draw-expander (syntax-rules (rule options method) ((_ (options options* ...) rest rest* ...) `(,@(list options* ...) ,@(draw-expander rest rest* ...))) ((_ (method method*) rest rest* ...) `((method ,'method*) ,@(draw-expander rest rest* ...))) ((_ (rule url) rest rest* ...) `((rule ,url) ,@(draw-expander rest rest* ...))) ((_ handler) (list handler)))) (define (remove-ext str) (let ((i (string-contains str "."))) (substring str 0 i))) (define (scan-app-components component) (let ((toplevel (current-toplevel))) (map (lambda (f) (string->symbol (remove-ext f))) (scandir (format #f "~a/app/~a/" toplevel component) (lambda (f) (not (or (string=? f ".") (string=? f "..") (string=? f ".gitkeep")))))))) (define (cache-this-route! url meta) (define (write-header port) (format port ";; Do not touch anything!!!~%") (format port ";; All things here should be automatically handled properly!!!~%")) (define route-cache (string-append (current-toplevel) "/tmp/cache/route.cache")) (when (or (not (file-exists? route-cache)) (format (artanis-current-output) "Route cache is missing, regenerating...~%") (call-with-output-file route-cache (lambda (port) (write-header port) (write '() port)))) (when (and url meta) (let ((rl (call-with-input-file route-cache read))) (delete-file route-cache) (call-with-output-file route-cache (lambda (port) (flock port LOCK_EX) (write-header port) (if (eof-object? rl) (write '() port) (write (assoc-set! rl url (drop-right meta 1)) port)) (flock port LOCK_UN)))))) (define (dump-route-from-cache) (define toplevel (current-toplevel)) (define route-cache (string-append toplevel "/tmp/cache/route.cache")) (define route (string-append toplevel "/.route")) (define (load-customized-router) (let ((croute (string-append toplevel "conf/route"))) (cond (else black magic to make happy (load croute))))) (when (file-exists? route) (delete-file route)) (when (not (file-exists? route-cache)) (cache-this-route! #f #f) (dump-route-from-cache)) (let ((rl (call-with-input-file route-cache read))) (cond ((eof-object? rl) (cache-this-route! #f #f) (dump-route-from-cache)) (else (call-with-output-file route (lambda (port) (for-each (lambda (r) (let* ((meta (cdr r)) (rule (assq-ref meta 'rule)) (method (assq-ref meta 'method))) (format port "~2t(~a ~s)~%" (if method method 'get) (if rule rule (car r))))) rl))) (load-customized-router))))) (define* (delete-directory dir #:optional (checkonly? #f)) (cond ((and (file-is-directory? dir) (file-exists? dir)) (system (format #f "rm -f ~a" dir))) (else (and (not checkonly?) (error delete-directory "Not a directory or doesn't exist " dir))))) (define* (handle-existing-file path #:optional (dir? #f)) (let* ((pp (if dir? (dirname path) path)) (component (basename (dirname pp))) (name (car (string-split (basename pp) #\.)))) (cond ((draw:is-force?) (if (file-is-directory? path) (delete-directory path) (delete-file path))) ((draw:is-skip?) (format (artanis-current-output) "skip ~10t app/~a/~a~%" component name)) (else (format (artanis-current-output) "~a `~a' exists! (Use --force/-f to overwrite or --skip/-s to ignore)~%" (string-capitalize component) name) (exit 1))))) (define (check-drawing-method lst) (define errstr "Invalid drawing method, shouldn't contain '/' ") (for-each (lambda (name) (when (not (irregex-match "[^/]+" name)) (error check-drawing-method errstr name))) lst) lst) (define (subbv->string bv encoding start end) (call-with-output-string (lambda (port) (set-port-encoding! port encoding) (put-bytevector port bv start (- end start))))) (define* (bv-u8-index bv u8 #:optional (time 1)) (let ((len (bytevector-length bv))) (let lp((i 0) (t 1)) (cond ((>= i len) #f) ((= (bytevector-u8-ref bv i) u8) (if (= t time) i (lp (1+ i) (1+ t)))) (else (lp (1+ i) t)))))) (define* (bv-u8-index-right bv u8 #:optional (time 1)) (let ((len (bytevector-length bv))) (let lp((i (1- len)) (t 1)) (cond ((< i 0) #f) ((= (bytevector-u8-ref bv i) u8) (if (= t time) i (lp (1- i) (1+ t)))) (else (lp (1- i) t)))))) (define* (subbv=? bv bv2 #:optional (start 0) (end (1- (bytevector-length bv)))) (and (<= (bytevector-length bv2) (bytevector-length bv)) (let lp((i end) (j (1- (bytevector-length bv2)))) (cond ((< i start) #t) ((= (bytevector-u8-ref bv i) (bytevector-u8-ref bv2 j)) (lp (1- i) (1- j))) (else #f))))) return position after (define* (bv-read-delimited bv delim #:optional (start 0) (end (bytevector-length bv))) (define len (- end start -1)) (let lp((i start)) (cond ((> i end) #f) ((= (bytevector-u8-ref bv i) delim) i) (else (lp (1+ i)))))) (define* (bv-read-line bv #:optional (start 0) (end (bytevector-length bv))) (bv-read-delimited bv 10 start end)) (define (put-bv port bv from to) (put-bytevector port bv from (- to from 2))) (define (build-bv-lookup-table bv) (let ((ht (make-hash-table))) (for-each (lambda (i) (hash-set! ht (bytevector-u8-ref bv i) #t)) (iota (bytevector-length bv))) ht)) (define Gbytes (ash 1 30)) (define Mbytes (ash 1 20)) (define Kbytes (ash 1 10)) (define (filesize size) (cond ((>= size Gbytes) (format #f "~,1fGiB" (/ size Gbytes))) ((>= size Mbytes) (format #f "~,1fMiB" (/ size Mbytes))) ((>= size Kbytes) (format #f "~,1fKiB" (/ size Kbytes))) (else (format #f "~a Bytes" size)))) (define* (plist-remove lst k #:optional (no-value? #f)) (let lp((next lst) (kk '__) (ret '())) (cond ((null? next) (values (reverse ret) kk)) ((eq? (car next) k) (if no-value? (lp (cdr next) (car next) ret) (lp (cddr next) (list (car next) (cadr next)) ret))) (else (lp (cdr next) kk (cons (car next) ret)))))) (define *name-re* (string->irregex "([^.]+)\\.scm")) (define (gen-migrate-module-name f) (cond ((irregex-search *name-re* (basename f)) => (lambda (m) (irregex-match-substring m 1))) (else (throw 'artanis-err 500 gen-migrate-module-name "Wrong parsing of module name, shouldn't be here!" f)))) (define (try-to-load-migrate-cache name) (let ((file (format #f "~a/tmp/cache/migration/~a.scm" (current-toplevel) name))) (cond ((file-exists? file) (load file)) (else (format (artanis-current-output) "[WARN] No cache for migration of `~a'~%" name) (format (artanis-current-output) "Run `art migrate up ~a', then try again!~%" name))))) (define (flush-to-migration-cache name fl) (let ((file (format #f "~a/tmp/cache/migration/~a.scm" (current-toplevel) name))) (when (file-exists? file) (delete-file file)) (call-with-output-file file (lambda (port) (format port "(define-~a~%" name) (for-each (lambda (ft) (format port "~2t~a~%" ft)) fl) (format port "~2t)~%"))))) (define (gen-local-conf-file) (format #f "~a/conf/artanis.conf" (current-toplevel))) (define-syntax-rule (with-dbd dbd0 body ...) (let ((dbd1 (get-conf '(db dbd)))) (cond ((or (and (list? dbd0) (memq dbd1 dbd0)) (eq? dbd1 dbd0)) body ...) (else (throw 'artanis-err 500 'with-dbd "This is only supported by `~a', but the current dbd is `~a'" dbd0 dbd1 'body ...))))) (define-syntax-rule (exclude-dbd dbds body ...) (let ((dbd (get-conf '(db dbd)))) (cond ((memq dbd dbds) (throw 'artanis-err 500 'exclude-dbd "This isn't supported by `~a', please check it out again!" dbds 'body ...)) (else body ...)))) (define-syntax-rule (DEBUG fmt args ...) (when (get-conf 'debug-mode) (format (artanis-current-output) fmt args ...))) (define call-with-sigint (if (not (provided? 'posix)) (lambda (thunk handler-thunk) (thunk)) (lambda (thunk handler-thunk) (let ((handler #f)) (catch 'interrupt (lambda () (dynamic-wind (lambda () (set! handler (sigaction SIGINT (lambda (sig) (throw 'interrupt))))) thunk (lambda () (if handler (sigaction SIGINT (car handler) (cdr handler)) (sigaction SIGINT #f))))) (lambda (k . _) (handler-thunk))))))) (define-syntax-rule (define-box-type name) (define-record-type name (fields treasure))) (define-macro (make-box-type bt v) (list (symbol-append 'make- bt) v)) (define-syntax-rule (box-type-treasure t) (record-accessor (record-rtd t) 0)) (define-syntax-rule (unbox-type t) (let ((treasure-getter (box-type-treasure t))) (treasure-getter t))) (define (socket-port? sp) (and (port? sp) (eq? (port-filename sp) 'socket))) (define (detect-type-name o) (define r6rs-record? (@ (rnrs) record?)) (define r6rs-record-type-name (@ (rnrs) record-type-name)) (define guile-specific-record? (@ (guile) record?)) (define (guile-specific-record-name o) ((@ (guile) record-type-name) ((@ (guile) record-type-descriptor) o))) (cond ((r6rs-record? o) (r6rs-record-type-name (record-rtd o))) ((guile-specific-record? o) (guile-specific-record-name o)) ((symbol? o) 'symbol) ((string? o) 'string) ((integer? o) (if (positive? o) '+int '-int)) ((number? o) 'num) ((thunk? o) 'thunk) ((procedure? o) 'proc) ((vector? o) 'vector) ((pair? o) 'pair) ((list? o) 'list) ((bytevector? o) 'bv) ((port? o) 'port) ((boolean? o) 'boolean) (else 'ANY))) (define (check-args-types op args) (define (check-eq? actual-type expect-type) (case expect-type ((+int) (eq? actual-type '+int)) ((-int) (eq? actual-type '-int)) ((int) (memq actual-type '(-int +int))) (else (eq? expect-type actual-type)))) (match (procedure-property op 'type-anno) (((targs ...) '-> (func-types ...)) (for-each (lambda (v e) (or (eq? e 'ANY) (check-eq? (detect-type-name v) e) (begin (DEBUG "(~{~a~^ ~}) =? (~{~a~^ ~})~%" targs args) (throw 'artanis-err 500 check-args-types "~a: Argument ~a is a `~a' type, but I expect type `~a'" op v (detect-type-name v) e)))) args targs)) (else (throw 'artanis-err 500 check-args-types "Invalid type annotation `~a'" (procedure-property op 'type-anno))))) (define (check-function-types op fret) (match (procedure-property op 'type-anno) (((targs ...) '-> (func-types ...)) (for-each (lambda (v e) (or (eq? e 'ANY) (eq? (detect-type-name v) e) (throw 'artanis-err 500 check-function-types "`Return value ~a(~a) is expected to be type `~a'" v (detect-type-name v) e))) fret func-types)) (else (throw 'artanis-err 500 check-function-types "Invalid type annotation `~a'" (procedure-property op 'type-anno))))) (define (detect-and-set-type-anno! op ftypes atypes) (let ((type `(,atypes -> ,ftypes))) (set-procedure-property! op 'type-anno type) type)) 1 . support multi - types , say , string / bv , maybe not easy to do it faster ? (define-syntax ::define (syntax-rules (-> :anno:) ((_ (op args ...) (:anno: (targs ...) -> func-types ...) body ...) (begin (define (op args ...) (when (get-conf 'debug-mode) (check-args-types op (list args ...))) (call-with-values (lambda () body ...) (lambda ret (when (get-conf 'debug-mode) (eq? (detect-type-name ret) (check-function-types op ret))) (apply values ret)))) (detect-and-set-type-anno! op '(func-types ...) '(targs ...)))))) (define-syntax-rule (did-not-specify-parameter what) (format #f "`current-~a' isn't specified, it's likely a bug!" what)) (define *color-list* `((CLEAR . "0") (RESET . "0") (BOLD . "1") (DARK . "2") (UNDERLINE . "4") (UNDERSCORE . "4") (BLINK . "5") (REVERSE . "6") (CONCEALED . "8") (BLACK . "30") (RED . "31") (GREEN . "32") (YELLOW . "33") (BLUE . "34") (MAGENTA . "35") (CYAN . "36") (WHITE . "37") (ON-BLACK . "40") (ON-RED . "41") (ON-GREEN . "42") (ON-YELLOW . "43") (ON-BLUE . "44") (ON-MAGENTA . "45") (ON-CYAN . "46") (ON-WHITE . "47"))) (define (get-color color) (assq-ref *color-list* color)) (define (generate-color colors) (let ((color-list (filter-map get-color colors))) (if (null? color-list) "" (string-append "\x1b[" (string-join color-list ";" 'infix) "m")))) (define* (colorize-string-helper color str control #:optional (rl-ignore #f)) (if rl-ignore (string-append "\x01" (generate-color color) "\x02" str "\x01" (generate-color control) "\x02") (string-append (generate-color color) str (generate-color control)))) (define* (colorize-string str color) "Example: (colorize-string \"hello\" '(BLUE BOLD))" (colorize-string-helper color str '(RESET) (using-readline?))) (define-syntax-rule (WARN-TEXT str) (colorize-string str '(YELLOW))) (define-syntax-rule (ERROR-TEXT str) (colorize-string str '(RED))) (define-syntax-rule (REASON-TEXT str) (colorize-string str '(CYAN))) (define-syntax-rule (NOTIFY-TEXT str) (colorize-string str '(WHITE))) (define-syntax-rule (STATUS-TEXT num) (colorize-string (object->string num)'(WHITE))) (define (get-trigger) (case (get-conf '(server trigger)) ((edge) (@ (artanis server epoll) EPOLLET)) ((level) 0) (else (throw 'artanis-err 500 get-trigger "Invalid (server trigger)!" (get-conf '(server trigger)))))) (define (get-family) (case (get-conf '(host family)) ((ipv4) AF_INET) ((ipv6) AF_INET6) (else (throw 'artanis-err 500 get-family "Invalid (host family)!" (get-conf '(host family)))))) (define (get-addr) (let ((host (get-conf '(host addr))) (family (get-family))) (if (and host (not (string=? host "127.0.0.1"))) (inet-pton family host) INADDR_LOOPBACK))) (define (request-path req) (uri-path (request-uri req))) (define (response-keep-alive? response) (let ((v (response-version response))) (and (or (< (response-code response) 400) (= (response-code response) 404)) (case (car v) ((1) (case (cdr v) ((1) (not (memq 'close (response-connection response)))) HTTP/1.0 needs explicit keep - alive notice ((0) (memq 'keep-alive (response-connection response))))) (else #f))))) (define (request-keep-alive? request) (or (equal? (request-upgrade request) '(websocket)) (equal? (request-connection request) '(keep-alive)) (equal? (request-version request) '(1 . 1)))) (define (procedure-name->string proc) (symbol->string (procedure-name proc))) (define-syntax-rule (proper-toplevel) (or (current-toplevel) "")) (define-record-type file-sender (fields size thunk)) (define (gen-content-length body) (let ((get-length (lambda () (cond ((bytevector? body) (bytevector-length body)) ((file-sender? body) (file-sender-size body)) ((string? body) (throw 'artanis-err 500 gen-content-length "BUG: body should have been converted to bytevector! ~a" body)) (else (throw 'artanis-err 500 gen-content-length "Invalid body ~a" body)))))) `(content-length . ,(if body (get-length) 0)))) (define (get-string-all-with-detected-charset filename) (call-with-input-file filename (lambda (port) (set-port-encoding! port (get-conf '(server charset))) (get-string-all port)))) (define (get-syspage file) (let ((local-syspage (format #f "~a/sys/pages/~a" (current-toplevel) file))) (if (file-exists? local-syspage) local-syspage (format #f "~a/~a" (get-conf '(server syspage path)) file)))) (define (syspage-show file) (bv-cat (get-syspage file) #f)) (define* (artanis-log blame-who? status mime #:key (port (current-error-port)) (request #f)) (case blame-who? ((client) (when (not request) (error "artanis-log: Fatal bug! Request shouldn't be #f here!~%")) (let* ((uri (request-uri request)) (path (uri-path uri)) (qstr (uri-query uri)) (method (request-method request))) (format port "[Remote] ~a @ ~a~%" (remote-info request) (local-time-stamp)) (format port "[Request] method: ~a, path: ~a, query: ~a~%" method path qstr) (format port "[Response] status: ~a, MIME: ~a~%~%" status mime))) ((server) (format port "[Server] ~a @ ~a~%" (get-conf '(host addr)) (local-time-stamp)) (format port "[Response] status: ~a, MIME: ~a~%~%" status mime)) (else (error "artanis-log: Fatal BUG here!")))) (define *guile-compatible-server-core* '(guile fibers)) (define (is-guile-compatible-server-core? name) (memq name *guile-compatible-server-core*)) (define (render-sys-page blame-who? status request) (define-syntax-rule (status->page s) (format #f "~a.html" s)) (artanis-log blame-who? status 'text/html #:request request) (let* ((charset (get-conf '(server charset))) (mtime (generate-modify-time (current-time))) (response (build-response #:code status #:headers `((server . ,(get-conf '(server info))) (last-modified . ,mtime) (content-type . (text/html (charset . ,charset)))))) (body (syspage-show (status->page status)))) (if (is-guile-compatible-server-core? (get-conf '(server engine))) (values response body) (values response body 'exception)))) (define (format-status-page/client status request) (format (current-error-port) (ERROR-TEXT "[EXCEPTION] ~a is abnormal request, status: ~a, ") (uri-path (request-uri request)) status) (display "rendering a sys page for it...\n" (current-error-port)) (render-sys-page 'client status request)) (define (format-status-page/server status) (format (current-error-port) "[SERVER ERROR] Internal error from server-side, ") (format (current-error-port) "rendering a ~a page for client ...~%" status) (render-sys-page 'server status #f)) (define (exception-from-client request) (lambda (status) (format-status-page/client status request))) (define (exception-from-server) (lambda (status) (format-status-page/server status))) (define *rf-re* (string->irregex ".*/artanis/artanis/(.*)$")) (define (->reasonable-file filename) (if (string? filename) (let ((m (irregex-search *rf-re* filename))) (if m (format #f "artanis/~a" (irregex-match-substring m 1)) filename)) "In unknown file")) (define-syntax-rule (make-unstop-exception-handler syspage-generator) (let ((port (current-error-port)) (filename (current-filename))) (lambda (k . e) (match e (((? procedure? subr) (? string? msg) . args) (format port "Captured in <~a>~%" (WARN-TEXT (->reasonable-file filename))) (when subr (format port "In procedure ~a :~%" (WARN-TEXT (procedure-name->string subr)))) (apply format port (REASON-TEXT (string-append "[REASON] " msg)) args) (newline port)) (((? integer? status) (or (? symbol? subr) (? procedure? subr)) (? string? msg) . args) (format port "HTTP ~a~%" (STATUS-TEXT status)) (format port "Captured in <~a>~%" (WARN-TEXT (->reasonable-file filename))) (when subr (format port "Threw in procedure ~a :~%" (WARN-TEXT (if (procedure? subr) (procedure-name->string subr) subr)))) (apply format port (REASON-TEXT (string-append "[REASON] " msg)) args) (newline port) (syspage-generator status)) (else (format port "~a - ~a~%" (WARN-TEXT "BUG: invalid exception format, but we throw it anyway!") e) (apply throw k e)))))) (define* (bv-copy/share bv #:key (from 0) (type 'vu8) (size (- (bytevector-length bv) from))) (when (> size (- (bytevector-length bv) from)) (error bv-copy/share (format #f "Size(~a) is larger than the length(~a) - from(~a)!" size (bytevector-length bv) from))) (when (>= from (bytevector-length bv)) (error bv-copy/share (format #f "Can't copy from the end of the bytevector (~a)!" from))) (let* ((ptr (bytevector->pointer bv)) (new-ptr (make-pointer (+ (pointer-address ptr) from)))) (pointer->bytevector new-ptr size 0 type))) (define* (bv-backward bv offset #:key (type 'vu8) (extend 0)) (let* ((ptr (bytevector->pointer bv)) (new-ptr (make-pointer (- (pointer-address ptr) offset))) (len (bytevector-length bv))) (pointer->bytevector new-ptr (+ len extend) 0 type))) (define (artanis-list-matches irx str) (let lp ((start 0) (ret '())) (let ((m (irregex-search irx str start))) (if m (lp (irregex-match-end-index m) (cons m ret)) ret)))) (define (artanis-sys-response status port bv-body) (build-response #:code status #:port port #:headers `((server . ,(get-conf '(server info))) ,(gen-content-length bv-body) (content-type . (text/html))))) (define (char-predicate string) (let ((cs (string->char-set string))) (lambda (c) (and (not (eof-object? c)) (char-set-contains? cs c))))) (define (handle-upload thunk) (catch 'system-error thunk (lambda e (let ((errno (system-error-errno e))) (cond ((= errno ENOMEM) NOTE : Out of memory , call ( gc ) and throw 507 (format (artanis-current-output) "No memory! Run GC now!~%") (gc) (throw 'artanis-err 507 handle-upload "Server is out of RAMs, please extend more RAMs!~%")) ((= errno EIO) NOTE : The storage device was disconnected , just throw 507 (throw 'artanis-err 507 handle-upload "Server is not available, maybe storage media was disconnected?~%")) ((= errno ENOSPC) NOTE : no space for uploading , just throw 507 (throw 'artanis-err 507 handle-upload "Server has insufficient storage space!~%")) (else (apply throw e))))))) (define invalid-char-set? (char-predicate "*&-{}[]?.\\%$#@!,")) (define is-valid-table-name? (lambda (name) (not (string-any invalid-char-set? name))))
64abbcf7e10de6830fc91c2c7dbe614e226b721998f71622f695bc2926289e99
alexandergunnarson/quantum
qualify.cljc
(ns quantum.untyped.core.qualify "Functions related to qualification (name, namespace, etc.) and unqualification of nameables." (:require [clojure.string :as str] [fipp.ednize] [quantum.untyped.core.core :as ucore] [quantum.untyped.core.ns :as uns] [quantum.untyped.core.type.predicates :refer [namespace?]])) (ucore/log-this-ns) (defn named? [x] #?(:clj (instance? clojure.lang.Named x) :cljs (implements? cljs.core/INamed x))) (defn ?ns->name [?ns] (name #?(:clj (if (namespace? ?ns) (ns-name ?ns) ?ns) :cljs ?ns))) ;; ===== QUALIFICATION ===== ;; (defn qualify #?(:clj ([sym] (qualify *ns* sym))) ([?ns sym] (symbol (?ns->name ?ns) (name sym)))) (defn qualify|dot [sym ns-] (symbol (str (?ns->name ns-) "." (name sym)))) #?(:clj (defn qualify|class [sym] (symbol (str (-> *ns* ns-name name munge) "." sym)))) (defn unqualify [sym] (-> sym name symbol)) #?(:clj (defn collapse-symbol ([sym] (collapse-symbol sym true)) ([sym extra-slash?] (symbol (when-let [n (namespace sym)] (when-not (= n (-> *ns* ns-name name)) (if-let [alias- (do #?(:clj (uns/ns-name>alias *ns* (symbol n)) :cljs false))] (str alias- (when extra-slash? "/")) n))) (name sym))))) ;; ===== IDENTS ===== ;; (defrecord ^{:doc "A delimited identifier. Defaults to delimiting all qualifiers by the pipe symbol instead of slashes or dots."} DelimitedIdent [qualifiers #_(t/seq (t/and string? (t/not (fn1 contains? \|))))] fipp.ednize/IOverride fipp.ednize/IEdn (-edn [this] (tagged-literal '| (symbol (str/join "|" qualifiers))))) (defn delim-ident? [x] (instance? DelimitedIdent x))
null
https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src-untyped/quantum/untyped/core/qualify.cljc
clojure
===== QUALIFICATION ===== ;; ===== IDENTS ===== ;;
(ns quantum.untyped.core.qualify "Functions related to qualification (name, namespace, etc.) and unqualification of nameables." (:require [clojure.string :as str] [fipp.ednize] [quantum.untyped.core.core :as ucore] [quantum.untyped.core.ns :as uns] [quantum.untyped.core.type.predicates :refer [namespace?]])) (ucore/log-this-ns) (defn named? [x] #?(:clj (instance? clojure.lang.Named x) :cljs (implements? cljs.core/INamed x))) (defn ?ns->name [?ns] (name #?(:clj (if (namespace? ?ns) (ns-name ?ns) ?ns) :cljs ?ns))) (defn qualify #?(:clj ([sym] (qualify *ns* sym))) ([?ns sym] (symbol (?ns->name ?ns) (name sym)))) (defn qualify|dot [sym ns-] (symbol (str (?ns->name ns-) "." (name sym)))) #?(:clj (defn qualify|class [sym] (symbol (str (-> *ns* ns-name name munge) "." sym)))) (defn unqualify [sym] (-> sym name symbol)) #?(:clj (defn collapse-symbol ([sym] (collapse-symbol sym true)) ([sym extra-slash?] (symbol (when-let [n (namespace sym)] (when-not (= n (-> *ns* ns-name name)) (if-let [alias- (do #?(:clj (uns/ns-name>alias *ns* (symbol n)) :cljs false))] (str alias- (when extra-slash? "/")) n))) (name sym))))) (defrecord ^{:doc "A delimited identifier. Defaults to delimiting all qualifiers by the pipe symbol instead of slashes or dots."} DelimitedIdent [qualifiers #_(t/seq (t/and string? (t/not (fn1 contains? \|))))] fipp.ednize/IOverride fipp.ednize/IEdn (-edn [this] (tagged-literal '| (symbol (str/join "|" qualifiers))))) (defn delim-ident? [x] (instance? DelimitedIdent x))
9d70f4b4cac789cd3bfc064155968657dd462bfcf7e4f73adc73e7655999c403
s-cerevisiae/leetcode-racket
1006-clumsy-factorial.rkt
#lang racket (define/contract (clumsy n) (-> exact-integer? exact-integer?) (for/fold ([stack (list n)] #:result (apply + stack)) ([x (in-range (- n 1) 0 -1)] [op (in-cycle '(* / + -))]) (match* (op stack) [('* (cons y ys)) (cons (* y x) ys)] [('/ (cons y ys)) (cons (quotient y x) ys)] [('+ ys) (cons x ys)] [('- ys) (cons (- x) ys)]))) (define (clumsy2 n) (match* (n (remainder n 4)) [((or 1 2) _) n] [(3 _) 6] [(4 _) 7] [(_ 0) (+ n 1)] [(_ (or 1 2)) (+ n 2)] [(_ 3) (- n 1)]))
null
https://raw.githubusercontent.com/s-cerevisiae/leetcode-racket/e610464f05d23c2306c4cd8a0c74b5f1c401e96f/1006-clumsy-factorial.rkt
racket
#lang racket (define/contract (clumsy n) (-> exact-integer? exact-integer?) (for/fold ([stack (list n)] #:result (apply + stack)) ([x (in-range (- n 1) 0 -1)] [op (in-cycle '(* / + -))]) (match* (op stack) [('* (cons y ys)) (cons (* y x) ys)] [('/ (cons y ys)) (cons (quotient y x) ys)] [('+ ys) (cons x ys)] [('- ys) (cons (- x) ys)]))) (define (clumsy2 n) (match* (n (remainder n 4)) [((or 1 2) _) n] [(3 _) 6] [(4 _) 7] [(_ 0) (+ n 1)] [(_ (or 1 2)) (+ n 2)] [(_ 3) (- n 1)]))
5025a0536846a8e825a1962f017ffc468b394d77870d015c2f3dee8ceb441c6e
xxyzz/SICP
Exercise_3_72.rkt
#lang racket/base (require racket/stream) (require racket/list) (define (merge-weighted s1 s2 weight) (cond [(stream-empty? s1) s2] [(stream-empty? s2) s1] [else (let* ([s1car (stream-first s1)] [s2car (stream-first s2)] [weight-result (- (weight s1car) (weight s2car))]) (cond [(<= weight-result 0) (stream-cons s1car (merge-weighted (stream-rest s1) s2 weight))] ; !! [(> weight-result 0) (stream-cons s2car (merge-weighted s1 (stream-rest s2) weight))]))])) (define (weighted-pairs s t weight) (stream-cons (list (stream-first s) (stream-first t)) (merge-weighted (stream-map (lambda (x) (list (stream-first s) x)) (stream-rest t)) (weighted-pairs (stream-rest s) (stream-rest t) weight) weight))) (define (stream-map proc . argstreams) (if (stream-empty? (car argstreams)) empty-stream (stream-cons (apply proc (map stream-first argstreams)) (apply stream-map (cons proc (map stream-rest argstreams)))))) (define (add-streams s1 s2) (stream-map + s1 s2)) (define ones (stream-cons 1 ones)) (define integers (stream-cons 1 (add-streams ones integers))) (define (square x) (expt x 2)) (define (weight-procedure x) (+ (square (first x)) (square (second x)))) (define S (weighted-pairs integers integers weight-procedure)) (define sum-of-square (stream-filter (lambda (x) (not (zero? x))) (stream-map (lambda (x y z) (let ([x-weight (weight-procedure x)] [y-weight (weight-procedure y)] [z-weight (weight-procedure z)]) (if (= x-weight y-weight z-weight) (begin (displayln (list x-weight x y z)) x-weight) 0))) S (stream-rest S) (stream-rest (stream-rest S))))) (stream->list (stream-take sum-of-square 6)) ( 325 ( 1 18 ) ( 6 17 ) ( 10 15 ) ) ( 425 ( 5 20 ) ( 8 19 ) ( 13 16 ) ) ( 650 ( 5 25 ) ( 11 23 ) ( 17 19 ) ) ( 725 ( 7 26 ) ( 10 25 ) ( 14 23 ) ) ( 845 ( 2 29 ) ( 13 26 ) ( 19 22 ) ) ( 850 ( 3 29 ) ( 11 27 ) ( 15 25 ) ) ' ( 325 425 650 725 845 850 )
null
https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/3_Modularity_Objects_and_State/3.5_Streams/Exercise_3_72.rkt
racket
!!
#lang racket/base (require racket/stream) (require racket/list) (define (merge-weighted s1 s2 weight) (cond [(stream-empty? s1) s2] [(stream-empty? s2) s1] [else (let* ([s1car (stream-first s1)] [s2car (stream-first s2)] [weight-result (- (weight s1car) (weight s2car))]) (cond [(<= weight-result 0) (stream-cons s1car [(> weight-result 0) (stream-cons s2car (merge-weighted s1 (stream-rest s2) weight))]))])) (define (weighted-pairs s t weight) (stream-cons (list (stream-first s) (stream-first t)) (merge-weighted (stream-map (lambda (x) (list (stream-first s) x)) (stream-rest t)) (weighted-pairs (stream-rest s) (stream-rest t) weight) weight))) (define (stream-map proc . argstreams) (if (stream-empty? (car argstreams)) empty-stream (stream-cons (apply proc (map stream-first argstreams)) (apply stream-map (cons proc (map stream-rest argstreams)))))) (define (add-streams s1 s2) (stream-map + s1 s2)) (define ones (stream-cons 1 ones)) (define integers (stream-cons 1 (add-streams ones integers))) (define (square x) (expt x 2)) (define (weight-procedure x) (+ (square (first x)) (square (second x)))) (define S (weighted-pairs integers integers weight-procedure)) (define sum-of-square (stream-filter (lambda (x) (not (zero? x))) (stream-map (lambda (x y z) (let ([x-weight (weight-procedure x)] [y-weight (weight-procedure y)] [z-weight (weight-procedure z)]) (if (= x-weight y-weight z-weight) (begin (displayln (list x-weight x y z)) x-weight) 0))) S (stream-rest S) (stream-rest (stream-rest S))))) (stream->list (stream-take sum-of-square 6)) ( 325 ( 1 18 ) ( 6 17 ) ( 10 15 ) ) ( 425 ( 5 20 ) ( 8 19 ) ( 13 16 ) ) ( 650 ( 5 25 ) ( 11 23 ) ( 17 19 ) ) ( 725 ( 7 26 ) ( 10 25 ) ( 14 23 ) ) ( 845 ( 2 29 ) ( 13 26 ) ( 19 22 ) ) ( 850 ( 3 29 ) ( 11 27 ) ( 15 25 ) ) ' ( 325 425 650 725 845 850 )
901387ae96f915c437f029c4376216e32a12f5be33def098148608bd6d603922
ivanjovanovic/sicp
e-3.26.scm
Exercise 3.26 . ; ; To search a table as implemented above, one needs to scan ; through the list of records. This is basically the unordered list representation of section 2.3.3 . For large tables , it may be more efficient ; to structure the table in a different manner. Describe a table implementation ; where the (key, value) records are organized using a binary tree, assuming ; that keys can be ordered in some way (e.g., numerically or alphabetically). ( Compare exercise 2.66 of chapter 2 . ) ; ------------------------------------------------------------ (load "../helpers.scm") ; In previous exercise we have implemented unlimited nesting of ; linked lists. In this one, every simple list is implemeted as a tree ; and to make it hierarchically generic we implement our table so it ; is constructed by nesting these binary trees. ; ; first we need way to build ordered list represented as the tree from 2.3-binary-trees.scm we take already defined elements ; tree abstraction, constructor and selectors (define (make-tree entry left right) (list entry left right)) (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) ; then we need a way to add element to the tree and to maintain it as ; ordered. Our element here is a (key, value) pair where we order by ; numerical value of the key. (define (adjoin-tree element tree) (cond ((null? tree) (make-tree element '() '())) ((= (key element) (key (entry tree))) tree) ((< (key element) (key (entry tree))) (make-tree (entry tree) (adjoin-tree element (left-branch tree)) (right-branch tree))) ((> (key element) (key (entry tree))) (make-tree (entry tree) (left-branch tree) (adjoin-tree element (right-branch tree)))))) ; to find element in the tree we use (define (lookup-tree lookup-key tree) (cond ((null? tree) '#f) ((= lookup-key (key (entry tree))) (entry tree)) ((< lookup-key (key (entry tree))) (lookup-tree lookup-key (left-branch tree))) ((> lookup-key (key (entry tree))) (lookup-tree lookup-key (right-branch tree))))) ; in previous procedure we used simple selector for getting key out of element (define (key element) (car element)) ; testing tree creation (define t (adjoin-tree (cons 100 'a) '())) (define t (adjoin-tree (cons 200 'b) t)) (define t (adjoin-tree (cons 50 'b) t)) (define t (adjoin-tree (cons 1000 'b) t)) (define t (adjoin-tree (cons 10 'b) t)) ( ( 100 . a ) ( ( 50 . b ) ( ( 10 . b ) ( ) ( ) ) ( ) ) ( ( 200 . b ) ( ) ( ( 1000 . b ) ( ) ( ) ) ) ) ; (output t) ( output ( lookup - tree 100 t ) ) ; ( 100 . a ) ( output ( lookup - tree 1000 t ) ) ; ( 1000 . b ) ; (output (lookup-tree 1 t)) ; #f ; now that we can make simple tree, we can make our nested table by nesting ; them instead nesting lists. I'll make it as a message dispatcher function with the ; nested state (define (make-table) (let ((local-table (list '*tabler))) (define (lookup keys) (define (lookup-recursive keys table) (let ((subtable (lookup-tree (car keys) (cdr table)))) (if subtable (if (null? (cdr keys)) (cdr subtable) (lookup-recursive (cdr keys) subtable)) '#f))) (lookup-recursive keys local-table)) (define (insert! keys value) (define (make-elements keys) (if (null? (cdr keys)) (cons (car keys) value) (cons (car keys) (make-tree (make-elements (cdr keys)) '() '())))) (define (insert-recursive! keys table) (let ((subtable (lookup-tree (car keys) (cdr table)))) (if subtable (if (null? (cdr keys)) (set-cdr! subtable value) (insert-recursive! (cdr keys) subtable)) (set-cdr! table (adjoin-tree (make-elements keys) (cdr table)))))) (insert-recursive! keys local-table)) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) ; do some testing (define t (make-table)) (define put (t 'insert-proc!)) (define get (t 'lookup-proc)) (put '(100) 'a) ( output ( get ' ( 100 ) ) ) ( output ( get ' ( 1000 ) ) ) (put '(1000) 'b) ( output ( get ' ( 1000 ) ) ) ; Since this is not a perfect implementation it doesnt cover the case when you already have defined ( put ' ( 100 ) ' a ) and want to define over it ( put ' ( 100 200 ) ' c ) , it will throw an error . It needs one more check in the code (define t (make-table)) (define put (t 'insert-proc!)) (define get (t 'lookup-proc)) (put '(100 200) 'c) (put '(100 300) 'd) ( output ( get ' ( 100 200 ) ) ) ( output ( get ' ( 100 300 ) ) ) Comparison with exercise 2.66 ; In 2.66 we have only one binary tree in concern and the lookup ; procedure to find element inside it. ; In this exercise, we reuse the abstraction of the binary tree for representing ordered set , but go one level of abstraction higher to make these trees nestable in a generic way . So , on one level of the tree we have comparison by keys and value of every element of the tree can contain ; either value or subtree which is again ordered by the key and can contain other subtrees.
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.3/e-3.26.scm
scheme
To search a table as implemented above, one needs to scan through the list of records. This is basically the unordered list to structure the table in a different manner. Describe a table implementation where the (key, value) records are organized using a binary tree, assuming that keys can be ordered in some way (e.g., numerically or alphabetically). ------------------------------------------------------------ In previous exercise we have implemented unlimited nesting of linked lists. In this one, every simple list is implemeted as a tree and to make it hierarchically generic we implement our table so it is constructed by nesting these binary trees. first we need way to build ordered list represented as the tree tree abstraction, constructor and selectors then we need a way to add element to the tree and to maintain it as ordered. Our element here is a (key, value) pair where we order by numerical value of the key. to find element in the tree we use in previous procedure we used simple selector for getting key out of element testing tree creation (output t) ( 100 . a ) ( 1000 . b ) (output (lookup-tree 1 t)) ; #f now that we can make simple tree, we can make our nested table by nesting them instead nesting lists. I'll make it as a message dispatcher function with the nested state do some testing Since this is not a perfect implementation it doesnt cover the case procedure to find element inside it. In this exercise, we reuse the abstraction of the binary tree for representing either value or subtree which is again ordered by the key and can contain other subtrees.
Exercise 3.26 . representation of section 2.3.3 . For large tables , it may be more efficient ( Compare exercise 2.66 of chapter 2 . ) (load "../helpers.scm") from 2.3-binary-trees.scm we take already defined elements (define (make-tree entry left right) (list entry left right)) (define (entry tree) (car tree)) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (adjoin-tree element tree) (cond ((null? tree) (make-tree element '() '())) ((= (key element) (key (entry tree))) tree) ((< (key element) (key (entry tree))) (make-tree (entry tree) (adjoin-tree element (left-branch tree)) (right-branch tree))) ((> (key element) (key (entry tree))) (make-tree (entry tree) (left-branch tree) (adjoin-tree element (right-branch tree)))))) (define (lookup-tree lookup-key tree) (cond ((null? tree) '#f) ((= lookup-key (key (entry tree))) (entry tree)) ((< lookup-key (key (entry tree))) (lookup-tree lookup-key (left-branch tree))) ((> lookup-key (key (entry tree))) (lookup-tree lookup-key (right-branch tree))))) (define (key element) (car element)) (define t (adjoin-tree (cons 100 'a) '())) (define t (adjoin-tree (cons 200 'b) t)) (define t (adjoin-tree (cons 50 'b) t)) (define t (adjoin-tree (cons 1000 'b) t)) (define t (adjoin-tree (cons 10 'b) t)) ( ( 100 . a ) ( ( 50 . b ) ( ( 10 . b ) ( ) ( ) ) ( ) ) ( ( 200 . b ) ( ) ( ( 1000 . b ) ( ) ( ) ) ) ) (define (make-table) (let ((local-table (list '*tabler))) (define (lookup keys) (define (lookup-recursive keys table) (let ((subtable (lookup-tree (car keys) (cdr table)))) (if subtable (if (null? (cdr keys)) (cdr subtable) (lookup-recursive (cdr keys) subtable)) '#f))) (lookup-recursive keys local-table)) (define (insert! keys value) (define (make-elements keys) (if (null? (cdr keys)) (cons (car keys) value) (cons (car keys) (make-tree (make-elements (cdr keys)) '() '())))) (define (insert-recursive! keys table) (let ((subtable (lookup-tree (car keys) (cdr table)))) (if subtable (if (null? (cdr keys)) (set-cdr! subtable value) (insert-recursive! (cdr keys) subtable)) (set-cdr! table (adjoin-tree (make-elements keys) (cdr table)))))) (insert-recursive! keys local-table)) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define t (make-table)) (define put (t 'insert-proc!)) (define get (t 'lookup-proc)) (put '(100) 'a) ( output ( get ' ( 100 ) ) ) ( output ( get ' ( 1000 ) ) ) (put '(1000) 'b) ( output ( get ' ( 1000 ) ) ) when you already have defined ( put ' ( 100 ) ' a ) and want to define over it ( put ' ( 100 200 ) ' c ) , it will throw an error . It needs one more check in the code (define t (make-table)) (define put (t 'insert-proc!)) (define get (t 'lookup-proc)) (put '(100 200) 'c) (put '(100 300) 'd) ( output ( get ' ( 100 200 ) ) ) ( output ( get ' ( 100 300 ) ) ) Comparison with exercise 2.66 In 2.66 we have only one binary tree in concern and the lookup ordered set , but go one level of abstraction higher to make these trees nestable in a generic way . So , on one level of the tree we have comparison by keys and value of every element of the tree can contain
86274bae22e7aa71888271222bf1f705eb5c241bf6e3b9eb64689bca916a93f5
sydow/ireal
IntegerInterval.hs
module Data.Number.IReal.IntegerInterval where import Data.Number.IReal.Powers import Data.Bits data IntegerInterval = I (Integer, Integer) deriving Show -- (lower,upper) -- make sure interval is not too thin upto :: Integer -> Integer -> IntegerInterval l `upto` u = I (l, max u (l+2)) midI, radI, lowerI, upperI :: IntegerInterval -> Integer midI (I (l,u)) = shift (l+u) (-1) radI (I (l,u)) = shift (u-l+1) (-1) lowerI (I (l,_)) = l upperI (I (_,u)) = u isThin :: IntegerInterval -> Bool isThin (I (l,u)) = u == l+2 ivalCase :: IntegerInterval -> a -> a -> a -> a ivalCase (I (l,u)) pos neg zer | l >= 0 = pos | u <= 0 = neg | otherwise = zer instance Num IntegerInterval where I (l1,u1) + I (l2,u2) = I (l1+l2,u1+u2) i1@(I (l1,u1)) * i2@(I (l2,u2)) = ivalCase i1 (f (l1*l2,u1*u2) (u1*l2,l1*u2) (u1*l2,u1*u2)) (f (l1*u2,u1*l2) (u1*u2,l1*l2) (l1*u2,l1*l2)) (f (l1*u2,u1*u2) (u1*l2,l1*u2) (min (l1*u2) (u1*l2),max (l1*l2) (u1*u2))) where f x y z = ivalCase i2 (I x) (I y) (I z) abs i@(I (l,u)) = ivalCase i i (-i) (0 `upto` max (-l) u) negate (I (l,u)) = I (-u,-l) signum i = ivalCase i 1 (-1) (error "signum (for IntegerInterval): argument includes 0") fromInteger n = I (n-1,n+1) instance Powers IntegerInterval where pow i@(I (l,u)) n |even n = ivalCase i (I (l^n,u^n)) (I (u^n,l^n)) (0 `upto` (max (-l) u) ^ n) |otherwise =I (l^n,u^n)
null
https://raw.githubusercontent.com/sydow/ireal/c06438544c711169baac7960540202379f9294b1/Data/Number/IReal/IntegerInterval.hs
haskell
(lower,upper) make sure interval is not too thin
module Data.Number.IReal.IntegerInterval where import Data.Number.IReal.Powers import Data.Bits upto :: Integer -> Integer -> IntegerInterval l `upto` u = I (l, max u (l+2)) midI, radI, lowerI, upperI :: IntegerInterval -> Integer midI (I (l,u)) = shift (l+u) (-1) radI (I (l,u)) = shift (u-l+1) (-1) lowerI (I (l,_)) = l upperI (I (_,u)) = u isThin :: IntegerInterval -> Bool isThin (I (l,u)) = u == l+2 ivalCase :: IntegerInterval -> a -> a -> a -> a ivalCase (I (l,u)) pos neg zer | l >= 0 = pos | u <= 0 = neg | otherwise = zer instance Num IntegerInterval where I (l1,u1) + I (l2,u2) = I (l1+l2,u1+u2) i1@(I (l1,u1)) * i2@(I (l2,u2)) = ivalCase i1 (f (l1*l2,u1*u2) (u1*l2,l1*u2) (u1*l2,u1*u2)) (f (l1*u2,u1*l2) (u1*u2,l1*l2) (l1*u2,l1*l2)) (f (l1*u2,u1*u2) (u1*l2,l1*u2) (min (l1*u2) (u1*l2),max (l1*l2) (u1*u2))) where f x y z = ivalCase i2 (I x) (I y) (I z) abs i@(I (l,u)) = ivalCase i i (-i) (0 `upto` max (-l) u) negate (I (l,u)) = I (-u,-l) signum i = ivalCase i 1 (-1) (error "signum (for IntegerInterval): argument includes 0") fromInteger n = I (n-1,n+1) instance Powers IntegerInterval where pow i@(I (l,u)) n |even n = ivalCase i (I (l^n,u^n)) (I (u^n,l^n)) (0 `upto` (max (-l) u) ^ n) |otherwise =I (l^n,u^n)
68ac786efa629a090a03d157a805ad53884fd3757c626420d44f5c6f741e22f9
EarnestResearch/honeycomb-haskell
Spec.hs
import qualified ApiSpec import qualified HoneycombSpec import Test.Hspec import qualified TraceSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Api" ApiSpec.spec describe "Honeycomb" HoneycombSpec.spec describe "Trace" TraceSpec.spec
null
https://raw.githubusercontent.com/EarnestResearch/honeycomb-haskell/0cb643a637e1b23eecded845970e6a973f8385cf/honeycomb/test/Spec.hs
haskell
import qualified ApiSpec import qualified HoneycombSpec import Test.Hspec import qualified TraceSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "Api" ApiSpec.spec describe "Honeycomb" HoneycombSpec.spec describe "Trace" TraceSpec.spec
7a8398abf6c4d7acd767c9a74a0283441acc756f111f88c253abfab41b1477d7
google-research/dex-lang
Err.hs
Copyright 2021 Google LLC -- -- Use of this source code is governed by a BSD-style -- license that can be found in the LICENSE file or at -- -source/licenses/bsd module Err (Err (..), Errs (..), ErrType (..), Except (..), ErrCtx (..), SrcPosCtx, SrcTextCtx, SrcPos, Fallible (..), Catchable (..), catchErrExcept, FallibleM (..), HardFailM (..), CtxReader (..), runFallibleM, runHardFail, throw, throwErr, addContext, addSrcContext, addSrcTextContext, catchIOExcept, liftExcept, liftExceptAlt, assertEq, ignoreExcept, pprint, docAsStr, getCurrentCallStack, printCurrentCallStack, FallibleApplicativeWrapper, traverseMergingErrs, SearcherM (..), Searcher (..), runSearcherM) where import Control.Exception hiding (throw) import Control.Applicative import Control.Monad import Control.Monad.Trans.Maybe import Control.Monad.Identity import Control.Monad.Writer.Strict import Control.Monad.State.Strict import Control.Monad.Reader import Data.Coerce import Data.Foldable (fold) import Data.Text (Text) import Data.Text qualified as T import Data.Text.Prettyprint.Doc.Render.Text import Data.Text.Prettyprint.Doc import GHC.Stack import System.Environment import System.IO.Unsafe -- === core API === data Err = Err ErrType ErrCtx String deriving (Show, Eq) newtype Errs = Errs [Err] deriving (Eq, Semigroup, Monoid) data ErrType = NoErr | ParseErr | SyntaxErr | TypeErr | KindErr | LinErr | VarDefErr | UnboundVarErr | AmbiguousVarErr | RepeatedVarErr | RepeatedPatVarErr | InvalidPatternErr | CompilerErr | IRVariantErr | NotImplementedErr | DataIOErr | MiscErr | RuntimeErr | ZipErr | EscapedNameErr | ModuleImportErr | MonadFailErr deriving (Show, Eq) type SrcPosCtx = Maybe SrcPos type SrcTextCtx = Maybe (Int, Text) -- Int is the offset in the source file data ErrCtx = ErrCtx { srcTextCtx :: SrcTextCtx , srcPosCtx :: SrcPosCtx , messageCtx :: [String] , stackCtx :: Maybe [String] } deriving (Show, Eq) type SrcPos = (Int, Int) class MonadFail m => Fallible m where throwErrs :: Errs -> m a addErrCtx :: ErrCtx -> m a -> m a class Fallible m => Catchable m where catchErr :: m a -> (Errs -> m a) -> m a catchErrExcept :: Catchable m => m a -> m (Except a) catchErrExcept m = catchErr (Success <$> m) (\e -> return $ Failure e) We have this in its own class because IO and ` Except ` ca n't implement it ( but FallibleM can ) class Fallible m => CtxReader m where getErrCtx :: m ErrCtx -- We have this in its own class because StateT can't implement it ( but FallibleM , Except and IO all can ) class Fallible m => FallibleApplicative m where mergeErrs :: m a -> m b -> m (a, b) newtype FallibleM a = FallibleM { fromFallibleM :: ReaderT ErrCtx Except a } deriving (Functor, Applicative, Monad) instance Fallible FallibleM where throwErrs (Errs errs) = FallibleM $ ReaderT \ambientCtx -> throwErrs $ Errs [Err errTy (ambientCtx <> ctx) s | Err errTy ctx s <- errs] # INLINE throwErrs # addErrCtx ctx (FallibleM m) = FallibleM $ local (<> ctx) m {-# INLINE addErrCtx #-} instance Catchable FallibleM where FallibleM m `catchErr` handler = FallibleM $ ReaderT \ctx -> case runReaderT m ctx of Failure errs -> runReaderT (fromFallibleM $ handler errs) ctx Success ans -> return ans instance FallibleApplicative FallibleM where mergeErrs (FallibleM (ReaderT f1)) (FallibleM (ReaderT f2)) = FallibleM $ ReaderT \ctx -> mergeErrs (f1 ctx) (f2 ctx) instance CtxReader FallibleM where getErrCtx = FallibleM ask # INLINE getErrCtx # instance Fallible IO where throwErrs errs = throwIO errs # INLINE throwErrs # addErrCtx ctx m = do result <- catchIOExcept m liftExcept $ addErrCtx ctx result {-# INLINE addErrCtx #-} instance Catchable IO where catchErr cont handler = catchIOExcept cont >>= \case Success result -> return result Failure errs -> handler errs instance FallibleApplicative IO where mergeErrs m1 m2 = do result1 <- catchIOExcept m1 result2 <- catchIOExcept m2 liftExcept $ mergeErrs result1 result2 runFallibleM :: FallibleM a -> Except a runFallibleM m = runReaderT (fromFallibleM m) mempty {-# INLINE runFallibleM #-} -- === Except type === Except is isomorphic to ` Either Errs ` but having a distinct type makes it -- easier to debug type errors. data Except a = Failure Errs | Success a deriving (Show, Eq) instance Functor Except where fmap = liftM # INLINE fmap # instance Applicative Except where pure = return # INLINE pure # liftA2 = liftM2 # INLINE liftA2 # instance Monad Except where return = Success # INLINE return # Failure errs >>= _ = Failure errs Success x >>= f = f x {-# INLINE (>>=) #-} -- === FallibleApplicativeWrapper === Wraps a Fallible monad , presenting an applicative interface that sequences -- actions using the error-concatenating `mergeErrs` instead of the default -- abort-on-failure sequencing. newtype FallibleApplicativeWrapper m a = FallibleApplicativeWrapper { fromFallibleApplicativeWrapper :: m a } deriving (Functor) instance FallibleApplicative m => Applicative (FallibleApplicativeWrapper m) where pure x = FallibleApplicativeWrapper $ pure x # INLINE pure # liftA2 f (FallibleApplicativeWrapper m1) (FallibleApplicativeWrapper m2) = FallibleApplicativeWrapper $ fmap (uncurry f) (mergeErrs m1 m2) # INLINE liftA2 # = = = HardFail = = = -- Implements Fallible by crashing. Used in type querying when we want to avoid work by trusting annotations and skipping the checks . newtype HardFailM a = HardFailM { runHardFail' :: Identity a } We do n't derive Functor , Applicative and , because Identity does n't -- use INLINE pragmas in its own instances, which unnecessarily inhibits optimizations. instance Functor HardFailM where fmap f (HardFailM (Identity x)) = HardFailM $ Identity $ f x # INLINE fmap # instance Applicative HardFailM where pure = HardFailM . Identity # INLINE pure # (<*>) = coerce {-# INLINE (<*>) #-} liftA2 = coerce # INLINE liftA2 # instance Monad HardFailM where (HardFailM (Identity x)) >>= k = k x {-# INLINE (>>=) #-} return = HardFailM . Identity # INLINE return # runHardFail :: HardFailM a -> a runHardFail m = runIdentity $ runHardFail' m # INLINE runHardFail # instance MonadFail HardFailM where fail s = error s # INLINE fail # instance Fallible HardFailM where throwErrs errs = error $ pprint errs # INLINE throwErrs # addErrCtx _ cont = cont {-# INLINE addErrCtx #-} instance FallibleApplicative HardFailM where mergeErrs cont1 cont2 = (,) <$> cont1 <*> cont2 -- === convenience layer === throw :: Fallible m => ErrType -> String -> m a throw errTy s = throwErrs $ Errs [addCompilerStackCtx $ Err errTy mempty s] {-# INLINE throw #-} throwErr :: Fallible m => Err -> m a throwErr err = throwErrs $ Errs [addCompilerStackCtx err] # INLINE throwErr # addCompilerStackCtx :: Err -> Err addCompilerStackCtx (Err ty ctx msg) = Err ty ctx{stackCtx = compilerStack} msg where #ifdef DEX_DEBUG compilerStack = getCurrentCallStack () #else compilerStack = stackCtx ctx #endif getCurrentCallStack :: () -> Maybe [String] getCurrentCallStack () = #ifdef DEX_DEBUG case reverse (unsafePerformIO currentCallStack) of [] -> Nothing stack -> Just stack #else Nothing #endif # NOINLINE getCurrentCallStack # printCurrentCallStack :: Maybe [String] -> String printCurrentCallStack Nothing = "<no call stack available>" printCurrentCallStack (Just frames) = fold frames addContext :: Fallible m => String -> m a -> m a addContext s m = addErrCtx (mempty {messageCtx = [s]}) m # INLINE addContext # addSrcContext :: Fallible m => SrcPosCtx -> m a -> m a addSrcContext ctx m = addErrCtx (mempty {srcPosCtx = ctx}) m # INLINE addSrcContext # addSrcTextContext :: Fallible m => Int -> Text -> m a -> m a addSrcTextContext offset text m = addErrCtx (mempty {srcTextCtx = Just (offset, text)}) m catchIOExcept :: MonadIO m => IO a -> m (Except a) catchIOExcept m = liftIO $ (liftM Success m) `catches` [ Handler \(e::Errs) -> return $ Failure e , Handler \(e::IOError) -> return $ Failure $ Errs [Err DataIOErr mempty $ show e] -- Propagate asynchronous exceptions like ThreadKilled; they are -- part of normal operation (of the live evaluation modes), not -- compiler bugs. , Handler \(e::AsyncException) -> liftIO $ throwIO e , Handler \(e::SomeException) -> return $ Failure $ Errs [Err CompilerErr mempty $ show e] ] liftExcept :: Fallible m => Except a -> m a liftExcept (Failure errs) = throwErrs errs liftExcept (Success ans) = return ans # INLINE liftExcept # liftExceptAlt :: Alternative m => Except a -> m a liftExceptAlt = \case Success a -> pure a Failure _ -> empty # INLINE liftExceptAlt # ignoreExcept :: HasCallStack => Except a -> a ignoreExcept (Failure e) = error $ pprint e ignoreExcept (Success x) = x # INLINE ignoreExcept # assertEq :: (HasCallStack, Fallible m, Show a, Pretty a, Eq a) => a -> a -> String -> m () assertEq x y s = if x == y then return () else throw CompilerErr msg where msg = "assertion failure (" ++ s ++ "):\n" ++ pprint x ++ " != " ++ pprint y ++ "\n\n" ++ prettyCallStack callStack ++ "\n" -- === search monad === infix 0 <!> class (Monad m, Alternative m) => Searcher m where Runs the second computation when the first yields an empty set of results . -- This is just `<|>` for greedy searchers like `Maybe`, but in other cases, like the list monad , it matters that the second computation is n't run if the first succeeds . (<!>) :: m a -> m a -> m a Adds an extra error case to ` FallibleM ` so we can give it an Alternative -- instance with an identity element. newtype SearcherM a = SearcherM { runSearcherM' :: MaybeT FallibleM a } deriving (Functor, Applicative, Monad) runSearcherM :: SearcherM a -> Except (Maybe a) runSearcherM m = runFallibleM $ runMaybeT (runSearcherM' m) # INLINE runSearcherM # instance MonadFail SearcherM where fail _ = SearcherM $ MaybeT $ return Nothing # INLINE fail # instance Fallible SearcherM where throwErrs e = SearcherM $ lift $ throwErrs e # INLINE throwErrs # addErrCtx ctx (SearcherM (MaybeT m)) = SearcherM $ MaybeT $ addErrCtx ctx $ m {-# INLINE addErrCtx #-} instance Alternative SearcherM where empty = SearcherM $ MaybeT $ return Nothing SearcherM (MaybeT m1) <|> SearcherM (MaybeT m2) = SearcherM $ MaybeT do m1 >>= \case Just ans -> return $ Just ans Nothing -> m2 instance Searcher SearcherM where (<!>) = (<|>) {-# INLINE (<!>) #-} instance CtxReader SearcherM where getErrCtx = SearcherM $ lift getErrCtx # INLINE getErrCtx # instance Searcher [] where [] <!> m = m m <!> _ = m {-# INLINE (<!>) #-} instance (Monoid w, Searcher m) => Searcher (WriterT w m) where WriterT m1 <!> WriterT m2 = WriterT (m1 <!> m2) {-# INLINE (<!>) #-} instance (Monoid w, Fallible m) => Fallible (WriterT w m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (WriterT m) = WriterT $ addErrCtx ctx m {-# INLINE addErrCtx #-} instance Searcher m => Searcher (ReaderT r m) where ReaderT f1 <!> ReaderT f2 = ReaderT \r -> f1 r <!> f2 r {-# INLINE (<!>) #-} instance Fallible [] where throwErrs _ = [] # INLINE throwErrs # addErrCtx _ m = m {-# INLINE addErrCtx #-} instance Fallible Maybe where throwErrs _ = Nothing # INLINE throwErrs # addErrCtx _ m = m {-# INLINE addErrCtx #-} -- === small pretty-printing utils === -- These are here instead of in PPrint.hs for import cycle reasons pprint :: Pretty a => a -> String pprint x = docAsStr $ pretty x # SCC pprint # docAsStr :: Doc ann -> String docAsStr doc = T.unpack $ renderStrict $ layoutPretty layout $ doc layout :: LayoutOptions layout = if unbounded then LayoutOptions Unbounded else defaultLayoutOptions where unbounded = unsafePerformIO $ (Just "1"==) <$> lookupEnv "DEX_PPRINT_UNBOUNDED" traverseMergingErrs :: (Traversable f, FallibleApplicative m) => (a -> m b) -> f a -> m (f b) traverseMergingErrs f xs = fromFallibleApplicativeWrapper $ traverse (\x -> FallibleApplicativeWrapper $ f x) xs -- === instances === instance MonadFail FallibleM where fail s = throw MonadFailErr s # INLINE fail # instance Fallible Except where throwErrs errs = Failure errs # INLINE throwErrs # addErrCtx _ (Success ans) = Success ans addErrCtx ctx (Failure (Errs errs)) = Failure $ Errs [Err errTy (ctx <> ctx') s | Err errTy ctx' s <- errs] {-# INLINE addErrCtx #-} instance FallibleApplicative Except where mergeErrs (Success x) (Success y) = Success (x, y) mergeErrs x y = Failure (getErrs x <> getErrs y) where getErrs :: Except a -> Errs getErrs = \case Failure e -> e Success _ -> mempty instance MonadFail Except where fail s = Failure $ Errs [Err CompilerErr mempty s] # INLINE fail # instance Exception Errs instance Show Errs where show errs = pprint errs instance Pretty Err where pretty (Err e ctx s) = pretty e <> pretty s <> prettyCtx -- TODO: figure out a more uniform way to newlines where prettyCtx = case ctx of ErrCtx _ Nothing [] Nothing -> mempty _ -> hardline <> pretty ctx instance Pretty ErrCtx where pretty (ErrCtx maybeTextCtx maybePosCtx messages stack) = -- The order of messages is outer-scope-to-inner-scope, but we want to print -- them starting the other way around (Not for a good reason. It's just what -- we've always done.) prettyLines (reverse messages) <> highlightedSource <> prettyStack where highlightedSource = case (maybeTextCtx, maybePosCtx) of (Just (offset, text), Just (start, stop)) -> hardline <> pretty (highlightRegion (start - offset, stop - offset) text) _ -> mempty prettyStack = case stack of Nothing -> mempty Just s -> hardline <> "Compiler stack trace:" <> nest 2 (hardline <> prettyLines s) instance Pretty a => Pretty (Except a) where pretty (Success x) = "Success:" <+> pretty x pretty (Failure e) = "Failure:" <+> pretty e instance Pretty ErrType where pretty e = case e of NoErr tags a chunk of output that was promoted into the Err ADT -- by appending Results. NoErr -> "" ParseErr -> "Parse error:" SyntaxErr -> "Syntax error: " TypeErr -> "Type error:" KindErr -> "Kind error:" LinErr -> "Linearity error: " IRVariantErr -> "Internal IR validation error: " VarDefErr -> "Error in (earlier) definition of variable: " UnboundVarErr -> "Error: variable not in scope: " AmbiguousVarErr -> "Error: ambiguous variable: " RepeatedVarErr -> "Error: variable already defined: " RepeatedPatVarErr -> "Error: variable already defined within pattern: " InvalidPatternErr -> "Error: not a valid pattern: " NotImplementedErr -> "Not implemented:" <> line <> "Please report this at github.com/google-research/dex-lang/issues\n" <> line CompilerErr -> "Compiler bug!" <> line <> "Please report this at github.com/google-research/dex-lang/issues\n" <> line DataIOErr -> "IO error: " MiscErr -> "Error:" RuntimeErr -> "Runtime error" ZipErr -> "Zipping error" EscapedNameErr -> "Leaked local variables:" ModuleImportErr -> "Module import error: " MonadFailErr -> "MonadFail error (internal error)" instance Fallible m => Fallible (ReaderT r m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (ReaderT f) = ReaderT \r -> addErrCtx ctx $ f r {-# INLINE addErrCtx #-} instance Catchable m => Catchable (ReaderT r m) where ReaderT f `catchErr` handler = ReaderT \r -> f r `catchErr` \e -> runReaderT (handler e) r instance FallibleApplicative m => FallibleApplicative (ReaderT r m) where mergeErrs (ReaderT f1) (ReaderT f2) = ReaderT \r -> mergeErrs (f1 r) (f2 r) instance CtxReader m => CtxReader (ReaderT r m) where getErrCtx = lift getErrCtx # INLINE getErrCtx # instance Pretty Errs where pretty (Errs [err]) = pretty err pretty (Errs errs) = prettyLines errs instance Fallible m => Fallible (StateT s m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (StateT f) = StateT \s -> addErrCtx ctx $ f s {-# INLINE addErrCtx #-} instance Catchable m => Catchable (StateT s m) where StateT f `catchErr` handler = StateT \s -> f s `catchErr` \e -> runStateT (handler e) s instance CtxReader m => CtxReader (StateT s m) where getErrCtx = lift getErrCtx # INLINE getErrCtx # instance Semigroup ErrCtx where ErrCtx text pos ctxStrs stk <> ErrCtx text' pos' ctxStrs' stk' = ErrCtx (leftmostJust text text') (rightmostJust pos pos' ) (ctxStrs <> ctxStrs') (leftmostJust stk stk') -- We usually extend errors form the right instance Monoid ErrCtx where mempty = ErrCtx Nothing Nothing [] Nothing -- === misc util stuff === leftmostJust :: Maybe a -> Maybe a -> Maybe a leftmostJust (Just x) _ = Just x leftmostJust Nothing y = y rightmostJust :: Maybe a -> Maybe a -> Maybe a rightmostJust = flip leftmostJust prettyLines :: (Foldable f, Pretty a) => f a -> Doc ann prettyLines xs = foldMap (\d -> pretty d <> hardline) xs highlightRegion :: (Int, Int) -> Text -> Text highlightRegion pos@(low, high) s | low > high || high > T.length s = error $ "Bad region: \n" ++ show pos ++ "\n" ++ T.unpack s | otherwise = -- TODO: flag to control line numbers ( disabling for now because it makes quine tests tricky ) -- "Line " ++ show (1 + lineNum) ++ "\n" allLines !! lineNum <> "\n" <> T.replicate start " " <> T.replicate (stop - start) "^" <> "\n" where allLines = T.lines s (lineNum, start, stop) = getPosTriple pos allLines getPosTriple :: (Int, Int) -> [Text] -> (Int, Int, Int) getPosTriple (start, stop) lines_ = (lineNum, start - offset, stop') where lineLengths = map ((+1) . T.length) lines_ lineOffsets = cumsum lineLengths lineNum = maxLT lineOffsets start offset = lineOffsets !! lineNum stop' = min (stop - offset) (lineLengths !! lineNum) cumsum :: [Int] -> [Int] cumsum xs = scanl (+) 0 xs maxLT :: Ord a => [a] -> a -> Int maxLT [] _ = 0 maxLT (x:xs) n = if n < x then -1 else 1 + maxLT xs n
null
https://raw.githubusercontent.com/google-research/dex-lang/d73f60dd359de6b0a06a706afc7429ee1a11bc7d/src/lib/Err.hs
haskell
Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at -source/licenses/bsd === core API === Int is the offset in the source file We have this in its own class because StateT can't implement it # INLINE addErrCtx # # INLINE addErrCtx # # INLINE runFallibleM # === Except type === easier to debug type errors. # INLINE (>>=) # === FallibleApplicativeWrapper === actions using the error-concatenating `mergeErrs` instead of the default abort-on-failure sequencing. Implements Fallible by crashing. Used in type querying when we want to avoid use INLINE pragmas in its own instances, which unnecessarily inhibits optimizations. # INLINE (<*>) # # INLINE (>>=) # # INLINE addErrCtx # === convenience layer === # INLINE throw # Propagate asynchronous exceptions like ThreadKilled; they are part of normal operation (of the live evaluation modes), not compiler bugs. === search monad === This is just `<|>` for greedy searchers like `Maybe`, but in other cases, instance with an identity element. # INLINE addErrCtx # # INLINE (<!>) # # INLINE (<!>) # # INLINE (<!>) # # INLINE addErrCtx # # INLINE (<!>) # # INLINE addErrCtx # # INLINE addErrCtx # === small pretty-printing utils === These are here instead of in PPrint.hs for import cycle reasons === instances === # INLINE addErrCtx # TODO: figure out a more uniform way to newlines The order of messages is outer-scope-to-inner-scope, but we want to print them starting the other way around (Not for a good reason. It's just what we've always done.) by appending Results. # INLINE addErrCtx # # INLINE addErrCtx # We usually extend errors form the right === misc util stuff === TODO: flag to control line numbers "Line " ++ show (1 + lineNum) ++ "\n"
Copyright 2021 Google LLC module Err (Err (..), Errs (..), ErrType (..), Except (..), ErrCtx (..), SrcPosCtx, SrcTextCtx, SrcPos, Fallible (..), Catchable (..), catchErrExcept, FallibleM (..), HardFailM (..), CtxReader (..), runFallibleM, runHardFail, throw, throwErr, addContext, addSrcContext, addSrcTextContext, catchIOExcept, liftExcept, liftExceptAlt, assertEq, ignoreExcept, pprint, docAsStr, getCurrentCallStack, printCurrentCallStack, FallibleApplicativeWrapper, traverseMergingErrs, SearcherM (..), Searcher (..), runSearcherM) where import Control.Exception hiding (throw) import Control.Applicative import Control.Monad import Control.Monad.Trans.Maybe import Control.Monad.Identity import Control.Monad.Writer.Strict import Control.Monad.State.Strict import Control.Monad.Reader import Data.Coerce import Data.Foldable (fold) import Data.Text (Text) import Data.Text qualified as T import Data.Text.Prettyprint.Doc.Render.Text import Data.Text.Prettyprint.Doc import GHC.Stack import System.Environment import System.IO.Unsafe data Err = Err ErrType ErrCtx String deriving (Show, Eq) newtype Errs = Errs [Err] deriving (Eq, Semigroup, Monoid) data ErrType = NoErr | ParseErr | SyntaxErr | TypeErr | KindErr | LinErr | VarDefErr | UnboundVarErr | AmbiguousVarErr | RepeatedVarErr | RepeatedPatVarErr | InvalidPatternErr | CompilerErr | IRVariantErr | NotImplementedErr | DataIOErr | MiscErr | RuntimeErr | ZipErr | EscapedNameErr | ModuleImportErr | MonadFailErr deriving (Show, Eq) type SrcPosCtx = Maybe SrcPos data ErrCtx = ErrCtx { srcTextCtx :: SrcTextCtx , srcPosCtx :: SrcPosCtx , messageCtx :: [String] , stackCtx :: Maybe [String] } deriving (Show, Eq) type SrcPos = (Int, Int) class MonadFail m => Fallible m where throwErrs :: Errs -> m a addErrCtx :: ErrCtx -> m a -> m a class Fallible m => Catchable m where catchErr :: m a -> (Errs -> m a) -> m a catchErrExcept :: Catchable m => m a -> m (Except a) catchErrExcept m = catchErr (Success <$> m) (\e -> return $ Failure e) We have this in its own class because IO and ` Except ` ca n't implement it ( but FallibleM can ) class Fallible m => CtxReader m where getErrCtx :: m ErrCtx ( but FallibleM , Except and IO all can ) class Fallible m => FallibleApplicative m where mergeErrs :: m a -> m b -> m (a, b) newtype FallibleM a = FallibleM { fromFallibleM :: ReaderT ErrCtx Except a } deriving (Functor, Applicative, Monad) instance Fallible FallibleM where throwErrs (Errs errs) = FallibleM $ ReaderT \ambientCtx -> throwErrs $ Errs [Err errTy (ambientCtx <> ctx) s | Err errTy ctx s <- errs] # INLINE throwErrs # addErrCtx ctx (FallibleM m) = FallibleM $ local (<> ctx) m instance Catchable FallibleM where FallibleM m `catchErr` handler = FallibleM $ ReaderT \ctx -> case runReaderT m ctx of Failure errs -> runReaderT (fromFallibleM $ handler errs) ctx Success ans -> return ans instance FallibleApplicative FallibleM where mergeErrs (FallibleM (ReaderT f1)) (FallibleM (ReaderT f2)) = FallibleM $ ReaderT \ctx -> mergeErrs (f1 ctx) (f2 ctx) instance CtxReader FallibleM where getErrCtx = FallibleM ask # INLINE getErrCtx # instance Fallible IO where throwErrs errs = throwIO errs # INLINE throwErrs # addErrCtx ctx m = do result <- catchIOExcept m liftExcept $ addErrCtx ctx result instance Catchable IO where catchErr cont handler = catchIOExcept cont >>= \case Success result -> return result Failure errs -> handler errs instance FallibleApplicative IO where mergeErrs m1 m2 = do result1 <- catchIOExcept m1 result2 <- catchIOExcept m2 liftExcept $ mergeErrs result1 result2 runFallibleM :: FallibleM a -> Except a runFallibleM m = runReaderT (fromFallibleM m) mempty Except is isomorphic to ` Either Errs ` but having a distinct type makes it data Except a = Failure Errs | Success a deriving (Show, Eq) instance Functor Except where fmap = liftM # INLINE fmap # instance Applicative Except where pure = return # INLINE pure # liftA2 = liftM2 # INLINE liftA2 # instance Monad Except where return = Success # INLINE return # Failure errs >>= _ = Failure errs Success x >>= f = f x Wraps a Fallible monad , presenting an applicative interface that sequences newtype FallibleApplicativeWrapper m a = FallibleApplicativeWrapper { fromFallibleApplicativeWrapper :: m a } deriving (Functor) instance FallibleApplicative m => Applicative (FallibleApplicativeWrapper m) where pure x = FallibleApplicativeWrapper $ pure x # INLINE pure # liftA2 f (FallibleApplicativeWrapper m1) (FallibleApplicativeWrapper m2) = FallibleApplicativeWrapper $ fmap (uncurry f) (mergeErrs m1 m2) # INLINE liftA2 # = = = HardFail = = = work by trusting annotations and skipping the checks . newtype HardFailM a = HardFailM { runHardFail' :: Identity a } We do n't derive Functor , Applicative and , because Identity does n't instance Functor HardFailM where fmap f (HardFailM (Identity x)) = HardFailM $ Identity $ f x # INLINE fmap # instance Applicative HardFailM where pure = HardFailM . Identity # INLINE pure # (<*>) = coerce liftA2 = coerce # INLINE liftA2 # instance Monad HardFailM where (HardFailM (Identity x)) >>= k = k x return = HardFailM . Identity # INLINE return # runHardFail :: HardFailM a -> a runHardFail m = runIdentity $ runHardFail' m # INLINE runHardFail # instance MonadFail HardFailM where fail s = error s # INLINE fail # instance Fallible HardFailM where throwErrs errs = error $ pprint errs # INLINE throwErrs # addErrCtx _ cont = cont instance FallibleApplicative HardFailM where mergeErrs cont1 cont2 = (,) <$> cont1 <*> cont2 throw :: Fallible m => ErrType -> String -> m a throw errTy s = throwErrs $ Errs [addCompilerStackCtx $ Err errTy mempty s] throwErr :: Fallible m => Err -> m a throwErr err = throwErrs $ Errs [addCompilerStackCtx err] # INLINE throwErr # addCompilerStackCtx :: Err -> Err addCompilerStackCtx (Err ty ctx msg) = Err ty ctx{stackCtx = compilerStack} msg where #ifdef DEX_DEBUG compilerStack = getCurrentCallStack () #else compilerStack = stackCtx ctx #endif getCurrentCallStack :: () -> Maybe [String] getCurrentCallStack () = #ifdef DEX_DEBUG case reverse (unsafePerformIO currentCallStack) of [] -> Nothing stack -> Just stack #else Nothing #endif # NOINLINE getCurrentCallStack # printCurrentCallStack :: Maybe [String] -> String printCurrentCallStack Nothing = "<no call stack available>" printCurrentCallStack (Just frames) = fold frames addContext :: Fallible m => String -> m a -> m a addContext s m = addErrCtx (mempty {messageCtx = [s]}) m # INLINE addContext # addSrcContext :: Fallible m => SrcPosCtx -> m a -> m a addSrcContext ctx m = addErrCtx (mempty {srcPosCtx = ctx}) m # INLINE addSrcContext # addSrcTextContext :: Fallible m => Int -> Text -> m a -> m a addSrcTextContext offset text m = addErrCtx (mempty {srcTextCtx = Just (offset, text)}) m catchIOExcept :: MonadIO m => IO a -> m (Except a) catchIOExcept m = liftIO $ (liftM Success m) `catches` [ Handler \(e::Errs) -> return $ Failure e , Handler \(e::IOError) -> return $ Failure $ Errs [Err DataIOErr mempty $ show e] , Handler \(e::AsyncException) -> liftIO $ throwIO e , Handler \(e::SomeException) -> return $ Failure $ Errs [Err CompilerErr mempty $ show e] ] liftExcept :: Fallible m => Except a -> m a liftExcept (Failure errs) = throwErrs errs liftExcept (Success ans) = return ans # INLINE liftExcept # liftExceptAlt :: Alternative m => Except a -> m a liftExceptAlt = \case Success a -> pure a Failure _ -> empty # INLINE liftExceptAlt # ignoreExcept :: HasCallStack => Except a -> a ignoreExcept (Failure e) = error $ pprint e ignoreExcept (Success x) = x # INLINE ignoreExcept # assertEq :: (HasCallStack, Fallible m, Show a, Pretty a, Eq a) => a -> a -> String -> m () assertEq x y s = if x == y then return () else throw CompilerErr msg where msg = "assertion failure (" ++ s ++ "):\n" ++ pprint x ++ " != " ++ pprint y ++ "\n\n" ++ prettyCallStack callStack ++ "\n" infix 0 <!> class (Monad m, Alternative m) => Searcher m where Runs the second computation when the first yields an empty set of results . like the list monad , it matters that the second computation is n't run if the first succeeds . (<!>) :: m a -> m a -> m a Adds an extra error case to ` FallibleM ` so we can give it an Alternative newtype SearcherM a = SearcherM { runSearcherM' :: MaybeT FallibleM a } deriving (Functor, Applicative, Monad) runSearcherM :: SearcherM a -> Except (Maybe a) runSearcherM m = runFallibleM $ runMaybeT (runSearcherM' m) # INLINE runSearcherM # instance MonadFail SearcherM where fail _ = SearcherM $ MaybeT $ return Nothing # INLINE fail # instance Fallible SearcherM where throwErrs e = SearcherM $ lift $ throwErrs e # INLINE throwErrs # addErrCtx ctx (SearcherM (MaybeT m)) = SearcherM $ MaybeT $ addErrCtx ctx $ m instance Alternative SearcherM where empty = SearcherM $ MaybeT $ return Nothing SearcherM (MaybeT m1) <|> SearcherM (MaybeT m2) = SearcherM $ MaybeT do m1 >>= \case Just ans -> return $ Just ans Nothing -> m2 instance Searcher SearcherM where (<!>) = (<|>) instance CtxReader SearcherM where getErrCtx = SearcherM $ lift getErrCtx # INLINE getErrCtx # instance Searcher [] where [] <!> m = m m <!> _ = m instance (Monoid w, Searcher m) => Searcher (WriterT w m) where WriterT m1 <!> WriterT m2 = WriterT (m1 <!> m2) instance (Monoid w, Fallible m) => Fallible (WriterT w m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (WriterT m) = WriterT $ addErrCtx ctx m instance Searcher m => Searcher (ReaderT r m) where ReaderT f1 <!> ReaderT f2 = ReaderT \r -> f1 r <!> f2 r instance Fallible [] where throwErrs _ = [] # INLINE throwErrs # addErrCtx _ m = m instance Fallible Maybe where throwErrs _ = Nothing # INLINE throwErrs # addErrCtx _ m = m pprint :: Pretty a => a -> String pprint x = docAsStr $ pretty x # SCC pprint # docAsStr :: Doc ann -> String docAsStr doc = T.unpack $ renderStrict $ layoutPretty layout $ doc layout :: LayoutOptions layout = if unbounded then LayoutOptions Unbounded else defaultLayoutOptions where unbounded = unsafePerformIO $ (Just "1"==) <$> lookupEnv "DEX_PPRINT_UNBOUNDED" traverseMergingErrs :: (Traversable f, FallibleApplicative m) => (a -> m b) -> f a -> m (f b) traverseMergingErrs f xs = fromFallibleApplicativeWrapper $ traverse (\x -> FallibleApplicativeWrapper $ f x) xs instance MonadFail FallibleM where fail s = throw MonadFailErr s # INLINE fail # instance Fallible Except where throwErrs errs = Failure errs # INLINE throwErrs # addErrCtx _ (Success ans) = Success ans addErrCtx ctx (Failure (Errs errs)) = Failure $ Errs [Err errTy (ctx <> ctx') s | Err errTy ctx' s <- errs] instance FallibleApplicative Except where mergeErrs (Success x) (Success y) = Success (x, y) mergeErrs x y = Failure (getErrs x <> getErrs y) where getErrs :: Except a -> Errs getErrs = \case Failure e -> e Success _ -> mempty instance MonadFail Except where fail s = Failure $ Errs [Err CompilerErr mempty s] # INLINE fail # instance Exception Errs instance Show Errs where show errs = pprint errs instance Pretty Err where pretty (Err e ctx s) = pretty e <> pretty s <> prettyCtx where prettyCtx = case ctx of ErrCtx _ Nothing [] Nothing -> mempty _ -> hardline <> pretty ctx instance Pretty ErrCtx where pretty (ErrCtx maybeTextCtx maybePosCtx messages stack) = prettyLines (reverse messages) <> highlightedSource <> prettyStack where highlightedSource = case (maybeTextCtx, maybePosCtx) of (Just (offset, text), Just (start, stop)) -> hardline <> pretty (highlightRegion (start - offset, stop - offset) text) _ -> mempty prettyStack = case stack of Nothing -> mempty Just s -> hardline <> "Compiler stack trace:" <> nest 2 (hardline <> prettyLines s) instance Pretty a => Pretty (Except a) where pretty (Success x) = "Success:" <+> pretty x pretty (Failure e) = "Failure:" <+> pretty e instance Pretty ErrType where pretty e = case e of NoErr tags a chunk of output that was promoted into the Err ADT NoErr -> "" ParseErr -> "Parse error:" SyntaxErr -> "Syntax error: " TypeErr -> "Type error:" KindErr -> "Kind error:" LinErr -> "Linearity error: " IRVariantErr -> "Internal IR validation error: " VarDefErr -> "Error in (earlier) definition of variable: " UnboundVarErr -> "Error: variable not in scope: " AmbiguousVarErr -> "Error: ambiguous variable: " RepeatedVarErr -> "Error: variable already defined: " RepeatedPatVarErr -> "Error: variable already defined within pattern: " InvalidPatternErr -> "Error: not a valid pattern: " NotImplementedErr -> "Not implemented:" <> line <> "Please report this at github.com/google-research/dex-lang/issues\n" <> line CompilerErr -> "Compiler bug!" <> line <> "Please report this at github.com/google-research/dex-lang/issues\n" <> line DataIOErr -> "IO error: " MiscErr -> "Error:" RuntimeErr -> "Runtime error" ZipErr -> "Zipping error" EscapedNameErr -> "Leaked local variables:" ModuleImportErr -> "Module import error: " MonadFailErr -> "MonadFail error (internal error)" instance Fallible m => Fallible (ReaderT r m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (ReaderT f) = ReaderT \r -> addErrCtx ctx $ f r instance Catchable m => Catchable (ReaderT r m) where ReaderT f `catchErr` handler = ReaderT \r -> f r `catchErr` \e -> runReaderT (handler e) r instance FallibleApplicative m => FallibleApplicative (ReaderT r m) where mergeErrs (ReaderT f1) (ReaderT f2) = ReaderT \r -> mergeErrs (f1 r) (f2 r) instance CtxReader m => CtxReader (ReaderT r m) where getErrCtx = lift getErrCtx # INLINE getErrCtx # instance Pretty Errs where pretty (Errs [err]) = pretty err pretty (Errs errs) = prettyLines errs instance Fallible m => Fallible (StateT s m) where throwErrs errs = lift $ throwErrs errs # INLINE throwErrs # addErrCtx ctx (StateT f) = StateT \s -> addErrCtx ctx $ f s instance Catchable m => Catchable (StateT s m) where StateT f `catchErr` handler = StateT \s -> f s `catchErr` \e -> runStateT (handler e) s instance CtxReader m => CtxReader (StateT s m) where getErrCtx = lift getErrCtx # INLINE getErrCtx # instance Semigroup ErrCtx where ErrCtx text pos ctxStrs stk <> ErrCtx text' pos' ctxStrs' stk' = ErrCtx (leftmostJust text text') (rightmostJust pos pos' ) (ctxStrs <> ctxStrs') instance Monoid ErrCtx where mempty = ErrCtx Nothing Nothing [] Nothing leftmostJust :: Maybe a -> Maybe a -> Maybe a leftmostJust (Just x) _ = Just x leftmostJust Nothing y = y rightmostJust :: Maybe a -> Maybe a -> Maybe a rightmostJust = flip leftmostJust prettyLines :: (Foldable f, Pretty a) => f a -> Doc ann prettyLines xs = foldMap (\d -> pretty d <> hardline) xs highlightRegion :: (Int, Int) -> Text -> Text highlightRegion pos@(low, high) s | low > high || high > T.length s = error $ "Bad region: \n" ++ show pos ++ "\n" ++ T.unpack s | otherwise = ( disabling for now because it makes quine tests tricky ) allLines !! lineNum <> "\n" <> T.replicate start " " <> T.replicate (stop - start) "^" <> "\n" where allLines = T.lines s (lineNum, start, stop) = getPosTriple pos allLines getPosTriple :: (Int, Int) -> [Text] -> (Int, Int, Int) getPosTriple (start, stop) lines_ = (lineNum, start - offset, stop') where lineLengths = map ((+1) . T.length) lines_ lineOffsets = cumsum lineLengths lineNum = maxLT lineOffsets start offset = lineOffsets !! lineNum stop' = min (stop - offset) (lineLengths !! lineNum) cumsum :: [Int] -> [Int] cumsum xs = scanl (+) 0 xs maxLT :: Ord a => [a] -> a -> Int maxLT [] _ = 0 maxLT (x:xs) n = if n < x then -1 else 1 + maxLT xs n
c1edfffecb057aa1a114dd2e727aafbc97fec78c32e90734ea4e1f5b430ad357
mwand/eopl3
lang.scm
(module lang (lib "eopl.ss" "eopl") ;; grammar for modules with abstract types ;; based on CHECKED. (provide (all-defined-out)) ;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;; (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) (define the-grammar '( (program ((arbno module-definition) expression) a-program) (module-definition ("module" identifier "interface" interface "body" module-body) a-module-definition) (interface ("[" (arbno declaration) "]") simple-iface) (declaration ("opaque" identifier) opaque-type-decl) (declaration ("transparent" identifier "=" type) transparent-type-decl) (declaration (identifier ":" type) val-decl) (module-body ("[" (arbno definition) "]") defns-module-body) (definition (identifier "=" expression) val-defn) (definition ("type" identifier "=" type) type-defn) ;; new expression: (expression ("from" identifier "take" identifier) qualified-var-exp) ;; new types (type (identifier) named-type) (type ("from" identifier "take" identifier) qualified-type) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; no changes in grammar below here ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (expression (number) const-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("proc" "(" identifier ":" type ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp) (expression ("letrec" type identifier "(" identifier ":" type ")" "=" expression "in" expression) letrec-exp) (type ("int") int-type) (type ("bool") bool-type) (type ("(" type "->" type ")") proc-type) )) ;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;; (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define show-the-datatypes (lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar))) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define just-scan (sllgen:make-string-scanner the-lexical-spec the-grammar)) ;;;;;;;;;;;;;;;; syntactic tests and observers ;;;;;;;;;;;;;;;; ;;;; for types (define atomic-type? (lambda (ty) (cases type ty (proc-type (ty1 ty2) #f) (else #t)))) (define proc-type? (lambda (ty) (cases type ty (proc-type (t1 t2) #t) (else #f)))) (define proc-type->arg-type (lambda (ty) (cases type ty (proc-type (arg-type result-type) arg-type) (else (eopl:error 'proc-type->arg-type "Not a proc type: ~s" ty))))) (define proc-type->result-type (lambda (ty) (cases type ty (proc-type (arg-type result-type) result-type) (else (eopl:error 'proc-type->result-types "Not a proc type: ~s" ty))))) (define type-to-external-form (lambda (ty) (cases type ty (int-type () 'int) (bool-type () 'bool) (proc-type (arg-type result-type) (list (type-to-external-form arg-type) '-> (type-to-external-form result-type))) (named-type (name) name) (qualified-type (modname varname) (list 'from modname 'take varname)) ))) ;;;; for module definitions ;; maybe-lookup-module-in-list : Sym * Listof(Defn) -> Maybe(Defn) (define maybe-lookup-module-in-list (lambda (name module-defs) (if (null? module-defs) #f (let ((name1 (module-definition->name (car module-defs)))) (if (eqv? name1 name) (car module-defs) (maybe-lookup-module-in-list name (cdr module-defs))))))) ;; maybe-lookup-module-in-list : Sym * Listof(Defn) -> Defn OR Error (define lookup-module-in-list (lambda (name module-defs) (cond ((maybe-lookup-module-in-list name module-defs) => (lambda (mdef) mdef)) (else (eopl:error 'lookup-module-in-list "unknown module ~s" name))))) (define module-definition->name (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-name)))) (define module-definition->interface (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-type)))) (define module-definition->body (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-body)))) (define val-decl? (lambda (decl) (cases declaration decl (val-decl (name ty) #t) (else #f)))) (define transparent-type-decl? (lambda (decl) (cases declaration decl (transparent-type-decl (name ty) #t) (else #f)))) (define opaque-type-decl? (lambda (decl) (cases declaration decl (opaque-type-decl (name) #t) (else #f)))) (define decl->name (lambda (decl) (cases declaration decl (opaque-type-decl (name) name) (transparent-type-decl (name ty) name) (val-decl (name ty) name)))) (define decl->type (lambda (decl) (cases declaration decl (transparent-type-decl (name ty) ty) (val-decl (name ty) ty) (opaque-type-decl (name) (eopl:error 'decl->type "can't take type of abstract type declaration ~s" decl))))) )
null
https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter8/abstract-types-lang/lang.scm
scheme
grammar for modules with abstract types based on CHECKED. grammatical specification ;;;;;;;;;;;;;;;; new expression: new types no changes in grammar below here sllgen boilerplate ;;;;;;;;;;;;;;;; syntactic tests and observers ;;;;;;;;;;;;;;;; for types for module definitions maybe-lookup-module-in-list : Sym * Listof(Defn) -> Maybe(Defn) maybe-lookup-module-in-list : Sym * Listof(Defn) -> Defn OR Error
(module lang (lib "eopl.ss" "eopl") (provide (all-defined-out)) (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) (define the-grammar '( (program ((arbno module-definition) expression) a-program) (module-definition ("module" identifier "interface" interface "body" module-body) a-module-definition) (interface ("[" (arbno declaration) "]") simple-iface) (declaration ("opaque" identifier) opaque-type-decl) (declaration ("transparent" identifier "=" type) transparent-type-decl) (declaration (identifier ":" type) val-decl) (module-body ("[" (arbno definition) "]") defns-module-body) (definition (identifier "=" expression) val-defn) (definition ("type" identifier "=" type) type-defn) (expression ("from" identifier "take" identifier) qualified-var-exp) (type (identifier) named-type) (type ("from" identifier "take" identifier) qualified-type) (expression (number) const-exp) (expression (identifier) var-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("proc" "(" identifier ":" type ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp) (expression ("letrec" type identifier "(" identifier ":" type ")" "=" expression "in" expression) letrec-exp) (type ("int") int-type) (type ("bool") bool-type) (type ("(" type "->" type ")") proc-type) )) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define show-the-datatypes (lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar))) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define just-scan (sllgen:make-string-scanner the-lexical-spec the-grammar)) (define atomic-type? (lambda (ty) (cases type ty (proc-type (ty1 ty2) #f) (else #t)))) (define proc-type? (lambda (ty) (cases type ty (proc-type (t1 t2) #t) (else #f)))) (define proc-type->arg-type (lambda (ty) (cases type ty (proc-type (arg-type result-type) arg-type) (else (eopl:error 'proc-type->arg-type "Not a proc type: ~s" ty))))) (define proc-type->result-type (lambda (ty) (cases type ty (proc-type (arg-type result-type) result-type) (else (eopl:error 'proc-type->result-types "Not a proc type: ~s" ty))))) (define type-to-external-form (lambda (ty) (cases type ty (int-type () 'int) (bool-type () 'bool) (proc-type (arg-type result-type) (list (type-to-external-form arg-type) '-> (type-to-external-form result-type))) (named-type (name) name) (qualified-type (modname varname) (list 'from modname 'take varname)) ))) (define maybe-lookup-module-in-list (lambda (name module-defs) (if (null? module-defs) #f (let ((name1 (module-definition->name (car module-defs)))) (if (eqv? name1 name) (car module-defs) (maybe-lookup-module-in-list name (cdr module-defs))))))) (define lookup-module-in-list (lambda (name module-defs) (cond ((maybe-lookup-module-in-list name module-defs) => (lambda (mdef) mdef)) (else (eopl:error 'lookup-module-in-list "unknown module ~s" name))))) (define module-definition->name (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-name)))) (define module-definition->interface (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-type)))) (define module-definition->body (lambda (m-defn) (cases module-definition m-defn (a-module-definition (m-name m-type m-body) m-body)))) (define val-decl? (lambda (decl) (cases declaration decl (val-decl (name ty) #t) (else #f)))) (define transparent-type-decl? (lambda (decl) (cases declaration decl (transparent-type-decl (name ty) #t) (else #f)))) (define opaque-type-decl? (lambda (decl) (cases declaration decl (opaque-type-decl (name) #t) (else #f)))) (define decl->name (lambda (decl) (cases declaration decl (opaque-type-decl (name) name) (transparent-type-decl (name ty) name) (val-decl (name ty) name)))) (define decl->type (lambda (decl) (cases declaration decl (transparent-type-decl (name ty) ty) (val-decl (name ty) ty) (opaque-type-decl (name) (eopl:error 'decl->type "can't take type of abstract type declaration ~s" decl))))) )
e1f21dbf39f8bceadcb38c68d1751dfab4d62e63c6e64420a2d9fd7da6983f13
Holmusk/elm-street
Ast.hs
| AST representing structure of Elm types . Haskell generic representation is converted to this AST which later is going to be pretty - printed . converted to this AST which later is going to be pretty-printed. -} module Elm.Ast ( ElmDefinition (..) , ElmRecord (..) , ElmType (..) , ElmPrim (..) , ElmRecordField (..) , ElmConstructor (..) , isEnum , getConstructorNames , TypeName (..) , TypeRef (..) , definitionToRef ) where import Data.List.NonEmpty (NonEmpty, toList) import Data.Text (Text) -- | Elm data type definition. data ElmDefinition = DefRecord !ElmRecord | DefType !ElmType | DefPrim !ElmPrim deriving (Show) | AST for @record type alias@ in Elm . data ElmRecord = ElmRecord { elmRecordName :: !Text -- ^ Name of the record , elmRecordFields :: !(NonEmpty ElmRecordField) -- ^ List of fields ^ ' True ' if type is a @newtype@ } deriving (Show) | Single field of type alias@. data ElmRecordField = ElmRecordField { elmRecordFieldType :: !TypeRef , elmRecordFieldName :: !Text } deriving (Show) -- | Wrapper for name of the type. newtype TypeName = TypeName { unTypeName :: Text } deriving (Show) | AST for @type@ in Elm . data ElmType = ElmType { elmTypeName :: !Text -- ^ Name of the data type , elmTypeVars :: ![Text] -- ^ List of type variables; currently only phantom variables ^ ' True ' if type is a @newtype@ , elmTypeConstructors :: !(NonEmpty ElmConstructor) -- ^ List of constructors } deriving (Show) | Constructor of @type@. data ElmConstructor = ElmConstructor { elmConstructorName :: !Text -- ^ Name of the constructor , elmConstructorFields :: ![TypeRef] -- ^ Fields of the constructor } deriving (Show) | Checks if the given ' ElmType ' is . isEnum :: ElmType -> Bool isEnum ElmType{..} = null elmTypeVars && null (foldMap elmConstructorFields elmTypeConstructors) -- | Gets the list of the constructor names. getConstructorNames :: ElmType -> [Text] getConstructorNames ElmType{..} = map elmConstructorName $ toList elmTypeConstructors -- | Primitive elm types; hardcoded by the language. data ElmPrim = ElmUnit -- ^ @()@ type in elm ^ @Never@ type in elm , analogous to Void in Haskell | ElmBool -- ^ @Bool@ | ElmChar -- ^ @Char@ | ElmInt -- ^ @Int@ ^ | ElmString -- ^ @String@ ^ @Posix@ in elm , @UTCTime@ in Haskell ^ @Json . Encode . Value@ in elm , @Data . . Value@ in Haskell | ElmMaybe !TypeRef -- ^ @Maybe T@ | ElmResult !TypeRef !TypeRef -- ^ @Result A B@ in elm | ElmPair !TypeRef !TypeRef -- ^ @(A, B)@ in elm | ElmTriple !TypeRef !TypeRef !TypeRef -- ^ @(A, B, C)@ in elm | ElmList !TypeRef -- ^ @List A@ in elm | ElmNonEmptyPair !TypeRef -- ^ @NonEmpty A@ represented by @(A, List A)@ in elm deriving (Show) -- | Reference to another existing type. data TypeRef = RefPrim !ElmPrim | RefCustom !TypeName deriving (Show) -- | Extracts reference to the existing data type type from some other type elm defintion. definitionToRef :: ElmDefinition -> TypeRef definitionToRef = \case DefRecord ElmRecord{..} -> RefCustom $ TypeName elmRecordName DefType ElmType{..} -> RefCustom $ TypeName elmTypeName DefPrim elmPrim -> RefPrim elmPrim
null
https://raw.githubusercontent.com/Holmusk/elm-street/09b201e085d8f0b31ecf8cbf8481f9b7b9d8406e/src/Elm/Ast.hs
haskell
| Elm data type definition. ^ Name of the record ^ List of fields | Wrapper for name of the type. ^ Name of the data type ^ List of type variables; currently only phantom variables ^ List of constructors ^ Name of the constructor ^ Fields of the constructor | Gets the list of the constructor names. | Primitive elm types; hardcoded by the language. ^ @()@ type in elm ^ @Bool@ ^ @Char@ ^ @Int@ ^ @String@ ^ @Maybe T@ ^ @Result A B@ in elm ^ @(A, B)@ in elm ^ @(A, B, C)@ in elm ^ @List A@ in elm ^ @NonEmpty A@ represented by @(A, List A)@ in elm | Reference to another existing type. | Extracts reference to the existing data type type from some other type elm defintion.
| AST representing structure of Elm types . Haskell generic representation is converted to this AST which later is going to be pretty - printed . converted to this AST which later is going to be pretty-printed. -} module Elm.Ast ( ElmDefinition (..) , ElmRecord (..) , ElmType (..) , ElmPrim (..) , ElmRecordField (..) , ElmConstructor (..) , isEnum , getConstructorNames , TypeName (..) , TypeRef (..) , definitionToRef ) where import Data.List.NonEmpty (NonEmpty, toList) import Data.Text (Text) data ElmDefinition = DefRecord !ElmRecord | DefType !ElmType | DefPrim !ElmPrim deriving (Show) | AST for @record type alias@ in Elm . data ElmRecord = ElmRecord ^ ' True ' if type is a @newtype@ } deriving (Show) | Single field of type alias@. data ElmRecordField = ElmRecordField { elmRecordFieldType :: !TypeRef , elmRecordFieldName :: !Text } deriving (Show) newtype TypeName = TypeName { unTypeName :: Text } deriving (Show) | AST for @type@ in Elm . data ElmType = ElmType ^ ' True ' if type is a @newtype@ } deriving (Show) | Constructor of @type@. data ElmConstructor = ElmConstructor } deriving (Show) | Checks if the given ' ElmType ' is . isEnum :: ElmType -> Bool isEnum ElmType{..} = null elmTypeVars && null (foldMap elmConstructorFields elmTypeConstructors) getConstructorNames :: ElmType -> [Text] getConstructorNames ElmType{..} = map elmConstructorName $ toList elmTypeConstructors data ElmPrim ^ @Never@ type in elm , analogous to Void in Haskell ^ ^ @Posix@ in elm , @UTCTime@ in Haskell ^ @Json . Encode . Value@ in elm , @Data . . Value@ in Haskell deriving (Show) data TypeRef = RefPrim !ElmPrim | RefCustom !TypeName deriving (Show) definitionToRef :: ElmDefinition -> TypeRef definitionToRef = \case DefRecord ElmRecord{..} -> RefCustom $ TypeName elmRecordName DefType ElmType{..} -> RefCustom $ TypeName elmTypeName DefPrim elmPrim -> RefPrim elmPrim
558834f5628a5b8019835e8eca28781dd42168c4730e1b30f64cf6717512cd19
zenspider/schemers
exercise.5.35.scm
#!/usr/bin/env csi -s (require rackunit) Exercise 5.35 ;; What expression was compiled to produce the code shown in * Note Figure 5 - 18 : : ? ;; * Figure 5.18 :* An example of compiler output . See * Note Exercise 5 - 35 : : . ;; ( assign ( op make - compiled - procedure ) ( label entry16 ) ;; (reg env)) ( goto ( label after - lambda15 ) ) ;; entry16 ;; (assign env (op compiled-procedure-env) (reg proc)) ;; (assign env ( op extend - environment ) ( const ( x ) ) ( reg argl ) ( reg env ) ) ;; (assign proc (op lookup-variable-value) (const +) (reg env)) ;; (save continue) ;; (save proc) ;; (save env) ;; (assign proc (op lookup-variable-value) (const g) (reg env)) ;; (save proc) ;; (assign proc (op lookup-variable-value) (const +) (reg env)) ( assign ( const 2 ) ) ;; (assign argl (op list) (reg val)) ( assign ( op lookup - variable - value ) ( const x ) ( reg env ) ) ( assign argl ( op cons ) ( reg val ) ( reg argl ) ) ;; (test (op primitive-procedure?) (reg proc)) ;; (branch (label primitive-branch19)) ;; compiled-branch18 ;; (assign continue (label after-call17)) ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ;; primitive-branch19 ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ;; after-call17 ;; (assign argl (op list) (reg val)) ;; (restore proc) ;; (test (op primitive-procedure?) (reg proc)) ;; (branch (label primitive-branch22)) ;; compiled-branch21 ;; (assign continue (label after-call20)) ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ;; primitive-branch22 ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ;; ;; after-call20 ;; (assign argl (op list) (reg val)) ;; (restore env) ( assign ( op lookup - variable - value ) ( const x ) ( reg env ) ) ( assign argl ( op cons ) ( reg val ) ( reg argl ) ) ;; (restore proc) ;; (restore continue) ;; (test (op primitive-procedure?) (reg proc)) ;; (branch (label primitive-branch25)) ;; compiled-branch24 ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ;; primitive-branch25 ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ( goto ( reg continue ) ) ;; after-call23 ;; after-lambda15 ;; (perform (op define-variable!) (const f) (reg val) (reg env)) ( assign ( const ok ) ) ;; I think it is this: (define (f x) (+ x (g (+ x 2))))
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_5/exercise.5.35.scm
scheme
What expression was compiled to produce the code (reg env)) entry16 (assign env (op compiled-procedure-env) (reg proc)) (assign env (assign proc (op lookup-variable-value) (const +) (reg env)) (save continue) (save proc) (save env) (assign proc (op lookup-variable-value) (const g) (reg env)) (save proc) (assign proc (op lookup-variable-value) (const +) (reg env)) (assign argl (op list) (reg val)) (test (op primitive-procedure?) (reg proc)) (branch (label primitive-branch19)) compiled-branch18 (assign continue (label after-call17)) primitive-branch19 after-call17 (assign argl (op list) (reg val)) (restore proc) (test (op primitive-procedure?) (reg proc)) (branch (label primitive-branch22)) compiled-branch21 (assign continue (label after-call20)) primitive-branch22 after-call20 (assign argl (op list) (reg val)) (restore env) (restore proc) (restore continue) (test (op primitive-procedure?) (reg proc)) (branch (label primitive-branch25)) compiled-branch24 primitive-branch25 after-call23 after-lambda15 (perform (op define-variable!) (const f) (reg val) (reg env)) I think it is this:
#!/usr/bin/env csi -s (require rackunit) Exercise 5.35 shown in * Note Figure 5 - 18 : : ? * Figure 5.18 :* An example of compiler output . See * Note Exercise 5 - 35 : : . ( assign ( op make - compiled - procedure ) ( label entry16 ) ( goto ( label after - lambda15 ) ) ( op extend - environment ) ( const ( x ) ) ( reg argl ) ( reg env ) ) ( assign ( const 2 ) ) ( assign ( op lookup - variable - value ) ( const x ) ( reg env ) ) ( assign argl ( op cons ) ( reg val ) ( reg argl ) ) ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ( assign ( op lookup - variable - value ) ( const x ) ( reg env ) ) ( assign argl ( op cons ) ( reg val ) ( reg argl ) ) ( assign ( op compiled - procedure - entry ) ( reg proc ) ) ( goto ( reg val ) ) ( assign ( op apply - primitive - procedure ) ( reg proc ) ( reg argl ) ) ( goto ( reg continue ) ) ( assign ( const ok ) ) (define (f x) (+ x (g (+ x 2))))
c7aaa9960678d12b1dbd1b5f3e5b4ff5c51b1cd90c80f35f06269a46481e594e
static-analysis-engineering/codehawk
bCHDwarfTest.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author : Adapted from : ( ) ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2023 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author: Henny Sipma Adapted from: Kaputt () ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2023 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty (* chutil *) open CHXmlDocument open CHXmlReader (* bchlib *) open BCHBasicTypes open BCHDoubleword open BCHLibTypes open BCHStreamWrapper (* bchlibelf *) open BCHDwarf open BCHDwarfUtils open BCHELFDebugAbbrevSection open BCHELFTypes open BCHELFSectionHeader (* tchlib *) module TS = TCHTestSuite module A = TCHAssertion module G = TCHGenerator module S = TCHSpecification (* bchlib *) module D = BCHDoubleword module SI = BCHSystemInfo module SW = BCHStreamWrapper module U = BCHByteUtilities (* tbchlibelf *) module EA = TCHBchlibelfAssertion module TR = CHTraceResult let testname = "bCHDwarf" let lastupdated = "2023-02-14" let decode_decompilation_unit_header_test () = let tests = [ ("cu-0", "000012d100040000000004", ("0x12d1", 4, "0x0", 4)); ("cu-1", "000036d900040000013c04", ("0x36d9", 4, "0x13c", 4)) ] in begin TS.new_testsuite (testname ^ "_decode_decompilation_unit_header_test") lastupdated; List.iter (fun (title, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let cuheader = decode_compilation_unit_header ch in EA.equal_compilation_unit_header result cuheader)) tests; TS.launch_tests () end let decode_debug_attribute_value_test () = let tests = [ ("addr", "DW_AT_low_pc", "DW_FORM_addr", "00811a00", "0x811a00"); ("data1", "DW_AT_language", "DW_FORM_data1", "01", "1"); ("data2", "DW_AT_decl_line", "DW_FORM_data2", "5595", "21909"); ("data4", "DW_AT_stmt_list", "DW_FORM_data4", "00003e17", "0x3e17"); ("sdata-0", "DW_AT_const_value", "DW_FORM_sdata", "00", "0"); ("sdata-18", "DW_AT_const_value", "DW_FORM_sdata", "12", "18"); ("sdata-200", "DW_AT_const_value", "DW_FORM_sdata", "c801", "200"); ("sdata-500", "DW_AT_const_value", "DW_FORM_sdata", "f403", "500"); ("sdata-neg", "DW_AT_const_value", "DW_FORM_sdata", "807f060000", "-128"); ("ref4", "DW_AT_type", "DW_FORM_ref4", "0000004f", "<0x4f>"); ("string", "DW_AT_name", "DW_FORM_string", "696e7400", "int"); ] in begin TS.new_testsuite (testname ^ "_decode_debug_attribute_value_test") lastupdated; List.iter (fun (title, s_attr, s_form, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let attr = string_to_dwarf_attr_type s_attr in let form = string_to_dwarf_form_type s_form in let (_, atvalue) = decode_debug_attribute_value ch wordzero (attr, form) in A.equal_string result (dwarf_attr_value_to_string atvalue))) tests; TS.launch_tests () end let decode_debug_ref_attribute_value_test () = let tests = [ ("ref4", "DW_AT_type", "DW_FORM_ref4", "0x0", "0000004f", "<0x4f>"); ("ref4-r0", "DW_AT_type", "DW_FORM_ref4", "0x63cb6", "00000030", "<0x63ce6>"); ("ref4-r1", "DW_AT_type", "DW_FORM_ref4", "0x63cb6", "0000012e", "<0x63de4>") ] in begin TS.new_testsuite (testname ^ "_decode_debug_ref_attribute_value_test") lastupdated; List.iter (fun (title, s_attr, s_form, base, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let attr = string_to_dwarf_attr_type s_attr in let form = string_to_dwarf_form_type s_form in let base = TR.tget_ok (string_to_doubleword base) in let (_, atvalue) = decode_debug_attribute_value ch base (attr, form) in A.equal_string result (dwarf_attr_value_to_string atvalue))) tests; TS.launch_tests () end let decode_compilation_unit_test () = let tests = [ ("cu-1", "01110010061101120103081b0825081305000000", "0x9a6a", "000000ad0002" ^ "00000778040100003e1700811a000081" ^ "20582e2e2f50726f6a6563745f536574" ^ "74696e67732f537461727475705f436f" ^ "64652f6763632f636f7265305f696e74" ^ "635f73775f68616e646c6572732e5300" ^ "5c5c56424f585356525c736861726564" ^ "5f446f776e6c6f6164735c776f726b73" ^ "706163655f73333264735f76322e315c" ^ "6d706335373737635f6465765f633130" ^ "5c44656275675f464c41534800303030" ^ "3030303030303030008001", ("0xad", "0x778", 1, DW_TAG_compile_unit, [(DW_AT_stmt_list, "0x3e17"); (DW_AT_low_pc, "0x811a00"); (DW_AT_high_pc, "0x812058"); (DW_AT_name, "../Project_Settings/Startup_Code/gcc/core0_intc_sw_handlers.S"); (DW_AT_comp_dir, "\\\\VBOXSVR\\shared_Downloads\\workspace_s32ds_v2.1\\mpc5777c_dev_c10\\Debug_FLASH"); (DW_AT_producer, "00000000000"); (DW_AT_language, "32769")])) ] in begin TS.new_testsuite (testname ^ "_decode_compilation_unit_test") lastupdated; List.iter (fun (title, abbrev, base, debuginfo, result) -> TS.add_simple_test ~title (fun () -> let astring = U.write_hex_bytes_to_bytestring abbrev in let istring = U.write_hex_bytes_to_bytestring debuginfo in let sh = mk_elf_section_header () in let section = mk_elf_debug_abbrev_section astring sh in let abbreventry = section#get_abbrev_entry in let fabbrev = fun (i: int) -> abbreventry in let chi = make_pushback_stream ~little_endian:false istring in let base = TR.tget_ok (string_to_doubleword base) in let cu = decode_compilation_unit chi base fabbrev in EA.equal_compilation_unit result cu)) tests; TS.launch_tests () end let () = begin TS.new_testfile testname lastupdated; decode_decompilation_unit_header_test (); decode_debug_attribute_value_test (); decode_debug_ref_attribute_value_test (); decode_compilation_unit_test (); TS.exit_file () end
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/e8fed9f226abe38578768968279c8242eb21fea9/CodeHawk/CHT/CHB_tests/bchlibelf_tests/txbchlibelf/bCHDwarfTest.ml
ocaml
chutil bchlib bchlibelf tchlib bchlib tbchlibelf
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author : Adapted from : ( ) ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2023 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Unit Testing Framework Author: Henny Sipma Adapted from: Kaputt () ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2023 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty open CHXmlDocument open CHXmlReader open BCHBasicTypes open BCHDoubleword open BCHLibTypes open BCHStreamWrapper open BCHDwarf open BCHDwarfUtils open BCHELFDebugAbbrevSection open BCHELFTypes open BCHELFSectionHeader module TS = TCHTestSuite module A = TCHAssertion module G = TCHGenerator module S = TCHSpecification module D = BCHDoubleword module SI = BCHSystemInfo module SW = BCHStreamWrapper module U = BCHByteUtilities module EA = TCHBchlibelfAssertion module TR = CHTraceResult let testname = "bCHDwarf" let lastupdated = "2023-02-14" let decode_decompilation_unit_header_test () = let tests = [ ("cu-0", "000012d100040000000004", ("0x12d1", 4, "0x0", 4)); ("cu-1", "000036d900040000013c04", ("0x36d9", 4, "0x13c", 4)) ] in begin TS.new_testsuite (testname ^ "_decode_decompilation_unit_header_test") lastupdated; List.iter (fun (title, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let cuheader = decode_compilation_unit_header ch in EA.equal_compilation_unit_header result cuheader)) tests; TS.launch_tests () end let decode_debug_attribute_value_test () = let tests = [ ("addr", "DW_AT_low_pc", "DW_FORM_addr", "00811a00", "0x811a00"); ("data1", "DW_AT_language", "DW_FORM_data1", "01", "1"); ("data2", "DW_AT_decl_line", "DW_FORM_data2", "5595", "21909"); ("data4", "DW_AT_stmt_list", "DW_FORM_data4", "00003e17", "0x3e17"); ("sdata-0", "DW_AT_const_value", "DW_FORM_sdata", "00", "0"); ("sdata-18", "DW_AT_const_value", "DW_FORM_sdata", "12", "18"); ("sdata-200", "DW_AT_const_value", "DW_FORM_sdata", "c801", "200"); ("sdata-500", "DW_AT_const_value", "DW_FORM_sdata", "f403", "500"); ("sdata-neg", "DW_AT_const_value", "DW_FORM_sdata", "807f060000", "-128"); ("ref4", "DW_AT_type", "DW_FORM_ref4", "0000004f", "<0x4f>"); ("string", "DW_AT_name", "DW_FORM_string", "696e7400", "int"); ] in begin TS.new_testsuite (testname ^ "_decode_debug_attribute_value_test") lastupdated; List.iter (fun (title, s_attr, s_form, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let attr = string_to_dwarf_attr_type s_attr in let form = string_to_dwarf_form_type s_form in let (_, atvalue) = decode_debug_attribute_value ch wordzero (attr, form) in A.equal_string result (dwarf_attr_value_to_string atvalue))) tests; TS.launch_tests () end let decode_debug_ref_attribute_value_test () = let tests = [ ("ref4", "DW_AT_type", "DW_FORM_ref4", "0x0", "0000004f", "<0x4f>"); ("ref4-r0", "DW_AT_type", "DW_FORM_ref4", "0x63cb6", "00000030", "<0x63ce6>"); ("ref4-r1", "DW_AT_type", "DW_FORM_ref4", "0x63cb6", "0000012e", "<0x63de4>") ] in begin TS.new_testsuite (testname ^ "_decode_debug_ref_attribute_value_test") lastupdated; List.iter (fun (title, s_attr, s_form, base, bytes, result) -> TS.add_simple_test ~title (fun () -> let bytestring = U.write_hex_bytes_to_bytestring bytes in let ch = make_pushback_stream ~little_endian:false bytestring in let attr = string_to_dwarf_attr_type s_attr in let form = string_to_dwarf_form_type s_form in let base = TR.tget_ok (string_to_doubleword base) in let (_, atvalue) = decode_debug_attribute_value ch base (attr, form) in A.equal_string result (dwarf_attr_value_to_string atvalue))) tests; TS.launch_tests () end let decode_compilation_unit_test () = let tests = [ ("cu-1", "01110010061101120103081b0825081305000000", "0x9a6a", "000000ad0002" ^ "00000778040100003e1700811a000081" ^ "20582e2e2f50726f6a6563745f536574" ^ "74696e67732f537461727475705f436f" ^ "64652f6763632f636f7265305f696e74" ^ "635f73775f68616e646c6572732e5300" ^ "5c5c56424f585356525c736861726564" ^ "5f446f776e6c6f6164735c776f726b73" ^ "706163655f73333264735f76322e315c" ^ "6d706335373737635f6465765f633130" ^ "5c44656275675f464c41534800303030" ^ "3030303030303030008001", ("0xad", "0x778", 1, DW_TAG_compile_unit, [(DW_AT_stmt_list, "0x3e17"); (DW_AT_low_pc, "0x811a00"); (DW_AT_high_pc, "0x812058"); (DW_AT_name, "../Project_Settings/Startup_Code/gcc/core0_intc_sw_handlers.S"); (DW_AT_comp_dir, "\\\\VBOXSVR\\shared_Downloads\\workspace_s32ds_v2.1\\mpc5777c_dev_c10\\Debug_FLASH"); (DW_AT_producer, "00000000000"); (DW_AT_language, "32769")])) ] in begin TS.new_testsuite (testname ^ "_decode_compilation_unit_test") lastupdated; List.iter (fun (title, abbrev, base, debuginfo, result) -> TS.add_simple_test ~title (fun () -> let astring = U.write_hex_bytes_to_bytestring abbrev in let istring = U.write_hex_bytes_to_bytestring debuginfo in let sh = mk_elf_section_header () in let section = mk_elf_debug_abbrev_section astring sh in let abbreventry = section#get_abbrev_entry in let fabbrev = fun (i: int) -> abbreventry in let chi = make_pushback_stream ~little_endian:false istring in let base = TR.tget_ok (string_to_doubleword base) in let cu = decode_compilation_unit chi base fabbrev in EA.equal_compilation_unit result cu)) tests; TS.launch_tests () end let () = begin TS.new_testfile testname lastupdated; decode_decompilation_unit_header_test (); decode_debug_attribute_value_test (); decode_debug_ref_attribute_value_test (); decode_compilation_unit_test (); TS.exit_file () end
1e8d3c43bee15c157d7e835e98ba28f905a26099da806d5bf8d482881002c7fb
tonsky/advent-of-code
main.clj
(ns advent-of-code.year2021.main) (defn solve-day [day] (let [ns (symbol (str "advent-of-code.year2021.day" day))] (require ns) (println "Day" day) (print "├ part 1: ") (flush) (println ((ns-resolve ns 'part1))) (print "└ part 2: ") (flush) (println ((ns-resolve ns 'part2))) (println))) (defn -main [& args] (doseq [day (range 1 (inc 25))] (solve-day day))) (comment (solve-day 1) (-main))
null
https://raw.githubusercontent.com/tonsky/advent-of-code/4b468df0df84f0fd5caf466c54fcbbb3d783bf71/src/advent_of_code/year2021/main.clj
clojure
(ns advent-of-code.year2021.main) (defn solve-day [day] (let [ns (symbol (str "advent-of-code.year2021.day" day))] (require ns) (println "Day" day) (print "├ part 1: ") (flush) (println ((ns-resolve ns 'part1))) (print "└ part 2: ") (flush) (println ((ns-resolve ns 'part2))) (println))) (defn -main [& args] (doseq [day (range 1 (inc 25))] (solve-day day))) (comment (solve-day 1) (-main))
38b82d72ccee5c6f23f268681d8918e183d0f5a329f39b4a5815c72a1fe7cdd8
gonimo/gonimo
STM.hs
module Utils.STM where import Control.Concurrent.STM import Control.Exception import Gonimo.Server.Error (ServerError (TransactionTimeout)) import Utils.Constants gTimeoutSTM :: Exception e => Int -> STM (Maybe a) -> e -> IO a | retries to execute an ' STM ' action for for some specified ' Microseconds ' gTimeoutSTM μs action ex = do isDelayOver <- registerDelay μs atomically $ do isOver <- readTVar isDelayOver if isOver then throwSTM ex else do result <- action maybe retry {-or-} return result timeoutSTM :: Microseconds -> STM (Maybe a) -> IO a timeoutSTM μs action = gTimeoutSTM μs action TransactionTimeout
null
https://raw.githubusercontent.com/gonimo/gonimo/f4072db9e56f0c853a9f07e048e254eaa671283b/back/src/Utils/STM.hs
haskell
or
module Utils.STM where import Control.Concurrent.STM import Control.Exception import Gonimo.Server.Error (ServerError (TransactionTimeout)) import Utils.Constants gTimeoutSTM :: Exception e => Int -> STM (Maybe a) -> e -> IO a | retries to execute an ' STM ' action for for some specified ' Microseconds ' gTimeoutSTM μs action ex = do isDelayOver <- registerDelay μs atomically $ do isOver <- readTVar isDelayOver if isOver then throwSTM ex else do result <- action timeoutSTM :: Microseconds -> STM (Maybe a) -> IO a timeoutSTM μs action = gTimeoutSTM μs action TransactionTimeout
11cd1f9c486239ee70811a8ec421325394e8c3102f5c62b4a3325be39dc8ebe9
andreabedini/foliage
HackageSecurity.hs
# LANGUAGE FlexibleContexts # module Foliage.HackageSecurity ( module Foliage.HackageSecurity, module Hackage.Security.Server, module Hackage.Security.TUF.FileMap, module Hackage.Security.Key.Env, module Hackage.Security.Util.Path, module Hackage.Security.Util.Some, ) where import Control.Monad (replicateM_) import Data.ByteString.Lazy qualified as BSL import Hackage.Security.Key.Env (fromKeys) import Hackage.Security.Server import Hackage.Security.TUF.FileMap import Hackage.Security.Util.Path (Absolute, Path, fromFilePath, fromUnrootedFilePath, makeAbsolute, rootPath, writeLazyByteString) import Hackage.Security.Util.Some import System.Directory (createDirectoryIfMissing) import System.FilePath readJSONSimple :: FromJSON ReadJSON_NoKeys_NoLayout a => FilePath -> IO (Either DeserializationError a) readJSONSimple fp = do p <- makeAbsolute (fromFilePath fp) readJSON_NoKeys_NoLayout p computeFileInfoSimple :: FilePath -> IO FileInfo computeFileInfoSimple fp = do p <- makeAbsolute (fromFilePath fp) computeFileInfo p createKeys :: FilePath -> IO () createKeys base = do createDirectoryIfMissing True (base </> "root") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "root") createDirectoryIfMissing True (base </> "target") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "target") createDirectoryIfMissing True (base </> "timestamp") replicateM_ 1 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "timestamp") createDirectoryIfMissing True (base </> "snapshot") replicateM_ 1 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "snapshot") createDirectoryIfMissing True (base </> "mirrors") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "mirrors") writeKeyWithId :: FilePath -> Some Key -> IO () writeKeyWithId base k = writeKey (base </> keyIdString (someKeyId k) <.> "json") k writeKey :: FilePath -> Some Key -> IO () writeKey fp key = do p <- makeAbsolute (fromFilePath fp) writeJSON_NoLayout p key renderSignedJSON :: ToJSON WriteJSON a => [Some Key] -> a -> BSL.ByteString renderSignedJSON keys thing = renderJSON hackageRepoLayout (withSignatures hackageRepoLayout keys thing) writeSignedJSON :: ToJSON WriteJSON a => Path Absolute -> (RepoLayout -> RepoPath) -> [Some Key] -> a -> IO () writeSignedJSON outputDirRoot repoPath keys thing = do writeLazyByteString fp $ renderSignedJSON keys thing where fp = anchorRepoPathLocally outputDirRoot $ repoPath hackageRepoLayout
null
https://raw.githubusercontent.com/andreabedini/foliage/35096a57378484c8ed9d887f56b10d0f39c1f6ab/app/Foliage/HackageSecurity.hs
haskell
# LANGUAGE FlexibleContexts # module Foliage.HackageSecurity ( module Foliage.HackageSecurity, module Hackage.Security.Server, module Hackage.Security.TUF.FileMap, module Hackage.Security.Key.Env, module Hackage.Security.Util.Path, module Hackage.Security.Util.Some, ) where import Control.Monad (replicateM_) import Data.ByteString.Lazy qualified as BSL import Hackage.Security.Key.Env (fromKeys) import Hackage.Security.Server import Hackage.Security.TUF.FileMap import Hackage.Security.Util.Path (Absolute, Path, fromFilePath, fromUnrootedFilePath, makeAbsolute, rootPath, writeLazyByteString) import Hackage.Security.Util.Some import System.Directory (createDirectoryIfMissing) import System.FilePath readJSONSimple :: FromJSON ReadJSON_NoKeys_NoLayout a => FilePath -> IO (Either DeserializationError a) readJSONSimple fp = do p <- makeAbsolute (fromFilePath fp) readJSON_NoKeys_NoLayout p computeFileInfoSimple :: FilePath -> IO FileInfo computeFileInfoSimple fp = do p <- makeAbsolute (fromFilePath fp) computeFileInfo p createKeys :: FilePath -> IO () createKeys base = do createDirectoryIfMissing True (base </> "root") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "root") createDirectoryIfMissing True (base </> "target") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "target") createDirectoryIfMissing True (base </> "timestamp") replicateM_ 1 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "timestamp") createDirectoryIfMissing True (base </> "snapshot") replicateM_ 1 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "snapshot") createDirectoryIfMissing True (base </> "mirrors") replicateM_ 3 $ createKey' KeyTypeEd25519 >>= writeKeyWithId (base </> "mirrors") writeKeyWithId :: FilePath -> Some Key -> IO () writeKeyWithId base k = writeKey (base </> keyIdString (someKeyId k) <.> "json") k writeKey :: FilePath -> Some Key -> IO () writeKey fp key = do p <- makeAbsolute (fromFilePath fp) writeJSON_NoLayout p key renderSignedJSON :: ToJSON WriteJSON a => [Some Key] -> a -> BSL.ByteString renderSignedJSON keys thing = renderJSON hackageRepoLayout (withSignatures hackageRepoLayout keys thing) writeSignedJSON :: ToJSON WriteJSON a => Path Absolute -> (RepoLayout -> RepoPath) -> [Some Key] -> a -> IO () writeSignedJSON outputDirRoot repoPath keys thing = do writeLazyByteString fp $ renderSignedJSON keys thing where fp = anchorRepoPathLocally outputDirRoot $ repoPath hackageRepoLayout
8358de94786d90300d90596bc666c928bbf5d8eb71eac32649dda9a606948e6a
GillianPlatform/Gillian
exceptions.ml
exception Impossible of string exception Unsupported of string
null
https://raw.githubusercontent.com/GillianPlatform/Gillian/1c8d65120c04ef87cda689a9d41268e25b5ffa7e/GillianCore/utils/exceptions.ml
ocaml
exception Impossible of string exception Unsupported of string
390a1ab3098c6ab84819ca4fcf5caccd8d31289849a1dfdbfcd51affa2a36d5f
sbtourist/clamq
project.clj
(defproject clamq/clamq-runner "0.5-SNAPSHOT" :description "Clojure APIs for Message Queues" :dependencies [[org.slf4j/slf4j-api "1.6.1"] [org.slf4j/slf4j-simple "1.6.1"] [clamq/clamq-activemq "0.5-SNAPSHOT"] [clamq/clamq-rabbitmq "0.5-SNAPSHOT"]] :aot [clamq.runner.main] :main clamq.runner.main)
null
https://raw.githubusercontent.com/sbtourist/clamq/34a6bbcb7a2a431ea629aa5cfbc687ef31f860f2/clamq-runner/project.clj
clojure
(defproject clamq/clamq-runner "0.5-SNAPSHOT" :description "Clojure APIs for Message Queues" :dependencies [[org.slf4j/slf4j-api "1.6.1"] [org.slf4j/slf4j-simple "1.6.1"] [clamq/clamq-activemq "0.5-SNAPSHOT"] [clamq/clamq-rabbitmq "0.5-SNAPSHOT"]] :aot [clamq.runner.main] :main clamq.runner.main)
4cde37c92676a594953bc74c30dd7d582e78cc9c76b45967d4e1f8cb5b9cea97
mzp/coq-ruby
hipattern.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) i $ I d : hipattern.mli 11739 2009 - 01 - 02 19:33:19Z herbelin $ i (*i*) open Util open Names open Term open Sign open Evd open Pattern open Proof_trees (*i*) s Given a term with second - order variables in it , represented by Meta 's , and possibly applied using SoApp terms , this function will perform second - order , binding - preserving , matching , in the case where the pattern is a pattern in the sense of . ALGORITHM : Given a pattern , we decompose it , flattening casts and apply 's , recursing on all operators , and pushing the name of the binder each time we descend a binder . When we reach a first - order variable , we ask that the corresponding term 's free - rels all be higher than the depth of the current stack . When we reach a second - order application , we ask that the intersection of the free - rels of the term and the current stack be contained in the arguments of the application represented by Meta's, and possibly applied using SoApp terms, this function will perform second-order, binding-preserving, matching, in the case where the pattern is a pattern in the sense of Dale Miller. ALGORITHM: Given a pattern, we decompose it, flattening casts and apply's, recursing on all operators, and pushing the name of the binder each time we descend a binder. When we reach a first-order variable, we ask that the corresponding term's free-rels all be higher than the depth of the current stack. When we reach a second-order application, we ask that the intersection of the free-rels of the term and the current stack be contained in the arguments of the application *) s I implemented the following functions which test whether a term [ t ] is an inductive but non - recursive type , a general conjuction , a general disjunction , or a type with no constructors . They are more general than matching with [ or_term ] , [ and_term ] , etc , since they do not depend on the name of the type . Hence , they also work on ad - hoc disjunctions introduced by the user . ( , 6/8/97 ) . is an inductive but non-recursive type, a general conjuction, a general disjunction, or a type with no constructors. They are more general than matching with [or_term], [and_term], etc, since they do not depend on the name of the type. Hence, they also work on ad-hoc disjunctions introduced by the user. (Eduardo, 6/8/97). *) type 'a matching_function = constr -> 'a option type testing_function = constr -> bool val match_with_non_recursive_type : (constr * constr list) matching_function val is_non_recursive_type : testing_function val match_with_disjunction : ?strict:bool -> (constr * constr list) matching_function val is_disjunction : ?strict:bool -> testing_function val match_with_conjunction : ?strict:bool -> (constr * constr list) matching_function val is_conjunction : ?strict:bool -> testing_function val match_with_record : (constr * constr list) matching_function val is_record : testing_function val match_with_empty_type : constr matching_function val is_empty_type : testing_function type with only one constructor and no arguments , possibly with indices val match_with_unit_or_eq_type : constr matching_function val is_unit_or_eq_type : testing_function type with only one constructor and no arguments , no indices val is_unit_type : testing_function val match_with_equation : (constr * constr list) matching_function val is_equation : testing_function type with only one constructor , no arguments and at least one dependency val match_with_equality_type : (constr * constr list) matching_function val match_with_nottype : (constr * constr) matching_function val is_nottype : testing_function val match_with_forall_term : (name * constr * constr) matching_function val is_forall_term : testing_function val match_with_imp_term : (constr * constr) matching_function val is_imp_term : testing_function I added these functions to test whether a type contains dependent products or not , and if an inductive has constructors with dependent types ( excluding parameters ) . this is useful to check whether a conjunction is a real conjunction and not a dependent tuple . ( , 13/5/2002 ) products or not, and if an inductive has constructors with dependent types (excluding parameters). this is useful to check whether a conjunction is a real conjunction and not a dependent tuple. (Pierre Corbineau, 13/5/2002) *) val has_nodep_prod_after : int -> testing_function val has_nodep_prod : testing_function val match_with_nodep_ind : (constr * constr list * int) matching_function val is_nodep_ind : testing_function val match_with_sigma_type : (constr * constr list) matching_function val is_sigma_type : testing_function * * * * patterns bound to some theory open Coqlib (* Match terms [(eq A t u)] or [(identity A t u)] *) (* Returns associated lemmas and [A,t,u] *) val find_eq_data_decompose : constr -> coq_leibniz_eq_data * (constr * constr * constr) (* Match a term of the form [(existT A P t p)] *) (* Returns associated lemmas and [A,P,t,p] *) val find_sigma_data_decompose : constr -> coq_sigma_data * (constr * constr * constr * constr) (* Match a term of the form [{x:A|P}], returns [A] and [P] *) val match_sigma : constr -> constr * constr val is_matching_sigma : constr -> bool (* Match a decidable equality judgement (e.g [{t=u:>T}+{~t=u}]), returns [t,u,T] and a boolean telling if equality is on the left side *) val match_eqdec : constr -> bool * constr * constr * constr * constr Match an equality up to conversion ; returns [ ( eq , ) ] in normal form open Proof_type open Tacmach val dest_nf_eq : goal sigma -> constr -> (constr * constr * constr) (* Match a negation *) val is_matching_not : constr -> bool val is_matching_imp_False : constr -> bool
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/tactics/hipattern.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i i Match terms [(eq A t u)] or [(identity A t u)] Returns associated lemmas and [A,t,u] Match a term of the form [(existT A P t p)] Returns associated lemmas and [A,P,t,p] Match a term of the form [{x:A|P}], returns [A] and [P] Match a decidable equality judgement (e.g [{t=u:>T}+{~t=u}]), returns [t,u,T] and a boolean telling if equality is on the left side Match a negation
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i $ I d : hipattern.mli 11739 2009 - 01 - 02 19:33:19Z herbelin $ i open Util open Names open Term open Sign open Evd open Pattern open Proof_trees s Given a term with second - order variables in it , represented by Meta 's , and possibly applied using SoApp terms , this function will perform second - order , binding - preserving , matching , in the case where the pattern is a pattern in the sense of . ALGORITHM : Given a pattern , we decompose it , flattening casts and apply 's , recursing on all operators , and pushing the name of the binder each time we descend a binder . When we reach a first - order variable , we ask that the corresponding term 's free - rels all be higher than the depth of the current stack . When we reach a second - order application , we ask that the intersection of the free - rels of the term and the current stack be contained in the arguments of the application represented by Meta's, and possibly applied using SoApp terms, this function will perform second-order, binding-preserving, matching, in the case where the pattern is a pattern in the sense of Dale Miller. ALGORITHM: Given a pattern, we decompose it, flattening casts and apply's, recursing on all operators, and pushing the name of the binder each time we descend a binder. When we reach a first-order variable, we ask that the corresponding term's free-rels all be higher than the depth of the current stack. When we reach a second-order application, we ask that the intersection of the free-rels of the term and the current stack be contained in the arguments of the application *) s I implemented the following functions which test whether a term [ t ] is an inductive but non - recursive type , a general conjuction , a general disjunction , or a type with no constructors . They are more general than matching with [ or_term ] , [ and_term ] , etc , since they do not depend on the name of the type . Hence , they also work on ad - hoc disjunctions introduced by the user . ( , 6/8/97 ) . is an inductive but non-recursive type, a general conjuction, a general disjunction, or a type with no constructors. They are more general than matching with [or_term], [and_term], etc, since they do not depend on the name of the type. Hence, they also work on ad-hoc disjunctions introduced by the user. (Eduardo, 6/8/97). *) type 'a matching_function = constr -> 'a option type testing_function = constr -> bool val match_with_non_recursive_type : (constr * constr list) matching_function val is_non_recursive_type : testing_function val match_with_disjunction : ?strict:bool -> (constr * constr list) matching_function val is_disjunction : ?strict:bool -> testing_function val match_with_conjunction : ?strict:bool -> (constr * constr list) matching_function val is_conjunction : ?strict:bool -> testing_function val match_with_record : (constr * constr list) matching_function val is_record : testing_function val match_with_empty_type : constr matching_function val is_empty_type : testing_function type with only one constructor and no arguments , possibly with indices val match_with_unit_or_eq_type : constr matching_function val is_unit_or_eq_type : testing_function type with only one constructor and no arguments , no indices val is_unit_type : testing_function val match_with_equation : (constr * constr list) matching_function val is_equation : testing_function type with only one constructor , no arguments and at least one dependency val match_with_equality_type : (constr * constr list) matching_function val match_with_nottype : (constr * constr) matching_function val is_nottype : testing_function val match_with_forall_term : (name * constr * constr) matching_function val is_forall_term : testing_function val match_with_imp_term : (constr * constr) matching_function val is_imp_term : testing_function I added these functions to test whether a type contains dependent products or not , and if an inductive has constructors with dependent types ( excluding parameters ) . this is useful to check whether a conjunction is a real conjunction and not a dependent tuple . ( , 13/5/2002 ) products or not, and if an inductive has constructors with dependent types (excluding parameters). this is useful to check whether a conjunction is a real conjunction and not a dependent tuple. (Pierre Corbineau, 13/5/2002) *) val has_nodep_prod_after : int -> testing_function val has_nodep_prod : testing_function val match_with_nodep_ind : (constr * constr list * int) matching_function val is_nodep_ind : testing_function val match_with_sigma_type : (constr * constr list) matching_function val is_sigma_type : testing_function * * * * patterns bound to some theory open Coqlib val find_eq_data_decompose : constr -> coq_leibniz_eq_data * (constr * constr * constr) val find_sigma_data_decompose : constr -> coq_sigma_data * (constr * constr * constr * constr) val match_sigma : constr -> constr * constr val is_matching_sigma : constr -> bool val match_eqdec : constr -> bool * constr * constr * constr * constr Match an equality up to conversion ; returns [ ( eq , ) ] in normal form open Proof_type open Tacmach val dest_nf_eq : goal sigma -> constr -> (constr * constr * constr) val is_matching_not : constr -> bool val is_matching_imp_False : constr -> bool
31d40fb00080bddd07410b306caca48be7307725d63c6be134d90bde897cb16a
jiangpengnju/htdp2e
structure_in_the_world.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname structure_in_the_world) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) When a world program must track two different and independent pieces of information , ; we must use a collection of structures to represent the word state data. One field keeps track of one piece of information and the other field the second ; piece of infromation. ; Consider a space invader game, in which a UFO descends along a straight vertical ; line and some tank moves horizontally at the bottom of a scene. If BOTH objects move at known constant speeds , all that 's needed to describe these two objects is one piece of infromation per object : the y - coordinate for the UFO and the x - coordinate for the tank . Putting these TOGETHER requires a structure with two fields : (define-struct space-game [ufo tank]) A Space - Game is a structure : ( make - space - game Number Number ) interpretation : ( make - space - game uy tx ) means that the UFO ' y - coordinate is currently uy , and the tank 's x - coordinate is at tx . (define ex1 (make-space-game 20 30)) (define ex2 (make-space-game 33 18)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Clearly, a UFO that descends only along a vertical line is boring. To turn this ; idea into an interesting game where the tank attacks the UFO with some weapon, ; the UFO must be able to descend in non-trivial lines, perhaps jumping randomly. An implementation of this idea means that we need two coordinates to describe ; the location of the UFO, so that our revised data definition for the space ; game becomes: SpaceGame is ( make - space - game Posn Number ) . interpretation : ( make - space - game ( make - posn ux uy ) tx ) means that the UFO is currently at ( ux , uy ) and the tank 's coordinate is tx .
null
https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/fixed-size-data/adding-structure/structure_in_the_world.rkt
racket
about the language level of this file in a form that our tools can easily process. we must use a collection of structures to represent the word state data. piece of infromation. Consider a space invader game, in which a UFO descends along a straight vertical line and some tank moves horizontally at the bottom of a scene. If BOTH objects Clearly, a UFO that descends only along a vertical line is boring. To turn this idea into an interesting game where the tank attacks the UFO with some weapon, the UFO must be able to descend in non-trivial lines, perhaps jumping randomly. the location of the UFO, so that our revised data definition for the space game becomes:
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname structure_in_the_world) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) When a world program must track two different and independent pieces of information , One field keeps track of one piece of information and the other field the second move at known constant speeds , all that 's needed to describe these two objects is one piece of infromation per object : the y - coordinate for the UFO and the x - coordinate for the tank . Putting these TOGETHER requires a structure with two fields : (define-struct space-game [ufo tank]) A Space - Game is a structure : ( make - space - game Number Number ) interpretation : ( make - space - game uy tx ) means that the UFO ' y - coordinate is currently uy , and the tank 's x - coordinate is at tx . (define ex1 (make-space-game 20 30)) (define ex2 (make-space-game 33 18)) An implementation of this idea means that we need two coordinates to describe SpaceGame is ( make - space - game Posn Number ) . interpretation : ( make - space - game ( make - posn ux uy ) tx ) means that the UFO is currently at ( ux , uy ) and the tank 's coordinate is tx .
ae2a07d399d793b37b35f03e053ce73f70b160152374e68ab2d3f6730effc974
formal-land/coq-of-ocaml
signatureShape.ml
open SmartPrint * The shape of a signature to simplify comparisons . Two signatures are considered similar if they have the same shape . The shape only contains the names of values and sub - module at the top - level of the module . Basically , shapes are sets of strings . considered similar if they have the same shape. The shape only contains the names of values and sub-module at the top-level of the module. Basically, shapes are sets of strings. *) * With the precise mode , we compute a type shape for the values of the signature . This type shape helps to distinguish between two signatures with the same elements but different types . We can activate this mode with the attribute ` [ @@coq_precise_signature ] ` on a signature definition . signature. This type shape helps to distinguish between two signatures with the same elements but different types. We can activate this mode with the attribute `[@@coq_precise_signature]` on a signature definition. *) module TypeShape = struct type t = { nb_function_parameters : int; nb_type_applications_result : int } let rec get_nb_function_parameters (typ : Types.type_expr) : int * Types.type_expr = match typ.desc with | Tarrow (_, _, typ2, _) -> let nb_function_parameters, result_typ = get_nb_function_parameters typ2 in (nb_function_parameters + 1, result_typ) | _ -> (0, typ) let rec get_nb_type_applications (typ : Types.type_expr) : int = match typ.desc with | Tconstr (_, [ typ ], _) -> 1 + get_nb_type_applications typ | _ -> 0 let of_typ (typ : Types.type_expr) : t = let nb_function_parameters, result_typ = get_nb_function_parameters typ in { nb_function_parameters; nb_type_applications_result = get_nb_type_applications result_typ; } end type t = { high_level : Name.Set.t; precise : TypeShape.t option Name.Map.t option; } let of_signature (attributes : Typedtree.attributes option) (signature : Types.signature) : t = let shape_list = signature |> List.filter_map (fun item -> match item with | Types.Sig_value (ident, typ, _) -> let typ_shape = TypeShape.of_typ typ.val_type in Some (Name.of_ident_raw ident, Some typ_shape) | Sig_module (ident, _, _, _, _) -> Some (Name.of_ident_raw ident, None) | _ -> None) in let high_level = shape_list |> List.map (fun (name, _) -> name) |> Name.Set.of_list in let compute_precise = match attributes with | None -> true | Some attributes -> Attribute.has_precise_signature attributes in let precise = if compute_precise then Some (shape_list |> List.to_seq |> Name.Map.of_seq) else None in { high_level; precise } let are_equal (shape1 : t) (shape2 : t) : bool = Name.Set.equal shape1.high_level shape2.high_level && match (shape1.precise, shape2.precise) with | Some precise1, Some precise2 -> Name.Map.equal ( = ) precise1 precise2 | _ -> true let is_empty (shape : t) : bool = Name.Set.is_empty shape.high_level let pretty_print (shape : t) : SmartPrint.t = shape.high_level |> Name.Set.elements (* We sort the elements of the shape to have a canonical representation. *) |> List.sort compare |> OCaml.list Name.to_coq
null
https://raw.githubusercontent.com/formal-land/coq-of-ocaml/19fe7cf51722da9453cb7ce43724e774e7c9d040/src/signatureShape.ml
ocaml
We sort the elements of the shape to have a canonical representation.
open SmartPrint * The shape of a signature to simplify comparisons . Two signatures are considered similar if they have the same shape . The shape only contains the names of values and sub - module at the top - level of the module . Basically , shapes are sets of strings . considered similar if they have the same shape. The shape only contains the names of values and sub-module at the top-level of the module. Basically, shapes are sets of strings. *) * With the precise mode , we compute a type shape for the values of the signature . This type shape helps to distinguish between two signatures with the same elements but different types . We can activate this mode with the attribute ` [ @@coq_precise_signature ] ` on a signature definition . signature. This type shape helps to distinguish between two signatures with the same elements but different types. We can activate this mode with the attribute `[@@coq_precise_signature]` on a signature definition. *) module TypeShape = struct type t = { nb_function_parameters : int; nb_type_applications_result : int } let rec get_nb_function_parameters (typ : Types.type_expr) : int * Types.type_expr = match typ.desc with | Tarrow (_, _, typ2, _) -> let nb_function_parameters, result_typ = get_nb_function_parameters typ2 in (nb_function_parameters + 1, result_typ) | _ -> (0, typ) let rec get_nb_type_applications (typ : Types.type_expr) : int = match typ.desc with | Tconstr (_, [ typ ], _) -> 1 + get_nb_type_applications typ | _ -> 0 let of_typ (typ : Types.type_expr) : t = let nb_function_parameters, result_typ = get_nb_function_parameters typ in { nb_function_parameters; nb_type_applications_result = get_nb_type_applications result_typ; } end type t = { high_level : Name.Set.t; precise : TypeShape.t option Name.Map.t option; } let of_signature (attributes : Typedtree.attributes option) (signature : Types.signature) : t = let shape_list = signature |> List.filter_map (fun item -> match item with | Types.Sig_value (ident, typ, _) -> let typ_shape = TypeShape.of_typ typ.val_type in Some (Name.of_ident_raw ident, Some typ_shape) | Sig_module (ident, _, _, _, _) -> Some (Name.of_ident_raw ident, None) | _ -> None) in let high_level = shape_list |> List.map (fun (name, _) -> name) |> Name.Set.of_list in let compute_precise = match attributes with | None -> true | Some attributes -> Attribute.has_precise_signature attributes in let precise = if compute_precise then Some (shape_list |> List.to_seq |> Name.Map.of_seq) else None in { high_level; precise } let are_equal (shape1 : t) (shape2 : t) : bool = Name.Set.equal shape1.high_level shape2.high_level && match (shape1.precise, shape2.precise) with | Some precise1, Some precise2 -> Name.Map.equal ( = ) precise1 precise2 | _ -> true let is_empty (shape : t) : bool = Name.Set.is_empty shape.high_level let pretty_print (shape : t) : SmartPrint.t = shape.high_level |> Name.Set.elements |> List.sort compare |> OCaml.list Name.to_coq
2e88b2f554b6f83b6e51ac94a421de78a977950f79c078a38d32f47258016dd0
fused-effects/fused-effects
Writer.hs
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} # HLINT ignore " Eta reduce " # module Writer ( tests , gen0 , genN , test ) where import Control.Arrow ((&&&)) import qualified Control.Carrier.Writer.Church as C.Writer.Church import qualified Control.Carrier.Writer.Strict as C.Writer.Strict import Control.Effect.Writer #if MIN_VERSION_transformers(0,5,6) import qualified Control.Monad.Trans.RWS.CPS as T.RWS.CPS #endif import qualified Control.Monad.Trans.RWS.Lazy as T.RWS.Lazy import qualified Control.Monad.Trans.RWS.Strict as T.RWS.Strict #if MIN_VERSION_transformers(0,5,6) import qualified Control.Monad.Trans.Writer.CPS as T.Writer.CPS #endif import qualified Control.Monad.Trans.Writer.Lazy as T.Writer.Lazy import qualified Control.Monad.Trans.Writer.Strict as T.Writer.Strict import Data.Bifunctor (first) import Data.Tuple (swap) import Gen import qualified Monad import qualified MonadFix tests :: TestTree tests = testGroup "Writer" [ testGroup "WriterC (Church)" $ [ testMonad , testMonadFix , testWriter ] >>= ($ runL (C.Writer.Church.runWriter (curry pure))) , testGroup "WriterC (Strict)" $ [ testMonad , testMonadFix , testWriter ] >>= ($ runL C.Writer.Strict.runWriter) , testGroup "(,)" $ testWriter (runL pure) #if MIN_VERSION_transformers(0,5,6) , testGroup "WriterT (CPS)" $ testWriter (runL (fmap swap . T.Writer.CPS.runWriterT)) #endif , testGroup "WriterT (Lazy)" $ testWriter (runL (fmap swap . T.Writer.Lazy.runWriterT)) , testGroup "WriterT (Strict)" $ testWriter (runL (fmap swap . T.Writer.Strict.runWriterT)) #if MIN_VERSION_transformers(0,5,6) , testGroup "RWST (CPS)" $ testWriter (runL (runRWST T.RWS.CPS.runRWST)) #endif , testGroup "RWST (Lazy)" $ testWriter (runL (runRWST T.RWS.Lazy.runRWST)) , testGroup "RWST (Strict)" $ testWriter (runL (runRWST T.RWS.Strict.runRWST)) ] where testMonad run = Monad.test (m (gen0 w) (genN w b)) a b c initial run testMonadFix run = MonadFix.test (m (gen0 w) (genN w b)) a b initial run testWriter run = Writer.test w (m (gen0 w) (genN w b)) a initial run initial = identity <*> unit runRWST f m = (\ (a, _, w) -> (w, a)) <$> f m () () gen0 :: Has (Writer w) sig m => GenTerm w -> GenTerm a -> [GenTerm (m a)] gen0 w a = [ infixL 4 "<$" (<$) <*> a <*> (label "tell" tell <*> w) ] genN :: forall w b m a sig . (Has (Writer w) sig m, Arg b, Arg w, Show b, Show w, Vary b, Vary w) => GenTerm w -> GenTerm b -> GenM m -> GenTerm a -> [GenTerm (m a)] genN w b m a = [ atom "fmap" fmap <*> fn a <*> (label "listen" (listen @w) <*> m b) , subtermM (m a) (label "censor" censor <*> fn w <*>) ] test :: (Has (Writer w) sig m, Arg w, Eq a, Eq w, Monoid w, Show a, Show w, Vary w, Functor f) => GenTerm w -> GenM m -> GenTerm a -> GenTerm (f ()) -> Run f ((,) w) m -> [TestTree] test w m a i (Run runWriter) = [ testProperty "tell appends a value to the log" . forall_ (i :. w :. m a :. Nil) $ \ i w m -> runWriter ((tell w >> m) <$ i) === fmap (first (mappend w)) (runWriter (m <$ i)) , testProperty "listen eavesdrops on written output" . forall_ (i :. m a :. Nil) $ \ i m -> runWriter (listen m <$ i) === fmap (fst &&& id) (runWriter (m <$ i)) , testProperty "censor revises written output" . forall_ (i :. fn w :. m a :. Nil) $ \ i f m -> runWriter (censor f m <$ i) === fmap (first f) (runWriter (m <$ i)) ]
null
https://raw.githubusercontent.com/fused-effects/fused-effects/85f4b7499789a1750eb9a8d35ea09933b0d7a97b/test/Writer.hs
haskell
# LANGUAGE RankNTypes # # OPTIONS_GHC -Wno-unrecognised-pragmas #
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # HLINT ignore " Eta reduce " # module Writer ( tests , gen0 , genN , test ) where import Control.Arrow ((&&&)) import qualified Control.Carrier.Writer.Church as C.Writer.Church import qualified Control.Carrier.Writer.Strict as C.Writer.Strict import Control.Effect.Writer #if MIN_VERSION_transformers(0,5,6) import qualified Control.Monad.Trans.RWS.CPS as T.RWS.CPS #endif import qualified Control.Monad.Trans.RWS.Lazy as T.RWS.Lazy import qualified Control.Monad.Trans.RWS.Strict as T.RWS.Strict #if MIN_VERSION_transformers(0,5,6) import qualified Control.Monad.Trans.Writer.CPS as T.Writer.CPS #endif import qualified Control.Monad.Trans.Writer.Lazy as T.Writer.Lazy import qualified Control.Monad.Trans.Writer.Strict as T.Writer.Strict import Data.Bifunctor (first) import Data.Tuple (swap) import Gen import qualified Monad import qualified MonadFix tests :: TestTree tests = testGroup "Writer" [ testGroup "WriterC (Church)" $ [ testMonad , testMonadFix , testWriter ] >>= ($ runL (C.Writer.Church.runWriter (curry pure))) , testGroup "WriterC (Strict)" $ [ testMonad , testMonadFix , testWriter ] >>= ($ runL C.Writer.Strict.runWriter) , testGroup "(,)" $ testWriter (runL pure) #if MIN_VERSION_transformers(0,5,6) , testGroup "WriterT (CPS)" $ testWriter (runL (fmap swap . T.Writer.CPS.runWriterT)) #endif , testGroup "WriterT (Lazy)" $ testWriter (runL (fmap swap . T.Writer.Lazy.runWriterT)) , testGroup "WriterT (Strict)" $ testWriter (runL (fmap swap . T.Writer.Strict.runWriterT)) #if MIN_VERSION_transformers(0,5,6) , testGroup "RWST (CPS)" $ testWriter (runL (runRWST T.RWS.CPS.runRWST)) #endif , testGroup "RWST (Lazy)" $ testWriter (runL (runRWST T.RWS.Lazy.runRWST)) , testGroup "RWST (Strict)" $ testWriter (runL (runRWST T.RWS.Strict.runRWST)) ] where testMonad run = Monad.test (m (gen0 w) (genN w b)) a b c initial run testMonadFix run = MonadFix.test (m (gen0 w) (genN w b)) a b initial run testWriter run = Writer.test w (m (gen0 w) (genN w b)) a initial run initial = identity <*> unit runRWST f m = (\ (a, _, w) -> (w, a)) <$> f m () () gen0 :: Has (Writer w) sig m => GenTerm w -> GenTerm a -> [GenTerm (m a)] gen0 w a = [ infixL 4 "<$" (<$) <*> a <*> (label "tell" tell <*> w) ] genN :: forall w b m a sig . (Has (Writer w) sig m, Arg b, Arg w, Show b, Show w, Vary b, Vary w) => GenTerm w -> GenTerm b -> GenM m -> GenTerm a -> [GenTerm (m a)] genN w b m a = [ atom "fmap" fmap <*> fn a <*> (label "listen" (listen @w) <*> m b) , subtermM (m a) (label "censor" censor <*> fn w <*>) ] test :: (Has (Writer w) sig m, Arg w, Eq a, Eq w, Monoid w, Show a, Show w, Vary w, Functor f) => GenTerm w -> GenM m -> GenTerm a -> GenTerm (f ()) -> Run f ((,) w) m -> [TestTree] test w m a i (Run runWriter) = [ testProperty "tell appends a value to the log" . forall_ (i :. w :. m a :. Nil) $ \ i w m -> runWriter ((tell w >> m) <$ i) === fmap (first (mappend w)) (runWriter (m <$ i)) , testProperty "listen eavesdrops on written output" . forall_ (i :. m a :. Nil) $ \ i m -> runWriter (listen m <$ i) === fmap (fst &&& id) (runWriter (m <$ i)) , testProperty "censor revises written output" . forall_ (i :. fn w :. m a :. Nil) $ \ i f m -> runWriter (censor f m <$ i) === fmap (first f) (runWriter (m <$ i)) ]
f4bbd446d70238c1a532791c24c7c0e6a30cd85a4930ba3ff1fb352af7a76d7c
ebresafegaga/tina
shell.ml
open Syntax open Runtime open Backend open Typing module P = Parsing.ParserEntry let eval source = let syntax = source |> Lexing.from_string |> P.parse in let ty = syntax |> Typecheck.handle_toplevel |> Ctx.pp_ctx |> String.concat "\n" in let term = syntax (* |> DesugarEffect.handle_toplevel*) |> Eval.process_toplevel |> String.concat "\n" in Printf.sprintf "%s \n %s" term ty let eval source = match eval source with | result -> Format.fprintf !Settings.output_formatter "%s@." result | exception Errors.RuntimeError msg -> Format.fprintf !Settings.error_formatter "%s@." msg let execute_source = eval let load_source = eval let compile_js source = let process src = src |> Lexing.from_string |> P.parse |> DesugarEffect.handle_toplevel |> DesugarData.handle_toplevel |> DesugarCase.handle_toplevel |> KNormal.handle_toplevel |> Js.handle_toplevel |> List.map Js.gen_toplevel |> String.concat "\n" in let js_code = process source in Format.fprintf !Settings.error_formatter "%s@." js_code let complie_llvm = ()
null
https://raw.githubusercontent.com/ebresafegaga/tina/66fa8daa66c0c6e65260bbea3e8e2ddcc2f9d2d0/shell/shell.ml
ocaml
|> DesugarEffect.handle_toplevel
open Syntax open Runtime open Backend open Typing module P = Parsing.ParserEntry let eval source = let syntax = source |> Lexing.from_string |> P.parse in let ty = syntax |> Typecheck.handle_toplevel |> Ctx.pp_ctx |> String.concat "\n" in Printf.sprintf "%s \n %s" term ty let eval source = match eval source with | result -> Format.fprintf !Settings.output_formatter "%s@." result | exception Errors.RuntimeError msg -> Format.fprintf !Settings.error_formatter "%s@." msg let execute_source = eval let load_source = eval let compile_js source = let process src = src |> Lexing.from_string |> P.parse |> DesugarEffect.handle_toplevel |> DesugarData.handle_toplevel |> DesugarCase.handle_toplevel |> KNormal.handle_toplevel |> Js.handle_toplevel |> List.map Js.gen_toplevel |> String.concat "\n" in let js_code = process source in Format.fprintf !Settings.error_formatter "%s@." js_code let complie_llvm = ()
289f8e5c7ace1baea3f4fea1f7c7522dce023790116f5c2f0a8a80f6c7e6d248
fyquah/hardcaml_zprize
test_barrett_reduction.mli
open Hardcaml module Make (M : sig val bits : int val output_bits : int end) : sig include module type of Field_ops_lib.Barrett_reduction.With_interface (M) val test : debug:bool -> test_cases:Z.t list -> config:Field_ops_lib.Barrett_reduction.Config.t -> sim:Cyclesim.With_interface(I)(O).t -> unit end
null
https://raw.githubusercontent.com/fyquah/hardcaml_zprize/7eb1bd214908fa801781db33287eaf12691715f8/libs/field_ops/test/test_barrett_reduction.mli
ocaml
open Hardcaml module Make (M : sig val bits : int val output_bits : int end) : sig include module type of Field_ops_lib.Barrett_reduction.With_interface (M) val test : debug:bool -> test_cases:Z.t list -> config:Field_ops_lib.Barrett_reduction.Config.t -> sim:Cyclesim.With_interface(I)(O).t -> unit end
49ab6f2e0810bd1e01951c55ee6ebed419a7282855d902cd3f31fa2d9cd735f7
txyyss/Project-Euler
Euler106.hs
Let S(A ) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non - empty disjoint -- subsets, B and C, the following properties are true: -- S(B) != S(C); that is, sums of subsets cannot be equal. If B contains more elements than C then S(B ) > S(C ) . -- For this problem we shall assume that a given set contains n strictly increasing elements and it already satisfies the second -- rule. Surprisingly , out of the 25 possible subset pairs that can be obtained from a set for which n = 4 , only 1 of these pairs need to be tested for equality ( first rule ) . Similarly , when n = 7 , only 70 out of the 966 subset pairs need to be tested . For n = 12 , how many of the 261625 subset pairs that can be -- obtained need to be tested for equality? NOTE : This problem is related to problems 103 and 105 . module Euler106 where -- see analysis here: -- -euler-106-minimum-comparisons-special-sum-sets/ choose :: Int -> Int -> Int choose m n = product [(n+1)..m] `div` product [2..(m-n)] catalan :: Int -> Int catalan n = choose (2*n) n `div` (n+1) needCheck :: Int -> Int -> Int needCheck n s = choose n s * choose (n-s) s `div` 2 - catalan s * choose n (2*s) result106 = sum $ map (needCheck 12) [2..6]
null
https://raw.githubusercontent.com/txyyss/Project-Euler/d2f41dad429013868445c1c9c1c270b951550ee9/Euler106.hs
haskell
subsets, B and C, the following properties are true: S(B) != S(C); that is, sums of subsets cannot be equal. For this problem we shall assume that a given set contains n rule. obtained need to be tested for equality? see analysis here: -euler-106-minimum-comparisons-special-sum-sets/
Let S(A ) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non - empty disjoint If B contains more elements than C then S(B ) > S(C ) . strictly increasing elements and it already satisfies the second Surprisingly , out of the 25 possible subset pairs that can be obtained from a set for which n = 4 , only 1 of these pairs need to be tested for equality ( first rule ) . Similarly , when n = 7 , only 70 out of the 966 subset pairs need to be tested . For n = 12 , how many of the 261625 subset pairs that can be NOTE : This problem is related to problems 103 and 105 . module Euler106 where choose :: Int -> Int -> Int choose m n = product [(n+1)..m] `div` product [2..(m-n)] catalan :: Int -> Int catalan n = choose (2*n) n `div` (n+1) needCheck :: Int -> Int -> Int needCheck n s = choose n s * choose (n-s) s `div` 2 - catalan s * choose n (2*s) result106 = sum $ map (needCheck 12) [2..6]
f7add9d1c7bb4dd9c74118b06a0949cafb8c74f570ac6d462d65a012bbd4d703
reflectionalist/S9fES
appendb.scm
Scheme 9 from Empty Space , Function Library By , 2010 ; Placed in the Public Domain ; ; (append! list ...) ==> unspecific ; (append! list ... object) ==> unspecific ; APPEND ! is like , but appends the LISTs destructively . ; It destroys all but the last object passed to it and returns ; an unspecific value. The append!ed list will be stored in the ; first LIST, which should be bound to a symbol or it will not be accessible after the operation . The first LIST may not be ; '(). ; ; Example: (let ((a (list 1 2 3))) ( append ! a ( list 4 5 6 ) ' end ) ; a) ==> (1 2 3 4 5 6 . end) (define (append! . a*) (letrec ((append2! (lambda (a b) (cond ((null? a) (error "append!: cannot append to ()")) ((null? b) a) (else (let find-nil ((a a)) (if (null? (cdr a)) (begin (set-cdr! a b) a) (find-nil (cdr a))))))))) (if (and (not (null? a*)) (not (null? (cdr a*)))) (begin (fold-left append2! (car a*) (cdr a*)) (void)))))
null
https://raw.githubusercontent.com/reflectionalist/S9fES/0ade11593cf35f112e197026886fc819042058dd/lib/appendb.scm
scheme
Placed in the Public Domain (append! list ...) ==> unspecific (append! list ... object) ==> unspecific It destroys all but the last object passed to it and returns an unspecific value. The append!ed list will be stored in the first LIST, which should be bound to a symbol or it will not '(). Example: (let ((a (list 1 2 3))) a) ==> (1 2 3 4 5 6 . end)
Scheme 9 from Empty Space , Function Library By , 2010 APPEND ! is like , but appends the LISTs destructively . be accessible after the operation . The first LIST may not be ( append ! a ( list 4 5 6 ) ' end ) (define (append! . a*) (letrec ((append2! (lambda (a b) (cond ((null? a) (error "append!: cannot append to ()")) ((null? b) a) (else (let find-nil ((a a)) (if (null? (cdr a)) (begin (set-cdr! a b) a) (find-nil (cdr a))))))))) (if (and (not (null? a*)) (not (null? (cdr a*)))) (begin (fold-left append2! (car a*) (cdr a*)) (void)))))
2e5ed1f72f7447ba13b46ec3299f21b059a70f916ef6c551fb03c3c00c81e32d
stritzinger/opcua
opcua_nodeset_parser.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% @doc OPCUA Node Set parser. %%% %%% Parse OPCUA Node Set files and generate internal database format. %%% %%% @end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -module(opcua_nodeset_parser). TODO % % %% %% - When opcua_space has been updated to handle the generation of all the %% metadata dynamically (subtypes, type definition...), use a space and %% store it. - Properly parse XML values from the NodeSet XML file . e.g. Variables like EnumValues ( ) should have a value . %% - The namespace handling is probably wrong, check how loading multiple %% nodesets with a different list of namespaces would work. %%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -include_lib("kernel/include/logger.hrl"). -include_lib("xmerl/include/xmerl.hrl"). -include("opcua.hrl"). -include("opcua_internal.hrl"). %%% EXPORTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% API Functions -export([parse/0]). MACROS % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % -define(IS_NODE(Name), Name =:= <<"UAObject">>; Name =:= <<"UAVariable">>; Name =:= <<"UAMethod">>; Name =:= <<"UAView">>; Name =:= <<"UAObjectType">>; Name =:= <<"UAVariableType">>; Name =:= <<"UADataType">>; Name =:= <<"UAReferenceType">> ). %%% API FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% parse() -> PrivDir = code:priv_dir(opcua), BaseDir = filename:join([PrivDir, "nodeset"]), InputDir = filename:join([BaseDir, "reference"]), OutputDir = filename:join([BaseDir, "data"]), parse_attributes(InputDir, OutputDir), parse_status(InputDir, OutputDir), parse_nodeset(InputDir, OutputDir). %%% INTERNAL FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% parse_attributes(InputDir, OutputDir) -> InputPath = filename:join([InputDir, "Schema", "AttributeIds.csv"]), OutputPath = filename:join([OutputDir, "nodeset.attributes.bterm"]), ?LOG_INFO("Loading OPCUA attributes mapping from ~s ...", [InputPath]), Terms = opcua_util_csv:fold(InputPath, fun([NameStr, IdStr], Acc) -> Name = opcua_util:convert_name(NameStr), Id = list_to_integer(IdStr), [{Id, Name} | Acc] end, []), ?LOG_INFO("Saving OPCUA attributes mapping into ~s ...", [OutputPath]), opcua_util_bterm:save(OutputPath, Terms). parse_status(InputDir, OutputDir) -> InputPath = filename:join([InputDir, "Schema", "StatusCode.csv"]), OutputPath = filename:join([OutputDir, "nodeset.status.bterm"]), ?LOG_INFO("Loading OPCUA status code mapping from ~s ...", [InputPath]), Terms = opcua_util_csv:fold(InputPath, fun([NameStr, "0x" ++ CodeStr | DescList], Acc) -> Name = opcua_util:convert_name(NameStr), Code = list_to_integer(CodeStr, 16), Desc = iolist_to_binary(lists:join("," , DescList)), [{Code, Name, Desc} | Acc] end, []), ?LOG_INFO("Saving OPCUA status code mapping into ~s ...", [OutputPath]), opcua_util_bterm:save(OutputPath, Terms). parse_nodeset(InputDir, OutputDir) -> Namespaces = #{0 => <<"/">>}, Meta = #{namespaces => Namespaces}, BaseInputPath = filename:join([InputDir, "Schema", "Opc.Ua.NodeSet2.Services.xml"]), InputPatternPath = filename:join([InputDir, "*", "*.NodeSet2.xml"]), InputPathList = [BaseInputPath | filelib:wildcard(InputPatternPath)], parse(OutputDir, InputPathList, Meta, []). parse(DestDir, [], Meta, Nodes) -> NodesProplist = lists:reverse(Nodes), DataTypesSchemas = extract_data_type_schemas(NodesProplist), Encodings = extract_encodings(NodesProplist), NodeSpecs = extract_nodes(NodesProplist), References = extract_references(NodesProplist), Namespaces = maps:to_list(maps:get(namespaces, Meta, #{})), write_terms(DestDir, "OPCUA data type schemas", "datatypes", DataTypesSchemas), write_terms(DestDir, "OPCUA encoding specifications", "encodings", Encodings), write_terms(DestDir, "OPCUA nodes", "nodes", NodeSpecs), write_terms(DestDir, "OPCUA references", "references", References), write_terms(DestDir, "OPCUA namespaces", "namespaces", Namespaces), ok; parse(DestDir, [File | Files], Meta, Nodes) -> ?LOG_INFO("Parsing OPCUA nodeset file ~s ...", [File]), {XML, []} = xmerl_scan:file(File, [{space, normalize}]), {Meta2, Nodes2} = parse_node_set(xml_to_simple(XML), Meta, Nodes), parse(DestDir, Files, Meta2, Nodes2). XML SAX PARSER CALLBACK FUNCTIONS % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % parse_node_set({<<"UANodeSet">>, _Attrs, Content}, Meta, Nodes) -> %FIXME: This is probably wrong, checks that the namespaces and alias are % not supposed to be local to a nodeset definition, if they are we shouldn't % merge them into the global map. Namespaces = parse_namespaces(get_value([<<"NamespaceUris">>], Content, [])), Aliases = parse_aliases(get_value([<<"Aliases">>], Content)), Meta2 = Meta#{ namespaces => maps:merge(maps:get(namespaces, Meta, #{}), Namespaces), aliases => maps:merge(maps:get(aliases, Meta, #{}), Aliases) }, lists:foldl(fun parse_node/2, {Meta2, Nodes}, Content). parse_namespaces(Namespaces) -> URIs = [URI || {<<"Uri">>, _, [URI]} <- Namespaces], maps:from_list(lists:zip(lists:seq(1, length(URIs)), URIs)). parse_aliases(Aliases) -> maps:from_list([{Name, parse(node_id, ID, #{aliases => #{}})} || {<<"Alias">>, #{<<"Alias">> := Name}, [ID]} <- Aliases]). parse_node({Tag, Attrs, Content} = Elem, {Meta, Nodes}) when ?IS_NODE(Tag) -> NodeId = get_attr(<<"NodeId">>, Attrs, node_id, Meta), Node = #opcua_node{ node_id = NodeId, origin = standard, browse_name = maps:get(<<"BrowseName">>, Attrs, undefined), display_name = hd(get_value([<<"DisplayName">>], Content)), node_class = parse_node_class(Elem, Meta) }, Refs = parse_references(get_value([<<"References">>], Content), NodeId, Meta), {Meta, [{NodeId, {Node, Refs}}|Nodes]}; parse_node(_Element, State) -> State. parse_references(Refs, NodeId, Meta) -> [parse_reference(R, NodeId, Meta) || R <- Refs]. parse_reference({<<"Reference">>, Attrs, [Peer]}, BaseNodeId, Meta) -> PeerNodeId = parse(node_id, Peer, Meta), {SourceNodeId, TargetNodeId} = case get_attr(<<"IsForward">>, Attrs, boolean, Meta, true) of true -> {BaseNodeId, PeerNodeId}; false -> {PeerNodeId, BaseNodeId} end, #opcua_reference{ type_id = get_attr(<<"ReferenceType">>, Attrs, node_id, Meta), source_id = SourceNodeId, target_id = TargetNodeId }. parse_node_class({<<"UAObject">>, Attrs, _Content}, Meta) -> #opcua_object{ event_notifier = get_attr(<<"EventNotifier">>, Attrs, integer, Meta, undefined) }; parse_node_class({<<"UADataType">>, Attrs, Content}, Meta) -> #opcua_data_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false), data_type_definition = parse_data_type_definition(get_in([<<"Definition">>], Content, undefined), Meta) }; parse_node_class({<<"UAReferenceType">>, Attrs, Content}, Meta) -> #opcua_reference_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false), symmetric = get_attr(<<"Symmetric">>, Attrs, boolean, Meta, false), inverse_name = get_value([<<"InverseName">>], Content, undefined) }; parse_node_class({<<"UAObjectType">>, Attrs, _Content}, Meta) -> #opcua_object_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false) }; parse_node_class({<<"UAVariableType">>, Attrs, _Content}, Meta) -> #opcua_variable_type{ data_type = get_attr(<<"DataType">>, Attrs, node_id, Meta, undefined), value_rank = get_attr(<<"ValueRank">>, Attrs, integer, Meta, undefined), array_dimensions = get_attr(<<"ArrayDimensions">>, Attrs, array_dimensions, Meta, undefined), is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false) }; parse_node_class({<<"UAVariable">>, Attrs, _Content}, Meta) -> #opcua_variable{ data_type = get_attr(<<"DataType">>, Attrs, node_id, Meta, undefined), value_rank = get_attr(<<"ValueRank">>, Attrs, integer, Meta, undefined), array_dimensions = get_attr(<<"ArrayDimensions">>, Attrs, array_dimensions, Meta, undefined), access_level = get_attr(<<"AccessLevel">>, Attrs, byte, Meta, undefined), user_access_level = get_attr(<<"UserAccessLevel">>, Attrs, byte, Meta, undefined), minimum_sampling_interval = get_attr(<<"MinimumSamplingInterval">>, Attrs, float, Meta, undefined), historizing = get_attr(<<"Historizing">>, Attrs, boolean, Meta, false), access_level_ex = get_attr(<<"AccessLevelEx">>, Attrs, uint32, Meta, undefined) }; parse_node_class({<<"UAMethod">>, Attrs, _Content}, Meta) -> #opcua_method{ executable = get_attr(<<"Executable">>, Attrs, boolean, Meta, true), user_executable = get_attr(<<"UserExecutable">>, Attrs, boolean, Meta, true) }. parse(node_id, Data, #{aliases := Aliases}) -> try opcua_node:parse(Data) catch _:badarg -> maps:get(Data, Aliases) end; parse(boolean, <<"true">>, _Meta) -> true; parse(boolean, <<"false">>, _Meta) -> false; parse(integer, Bin, _Meta) -> {Int, <<>>} = string:to_integer(Bin), Int; parse(uint32, Bin, Meta) -> parse({integer, uint32, 0, 4294967295}, Bin, Meta); parse(byte, Bin, Meta) -> parse({integer, byte, 0, 255}, Bin, Meta); parse(float, Duration, Meta) -> case string:to_float(Duration) of {Float, <<>>} -> Float; {error, no_float} -> parse(integer, Duration, Meta) * 1.0 end; parse({integer, Name, Lower, Upper}, Bin, _Meta) -> case string:to_integer(Bin) of {Int, <<>>} when Int >= Lower, Int =< Upper -> Int; _Other -> {invalid_type, Name, Bin} end; parse(array_dimensions, Dimensions, Meta) -> [parse(integer, D, Meta) || D <- binary:split(Dimensions, <<$,>>, [global])]. parse_data_type_definition(undefined, _Meta) -> undefined; parse_data_type_definition({_Tag, Attrs, Fields}, Meta) -> ParsedFields = [parse_data_type_definition_field(F, Meta) || F <- Fields], IsUnion = get_attr(<<"IsUnion">>, Attrs, boolean, Meta, false), IsOptionSet = get_attr(<<"IsOptionSet">>, Attrs, boolean, Meta, false), #{fields => ParsedFields, is_union => IsUnion, is_option_set => IsOptionSet}. parse_data_type_definition_field({<<"Field">>, Attrs, _Content}, Meta) -> {opcua_util:convert_name(maps:get(<<"Name">>, Attrs)), maps:from_list(lists:foldl( fun({Attr, Key, Type}, Result) -> try [{Key, get_attr(Attr, Attrs, Type, Meta)}|Result] catch error:{attr_not_found, Attr} -> Result end end, [], [ {<<"DataType">>, data_type, node_id}, {<<"Value">>, value, integer}, {<<"ValueRank">>, value_rank, integer}, {<<"IsOptional">>, is_optional, boolean} ] ))}. %%% INTERNAL FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% get_attr(Name, Attrs, Type, Meta) -> get_attr(Name, Attrs, Type, Meta, fun() -> error({attr_not_found, Name}) end). get_attr(Name, Attrs, Type, Meta, Default) -> case maps:find(Name, Attrs) of {ok, Value} -> parse(Type, Value, Meta); error when is_function(Default) -> Default(); error -> Default end. get_value(Keys, Content) -> get_value(Keys, Content, fun() -> error({value_not_found, Keys, Content}) end). get_value(Keys, Content, Default) -> case get_in(Keys, Content, Default) of {_Tag, _Attrs, Value} -> Value; Default -> Default end. get_in([K|Keys], [Tuple|_List], Default) when element(1, Tuple) =:= K -> get_in(Keys, Tuple, Default); get_in(Keys, [_Tuple|List], Default) -> get_in(Keys, List, Default); get_in([], Item, _Default) -> Item; get_in(_Keys, [], Default) when is_function(Default) -> Default(); get_in(_Keys, [], Default) -> Default. xml_to_simple(#xmlElement{} = E) -> { atom_to_binary(E#xmlElement.name, utf8), xml_attrs_to_map(E#xmlElement.attributes), xml_to_simple(E#xmlElement.content) }; xml_to_simple(Elements) when is_list(Elements) -> [S || E <- Elements, S <- [xml_to_simple(E)], S =/= <<" ">>]; xml_to_simple(#xmlText{value = Value}) -> iolist_to_binary(Value). xml_attrs_to_map(Attrs) -> maps:from_list([ {atom_to_binary(Name, utf8), iolist_to_binary(Value)} || #xmlAttribute{name = Name, value = Value} <- Attrs ]). extract_references(NodesProplist) -> [Ref || {_NodeId, {_Node, Refs}} <- NodesProplist, Ref <- Refs]. extract_nodes(NodesProplist) -> [Node || {_NodeId, {Node, _Refs}} <- NodesProplist]. extract_data_type_schemas(NodesProplist) -> DataTypeNodesProplist = lists:filter(fun({_, {Node, _}}) -> is_record(Node#opcua_node.node_class, opcua_data_type) end, NodesProplist), opcua_nodeset_datatypes:generate_schemas(DataTypeNodesProplist). extract_encodings(NodesProplist) -> [{TargetNodeId, {SourceNodeId, binary}} || {_NodeId, { #opcua_node{browse_name = <<"Default Binary">>}, References } } <- NodesProplist, #opcua_reference{ type_id = #opcua_node_id{value = 38}, source_id = SourceNodeId, target_id = TargetNodeId } <- References ]. write_terms(BaseDir, Desc, Tag, Terms) -> OutputPath = filename:join([BaseDir, "nodeset."++ Tag ++ ".bterm"]), ?LOG_INFO("Saving ~s into ~s ...", [Desc, OutputPath]), opcua_util_bterm:save(OutputPath, Terms).
null
https://raw.githubusercontent.com/stritzinger/opcua/a9802f829f80e6961871653f4d3c932f9496ba99/src/opcua_nodeset_parser.erl
erlang
@doc OPCUA Node Set parser. Parse OPCUA Node Set files and generate internal database format. @end % - When opcua_space has been updated to handle the generation of all the metadata dynamically (subtypes, type definition...), use a space and store it. - The namespace handling is probably wrong, check how loading multiple nodesets with a different list of namespaces would work. INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXPORTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% API Functions % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % API FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INTERNAL FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % FIXME: This is probably wrong, checks that the namespaces and alias are not supposed to be local to a nodeset definition, if they are we shouldn't merge them into the global map. INTERNAL FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-module(opcua_nodeset_parser). - Properly parse XML values from the NodeSet XML file . e.g. Variables like EnumValues ( ) should have a value . -include_lib("kernel/include/logger.hrl"). -include_lib("xmerl/include/xmerl.hrl"). -include("opcua.hrl"). -include("opcua_internal.hrl"). -export([parse/0]). -define(IS_NODE(Name), Name =:= <<"UAObject">>; Name =:= <<"UAVariable">>; Name =:= <<"UAMethod">>; Name =:= <<"UAView">>; Name =:= <<"UAObjectType">>; Name =:= <<"UAVariableType">>; Name =:= <<"UADataType">>; Name =:= <<"UAReferenceType">> ). parse() -> PrivDir = code:priv_dir(opcua), BaseDir = filename:join([PrivDir, "nodeset"]), InputDir = filename:join([BaseDir, "reference"]), OutputDir = filename:join([BaseDir, "data"]), parse_attributes(InputDir, OutputDir), parse_status(InputDir, OutputDir), parse_nodeset(InputDir, OutputDir). parse_attributes(InputDir, OutputDir) -> InputPath = filename:join([InputDir, "Schema", "AttributeIds.csv"]), OutputPath = filename:join([OutputDir, "nodeset.attributes.bterm"]), ?LOG_INFO("Loading OPCUA attributes mapping from ~s ...", [InputPath]), Terms = opcua_util_csv:fold(InputPath, fun([NameStr, IdStr], Acc) -> Name = opcua_util:convert_name(NameStr), Id = list_to_integer(IdStr), [{Id, Name} | Acc] end, []), ?LOG_INFO("Saving OPCUA attributes mapping into ~s ...", [OutputPath]), opcua_util_bterm:save(OutputPath, Terms). parse_status(InputDir, OutputDir) -> InputPath = filename:join([InputDir, "Schema", "StatusCode.csv"]), OutputPath = filename:join([OutputDir, "nodeset.status.bterm"]), ?LOG_INFO("Loading OPCUA status code mapping from ~s ...", [InputPath]), Terms = opcua_util_csv:fold(InputPath, fun([NameStr, "0x" ++ CodeStr | DescList], Acc) -> Name = opcua_util:convert_name(NameStr), Code = list_to_integer(CodeStr, 16), Desc = iolist_to_binary(lists:join("," , DescList)), [{Code, Name, Desc} | Acc] end, []), ?LOG_INFO("Saving OPCUA status code mapping into ~s ...", [OutputPath]), opcua_util_bterm:save(OutputPath, Terms). parse_nodeset(InputDir, OutputDir) -> Namespaces = #{0 => <<"/">>}, Meta = #{namespaces => Namespaces}, BaseInputPath = filename:join([InputDir, "Schema", "Opc.Ua.NodeSet2.Services.xml"]), InputPatternPath = filename:join([InputDir, "*", "*.NodeSet2.xml"]), InputPathList = [BaseInputPath | filelib:wildcard(InputPatternPath)], parse(OutputDir, InputPathList, Meta, []). parse(DestDir, [], Meta, Nodes) -> NodesProplist = lists:reverse(Nodes), DataTypesSchemas = extract_data_type_schemas(NodesProplist), Encodings = extract_encodings(NodesProplist), NodeSpecs = extract_nodes(NodesProplist), References = extract_references(NodesProplist), Namespaces = maps:to_list(maps:get(namespaces, Meta, #{})), write_terms(DestDir, "OPCUA data type schemas", "datatypes", DataTypesSchemas), write_terms(DestDir, "OPCUA encoding specifications", "encodings", Encodings), write_terms(DestDir, "OPCUA nodes", "nodes", NodeSpecs), write_terms(DestDir, "OPCUA references", "references", References), write_terms(DestDir, "OPCUA namespaces", "namespaces", Namespaces), ok; parse(DestDir, [File | Files], Meta, Nodes) -> ?LOG_INFO("Parsing OPCUA nodeset file ~s ...", [File]), {XML, []} = xmerl_scan:file(File, [{space, normalize}]), {Meta2, Nodes2} = parse_node_set(xml_to_simple(XML), Meta, Nodes), parse(DestDir, Files, Meta2, Nodes2). parse_node_set({<<"UANodeSet">>, _Attrs, Content}, Meta, Nodes) -> Namespaces = parse_namespaces(get_value([<<"NamespaceUris">>], Content, [])), Aliases = parse_aliases(get_value([<<"Aliases">>], Content)), Meta2 = Meta#{ namespaces => maps:merge(maps:get(namespaces, Meta, #{}), Namespaces), aliases => maps:merge(maps:get(aliases, Meta, #{}), Aliases) }, lists:foldl(fun parse_node/2, {Meta2, Nodes}, Content). parse_namespaces(Namespaces) -> URIs = [URI || {<<"Uri">>, _, [URI]} <- Namespaces], maps:from_list(lists:zip(lists:seq(1, length(URIs)), URIs)). parse_aliases(Aliases) -> maps:from_list([{Name, parse(node_id, ID, #{aliases => #{}})} || {<<"Alias">>, #{<<"Alias">> := Name}, [ID]} <- Aliases]). parse_node({Tag, Attrs, Content} = Elem, {Meta, Nodes}) when ?IS_NODE(Tag) -> NodeId = get_attr(<<"NodeId">>, Attrs, node_id, Meta), Node = #opcua_node{ node_id = NodeId, origin = standard, browse_name = maps:get(<<"BrowseName">>, Attrs, undefined), display_name = hd(get_value([<<"DisplayName">>], Content)), node_class = parse_node_class(Elem, Meta) }, Refs = parse_references(get_value([<<"References">>], Content), NodeId, Meta), {Meta, [{NodeId, {Node, Refs}}|Nodes]}; parse_node(_Element, State) -> State. parse_references(Refs, NodeId, Meta) -> [parse_reference(R, NodeId, Meta) || R <- Refs]. parse_reference({<<"Reference">>, Attrs, [Peer]}, BaseNodeId, Meta) -> PeerNodeId = parse(node_id, Peer, Meta), {SourceNodeId, TargetNodeId} = case get_attr(<<"IsForward">>, Attrs, boolean, Meta, true) of true -> {BaseNodeId, PeerNodeId}; false -> {PeerNodeId, BaseNodeId} end, #opcua_reference{ type_id = get_attr(<<"ReferenceType">>, Attrs, node_id, Meta), source_id = SourceNodeId, target_id = TargetNodeId }. parse_node_class({<<"UAObject">>, Attrs, _Content}, Meta) -> #opcua_object{ event_notifier = get_attr(<<"EventNotifier">>, Attrs, integer, Meta, undefined) }; parse_node_class({<<"UADataType">>, Attrs, Content}, Meta) -> #opcua_data_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false), data_type_definition = parse_data_type_definition(get_in([<<"Definition">>], Content, undefined), Meta) }; parse_node_class({<<"UAReferenceType">>, Attrs, Content}, Meta) -> #opcua_reference_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false), symmetric = get_attr(<<"Symmetric">>, Attrs, boolean, Meta, false), inverse_name = get_value([<<"InverseName">>], Content, undefined) }; parse_node_class({<<"UAObjectType">>, Attrs, _Content}, Meta) -> #opcua_object_type{ is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false) }; parse_node_class({<<"UAVariableType">>, Attrs, _Content}, Meta) -> #opcua_variable_type{ data_type = get_attr(<<"DataType">>, Attrs, node_id, Meta, undefined), value_rank = get_attr(<<"ValueRank">>, Attrs, integer, Meta, undefined), array_dimensions = get_attr(<<"ArrayDimensions">>, Attrs, array_dimensions, Meta, undefined), is_abstract = get_attr(<<"IsAbstract">>, Attrs, boolean, Meta, false) }; parse_node_class({<<"UAVariable">>, Attrs, _Content}, Meta) -> #opcua_variable{ data_type = get_attr(<<"DataType">>, Attrs, node_id, Meta, undefined), value_rank = get_attr(<<"ValueRank">>, Attrs, integer, Meta, undefined), array_dimensions = get_attr(<<"ArrayDimensions">>, Attrs, array_dimensions, Meta, undefined), access_level = get_attr(<<"AccessLevel">>, Attrs, byte, Meta, undefined), user_access_level = get_attr(<<"UserAccessLevel">>, Attrs, byte, Meta, undefined), minimum_sampling_interval = get_attr(<<"MinimumSamplingInterval">>, Attrs, float, Meta, undefined), historizing = get_attr(<<"Historizing">>, Attrs, boolean, Meta, false), access_level_ex = get_attr(<<"AccessLevelEx">>, Attrs, uint32, Meta, undefined) }; parse_node_class({<<"UAMethod">>, Attrs, _Content}, Meta) -> #opcua_method{ executable = get_attr(<<"Executable">>, Attrs, boolean, Meta, true), user_executable = get_attr(<<"UserExecutable">>, Attrs, boolean, Meta, true) }. parse(node_id, Data, #{aliases := Aliases}) -> try opcua_node:parse(Data) catch _:badarg -> maps:get(Data, Aliases) end; parse(boolean, <<"true">>, _Meta) -> true; parse(boolean, <<"false">>, _Meta) -> false; parse(integer, Bin, _Meta) -> {Int, <<>>} = string:to_integer(Bin), Int; parse(uint32, Bin, Meta) -> parse({integer, uint32, 0, 4294967295}, Bin, Meta); parse(byte, Bin, Meta) -> parse({integer, byte, 0, 255}, Bin, Meta); parse(float, Duration, Meta) -> case string:to_float(Duration) of {Float, <<>>} -> Float; {error, no_float} -> parse(integer, Duration, Meta) * 1.0 end; parse({integer, Name, Lower, Upper}, Bin, _Meta) -> case string:to_integer(Bin) of {Int, <<>>} when Int >= Lower, Int =< Upper -> Int; _Other -> {invalid_type, Name, Bin} end; parse(array_dimensions, Dimensions, Meta) -> [parse(integer, D, Meta) || D <- binary:split(Dimensions, <<$,>>, [global])]. parse_data_type_definition(undefined, _Meta) -> undefined; parse_data_type_definition({_Tag, Attrs, Fields}, Meta) -> ParsedFields = [parse_data_type_definition_field(F, Meta) || F <- Fields], IsUnion = get_attr(<<"IsUnion">>, Attrs, boolean, Meta, false), IsOptionSet = get_attr(<<"IsOptionSet">>, Attrs, boolean, Meta, false), #{fields => ParsedFields, is_union => IsUnion, is_option_set => IsOptionSet}. parse_data_type_definition_field({<<"Field">>, Attrs, _Content}, Meta) -> {opcua_util:convert_name(maps:get(<<"Name">>, Attrs)), maps:from_list(lists:foldl( fun({Attr, Key, Type}, Result) -> try [{Key, get_attr(Attr, Attrs, Type, Meta)}|Result] catch error:{attr_not_found, Attr} -> Result end end, [], [ {<<"DataType">>, data_type, node_id}, {<<"Value">>, value, integer}, {<<"ValueRank">>, value_rank, integer}, {<<"IsOptional">>, is_optional, boolean} ] ))}. get_attr(Name, Attrs, Type, Meta) -> get_attr(Name, Attrs, Type, Meta, fun() -> error({attr_not_found, Name}) end). get_attr(Name, Attrs, Type, Meta, Default) -> case maps:find(Name, Attrs) of {ok, Value} -> parse(Type, Value, Meta); error when is_function(Default) -> Default(); error -> Default end. get_value(Keys, Content) -> get_value(Keys, Content, fun() -> error({value_not_found, Keys, Content}) end). get_value(Keys, Content, Default) -> case get_in(Keys, Content, Default) of {_Tag, _Attrs, Value} -> Value; Default -> Default end. get_in([K|Keys], [Tuple|_List], Default) when element(1, Tuple) =:= K -> get_in(Keys, Tuple, Default); get_in(Keys, [_Tuple|List], Default) -> get_in(Keys, List, Default); get_in([], Item, _Default) -> Item; get_in(_Keys, [], Default) when is_function(Default) -> Default(); get_in(_Keys, [], Default) -> Default. xml_to_simple(#xmlElement{} = E) -> { atom_to_binary(E#xmlElement.name, utf8), xml_attrs_to_map(E#xmlElement.attributes), xml_to_simple(E#xmlElement.content) }; xml_to_simple(Elements) when is_list(Elements) -> [S || E <- Elements, S <- [xml_to_simple(E)], S =/= <<" ">>]; xml_to_simple(#xmlText{value = Value}) -> iolist_to_binary(Value). xml_attrs_to_map(Attrs) -> maps:from_list([ {atom_to_binary(Name, utf8), iolist_to_binary(Value)} || #xmlAttribute{name = Name, value = Value} <- Attrs ]). extract_references(NodesProplist) -> [Ref || {_NodeId, {_Node, Refs}} <- NodesProplist, Ref <- Refs]. extract_nodes(NodesProplist) -> [Node || {_NodeId, {Node, _Refs}} <- NodesProplist]. extract_data_type_schemas(NodesProplist) -> DataTypeNodesProplist = lists:filter(fun({_, {Node, _}}) -> is_record(Node#opcua_node.node_class, opcua_data_type) end, NodesProplist), opcua_nodeset_datatypes:generate_schemas(DataTypeNodesProplist). extract_encodings(NodesProplist) -> [{TargetNodeId, {SourceNodeId, binary}} || {_NodeId, { #opcua_node{browse_name = <<"Default Binary">>}, References } } <- NodesProplist, #opcua_reference{ type_id = #opcua_node_id{value = 38}, source_id = SourceNodeId, target_id = TargetNodeId } <- References ]. write_terms(BaseDir, Desc, Tag, Terms) -> OutputPath = filename:join([BaseDir, "nodeset."++ Tag ++ ".bterm"]), ?LOG_INFO("Saving ~s into ~s ...", [Desc, OutputPath]), opcua_util_bterm:save(OutputPath, Terms).
7008b6a1a0497347b8db0d88787024384c4f2d1a42f5ee49d7b679f037daa6f1
josefs/Gradualizer
nonempty_list_match_in_head_nonexhaustive.erl
-module(nonempty_list_match_in_head_nonexhaustive). -export([f/1]). -type t() :: {} | [t()]. -spec f(t()) -> ok. f(_A = [_|_]) -> ok.
null
https://raw.githubusercontent.com/josefs/Gradualizer/3cda2e5aa1b1313b3e02fce67986fcda3ab9a02c/test/should_fail/nonempty_list_match_in_head_nonexhaustive.erl
erlang
-module(nonempty_list_match_in_head_nonexhaustive). -export([f/1]). -type t() :: {} | [t()]. -spec f(t()) -> ok. f(_A = [_|_]) -> ok.
f15d3b1b3837996f507e041fb746097dbe61e907bc17a9e696907959c6d78780
Rober-t/apxr_run
scape_test.erl
-module(scape_test). -include_lib("eunit/include/eunit.hrl"). %% runners scape_test_() -> {setup, fun setup/0, fun cleanup/1, [ fun scape_subtest/0 ]}. %% tests scape_subtest() -> % start utils:random_seed(), scape:start_link(1.0, 1.0, 50.0, 50.0, flatland), AgentIds = [{agent, rand:uniform() - 0.5} || _<- lists:seq(1, 125)], % enter [test_enter(AId) || AId <- AgentIds], timer:sleep(100), % sense [test_sense(AId) || AId <- AgentIds], % actuate [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), % sense [test_sense(AId) || AId <- AgentIds], % actuate [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), % sense [test_sense(AId) || AId <- AgentIds], % actuate [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), % sense [test_sense(AId) || AId <- AgentIds], % actuate [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), % sense [test_sense(AId) || AId <- AgentIds], % actuate [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), % query_area QueryResults = scape:query_area(1.0, 1.0, 50.0, 50.0), ?assert(is_list(QueryResults)), timer:sleep(100), % leave [test_leave(AId) || AId <- AgentIds]. %% helpers test_enter(AId) -> Morphologies = [predator, prey], Params = [ {lists:nth(rand:uniform(length(Morphologies)), Morphologies), [{sensor, {-1.0, rand:uniform() - 0.5}}], [{actuator, {1.0, rand:uniform() - 0.5}}] }], ?assertEqual(ok, scape:enter(AId, Params)). test_sense(AId) -> SensorPid = self(), Params = [], ?assertEqual(ok, scape:sense(AId, SensorPid, Params)). test_actuate(AId) -> ActuatorPid = self(), Function = two_wheels, Params = [(rand:uniform() + 2.0), (rand:uniform() + 2.0)], ?assertEqual(ok, scape:actuate(AId, ActuatorPid, Function, Params)). test_leave(AId) -> Params = [], ?assertEqual(ok, scape:leave(AId, Params)). setup() -> application:start(shards), shards:new(t1, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), shards:new(t2, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), shards:new(t3, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(scape_names_pids, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), {ok, SecPid} = sector_sup:start_link(), ets:new(ids_sids_loc, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(xy_pts, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(qt, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SecPid. cleanup(_SecPid) -> ok. % exit(SecPid, normal), % ets:delete(scape_names_pids), % ets:delete(ids_sids_loc), ets : delete(xy_pts ) , % ets:delete(qt), % application:stop(shards).
null
https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/test/scape_test.erl
erlang
runners tests start enter sense actuate sense actuate sense actuate sense actuate sense actuate query_area leave helpers exit(SecPid, normal), ets:delete(scape_names_pids), ets:delete(ids_sids_loc), ets:delete(qt), application:stop(shards).
-module(scape_test). -include_lib("eunit/include/eunit.hrl"). scape_test_() -> {setup, fun setup/0, fun cleanup/1, [ fun scape_subtest/0 ]}. scape_subtest() -> utils:random_seed(), scape:start_link(1.0, 1.0, 50.0, 50.0, flatland), AgentIds = [{agent, rand:uniform() - 0.5} || _<- lists:seq(1, 125)], [test_enter(AId) || AId <- AgentIds], timer:sleep(100), [test_sense(AId) || AId <- AgentIds], [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), [test_sense(AId) || AId <- AgentIds], [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), [test_sense(AId) || AId <- AgentIds], [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), [test_sense(AId) || AId <- AgentIds], [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), [test_sense(AId) || AId <- AgentIds], [test_actuate(AId) || AId <- AgentIds], timer:sleep(100), QueryResults = scape:query_area(1.0, 1.0, 50.0, 50.0), ?assert(is_list(QueryResults)), timer:sleep(100), [test_leave(AId) || AId <- AgentIds]. test_enter(AId) -> Morphologies = [predator, prey], Params = [ {lists:nth(rand:uniform(length(Morphologies)), Morphologies), [{sensor, {-1.0, rand:uniform() - 0.5}}], [{actuator, {1.0, rand:uniform() - 0.5}}] }], ?assertEqual(ok, scape:enter(AId, Params)). test_sense(AId) -> SensorPid = self(), Params = [], ?assertEqual(ok, scape:sense(AId, SensorPid, Params)). test_actuate(AId) -> ActuatorPid = self(), Function = two_wheels, Params = [(rand:uniform() + 2.0), (rand:uniform() + 2.0)], ?assertEqual(ok, scape:actuate(AId, ActuatorPid, Function, Params)). test_leave(AId) -> Params = [], ?assertEqual(ok, scape:leave(AId, Params)). setup() -> application:start(shards), shards:new(t1, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), shards:new(t2, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), shards:new(t3, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(scape_names_pids, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), {ok, SecPid} = sector_sup:start_link(), ets:new(ids_sids_loc, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(xy_pts, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), ets:new(qt, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SecPid. cleanup(_SecPid) -> ok. ets : delete(xy_pts ) ,
58d2b98ad9f2c8c37227280737e336c2507333cc76d80b5efbabfe2fff3a6e3c
samply/blaze
spec.clj
(ns blaze.db.kv.rocksdb.impl.spec (:require [clojure.spec.alpha :as s]) (:import [org.rocksdb ColumnFamilyHandle WriteBatchInterface])) (s/def :blaze.db.kv.rocksdb.impl/column-family-handle #(instance? ColumnFamilyHandle %)) (s/def :blaze.db.kv.rocksdb.impl/write-batch #(instance? WriteBatchInterface %))
null
https://raw.githubusercontent.com/samply/blaze/281ca0f35c845ed6e7b7f37fe2d4b9a060b065ca/modules/rocksdb/test/blaze/db/kv/rocksdb/impl/spec.clj
clojure
(ns blaze.db.kv.rocksdb.impl.spec (:require [clojure.spec.alpha :as s]) (:import [org.rocksdb ColumnFamilyHandle WriteBatchInterface])) (s/def :blaze.db.kv.rocksdb.impl/column-family-handle #(instance? ColumnFamilyHandle %)) (s/def :blaze.db.kv.rocksdb.impl/write-batch #(instance? WriteBatchInterface %))
480476f82cd0753a0181e129732a9f2547f2e7fdf9a0e38dcb8ada9d835c6416
ComputerScienceHouse/csh-eval
Members.hs
Module : CSH.Eval . Frontend . Members Description : The route handler for the members page Copyright : , , , Computer Science House 2015 License : MIT Maintainer : Stability : Provisional Portability : POSIX DOCUMENT THIS ! Module : CSH.Eval.Frontend.Members Description : The route handler for the members page Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015 License : MIT Maintainer : Stability : Provisional Portability : POSIX DOCUMENT THIS! -} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} # LANGUAGE TemplateHaskell # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE FlexibleContexts # {-# LANGUAGE ViewPatterns #-} module CSH.Eval.Frontend.Members ( getMembersR , getMemberR ) where import qualified Data.ByteString.Char8 as B import CSH.Eval.Cacheable.Fetch import CSH.Eval.Model import CSH.Eval.Frontend.Data import qualified Data.Text as T import System.Log.Logger import Yesod import Network.HTTP.Types -- | The handler for the members listing page getMembersR :: Handler Html getMembersR = defaultLayout $(whamletFile "frontend/templates/members/index.hamlet") dummyMembers :: [(String, String, Int, Bool, Bool)] dummyMembers = take 100 . cycle $ [("harlan", "Harlan Haskins", 4, True, True) ,("dag10", "Drew Gottlieb", 4, True, False) ,("tmobile", "Travis Whitaker", 8, True, False) ] charFor :: Bool -> T.Text charFor True = "✅" charFor False = "❌" -- | The handler for a single member's page getMemberR :: String -> Handler Html getMemberR username = do y <- getYesod let cache = getCache y let logger = getFrontendLogger y eitherUsr <- execCacheable cache (getMemberUsername (T.pack username)) let attendance = [("Evals", "Committee", "10/13/2015"), ("Financial", "Committee", "10/13/2015")] case eitherUsr of (Left _) -> sendResponseStatus internalServerError500 ("Could not find " ++ username) (Right usr) -> defaultLayout $(whamletFile "frontend/templates/index.hamlet") widgetEval :: Evaluation -> Widget widgetEval eval = do y <- getYesod $(whamletFile "frontend/templates/member/widgets/evaluation.hamlet")
null
https://raw.githubusercontent.com/ComputerScienceHouse/csh-eval/d2d4bac07bfbfcdb58aa01694d422f326bd3d414/src/CSH/Eval/Frontend/Members.hs
haskell
# LANGUAGE QuasiQuotes # # LANGUAGE TypeFamilies # # LANGUAGE OverloadedStrings # # LANGUAGE ViewPatterns # | The handler for the members listing page | The handler for a single member's page
Module : CSH.Eval . Frontend . Members Description : The route handler for the members page Copyright : , , , Computer Science House 2015 License : MIT Maintainer : Stability : Provisional Portability : POSIX DOCUMENT THIS ! Module : CSH.Eval.Frontend.Members Description : The route handler for the members page Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015 License : MIT Maintainer : Stability : Provisional Portability : POSIX DOCUMENT THIS! -} # LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # module CSH.Eval.Frontend.Members ( getMembersR , getMemberR ) where import qualified Data.ByteString.Char8 as B import CSH.Eval.Cacheable.Fetch import CSH.Eval.Model import CSH.Eval.Frontend.Data import qualified Data.Text as T import System.Log.Logger import Yesod import Network.HTTP.Types getMembersR :: Handler Html getMembersR = defaultLayout $(whamletFile "frontend/templates/members/index.hamlet") dummyMembers :: [(String, String, Int, Bool, Bool)] dummyMembers = take 100 . cycle $ [("harlan", "Harlan Haskins", 4, True, True) ,("dag10", "Drew Gottlieb", 4, True, False) ,("tmobile", "Travis Whitaker", 8, True, False) ] charFor :: Bool -> T.Text charFor True = "✅" charFor False = "❌" getMemberR :: String -> Handler Html getMemberR username = do y <- getYesod let cache = getCache y let logger = getFrontendLogger y eitherUsr <- execCacheable cache (getMemberUsername (T.pack username)) let attendance = [("Evals", "Committee", "10/13/2015"), ("Financial", "Committee", "10/13/2015")] case eitherUsr of (Left _) -> sendResponseStatus internalServerError500 ("Could not find " ++ username) (Right usr) -> defaultLayout $(whamletFile "frontend/templates/index.hamlet") widgetEval :: Evaluation -> Widget widgetEval eval = do y <- getYesod $(whamletFile "frontend/templates/member/widgets/evaluation.hamlet")
f2ee58e72b43c43cdf8e7552b99de3c4e1defff54c15a82b97c4c9b80fb0cd10
untangled-web/untangled-client
routing.cljs
(ns untangled.client.routing (:require-macros untangled.client.routing) (:require [untangled.client.mutations :as m] untangled.client.core om.next om.dom [untangled.client.logging :as log])) (def routing-tree-key ::routing-tree) (def routers-table :untangled.client.routing.routers/by-id) ; NOTE: needed in macro, but hand-coded (defn make-route "Make a route name that executes the provided routing instructions to change which screen in on the UI. routing-instructions must be a vector. Returns an item that can be passed to `routing-tree` to generate your overall application's routing plan. `(make-route :route/a [(router-instruction ...) ...])` " [name routing-instructions] {:pre [(vector? routing-instructions)]} {:name name :instructions routing-instructions}) (defn routing-tree "Generate initial state for your application's routing tree. The return value of this should be merged into your overall app state in your Root UI component ``` (defui Root static uc/InitialAppState (initial-state [cls params] (merge {:child-key (uc/get-initial-state Child)} (routing-tree (make-route :route/a [(router-instruction ...)]) ...))) ... ``` " [& routes] {routing-tree-key (reduce (fn [tree {:keys [name instructions]}] (assoc tree name instructions)) {} routes)}) (defn router-instruction "Return the definition of a change-route instruction." [router-id target-screen-ident] {:target-router router-id :target-screen target-screen-ident}) (defn current-route "Get the current route from the router with the given id" [state-map router-id] (get-in state-map [routers-table router-id :current-route])) (defn- set-ident-route-params "Replace any keywords of the form :params/X with the value of (get route-params X)" [ident route-params] (mapv (fn [element] (if (and (keyword? element) (= "param" (namespace element))) (keyword (get route-params (keyword (name element)) element)) element)) ident)) (defn set-route "Set the given screen-ident as the current route on the router with the given ID. Returns a new application state map." [state-map router-id screen-ident] (assoc-in state-map [routers-table router-id :current-route] screen-ident)) (defn update-routing-links "Given the app state map, returns a new map that has the routing graph links updated for the given route/params as a bidi match." [state-map {:keys [handler route-params]}] (let [routing-instructions (get-in state-map [routing-tree-key handler])] (if-not (or (nil? routing-instructions) (vector? routing-instructions)) (log/error "Routing tree does not contain a vector of routing-instructions for handler " handler) (reduce (fn [m {:keys [target-router target-screen]}] (let [parameterized-screen-ident (set-ident-route-params target-screen route-params)] (set-route m target-router parameterized-screen-ident))) state-map routing-instructions)))) (defn route-to "Om Mutation (use in transact! only): Change the application's overall UI route to the given route by handler. Handler must be a single keyword that indicates an entry in your routing tree (which must be in the initial app state of your UI root). route-params is a map of key-value pairs that will be substituted in the target screen idents of the routing tree." [{:keys [handler route-params]}] (comment "placeholder for IDE assistance")) (defmethod m/mutate `route-to [{:keys [state]} k p] {:action (fn [] (swap! state update-routing-links p))})
null
https://raw.githubusercontent.com/untangled-web/untangled-client/d9b350db3a5e19910692ee70281d8c156fd3a3f9/src/untangled/client/routing.cljs
clojure
NOTE: needed in macro, but hand-coded
(ns untangled.client.routing (:require-macros untangled.client.routing) (:require [untangled.client.mutations :as m] untangled.client.core om.next om.dom [untangled.client.logging :as log])) (def routing-tree-key ::routing-tree) (defn make-route "Make a route name that executes the provided routing instructions to change which screen in on the UI. routing-instructions must be a vector. Returns an item that can be passed to `routing-tree` to generate your overall application's routing plan. `(make-route :route/a [(router-instruction ...) ...])` " [name routing-instructions] {:pre [(vector? routing-instructions)]} {:name name :instructions routing-instructions}) (defn routing-tree "Generate initial state for your application's routing tree. The return value of this should be merged into your overall app state in your Root UI component ``` (defui Root static uc/InitialAppState (initial-state [cls params] (merge {:child-key (uc/get-initial-state Child)} (routing-tree (make-route :route/a [(router-instruction ...)]) ...))) ... ``` " [& routes] {routing-tree-key (reduce (fn [tree {:keys [name instructions]}] (assoc tree name instructions)) {} routes)}) (defn router-instruction "Return the definition of a change-route instruction." [router-id target-screen-ident] {:target-router router-id :target-screen target-screen-ident}) (defn current-route "Get the current route from the router with the given id" [state-map router-id] (get-in state-map [routers-table router-id :current-route])) (defn- set-ident-route-params "Replace any keywords of the form :params/X with the value of (get route-params X)" [ident route-params] (mapv (fn [element] (if (and (keyword? element) (= "param" (namespace element))) (keyword (get route-params (keyword (name element)) element)) element)) ident)) (defn set-route "Set the given screen-ident as the current route on the router with the given ID. Returns a new application state map." [state-map router-id screen-ident] (assoc-in state-map [routers-table router-id :current-route] screen-ident)) (defn update-routing-links "Given the app state map, returns a new map that has the routing graph links updated for the given route/params as a bidi match." [state-map {:keys [handler route-params]}] (let [routing-instructions (get-in state-map [routing-tree-key handler])] (if-not (or (nil? routing-instructions) (vector? routing-instructions)) (log/error "Routing tree does not contain a vector of routing-instructions for handler " handler) (reduce (fn [m {:keys [target-router target-screen]}] (let [parameterized-screen-ident (set-ident-route-params target-screen route-params)] (set-route m target-router parameterized-screen-ident))) state-map routing-instructions)))) (defn route-to "Om Mutation (use in transact! only): Change the application's overall UI route to the given route by handler. Handler must be a single keyword that indicates an entry in your routing tree (which must be in the initial app state of your UI root). route-params is a map of key-value pairs that will be substituted in the target screen idents of the routing tree." [{:keys [handler route-params]}] (comment "placeholder for IDE assistance")) (defmethod m/mutate `route-to [{:keys [state]} k p] {:action (fn [] (swap! state update-routing-links p))})
b0280d9a1fcebd8177f358ef00bed6220066a3432630bdb8acbe23c6d6c1ea89
thma/PolysemyCleanArchitecture
InterfaceAdaptersKVSAcidStateSpec.hs
module InterfaceAdaptersKVSAcidStateSpec where import Control.Exception import Control.Monad.Cont (liftIO) import Data.Function ((&)) import Data . List ( isSuffixOf ) import qualified Data.Map.Strict as M import InterfaceAdapters.Config import InterfaceAdapters.KVSAcidState import Polysemy import Polysemy.Input (Input, runInputConst) import Polysemy.Trace import System.Directory (removeDirectoryRecursive) import Test.Hspec import UseCases.KVS import Control.Concurrent main :: IO () main = hspec spec -- Testing the KVS AcidState implementation -- | Takes a program with effects and handles each effect till it gets reduced to IO a. runAllEffects :: Sem '[KeyValueTable, Input Config, Trace, Embed IO] a -> IO a runAllEffects program = program use AcidState based interpretation of the ( KVS Int [ String ] ) effect & runInputConst config -- use the variable config as source for (Input Config) effect & ignoreTrace -- ignore all traces reduce Sem r ( Embed IO a ) to IO a where config = Config {port = 8080, dbPath = "kvs-test.db", backend = SQLite, verbose = False} errors are rethrown as Runtime errors , which can be verified by HSpec . handleErrors :: IO (Either err a) -> IO a handleErrors e = do eitherError <- e case eitherError of Right v -> return v Left _ -> error "something bad happend" | a key value table mapping Int to a list of type KeyValueTable = KVS Int [String] data Memo = Memo Int [String] deriving (Show) persistMemo :: (Member KeyValueTable r) => Memo -> Sem r () persistMemo (Memo k val ) = insertKvs k val fetchMemo :: (Member KeyValueTable r) => Int -> Sem r (Maybe [String]) fetchMemo = getKvs fetchAll :: (Member KeyValueTable r) => Sem r (M.Map Int [String]) fetchAll = fmap M.fromList listAllKvs deleteMemo :: (Member KeyValueTable r) => Int -> Sem r () deleteMemo = deleteKvs -- Helper functions for interpreting all effects in IO runPersist :: Memo -> IO () runPersist val = runAllEffects (persistMemo val) runFetch :: Int -> IO (Maybe [String]) runFetch k = runAllEffects (fetchMemo k) runFetchAll :: IO (M.Map Int [String]) runFetchAll = runAllEffects fetchAll runDelete :: Int -> IO () runDelete k = runAllEffects (deleteMemo k) key :: Int key = 4711 v :: [String] v = ["In the morning", "I don't drink coffee", "But lots of curcuma chai."] memo :: Memo memo = Memo key v -- | helper function to clean the test data files deleteAllFiles :: IO () deleteAllFiles = catch (removeDirectoryRecursive "_state") handler where handler :: SomeException -> IO () handler _ = return () spec :: Spec spec = do describe "The KV AcidState Implementation" $ do it "needs a file cleaning for repeatable tests in the file system..." $ do liftIO deleteAllFiles for some reason in the Windows POSIX implementation we need some -- time after deleting before we can create the directory anew again... so the 2nd call juis just eating up come CPU time . True `shouldBe` True it "returns Nothing if nothing can be found for a given id" $ do maybeMatch <- runFetch key maybeMatch `shouldBe` Nothing it "persists a key-value pair to the AcidState database" $ do runPersist memo maybeMatch <- runFetch key maybeMatch `shouldBe` Just v it "fetches a Map of all key-value entries from the KV store" $ do kvMap <- runFetchAll M.size kvMap `shouldBe` 1 -- it "deletes an entry from the key value store" $ do runPersist memo key -- --maybeMatch <- runFetch key --maybeMatch ` shouldBe ` Nothing
null
https://raw.githubusercontent.com/thma/PolysemyCleanArchitecture/beaf8b5a029707856cef7ff54ea03f2927f1021c/test/InterfaceAdaptersKVSAcidStateSpec.hs
haskell
Testing the KVS AcidState implementation | Takes a program with effects and handles each effect till it gets reduced to IO a. use the variable config as source for (Input Config) effect ignore all traces Helper functions for interpreting all effects in IO | helper function to clean the test data files time after deleting before we can create the directory anew again... it "deletes an entry from the key value store" $ do --maybeMatch <- runFetch key maybeMatch ` shouldBe ` Nothing
module InterfaceAdaptersKVSAcidStateSpec where import Control.Exception import Control.Monad.Cont (liftIO) import Data.Function ((&)) import Data . List ( isSuffixOf ) import qualified Data.Map.Strict as M import InterfaceAdapters.Config import InterfaceAdapters.KVSAcidState import Polysemy import Polysemy.Input (Input, runInputConst) import Polysemy.Trace import System.Directory (removeDirectoryRecursive) import Test.Hspec import UseCases.KVS import Control.Concurrent main :: IO () main = hspec spec runAllEffects :: Sem '[KeyValueTable, Input Config, Trace, Embed IO] a -> IO a runAllEffects program = program use AcidState based interpretation of the ( KVS Int [ String ] ) effect reduce Sem r ( Embed IO a ) to IO a where config = Config {port = 8080, dbPath = "kvs-test.db", backend = SQLite, verbose = False} errors are rethrown as Runtime errors , which can be verified by HSpec . handleErrors :: IO (Either err a) -> IO a handleErrors e = do eitherError <- e case eitherError of Right v -> return v Left _ -> error "something bad happend" | a key value table mapping Int to a list of type KeyValueTable = KVS Int [String] data Memo = Memo Int [String] deriving (Show) persistMemo :: (Member KeyValueTable r) => Memo -> Sem r () persistMemo (Memo k val ) = insertKvs k val fetchMemo :: (Member KeyValueTable r) => Int -> Sem r (Maybe [String]) fetchMemo = getKvs fetchAll :: (Member KeyValueTable r) => Sem r (M.Map Int [String]) fetchAll = fmap M.fromList listAllKvs deleteMemo :: (Member KeyValueTable r) => Int -> Sem r () deleteMemo = deleteKvs runPersist :: Memo -> IO () runPersist val = runAllEffects (persistMemo val) runFetch :: Int -> IO (Maybe [String]) runFetch k = runAllEffects (fetchMemo k) runFetchAll :: IO (M.Map Int [String]) runFetchAll = runAllEffects fetchAll runDelete :: Int -> IO () runDelete k = runAllEffects (deleteMemo k) key :: Int key = 4711 v :: [String] v = ["In the morning", "I don't drink coffee", "But lots of curcuma chai."] memo :: Memo memo = Memo key v deleteAllFiles :: IO () deleteAllFiles = catch (removeDirectoryRecursive "_state") handler where handler :: SomeException -> IO () handler _ = return () spec :: Spec spec = do describe "The KV AcidState Implementation" $ do it "needs a file cleaning for repeatable tests in the file system..." $ do liftIO deleteAllFiles for some reason in the Windows POSIX implementation we need some so the 2nd call juis just eating up come CPU time . True `shouldBe` True it "returns Nothing if nothing can be found for a given id" $ do maybeMatch <- runFetch key maybeMatch `shouldBe` Nothing it "persists a key-value pair to the AcidState database" $ do runPersist memo maybeMatch <- runFetch key maybeMatch `shouldBe` Just v it "fetches a Map of all key-value entries from the KV store" $ do kvMap <- runFetchAll M.size kvMap `shouldBe` 1 runPersist memo key
87bd7a6bf1e467804cfca831a35c4a582915e58158a834aa7df2d5df93a59273
FlowForwarding/loom
icontrol_app.erl
-module(icontrol_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> icontrol_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/FlowForwarding/loom/86a9c5aa8b7d4776062365716c9a3dbbf3330bc5/icontrol/apps/icontrol/src/icontrol_app.erl
erlang
Application callbacks =================================================================== Application callbacks ===================================================================
-module(icontrol_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> icontrol_sup:start_link(). stop(_State) -> ok.
73506d316678f3fd3accaf7ebdbbd99a7e48c3be38e09951726d92764eb07ffa
ddssff/cabal-debian
DiffOutput.hs
----------------------------------------------------------------------------- -- | Module : Data . Algorithm . Copyright : ( c ) 2008 - 2011 , 2011 License : BSD 3 Clause -- Maintainer : -- Stability : experimental -- Portability : portable Author : ( ) and JP Moresmau ( ) -- -- Generates a string output that is similar to diff normal mode ----------------------------------------------------------------------------- module Data.Algorithm.DiffOutput where import Data.Algorithm.Diff import Text.PrettyPrint import Data.Char import Data.List import Data.Monoid (mappend) | Converts Diffs to DiffOperations diffToLineRanges :: [Diff [String]] -> [DiffOperation LineRange] diffToLineRanges = toLineRange 1 1 where toLineRange :: Int -> Int -> [Diff [String]] -> [DiffOperation LineRange] toLineRange _ _ []=[] toLineRange leftLine rightLine (Both ls _:rs)= let lins=length ls in toLineRange (leftLine+lins) (rightLine+lins) rs toLineRange leftLine rightLine (Second lsS:First lsF:rs)= toChange leftLine rightLine lsF lsS rs toLineRange leftLine rightLine (First lsF:Second lsS:rs)= toChange leftLine rightLine lsF lsS rs toLineRange leftLine rightLine (Second lsS:rs)= let linesS=length lsS diff=Addition (LineRange (rightLine,rightLine+linesS-1) lsS) (leftLine-1) in diff : toLineRange leftLine (rightLine+linesS) rs toLineRange leftLine rightLine (First lsF:rs)= let linesF=length lsF diff=Deletion (LineRange (leftLine,leftLine+linesF-1) lsF) (rightLine-1) in diff: toLineRange(leftLine+linesF) rightLine rs toChange leftLine rightLine lsF lsS rs= let linesS=length lsS linesF=length lsF in Change (LineRange (leftLine,leftLine+linesF-1) lsF) (LineRange (rightLine,rightLine+linesS-1) lsS) : toLineRange (leftLine+linesF) (rightLine+linesS) rs -- | pretty print the differences. The output is similar to the output of the diff utility ppDiff :: [Diff [String]] -> String ppDiff gdiff = let diffLineRanges = diffToLineRanges gdiff in render (prettyDiffs diffLineRanges) ++ "\n" -- | pretty print of diff operations prettyDiffs :: [DiffOperation LineRange] -> Doc prettyDiffs [] = empty prettyDiffs (d : rest) = prettyDiff d $$ prettyDiffs rest where prettyDiff (Deletion inLeft lineNoRight) = prettyRange (lrNumbers inLeft) `mappend` char 'd' `mappend` int lineNoRight $$ prettyLines '<' (lrContents inLeft) prettyDiff (Addition inRight lineNoLeft) = int lineNoLeft `mappend` char 'a' `mappend` prettyRange (lrNumbers inRight) $$ prettyLines '>' (lrContents inRight) prettyDiff (Change inLeft inRight) = prettyRange (lrNumbers inLeft) `mappend` char 'c' `mappend` prettyRange (lrNumbers inRight) $$ prettyLines '<' (lrContents inLeft) $$ text "---" $$ prettyLines '>' (lrContents inRight) prettyRange (start, end) = if start == end then int start else int start `mappend` comma `mappend` int end prettyLines start lins = vcat (map (\l -> char start <+> text l) lins) | Parse pretty printed Diffs as DiffOperations parsePrettyDiffs :: String -> [DiffOperation LineRange] parsePrettyDiffs = reverse . doParse [] . lines where doParse diffs [] = diffs doParse diffs s = let (mnd,r) = parseDiff s in case mnd of Just nd -> doParse (nd:diffs) r _ -> doParse diffs r parseDiff [] = (Nothing,[]) parseDiff (h:rs) = let (r1,hrs1) = parseRange h in case hrs1 of ('d':hrs2) -> parseDel r1 hrs2 rs ('a':hrs2) -> parseAdd r1 hrs2 rs ('c':hrs2) -> parseChange r1 hrs2 rs _ -> (Nothing,rs) parseDel r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls,rs2) = span (isPrefixOf "<") rs in (Just $ Deletion (LineRange r1 (map (drop 2) ls)) (fst r2), rs2) parseAdd r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls,rs2) = span (isPrefixOf ">") rs in (Just $ Addition (LineRange r2 (map (drop 2) ls)) (fst r1), rs2) parseChange r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls1,rs2) = span (isPrefixOf "<") rs in case rs2 of ("---":rs3) -> let (ls2,rs4) = span (isPrefixOf ">") rs3 in (Just $ Change (LineRange r1 (map (drop 2) ls1)) (LineRange r2 (map (drop 2) ls2)), rs4) _ -> (Nothing,rs2) parseRange :: String -> ((LineNo, LineNo),String) parseRange l = let (fstLine,rs) = span isDigit l (sndLine,rs3) = case rs of (',':rs2) -> span isDigit rs2 _ -> (fstLine,rs) in ((read fstLine,read sndLine),rs3) -- | Line number alias type LineNo = Int -- | Line Range: start, end and contents data LineRange = LineRange { lrNumbers :: (LineNo, LineNo) , lrContents :: [String] } deriving (Show,Read,Eq,Ord) -- | Diff Operation representing changes to apply data DiffOperation a = Deletion a LineNo | Addition a LineNo | Change a a deriving (Show,Read,Eq,Ord)
null
https://raw.githubusercontent.com/ddssff/cabal-debian/763270aed987f870762e660f243451e9a34e1325/test-data/diff/input/src/Data/Algorithm/DiffOutput.hs
haskell
--------------------------------------------------------------------------- | Maintainer : Stability : experimental Portability : portable Generates a string output that is similar to diff normal mode --------------------------------------------------------------------------- | pretty print the differences. The output is similar to the output of the diff utility | pretty print of diff operations | Line number alias | Line Range: start, end and contents | Diff Operation representing changes to apply
Module : Data . Algorithm . Copyright : ( c ) 2008 - 2011 , 2011 License : BSD 3 Clause Author : ( ) and JP Moresmau ( ) module Data.Algorithm.DiffOutput where import Data.Algorithm.Diff import Text.PrettyPrint import Data.Char import Data.List import Data.Monoid (mappend) | Converts Diffs to DiffOperations diffToLineRanges :: [Diff [String]] -> [DiffOperation LineRange] diffToLineRanges = toLineRange 1 1 where toLineRange :: Int -> Int -> [Diff [String]] -> [DiffOperation LineRange] toLineRange _ _ []=[] toLineRange leftLine rightLine (Both ls _:rs)= let lins=length ls in toLineRange (leftLine+lins) (rightLine+lins) rs toLineRange leftLine rightLine (Second lsS:First lsF:rs)= toChange leftLine rightLine lsF lsS rs toLineRange leftLine rightLine (First lsF:Second lsS:rs)= toChange leftLine rightLine lsF lsS rs toLineRange leftLine rightLine (Second lsS:rs)= let linesS=length lsS diff=Addition (LineRange (rightLine,rightLine+linesS-1) lsS) (leftLine-1) in diff : toLineRange leftLine (rightLine+linesS) rs toLineRange leftLine rightLine (First lsF:rs)= let linesF=length lsF diff=Deletion (LineRange (leftLine,leftLine+linesF-1) lsF) (rightLine-1) in diff: toLineRange(leftLine+linesF) rightLine rs toChange leftLine rightLine lsF lsS rs= let linesS=length lsS linesF=length lsF in Change (LineRange (leftLine,leftLine+linesF-1) lsF) (LineRange (rightLine,rightLine+linesS-1) lsS) : toLineRange (leftLine+linesF) (rightLine+linesS) rs ppDiff :: [Diff [String]] -> String ppDiff gdiff = let diffLineRanges = diffToLineRanges gdiff in render (prettyDiffs diffLineRanges) ++ "\n" prettyDiffs :: [DiffOperation LineRange] -> Doc prettyDiffs [] = empty prettyDiffs (d : rest) = prettyDiff d $$ prettyDiffs rest where prettyDiff (Deletion inLeft lineNoRight) = prettyRange (lrNumbers inLeft) `mappend` char 'd' `mappend` int lineNoRight $$ prettyLines '<' (lrContents inLeft) prettyDiff (Addition inRight lineNoLeft) = int lineNoLeft `mappend` char 'a' `mappend` prettyRange (lrNumbers inRight) $$ prettyLines '>' (lrContents inRight) prettyDiff (Change inLeft inRight) = prettyRange (lrNumbers inLeft) `mappend` char 'c' `mappend` prettyRange (lrNumbers inRight) $$ prettyLines '<' (lrContents inLeft) $$ text "---" $$ prettyLines '>' (lrContents inRight) prettyRange (start, end) = if start == end then int start else int start `mappend` comma `mappend` int end prettyLines start lins = vcat (map (\l -> char start <+> text l) lins) | Parse pretty printed Diffs as DiffOperations parsePrettyDiffs :: String -> [DiffOperation LineRange] parsePrettyDiffs = reverse . doParse [] . lines where doParse diffs [] = diffs doParse diffs s = let (mnd,r) = parseDiff s in case mnd of Just nd -> doParse (nd:diffs) r _ -> doParse diffs r parseDiff [] = (Nothing,[]) parseDiff (h:rs) = let (r1,hrs1) = parseRange h in case hrs1 of ('d':hrs2) -> parseDel r1 hrs2 rs ('a':hrs2) -> parseAdd r1 hrs2 rs ('c':hrs2) -> parseChange r1 hrs2 rs _ -> (Nothing,rs) parseDel r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls,rs2) = span (isPrefixOf "<") rs in (Just $ Deletion (LineRange r1 (map (drop 2) ls)) (fst r2), rs2) parseAdd r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls,rs2) = span (isPrefixOf ">") rs in (Just $ Addition (LineRange r2 (map (drop 2) ls)) (fst r1), rs2) parseChange r1 hrs2 rs = let (r2,_) = parseRange hrs2 (ls1,rs2) = span (isPrefixOf "<") rs in case rs2 of ("---":rs3) -> let (ls2,rs4) = span (isPrefixOf ">") rs3 in (Just $ Change (LineRange r1 (map (drop 2) ls1)) (LineRange r2 (map (drop 2) ls2)), rs4) _ -> (Nothing,rs2) parseRange :: String -> ((LineNo, LineNo),String) parseRange l = let (fstLine,rs) = span isDigit l (sndLine,rs3) = case rs of (',':rs2) -> span isDigit rs2 _ -> (fstLine,rs) in ((read fstLine,read sndLine),rs3) type LineNo = Int data LineRange = LineRange { lrNumbers :: (LineNo, LineNo) , lrContents :: [String] } deriving (Show,Read,Eq,Ord) data DiffOperation a = Deletion a LineNo | Addition a LineNo | Change a a deriving (Show,Read,Eq,Ord)
7396099e4c89ac831f67e5430820228a99a11cb030cd8daf96d5cdc1118a6204
deadtrickster/prometheus.cl
package.lisp
(in-package #:cl-user) (defpackage #:prometheus.test.support (:use #:cl #:alexandria #:prove) (:export #:error-class-exists #:is-error-report #:error-report-test #:with-fresh-registry))
null
https://raw.githubusercontent.com/deadtrickster/prometheus.cl/60572b793135e8ab5a857d47cc1a5fe0af3a2d53/t/support/package.lisp
lisp
(in-package #:cl-user) (defpackage #:prometheus.test.support (:use #:cl #:alexandria #:prove) (:export #:error-class-exists #:is-error-report #:error-report-test #:with-fresh-registry))
3dbd35017af6e6a9b3bbacdc7b213fbb21e9a11bf4b9e62793d24d7b977314f0
lvh/caesium
binding.clj
(ns caesium.binding "**DANGER** These are the low-level bindings to libsodium, using jnr-ffi. They are probably not what you want; instead, please look at the [[caesium.crypto.box]], [[caesium.crypto.secretbox]], [[caesium.crypto.generichash]], [[caesium.crypto.sign]] et cetera, namespaces." (:require [clojure.string :as s] [clojure.math.combinatorics :as c] [medley.core :as m] [clojure.string :as str]) (:import [jnr.ffi LibraryLoader LibraryOption] [jnr.ffi.annotations In Out Pinned LongLong] [jnr.ffi.types size_t])) (def ^:private bound-byte-type-syms '[bytes java.nio.ByteBuffer]) (defn ^:private permuted-byte-types "Given a method signature, return signatures for all bound byte types. Signature should be as per [[bound-fns]], with byte arguments annotated with `{:tag 'bytes}` in their metadata (note: the symbol, not the fn)." [[name args]] (let [byte-args (filter (comp #{'bytes} :tag meta) args)] (for [types (c/selections bound-byte-type-syms (count byte-args)) :let [arg->type (zipmap byte-args types) ann (fn [arg] (let [tag (get arg->type arg (:tag (meta arg)))] (vary-meta arg assoc :tag tag)))]] [name (mapv ann args)]))) (def ^:private raw-bound-fns "See [[bound-fns]], but without the permutations." '[[^int sodium_init []] [^String sodium_version_string []] [^void randombytes [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen]] [^long ^{size_t {}} crypto_secretbox_keybytes []] [^long ^{size_t {}} crypto_secretbox_noncebytes []] [^long ^{size_t {}} crypto_secretbox_macbytes []] [^String crypto_secretbox_primitive []] [^int crypto_secretbox_easy [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_open_easy [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_open_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_box_seedbytes []] [^long ^{size_t {}} crypto_box_publickeybytes []] [^long ^{size_t {}} crypto_box_secretkeybytes []] [^long ^{size_t {}} crypto_box_noncebytes []] [^long ^{size_t {}} crypto_box_macbytes []] [^long ^{size_t {}} crypto_box_sealbytes []] [^String ^{size_t {}} crypto_box_primitive []] [^int crypto_box_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_box_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_easy [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_open_easy [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_seal [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} pk]] [^int crypto_box_seal_open [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_open_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^long ^{size_t {}} crypto_shorthash_bytes] [^long ^{size_t {}} crypto_shorthash_keybytes] [^String crypto_shorthash_primitive []] [^int crypto_shorthash [^bytes ^{Pinned {}} out ^bytes ^{Pinned {}} in ^long ^{LongLong {}} inlen ^bytes ^{Pinned {}} k]] [^void crypto_shorthash_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_sign_bytes []] [^long ^{size_t {}} crypto_sign_seedbytes []] [^long ^{size_t {}} crypto_sign_publickeybytes []] [^long ^{size_t {}} crypto_sign_secretkeybytes []] [^String crypto_sign_primitive []] [^int crypto_sign_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_sign_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_sign [^bytes ^{Pinned {}} sm ^jnr.ffi.byref.LongLongByReference smlen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} sk]] [^int crypto_sign_open [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} sm ^long ^{LongLong {}} smlen ^bytes ^{Pinned {}} pk]] [^int crypto_sign_detached [^bytes ^{Pinned {}} sig ^jnr.ffi.byref.LongLongByReference siglen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} sk]] [^int crypto_sign_verify_detached [^bytes ^{Pinned {}} sig ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} pk]] [^long ^{size_t {}} crypto_generichash_bytes_min []] [^long ^{size_t {}} crypto_generichash_bytes_max []] [^long ^{size_t {}} crypto_generichash_bytes []] [^long ^{size_t {}} crypto_generichash_keybytes_min []] [^long ^{size_t {}} crypto_generichash_keybytes_max []] [^long ^{size_t {}} crypto_generichash_keybytes []] [^String crypto_generichash_primitive []] [^int crypto_generichash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen]] [^long ^{size_t {}} crypto_generichash_blake2b_bytes_min []] [^long ^{size_t {}} crypto_generichash_blake2b_bytes_max []] [^long ^{size_t {}} crypto_generichash_blake2b_bytes []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes_min []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes_max []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes []] [^long ^{size_t {}} crypto_generichash_blake2b_saltbytes []] [^long ^{size_t {}} crypto_generichash_blake2b_personalbytes []] [^long ^{size_t {}} crypto_generichash_blake2b_statebytes []] [^int crypto_generichash_blake2b [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen]] [^int crypto_generichash_blake2b_salt_personal [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen ^bytes ^{Pinned {}} salt ^bytes ^{Pinned {}} personal]] [^int crypto_pwhash_alg_argon2i13 []] [^int crypto_pwhash_alg_argon2id13 []] [^int crypto_pwhash_alg_default []] [^long ^{size_t {}} crypto_pwhash_bytes_min []] [^long ^{size_t {}} crypto_pwhash_bytes_max []] [^long ^{size_t {}} crypto_pwhash_passwd_min []] [^long ^{size_t {}} crypto_pwhash_passwd_max []] [^long ^{size_t {}} crypto_pwhash_saltbytes []] [^long ^{size_t {}} crypto_pwhash_strbytes []] [^String crypto_pwhash_strprefix []] [^long ^{size_t {}} crypto_pwhash_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_memlimit_sensitive []] [^String crypto_pwhash_primitive []] [^int crypto_pwhash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_str_alg [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2i_alg_argon2i13 []] [^long ^{size_t {}} crypto_pwhash_argon2i_bytes_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_bytes_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_passwd_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_passwd_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_saltbytes []] [^long ^{size_t {}} crypto_pwhash_argon2i_strbytes []] [^String crypto_pwhash_argon2i_strprefix []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_sensitive []] [^int crypto_pwhash_argon2i [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_argon2i_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2i_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_argon2i_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2id_alg_argon2id13 []] [^long ^{size_t {}} crypto_pwhash_argon2id_bytes_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_bytes_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_passwd_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_passwd_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_saltbytes []] [^long ^{size_t {}} crypto_pwhash_argon2id_strbytes []] [^String crypto_pwhash_argon2id_strprefix []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_sensitive []] [^int crypto_pwhash_argon2id [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_argon2id_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2id_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_argon2id_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_bytes_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_bytes_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_passwd_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_passwd_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_saltbytes []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_strbytes []] [^String crypto_pwhash_scryptsalsa208sha256_strprefix []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive []] [^int crypto_pwhash_scryptsalsa208sha256 [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_scryptsalsa208sha256_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_scryptsalsa208sha256_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_scryptsalsa208sha256_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^long ^{size_t {}} crypto_hash_sha256_bytes []] [^int crypto_hash_sha256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^long ^{size_t {}} crypto_hash_sha512_bytes []] [^int crypto_hash_sha512 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^long ^{size_t {}} crypto_auth_hmacsha256_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha256_keybytes []] [^int crypto_auth_hmacsha256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_auth_hmacsha512_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha512_keybytes []] [^int crypto_auth_hmacsha512 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_auth_hmacsha512256_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha512256_keybytes []] [^int crypto_auth_hmacsha512256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_scalarmult_bytes []] [^long ^{size_t {}} crypto_scalarmult_scalarbytes []] [^String crypto_scalarmult_primitive []] [^int crypto_scalarmult_base [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n]] [^int crypto_scalarmult [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} p]] [^long ^{size_t {}} crypto_scalarmult_ristretto255_bytes []] [^long ^{size_t {}} crypto_scalarmult_ristretto255_scalarbytes []] [^int crypto_scalarmult_ristretto255_base [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n]] [^int crypto_scalarmult_ristretto255 [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} p]] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_keybytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_nsecbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_npubbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_abytes []] [^int crypto_aead_chacha20poly1305_ietf_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_aead_chacha20poly1305_keybytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_nsecbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_npubbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_abytes []] [^int crypto_aead_chacha20poly1305_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_keybytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_nsecbytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_npubbytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_abytes []] [^int crypto_aead_xchacha20poly1305_ietf_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_kx_publickeybytes []] [^long ^{size_t {}} crypto_kx_secretkeybytes []] [^long ^{size_t {}} crypto_kx_seedbytes []] [^long ^{size_t {}} crypto_kx_sessionkeybytes []] [^String crypto_kx_primitive []] [^int crypto_kx_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_kx_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_kx_client_session_keys [^bytes ^{Pinned {}} rx ^bytes ^{Pinned {}} tx ^bytes ^{Pinned {}} client_pk ^bytes ^{Pinned {}} client_sk ^bytes ^{Pinned {}} server_pk]] [^int crypto_kx_server_session_keys [^bytes ^{Pinned {}} rx ^bytes ^{Pinned {}} tx ^bytes ^{Pinned {}} server_pk ^bytes ^{Pinned {}} server_sk ^bytes ^{Pinned {}} client_pk]] [^long ^{size_t {}} crypto_kdf_bytes_min] [^long ^{size_t {}} crypto_kdf_bytes_max] [^long ^{size_t {}} crypto_kdf_contextbytes] [^long ^{size_t {}} crypto_kdf_keybytes] [^String crypto_kdf_primitive []] [^void crypto_kdf_keygen [^bytes ^{Pinned {}} k]] [^int crypto_kdf_derive_from_key [^bytes ^{Pinned {}} subk ^long ^{LongLong {}} subklen ^long ^{LongLong {}} subkid ^bytes ^{Pinned {}} ctx ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_core_ristretto255_bytes []] [^long ^{size_t {}} crypto_core_ristretto255_hashbytes []] [^long ^{size_t {}} crypto_core_ristretto255_scalarbytes []] [^long ^{size_t {}} crypto_core_ristretto255_nonreducedscalarbytes []] [^int crypto_core_ristretto255_is_valid_point [^bytes ^{Pinned {}} p]] [^int crypto_core_ristretto255_add [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} q]] [^int crypto_core_ristretto255_sub [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} q]] [^int crypto_core_ristretto255_from_hash [^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} r]] [^void crypto_core_ristretto255_random [^bytes ^{Pinned {}} p]] [^void crypto_core_ristretto255_scalar_random [^bytes ^{Pinned {}} r]] [^int crypto_core_ristretto255_scalar_invert [^bytes ^{Pinned {}} recip ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_negate [^bytes ^{Pinned {}} neg ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_complement [^bytes ^{Pinned {}} result ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_add [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_sub [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_mul [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_reduce [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} s]] [^int crypto_core_ristretto255_scalar_is_canonical [^bytes ^{Pinned {}} s]]]) (def ^:private bound-fns "A mapping of type- and jnr.ffi-annotated bound method symbols to respective argspec. This exists so that tooling (like magic macro helpers) can easily inspect caesium allegedly binds. That can be done by reflecting on the interface too, but that's significantly less convenient; Clojure's reflection tools don't show annotations, and we always use the data in metadata-annotated form anyway (both to create the interface and to bind fns to vars). This has to be a seq and not a map, because the same key (symbol, method name) might occur with multiple values (e.g. when binding the same char* fn with different JVM byte types)." (mapcat permuted-byte-types raw-bound-fns)) (defmacro ^:private defsodium [] `(definterface ~'Sodium ~@bound-fns)) (defsodium) (defn ^:private load-sodium "Load native libsodium library." ([] (load-sodium "sodium")) ([lib] (try (-> (LibraryLoader/create Sodium) (.failImmediately) (.load lib)) (catch Exception e (throw (ClassNotFoundException. "unable to load native libsodium; is it installed?" e)))))) (def ^Sodium sodium "The sodium library singleton instance." (load-sodium)) (assert (#{0 1} (.sodium_init sodium))) (defn ^:private c-name "Resolves the fn name in the current ns to the fn name in the equivalent libsodium C pseudo-namespace. This understands problems like e.g. generichash in the generichash namespace meaning crypto_generichash, not the (nonexistant) crypto_generichash_generichash." [^clojure.lang.Namespace namespace ^clojure.lang.Symbol fn-name] (let [fn-name (s/replace (name fn-name) "-" "_") fn-name-parts (set (str/split fn-name #"_")) prefix (-> namespace ns-name str (s/split #"\.") rest vec) path (concat (remove fn-name-parts prefix) [fn-name])] (symbol (s/join "_" path)))) (defn ^:private java-call-sym "Creates the Clojure Java method call syntax to call a method on the libsodium binding." [c-name] (symbol (str "." c-name))) (defmacro defconsts "Define a number of constants by name. Uses the *ns* to figure out the const-returning fn in libsodium." [consts] `(do ~@(for [const consts :let [c-name (c-name *ns* const) docstring (str "Constant returned by `" c-name "`. " "See libsodium docs.")]] `(def ~(with-meta const {:const true}) ~docstring (~(java-call-sym c-name) sodium))))) (defmacro call! "Produces a form for calling named fn with lots of magic: * The fn-name is specified using its short name, which is resolved against the ns as per [[defconsts]]. * All bufs are annotated as ByteBuffers. * Buffer lengths are automatically added." [fn-name & args] (let [c-name (c-name *ns* fn-name) [_ c-args] (m/find-first (comp #{c-name} first) raw-bound-fns) normalize-tag (fn [k] (get {'bytes 'java.nio.ByteBuffer} k k)) tag (fn [arg] (-> (m/find-first #{arg} c-args) meta :tag normalize-tag)) call-args (for [arg c-args] (cond (some #{arg} args) (with-meta arg {:tag (tag arg)}) (= 'long (tag arg)) (let [arg-sym (symbol (str/replace (name arg) #"len$" ""))] `(long (caesium.byte-bufs/buflen ~arg-sym))) (= 'jnr.ffi.byref.LongLongByReference (tag arg)) nil))] `(~(java-call-sym c-name) sodium ~@call-args)))
null
https://raw.githubusercontent.com/lvh/caesium/ff85b7a967e927f45bd37661609ea514c1b4a6c2/src/caesium/binding.clj
clojure
instead, please look at
(ns caesium.binding "**DANGER** These are the low-level bindings to libsodium, using the [[caesium.crypto.box]], [[caesium.crypto.secretbox]], [[caesium.crypto.generichash]], [[caesium.crypto.sign]] et cetera, namespaces." (:require [clojure.string :as s] [clojure.math.combinatorics :as c] [medley.core :as m] [clojure.string :as str]) (:import [jnr.ffi LibraryLoader LibraryOption] [jnr.ffi.annotations In Out Pinned LongLong] [jnr.ffi.types size_t])) (def ^:private bound-byte-type-syms '[bytes java.nio.ByteBuffer]) (defn ^:private permuted-byte-types "Given a method signature, return signatures for all bound byte types. Signature should be as per [[bound-fns]], with byte arguments annotated with `{:tag 'bytes}` in their metadata (note: the symbol, not the fn)." [[name args]] (let [byte-args (filter (comp #{'bytes} :tag meta) args)] (for [types (c/selections bound-byte-type-syms (count byte-args)) :let [arg->type (zipmap byte-args types) ann (fn [arg] (let [tag (get arg->type arg (:tag (meta arg)))] (vary-meta arg assoc :tag tag)))]] [name (mapv ann args)]))) (def ^:private raw-bound-fns "See [[bound-fns]], but without the permutations." '[[^int sodium_init []] [^String sodium_version_string []] [^void randombytes [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen]] [^long ^{size_t {}} crypto_secretbox_keybytes []] [^long ^{size_t {}} crypto_secretbox_noncebytes []] [^long ^{size_t {}} crypto_secretbox_macbytes []] [^String crypto_secretbox_primitive []] [^int crypto_secretbox_easy [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_open_easy [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^int crypto_secretbox_open_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_box_seedbytes []] [^long ^{size_t {}} crypto_box_publickeybytes []] [^long ^{size_t {}} crypto_box_secretkeybytes []] [^long ^{size_t {}} crypto_box_noncebytes []] [^long ^{size_t {}} crypto_box_macbytes []] [^long ^{size_t {}} crypto_box_sealbytes []] [^String ^{size_t {}} crypto_box_primitive []] [^int crypto_box_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_box_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_easy [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_open_easy [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_seal [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} pk]] [^int crypto_box_seal_open [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_box_open_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^long ^{size_t {}} crypto_shorthash_bytes] [^long ^{size_t {}} crypto_shorthash_keybytes] [^String crypto_shorthash_primitive []] [^int crypto_shorthash [^bytes ^{Pinned {}} out ^bytes ^{Pinned {}} in ^long ^{LongLong {}} inlen ^bytes ^{Pinned {}} k]] [^void crypto_shorthash_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_sign_bytes []] [^long ^{size_t {}} crypto_sign_seedbytes []] [^long ^{size_t {}} crypto_sign_publickeybytes []] [^long ^{size_t {}} crypto_sign_secretkeybytes []] [^String crypto_sign_primitive []] [^int crypto_sign_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_sign_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_sign [^bytes ^{Pinned {}} sm ^jnr.ffi.byref.LongLongByReference smlen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} sk]] [^int crypto_sign_open [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} sm ^long ^{LongLong {}} smlen ^bytes ^{Pinned {}} pk]] [^int crypto_sign_detached [^bytes ^{Pinned {}} sig ^jnr.ffi.byref.LongLongByReference siglen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} sk]] [^int crypto_sign_verify_detached [^bytes ^{Pinned {}} sig ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} pk]] [^long ^{size_t {}} crypto_generichash_bytes_min []] [^long ^{size_t {}} crypto_generichash_bytes_max []] [^long ^{size_t {}} crypto_generichash_bytes []] [^long ^{size_t {}} crypto_generichash_keybytes_min []] [^long ^{size_t {}} crypto_generichash_keybytes_max []] [^long ^{size_t {}} crypto_generichash_keybytes []] [^String crypto_generichash_primitive []] [^int crypto_generichash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen]] [^long ^{size_t {}} crypto_generichash_blake2b_bytes_min []] [^long ^{size_t {}} crypto_generichash_blake2b_bytes_max []] [^long ^{size_t {}} crypto_generichash_blake2b_bytes []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes_min []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes_max []] [^long ^{size_t {}} crypto_generichash_blake2b_keybytes []] [^long ^{size_t {}} crypto_generichash_blake2b_saltbytes []] [^long ^{size_t {}} crypto_generichash_blake2b_personalbytes []] [^long ^{size_t {}} crypto_generichash_blake2b_statebytes []] [^int crypto_generichash_blake2b [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen]] [^int crypto_generichash_blake2b_salt_personal [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} key ^long ^{LongLong {}} keylen ^bytes ^{Pinned {}} salt ^bytes ^{Pinned {}} personal]] [^int crypto_pwhash_alg_argon2i13 []] [^int crypto_pwhash_alg_argon2id13 []] [^int crypto_pwhash_alg_default []] [^long ^{size_t {}} crypto_pwhash_bytes_min []] [^long ^{size_t {}} crypto_pwhash_bytes_max []] [^long ^{size_t {}} crypto_pwhash_passwd_min []] [^long ^{size_t {}} crypto_pwhash_passwd_max []] [^long ^{size_t {}} crypto_pwhash_saltbytes []] [^long ^{size_t {}} crypto_pwhash_strbytes []] [^String crypto_pwhash_strprefix []] [^long ^{size_t {}} crypto_pwhash_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_memlimit_sensitive []] [^String crypto_pwhash_primitive []] [^int crypto_pwhash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_str_alg [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2i_alg_argon2i13 []] [^long ^{size_t {}} crypto_pwhash_argon2i_bytes_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_bytes_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_passwd_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_passwd_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_saltbytes []] [^long ^{size_t {}} crypto_pwhash_argon2i_strbytes []] [^String crypto_pwhash_argon2i_strprefix []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2i_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_argon2i_memlimit_sensitive []] [^int crypto_pwhash_argon2i [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_argon2i_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2i_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_argon2i_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2id_alg_argon2id13 []] [^long ^{size_t {}} crypto_pwhash_argon2id_bytes_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_bytes_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_passwd_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_passwd_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_saltbytes []] [^long ^{size_t {}} crypto_pwhash_argon2id_strbytes []] [^String crypto_pwhash_argon2id_strprefix []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_moderate []] [^long ^{size_t {}} crypto_pwhash_argon2id_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_argon2id_memlimit_sensitive []] [^int crypto_pwhash_argon2id [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit ^long ^{LongLong {}} alg]] [^int crypto_pwhash_argon2id_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_argon2id_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_argon2id_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_bytes_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_bytes_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_passwd_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_passwd_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_saltbytes []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_strbytes []] [^String crypto_pwhash_scryptsalsa208sha256_strprefix []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_min []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_max []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_interactive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_interactive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive []] [^long ^{size_t {}} crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive []] [^int crypto_pwhash_scryptsalsa208sha256 [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} buflen ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} salt ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_scryptsalsa208sha256_str [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^int crypto_pwhash_scryptsalsa208sha256_str_verify [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^int crypto_pwhash_scryptsalsa208sha256_str_needs_rehash [^bytes ^{Pinned {}} buf ^long ^{LongLong {}} opslimit ^long ^{LongLong {}} memlimit]] [^long ^{size_t {}} crypto_hash_sha256_bytes []] [^int crypto_hash_sha256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^long ^{size_t {}} crypto_hash_sha512_bytes []] [^int crypto_hash_sha512 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen]] [^long ^{size_t {}} crypto_auth_hmacsha256_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha256_keybytes []] [^int crypto_auth_hmacsha256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_auth_hmacsha512_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha512_keybytes []] [^int crypto_auth_hmacsha512 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_auth_hmacsha512256_bytes []] [^long ^{size_t {}} crypto_auth_hmacsha512256_keybytes []] [^int crypto_auth_hmacsha512256 [^bytes ^{Pinned {}} buf ^bytes ^{Pinned {}} msg ^long ^{LongLong {}} msglen ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_scalarmult_bytes []] [^long ^{size_t {}} crypto_scalarmult_scalarbytes []] [^String crypto_scalarmult_primitive []] [^int crypto_scalarmult_base [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n]] [^int crypto_scalarmult [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} p]] [^long ^{size_t {}} crypto_scalarmult_ristretto255_bytes []] [^long ^{size_t {}} crypto_scalarmult_ristretto255_scalarbytes []] [^int crypto_scalarmult_ristretto255_base [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n]] [^int crypto_scalarmult_ristretto255 [^bytes ^{Pinned {}} q ^bytes ^{Pinned {}} n ^bytes ^{Pinned {}} p]] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_keybytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_nsecbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_npubbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_ietf_abytes []] [^int crypto_aead_chacha20poly1305_ietf_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_ietf_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_aead_chacha20poly1305_keybytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_nsecbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_npubbytes []] [^long ^{size_t {}} crypto_aead_chacha20poly1305_abytes []] [^int crypto_aead_chacha20poly1305_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_chacha20poly1305_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_keybytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_nsecbytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_npubbytes []] [^long ^{size_t {}} crypto_aead_xchacha20poly1305_ietf_abytes []] [^int crypto_aead_xchacha20poly1305_ietf_encrypt [^bytes ^{Pinned {}} c ^jnr.ffi.byref.LongLongByReference clen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_decrypt [^bytes ^{Pinned {}} m ^jnr.ffi.byref.LongLongByReference mlen_p ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_encrypt_detached [^bytes ^{Pinned {}} c ^bytes ^{Pinned {}} mac ^jnr.ffi.byref.LongLongByReference maclen_p ^bytes ^{Pinned {}} m ^long ^{LongLong {}} mlen ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_decrypt_detached [^bytes ^{Pinned {}} m ^bytes ^{Pinned {}} nsec ^bytes ^{Pinned {}} c ^long ^{LongLong {}} clen ^bytes ^{Pinned {}} mac ^bytes ^{Pinned {}} ad ^long ^{LongLong {}} adlen ^bytes ^{Pinned {}} npub ^bytes ^{Pinned {}} k]] [^int crypto_aead_xchacha20poly1305_ietf_keygen [^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_kx_publickeybytes []] [^long ^{size_t {}} crypto_kx_secretkeybytes []] [^long ^{size_t {}} crypto_kx_seedbytes []] [^long ^{size_t {}} crypto_kx_sessionkeybytes []] [^String crypto_kx_primitive []] [^int crypto_kx_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk]] [^int crypto_kx_seed_keypair [^bytes ^{Pinned {}} pk ^bytes ^{Pinned {}} sk ^bytes ^{Pinned {}} seed]] [^int crypto_kx_client_session_keys [^bytes ^{Pinned {}} rx ^bytes ^{Pinned {}} tx ^bytes ^{Pinned {}} client_pk ^bytes ^{Pinned {}} client_sk ^bytes ^{Pinned {}} server_pk]] [^int crypto_kx_server_session_keys [^bytes ^{Pinned {}} rx ^bytes ^{Pinned {}} tx ^bytes ^{Pinned {}} server_pk ^bytes ^{Pinned {}} server_sk ^bytes ^{Pinned {}} client_pk]] [^long ^{size_t {}} crypto_kdf_bytes_min] [^long ^{size_t {}} crypto_kdf_bytes_max] [^long ^{size_t {}} crypto_kdf_contextbytes] [^long ^{size_t {}} crypto_kdf_keybytes] [^String crypto_kdf_primitive []] [^void crypto_kdf_keygen [^bytes ^{Pinned {}} k]] [^int crypto_kdf_derive_from_key [^bytes ^{Pinned {}} subk ^long ^{LongLong {}} subklen ^long ^{LongLong {}} subkid ^bytes ^{Pinned {}} ctx ^bytes ^{Pinned {}} k]] [^long ^{size_t {}} crypto_core_ristretto255_bytes []] [^long ^{size_t {}} crypto_core_ristretto255_hashbytes []] [^long ^{size_t {}} crypto_core_ristretto255_scalarbytes []] [^long ^{size_t {}} crypto_core_ristretto255_nonreducedscalarbytes []] [^int crypto_core_ristretto255_is_valid_point [^bytes ^{Pinned {}} p]] [^int crypto_core_ristretto255_add [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} q]] [^int crypto_core_ristretto255_sub [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} q]] [^int crypto_core_ristretto255_from_hash [^bytes ^{Pinned {}} p ^bytes ^{Pinned {}} r]] [^void crypto_core_ristretto255_random [^bytes ^{Pinned {}} p]] [^void crypto_core_ristretto255_scalar_random [^bytes ^{Pinned {}} r]] [^int crypto_core_ristretto255_scalar_invert [^bytes ^{Pinned {}} recip ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_negate [^bytes ^{Pinned {}} neg ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_complement [^bytes ^{Pinned {}} result ^bytes ^{Pinned {}} s]] [^void crypto_core_ristretto255_scalar_add [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_sub [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_mul [^bytes ^{Pinned {}} z ^bytes ^{Pinned {}} x ^bytes ^{Pinned {}} y]] [^void crypto_core_ristretto255_scalar_reduce [^bytes ^{Pinned {}} r ^bytes ^{Pinned {}} s]] [^int crypto_core_ristretto255_scalar_is_canonical [^bytes ^{Pinned {}} s]]]) (def ^:private bound-fns "A mapping of type- and jnr.ffi-annotated bound method symbols to respective argspec. This exists so that tooling (like magic macro helpers) can easily inspect caesium allegedly binds. That can be done by reflecting on Clojure's reflection tools don't show annotations, and we always use the data in metadata-annotated form anyway (both to create the interface and to bind fns to vars). This has to be a seq and not a map, because the same key (symbol, method name) might occur with multiple values (e.g. when binding the same char* fn with different JVM byte types)." (mapcat permuted-byte-types raw-bound-fns)) (defmacro ^:private defsodium [] `(definterface ~'Sodium ~@bound-fns)) (defsodium) (defn ^:private load-sodium "Load native libsodium library." ([] (load-sodium "sodium")) ([lib] (try (-> (LibraryLoader/create Sodium) (.failImmediately) (.load lib)) (catch Exception e (throw (ClassNotFoundException. "unable to load native libsodium; is it installed?" e)))))) (def ^Sodium sodium "The sodium library singleton instance." (load-sodium)) (assert (#{0 1} (.sodium_init sodium))) (defn ^:private c-name "Resolves the fn name in the current ns to the fn name in the equivalent libsodium C pseudo-namespace. This understands problems like e.g. generichash in the generichash namespace meaning crypto_generichash, not the (nonexistant) crypto_generichash_generichash." [^clojure.lang.Namespace namespace ^clojure.lang.Symbol fn-name] (let [fn-name (s/replace (name fn-name) "-" "_") fn-name-parts (set (str/split fn-name #"_")) prefix (-> namespace ns-name str (s/split #"\.") rest vec) path (concat (remove fn-name-parts prefix) [fn-name])] (symbol (s/join "_" path)))) (defn ^:private java-call-sym "Creates the Clojure Java method call syntax to call a method on the libsodium binding." [c-name] (symbol (str "." c-name))) (defmacro defconsts "Define a number of constants by name. Uses the *ns* to figure out the const-returning fn in libsodium." [consts] `(do ~@(for [const consts :let [c-name (c-name *ns* const) docstring (str "Constant returned by `" c-name "`. " "See libsodium docs.")]] `(def ~(with-meta const {:const true}) ~docstring (~(java-call-sym c-name) sodium))))) (defmacro call! "Produces a form for calling named fn with lots of magic: * The fn-name is specified using its short name, which is resolved against the ns as per [[defconsts]]. * All bufs are annotated as ByteBuffers. * Buffer lengths are automatically added." [fn-name & args] (let [c-name (c-name *ns* fn-name) [_ c-args] (m/find-first (comp #{c-name} first) raw-bound-fns) normalize-tag (fn [k] (get {'bytes 'java.nio.ByteBuffer} k k)) tag (fn [arg] (-> (m/find-first #{arg} c-args) meta :tag normalize-tag)) call-args (for [arg c-args] (cond (some #{arg} args) (with-meta arg {:tag (tag arg)}) (= 'long (tag arg)) (let [arg-sym (symbol (str/replace (name arg) #"len$" ""))] `(long (caesium.byte-bufs/buflen ~arg-sym))) (= 'jnr.ffi.byref.LongLongByReference (tag arg)) nil))] `(~(java-call-sym c-name) sodium ~@call-args)))
6df4f579b5b9db370fb7a63cfabff138a7aa76751469514578e3eac119b96044
thelema/ocaml-community
builtini_bindtags.ml
##ifdef CAMLTK let cCAMLtoTKbindings = function | WidgetBindings v1 -> cCAMLtoTKwidget widget_any_table v1 | TagBindings v1 -> TkToken v1 ;; (* this doesn't really belong here *) let cTKtoCAMLbindings s = if String.length s > 0 && s.[0] = '.' then WidgetBindings (cTKtoCAMLwidget s) else TagBindings s ;; ##else let cCAMLtoTKbindings = function | `Widget v1 -> cCAMLtoTKwidget v1 | `Tag v1 -> TkToken v1 ;; (* this doesn't really belong here *) let cTKtoCAMLbindings s = if String.length s > 0 && s.[0] = '.' then `Widget (cTKtoCAMLwidget s) else `Tag s ;; ##endif
null
https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/otherlibs/labltk/builtin/builtini_bindtags.ml
ocaml
this doesn't really belong here this doesn't really belong here
##ifdef CAMLTK let cCAMLtoTKbindings = function | WidgetBindings v1 -> cCAMLtoTKwidget widget_any_table v1 | TagBindings v1 -> TkToken v1 ;; let cTKtoCAMLbindings s = if String.length s > 0 && s.[0] = '.' then WidgetBindings (cTKtoCAMLwidget s) else TagBindings s ;; ##else let cCAMLtoTKbindings = function | `Widget v1 -> cCAMLtoTKwidget v1 | `Tag v1 -> TkToken v1 ;; let cTKtoCAMLbindings s = if String.length s > 0 && s.[0] = '.' then `Widget (cTKtoCAMLwidget s) else `Tag s ;; ##endif
36e917c550ef04dc2ff6a14e6db556f6b0346a32cb2434d1ed4ab7d5c5afc856
clj-kondo/clj-kondo
main_test.clj
(ns clj-kondo.main-test (:require [cheshire.core :as cheshire] [clj-kondo.core :as clj-kondo] [clj-kondo.main :refer [main]] [clj-kondo.test-utils :as tu :refer [lint! assert-submaps assert-submap submap? make-dirs rename-path remove-dir assert-submaps2]] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :as t :refer [deftest is testing]] [missing.test.assertions])) (deftest self-lint-test (is (empty? (lint! (io/file "src") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "test") {:linters {:unresolved-symbol {:level :error}}})))) (deftest inline-def-test (let [linted (lint! (io/file "corpus" "inline_def.clj") "--config" "{:linters {:redefined-var {:level :off}}}") row-col-files (map #(select-keys % [:row :col :file]) linted)] (assert-submaps '({:row 5, :col 3, :file "corpus/inline_def.clj"} {:row 8, :col 3, :file "corpus/inline_def.clj"} {:row 10, :col 10, :file "corpus/inline_def.clj"} {:row 12, :col 16, :file "corpus/inline_def.clj"} {:row 14, :col 18, :file "corpus/inline_def.clj"}) row-col-files) (is (= #{"inline def"} (set (map :message linted))))) (doseq [lang [:clj :cljs]] (is (empty? (lint! "(defmacro foo [] `(def x 1))" "--lang" (name lang)))) (is (empty? (lint! "(defn foo [] '(def x 3))" "--lang" (name lang)))))) (deftest def-fn-test (let [config {:linters {:def-fn {:level :warn}}}] (let [linted (lint! "(def x (fn [] 1))" config) row-col (map #(select-keys % [:row :col]) linted)] (assert-submaps '({:row 1, :col 8}) row-col) (is (= #{"Use defn instead of def + fn"} (set (map :message linted))))) (let [linted (lint! "(def x (let [y 1] (fn [] y)))" config) row-col (map #(select-keys % [:row :col]) linted)] (assert-submaps '({:row 1, :col 19}) row-col) (is (= #{"Use defn instead of def + fn"} (set (map :message linted))))) (doseq [lang [:clj :cljs]] (is (empty? (lint! "(def x [(fn [] 1)])" "--lang" (name lang) "--config" (pr-str config)))) (is (empty? (lint! "(def x (let [x 1] [(fn [] x)]))" "--lang" (name lang) "--config" (pr-str config))))))) (deftest redundant-let-test (let [linted (lint! (io/file "corpus" "redundant_let.clj")) row-col-files (map #(select-keys % [:row :col :file]) linted)] (assert-submaps '({:row 4, :col 3, :file "corpus/redundant_let.clj"} {:row 8, :col 3, :file "corpus/redundant_let.clj"} {:row 12, :col 3, :file "corpus/redundant_let.clj"}) row-col-files) (is (= #{"Redundant let expression."} (set (map :message linted))))) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :warning, :message #"Redundant let"}) (lint! "(let [x 2] (let [y 1]))" "--lang" "cljs")) (testing "linters still work in areas where arity linter is are disabled" (assert-submaps '({:file "<stdin>", :row 1, :col 43, :level :warning, :message #"Redundant let"}) (lint! "(reify Object (toString [this] (let [y 1] (let [x y] x))))"))) (assert-submaps [{:row 1, :col 1 :message #"Redundant let"} ](lint! "(let [] 1)")) (is (empty? (lint! "(let [x 2] `(let [y# 3]))"))) (is (empty? (lint! "(let [x 2] '(let [y 3]))"))) (is (empty? (lint! "(let [x 2] (let [y 1]) (let [y 2]))"))) (is (empty? (lint! "(let [x 2] (when true (let [y 1])))"))) (is (empty? (lint! "(let [z 1] (when true (let [x (let [y 2] y)])))"))) (is (empty? (lint! "#(let [x 1])"))) (is (empty? (lint! "(let [x 1] [x (let [y (+ x 1)] y)])"))) (is (empty? (lint! "(let [x 1] #{(let [y 1] y)})"))) (is (empty? (lint! "(let [x 1] #:a{:a (let [y 1] y)})"))) (is (empty? (lint! "(let [x 1] {:a (let [y 1] y)})"))) (is (empty? (lint! " (ns foo {:clj-kondo/config '{:lint-as {clojure.test.check.generators/let clojure.core/let}}} (:require [clojure.test.check.generators :as gen])) (let [_init-link-events 1] (gen/let [_chain-size 2 _command-chain 2] 1)) "))) (is (empty? (lint! "(let [#?@(:clj [x 1])] #?(:clj x))" "--lang" "cljc")))) (deftest redundant-do-test (assert-submaps '({:row 3, :col 1, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 4, :col 7, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 5, :col 14, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 6, :col 8, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 7, :col 16, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 8, :col 1, :file "corpus/redundant_do.clj" :message "Missing body in when"} {:row 9, :col 12, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 10, :col 16, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 11, :col 9, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 12, :col 17, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 13, :col 25, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 14, :col 18, :file "corpus/redundant_do.clj" :message "redundant do"}) (lint! (io/file "corpus" "redundant_do.clj") {:linters {:redundant-expression {:level :off}}})) (is (empty? (lint! "(do 1 `(do 1 2 3))" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "(do 1 '(do 1 2 3))" {:linters {:redundant-expression {:level :off}}}))) (is (not-empty (lint! "(fn [] (do :foo :bar))" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "#(do :foo)"))) (is (empty? (lint! "#(do {:a %})"))) (is (empty? (lint! "#(do)"))) (is (empty? (lint! "#(do :foo :bar)" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "#(do (prn %1 %2 true) %1)"))) (is (empty? (lint! "(let [x (do (println 1) 1)] x)"))) (is (empty? (lint! "(let [_ nil] #?(:cljs (do (println 1) (println 2)) :clj (println 3))) " "--lang" "cljc")))) (deftest cljc-test (assert-submaps '({:file "corpus/cljc/datascript.cljc", :row 9, :col 1} {:file "corpus/cljc/test_cljc.cljc", :row 13, :col 9} {:file "corpus/cljc/test_cljc.cljc", :row 14, :col 10} {:file "corpus/cljc/test_cljc.cljc", :row 21, :col 1} {:file "corpus/cljc/test_cljc.cljs", :row 5, :col 1} {:file "corpus/cljc/test_cljc_from_clj.clj", :row 5, :col 1} {:file "corpus/cljc/test_cljs.cljs", :row 5, :col 1} {:file "corpus/cljc/test_cljs.cljs", :row 6, :col 1}) (lint! (io/file "corpus" "cljc"))) (assert-submaps '({:file "corpus/spec/alpha.cljs", :row 6, :col 1, :level :error, :message "spec.alpha/def is called with 2 args but expects 3"}) (lint! (io/file "corpus" "spec"))) (is (empty? (lint! "(defn foo [#?(:default s :clj s)]) (foo 1)" "--lang" "cljc"))) (is (empty? (lint! "(defn foo [_x _y]) (foo 1 #uuid \"00000000-0000-0000-0000-000000000000\")" "--lang" "cljc"))) (is (empty? (lint! "(def ^{#?@(:clj [:deprecated \"deprecation message\"])} my-deprecated-var :bla)" "--lang" "cljc"))) (is (empty? (lint! "^#?(:clj :a :cljsr :b) [1 2 3]" "--lang" "cljc")))) (deftest exclude-clojure-test (let [linted (lint! (io/file "corpus" "exclude_clojure.clj"))] (assert-submaps '({:file "corpus/exclude_clojure.clj", :row 12, :col 1, :level :error, :message "clojure.core/get is called with 4 args but expects 2"}) linted))) (deftest private-call-test (assert-submaps '({:file "corpus/private/private_calls.clj", :row 2, :col 49, :level :error, :message "#'private.private-defs/private is private"} {:file "corpus/private/private_calls.clj", :row 4, :col 1, :level :error, :message "#'private.private-defs/private is private"} {:file "corpus/private/private_calls.clj", :row 5, :col 1, :level :error, :message "#'private.private-defs/private-by-meta is private"} {:file "corpus/private/private_calls.clj", :row 6, :col 6, :level :error, :message "#'private.private-defs/private is private"}) (lint! (io/file "corpus" "private"))) (assert-submaps '({:file "<stdin>", :row 6, :col 1, :level :error, :message "#'foo/foo is private"}) (lint! "(ns foo) (defn- foo []) (defmacro blah [] `foo) ;; using it in syntax quote should mark private var as used (ns bar (:require [foo])) `foo/foo ;; this doesn't use the private var, it only uses the ns alias foo/foo ;; this does use the private var "))) (deftest read-error-test (testing "when an error happens in one file, the other file is still linted" (let [linted (lint! (io/file "corpus" "read_error"))] (assert-submaps '({:file "corpus/read_error/error.clj", :row 1, :col 1, :level :error, :message "Found an opening ( with no matching )"} {:file "corpus/read_error/error.clj" :row 2, :col 1, :level :error, :message "Expected a ) to match ( from line 1"} {:file "corpus/read_error/ok.clj", :row 6, :col 1, :level :error, :message "read-error.ok/foo is called with 1 arg but expects 0"}) linted)))) (deftest nested-namespaced-maps-test (assert-submaps '({:file "corpus/nested_namespaced_maps.clj", :row 9, :col 1, :level :error, :message "nested-namespaced-maps/test-fn is called with 2 args but expects 1"} {:file "corpus/nested_namespaced_maps.clj", :row 11, :col 12, :level :error, :message "duplicate key :a"}) (lint! (io/file "corpus" "nested_namespaced_maps.clj"))) (is (empty? (lint! "(meta ^#:foo{:a 1} {})")))) (deftest exit-code-test (with-out-str (testing "the exit code is 0 when no errors are detected" (is (zero? (with-in-str "(defn foo []) (foo)" (main "--lint" "-"))))) (testing "the exit code is 2 when warning are detected" (is (= 2 (with-in-str "(do (do 1))" (main "--lint" "-"))))) (testing "the exit code is 1 when errors are detected" (is (= 3 (with-in-str "(defn foo []) (foo 1)" (main "--lint" "-"))))))) (deftest exit-code-with-fail-level-test (with-out-str (testing "the exit code is 0 when fail-level is explicitly set to warning and no errors are detected" (is (zero? (with-in-str "(defn foo []) (foo)" (main "--fail-level" "warning" "--lint" "-"))))) (testing "the exit code is 2 when fail-level is warning and warnings are detected" (is (= 2 (with-in-str "(do (do 1))" (main "--fail-level" "warning" "--lint" "-"))))) (testing "the exit code is 3 when fail-level is error and errors are detected" (is (= 3 (with-in-str "(defn foo []) (foo 1)" (main "--fail-level" "error" "--lint" "-"))))))) (deftest cond-test (doseq [lang [:clj :cljs :cljc]] (testing (str "lang: " lang) (assert-submaps '({:row 9, :col 3, :level :warning} {:row 16, :col 3, :level :warning}) (lint! (io/file "corpus" (str "cond_without_else." (name lang))))) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "cond requires even number of forms"}) (lint! "(cond 1 2 3)" "--lang" (name lang))))) (assert-submaps '({:file "corpus/cond_without_else/core.cljc", :row 6, :col 21, :level :warning} {:file "corpus/cond_without_else/core.cljs", :row 3, :col 7, :level :warning}) (lint! [(io/file "corpus" "cond_without_else" "core.cljc") (io/file "corpus" "cond_without_else" "core.cljs")]))) (deftest cljs-core-macro-test (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/for is called with 4 args but expects 2"} (first (lint! "(for [x []] 1 2 3)" "--lang" "cljs")))) (deftest built-in-test (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "cljs")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "cljc")))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.test/successful? is called with 3 args but expects 1"} (first (lint! "(ns my-cljs (:require [clojure.test :refer [successful?]])) (successful? 1 2 3)" "--lang" "clj"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "cljs.test/successful? is called with 3 args but expects 1"} (first (lint! "(ns my-cljs (:require [cljs.test :refer [successful?]])) (successful? 1 2 3)" "--lang" "cljs"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.set/difference is called with 0 args but expects 1, 2 or more"} (first (lint! "(ns my-cljs (:require [clojure.set :refer [difference]])) (difference)" "--lang" "clj"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.set/difference is called with 0 args but expects 1, 2 or more"} (first (lint! "(ns my-cljs (:require [clojure.set :refer [difference]])) (difference)" "--lang" "cljs")))) (deftest built-in-java-test (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "(Thread/sleep 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "(java.lang.Thread/sleep 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Math/pow is called with 3 args but expects 2"} (first (lint! "(Math/pow 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.math.BigInteger/valueOf is called with 3 args but expects 1"} (first (lint! "(BigInteger/valueOf 1 2 3)" "--lang" "clj")))) (assert-submap {:message #"java.lang.Thread"} (first (lint! "(java.lang.Thread/sleep 1 2 3)" "--lang" "cljs"))) (is (= {:file "<stdin>", :row 1, :col 9, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "#?(:clj (java.lang.Thread/sleep 1 2 3))" "--lang" "cljc"))))) (deftest resolve-core-ns-test (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/vec is called with 0 args but expects 1"} (first (lint! "(clojure.core/vec)" "--lang" "clj"))) (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/vec is called with 0 args but expects 1"} (first (lint! "(cljs.core/vec)" "--lang" "cljs"))) (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/vec is called with 0 args but expects 1"} (first (lint! "(clojure.core/vec)" "--lang" "cljs")))) (deftest override-test (doseq [lang [:clj :cljs]] (testing (str "lang: " (name lang)) (assert-submaps [{:file "<stdin>", :row 1, :col 1, :level :error, :message (str (case lang :clj "clojure" :cljs "cljs") ".core/quote is called with 3 args but expects 1")}] (lint! "(quote 1 2 3)" "--lang" (name lang))))) (is (empty? (lint! "(cljs.core/array 1 2 3)" "--lang" "cljs")))) (deftest cljs-clojure-ns-alias-test (assert-submap '{:file "<stdin>", :row 2, :col 1, :level :error, :message "cljs.test/do-report is called with 3 args but expects 1"} (first (lint! "(ns foo (:require [clojure.test :as t])) (t/do-report 1 2 3)" "--lang" "cljs")))) (deftest prefix-libspec-test (assert-submaps '({:col 14 :file "corpus/prefixed_libspec.clj" :level :error :message "Prefix lists can only have two levels." :row 11} {:file "corpus/prefixed_libspec.clj", :row 14, :col 1, :level :error, :message "foo.bar.baz/b is called with 0 args but expects 1"} {:file "corpus/prefixed_libspec.clj", :row 15, :col 1, :level :error, :message "foo.baz/c is called with 0 args but expects 1"}) (lint! (io/file "corpus" "prefixed_libspec.clj")))) (deftest prefix-libspec-containing-periods-test (testing "when a lib name with a period is found" (is (= '({:col 32 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer [foo.bar :as baz]]))" {:linters {:unused-namespace {:level :off}}})))) (testing "when multiple lib names with periods are found" (is (= '({:col 32 :file "<stdin>" :level :error :message "found lib name 'babashka.quux' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3} {:col 32 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 4}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer [babashka.quux :as baz] [foo.bar :as quux]]))" {:linters {:unused-namespace {:level :off}}})))) (testing "when a lib name with periods is a simple symbol" (is (= '({:col 31 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer foo.bar]))" {:linters {:unused-namespace {:level :off}}}))))) (deftest rename-test (testing "the renamed function isn't available under the referred name" (assert-submaps '({:file "<stdin>", :row 2, :col 11, :level :error, :message "clojure.string/includes? is called with 1 arg but expects 2"}) (lint! "(ns foo (:require [clojure.string :refer [includes?] :rename {includes? i}])) (i \"str\") (includes? \"str\")"))) (assert-submaps '({:file "corpus/rename.cljc", :row 4, :col 9, :level :error, :message "clojure.core/update is called with 0 args but expects 3, 4, 5, 6 or more"} {:file "corpus/rename.cljc", :row 5, :col 10, :level :error, :message "clojure.core/update is called with 0 args but expects 3, 4, 5, 6 or more"} {:file "corpus/rename.cljc", :row 6, :col 9, :level :error, :message "Unresolved symbol: conj"} {:file "corpus/rename.cljc", :row 7, :col 10, :level :error, :message "Unresolved symbol: conj"} {:file "corpus/rename.cljc", :row 8, :col 10, :level :error, :message "Unresolved symbol: join"} {:file "corpus/rename.cljc", :row 9, :col 11, :level :error, :message "Unresolved symbol: join"} {:file "corpus/rename.cljc", :row 10, :col 9, :level :error, :message "clojure.string/join is called with 0 args but expects 1 or 2"} {:file "corpus/rename.cljc", :row 11, :col 10, :level :error, :message "clojure.string/join is called with 0 args but expects 1 or 2"}) (lint! (io/file "corpus" "rename.cljc") '{:linters {:unresolved-symbol {:level :error}}}))) (deftest refer-all-rename-test (testing ":require with :refer :all and :rename" (assert-submaps '({:file "corpus/refer_all.clj", :row 15, :col 1, :level :error, :message "funs/foo is called with 0 args but expects 1"} {:file "corpus/refer_all.clj", :row 16, :col 1, :level :error, :message "funs/bar is called with 0 args but expects 1"}) (lint! (io/file "corpus" "refer_all.clj") {:linters {:unresolved-var {:level :off}}})) (assert-submaps '({:file "corpus/refer_all.cljs", :row 8, :col 1, :level :error, :message "macros/foo is called with 0 args but expects 1"}) (lint! (io/file "corpus" "refer_all.cljs"))))) (deftest alias-test (assert-submap '{:file "<stdin>", :row 1, :col 35, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"} (first (lint! "(ns foo) (alias 'c 'clojure.core) (c/select-keys)"))) (is (empty? (lint! " (require 'bar 'foo) (alias (quote f) (quote foo)) (alias (quote b) (quote bar)) (f/inc) (b/inc) ")))) (deftest reduce-without-init-test (testing "when enabled, warn on two argument usage of reduce" (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Reduce called without explicit initial value."}) (lint! "(reduce max [])" {:linters {:reduce-without-init {:level :warning}}})) (is (empty? (lint! "(reduce + [1 2 3])" {:linters {:reduce-without-init {:level :warning}}}))) (is (empty? (lint! "(reduce max 0 [1 2 3])" {:linters {:reduce-without-init {:level :warning}}}))) (is (empty? (lint! "(reduce + [1 2 3])"))) (is (empty? (lint! "(reduce max [])" '{:linters {:reduce-without-init {:level :warning :exclude [clojure.core/max]}}}))))) (deftest case-test (testing "case dispatch values should not be linted as function calls" (assert-submaps '({:file "corpus/case.clj", :row 7, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 9, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 14, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 15, :col 3, :level :error, :message "clojure.core/odd? is called with 2 args but expects 1"}) (lint! (io/file "corpus" "case.clj") {:linters {:unresolved-symbol {:level :error}}}))) (testing "no false positive when using unquoted symbols" (is (empty? (lint! " (case 'str/join str/join :foo) (let [x 'y] (case x y 1 2))" {:linters {:unresolved-symbol {:level :error}}})))) (testing "no false positive when using defn in case list dispatch" (is (empty? (lint! "(let [x 1] (case x (defn select-keys) 1 2))" {:linters {:unresolved-symbol {:level :error}}})))) (testing "case dispatch vals are analyzed" (is (empty? (lint! "(require '[clojure.string :as str] (case 10 ::str/foo 11))" {:linters {:unresolved-symbol {:level :error} :unused-namespace {:level :error}}})))) (testing "CLJS constant" ;; More info on this: -06-15-clojurescript-case-constants.html (assert-submaps '({:file "<stdin>", :row 1, :col 24, :level :error, :message "Unused private var user/x"}) (lint! "(def ^:private ^:const x 2) (case 1 x :yeah)" {:linters {:unused-private-var {:level :error}}})) (is (empty? (lint! "(def ^:private ^:const x 2) (case 1 x :yeah)" {:linters {:unused-private-var {:level :error}}} "--lang" "cljs")))) (testing "quoted case test constant" (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :warning, :message "Case test is compile time constant and should not be quoted."}) (lint! "(case 'x 'a 1 b 0)"))) (testing "duplicate case test constant" (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "Duplicate case test constant: :a"} {:file "<stdin>", :row 1, :col 24, :level :error, :message "Duplicate case test constant: :a"}) (lint! "(case f :a 2 :a 3 :b 1 :a 0)")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "Duplicate case test constant: :a"}) (lint! "(case f :a 2 :a 3 :b 1 :default)")) (assert-submaps '({:file "<stdin>", :row 3, :col 3, :level :error, :message "Duplicate case test constant: :bar"} {:file "<stdin>", :row 4, :col 3, :level :error, :message "Duplicate case test constant: :bar"}) (lint! "(case x (:foo :bar) :yolo :bar :hello :bar :hi)")) (assert-submaps '({:file "<stdin>", :row 2, :col 6, :level :error, :message "Duplicate case test constant: a"} {:file "<stdin>", :row 3, :col 3, :level :error, :message "Duplicate case test constant: a"}) (lint! "(case x (a a) 1 a 1 1)")) (is (empty? (lint! "(case 0 :a 1 :a)"))) (is (empty? (lint! "(case f :a 1 :b 2)"))) (is (empty? (lint! "(case f :a 1 :b 2 :a)"))))) (deftest local-bindings-test (is (empty? (lint! "(fn [select-keys] (select-keys))"))) (is (empty? (lint! "(fn [[select-keys x y z]] (select-keys))"))) (is (empty? (lint! "(fn [{:keys [:select-keys :b]}] (select-keys))"))) (is (empty? (lint! "(defn foo [{:keys [select-keys :b]}] (let [x 1] (select-keys)))"))) (is (seq (lint! "(defn foo ([select-keys]) ([x y] (select-keys)))"))) (is (empty? (lint! "(if-let [select-keys (fn [])] (select-keys) :bar)"))) (is (empty? (lint! "(when-let [select-keys (fn [])] (select-keys))"))) (is (empty? (lint! "(fn foo [x] (foo x))"))) (is (empty? (lint! "(fn select-keys [x] (select-keys 1))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :error, :message "foo is called with 3 args but expects 1"}) (lint! "(fn foo [x] (foo 1 2 3))")) (is (empty? (lint! "(fn foo ([x] (foo 1 2)) ([x y]))"))) (assert-submaps '({:message "f is called with 3 args but expects 0"}) (lint! "(let [f (fn [])] (f 1 2 3))")) (assert-submaps '({:message "f is called with 3 args but expects 0"}) (lint! "(let [f #()] (f 1 2 3))")) (assert-submaps '({:message "f is called with 0 args but expects 1 or more"}) (lint! "(let [f #(apply println % %&)] (f))")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "fn is called with 1 arg but expects 0"}) (lint! "(let [fn (fn [])] (fn 1))")) (is (empty? (lint! "(let [f #(apply println % %&)] (f 1))"))) (is (empty? (lint! "(let [f #(apply println % %&)] (f 1 2 3 4 5 6))"))) (is (empty? (lint! "(fn ^:static meta [x] (when (instance? clojure.lang.IMeta x) (. ^clojure.lang.IMeta x (meta))))"))) (is (empty? (lint! "(doseq [fn [inc]] (fn 1))"))) (is (empty? (lint! "(select-keys (let [x (fn [])] (x 1 2 3)) [])" "--config" "{:linters {:invalid-arity {:skip-args [clojure.core/select-keys]} :unresolved-symbol {:level :off}}}"))) (is (empty? (lint! "(defn foo [x {:keys [y] :or {y x}}] x y)" {:linters {:unresolved-symbol {:level :error} :unused-binding {:level :warning}}}))) (is (empty? (lint! "(defn foo [[x y] {:keys [:z] :or {z (+ x y)}}] z)" {:linters {:unresolved-symbol {:level :error} :unused-binding {:level :warning}}})))) (deftest let-test (assert-submap {:file "<stdin>", :row 1, :col 6, :level :error, :message "let binding vector requires even number of forms"} (first (lint! "(let [x 1 y])"))) (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"}) (lint! "(let [x 1 y (select-keys)])")) (is (empty? (lint! "(let [select-keys (fn []) y (select-keys)])"))) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "f is called with 1 arg but expects 0"}) (lint! "(let [f (fn []) y (f 1)])")) (assert-submaps '({:file "<stdin>", :row 1, :col 18, :level :error, :message "f is called with 1 arg but expects 0"}) (lint! "(let [f (fn [])] (f 1))")) (assert-submaps '({:file "<stdin>", :row 1, :col 6, :level :error, :message #"vector"}) (lint! "(let x 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"0 args"}) (lint! "(let)")) (is (empty (lint! "(let [f (fn []) f (fn [_]) y (f 1)])"))) (is (empty? (lint! "(let [err (fn [& msg])] (err 1 2 3))")))) (deftest if-let-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y 2])")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 4 args but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y 2] x 1 2)" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-let [x 1] true)" "--lang" lang)) (is (empty? (lint! "(if-let [{:keys [row col]} {:row 1 :col 2}] row 1)" "--lang" lang))))) (deftest if-some-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-some is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "if-some binding vector requires exactly 2 forms"}) (lint! "(if-some [x 1 y 2])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-some is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "if-some binding vector requires exactly 2 forms"}) (lint! "(if-some [x 1 y])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-some [x 1] true)" "--lang" lang)) (is (empty? (lint! "(if-some [{:keys [row col]} {:row 1 :col 2}] row 1)" "--lang" lang))))) (deftest when-let-test (assert-submap {:file "<stdin>", :row 1, :col 11, :level :error, :message "when-let binding vector requires exactly 2 forms"} (first (lint! "(when-let [x 1 y 2])"))) (assert-submap {:file "<stdin>", :row 1, :col 11, :level :error, :message "when-let binding vector requires exactly 2 forms"} (first (lint! "(when-let [x 1 y])"))) (is (empty? (lint! "(when-let [{:keys [:row :col]} {:row 1 :col 2}])")))) (deftest config-test (is (empty? (lint! "(select-keys 1 2 3)" '{:linters {:invalid-arity {:level :off}}}))) (is (empty? (lint! "(clojure.core/is-annotation? 1)" '{:linters {:private-call {:level :off}}}))) (is (empty? (lint! "(def (def x 1))" '{:linters {:inline-def {:level :off}}}))) (is (empty? (lint! "(do (do 1 2 3))" '{:linters {:redundant-do {:level :off} :redundant-expression {:level :off}}}))) (is (empty? (lint! "(let [x 1] (let [y 2]))" '{:linters {:redundant-let {:level :off}}}))) (is (empty? (lint! "(cond 1 2)" '{:linters {:cond-else {:level :off}}}))) (when-not tu/native? (is (str/includes? (let [err (java.io.StringWriter.)] (binding [*err* err] (lint! (io/file "corpus") '{:output {:progress true}} "--config-dir" "corpus/.clj-kondo") (str err))) "....")) (doseq [fmt [:json :edn]] (is (not (str/includes? (with-out-str (lint! (io/file "corpus") {:output {:progress true :format fmt}} "--config-dir" "corpus/.clj-kondo")) "...."))))) (is (not (some #(str/includes? % "datascript") (map :file (lint! (io/file "corpus") '{:output {:exclude-files ["datascript"]}} "--config-dir" "corpus/.clj-kondo"))))) (is (not (some #(str/includes? % "datascript") (map :file (lint! (io/file "corpus") '{:output {:include-files ["inline_def"]}} "--config-dir" "corpus/.clj-kondo"))))) (is (str/starts-with? (with-out-str (with-in-str "(do 1)" (main "--lint" "-" "--config" (str '{:output {:pattern "{{LEVEL}}_{{filename}}"} :linters {:unresolved-symbol {:level :off}}})))) "WARNING_<stdin>")) (is (empty? (lint! "(comment (select-keys))" '{:skip-comments true :linters {:unresolved-symbol {:level :off}}}))) (assert-submap '({:file "<stdin>", :row 1, :col 16, :level :error, :message "user/foo is called with 2 args but expects 1"}) (lint! "(defn foo [x]) (foo (comment 1 2 3) 2)" '{:skip-comments true})) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.specs])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [foo.specs bar.specs]}}}))) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.specs])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [".*\\.specs$"]}}}))) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.spex])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [".*\\.specs$" ".*\\.spex$"]}}})))) (deftest skip-comments-test (is (= 1 (count (lint! "(comment (inc :foo))" {:linters {:type-mismatch {:level :error}}})))) (is (empty? (lint! "(comment (inc :foo))" {:skip-comments true :linters {:type-mismatch {:level :error}}}))) (is (= 1 (count (lint! "(ns foo {:clj-kondo/config {:skip-comments false}}) (comment (inc :foo))" {:skip-comments true :linters {:type-mismatch {:level :error}}}))))) (deftest replace-config-test (let [res (lint! "(let [x 1] (let [y 2]))" "--config" "^:replace {:linters {:redundant-let {:level :info}}}")] (is (every? #(identical? :info (:level %)) res)))) (deftest map-duplicate-keys-test (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "duplicate key :a"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} {:file "<stdin>", :row 1, :col 35, :level :error, :message "duplicate key :a"}) (lint! "{:a 1 :a (select-keys 1) :c {:a 1 :a 2}}"))) (is (= '({:file "<stdin>", :row 1, :col 6, :level :error, :message "duplicate key 1"} {:file "<stdin>", :row 1, :col 18, :level :error, :message "duplicate key \"foo\""}) (lint! "{1 1 1 1 \"foo\" 1 \"foo\" 2}"))) (is (empty? (lint! " (ns foo (:require [foo.bar :as bar])) (def foo {:bar/id \"asdf\" ::bar/id \"lkj\"})"))) (is (= '({:col 15 :file "<stdin>" :level :error :message "duplicate key (1 2)" :row 1}) (lint! "'{[1 2] \"bar\" (1 2) 12}"))) (is (= '({:col 22 :file "<stdin>" :level :error :message "duplicate key (let [x 2] x)" :row 1}) (lint! "{(let [x 2] x) \"bar\" (let [x 2] x) 12}"))) (is (= '({:col 14 :file "<stdin>" :level :error :message "duplicate key '(1 2)" :row 1}) (lint! "{[1 2] \"bar\" '(1 2) 12}"))) (is (= '({:col 20 :file "<stdin>" :level :error :message "duplicate key #{1 3 :foo}" :row 1}) (lint! "{#{1 :foo 3} \"bar\" #{1 3 :foo} 12}"))) (is (= '({:col 23 :file "<stdin>" :level :error :message "duplicate key #{1 'baz :foo}" :row 1}) (lint! "{#{1 :foo 'baz} \"bar\" #{1 'baz :foo} 12}"))) (is (= '({:col 23 :file "<stdin>" :level :error :message "duplicate key #{1 'baz :foo}" :row 1}) (lint! "{'#{1 :foo baz} \"bar\" #{1 'baz :foo} 12}"))) (is (= '({:col 14 :file "<stdin>" :level :error :message "duplicate key {1 2}" :row 1}) (lint! "{{1 2} \"bar\" {1 2} 12}"))) (is (= '({:col 24 :file "<stdin>" :level :error :message "duplicate key {1 2 'foo :bar}" :row 1}) (lint! "{'{1 2 foo :bar} \"bar\" {1 2 'foo :bar} 12}"))) (is (= '({:col 37 :file "<stdin>" :level :error :message "duplicate key '{1 {:foo #{3 4} bar (1 2)}}" :row 1}) (lint! "{{1 {:foo #{3 4} 'bar [1 2]}} \"bar\" '{1 {:foo #{3 4} bar (1 2)}} 12}")))) (deftest map-missing-value (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "missing value for key :b"}) (lint! "{:a 1 :b}"))) (is (= '({:file "<stdin>", :row 1, :col 14, :level :error, :message "missing value for key :a"}) (lint! "(let [x {:a {:a }}] x)"))) (is (= '({:file "<stdin>", :row 1, :col 15, :level :error, :message "missing value for key :a"}) (lint! "(loop [x {:a {:a }}] x)"))) (is (= '({:file "<stdin>", :row 1, :col 10, :level :error, :message "missing value for key :post"}) (lint! "(fn [x] {:post} x)"))) (assert-submaps '({:row 1, :col 22, :level :error, :message "missing value for key :c"}) (lint! "(let [{:keys [:a :b] :c} {}] [a b])"))) (deftest set-duplicate-keys-test (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "duplicate set element 1"}) (lint! "#{1 2 1}"))) (is (empty? (lint! "(let [foo 1] #{'foo foo})")))) (deftest macroexpand-test (assert-submap {:file "<stdin>", :row 1, :col 8, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(-> {} select-keys)"))) (assert-submap {:file "<stdin>", :row 1, :col 8, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(-> {} (select-keys))"))) (assert-submap {:file "<stdin>", :row 1, :col 9, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(->> {} select-keys)"))) (assert-submap {:file "<stdin>", :row 1, :col 9, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(->> {} (select-keys))"))) (testing "cats" (is (seq (lint! "(ns foo (:require [cats.core :as m])) (m/->= (right {}) (select-keys))"))) (is (seq (lint! "(ns foo (:require [cats.core :as m])) (m/->>= (right {}) (select-keys))")))) (testing "with CLJC" (is (empty? (lint! "(-> 1 #?(:clj inc :cljs inc))" "--lang" "cljc"))) (assert-submap {:file "<stdin>", :row 1, :col 15, :level :error, :message "java.lang.Math/pow is called with 1 arg but expects 2"} (first (lint! "(-> 1 #?(:clj (Math/pow)))" "--lang" "cljc")))) (testing "with type hints" (assert-submap {:file "<stdin>", :row 1, :col 60, :level :error, :message "clojure.string/includes? is called with 1 arg but expects 2"} (first (lint! "(ns foo (:require [clojure.string])) (-> \"foo\" ^String str clojure.string/includes?)"))) (assert-submap {:file "<stdin>", :row 1, :col 12, :level :error, :message "duplicate key :a"} (first (lint! "(-> ^{:a 1 :a 2} [1 2 3])")))) (testing "macroexpansion of anon fn literal" (assert-submaps '({:file "<stdin>", :row 1, :col 2, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"}) (lint! "#(select-keys %)")) (is (empty? (lint! "(let [f #(apply println %&)] (f 1 2 3 4))"))) (testing "fix for issue #181: the let in the expansion is resolved to clojure.core and not the custom let" (assert-submaps '({:file "<stdin>", :row 2, :col 41, :level :error, :message "missing value for key :a"}) (lint! "(ns foo (:refer-clojure :exclude [let])) (defmacro let [_]) #(println % {:a})"))))) (deftest schema-test (assert-submaps '({:file "corpus/schema/calls.clj", :row 4, :col 1, :level :error, :message "schema.defs/verify-signature is called with 0 args but expects 3"} {:file "corpus/schema/calls.clj", :row 4, :col 1, :level :error, :message "#'schema.defs/verify-signature is private"} {:file "corpus/schema/defs.clj", :row 10, :col 1, :level :error, :message "schema.defs/verify-signature is called with 2 args but expects 3"} {:file "corpus/schema/defs.clj", :row 12, :col 1, :level :error, :message "Invalid function body."}) (lint! (io/file "corpus" "schema") '{:linters {:unresolved-symbol {:level :error}}})) (is (empty? (lint! "(ns foo (:require [schema.core :refer [defschema]])) (defschema foo nil) foo" '{:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(ns yyyy (:require [schema.core :as s])) (s/fn my-identity :- s/Any [x :- s/Any] x)" '{:linters {:unresolved-symbol {:level :error}}})))) (deftest in-ns-test (assert-submaps '({:file "corpus/in-ns/base_ns.clj", :row 5, :col 1, :level :error, :message "in-ns.base-ns/foo is called with 3 args but expects 0"} {:file "corpus/in-ns/in_ns.clj", :row 5, :col 1, :level :error, :message "in-ns.base-ns/foo is called with 3 args but expects 0"}) (lint! (io/file "corpus" "in-ns"))) (assert-submap {:file "<stdin>", :row 1, :col 55, :level :error, :message "foo/foo-2 is called with 3 args but expects 0"} (first (lint! "(ns foo) (defn foo-1 [] (in-ns 'bar)) (defn foo-2 []) (foo-2 1 2 3)"))) (is (empty? (lint! "(let [ns-name \"user\"] (in-ns ns-name))" '{:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(in-ns 'foo) (clojure.core/let [x 1])" '{:linters {:unresolved-symbol {:level :error}}})))) (deftest recur-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(defn foo [x] (recur x x))")) (assert-submaps '({:file "<stdin>", :row 1, :col 9, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(fn [x] (recur x x))")) (is (empty? (lint! "(defn foo [x & xs] (recur x [x]))"))) (is (empty? (lint! "(defn foo ([]) ([x & xs] (recur x [x])))"))) (is (empty? (lint! "(fn ([]) ([x y & xs] (recur x x [x])))"))) (is (empty? (lint! "(loop [x 1 y 2] (recur x y))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "recur argument count mismatch (expected 2, got 3)"}) (lint! "(loop [x 1 y 2] (recur x y x))")) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1))"))) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (defn foo [x y] (go-loop [x nil] (recur 1)))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 74, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (assert-submaps '({:file "<stdin>", :row 1, :col 85, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require-macros [cljs.core.async.macros :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (assert-submaps '({:file "<stdin>", :row 1, :col 78, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require-macros [cljs.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (is (empty? (lint! "#(recur)"))) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [thread]])) (thread (recur))"))) (is (empty? (lint! "(ns clojure.core.async) (defmacro thread [& body]) (thread (when true (recur)))"))) (is (empty? (lint! "(fn* ^:static cons [x seq] (recur 1 2))"))) (is (empty? (lint! " (defprotocol IFoo (-foo [_])) (defrecord Foo [] IFoo (-foo [_] (let [_f (fn [x] (recur x))] (recur)))) (deftype FooType [] java.lang.Runnable (run [_] (let [_f (fn [x] (recur x))] (recur)))) (reify IFoo (-foo [_] (let [_f (fn [x] (recur x))] (loop [x 1] (recur x)) (recur)))) (extend-protocol IFoo Number (-foo [this] (recur this))) (extend-type Number IFoo (-foo [this] (recur this)))"))) (is (empty? (lint! "(defrecord Foo [] clojure.lang.ILookup (valAt [_ _] (letfn [(_foo [_x] (recur 1))])))")))) (deftest lint-as-test (assert-submaps '({:file "<stdin>", :row 1, :col 93, :level :error, :message "foo/foo is called with 3 args but expects 1"}) (lint! "(ns foo) (defmacro my-defn [name args & body] `(defn ~name ~args ~@body)) (my-defn foo [x]) (foo 1 2 3)" '{:lint-as {foo/my-defn clojure.core/defn}})) (assert-submaps '[{:level :error, :message #"fully qualified symbol"}] (lint! "(require '[foo.bar]) (foo.bar/when-let)" '{:lint-as {foo.bar/when-let when-let}})) (is (empty? (lint! "(ns foo) (defmacro deftest [name & body] `(defn ~name [] ~@body)) (deftest foo)" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {foo/deftest clojure.test/deftest}}))) (is (empty? (lint! (io/file "corpus" "lint_as_for.clj") '{:linters {:unresolved-symbol {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [weird.lib :refer [weird-def]])) (weird-def foo x y z) foo" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {weird.lib/weird-def clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require [orchestra.core :refer [defn-spec]])) (defn- foo []) (defn-spec my-inc integer? [a integer?] ; Each argument is followed by its spec. (foo) ;; private function is used (inc \"foo\") ;; type mismatch ignored ) (my-inc)" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {orchestra.core/defn-spec clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require [rum.core :as rum])) (rum/defcs stateful < (rum/local 0 ::key) [state label] (let [local-atom (::key state)] [:div { :on-click (fn [_] (swap! local-atom inc)) } label \": \" @local-atom])) (stateful) " '{:linters {:unresolved-symbol {:level :warning}} :lint-as {rum.core/defcs clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require plumbing.core)) (let [live? true] (-> {} (plumbing.core/?> live? (assoc :live live?)))) " '{:lint-as {plumbing.core/?> clojure.core/cond->}})))) (deftest letfn-test (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"}) (lint! "(letfn [] (select-keys))")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "f1 is called with 0 args but expects 1"}) (lint! "(letfn [(f1 [_])] (f1))")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "recur argument count mismatch (expected 1, got 0)"}) (lint! "(letfn [(f1 [_] (recur))])")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "f2 is called with 0 args but expects 1"}) (lint! "(letfn [(f1 [_] (f2)) (f2 [_])])"))) (deftest namespace-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 5, :level :error, :message "namespace name expected"}) (lint! "(ns \"hello\")")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "Unparsable libspec: [foo oh-no :as]"}) (lint! "(ns foo (:require [foo oh-no :as]))" {:linters {:syntax {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "Unparsable libspec: [foo oh-no :as]"}) (lint! "(require '[foo oh-no :as])" {:linters {:syntax {:level :error}}}))) (deftest call-as-use-test (is (empty? (lint! "(extend-protocol clojure.lang.IChunkedSeq (internal-reduce [s f val] (recur (chunk-next s) f val)))")))) (deftest redefined-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "redefined var #'user/foo"}) (lint! "(defn foo []) (defn foo [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 29, :level :warning, :message "redefined var #'user/foo"}) (lint! "(let [bar 42] (def foo bar) (def foo bar))")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "inc already refers to #'clojure.core/inc"}) (lint! "(defn inc [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "inc already refers to #'cljs.core/inc"}) (lint! "(defn inc [])" "--lang" "cljs")) (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace bar is required but never used"} {:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'bar/x is referred but never used"} {:file "<stdin>", :row 1, :col 38, :level :warning, :message "x already refers to #'bar/x"}) (lint! "(ns foo (:require [bar :refer [x]])) (defn x [])")) (is (empty? (lint! "(defn foo [])"))) (is (empty? (lint! "(ns foo (:refer-clojure :exclude [inc])) (defn inc [])"))) (is (empty? (lint! "(declare foo) (def foo 1)"))) (is (empty? (lint! "(def foo 1) (declare foo)"))) (is (empty? (lint! "(if (odd? 3) (def foo 1) (def foo 2))"))) (testing "disable linter in comment" (is (empty? (lint! "(comment (def x 1) (def x 2))"))))) (deftest unreachable-code-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "unreachable code"}) (lint! "(cond :else 1 (odd? 1) 2)"))) (deftest dont-crash-analyzer-test (doseq [example ["(let)" "(if-let)" "(when-let)" "(loop)" "(doseq)"] :let [prog (str example " (inc)")]] (is (some (fn [finding] (submap? {:file "<stdin>", :row 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} finding)) (lint! prog))))) (deftest for-doseq-test (assert-submaps [{:col 8 :message #"vector"}] (lint! "(doseq 1 2)")) (is (empty? (lint! "(for [select-keys []] (select-keys 1))"))) (is (empty? (lint! "(doseq [select-keys []] (select-keys 1))")))) (deftest keyword-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "keyword :x is called with 3 args but expects 1 or 2"}) (lint! "(:x 1 2 3)")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "keyword :b/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo) (:b/x {:bar/x 1} 1 2)")) (assert-submaps '({:file "<stdin>", :row 1, :col 33, :level :error, :message "keyword :bar/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo (:require [bar :as b])) (::b/x {:bar/x 1} 1 2)")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "keyword :foo/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo) (::x {::x 1} 2 3)")) (is (empty? (lint! "(select-keys (:more 1 2 3 4) [])" "--config" "{:linters {:invalid-arity {:skip-args [clojure.core/select-keys]}}}")))) (deftest map-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "map is called with 0 args but expects 1 or 2"}) (lint! "({:a 1})")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "map is called with 3 args but expects 1 or 2"}) (lint! "({:a 1} 1 2 3)")) (is (empty? (lint! "(foo ({:a 1} 1 2 3))" "--config" "{:linters {:invalid-arity {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest symbol-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "symbol is called with 0 args but expects 1 or 2"}) (lint! "('foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "symbol is called with 3 args but expects 1 or 2"}) (lint! "('foo 1 2 3)")) (is (empty? (lint! "(foo ('foo 1 2 3))" "--config" "{:linters {:invalid-arity {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest vector-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Vector can only be called with 1 arg but was called with: 0"} {:file "<stdin>", :row 1, :col 13, :level :error, :message "Vector can only be called with 1 arg but was called with: 2"}) (lint! "([]) ([] 1) ([] 1 2)"))) (deftest not-a-function-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a boolean is not a function"}) (lint! "(true 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a string is not a function"}) (lint! "(\"foo\" 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a number is not a function"}) (lint! "(1 1)")) (is (empty? (lint! "'(1 1)"))) (is (empty? (lint! "(foo (1 1))" "--config" "{:linters {:not-a-function {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest cljs-self-require-test (is (empty? (lint! (io/file "corpus" "cljs_self_require.cljc"))))) (deftest unsupported-binding-form-test (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "unsupported binding form :x"}) (lint! "(defn foo [:x])")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "unsupported binding form a/a"}) (lint! "(defn foo [a/a])")) (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "unsupported binding form 1"}) (lint! "(let [1 1])")) (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "unsupported binding form (x)"}) (lint! "(let [(x) 1])")) (is (empty? (lint! "(fn [[x y z] :as x])"))) (is (empty? (lint! "(fn [[x y z & xs]])"))) (is (empty? (lint! "(let [^String x \"foo\"])")))) (deftest non-destructured-binding-test (doseq [input ["(let [{:keys [:i] :or {i 2 j 3}} {}] i)" "(let [{:or {i 2 j 3} :keys [:i]} {}] i)"]] (assert-submaps '({:file "<stdin>", :row 1 :level :warning, :message "j is not bound in this destructuring form"}) (lint! input {:linters {:unused-binding {:level :warning}}})))) (deftest output-test (is (str/starts-with? (with-in-str "" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:summary true}}"))) "linting took")) (is (not (str/starts-with? (with-in-str "" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:summary false}}"))) "linting took"))) (is (= '({:filename "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} {:filename "<stdin>", :row 1, :col 6, :level :error, :message "clojure.core/dec is called with 0 args but expects 1"}) (let [parse-fn (fn [line] (when-let [[_ file row col level message] (re-matches #"(.+):(\d+):(\d+): (\w+): (.*)" line)] {:filename file :row (Integer/parseInt row) :col (Integer/parseInt col) :level (keyword level) :message message})) text (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:format :text}}")))] (keep parse-fn (str/split-lines text))))) (doseq [[output-format parse-fn] [[:edn edn/read-string] [:json #(cheshire/parse-string % true)]] summary? [true false]] (let [output (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s :summary %s}}" output-format summary?)))) parsed (parse-fn output)] (assert-submap {:findings [{:type (case output-format :edn :invalid-arity "invalid-arity"), :filename "<stdin>", :row 1, :col 1, :end-row 1, :end-col 6, :level (case output-format :edn :error "error"), :message "clojure.core/inc is called with 0 args but expects 1"} {:type (case output-format :edn :invalid-arity "invalid-arity"), :filename "<stdin>", :row 1, :col 6, :end-row 1, :end-col 11, :level (case output-format :edn :error "error"), :message "clojure.core/dec is called with 0 args but expects 1"}]} parsed) (if summary? (assert-submap '{:error 2} (:summary parsed)) (is (nil? (find parsed :summary)))))) (doseq [[output-format parse-fn] [[:edn edn/read-string] [:json #(cheshire/parse-string % true)]]] (let [output (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s}}" output-format)))) parsed (parse-fn output)] (is (map? parsed)))) (testing "JSON output escapes special characters" (let [output (with-in-str "{\"foo\" 1 \"foo\" 1}" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s}}" :json)))) parsed (cheshire/parse-string output true)] (is (map? parsed))) (let [output (with-in-str "{:a 1}" (with-out-str (main "--cache" "false" "--lint" "\"foo\".clj" "--config" (format "{:output {:format %s}}" :json)))) parsed (cheshire/parse-string output true)] (is (map? parsed))))) (deftest show-rule-name-in-message-output-test (letfn [(run-main [config] (->> (main "--cache" "false" "--lint" "-" "--config" config) (with-out-str) (with-in-str "(inc)(dec)") (str/split-lines) ;; dropping the 'linting took' line (drop-last)))] (testing "with :show-rule-name-in-message true" (doseq [output-line (run-main "{:output {:linter-name true}}") :let [[_ begin] (re-matches #".*(<stdin>:\d+:\d+).*" output-line)]] (testing (str "output line '" begin "' ") (is (str/ends-with? output-line "[:invalid-arity]") "has rule name")))) (testing "with :show-rule-name-in-message false" (doseq [output-line (run-main "{:output {:show-rule-name-in-message false}}") :let [[_ begin] (re-matches #".*(<stdin>:\d+:\d+).*" output-line)]] (testing (str "output line '" begin "' ") (is (not (str/ends-with? output-line "[:invalid-arity]")) "doesn't have rule name")))))) (deftest defprotocol-test (assert-submaps '({:file "corpus/defprotocol.clj", :row 14, :col 1, :level :error, :message "defprotocol/-foo is called with 4 args but expects 1, 2 or 3"}) (lint! (io/file "corpus" "defprotocol.clj"))) (is (empty? (lint! " (ns repro (:import [clojure.lang IReduceInit])) (defprotocol Db (-list-resources ^IReduceInit [db type start-id]))")))) (deftest defrecord-test (assert-submaps '({:file "corpus/defrecord.clj", :row 6, :col 23, :level :warning, :message "unused binding this"} {:file "corpus/defrecord.clj", :row 8, :col 1, :level :error, :message "defrecord/->Thing is called with 3 args but expects 2"} {:file "corpus/defrecord.clj", :row 9, :col 1, :level :error, :message "defrecord/map->Thing is called with 2 args but expects 1"}) (lint! (io/file "corpus" "defrecord.clj") "--config" "{:linters {:unused-binding {:level :warning}}}")) (is (empty? (lint! (io/file "corpus" "record_protocol_metadata.clj") {:unused-import {:level :warning}})))) (deftest deftype-test (assert-submaps '({:file "corpus/deftype.cljs", :row 9, :col 10, :level :warning, :message "unused binding coll"} {:file "corpus/deftype.cljs", :row 17, :col 16, :level :warning, :message "unused binding coll"}) (lint! (io/file "corpus" "deftype.cljs") "--config" "{:linters {:unused-binding {:level :warning}}}"))) (deftest defmulti-test (assert-submaps '({:file "corpus/defmulti.clj", :row 7, :col 12, :level :error, :message "Unresolved symbol: greetingx"} {:file "corpus/defmulti.clj", :row 7, :col 35, :level :warning, :message "unused binding y"} {:file "corpus/defmulti.clj", :row 13, :col 24, :level :warning, :message "unused binding y"} {:file "corpus/defmulti.clj", :row 13, :col 39, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! (io/file "corpus" "defmulti.clj") '{:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})) (is (empty? (lint! "(defmulti foo)")))) (deftest misc-false-positives-test (is (empty? (lint! "(cond-> 1 true (as-> x (inc x)))"))) (is (empty? (lint! "(ns foo) (defn foo [] (ns bar (:require [clojure.string :as s])))"))) (is (empty? (lint! "(defn foo [x y z] ^{:a x :b y :c z} [1 2 3])"))) (is (empty? (lint! "(fn [^js x] x)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(= '`+ (read-string \"`+\"))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "core.rrb-vector.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(defn get-email [{email :email :as user :or {email user}}] email)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(ns repro (:require [clojure.string :refer [starts-with?]])) (defn foo {:test-fn starts-with?} [])" {:linters {:unresolved-symbol {:level :error}}}))) There actually still is issue # 450 that would cause this error . But we had ;; special handling for constructor calls before and we don't want new errors when PR # 557 is merged . (is (empty? (lint! "(import my.ns.Obj) (Obj.)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "project.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "^{:a #js [1 2 3]} [1 2 3]" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "metadata.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(.log js/console ^js #js [1 2 3])" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(bound-fn [x] x)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "nested_syntax_quote.clj") {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(doseq [[ns-sym _ alias-sym] (cons t ts)] (create-ns ns-sym) (alias alias-sym ns-sym))" {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! " (ns app.repro (:import java.lang.String)) (defmacro test-macro [] ;^String (str \"a\" \"b\") `(let [test# ^String (str \"a\" \"b\")] test#))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(when-let [x 1] x x x)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(defn foo [x] (if-let [x 1] x x))" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}}))) (is (empty? (lint! "goog.global" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(fn [x] (* ^number x 1))" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! " (clojure.core/let ^{:row 15, :col 2, :line 1} [^{:row 15, :col 3} x 1] ^{:row 16, :col 2} (^{:row 16, :col 3} inc ^{:row 16, :col 7} x))" {:linters {:type-mismatch {:level :error}}}))) (is (empty? (lint! "(def x) (doto x)"))) (is (empty? (lint! "(def ^:private a 1) (let [{:keys [a] :or {a a}} {}] a)" {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(scala.Int/MinValue)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(require '[clojure.string :as s]) '::s/foo"))) (is (empty? (lint! "(simple-benchmark [x 100] (+ 1 2 x) 10)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(defn foo [_a _b] (dosync (recur)))"))) (is (empty? (lint! "(defn foo [_a _b] (lazy-seq (recur)))"))) (is (empty? (lint! "(defn foo [_a _b] (lazy-cat (recur)))"))) (is (empty? (lint! "(ns foo (:refer-clojure :only [defn]))"))) (is (empty? (lint! " (ns kitchen-async.promise (:refer-clojure :exclude [promise ->]) (:require [clojure.core :as cc])) (defmacro promise [] (cc/let [_ (cond-> [] true (conj 1))])) (defmacro -> [])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(fn [^clj x] ^clj x)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! " (ns foo) (gen-class :name foo.Engine :state state :init init :methods [[eval [java.util.HashMap String] java.util.Map]])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! " (exists? foo.bar/baz)" {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(def ^{:macro true} foo (fn* [_ _] (map (fn* []) [])))"))) (is (empty? (lint! "::f._al"))) (is (empty? (lint! "(with-precision 6 :rounding CEILING (+ 3.5555555M 1))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest tagged-literal-test (is (empty? (lint! "(let [x 1] #js {:a x})" {:linters {:unused-binding {:level :warning}}} "--lang" "cljs"))) (is (empty? (lint! "(set! *default-data-reader-fn* tagged-literal) #read-thing ([1 2 3] 4 5 6 (inc :foo))" ))) (is (empty? (lint! "(let [foo \"2022-02-10\" bar #time/date foo] bar)" {:linters {:unused-binding {:level :warning}}})))) (deftest data-readers-config-test (is (empty? (lint! (io/file "corpus/data_readers.clj") {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}}))) (is (empty? (lint! (io/file "corpus/data_readers.cljc") {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}})))) (deftest extend-type-specify-test (assert-submaps '({:file "<stdin>", :row 2, :col 25, :level :error, :message "Unresolved symbol: x"}) (lint! " (specify! #js {:current x} IDeref (-deref [this] (.-current ^js this)))" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")) (is (empty? (lint! " (extend-type String clojure.lang.IDeref (deref [this] this))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest js-property-access-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Unresolved symbol: foo"}) (lint! "foo.bar" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")) (is (empty? (lint! "(let [foo #js{}] foo.bar (foo.bar)) (def bar #js {}) bar.baz (bar.baz)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")))) (deftest amap-test (is (empty? (lint! " (def an-array (int-array 25000 (int 0))) (amap ^ints an-array idx ret (+ (int 1) (aget ^ints an-array idx)))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(let [nodes (into-array [1 2 3]) nodes (amap nodes idx _ idx)] nodes)" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})))) (deftest proxy-super-test (is (empty? (lint! " (proxy [java.util.ArrayList] [] (add [x] (let [^ArrayList this this] (proxy-super add x)))) " {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! " (proxy [ArrayList] [] (let [xx x] (proxy-super add xx)))" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})))) (deftest with-redefs-test (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "with-redefs requires a vector for its binding"}) (lint! "(with-redefs 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "with-redefs binding vector requires even number of forms"}) (lint! "(with-redefs [clojure.core/inc])")) (is (empty? (lint! " (ns foo) (defn- private-fn []) (private-fn) (ns bar (:require [foo])) (with-redefs [foo/private-fn (fn [])] (+ 1 2 3))"))) (is (empty? (lint! (io/file "corpus" "with_redefs.clj")))) (testing "binding is linted the same way as with-redefs" (is (empty? (lint! "(ns foo) (def ^:private ^:dynamic *foo*) *foo* (ns bar (:require [foo])) (binding [foo/*foo* 2])"))))) (deftest file-error-test (assert-submaps '({:file "not-existing.clj", :row 0, :col 0, :level :error, :message "file does not exist"}) (lint! (io/file "not-existing.clj")))) (deftest edn-test (assert-submaps '({:file "corpus/edn/edn.edn", :row 1, :col 10, :level :error, :message "duplicate key a"}) (lint! (io/file "corpus" "edn")))) (deftest spec-test (assert-submaps [{:file "corpus/spec_syntax.clj", :row 9, :col 9, :level :error, :message "expected symbol"} {:file "corpus/spec_syntax.clj", :row 9, :col 11, :level :error, :message "missing value for key :args"} {:file "corpus/spec_syntax.clj", :row 11, :col 13, :level :error, :message "unknown option :xargs"} #_{:file "corpus/spec_syntax.clj", :row 20, :col 9, :level :error, :message "Unresolved symbol: xstr/starts-with?"} {:file "corpus/spec_syntax.clj", :row 30, :col 15, :level :error, :message "unknown option ::opt"} {:file "corpus/spec_syntax.clj", :row 31, :col 15, :level :error, :message "unknown option ::opt-un"} {:file "corpus/spec_syntax.clj", :row 32, :col 15, :level :error, :message "unknown option ::req"} {:file "corpus/spec_syntax.clj", :row 33, :col 15, :level :error, :message "unknown option ::req-un"}] (lint! (io/file "corpus" "spec_syntax.clj") '{:linters {:unresolved-symbol {:level :error} :unused-namespace {:level :error}}}))) (deftest hashbang-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! "#!/usr/bin/env clojure\n(inc)"))) (deftest GH-301-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :error, :message "duplicate key :&::before"}) (lint! "{:&::before 1 :&::before 1}"))) (deftest misplaced-docstring-test (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :warning, :message "Misplaced docstring."}) (lint! "(defn f [x] \"dude\" x)" {:linters {:redundant-expression {:level :off}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :warning, :message "Misplaced docstring."}) (lint! "(defn foo [x y] \"dude \" [x y])" {:linters {:redundant-expression {:level :off}}})) (is (empty? (lint! "(defn f [x] \"dude\")"))) ;; for now this is empty, but in the next version we might warn about the ;; string "dude" being a discarded value (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "Unused value: \"dude\""}) (lint! "(defn f \"dude\" [x] \"dude\" x)" {:linters {:unused-value {:level :warning}}}))) (deftest defn-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Invalid function body."}) (lint! "(defn f \"dude\" x) (f 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "Invalid function body."}) (lint! "(defn oops ())")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "Function arguments should be wrapped in vector."}) (lint! "(defn oops (x))")) (assert-submaps '({:file "<stdin>", :row 1, :col 22, :level :error, :message "More than one function overload with arity 2."}) (lint! "(defn fun ([x y] x) ([y x] y))")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "More than one function overload with arity 1."}) (lint! "(fn ([x] x) ([y] y))")) (is (empty? (lint! "(defn ok-fine [] {:this :is :not :attr-map2 :meta :data})"))) (testing "multi-arity" (is (empty? (lint! "(defn- second-attr-map-private-defn ([]) {:look :metadata!}) (second-attr-map-private-defn)"))) (is (empty? (lint! "(defn second-attr-map ([]) ([x] x) {:look :metadata!})"))) (is (empty? (lint! "(defmacro ^{:leading :meta} second-attr-map-macro {:attr1 :meta} ([]) ([x] x) {:attr2 :metadata!})"))) (assert-submaps '({:file "<stdin>" :row 1 :col 27 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) ([x] x) [:not :good])")) (assert-submaps '({:file "<stdin>" :row 1 :col 19 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) {:not :good} {:look metadata!})")) (assert-submaps '({:file "<stdin>" :row 1 :col 19 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) ({:not :good}))")) (assert-submaps2 '({:file "<stdin>" :row 1 :col 21 :level :error :message "Only one varargs binding allowed but got: xs, ys"}) (lint! "(defn foo [x y & xs ys] [x y xs ys])")))) (deftest not-empty?-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "use the idiom (seq x) rather than (not (empty? x))"}) (lint! "(not (empty? [1]))"))) (deftest deprecated-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 28, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(defn ^:deprecated foo []) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 35, :level :warning, :message "#'user/foo is deprecated since 1.0"}) (lint! "(defn foo {:deprecated \"1.0\"} []) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "#'clojure.core/agent-errors is deprecated since 1.2"}) (lint! "(agent-errors 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(def ^:deprecated foo (fn [])) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(def ^:deprecated foo (fn [])) foo")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "#'clojure.core/replicate is deprecated since 1.3"}) (lint! "replicate")) (assert-submaps '({:file "<stdin>", :row 1, :col 83, :level :warning, :message "#'user/deprecated-multi is deprecated"}) (lint! "(defmulti deprecated-multi \"Docstring\" {:private true :deprecated true} identity) (deprecated-multi)")) (testing "config" (assert-submaps '({:file "corpus/deprecated_var.clj", :row 9, :col 30, :level :warning, :message "#'foo.foo/deprecated-fn is deprecated"} {:file "corpus/deprecated_var.clj", :row 10, :col 1, :level :warning, :message "#'foo.foo/deprecated-fn is deprecated"}) (lint! (io/file "corpus" "deprecated_var.clj") '{:linters {:deprecated-var {:exclude {foo.foo/deprecated-fn {:namespaces [foo.bar "bar\\.*"] :defs [foo.baz/allowed "foo\\.baz/ign\\.*"]}}}}}))) (assert-submaps '({:file "<stdin>", :row 2, :col 40, :level :warning, :message "#'user/my-deprecated-var is deprecated since deprecation message"}) (lint! "(def ^#?(:clj {:deprecated \"deprecation message\"} :cljs {}) my-deprecated-var :bla) my-deprecated-var" "--lang" "cljc")) (is (empty? (lint! "(defn ^:deprecated foo [] (foo))"))) (is (empty? (lint! "(def ^:deprecated foo (fn [] (foo)))"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}) (def ^:deprecated foo) foo"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}) (def ^:deprecated foo) foo"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:exclude {dude/foo {:namespaces [dude]}}}}}}) (def ^:deprecated foo) foo")))) (deftest unused-referred-var-test (assert-submaps '({:file "corpus/unused_referred_var.clj", :row 2, :col 50, :level :warning, :message "#'clojure.string/ends-with? is referred but never used"}) (lint! (io/file "corpus" "unused_referred_var.clj"))) (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace bar is required but never used"}) (lint! "(ns foo (:require [bar :refer [bar]]))" '{:linters {:unused-referred-var {:exclude {bar [bar]}}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 23, :level :warning, :message "namespace aws-sdk is required but never used"} {:file "<stdin>", :row 1, :col 42, :level :warning, :message "#'aws-sdk/AWS is referred but never used"}) (lint! "(ns lambda (:require [\"aws-sdk\" :default AWS]))" "--lang" "cljs")) (assert-submaps '({:file "<stdin>", :row 1, :col 36, :level :warning, :message "#'bar/v1 is referred but never used"}) (lint! "(ns foo (:require [bar :rename {v1 v2}])) ::bar/x")) (is (empty? (lint! "(ns foo (:require [bar :refer [bar]])) (apply bar 1 2 [3 4])"))) (is (empty? (lint! "(ns ^{:clj-kondo/config '{:linters {:unused-referred-var {:exclude {bar [bar]}}}}} foo (:require [bar :refer [bar] :as b])) (apply b/x 1 2 [3 4])")))) (deftest duplicate-require-test (assert-submaps '({:file "<stdin>", :row 1, :col 43, :level :warning, :message "duplicate require of clojure.string"}) (lint! "(ns foo (:require [clojure.string :as s] [clojure.string :as str])) s/join")) (assert-submaps '({:file "<stdin>", :row 1, :col 54, :level :warning, :message "duplicate require of clojure.string"}) (lint! "(ns foo (:require [clojure.string :as s])) (require 'clojure.string) s/join")) (is (empty? (lint! "(ns foo (:require-macros [cljs.core :as core]) (:require [cljs.core :as core])) core/conj" "--lang" "cljs")))) (deftest refer-all-test (assert-submaps '({:file "corpus/compojure/consumer.clj", :row 6, :col 1, :level :error, :message "compojure.core/defroutes is called with 0 args but expects 1 or more"} {:file "corpus/compojure/consumer.clj", :row 7, :col 1, :level :error, :message "compojure.core/GET is called with 0 args but expects 2 or more"} {:file "corpus/compojure/consumer.clj", :row 8, :col 1, :level :error, :message "compojure.core/POST is called with 0 args but expects 2 or more"} {:file "corpus/compojure/consumer.clj", :row 14, :col 8, :level :error, :message "Unresolved symbol: x"}) (lint! (io/file "corpus" "compojure") {:linters {:unresolved-symbol {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 31, :level :warning, :message "use alias or :refer"}) (lint! "(ns foo (:require [bar :refer :all]))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 42, :level :warning, :message "use alias or :refer [capitalize join]"}) (lint! "(ns foo (:require [clojure.string :refer :all])) (defn foo [strs] (join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 48, :level :warning, :message "use alias or :refer [capitalize]"}) (lint! "(ns foo (:require [clojure.string :as s :refer :all])) (defn foo [strs] (s/join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 56, :level :warning, :message "use alias or :refer [capitalize join]"}) (lint! "(ns foo (:require [clojure.string :refer [join] :refer :all])) (defn foo [strs] (join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "corpus/use.clj", :row 4, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 9, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 14, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 19, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 19, :col 10, :level :warning, :message "namespace clojure.string is required but never used"} {:file "corpus/use.clj", :row 19, :col 32, :level :warning, :message "#'clojure.string/join is referred but never used"} {:file "corpus/use.clj", :row 22, :col 2, :level :warning, :message "use require with alias or :refer [join]"} {:file "corpus/use.clj", :row 22, :col 8, :level :warning, :message "namespace clojure.string is required but never used"} {:file "corpus/use.clj", :row 22, :col 30, :level :warning, :message "#'clojure.string/join is referred but never used"} {:file "corpus/use.clj", :row 25, :col 2, :level :warning, :message "use require with alias or :refer [join]"} {:file "corpus/use.clj", :row 29, :col 2, :level :warning, :message "use require with alias or :refer [join]"}) (lint! (io/file "corpus" "use.clj") {:linters {:refer-all {:level :warning} :use {:level :warning}}})) (is (empty? (lint! "(require '[clojure.test :refer :all])" '{:linters {:refer-all {:level :warning :exclude [clojure.test]}}}))) (testing "vars from linted or built-in namespaces are known with :refer :all, see #1010" (is (empty? (lint! " (ns deftest-resolve-test-name-fail (:require [clojure.string :refer :all] [clojure.test :refer :all])) (deftest my-test (is (blank? \"\"))) " '{:linters {:refer-all {:level :off} :unresolved-symbol {:level :error}}}))))) (deftest canonical-paths-test (testing "single file" (let [f (io/file (first (map :file (lint! (io/file "corpus" "use.clj") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f))))) (testing "directory" (let [f (io/file (first (map :file (lint! (io/file "corpus" "private") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f))))) (testing "jar file" (let [f (io/file (first (map :file (lint! (io/file (System/getProperty "user.home") ".m2" "repository" "org" ".." "org" ;; note: not canonical "clojure" "spec.alpha" "0.2.176" "spec.alpha-0.2.176.jar") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f)))))) (deftest import-vars-test (assert-submaps '({:file "corpus/import_vars.clj", :row 23, :col 1, :level :error, :message "clojure.walk/prewalk is called with 0 args but expects 2"} {:file "corpus/import_vars.clj", :row 24, :col 1, :level :error, :message "app.core/foo is called with 0 args but expects 1"}) (lint! (io/file "corpus" "import_vars.clj") {:linters {:unresolved-symbol {:level :error}}})) (testing "import-vars with vector works when using cache" (when (.exists (io/file ".clj-kondo")) (rename-path ".clj-kondo" ".clj-kondo.bak")) (make-dirs ".clj-kondo") (lint! "(ns app.core) (defn foo [])" "--cache") (lint! "(ns app.api (:require [potemkin :refer [import-vars]])) (import-vars [app.core foo])" "--cache") (assert-submaps '({:file "<stdin>", :row 1, :col 49, :level :error, :message "app.core/foo is called with 1 arg but expects 0"}) (lint! "(ns consumer (:require [app.api :refer [foo]])) (foo 1)" "--cache")) (remove-dir ".clj-kondo") (when (.exists (io/file ".clj-kondo.bak")) (rename-path ".clj-kondo.bak" ".clj-kondo"))) (testing "import-vars with full qualified symbol with vector works when using cache" (when (.exists (io/file ".clj-kondo")) (rename-path ".clj-kondo" ".clj-kondo.bak")) (make-dirs ".clj-kondo") (lint! "(ns app.core) (defn foo []) (defn bar [])" "--cache") (lint! "(ns app.api (:require [potemkin :refer [import-vars]])) (import-vars app.core/foo app.core/bar)" "--cache") (assert-submaps '({:file "<stdin>", :row 1, :col 53, :level :error, :message "app.core/foo is called with 1 arg but expects 0"} {:file "<stdin>", :row 1, :col 61, :level :error, :message "app.core/bar is called with 1 arg but expects 0"}) (lint! "(ns consumer (:require [app.api :refer [foo bar]])) (foo 1) (bar 2)" "--cache")) (remove-dir ".clj-kondo") (when (.exists (io/file ".clj-kondo.bak")) (rename-path ".clj-kondo.bak" ".clj-kondo"))) (testing "aliases" (assert-submaps ' ({:file "<stdin>", :row 9, :col 10, :level :error, :message "clojure.string/starts-with? is called with 0 args but expects 2"} {:file "<stdin>", :row 9, :col 27, :level :error, :message "Unresolved var: i/x"}) (lint! " (ns importing-ns (:require [potemkin :refer [import-vars]] [clojure.string :as str])) (import-vars [str blank?, starts-with?]) (ns using-ns (:require [importing-ns :as i])) i/blank? (i/starts-with?) i/x " {:linters {:invalid-arity {:level :error} :unresolved-symbol {:level :error} :unresolved-var {:level :error} :type-mismatch {:level :error}}}))) (is (empty? (lint! " (ns dev.clj-kondo {:clj-kondo/config '{:linters {:missing-docstring {:level :warning}}}} (:require [potemkin :refer [import-vars]] [clojure.string])) (import-vars [clojure.string blank?, starts-with?, ends-with?, includes?])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! " (ns foo.bar) (defn foo []) ;; non-empty to generated ns cache ;; dynamically generated baz (ns foo (:require [foo.bar] [potemkin :refer [import-vars]])) (import-vars [foo.bar baz]) (ns bar (:require [foo])) foo/baz " {:linters {:unresolved-symbol {:level :error} :unresolved-var {:level :error}}}))) TODO ? for now just include duplicate lint - as #_(testing "lint-as works automatically with imported vars" (is (empty? (lint! " (ns foo.bar) (defmacro defsomething [name & body]) (ns foo (:require [potemkin :refer [import-vars]])) (import-vars [foo.bar defsomething]) (ns consumer (:require foo)) (foo/defsomething dude) " '{:lint-as {foo.bar/defsomething clojure.core/def} :linters {:unresolved-symbol {:level :error} :unresolved-var {:level :error}}}))))) (deftest potemkin-import-vars-cyclic-test (assert-submaps '({:file "<stdin>", :row 4, :col 1, :level :warning, :message "redefined var #'foo/foo"}) (lint! " (ns foo (:require [potemkin])) (defn foo []) (potemkin/import-vars [foo foo]) ")) (is (empty? (lint!" (ns foo (:require [bar])) (require '[potemkin]) (potemkin/import-vars [bar x]) (ns bar (:require [foo] [potemkin])) (potemkin/import-vars [foo x])")))) (deftest dir-with-source-extension-test (testing "analyses source in dir with source extension" (let [dir (io/file "corpus" "directory.clj") jar (io/file "corpus" "withcljdir.jar")] (assert-submaps '({:file "dirinjar.clj/arity.clj" , :row 1, :col 1, :level :error, :message "clojure.core/map is called with 0 args but expects 1, 2, 3, 4 or more"}) (lint! jar)) (assert-submaps '({:file "corpus/directory.clj/arity2.clj", :row 1, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! dir))))) (deftest core-async-alt-test (assert-submaps '({:file "corpus/core_async/alt.clj", :row 7, :col 9, :level :error, :message "Unresolved symbol: x1"} {:file "corpus/core_async/alt.clj", :row 7, :col 12, :level :error, :message "Unresolved symbol: x2"} {:file "corpus/core_async/alt.clj", :row 11, :col 24, :level :error, :message "clojure.string/join is called with 3 args but expects 1 or 2"} {:file "corpus/core_async/alt.clj", :row 12, :col 10, :level :error, :message "Unresolved symbol: x3"} {:file "corpus/core_async/alt.clj", :row 12, :col 13, :level :error, :message "Unresolved symbol: x4"}) (lint! (io/file "corpus" "core_async" "alt.clj") {:linters {:unresolved-symbol {:level :error}}}))) (deftest if-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Too few arguments to if."} {:file "<stdin>", :row 1, :col 6, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 15, :level :error, :message "Too many arguments to if."}) (lint! "(if) (if 1 1) (if 1 1 1 1)"))) (deftest if-not-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/if-not is called with 0 args but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/if-not is called with 4 args but expects 2 or 3"}) (lint! "(if-not) (if-not 1 1 1 1)")) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-not 1 1)" "--lang" lang)))) (deftest unused-private-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 25, :level :warning, :message "Unused private var foo/f"}) (lint! "(ns foo) (def ^:private f)")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :warning, :message "Unused private var foo/f"}) (lint! "(ns foo) (defn- f [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 103, :level :warning, :message "Unused private var foo/g"}) (lint! "(ns foo {:clj-kondo/config '{:linters {:unused-private-var {:exclude [foo/f]}}}}) (defn- f []) (defn- g [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 8, :level :warning, :message "Unused private var user/foo"} {:file "<stdin>", :row 1, :col 29, :level :warning, :message "Unused private var user/bar"}) (lint! "(defn- foo [] (foo)) (defn- bar ([] (bar 1)) ([_]))")) (is (empty? (lint! "(ns foo) (defn- f []) (f)"))) (is (empty? (lint! "(ns foo) (defn- f [])" '{:linters {:unused-private-var {:exclude [foo/f]}}}))) (is (empty? (lint! " (defrecord ^:private SessionStore [session-service]) (deftype ^:private SessionStore2 [session-service]) (defprotocol ^:private Foo (foo [this])) (definterface ^:private SessionStore3)")))) (deftest definterface-test (is (empty? (lint! "(definterface Foo (foo [x]) (bar [x]))" {:linters {:unused-binding {:level :warning}}})))) (deftest cond->test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Expected: number, received: map."}) (lint! "(let [m {:a 1}] (cond-> m (inc m) (assoc :a 1)))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 9, :level :error, :message "Expected: number, received: map."}) (lint! "(cond-> {:a 1} (odd? 1) (inc))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 25, :level :error, :message "clojure.core/inc is called with 2 args but expects 1"}) (lint! "(cond-> {:a 1} (odd? 1) (inc 1))" {:linters {:type-mismatch {:level :error}}}))) (deftest doto-test (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "Expected: number, received: map."}) (lint! "(doto {} (inc))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/inc is called with 3 args but expects 1"}) (lint! "(doto {} (inc 1 2))" {:linters {:invalid-arity {:level :error}}})) ;; preventing false positives (is (empty? (lint! "(doto (java.util.ArrayList. [1 2 3]) (as-> a (.addAll a a)))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest var-test (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "clojure.core/var is called with 0 args but expects 1"} {:file "<stdin>", :row 1, :col 30, :level :error, :message "Unresolved symbol: y"}) (lint! "(def x 1) (var x) (var) (var y)" {:linters {:unresolved-symbol {:level :error}}}))) (deftest consistent-alias-test (testing "symbol namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 39, :level :warning, :message #"Inconsistent.*str.*x"}] (lint! "(ns foo (:require [clojure.string :as x])) x/join" {:linters {:consistent-alias {:aliases '{clojure.string str}}}})) (is (empty? (lint! "(ns foo (:require [clojure.string])) clojure.string/join" {:linters {:consistent-alias {:aliases '{clojure.string str}}}})))) (testing "string namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 32, :level :warning, :message #"Inconsistent.*react.*r"}] (lint! "(ns foo (:require [\"react\" :as r])) r/StrictMode" {:linters {:consistent-alias {:aliases '{react react}}}}))) (testing "scoped namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 52, :level :warning, :message #"Inconsistent.*accordion.*acc"}] (lint! "(ns foo (:require [\"@radix-ui/react-accordion\" :as acc])) acc/Root" {:linters {:consistent-alias {:aliases '{"@radix-ui/react-accordion" accordion}}}})))) (deftest unsorted-required-namespaces-test (assert-submaps [{:file "<stdin>" :row 1 :col 31 :level :warning :message "Unsorted namespace: abar.core"}] (lint! "(ns foo (:require [bar.core] [abar.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}})) (assert-submaps [{:file "<stdin>" :row 1 :col 21 :level :warning :message "Unsorted namespace: abar.core"}] (lint! "(require 'bar.core 'abar.core)" {:linters {:unsorted-required-namespaces {:level :warning}}})) (testing "Duplicate requires are not reported as unsorted." (is (empty? (lint! "(ns foo (:require [cljs.core.async] [cljs.core.async]))" {:linters {:unsorted-required-namespaces {:level :warning} :duplicate-require {:level :off}}})))) (testing "Duplicate requires are not reported when occurring in different clauses" (is (empty? (lint! "(ns foo (:require-macros [cljs.core.async.macros]) (:require [cljs.core.async]))" {:linters {:unsorted-required-namespaces {:level :warning}}})))) (testing "string requires go on top" (assert-submaps '({:file "<stdin>", :row 1, :col 29, :level :warning, :message "Unsorted namespace: b.core"}) (lint! "(ns foo (:require [a.core] [\"b.core\"]))" {:linters {:unsorted-required-namespaces {:level :warning}}})) (is (empty? (lint! "(ns foo (:require [\"b.core\"] [a.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}})))) (is (empty? (lint! "(ns foo (:require [bar.core] [abar.core]))" {:linters {:unsorted-required-namespaces {:level :off}}}))) (is (empty? (lint! "(ns foo (:require [abar.core] [bar.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [abar.core] [bar.core]) (:import [java.lib JavaClass] [ajava.lib AnotherClass]))" {:linters {:unsorted-required-namespaces {:level :warning} :unused-import {:level :off}}}))) (testing "linter can be activated or deactivated via namespace metadata" (assert-submaps '({:file "<stdin>", :row 6, :col 5, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns foo {:clj-kondo/config '{:linters {:unsorted-required-namespaces {:level :warning}}}} (:require [zoo.foo] [bar.foo]))"))) (testing "For now CLJC branches are ignored" (is (empty? (lint! " (ns foo (:require #?(:clj [foo.bar]) [bar.foo]))" {:linters {:unsorted-required-namespaces {:level :warning} :unused-import {:level :off}}} "--lang" "cljc")))) (is (empty? (lint! "(ns foo (:require [clojure.string] [clojure.test]))" {:linters {:unsorted-required-namespaces {:level :warning}}} "--lang" "cljs"))) (testing "nested libspecs" (is (empty? (lint! " (ns foo (:require [charlie] [delta [alpha] [bravo]] [echo])) " {:linters {:unsorted-required-namespaces {:level :warning}}})))) (testing "namespaces in spliced reader conditionals are ignored" (is (empty? (lint! "(ns myname.myapp (:require [com.fulcrologic.fulcro.components] [taoensso.timbre] #?@(:cljs [[com.fulcrologic.fulcro.dom ]] :clj [[com.fulcrologic.fulcro.dom-server]])))" {:linters {:unsorted-required-namespaces {:level :warning}}} "--lang" "cljc")))) (testing "case insensitivity" (is (empty? (lint! "(ns foo (:require bar Bar))" {:linters {:unsorted-required-namespaces {:level :warning}}}))))) (deftest set!-test (assert-submaps '[{:col 13 :message #"arg"}] (lint! "(declare x) (set! (.-foo x) 1 2 3)")) (is (empty? (lint! "(def x (js-obj)) (set! x -field 2)" "--lang" "cljs")))) (deftest absolute-path-namespace (is (empty? (lint! "(ns main.core (:require [\"/vendors/daterangepicker\"]))" "--lang" "cljc" "--cache" "true")))) (deftest import-syntax (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "Expected: package name followed by classes."}) (lint! "(ns foo (:import [foo.bar]))")) (assert-submaps '({:file "<stdin>", :row 1, :col 61, :level :error, :message "Expected: class symbol"} {:file "<stdin>", :row 1, :col 68, :level :error, :message "Expected: class symbol"}) (lint! "(ns circle.http.api.v2.context (:import [circle.http.defapi :refer [defapi-with-auth]]))")) (assert-submaps '({:file "<stdin>", :row 1, :col 18, :level :error, :message "import form is invalid: clauses must not be empty"}) (lint! "(ns foo (:import ()))")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "import form is invalid: clauses must not be empty"}) (lint! "(import '())"))) (deftest expected-class-symbol-test (is (empty? (with-out-str (lint! "(ns circle.http.api.v2.context (:import [circle.http.defapi :refer [defapi-with-auth]]))"))))) (deftest empty-require (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "require form is invalid: clauses must not be empty"}) (lint! "(ns foo (:require []))")) (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "require form is invalid: clauses must not be empty"}) (lint! "(require '[])"))) (deftest unquoted-namespace-config-test (assert-submaps '({:file "<stdin>", :row 4, :col 14, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns foo {:clj-kondo/config {:linters {:unsorted-required-namespaces {:level :warning}}}} (:require [foo.bar] [bar.foo]))")) (assert-submaps '({:file "<stdin>", :row 4, :col 14, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns ^{:clj-kondo/config {:linters {:unsorted-required-namespaces {:level :warning}}}} foo (:require [foo.bar] [bar.foo]))"))) (deftest conflicting-aliases-test (assert-submaps [{:file "<stdin>", :row 1, :col 50, :level :error, :message #"Conflicting alias for "}] (lint! "(ns foo (:require [foo.bar :as bar] [baz.bar :as bar]))" {:linters {:conflicting-alias {:level :error} :unused-namespace {:level :off}}})) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [baz.bar :as baz]))" {:linters {:conflicting-alias {:level :error} :unused-namespace {:level :off}}}))) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [baz.bar] [foo.baz :refer [fun muchfun]]))" {:linters {:conflicting-alias {:level :error} :unused-referred-var {:level :off} :unused-namespace {:level :off}}})))) (deftest refer-test (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer [asd]])) (foo/bazbar) (asd)"))) (assert-submaps [{:file "<stdin>", :row 1, :col 46, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer [asd]])) (foo/bazbar) (asd)" {:linters {:refer {:level :warning}}})) (assert-submaps [{:file "<stdin>", :row 1, :col 46, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer :all])) (foo/bazbar) (asd)" {:linters {:refer {:level :warning} :refer-all {:level :off}}})) (assert-submaps [{:file "<stdin>", :row 1, :col 35, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require-macros [foo.bar :refer [macro]])) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}} "--lang" "cljs")) (assert-submaps [{:file "<stdin>", :row 1, :col 28, :level :warning, :message #"require with :refer-macros"}] (lint! "(ns foo (:require [foo.bar :refer-macros [macro]])) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}} "--lang" "cljs")) (assert-submaps [{:file "<stdin>", :row 1, :col 20, :level :warning, :message #"require with :refer"}] (lint! "(require '[foo.bar :refer [macro]]) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}})) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo])) (foo/bazbar)" {:linters {:refer {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [clojure.test :refer [deftest]])) deftest" '{:linters {:refer {:level :warning :exclude [clojure.test]}}})))) (deftest missing-else-branch-test (assert-submaps [{:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 13, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 29, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 46, :level :warning, :message "Missing else branch."}] (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)")) (is (empty? (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)" {:linters {:missing-else-branch {:level :off}}}))) (is (empty? (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)" {:linters {:if {:level :off}}})))) (deftest single-key-in-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :warning, :message "get-in with single key"}) (lint! "(get-in {} [:k])" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :warning, :message "assoc-in with single key"}) (lint! "(assoc-in {} [:k] :v)" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "update-in with single key"}) (lint! "(update-in {} [:k] inc)" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (is (empty? (lint! "(get-in {} [:k1 :k2])" {:linters {:single-key-in {:level :warning}}}))) (is (empty? (lint! "(get-in {} (keys-fn))" {:linters {:single-key-in {:level :warning}}}))) (testing "don't throw exception when args are missing" (is (some? (lint! "(assoc-in)"))))) (deftest multiple-options-test (testing "multiple --lint option" (let [out (edn/read-string (with-out-str (main "--lint" "corpus/case.clj" "--lint" "corpus/defmulti.clj" "--config" "{:output {:format :edn}}")))] (is (= #{"corpus/case.clj" "corpus/defmulti.clj"} (into #{} (comp (map :filename) (distinct)) (:findings out)))) (is (= {:error 6 :warning 2 :info 0} (select-keys (:summary out) [:error :warning :info]))))) (testing "multiple --config option" (let [out (edn/read-string (with-out-str (main "--lint" "corpus/case.clj" "--lint" "corpus/defmulti.clj" "--config" "{:output {:format :edn}}" "--config" "{:linters {:invalid-arity {:level :warning}}}")))] (is (= {:error 1 :warning 7 :info 0} (select-keys (:summary out) [:error :warning :info])))))) (deftest config-dir-test (is (seq (lint! (io/file "corpus" "config_dir" "foo.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty (lint! (io/file "corpus" "config_dir" "foo.clj") {:linters {:unresolved-symbol {:level :error}}} "--config-dir" (.getPath (io/file "corpus" "config_dir")))))) (deftest cljc-features-test (is (seq (lint! "(set! *warn-on-reflection* true)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljc"))) (is (empty? (lint! "(set! *warn-on-reflection* true)" {:cljc {:features [:clj]} :linters {:unresolved-symbol {:level :error}}} "--lang" "cljc")))) (deftest continue-on-invalid-token-code-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "Invalid symbol: foo/."} {:file "<stdin>", :row 3, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! " foo/ (inc)")) (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} {:file "<stdin>", :row 3, :col 1, :level :error, :message "Invalid symbol: foo/."}) (lint! " (inc) foo/"))) (deftest continue-on-invalid-keyword-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "A single colon is not a valid keyword."} {:file "<stdin>", :row 3, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! " : (inc)"))) (deftest nested-fn-literal-test (assert-submaps '({:file "<stdin>", :row 2, :col 7, :level :error, :message "Nested #()s are not allowed"}) (lint! " #(inc #(inc %))"))) (deftest destructuring-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Keys in :or should be simple symbols."}) (lint! "(defn baz [a & {:keys [c] :or {:c 10}}] (* a c))")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Keys in :or should be simple symbols."}) (lint! "(defn baz [a & {:keys [c] :or {\"c\" 10}}] (* a c))"))) (deftest do-template-test (assert-submaps '({:file "<stdin>", :row 4, :col 4, :level :error, :message "Unresolved symbol: f"} {:file "<stdin>", :row 4, :col 6, :level :error, :message "Unresolved symbol: g"}) (lint! "(require '[clojure.template :as templ]) (templ/do-template [a b] (def a b) x 1 y 2) (+ x y) (+ f g)" {:linters {:unresolved-symbol {:level :error}}}))) (deftest def-and-alias-with-qualified-symbols (testing "see GH-1326" (is (empty? (lint! "(ns foo) (alias 'f 'foo) (declare f/x) f/x x (def f/x 1)"))) (is (empty? (lint! "(ns foo) (declare foo/x) foo/x x (def foo/x 1)"))) (assert-submaps (lint! "(declare foo/x) foo/x x (def foo/x 1)") '({:file "<stdin>", :row 1, :col 10, :level :error, :message "Invalid var name: foo/x"} {:file "<stdin>", :row 1, :col 17, :level :warning, :message "Unresolved namespace foo. Are you missing a require?"} {:file "<stdin>", :row 1, :col 30, :level :error, :message "Invalid var name: foo/x"})))) (deftest issue-1366-conflicting-user-ns (let [expected-filename (tu/normalize-filename "corpus/issue-1366/dir-1/user.clj")] (is (apply = expected-filename (map (comp tu/normalize-filename :filename) (:findings (clj-kondo/run! {:lint ["corpus/issue-1366/dir-1" "corpus/issue-1366/dir-2"]}))))))) (deftest loop-without-recur (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [])" {:linters {:loop-without-recur {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [] (fn [] (recur)))" {:linters {:loop-without-recur {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [] (future (recur)))" {:linters {:loop-without-recur {:level :warning}}})) (is (empty? (lint! "(loop [] (recur))" {:linters {:loop-without-recur {:level :warning}}})))) (deftest as-alias-test (assert-submaps2 '(#_{:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace foo.bar is required but never used"} {:file "<stdin>", :row 1, :col 44, :level :warning, :message "Unresolved namespace fx. Are you missing a require?"}) (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fx/bar")) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fb/bar")))) (deftest as-aliased-var-usage-test (assert-submaps2 [{:row 1, :col 44, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) fb/bar")) (assert-submaps2 [{:row 1, :col 45, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) (fb/bar)")) (assert-submaps2 [{:file "<stdin>", :row 1, :col 47, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) `[~fb/bar]")) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fb/bar"))) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) `fb/bar")))) (deftest ns-unmap-test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Unresolved symbol: inc"}) (lint! "(ns foo) (ns-unmap *ns* 'inc) (inc 1)" {:linters {:unresolved-symbol {:level :error}}})) (is (empty? (lint! "(doseq [sym ['foo 'bar 'baz]] (ns-unmap *ns* sym))" {:linters {:unused-binding {:level :warning}}})))) (deftest duplicate-files (is (empty? (lint! [(io/file "corpus" "simple_test") (io/file "corpus" "simple_test" "a_test.clj")] "--config" "{:linters {:redefined-var {:level :error}}}")))) (deftest main-without-gen-class (is (= '({:file "<stdin>", :row 5, :col 1, :level :warning, :message "Main function without gen-class."}) (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}} #_(:gen-class)) (defn -main [& _args]) "))) (is (empty? (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}} (:gen-class)) (defn -main [& _args]) "))) (testing "in CLJS you'll never get a warning" (is (empty? (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}}) (defn -main [& _args]) " "--lang" "cljs")))) (testing "gen-class as macro outside ns form" (is (empty? (lint! " (ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}}) (gen-class) (defn -main []) "))))) (deftest CLJS-3330-deprecate-global-goog-modules see (assert-submaps '({:file "<stdin>", :row 1, :col 2, :level :warning, :message "Unresolved namespace goog.object. Are you missing a require?"}) (lint! "(goog.object/get #js {:a 1} \"a\")" "--lang" "cljs"))) (deftest clojure-test-check-properties-for-all-test (is (empty? (lint! "(require '[clojure.test.check.properties :refer [for-all]] '[clojure.test.check.generators :as gen]) (for-all [a gen/large-integer b gen/large-integer] (>= (+ a b) a))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest special-form-test (is (empty? (lint! "(defn new [] :foo) (new js/Date 2022 1 1 1 1)" "--lang" "cljs")))) ;;;; Scratch (comment (inline-def-test) (redundant-let-test) (redundant-do-test) (exit-code-test) (t/run-tests) )
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/41243e234d12e0de5f54994796d6727290785a1f/test/clj_kondo/main_test.clj
clojure
using it in syntax quote should mark private var as used this doesn't use the private var, it only uses the ns alias this does use the private var More info on this: -06-15-clojurescript-case-constants.html Each argument is followed by its spec. private function is used type mismatch ignored dropping the 'linting took' line special handling for constructor calls before and we don't want new errors ^String (str \"a\" \"b\") for now this is empty, but in the next version we might warn about the string "dude" being a discarded value note: not canonical non-empty to generated ns cache dynamically generated baz preventing false positives Scratch
(ns clj-kondo.main-test (:require [cheshire.core :as cheshire] [clj-kondo.core :as clj-kondo] [clj-kondo.main :refer [main]] [clj-kondo.test-utils :as tu :refer [lint! assert-submaps assert-submap submap? make-dirs rename-path remove-dir assert-submaps2]] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :as t :refer [deftest is testing]] [missing.test.assertions])) (deftest self-lint-test (is (empty? (lint! (io/file "src") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "test") {:linters {:unresolved-symbol {:level :error}}})))) (deftest inline-def-test (let [linted (lint! (io/file "corpus" "inline_def.clj") "--config" "{:linters {:redefined-var {:level :off}}}") row-col-files (map #(select-keys % [:row :col :file]) linted)] (assert-submaps '({:row 5, :col 3, :file "corpus/inline_def.clj"} {:row 8, :col 3, :file "corpus/inline_def.clj"} {:row 10, :col 10, :file "corpus/inline_def.clj"} {:row 12, :col 16, :file "corpus/inline_def.clj"} {:row 14, :col 18, :file "corpus/inline_def.clj"}) row-col-files) (is (= #{"inline def"} (set (map :message linted))))) (doseq [lang [:clj :cljs]] (is (empty? (lint! "(defmacro foo [] `(def x 1))" "--lang" (name lang)))) (is (empty? (lint! "(defn foo [] '(def x 3))" "--lang" (name lang)))))) (deftest def-fn-test (let [config {:linters {:def-fn {:level :warn}}}] (let [linted (lint! "(def x (fn [] 1))" config) row-col (map #(select-keys % [:row :col]) linted)] (assert-submaps '({:row 1, :col 8}) row-col) (is (= #{"Use defn instead of def + fn"} (set (map :message linted))))) (let [linted (lint! "(def x (let [y 1] (fn [] y)))" config) row-col (map #(select-keys % [:row :col]) linted)] (assert-submaps '({:row 1, :col 19}) row-col) (is (= #{"Use defn instead of def + fn"} (set (map :message linted))))) (doseq [lang [:clj :cljs]] (is (empty? (lint! "(def x [(fn [] 1)])" "--lang" (name lang) "--config" (pr-str config)))) (is (empty? (lint! "(def x (let [x 1] [(fn [] x)]))" "--lang" (name lang) "--config" (pr-str config))))))) (deftest redundant-let-test (let [linted (lint! (io/file "corpus" "redundant_let.clj")) row-col-files (map #(select-keys % [:row :col :file]) linted)] (assert-submaps '({:row 4, :col 3, :file "corpus/redundant_let.clj"} {:row 8, :col 3, :file "corpus/redundant_let.clj"} {:row 12, :col 3, :file "corpus/redundant_let.clj"}) row-col-files) (is (= #{"Redundant let expression."} (set (map :message linted))))) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :warning, :message #"Redundant let"}) (lint! "(let [x 2] (let [y 1]))" "--lang" "cljs")) (testing "linters still work in areas where arity linter is are disabled" (assert-submaps '({:file "<stdin>", :row 1, :col 43, :level :warning, :message #"Redundant let"}) (lint! "(reify Object (toString [this] (let [y 1] (let [x y] x))))"))) (assert-submaps [{:row 1, :col 1 :message #"Redundant let"} ](lint! "(let [] 1)")) (is (empty? (lint! "(let [x 2] `(let [y# 3]))"))) (is (empty? (lint! "(let [x 2] '(let [y 3]))"))) (is (empty? (lint! "(let [x 2] (let [y 1]) (let [y 2]))"))) (is (empty? (lint! "(let [x 2] (when true (let [y 1])))"))) (is (empty? (lint! "(let [z 1] (when true (let [x (let [y 2] y)])))"))) (is (empty? (lint! "#(let [x 1])"))) (is (empty? (lint! "(let [x 1] [x (let [y (+ x 1)] y)])"))) (is (empty? (lint! "(let [x 1] #{(let [y 1] y)})"))) (is (empty? (lint! "(let [x 1] #:a{:a (let [y 1] y)})"))) (is (empty? (lint! "(let [x 1] {:a (let [y 1] y)})"))) (is (empty? (lint! " (ns foo {:clj-kondo/config '{:lint-as {clojure.test.check.generators/let clojure.core/let}}} (:require [clojure.test.check.generators :as gen])) (let [_init-link-events 1] (gen/let [_chain-size 2 _command-chain 2] 1)) "))) (is (empty? (lint! "(let [#?@(:clj [x 1])] #?(:clj x))" "--lang" "cljc")))) (deftest redundant-do-test (assert-submaps '({:row 3, :col 1, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 4, :col 7, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 5, :col 14, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 6, :col 8, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 7, :col 16, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 8, :col 1, :file "corpus/redundant_do.clj" :message "Missing body in when"} {:row 9, :col 12, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 10, :col 16, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 11, :col 9, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 12, :col 17, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 13, :col 25, :file "corpus/redundant_do.clj" :message "redundant do"} {:row 14, :col 18, :file "corpus/redundant_do.clj" :message "redundant do"}) (lint! (io/file "corpus" "redundant_do.clj") {:linters {:redundant-expression {:level :off}}})) (is (empty? (lint! "(do 1 `(do 1 2 3))" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "(do 1 '(do 1 2 3))" {:linters {:redundant-expression {:level :off}}}))) (is (not-empty (lint! "(fn [] (do :foo :bar))" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "#(do :foo)"))) (is (empty? (lint! "#(do {:a %})"))) (is (empty? (lint! "#(do)"))) (is (empty? (lint! "#(do :foo :bar)" {:linters {:redundant-expression {:level :off}}}))) (is (empty? (lint! "#(do (prn %1 %2 true) %1)"))) (is (empty? (lint! "(let [x (do (println 1) 1)] x)"))) (is (empty? (lint! "(let [_ nil] #?(:cljs (do (println 1) (println 2)) :clj (println 3))) " "--lang" "cljc")))) (deftest cljc-test (assert-submaps '({:file "corpus/cljc/datascript.cljc", :row 9, :col 1} {:file "corpus/cljc/test_cljc.cljc", :row 13, :col 9} {:file "corpus/cljc/test_cljc.cljc", :row 14, :col 10} {:file "corpus/cljc/test_cljc.cljc", :row 21, :col 1} {:file "corpus/cljc/test_cljc.cljs", :row 5, :col 1} {:file "corpus/cljc/test_cljc_from_clj.clj", :row 5, :col 1} {:file "corpus/cljc/test_cljs.cljs", :row 5, :col 1} {:file "corpus/cljc/test_cljs.cljs", :row 6, :col 1}) (lint! (io/file "corpus" "cljc"))) (assert-submaps '({:file "corpus/spec/alpha.cljs", :row 6, :col 1, :level :error, :message "spec.alpha/def is called with 2 args but expects 3"}) (lint! (io/file "corpus" "spec"))) (is (empty? (lint! "(defn foo [#?(:default s :clj s)]) (foo 1)" "--lang" "cljc"))) (is (empty? (lint! "(defn foo [_x _y]) (foo 1 #uuid \"00000000-0000-0000-0000-000000000000\")" "--lang" "cljc"))) (is (empty? (lint! "(def ^{#?@(:clj [:deprecated \"deprecation message\"])} my-deprecated-var :bla)" "--lang" "cljc"))) (is (empty? (lint! "^#?(:clj :a :cljsr :b) [1 2 3]" "--lang" "cljc")))) (deftest exclude-clojure-test (let [linted (lint! (io/file "corpus" "exclude_clojure.clj"))] (assert-submaps '({:file "corpus/exclude_clojure.clj", :row 12, :col 1, :level :error, :message "clojure.core/get is called with 4 args but expects 2"}) linted))) (deftest private-call-test (assert-submaps '({:file "corpus/private/private_calls.clj", :row 2, :col 49, :level :error, :message "#'private.private-defs/private is private"} {:file "corpus/private/private_calls.clj", :row 4, :col 1, :level :error, :message "#'private.private-defs/private is private"} {:file "corpus/private/private_calls.clj", :row 5, :col 1, :level :error, :message "#'private.private-defs/private-by-meta is private"} {:file "corpus/private/private_calls.clj", :row 6, :col 6, :level :error, :message "#'private.private-defs/private is private"}) (lint! (io/file "corpus" "private"))) (assert-submaps '({:file "<stdin>", :row 6, :col 1, :level :error, :message "#'foo/foo is private"}) (lint! "(ns foo) (defn- foo []) (ns bar (:require [foo])) "))) (deftest read-error-test (testing "when an error happens in one file, the other file is still linted" (let [linted (lint! (io/file "corpus" "read_error"))] (assert-submaps '({:file "corpus/read_error/error.clj", :row 1, :col 1, :level :error, :message "Found an opening ( with no matching )"} {:file "corpus/read_error/error.clj" :row 2, :col 1, :level :error, :message "Expected a ) to match ( from line 1"} {:file "corpus/read_error/ok.clj", :row 6, :col 1, :level :error, :message "read-error.ok/foo is called with 1 arg but expects 0"}) linted)))) (deftest nested-namespaced-maps-test (assert-submaps '({:file "corpus/nested_namespaced_maps.clj", :row 9, :col 1, :level :error, :message "nested-namespaced-maps/test-fn is called with 2 args but expects 1"} {:file "corpus/nested_namespaced_maps.clj", :row 11, :col 12, :level :error, :message "duplicate key :a"}) (lint! (io/file "corpus" "nested_namespaced_maps.clj"))) (is (empty? (lint! "(meta ^#:foo{:a 1} {})")))) (deftest exit-code-test (with-out-str (testing "the exit code is 0 when no errors are detected" (is (zero? (with-in-str "(defn foo []) (foo)" (main "--lint" "-"))))) (testing "the exit code is 2 when warning are detected" (is (= 2 (with-in-str "(do (do 1))" (main "--lint" "-"))))) (testing "the exit code is 1 when errors are detected" (is (= 3 (with-in-str "(defn foo []) (foo 1)" (main "--lint" "-"))))))) (deftest exit-code-with-fail-level-test (with-out-str (testing "the exit code is 0 when fail-level is explicitly set to warning and no errors are detected" (is (zero? (with-in-str "(defn foo []) (foo)" (main "--fail-level" "warning" "--lint" "-"))))) (testing "the exit code is 2 when fail-level is warning and warnings are detected" (is (= 2 (with-in-str "(do (do 1))" (main "--fail-level" "warning" "--lint" "-"))))) (testing "the exit code is 3 when fail-level is error and errors are detected" (is (= 3 (with-in-str "(defn foo []) (foo 1)" (main "--fail-level" "error" "--lint" "-"))))))) (deftest cond-test (doseq [lang [:clj :cljs :cljc]] (testing (str "lang: " lang) (assert-submaps '({:row 9, :col 3, :level :warning} {:row 16, :col 3, :level :warning}) (lint! (io/file "corpus" (str "cond_without_else." (name lang))))) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "cond requires even number of forms"}) (lint! "(cond 1 2 3)" "--lang" (name lang))))) (assert-submaps '({:file "corpus/cond_without_else/core.cljc", :row 6, :col 21, :level :warning} {:file "corpus/cond_without_else/core.cljs", :row 3, :col 7, :level :warning}) (lint! [(io/file "corpus" "cond_without_else" "core.cljc") (io/file "corpus" "cond_without_else" "core.cljs")]))) (deftest cljs-core-macro-test (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/for is called with 4 args but expects 2"} (first (lint! "(for [x []] 1 2 3)" "--lang" "cljs")))) (deftest built-in-test (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "cljs")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(select-keys 1)" "--lang" "cljc")))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.test/successful? is called with 3 args but expects 1"} (first (lint! "(ns my-cljs (:require [clojure.test :refer [successful?]])) (successful? 1 2 3)" "--lang" "clj"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "cljs.test/successful? is called with 3 args but expects 1"} (first (lint! "(ns my-cljs (:require [cljs.test :refer [successful?]])) (successful? 1 2 3)" "--lang" "cljs"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.set/difference is called with 0 args but expects 1, 2 or more"} (first (lint! "(ns my-cljs (:require [clojure.set :refer [difference]])) (difference)" "--lang" "clj"))) (assert-submap {:file "<stdin>", :row 2, :col 5, :level :error, :message "clojure.set/difference is called with 0 args but expects 1, 2 or more"} (first (lint! "(ns my-cljs (:require [clojure.set :refer [difference]])) (difference)" "--lang" "cljs")))) (deftest built-in-java-test (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "(Thread/sleep 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "(java.lang.Thread/sleep 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.lang.Math/pow is called with 3 args but expects 2"} (first (lint! "(Math/pow 1 2 3)" "--lang" "clj")))) (is (= {:file "<stdin>", :row 1, :col 1, :level :error, :message "java.math.BigInteger/valueOf is called with 3 args but expects 1"} (first (lint! "(BigInteger/valueOf 1 2 3)" "--lang" "clj")))) (assert-submap {:message #"java.lang.Thread"} (first (lint! "(java.lang.Thread/sleep 1 2 3)" "--lang" "cljs"))) (is (= {:file "<stdin>", :row 1, :col 9, :level :error, :message "java.lang.Thread/sleep is called with 3 args but expects 1 or 2"} (first (lint! "#?(:clj (java.lang.Thread/sleep 1 2 3))" "--lang" "cljc"))))) (deftest resolve-core-ns-test (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/vec is called with 0 args but expects 1"} (first (lint! "(clojure.core/vec)" "--lang" "clj"))) (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/vec is called with 0 args but expects 1"} (first (lint! "(cljs.core/vec)" "--lang" "cljs"))) (assert-submap '{:file "<stdin>", :row 1, :col 1, :level :error, :message "cljs.core/vec is called with 0 args but expects 1"} (first (lint! "(clojure.core/vec)" "--lang" "cljs")))) (deftest override-test (doseq [lang [:clj :cljs]] (testing (str "lang: " (name lang)) (assert-submaps [{:file "<stdin>", :row 1, :col 1, :level :error, :message (str (case lang :clj "clojure" :cljs "cljs") ".core/quote is called with 3 args but expects 1")}] (lint! "(quote 1 2 3)" "--lang" (name lang))))) (is (empty? (lint! "(cljs.core/array 1 2 3)" "--lang" "cljs")))) (deftest cljs-clojure-ns-alias-test (assert-submap '{:file "<stdin>", :row 2, :col 1, :level :error, :message "cljs.test/do-report is called with 3 args but expects 1"} (first (lint! "(ns foo (:require [clojure.test :as t])) (t/do-report 1 2 3)" "--lang" "cljs")))) (deftest prefix-libspec-test (assert-submaps '({:col 14 :file "corpus/prefixed_libspec.clj" :level :error :message "Prefix lists can only have two levels." :row 11} {:file "corpus/prefixed_libspec.clj", :row 14, :col 1, :level :error, :message "foo.bar.baz/b is called with 0 args but expects 1"} {:file "corpus/prefixed_libspec.clj", :row 15, :col 1, :level :error, :message "foo.baz/c is called with 0 args but expects 1"}) (lint! (io/file "corpus" "prefixed_libspec.clj")))) (deftest prefix-libspec-containing-periods-test (testing "when a lib name with a period is found" (is (= '({:col 32 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer [foo.bar :as baz]]))" {:linters {:unused-namespace {:level :off}}})))) (testing "when multiple lib names with periods are found" (is (= '({:col 32 :file "<stdin>" :level :error :message "found lib name 'babashka.quux' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3} {:col 32 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 4}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer [babashka.quux :as baz] [foo.bar :as quux]]))" {:linters {:unused-namespace {:level :off}}})))) (testing "when a lib name with periods is a simple symbol" (is (= '({:col 31 :file "<stdin>" :level :error :message "found lib name 'foo.bar' containing period with prefix 'clj-kondo.impl.analyzer'. lib names inside prefix lists must not contain periods." :row 3}) (lint! "(ns baz (:require [clj-kondo.impl.analyzer foo.bar]))" {:linters {:unused-namespace {:level :off}}}))))) (deftest rename-test (testing "the renamed function isn't available under the referred name" (assert-submaps '({:file "<stdin>", :row 2, :col 11, :level :error, :message "clojure.string/includes? is called with 1 arg but expects 2"}) (lint! "(ns foo (:require [clojure.string :refer [includes?] :rename {includes? i}])) (i \"str\") (includes? \"str\")"))) (assert-submaps '({:file "corpus/rename.cljc", :row 4, :col 9, :level :error, :message "clojure.core/update is called with 0 args but expects 3, 4, 5, 6 or more"} {:file "corpus/rename.cljc", :row 5, :col 10, :level :error, :message "clojure.core/update is called with 0 args but expects 3, 4, 5, 6 or more"} {:file "corpus/rename.cljc", :row 6, :col 9, :level :error, :message "Unresolved symbol: conj"} {:file "corpus/rename.cljc", :row 7, :col 10, :level :error, :message "Unresolved symbol: conj"} {:file "corpus/rename.cljc", :row 8, :col 10, :level :error, :message "Unresolved symbol: join"} {:file "corpus/rename.cljc", :row 9, :col 11, :level :error, :message "Unresolved symbol: join"} {:file "corpus/rename.cljc", :row 10, :col 9, :level :error, :message "clojure.string/join is called with 0 args but expects 1 or 2"} {:file "corpus/rename.cljc", :row 11, :col 10, :level :error, :message "clojure.string/join is called with 0 args but expects 1 or 2"}) (lint! (io/file "corpus" "rename.cljc") '{:linters {:unresolved-symbol {:level :error}}}))) (deftest refer-all-rename-test (testing ":require with :refer :all and :rename" (assert-submaps '({:file "corpus/refer_all.clj", :row 15, :col 1, :level :error, :message "funs/foo is called with 0 args but expects 1"} {:file "corpus/refer_all.clj", :row 16, :col 1, :level :error, :message "funs/bar is called with 0 args but expects 1"}) (lint! (io/file "corpus" "refer_all.clj") {:linters {:unresolved-var {:level :off}}})) (assert-submaps '({:file "corpus/refer_all.cljs", :row 8, :col 1, :level :error, :message "macros/foo is called with 0 args but expects 1"}) (lint! (io/file "corpus" "refer_all.cljs"))))) (deftest alias-test (assert-submap '{:file "<stdin>", :row 1, :col 35, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"} (first (lint! "(ns foo) (alias 'c 'clojure.core) (c/select-keys)"))) (is (empty? (lint! " (require 'bar 'foo) (alias (quote f) (quote foo)) (alias (quote b) (quote bar)) (f/inc) (b/inc) ")))) (deftest reduce-without-init-test (testing "when enabled, warn on two argument usage of reduce" (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Reduce called without explicit initial value."}) (lint! "(reduce max [])" {:linters {:reduce-without-init {:level :warning}}})) (is (empty? (lint! "(reduce + [1 2 3])" {:linters {:reduce-without-init {:level :warning}}}))) (is (empty? (lint! "(reduce max 0 [1 2 3])" {:linters {:reduce-without-init {:level :warning}}}))) (is (empty? (lint! "(reduce + [1 2 3])"))) (is (empty? (lint! "(reduce max [])" '{:linters {:reduce-without-init {:level :warning :exclude [clojure.core/max]}}}))))) (deftest case-test (testing "case dispatch values should not be linted as function calls" (assert-submaps '({:file "corpus/case.clj", :row 7, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 9, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 14, :col 3, :level :error, :message "clojure.core/filter is called with 3 args but expects 1 or 2"} {:file "corpus/case.clj", :row 15, :col 3, :level :error, :message "clojure.core/odd? is called with 2 args but expects 1"}) (lint! (io/file "corpus" "case.clj") {:linters {:unresolved-symbol {:level :error}}}))) (testing "no false positive when using unquoted symbols" (is (empty? (lint! " (case 'str/join str/join :foo) (let [x 'y] (case x y 1 2))" {:linters {:unresolved-symbol {:level :error}}})))) (testing "no false positive when using defn in case list dispatch" (is (empty? (lint! "(let [x 1] (case x (defn select-keys) 1 2))" {:linters {:unresolved-symbol {:level :error}}})))) (testing "case dispatch vals are analyzed" (is (empty? (lint! "(require '[clojure.string :as str] (case 10 ::str/foo 11))" {:linters {:unresolved-symbol {:level :error} :unused-namespace {:level :error}}})))) (testing "CLJS constant" (assert-submaps '({:file "<stdin>", :row 1, :col 24, :level :error, :message "Unused private var user/x"}) (lint! "(def ^:private ^:const x 2) (case 1 x :yeah)" {:linters {:unused-private-var {:level :error}}})) (is (empty? (lint! "(def ^:private ^:const x 2) (case 1 x :yeah)" {:linters {:unused-private-var {:level :error}}} "--lang" "cljs")))) (testing "quoted case test constant" (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :warning, :message "Case test is compile time constant and should not be quoted."}) (lint! "(case 'x 'a 1 b 0)"))) (testing "duplicate case test constant" (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "Duplicate case test constant: :a"} {:file "<stdin>", :row 1, :col 24, :level :error, :message "Duplicate case test constant: :a"}) (lint! "(case f :a 2 :a 3 :b 1 :a 0)")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "Duplicate case test constant: :a"}) (lint! "(case f :a 2 :a 3 :b 1 :default)")) (assert-submaps '({:file "<stdin>", :row 3, :col 3, :level :error, :message "Duplicate case test constant: :bar"} {:file "<stdin>", :row 4, :col 3, :level :error, :message "Duplicate case test constant: :bar"}) (lint! "(case x (:foo :bar) :yolo :bar :hello :bar :hi)")) (assert-submaps '({:file "<stdin>", :row 2, :col 6, :level :error, :message "Duplicate case test constant: a"} {:file "<stdin>", :row 3, :col 3, :level :error, :message "Duplicate case test constant: a"}) (lint! "(case x (a a) 1 a 1 1)")) (is (empty? (lint! "(case 0 :a 1 :a)"))) (is (empty? (lint! "(case f :a 1 :b 2)"))) (is (empty? (lint! "(case f :a 1 :b 2 :a)"))))) (deftest local-bindings-test (is (empty? (lint! "(fn [select-keys] (select-keys))"))) (is (empty? (lint! "(fn [[select-keys x y z]] (select-keys))"))) (is (empty? (lint! "(fn [{:keys [:select-keys :b]}] (select-keys))"))) (is (empty? (lint! "(defn foo [{:keys [select-keys :b]}] (let [x 1] (select-keys)))"))) (is (seq (lint! "(defn foo ([select-keys]) ([x y] (select-keys)))"))) (is (empty? (lint! "(if-let [select-keys (fn [])] (select-keys) :bar)"))) (is (empty? (lint! "(when-let [select-keys (fn [])] (select-keys))"))) (is (empty? (lint! "(fn foo [x] (foo x))"))) (is (empty? (lint! "(fn select-keys [x] (select-keys 1))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :error, :message "foo is called with 3 args but expects 1"}) (lint! "(fn foo [x] (foo 1 2 3))")) (is (empty? (lint! "(fn foo ([x] (foo 1 2)) ([x y]))"))) (assert-submaps '({:message "f is called with 3 args but expects 0"}) (lint! "(let [f (fn [])] (f 1 2 3))")) (assert-submaps '({:message "f is called with 3 args but expects 0"}) (lint! "(let [f #()] (f 1 2 3))")) (assert-submaps '({:message "f is called with 0 args but expects 1 or more"}) (lint! "(let [f #(apply println % %&)] (f))")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "fn is called with 1 arg but expects 0"}) (lint! "(let [fn (fn [])] (fn 1))")) (is (empty? (lint! "(let [f #(apply println % %&)] (f 1))"))) (is (empty? (lint! "(let [f #(apply println % %&)] (f 1 2 3 4 5 6))"))) (is (empty? (lint! "(fn ^:static meta [x] (when (instance? clojure.lang.IMeta x) (. ^clojure.lang.IMeta x (meta))))"))) (is (empty? (lint! "(doseq [fn [inc]] (fn 1))"))) (is (empty? (lint! "(select-keys (let [x (fn [])] (x 1 2 3)) [])" "--config" "{:linters {:invalid-arity {:skip-args [clojure.core/select-keys]} :unresolved-symbol {:level :off}}}"))) (is (empty? (lint! "(defn foo [x {:keys [y] :or {y x}}] x y)" {:linters {:unresolved-symbol {:level :error} :unused-binding {:level :warning}}}))) (is (empty? (lint! "(defn foo [[x y] {:keys [:z] :or {z (+ x y)}}] z)" {:linters {:unresolved-symbol {:level :error} :unused-binding {:level :warning}}})))) (deftest let-test (assert-submap {:file "<stdin>", :row 1, :col 6, :level :error, :message "let binding vector requires even number of forms"} (first (lint! "(let [x 1 y])"))) (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"}) (lint! "(let [x 1 y (select-keys)])")) (is (empty? (lint! "(let [select-keys (fn []) y (select-keys)])"))) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "f is called with 1 arg but expects 0"}) (lint! "(let [f (fn []) y (f 1)])")) (assert-submaps '({:file "<stdin>", :row 1, :col 18, :level :error, :message "f is called with 1 arg but expects 0"}) (lint! "(let [f (fn [])] (f 1))")) (assert-submaps '({:file "<stdin>", :row 1, :col 6, :level :error, :message #"vector"}) (lint! "(let x 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"0 args"}) (lint! "(let)")) (is (empty (lint! "(let [f (fn []) f (fn [_]) y (f 1)])"))) (is (empty? (lint! "(let [err (fn [& msg])] (err 1 2 3))")))) (deftest if-let-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y 2])")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 4 args but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y 2] x 1 2)" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-let is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 9, :level :error, :message "if-let binding vector requires exactly 2 forms"}) (lint! "(if-let [x 1 y])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-let [x 1] true)" "--lang" lang)) (is (empty? (lint! "(if-let [{:keys [row col]} {:row 1 :col 2}] row 1)" "--lang" lang))))) (deftest if-some-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-some is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "if-some binding vector requires exactly 2 forms"}) (lint! "(if-some [x 1 y 2])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message #"if-some is called with 1 arg but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "if-some binding vector requires exactly 2 forms"}) (lint! "(if-some [x 1 y])" "--lang" lang)) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-some [x 1] true)" "--lang" lang)) (is (empty? (lint! "(if-some [{:keys [row col]} {:row 1 :col 2}] row 1)" "--lang" lang))))) (deftest when-let-test (assert-submap {:file "<stdin>", :row 1, :col 11, :level :error, :message "when-let binding vector requires exactly 2 forms"} (first (lint! "(when-let [x 1 y 2])"))) (assert-submap {:file "<stdin>", :row 1, :col 11, :level :error, :message "when-let binding vector requires exactly 2 forms"} (first (lint! "(when-let [x 1 y])"))) (is (empty? (lint! "(when-let [{:keys [:row :col]} {:row 1 :col 2}])")))) (deftest config-test (is (empty? (lint! "(select-keys 1 2 3)" '{:linters {:invalid-arity {:level :off}}}))) (is (empty? (lint! "(clojure.core/is-annotation? 1)" '{:linters {:private-call {:level :off}}}))) (is (empty? (lint! "(def (def x 1))" '{:linters {:inline-def {:level :off}}}))) (is (empty? (lint! "(do (do 1 2 3))" '{:linters {:redundant-do {:level :off} :redundant-expression {:level :off}}}))) (is (empty? (lint! "(let [x 1] (let [y 2]))" '{:linters {:redundant-let {:level :off}}}))) (is (empty? (lint! "(cond 1 2)" '{:linters {:cond-else {:level :off}}}))) (when-not tu/native? (is (str/includes? (let [err (java.io.StringWriter.)] (binding [*err* err] (lint! (io/file "corpus") '{:output {:progress true}} "--config-dir" "corpus/.clj-kondo") (str err))) "....")) (doseq [fmt [:json :edn]] (is (not (str/includes? (with-out-str (lint! (io/file "corpus") {:output {:progress true :format fmt}} "--config-dir" "corpus/.clj-kondo")) "...."))))) (is (not (some #(str/includes? % "datascript") (map :file (lint! (io/file "corpus") '{:output {:exclude-files ["datascript"]}} "--config-dir" "corpus/.clj-kondo"))))) (is (not (some #(str/includes? % "datascript") (map :file (lint! (io/file "corpus") '{:output {:include-files ["inline_def"]}} "--config-dir" "corpus/.clj-kondo"))))) (is (str/starts-with? (with-out-str (with-in-str "(do 1)" (main "--lint" "-" "--config" (str '{:output {:pattern "{{LEVEL}}_{{filename}}"} :linters {:unresolved-symbol {:level :off}}})))) "WARNING_<stdin>")) (is (empty? (lint! "(comment (select-keys))" '{:skip-comments true :linters {:unresolved-symbol {:level :off}}}))) (assert-submap '({:file "<stdin>", :row 1, :col 16, :level :error, :message "user/foo is called with 2 args but expects 1"}) (lint! "(defn foo [x]) (foo (comment 1 2 3) 2)" '{:skip-comments true})) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.specs])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [foo.specs bar.specs]}}}))) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.specs])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [".*\\.specs$"]}}}))) (is (empty? (lint! "(ns foo (:require [foo.specs] [bar.spex])) (defn my-fn [x] x)" '{:linters {:unused-namespace {:exclude [".*\\.specs$" ".*\\.spex$"]}}})))) (deftest skip-comments-test (is (= 1 (count (lint! "(comment (inc :foo))" {:linters {:type-mismatch {:level :error}}})))) (is (empty? (lint! "(comment (inc :foo))" {:skip-comments true :linters {:type-mismatch {:level :error}}}))) (is (= 1 (count (lint! "(ns foo {:clj-kondo/config {:skip-comments false}}) (comment (inc :foo))" {:skip-comments true :linters {:type-mismatch {:level :error}}}))))) (deftest replace-config-test (let [res (lint! "(let [x 1] (let [y 2]))" "--config" "^:replace {:linters {:redundant-let {:level :info}}}")] (is (every? #(identical? :info (:level %)) res)))) (deftest map-duplicate-keys-test (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "duplicate key :a"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} {:file "<stdin>", :row 1, :col 35, :level :error, :message "duplicate key :a"}) (lint! "{:a 1 :a (select-keys 1) :c {:a 1 :a 2}}"))) (is (= '({:file "<stdin>", :row 1, :col 6, :level :error, :message "duplicate key 1"} {:file "<stdin>", :row 1, :col 18, :level :error, :message "duplicate key \"foo\""}) (lint! "{1 1 1 1 \"foo\" 1 \"foo\" 2}"))) (is (empty? (lint! " (ns foo (:require [foo.bar :as bar])) (def foo {:bar/id \"asdf\" ::bar/id \"lkj\"})"))) (is (= '({:col 15 :file "<stdin>" :level :error :message "duplicate key (1 2)" :row 1}) (lint! "'{[1 2] \"bar\" (1 2) 12}"))) (is (= '({:col 22 :file "<stdin>" :level :error :message "duplicate key (let [x 2] x)" :row 1}) (lint! "{(let [x 2] x) \"bar\" (let [x 2] x) 12}"))) (is (= '({:col 14 :file "<stdin>" :level :error :message "duplicate key '(1 2)" :row 1}) (lint! "{[1 2] \"bar\" '(1 2) 12}"))) (is (= '({:col 20 :file "<stdin>" :level :error :message "duplicate key #{1 3 :foo}" :row 1}) (lint! "{#{1 :foo 3} \"bar\" #{1 3 :foo} 12}"))) (is (= '({:col 23 :file "<stdin>" :level :error :message "duplicate key #{1 'baz :foo}" :row 1}) (lint! "{#{1 :foo 'baz} \"bar\" #{1 'baz :foo} 12}"))) (is (= '({:col 23 :file "<stdin>" :level :error :message "duplicate key #{1 'baz :foo}" :row 1}) (lint! "{'#{1 :foo baz} \"bar\" #{1 'baz :foo} 12}"))) (is (= '({:col 14 :file "<stdin>" :level :error :message "duplicate key {1 2}" :row 1}) (lint! "{{1 2} \"bar\" {1 2} 12}"))) (is (= '({:col 24 :file "<stdin>" :level :error :message "duplicate key {1 2 'foo :bar}" :row 1}) (lint! "{'{1 2 foo :bar} \"bar\" {1 2 'foo :bar} 12}"))) (is (= '({:col 37 :file "<stdin>" :level :error :message "duplicate key '{1 {:foo #{3 4} bar (1 2)}}" :row 1}) (lint! "{{1 {:foo #{3 4} 'bar [1 2]}} \"bar\" '{1 {:foo #{3 4} bar (1 2)}} 12}")))) (deftest map-missing-value (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "missing value for key :b"}) (lint! "{:a 1 :b}"))) (is (= '({:file "<stdin>", :row 1, :col 14, :level :error, :message "missing value for key :a"}) (lint! "(let [x {:a {:a }}] x)"))) (is (= '({:file "<stdin>", :row 1, :col 15, :level :error, :message "missing value for key :a"}) (lint! "(loop [x {:a {:a }}] x)"))) (is (= '({:file "<stdin>", :row 1, :col 10, :level :error, :message "missing value for key :post"}) (lint! "(fn [x] {:post} x)"))) (assert-submaps '({:row 1, :col 22, :level :error, :message "missing value for key :c"}) (lint! "(let [{:keys [:a :b] :c} {}] [a b])"))) (deftest set-duplicate-keys-test (is (= '({:file "<stdin>", :row 1, :col 7, :level :error, :message "duplicate set element 1"}) (lint! "#{1 2 1}"))) (is (empty? (lint! "(let [foo 1] #{'foo foo})")))) (deftest macroexpand-test (assert-submap {:file "<stdin>", :row 1, :col 8, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(-> {} select-keys)"))) (assert-submap {:file "<stdin>", :row 1, :col 8, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(-> {} (select-keys))"))) (assert-submap {:file "<stdin>", :row 1, :col 9, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(->> {} select-keys)"))) (assert-submap {:file "<stdin>", :row 1, :col 9, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"} (first (lint! "(->> {} (select-keys))"))) (testing "cats" (is (seq (lint! "(ns foo (:require [cats.core :as m])) (m/->= (right {}) (select-keys))"))) (is (seq (lint! "(ns foo (:require [cats.core :as m])) (m/->>= (right {}) (select-keys))")))) (testing "with CLJC" (is (empty? (lint! "(-> 1 #?(:clj inc :cljs inc))" "--lang" "cljc"))) (assert-submap {:file "<stdin>", :row 1, :col 15, :level :error, :message "java.lang.Math/pow is called with 1 arg but expects 2"} (first (lint! "(-> 1 #?(:clj (Math/pow)))" "--lang" "cljc")))) (testing "with type hints" (assert-submap {:file "<stdin>", :row 1, :col 60, :level :error, :message "clojure.string/includes? is called with 1 arg but expects 2"} (first (lint! "(ns foo (:require [clojure.string])) (-> \"foo\" ^String str clojure.string/includes?)"))) (assert-submap {:file "<stdin>", :row 1, :col 12, :level :error, :message "duplicate key :a"} (first (lint! "(-> ^{:a 1 :a 2} [1 2 3])")))) (testing "macroexpansion of anon fn literal" (assert-submaps '({:file "<stdin>", :row 1, :col 2, :level :error, :message "clojure.core/select-keys is called with 1 arg but expects 2"}) (lint! "#(select-keys %)")) (is (empty? (lint! "(let [f #(apply println %&)] (f 1 2 3 4))"))) (testing "fix for issue #181: the let in the expansion is resolved to clojure.core and not the custom let" (assert-submaps '({:file "<stdin>", :row 2, :col 41, :level :error, :message "missing value for key :a"}) (lint! "(ns foo (:refer-clojure :exclude [let])) (defmacro let [_]) #(println % {:a})"))))) (deftest schema-test (assert-submaps '({:file "corpus/schema/calls.clj", :row 4, :col 1, :level :error, :message "schema.defs/verify-signature is called with 0 args but expects 3"} {:file "corpus/schema/calls.clj", :row 4, :col 1, :level :error, :message "#'schema.defs/verify-signature is private"} {:file "corpus/schema/defs.clj", :row 10, :col 1, :level :error, :message "schema.defs/verify-signature is called with 2 args but expects 3"} {:file "corpus/schema/defs.clj", :row 12, :col 1, :level :error, :message "Invalid function body."}) (lint! (io/file "corpus" "schema") '{:linters {:unresolved-symbol {:level :error}}})) (is (empty? (lint! "(ns foo (:require [schema.core :refer [defschema]])) (defschema foo nil) foo" '{:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(ns yyyy (:require [schema.core :as s])) (s/fn my-identity :- s/Any [x :- s/Any] x)" '{:linters {:unresolved-symbol {:level :error}}})))) (deftest in-ns-test (assert-submaps '({:file "corpus/in-ns/base_ns.clj", :row 5, :col 1, :level :error, :message "in-ns.base-ns/foo is called with 3 args but expects 0"} {:file "corpus/in-ns/in_ns.clj", :row 5, :col 1, :level :error, :message "in-ns.base-ns/foo is called with 3 args but expects 0"}) (lint! (io/file "corpus" "in-ns"))) (assert-submap {:file "<stdin>", :row 1, :col 55, :level :error, :message "foo/foo-2 is called with 3 args but expects 0"} (first (lint! "(ns foo) (defn foo-1 [] (in-ns 'bar)) (defn foo-2 []) (foo-2 1 2 3)"))) (is (empty? (lint! "(let [ns-name \"user\"] (in-ns ns-name))" '{:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(in-ns 'foo) (clojure.core/let [x 1])" '{:linters {:unresolved-symbol {:level :error}}})))) (deftest recur-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(defn foo [x] (recur x x))")) (assert-submaps '({:file "<stdin>", :row 1, :col 9, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(fn [x] (recur x x))")) (is (empty? (lint! "(defn foo [x & xs] (recur x [x]))"))) (is (empty? (lint! "(defn foo ([]) ([x & xs] (recur x [x])))"))) (is (empty? (lint! "(fn ([]) ([x y & xs] (recur x x [x])))"))) (is (empty? (lint! "(loop [x 1 y 2] (recur x y))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "recur argument count mismatch (expected 2, got 3)"}) (lint! "(loop [x 1 y 2] (recur x y x))")) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1))"))) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (defn foo [x y] (go-loop [x nil] (recur 1)))"))) (assert-submaps '({:file "<stdin>", :row 1, :col 74, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require [clojure.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (assert-submaps '({:file "<stdin>", :row 1, :col 85, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require-macros [cljs.core.async.macros :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (assert-submaps '({:file "<stdin>", :row 1, :col 78, :level :error, :message "recur argument count mismatch (expected 1, got 2)"}) (lint! "(ns foo (:require-macros [cljs.core.async :refer [go-loop]])) (go-loop [x 1] (recur 1 2))")) (is (empty? (lint! "#(recur)"))) (is (empty? (lint! "(ns foo (:require [clojure.core.async :refer [thread]])) (thread (recur))"))) (is (empty? (lint! "(ns clojure.core.async) (defmacro thread [& body]) (thread (when true (recur)))"))) (is (empty? (lint! "(fn* ^:static cons [x seq] (recur 1 2))"))) (is (empty? (lint! " (defprotocol IFoo (-foo [_])) (defrecord Foo [] IFoo (-foo [_] (let [_f (fn [x] (recur x))] (recur)))) (deftype FooType [] java.lang.Runnable (run [_] (let [_f (fn [x] (recur x))] (recur)))) (reify IFoo (-foo [_] (let [_f (fn [x] (recur x))] (loop [x 1] (recur x)) (recur)))) (extend-protocol IFoo Number (-foo [this] (recur this))) (extend-type Number IFoo (-foo [this] (recur this)))"))) (is (empty? (lint! "(defrecord Foo [] clojure.lang.ILookup (valAt [_ _] (letfn [(_foo [_x] (recur 1))])))")))) (deftest lint-as-test (assert-submaps '({:file "<stdin>", :row 1, :col 93, :level :error, :message "foo/foo is called with 3 args but expects 1"}) (lint! "(ns foo) (defmacro my-defn [name args & body] `(defn ~name ~args ~@body)) (my-defn foo [x]) (foo 1 2 3)" '{:lint-as {foo/my-defn clojure.core/defn}})) (assert-submaps '[{:level :error, :message #"fully qualified symbol"}] (lint! "(require '[foo.bar]) (foo.bar/when-let)" '{:lint-as {foo.bar/when-let when-let}})) (is (empty? (lint! "(ns foo) (defmacro deftest [name & body] `(defn ~name [] ~@body)) (deftest foo)" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {foo/deftest clojure.test/deftest}}))) (is (empty? (lint! (io/file "corpus" "lint_as_for.clj") '{:linters {:unresolved-symbol {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [weird.lib :refer [weird-def]])) (weird-def foo x y z) foo" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {weird.lib/weird-def clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require [orchestra.core :refer [defn-spec]])) (defn- foo []) (defn-spec my-inc integer? ) (my-inc)" '{:linters {:unresolved-symbol {:level :warning}} :lint-as {orchestra.core/defn-spec clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require [rum.core :as rum])) (rum/defcs stateful < (rum/local 0 ::key) [state label] (let [local-atom (::key state)] [:div { :on-click (fn [_] (swap! local-atom inc)) } label \": \" @local-atom])) (stateful) " '{:linters {:unresolved-symbol {:level :warning}} :lint-as {rum.core/defcs clj-kondo.lint-as/def-catch-all}}))) (is (empty? (lint! "(ns foo (:require plumbing.core)) (let [live? true] (-> {} (plumbing.core/?> live? (assoc :live live?)))) " '{:lint-as {plumbing.core/?> clojure.core/cond->}})))) (deftest letfn-test (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "clojure.core/select-keys is called with 0 args but expects 2"}) (lint! "(letfn [] (select-keys))")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "f1 is called with 0 args but expects 1"}) (lint! "(letfn [(f1 [_])] (f1))")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "recur argument count mismatch (expected 1, got 0)"}) (lint! "(letfn [(f1 [_] (recur))])")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :error, :message "f2 is called with 0 args but expects 1"}) (lint! "(letfn [(f1 [_] (f2)) (f2 [_])])"))) (deftest namespace-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 5, :level :error, :message "namespace name expected"}) (lint! "(ns \"hello\")")) (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "Unparsable libspec: [foo oh-no :as]"}) (lint! "(ns foo (:require [foo oh-no :as]))" {:linters {:syntax {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "Unparsable libspec: [foo oh-no :as]"}) (lint! "(require '[foo oh-no :as])" {:linters {:syntax {:level :error}}}))) (deftest call-as-use-test (is (empty? (lint! "(extend-protocol clojure.lang.IChunkedSeq (internal-reduce [s f val] (recur (chunk-next s) f val)))")))) (deftest redefined-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "redefined var #'user/foo"}) (lint! "(defn foo []) (defn foo [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 29, :level :warning, :message "redefined var #'user/foo"}) (lint! "(let [bar 42] (def foo bar) (def foo bar))")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "inc already refers to #'clojure.core/inc"}) (lint! "(defn inc [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "inc already refers to #'cljs.core/inc"}) (lint! "(defn inc [])" "--lang" "cljs")) (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace bar is required but never used"} {:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'bar/x is referred but never used"} {:file "<stdin>", :row 1, :col 38, :level :warning, :message "x already refers to #'bar/x"}) (lint! "(ns foo (:require [bar :refer [x]])) (defn x [])")) (is (empty? (lint! "(defn foo [])"))) (is (empty? (lint! "(ns foo (:refer-clojure :exclude [inc])) (defn inc [])"))) (is (empty? (lint! "(declare foo) (def foo 1)"))) (is (empty? (lint! "(def foo 1) (declare foo)"))) (is (empty? (lint! "(if (odd? 3) (def foo 1) (def foo 2))"))) (testing "disable linter in comment" (is (empty? (lint! "(comment (def x 1) (def x 2))"))))) (deftest unreachable-code-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "unreachable code"}) (lint! "(cond :else 1 (odd? 1) 2)"))) (deftest dont-crash-analyzer-test (doseq [example ["(let)" "(if-let)" "(when-let)" "(loop)" "(doseq)"] :let [prog (str example " (inc)")]] (is (some (fn [finding] (submap? {:file "<stdin>", :row 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} finding)) (lint! prog))))) (deftest for-doseq-test (assert-submaps [{:col 8 :message #"vector"}] (lint! "(doseq 1 2)")) (is (empty? (lint! "(for [select-keys []] (select-keys 1))"))) (is (empty? (lint! "(doseq [select-keys []] (select-keys 1))")))) (deftest keyword-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "keyword :x is called with 3 args but expects 1 or 2"}) (lint! "(:x 1 2 3)")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "keyword :b/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo) (:b/x {:bar/x 1} 1 2)")) (assert-submaps '({:file "<stdin>", :row 1, :col 33, :level :error, :message "keyword :bar/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo (:require [bar :as b])) (::b/x {:bar/x 1} 1 2)")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "keyword :foo/x is called with 3 args but expects 1 or 2"}) (lint! "(ns foo) (::x {::x 1} 2 3)")) (is (empty? (lint! "(select-keys (:more 1 2 3 4) [])" "--config" "{:linters {:invalid-arity {:skip-args [clojure.core/select-keys]}}}")))) (deftest map-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "map is called with 0 args but expects 1 or 2"}) (lint! "({:a 1})")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "map is called with 3 args but expects 1 or 2"}) (lint! "({:a 1} 1 2 3)")) (is (empty? (lint! "(foo ({:a 1} 1 2 3))" "--config" "{:linters {:invalid-arity {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest symbol-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "symbol is called with 0 args but expects 1 or 2"}) (lint! "('foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "symbol is called with 3 args but expects 1 or 2"}) (lint! "('foo 1 2 3)")) (is (empty? (lint! "(foo ('foo 1 2 3))" "--config" "{:linters {:invalid-arity {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest vector-call-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Vector can only be called with 1 arg but was called with: 0"} {:file "<stdin>", :row 1, :col 13, :level :error, :message "Vector can only be called with 1 arg but was called with: 2"}) (lint! "([]) ([] 1) ([] 1 2)"))) (deftest not-a-function-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a boolean is not a function"}) (lint! "(true 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a string is not a function"}) (lint! "(\"foo\" 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "a number is not a function"}) (lint! "(1 1)")) (is (empty? (lint! "'(1 1)"))) (is (empty? (lint! "(foo (1 1))" "--config" "{:linters {:not-a-function {:skip-args [user/foo]} :unresolved-symbol {:level :off}}}")))) (deftest cljs-self-require-test (is (empty? (lint! (io/file "corpus" "cljs_self_require.cljc"))))) (deftest unsupported-binding-form-test (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "unsupported binding form :x"}) (lint! "(defn foo [:x])")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "unsupported binding form a/a"}) (lint! "(defn foo [a/a])")) (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "unsupported binding form 1"}) (lint! "(let [1 1])")) (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "unsupported binding form (x)"}) (lint! "(let [(x) 1])")) (is (empty? (lint! "(fn [[x y z] :as x])"))) (is (empty? (lint! "(fn [[x y z & xs]])"))) (is (empty? (lint! "(let [^String x \"foo\"])")))) (deftest non-destructured-binding-test (doseq [input ["(let [{:keys [:i] :or {i 2 j 3}} {}] i)" "(let [{:or {i 2 j 3} :keys [:i]} {}] i)"]] (assert-submaps '({:file "<stdin>", :row 1 :level :warning, :message "j is not bound in this destructuring form"}) (lint! input {:linters {:unused-binding {:level :warning}}})))) (deftest output-test (is (str/starts-with? (with-in-str "" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:summary true}}"))) "linting took")) (is (not (str/starts-with? (with-in-str "" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:summary false}}"))) "linting took"))) (is (= '({:filename "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} {:filename "<stdin>", :row 1, :col 6, :level :error, :message "clojure.core/dec is called with 0 args but expects 1"}) (let [parse-fn (fn [line] (when-let [[_ file row col level message] (re-matches #"(.+):(\d+):(\d+): (\w+): (.*)" line)] {:filename file :row (Integer/parseInt row) :col (Integer/parseInt col) :level (keyword level) :message message})) text (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" "{:output {:format :text}}")))] (keep parse-fn (str/split-lines text))))) (doseq [[output-format parse-fn] [[:edn edn/read-string] [:json #(cheshire/parse-string % true)]] summary? [true false]] (let [output (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s :summary %s}}" output-format summary?)))) parsed (parse-fn output)] (assert-submap {:findings [{:type (case output-format :edn :invalid-arity "invalid-arity"), :filename "<stdin>", :row 1, :col 1, :end-row 1, :end-col 6, :level (case output-format :edn :error "error"), :message "clojure.core/inc is called with 0 args but expects 1"} {:type (case output-format :edn :invalid-arity "invalid-arity"), :filename "<stdin>", :row 1, :col 6, :end-row 1, :end-col 11, :level (case output-format :edn :error "error"), :message "clojure.core/dec is called with 0 args but expects 1"}]} parsed) (if summary? (assert-submap '{:error 2} (:summary parsed)) (is (nil? (find parsed :summary)))))) (doseq [[output-format parse-fn] [[:edn edn/read-string] [:json #(cheshire/parse-string % true)]]] (let [output (with-in-str "(inc)(dec)" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s}}" output-format)))) parsed (parse-fn output)] (is (map? parsed)))) (testing "JSON output escapes special characters" (let [output (with-in-str "{\"foo\" 1 \"foo\" 1}" (with-out-str (main "--cache" "false" "--lint" "-" "--config" (format "{:output {:format %s}}" :json)))) parsed (cheshire/parse-string output true)] (is (map? parsed))) (let [output (with-in-str "{:a 1}" (with-out-str (main "--cache" "false" "--lint" "\"foo\".clj" "--config" (format "{:output {:format %s}}" :json)))) parsed (cheshire/parse-string output true)] (is (map? parsed))))) (deftest show-rule-name-in-message-output-test (letfn [(run-main [config] (->> (main "--cache" "false" "--lint" "-" "--config" config) (with-out-str) (with-in-str "(inc)(dec)") (str/split-lines) (drop-last)))] (testing "with :show-rule-name-in-message true" (doseq [output-line (run-main "{:output {:linter-name true}}") :let [[_ begin] (re-matches #".*(<stdin>:\d+:\d+).*" output-line)]] (testing (str "output line '" begin "' ") (is (str/ends-with? output-line "[:invalid-arity]") "has rule name")))) (testing "with :show-rule-name-in-message false" (doseq [output-line (run-main "{:output {:show-rule-name-in-message false}}") :let [[_ begin] (re-matches #".*(<stdin>:\d+:\d+).*" output-line)]] (testing (str "output line '" begin "' ") (is (not (str/ends-with? output-line "[:invalid-arity]")) "doesn't have rule name")))))) (deftest defprotocol-test (assert-submaps '({:file "corpus/defprotocol.clj", :row 14, :col 1, :level :error, :message "defprotocol/-foo is called with 4 args but expects 1, 2 or 3"}) (lint! (io/file "corpus" "defprotocol.clj"))) (is (empty? (lint! " (ns repro (:import [clojure.lang IReduceInit])) (defprotocol Db (-list-resources ^IReduceInit [db type start-id]))")))) (deftest defrecord-test (assert-submaps '({:file "corpus/defrecord.clj", :row 6, :col 23, :level :warning, :message "unused binding this"} {:file "corpus/defrecord.clj", :row 8, :col 1, :level :error, :message "defrecord/->Thing is called with 3 args but expects 2"} {:file "corpus/defrecord.clj", :row 9, :col 1, :level :error, :message "defrecord/map->Thing is called with 2 args but expects 1"}) (lint! (io/file "corpus" "defrecord.clj") "--config" "{:linters {:unused-binding {:level :warning}}}")) (is (empty? (lint! (io/file "corpus" "record_protocol_metadata.clj") {:unused-import {:level :warning}})))) (deftest deftype-test (assert-submaps '({:file "corpus/deftype.cljs", :row 9, :col 10, :level :warning, :message "unused binding coll"} {:file "corpus/deftype.cljs", :row 17, :col 16, :level :warning, :message "unused binding coll"}) (lint! (io/file "corpus" "deftype.cljs") "--config" "{:linters {:unused-binding {:level :warning}}}"))) (deftest defmulti-test (assert-submaps '({:file "corpus/defmulti.clj", :row 7, :col 12, :level :error, :message "Unresolved symbol: greetingx"} {:file "corpus/defmulti.clj", :row 7, :col 35, :level :warning, :message "unused binding y"} {:file "corpus/defmulti.clj", :row 13, :col 24, :level :warning, :message "unused binding y"} {:file "corpus/defmulti.clj", :row 13, :col 39, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! (io/file "corpus" "defmulti.clj") '{:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})) (is (empty? (lint! "(defmulti foo)")))) (deftest misc-false-positives-test (is (empty? (lint! "(cond-> 1 true (as-> x (inc x)))"))) (is (empty? (lint! "(ns foo) (defn foo [] (ns bar (:require [clojure.string :as s])))"))) (is (empty? (lint! "(defn foo [x y z] ^{:a x :b y :c z} [1 2 3])"))) (is (empty? (lint! "(fn [^js x] x)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(= '`+ (read-string \"`+\"))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "core.rrb-vector.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(defn get-email [{email :email :as user :or {email user}}] email)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(ns repro (:require [clojure.string :refer [starts-with?]])) (defn foo {:test-fn starts-with?} [])" {:linters {:unresolved-symbol {:level :error}}}))) There actually still is issue # 450 that would cause this error . But we had when PR # 557 is merged . (is (empty? (lint! "(import my.ns.Obj) (Obj.)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "project.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "^{:a #js [1 2 3]} [1 2 3]" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "metadata.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(.log js/console ^js #js [1 2 3])" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(bound-fn [x] x)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! (io/file "corpus" "nested_syntax_quote.clj") {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(doseq [[ns-sym _ alias-sym] (cons t ts)] (create-ns ns-sym) (alias alias-sym ns-sym))" {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! " (ns app.repro (:import java.lang.String)) (defmacro test-macro [] `(let [test# ^String (str \"a\" \"b\")] test#))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(when-let [x 1] x x x)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(defn foo [x] (if-let [x 1] x x))" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}}))) (is (empty? (lint! "goog.global" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(fn [x] (* ^number x 1))" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! " (clojure.core/let ^{:row 15, :col 2, :line 1} [^{:row 15, :col 3} x 1] ^{:row 16, :col 2} (^{:row 16, :col 3} inc ^{:row 16, :col 7} x))" {:linters {:type-mismatch {:level :error}}}))) (is (empty? (lint! "(def x) (doto x)"))) (is (empty? (lint! "(def ^:private a 1) (let [{:keys [a] :or {a a}} {}] a)" {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! "(scala.Int/MinValue)" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(require '[clojure.string :as s]) '::s/foo"))) (is (empty? (lint! "(simple-benchmark [x 100] (+ 1 2 x) 10)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(defn foo [_a _b] (dosync (recur)))"))) (is (empty? (lint! "(defn foo [_a _b] (lazy-seq (recur)))"))) (is (empty? (lint! "(defn foo [_a _b] (lazy-cat (recur)))"))) (is (empty? (lint! "(ns foo (:refer-clojure :only [defn]))"))) (is (empty? (lint! " (ns kitchen-async.promise (:refer-clojure :exclude [promise ->]) (:require [clojure.core :as cc])) (defmacro promise [] (cc/let [_ (cond-> [] true (conj 1))])) (defmacro -> [])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(fn [^clj x] ^clj x)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! " (ns foo) (gen-class :name foo.Engine :state state :init init :methods [[eval [java.util.HashMap String] java.util.Map]])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! " (exists? foo.bar/baz)" {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}} "--lang" "cljs"))) (is (empty? (lint! "(def ^{:macro true} foo (fn* [_ _] (map (fn* []) [])))"))) (is (empty? (lint! "::f._al"))) (is (empty? (lint! "(with-precision 6 :rounding CEILING (+ 3.5555555M 1))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest tagged-literal-test (is (empty? (lint! "(let [x 1] #js {:a x})" {:linters {:unused-binding {:level :warning}}} "--lang" "cljs"))) (is (empty? (lint! "(set! *default-data-reader-fn* tagged-literal) #read-thing ([1 2 3] 4 5 6 (inc :foo))" ))) (is (empty? (lint! "(let [foo \"2022-02-10\" bar #time/date foo] bar)" {:linters {:unused-binding {:level :warning}}})))) (deftest data-readers-config-test (is (empty? (lint! (io/file "corpus/data_readers.clj") {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}}))) (is (empty? (lint! (io/file "corpus/data_readers.cljc") {:linters {:unresolved-symbol {:level :error} :unresolved-namespace {:level :error}}})))) (deftest extend-type-specify-test (assert-submaps '({:file "<stdin>", :row 2, :col 25, :level :error, :message "Unresolved symbol: x"}) (lint! " (specify! #js {:current x} IDeref (-deref [this] (.-current ^js this)))" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")) (is (empty? (lint! " (extend-type String clojure.lang.IDeref (deref [this] this))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest js-property-access-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Unresolved symbol: foo"}) (lint! "foo.bar" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")) (is (empty? (lint! "(let [foo #js{}] foo.bar (foo.bar)) (def bar #js {}) bar.baz (bar.baz)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljs")))) (deftest amap-test (is (empty? (lint! " (def an-array (int-array 25000 (int 0))) (amap ^ints an-array idx ret (+ (int 1) (aget ^ints an-array idx)))" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! "(let [nodes (into-array [1 2 3]) nodes (amap nodes idx _ idx)] nodes)" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})))) (deftest proxy-super-test (is (empty? (lint! " (proxy [java.util.ArrayList] [] (add [x] (let [^ArrayList this this] (proxy-super add x)))) " {:linters {:unused-binding {:level :warning}}}))) (is (empty? (lint! " (proxy [ArrayList] [] (let [xx x] (proxy-super add xx)))" {:linters {:unused-binding {:level :warning} :unresolved-symbol {:level :error}}})))) (deftest with-redefs-test (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "with-redefs requires a vector for its binding"}) (lint! "(with-redefs 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "with-redefs binding vector requires even number of forms"}) (lint! "(with-redefs [clojure.core/inc])")) (is (empty? (lint! " (ns foo) (defn- private-fn []) (private-fn) (ns bar (:require [foo])) (with-redefs [foo/private-fn (fn [])] (+ 1 2 3))"))) (is (empty? (lint! (io/file "corpus" "with_redefs.clj")))) (testing "binding is linted the same way as with-redefs" (is (empty? (lint! "(ns foo) (def ^:private ^:dynamic *foo*) *foo* (ns bar (:require [foo])) (binding [foo/*foo* 2])"))))) (deftest file-error-test (assert-submaps '({:file "not-existing.clj", :row 0, :col 0, :level :error, :message "file does not exist"}) (lint! (io/file "not-existing.clj")))) (deftest edn-test (assert-submaps '({:file "corpus/edn/edn.edn", :row 1, :col 10, :level :error, :message "duplicate key a"}) (lint! (io/file "corpus" "edn")))) (deftest spec-test (assert-submaps [{:file "corpus/spec_syntax.clj", :row 9, :col 9, :level :error, :message "expected symbol"} {:file "corpus/spec_syntax.clj", :row 9, :col 11, :level :error, :message "missing value for key :args"} {:file "corpus/spec_syntax.clj", :row 11, :col 13, :level :error, :message "unknown option :xargs"} #_{:file "corpus/spec_syntax.clj", :row 20, :col 9, :level :error, :message "Unresolved symbol: xstr/starts-with?"} {:file "corpus/spec_syntax.clj", :row 30, :col 15, :level :error, :message "unknown option ::opt"} {:file "corpus/spec_syntax.clj", :row 31, :col 15, :level :error, :message "unknown option ::opt-un"} {:file "corpus/spec_syntax.clj", :row 32, :col 15, :level :error, :message "unknown option ::req"} {:file "corpus/spec_syntax.clj", :row 33, :col 15, :level :error, :message "unknown option ::req-un"}] (lint! (io/file "corpus" "spec_syntax.clj") '{:linters {:unresolved-symbol {:level :error} :unused-namespace {:level :error}}}))) (deftest hashbang-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! "#!/usr/bin/env clojure\n(inc)"))) (deftest GH-301-test (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :error, :message "duplicate key :&::before"}) (lint! "{:&::before 1 :&::before 1}"))) (deftest misplaced-docstring-test (assert-submaps '({:file "<stdin>", :row 1, :col 13, :level :warning, :message "Misplaced docstring."}) (lint! "(defn f [x] \"dude\" x)" {:linters {:redundant-expression {:level :off}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :warning, :message "Misplaced docstring."}) (lint! "(defn foo [x y] \"dude \" [x y])" {:linters {:redundant-expression {:level :off}}})) (is (empty? (lint! "(defn f [x] \"dude\")"))) (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "Unused value: \"dude\""}) (lint! "(defn f \"dude\" [x] \"dude\" x)" {:linters {:unused-value {:level :warning}}}))) (deftest defn-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Invalid function body."}) (lint! "(defn f \"dude\" x) (f 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "Invalid function body."}) (lint! "(defn oops ())")) (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :error, :message "Function arguments should be wrapped in vector."}) (lint! "(defn oops (x))")) (assert-submaps '({:file "<stdin>", :row 1, :col 22, :level :error, :message "More than one function overload with arity 2."}) (lint! "(defn fun ([x y] x) ([y x] y))")) (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :error, :message "More than one function overload with arity 1."}) (lint! "(fn ([x] x) ([y] y))")) (is (empty? (lint! "(defn ok-fine [] {:this :is :not :attr-map2 :meta :data})"))) (testing "multi-arity" (is (empty? (lint! "(defn- second-attr-map-private-defn ([]) {:look :metadata!}) (second-attr-map-private-defn)"))) (is (empty? (lint! "(defn second-attr-map ([]) ([x] x) {:look :metadata!})"))) (is (empty? (lint! "(defmacro ^{:leading :meta} second-attr-map-macro {:attr1 :meta} ([]) ([x] x) {:attr2 :metadata!})"))) (assert-submaps '({:file "<stdin>" :row 1 :col 27 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) ([x] x) [:not :good])")) (assert-submaps '({:file "<stdin>" :row 1 :col 19 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) {:not :good} {:look metadata!})")) (assert-submaps '({:file "<stdin>" :row 1 :col 19 :level :error :message "Function arguments should be wrapped in vector."}) (lint! "(defn oopsie ([]) ({:not :good}))")) (assert-submaps2 '({:file "<stdin>" :row 1 :col 21 :level :error :message "Only one varargs binding allowed but got: xs, ys"}) (lint! "(defn foo [x y & xs ys] [x y xs ys])")))) (deftest not-empty?-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "use the idiom (seq x) rather than (not (empty? x))"}) (lint! "(not (empty? [1]))"))) (deftest deprecated-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 28, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(defn ^:deprecated foo []) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 35, :level :warning, :message "#'user/foo is deprecated since 1.0"}) (lint! "(defn foo {:deprecated \"1.0\"} []) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "#'clojure.core/agent-errors is deprecated since 1.2"}) (lint! "(agent-errors 1)")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(def ^:deprecated foo (fn [])) (foo)")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :warning, :message "#'user/foo is deprecated"}) (lint! "(def ^:deprecated foo (fn [])) foo")) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "#'clojure.core/replicate is deprecated since 1.3"}) (lint! "replicate")) (assert-submaps '({:file "<stdin>", :row 1, :col 83, :level :warning, :message "#'user/deprecated-multi is deprecated"}) (lint! "(defmulti deprecated-multi \"Docstring\" {:private true :deprecated true} identity) (deprecated-multi)")) (testing "config" (assert-submaps '({:file "corpus/deprecated_var.clj", :row 9, :col 30, :level :warning, :message "#'foo.foo/deprecated-fn is deprecated"} {:file "corpus/deprecated_var.clj", :row 10, :col 1, :level :warning, :message "#'foo.foo/deprecated-fn is deprecated"}) (lint! (io/file "corpus" "deprecated_var.clj") '{:linters {:deprecated-var {:exclude {foo.foo/deprecated-fn {:namespaces [foo.bar "bar\\.*"] :defs [foo.baz/allowed "foo\\.baz/ign\\.*"]}}}}}))) (assert-submaps '({:file "<stdin>", :row 2, :col 40, :level :warning, :message "#'user/my-deprecated-var is deprecated since deprecation message"}) (lint! "(def ^#?(:clj {:deprecated \"deprecation message\"} :cljs {}) my-deprecated-var :bla) my-deprecated-var" "--lang" "cljc")) (is (empty? (lint! "(defn ^:deprecated foo [] (foo))"))) (is (empty? (lint! "(def ^:deprecated foo (fn [] (foo)))"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}) (def ^:deprecated foo) foo"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}) (def ^:deprecated foo) foo"))) (is (empty? (lint! "(ns dude {:clj-kondo/config '{:linters {:deprecated-var {:exclude {dude/foo {:namespaces [dude]}}}}}}) (def ^:deprecated foo) foo")))) (deftest unused-referred-var-test (assert-submaps '({:file "corpus/unused_referred_var.clj", :row 2, :col 50, :level :warning, :message "#'clojure.string/ends-with? is referred but never used"}) (lint! (io/file "corpus" "unused_referred_var.clj"))) (assert-submaps '({:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace bar is required but never used"}) (lint! "(ns foo (:require [bar :refer [bar]]))" '{:linters {:unused-referred-var {:exclude {bar [bar]}}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 23, :level :warning, :message "namespace aws-sdk is required but never used"} {:file "<stdin>", :row 1, :col 42, :level :warning, :message "#'aws-sdk/AWS is referred but never used"}) (lint! "(ns lambda (:require [\"aws-sdk\" :default AWS]))" "--lang" "cljs")) (assert-submaps '({:file "<stdin>", :row 1, :col 36, :level :warning, :message "#'bar/v1 is referred but never used"}) (lint! "(ns foo (:require [bar :rename {v1 v2}])) ::bar/x")) (is (empty? (lint! "(ns foo (:require [bar :refer [bar]])) (apply bar 1 2 [3 4])"))) (is (empty? (lint! "(ns ^{:clj-kondo/config '{:linters {:unused-referred-var {:exclude {bar [bar]}}}}} foo (:require [bar :refer [bar] :as b])) (apply b/x 1 2 [3 4])")))) (deftest duplicate-require-test (assert-submaps '({:file "<stdin>", :row 1, :col 43, :level :warning, :message "duplicate require of clojure.string"}) (lint! "(ns foo (:require [clojure.string :as s] [clojure.string :as str])) s/join")) (assert-submaps '({:file "<stdin>", :row 1, :col 54, :level :warning, :message "duplicate require of clojure.string"}) (lint! "(ns foo (:require [clojure.string :as s])) (require 'clojure.string) s/join")) (is (empty? (lint! "(ns foo (:require-macros [cljs.core :as core]) (:require [cljs.core :as core])) core/conj" "--lang" "cljs")))) (deftest refer-all-test (assert-submaps '({:file "corpus/compojure/consumer.clj", :row 6, :col 1, :level :error, :message "compojure.core/defroutes is called with 0 args but expects 1 or more"} {:file "corpus/compojure/consumer.clj", :row 7, :col 1, :level :error, :message "compojure.core/GET is called with 0 args but expects 2 or more"} {:file "corpus/compojure/consumer.clj", :row 8, :col 1, :level :error, :message "compojure.core/POST is called with 0 args but expects 2 or more"} {:file "corpus/compojure/consumer.clj", :row 14, :col 8, :level :error, :message "Unresolved symbol: x"}) (lint! (io/file "corpus" "compojure") {:linters {:unresolved-symbol {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 31, :level :warning, :message "use alias or :refer"}) (lint! "(ns foo (:require [bar :refer :all]))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 42, :level :warning, :message "use alias or :refer [capitalize join]"}) (lint! "(ns foo (:require [clojure.string :refer :all])) (defn foo [strs] (join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 48, :level :warning, :message "use alias or :refer [capitalize]"}) (lint! "(ns foo (:require [clojure.string :as s :refer :all])) (defn foo [strs] (s/join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 56, :level :warning, :message "use alias or :refer [capitalize join]"}) (lint! "(ns foo (:require [clojure.string :refer [join] :refer :all])) (defn foo [strs] (join (map capitalize strs)))" {:linters {:refer-all {:level :warning}}})) (assert-submaps '({:file "corpus/use.clj", :row 4, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 9, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 14, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 19, :col 4, :level :warning, :message "use :require with alias or :refer [join]"} {:file "corpus/use.clj", :row 19, :col 10, :level :warning, :message "namespace clojure.string is required but never used"} {:file "corpus/use.clj", :row 19, :col 32, :level :warning, :message "#'clojure.string/join is referred but never used"} {:file "corpus/use.clj", :row 22, :col 2, :level :warning, :message "use require with alias or :refer [join]"} {:file "corpus/use.clj", :row 22, :col 8, :level :warning, :message "namespace clojure.string is required but never used"} {:file "corpus/use.clj", :row 22, :col 30, :level :warning, :message "#'clojure.string/join is referred but never used"} {:file "corpus/use.clj", :row 25, :col 2, :level :warning, :message "use require with alias or :refer [join]"} {:file "corpus/use.clj", :row 29, :col 2, :level :warning, :message "use require with alias or :refer [join]"}) (lint! (io/file "corpus" "use.clj") {:linters {:refer-all {:level :warning} :use {:level :warning}}})) (is (empty? (lint! "(require '[clojure.test :refer :all])" '{:linters {:refer-all {:level :warning :exclude [clojure.test]}}}))) (testing "vars from linted or built-in namespaces are known with :refer :all, see #1010" (is (empty? (lint! " (ns deftest-resolve-test-name-fail (:require [clojure.string :refer :all] [clojure.test :refer :all])) (deftest my-test (is (blank? \"\"))) " '{:linters {:refer-all {:level :off} :unresolved-symbol {:level :error}}}))))) (deftest canonical-paths-test (testing "single file" (let [f (io/file (first (map :file (lint! (io/file "corpus" "use.clj") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f))))) (testing "directory" (let [f (io/file (first (map :file (lint! (io/file "corpus" "private") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f))))) (testing "jar file" (let [f (io/file (first (map :file (lint! (io/file (System/getProperty "user.home") ".m2" "repository" "org" "clojure" "spec.alpha" "0.2.176" "spec.alpha-0.2.176.jar") {:output {:canonical-paths true}}))))] (is (= (.getPath f) (.getAbsolutePath f)))))) (deftest import-vars-test (assert-submaps '({:file "corpus/import_vars.clj", :row 23, :col 1, :level :error, :message "clojure.walk/prewalk is called with 0 args but expects 2"} {:file "corpus/import_vars.clj", :row 24, :col 1, :level :error, :message "app.core/foo is called with 0 args but expects 1"}) (lint! (io/file "corpus" "import_vars.clj") {:linters {:unresolved-symbol {:level :error}}})) (testing "import-vars with vector works when using cache" (when (.exists (io/file ".clj-kondo")) (rename-path ".clj-kondo" ".clj-kondo.bak")) (make-dirs ".clj-kondo") (lint! "(ns app.core) (defn foo [])" "--cache") (lint! "(ns app.api (:require [potemkin :refer [import-vars]])) (import-vars [app.core foo])" "--cache") (assert-submaps '({:file "<stdin>", :row 1, :col 49, :level :error, :message "app.core/foo is called with 1 arg but expects 0"}) (lint! "(ns consumer (:require [app.api :refer [foo]])) (foo 1)" "--cache")) (remove-dir ".clj-kondo") (when (.exists (io/file ".clj-kondo.bak")) (rename-path ".clj-kondo.bak" ".clj-kondo"))) (testing "import-vars with full qualified symbol with vector works when using cache" (when (.exists (io/file ".clj-kondo")) (rename-path ".clj-kondo" ".clj-kondo.bak")) (make-dirs ".clj-kondo") (lint! "(ns app.core) (defn foo []) (defn bar [])" "--cache") (lint! "(ns app.api (:require [potemkin :refer [import-vars]])) (import-vars app.core/foo app.core/bar)" "--cache") (assert-submaps '({:file "<stdin>", :row 1, :col 53, :level :error, :message "app.core/foo is called with 1 arg but expects 0"} {:file "<stdin>", :row 1, :col 61, :level :error, :message "app.core/bar is called with 1 arg but expects 0"}) (lint! "(ns consumer (:require [app.api :refer [foo bar]])) (foo 1) (bar 2)" "--cache")) (remove-dir ".clj-kondo") (when (.exists (io/file ".clj-kondo.bak")) (rename-path ".clj-kondo.bak" ".clj-kondo"))) (testing "aliases" (assert-submaps ' ({:file "<stdin>", :row 9, :col 10, :level :error, :message "clojure.string/starts-with? is called with 0 args but expects 2"} {:file "<stdin>", :row 9, :col 27, :level :error, :message "Unresolved var: i/x"}) (lint! " (ns importing-ns (:require [potemkin :refer [import-vars]] [clojure.string :as str])) (import-vars [str blank?, starts-with?]) (ns using-ns (:require [importing-ns :as i])) i/blank? (i/starts-with?) i/x " {:linters {:invalid-arity {:level :error} :unresolved-symbol {:level :error} :unresolved-var {:level :error} :type-mismatch {:level :error}}}))) (is (empty? (lint! " (ns dev.clj-kondo {:clj-kondo/config '{:linters {:missing-docstring {:level :warning}}}} (:require [potemkin :refer [import-vars]] [clojure.string])) (import-vars [clojure.string blank?, starts-with?, ends-with?, includes?])" {:linters {:unresolved-symbol {:level :error}}}))) (is (empty? (lint! " (ns foo.bar) (ns foo (:require [foo.bar] [potemkin :refer [import-vars]])) (import-vars [foo.bar baz]) (ns bar (:require [foo])) foo/baz " {:linters {:unresolved-symbol {:level :error} :unresolved-var {:level :error}}}))) TODO ? for now just include duplicate lint - as #_(testing "lint-as works automatically with imported vars" (is (empty? (lint! " (ns foo.bar) (defmacro defsomething [name & body]) (ns foo (:require [potemkin :refer [import-vars]])) (import-vars [foo.bar defsomething]) (ns consumer (:require foo)) (foo/defsomething dude) " '{:lint-as {foo.bar/defsomething clojure.core/def} :linters {:unresolved-symbol {:level :error} :unresolved-var {:level :error}}}))))) (deftest potemkin-import-vars-cyclic-test (assert-submaps '({:file "<stdin>", :row 4, :col 1, :level :warning, :message "redefined var #'foo/foo"}) (lint! " (ns foo (:require [potemkin])) (defn foo []) (potemkin/import-vars [foo foo]) ")) (is (empty? (lint!" (ns foo (:require [bar])) (require '[potemkin]) (potemkin/import-vars [bar x]) (ns bar (:require [foo] [potemkin])) (potemkin/import-vars [foo x])")))) (deftest dir-with-source-extension-test (testing "analyses source in dir with source extension" (let [dir (io/file "corpus" "directory.clj") jar (io/file "corpus" "withcljdir.jar")] (assert-submaps '({:file "dirinjar.clj/arity.clj" , :row 1, :col 1, :level :error, :message "clojure.core/map is called with 0 args but expects 1, 2, 3, 4 or more"}) (lint! jar)) (assert-submaps '({:file "corpus/directory.clj/arity2.clj", :row 1, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! dir))))) (deftest core-async-alt-test (assert-submaps '({:file "corpus/core_async/alt.clj", :row 7, :col 9, :level :error, :message "Unresolved symbol: x1"} {:file "corpus/core_async/alt.clj", :row 7, :col 12, :level :error, :message "Unresolved symbol: x2"} {:file "corpus/core_async/alt.clj", :row 11, :col 24, :level :error, :message "clojure.string/join is called with 3 args but expects 1 or 2"} {:file "corpus/core_async/alt.clj", :row 12, :col 10, :level :error, :message "Unresolved symbol: x3"} {:file "corpus/core_async/alt.clj", :row 12, :col 13, :level :error, :message "Unresolved symbol: x4"}) (lint! (io/file "corpus" "core_async" "alt.clj") {:linters {:unresolved-symbol {:level :error}}}))) (deftest if-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "Too few arguments to if."} {:file "<stdin>", :row 1, :col 6, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 15, :level :error, :message "Too many arguments to if."}) (lint! "(if) (if 1 1) (if 1 1 1 1)"))) (deftest if-not-test (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :error, :message "clojure.core/if-not is called with 0 args but expects 2 or 3"} {:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/if-not is called with 4 args but expects 2 or 3"}) (lint! "(if-not) (if-not 1 1 1 1)")) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."}) (lint! "(if-not 1 1)" "--lang" lang)))) (deftest unused-private-var-test (assert-submaps '({:file "<stdin>", :row 1, :col 25, :level :warning, :message "Unused private var foo/f"}) (lint! "(ns foo) (def ^:private f)")) (assert-submaps '({:file "<stdin>", :row 1, :col 17, :level :warning, :message "Unused private var foo/f"}) (lint! "(ns foo) (defn- f [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 103, :level :warning, :message "Unused private var foo/g"}) (lint! "(ns foo {:clj-kondo/config '{:linters {:unused-private-var {:exclude [foo/f]}}}}) (defn- f []) (defn- g [])")) (assert-submaps '({:file "<stdin>", :row 1, :col 8, :level :warning, :message "Unused private var user/foo"} {:file "<stdin>", :row 1, :col 29, :level :warning, :message "Unused private var user/bar"}) (lint! "(defn- foo [] (foo)) (defn- bar ([] (bar 1)) ([_]))")) (is (empty? (lint! "(ns foo) (defn- f []) (f)"))) (is (empty? (lint! "(ns foo) (defn- f [])" '{:linters {:unused-private-var {:exclude [foo/f]}}}))) (is (empty? (lint! " (defrecord ^:private SessionStore [session-service]) (deftype ^:private SessionStore2 [session-service]) (defprotocol ^:private Foo (foo [this])) (definterface ^:private SessionStore3)")))) (deftest definterface-test (is (empty? (lint! "(definterface Foo (foo [x]) (bar [x]))" {:linters {:unused-binding {:level :warning}}})))) (deftest cond->test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Expected: number, received: map."}) (lint! "(let [m {:a 1}] (cond-> m (inc m) (assoc :a 1)))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 9, :level :error, :message "Expected: number, received: map."}) (lint! "(cond-> {:a 1} (odd? 1) (inc))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 25, :level :error, :message "clojure.core/inc is called with 2 args but expects 1"}) (lint! "(cond-> {:a 1} (odd? 1) (inc 1))" {:linters {:type-mismatch {:level :error}}}))) (deftest doto-test (assert-submaps '({:file "<stdin>", :row 1, :col 7, :level :error, :message "Expected: number, received: map."}) (lint! "(doto {} (inc))" {:linters {:type-mismatch {:level :error}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "clojure.core/inc is called with 3 args but expects 1"}) (lint! "(doto {} (inc 1 2))" {:linters {:invalid-arity {:level :error}}})) (is (empty? (lint! "(doto (java.util.ArrayList. [1 2 3]) (as-> a (.addAll a a)))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest var-test (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "clojure.core/var is called with 0 args but expects 1"} {:file "<stdin>", :row 1, :col 30, :level :error, :message "Unresolved symbol: y"}) (lint! "(def x 1) (var x) (var) (var y)" {:linters {:unresolved-symbol {:level :error}}}))) (deftest consistent-alias-test (testing "symbol namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 39, :level :warning, :message #"Inconsistent.*str.*x"}] (lint! "(ns foo (:require [clojure.string :as x])) x/join" {:linters {:consistent-alias {:aliases '{clojure.string str}}}})) (is (empty? (lint! "(ns foo (:require [clojure.string])) clojure.string/join" {:linters {:consistent-alias {:aliases '{clojure.string str}}}})))) (testing "string namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 32, :level :warning, :message #"Inconsistent.*react.*r"}] (lint! "(ns foo (:require [\"react\" :as r])) r/StrictMode" {:linters {:consistent-alias {:aliases '{react react}}}}))) (testing "scoped namespaces" (assert-submaps [{:file "<stdin>", :row 1, :col 52, :level :warning, :message #"Inconsistent.*accordion.*acc"}] (lint! "(ns foo (:require [\"@radix-ui/react-accordion\" :as acc])) acc/Root" {:linters {:consistent-alias {:aliases '{"@radix-ui/react-accordion" accordion}}}})))) (deftest unsorted-required-namespaces-test (assert-submaps [{:file "<stdin>" :row 1 :col 31 :level :warning :message "Unsorted namespace: abar.core"}] (lint! "(ns foo (:require [bar.core] [abar.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}})) (assert-submaps [{:file "<stdin>" :row 1 :col 21 :level :warning :message "Unsorted namespace: abar.core"}] (lint! "(require 'bar.core 'abar.core)" {:linters {:unsorted-required-namespaces {:level :warning}}})) (testing "Duplicate requires are not reported as unsorted." (is (empty? (lint! "(ns foo (:require [cljs.core.async] [cljs.core.async]))" {:linters {:unsorted-required-namespaces {:level :warning} :duplicate-require {:level :off}}})))) (testing "Duplicate requires are not reported when occurring in different clauses" (is (empty? (lint! "(ns foo (:require-macros [cljs.core.async.macros]) (:require [cljs.core.async]))" {:linters {:unsorted-required-namespaces {:level :warning}}})))) (testing "string requires go on top" (assert-submaps '({:file "<stdin>", :row 1, :col 29, :level :warning, :message "Unsorted namespace: b.core"}) (lint! "(ns foo (:require [a.core] [\"b.core\"]))" {:linters {:unsorted-required-namespaces {:level :warning}}})) (is (empty? (lint! "(ns foo (:require [\"b.core\"] [a.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}})))) (is (empty? (lint! "(ns foo (:require [bar.core] [abar.core]))" {:linters {:unsorted-required-namespaces {:level :off}}}))) (is (empty? (lint! "(ns foo (:require [abar.core] [bar.core]))" {:linters {:unsorted-required-namespaces {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [abar.core] [bar.core]) (:import [java.lib JavaClass] [ajava.lib AnotherClass]))" {:linters {:unsorted-required-namespaces {:level :warning} :unused-import {:level :off}}}))) (testing "linter can be activated or deactivated via namespace metadata" (assert-submaps '({:file "<stdin>", :row 6, :col 5, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns foo {:clj-kondo/config '{:linters {:unsorted-required-namespaces {:level :warning}}}} (:require [zoo.foo] [bar.foo]))"))) (testing "For now CLJC branches are ignored" (is (empty? (lint! " (ns foo (:require #?(:clj [foo.bar]) [bar.foo]))" {:linters {:unsorted-required-namespaces {:level :warning} :unused-import {:level :off}}} "--lang" "cljc")))) (is (empty? (lint! "(ns foo (:require [clojure.string] [clojure.test]))" {:linters {:unsorted-required-namespaces {:level :warning}}} "--lang" "cljs"))) (testing "nested libspecs" (is (empty? (lint! " (ns foo (:require [charlie] [delta [alpha] [bravo]] [echo])) " {:linters {:unsorted-required-namespaces {:level :warning}}})))) (testing "namespaces in spliced reader conditionals are ignored" (is (empty? (lint! "(ns myname.myapp (:require [com.fulcrologic.fulcro.components] [taoensso.timbre] #?@(:cljs [[com.fulcrologic.fulcro.dom ]] :clj [[com.fulcrologic.fulcro.dom-server]])))" {:linters {:unsorted-required-namespaces {:level :warning}}} "--lang" "cljc")))) (testing "case insensitivity" (is (empty? (lint! "(ns foo (:require bar Bar))" {:linters {:unsorted-required-namespaces {:level :warning}}}))))) (deftest set!-test (assert-submaps '[{:col 13 :message #"arg"}] (lint! "(declare x) (set! (.-foo x) 1 2 3)")) (is (empty? (lint! "(def x (js-obj)) (set! x -field 2)" "--lang" "cljs")))) (deftest absolute-path-namespace (is (empty? (lint! "(ns main.core (:require [\"/vendors/daterangepicker\"]))" "--lang" "cljc" "--cache" "true")))) (deftest import-syntax (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "Expected: package name followed by classes."}) (lint! "(ns foo (:import [foo.bar]))")) (assert-submaps '({:file "<stdin>", :row 1, :col 61, :level :error, :message "Expected: class symbol"} {:file "<stdin>", :row 1, :col 68, :level :error, :message "Expected: class symbol"}) (lint! "(ns circle.http.api.v2.context (:import [circle.http.defapi :refer [defapi-with-auth]]))")) (assert-submaps '({:file "<stdin>", :row 1, :col 18, :level :error, :message "import form is invalid: clauses must not be empty"}) (lint! "(ns foo (:import ()))")) (assert-submaps '({:file "<stdin>", :row 1, :col 10, :level :error, :message "import form is invalid: clauses must not be empty"}) (lint! "(import '())"))) (deftest expected-class-symbol-test (is (empty? (with-out-str (lint! "(ns circle.http.api.v2.context (:import [circle.http.defapi :refer [defapi-with-auth]]))"))))) (deftest empty-require (assert-submaps '({:file "<stdin>", :row 1, :col 19, :level :error, :message "require form is invalid: clauses must not be empty"}) (lint! "(ns foo (:require []))")) (assert-submaps '({:file "<stdin>", :row 1, :col 11, :level :error, :message "require form is invalid: clauses must not be empty"}) (lint! "(require '[])"))) (deftest unquoted-namespace-config-test (assert-submaps '({:file "<stdin>", :row 4, :col 14, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns foo {:clj-kondo/config {:linters {:unsorted-required-namespaces {:level :warning}}}} (:require [foo.bar] [bar.foo]))")) (assert-submaps '({:file "<stdin>", :row 4, :col 14, :level :warning, :message "Unsorted namespace: bar.foo"}) (lint! " (ns ^{:clj-kondo/config {:linters {:unsorted-required-namespaces {:level :warning}}}} foo (:require [foo.bar] [bar.foo]))"))) (deftest conflicting-aliases-test (assert-submaps [{:file "<stdin>", :row 1, :col 50, :level :error, :message #"Conflicting alias for "}] (lint! "(ns foo (:require [foo.bar :as bar] [baz.bar :as bar]))" {:linters {:conflicting-alias {:level :error} :unused-namespace {:level :off}}})) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [baz.bar :as baz]))" {:linters {:conflicting-alias {:level :error} :unused-namespace {:level :off}}}))) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [baz.bar] [foo.baz :refer [fun muchfun]]))" {:linters {:conflicting-alias {:level :error} :unused-referred-var {:level :off} :unused-namespace {:level :off}}})))) (deftest refer-test (is (empty? (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer [asd]])) (foo/bazbar) (asd)"))) (assert-submaps [{:file "<stdin>", :row 1, :col 46, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer [asd]])) (foo/bazbar) (asd)" {:linters {:refer {:level :warning}}})) (assert-submaps [{:file "<stdin>", :row 1, :col 46, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require [foo.bar :as foo] [foo.baz :refer :all])) (foo/bazbar) (asd)" {:linters {:refer {:level :warning} :refer-all {:level :off}}})) (assert-submaps [{:file "<stdin>", :row 1, :col 35, :level :warning, :message #"require with :refer"}] (lint! "(ns foo (:require-macros [foo.bar :refer [macro]])) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}} "--lang" "cljs")) (assert-submaps [{:file "<stdin>", :row 1, :col 28, :level :warning, :message #"require with :refer-macros"}] (lint! "(ns foo (:require [foo.bar :refer-macros [macro]])) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}} "--lang" "cljs")) (assert-submaps [{:file "<stdin>", :row 1, :col 20, :level :warning, :message #"require with :refer"}] (lint! "(require '[foo.bar :refer [macro]]) (macro) " {:linters {:refer {:level :warning} :refer-all {:level :off}}})) (is (empty? (lint! "(ns foo (:require [foo.bar :as foo])) (foo/bazbar)" {:linters {:refer {:level :warning}}}))) (is (empty? (lint! "(ns foo (:require [clojure.test :refer [deftest]])) deftest" '{:linters {:refer {:level :warning :exclude [clojure.test]}}})))) (deftest missing-else-branch-test (assert-submaps [{:file "<stdin>", :row 1, :col 1, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 13, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 29, :level :warning, :message "Missing else branch."} {:file "<stdin>", :row 1, :col 46, :level :warning, :message "Missing else branch."}] (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)")) (is (empty? (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)" {:linters {:missing-else-branch {:level :off}}}))) (is (empty? (lint! "(if true 1) (if-not true 1) (if-let [x 1] x) (if-some [x 1] x)" {:linters {:if {:level :off}}})))) (deftest single-key-in-test (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 12, :level :warning, :message "get-in with single key"}) (lint! "(get-in {} [:k])" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 14, :level :warning, :message "assoc-in with single key"}) (lint! "(assoc-in {} [:k] :v)" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (doseq [lang ["clj" "cljs"]] (assert-submaps '({:file "<stdin>", :row 1, :col 15, :level :warning, :message "update-in with single key"}) (lint! "(update-in {} [:k] inc)" "--lang" lang "--config" {:linters {:single-key-in {:level :warning}}}))) (is (empty? (lint! "(get-in {} [:k1 :k2])" {:linters {:single-key-in {:level :warning}}}))) (is (empty? (lint! "(get-in {} (keys-fn))" {:linters {:single-key-in {:level :warning}}}))) (testing "don't throw exception when args are missing" (is (some? (lint! "(assoc-in)"))))) (deftest multiple-options-test (testing "multiple --lint option" (let [out (edn/read-string (with-out-str (main "--lint" "corpus/case.clj" "--lint" "corpus/defmulti.clj" "--config" "{:output {:format :edn}}")))] (is (= #{"corpus/case.clj" "corpus/defmulti.clj"} (into #{} (comp (map :filename) (distinct)) (:findings out)))) (is (= {:error 6 :warning 2 :info 0} (select-keys (:summary out) [:error :warning :info]))))) (testing "multiple --config option" (let [out (edn/read-string (with-out-str (main "--lint" "corpus/case.clj" "--lint" "corpus/defmulti.clj" "--config" "{:output {:format :edn}}" "--config" "{:linters {:invalid-arity {:level :warning}}}")))] (is (= {:error 1 :warning 7 :info 0} (select-keys (:summary out) [:error :warning :info])))))) (deftest config-dir-test (is (seq (lint! (io/file "corpus" "config_dir" "foo.clj") {:linters {:unresolved-symbol {:level :error}}}))) (is (empty (lint! (io/file "corpus" "config_dir" "foo.clj") {:linters {:unresolved-symbol {:level :error}}} "--config-dir" (.getPath (io/file "corpus" "config_dir")))))) (deftest cljc-features-test (is (seq (lint! "(set! *warn-on-reflection* true)" {:linters {:unresolved-symbol {:level :error}}} "--lang" "cljc"))) (is (empty? (lint! "(set! *warn-on-reflection* true)" {:cljc {:features [:clj]} :linters {:unresolved-symbol {:level :error}}} "--lang" "cljc")))) (deftest continue-on-invalid-token-code-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "Invalid symbol: foo/."} {:file "<stdin>", :row 3, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! " foo/ (inc)")) (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"} {:file "<stdin>", :row 3, :col 1, :level :error, :message "Invalid symbol: foo/."}) (lint! " (inc) foo/"))) (deftest continue-on-invalid-keyword-test (assert-submaps '({:file "<stdin>", :row 2, :col 1, :level :error, :message "A single colon is not a valid keyword."} {:file "<stdin>", :row 3, :col 1, :level :error, :message "clojure.core/inc is called with 0 args but expects 1"}) (lint! " : (inc)"))) (deftest nested-fn-literal-test (assert-submaps '({:file "<stdin>", :row 2, :col 7, :level :error, :message "Nested #()s are not allowed"}) (lint! " #(inc #(inc %))"))) (deftest destructuring-syntax-test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Keys in :or should be simple symbols."}) (lint! "(defn baz [a & {:keys [c] :or {:c 10}}] (* a c))")) (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Keys in :or should be simple symbols."}) (lint! "(defn baz [a & {:keys [c] :or {\"c\" 10}}] (* a c))"))) (deftest do-template-test (assert-submaps '({:file "<stdin>", :row 4, :col 4, :level :error, :message "Unresolved symbol: f"} {:file "<stdin>", :row 4, :col 6, :level :error, :message "Unresolved symbol: g"}) (lint! "(require '[clojure.template :as templ]) (templ/do-template [a b] (def a b) x 1 y 2) (+ x y) (+ f g)" {:linters {:unresolved-symbol {:level :error}}}))) (deftest def-and-alias-with-qualified-symbols (testing "see GH-1326" (is (empty? (lint! "(ns foo) (alias 'f 'foo) (declare f/x) f/x x (def f/x 1)"))) (is (empty? (lint! "(ns foo) (declare foo/x) foo/x x (def foo/x 1)"))) (assert-submaps (lint! "(declare foo/x) foo/x x (def foo/x 1)") '({:file "<stdin>", :row 1, :col 10, :level :error, :message "Invalid var name: foo/x"} {:file "<stdin>", :row 1, :col 17, :level :warning, :message "Unresolved namespace foo. Are you missing a require?"} {:file "<stdin>", :row 1, :col 30, :level :error, :message "Invalid var name: foo/x"})))) (deftest issue-1366-conflicting-user-ns (let [expected-filename (tu/normalize-filename "corpus/issue-1366/dir-1/user.clj")] (is (apply = expected-filename (map (comp tu/normalize-filename :filename) (:findings (clj-kondo/run! {:lint ["corpus/issue-1366/dir-1" "corpus/issue-1366/dir-2"]}))))))) (deftest loop-without-recur (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [])" {:linters {:loop-without-recur {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [] (fn [] (recur)))" {:linters {:loop-without-recur {:level :warning}}})) (assert-submaps '({:file "<stdin>", :row 1, :col 1, :level :warning, :message "Loop without recur."}) (lint! "(loop [] (future (recur)))" {:linters {:loop-without-recur {:level :warning}}})) (is (empty? (lint! "(loop [] (recur))" {:linters {:loop-without-recur {:level :warning}}})))) (deftest as-alias-test (assert-submaps2 '(#_{:file "<stdin>", :row 1, :col 20, :level :warning, :message "namespace foo.bar is required but never used"} {:file "<stdin>", :row 1, :col 44, :level :warning, :message "Unresolved namespace fx. Are you missing a require?"}) (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fx/bar")) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fb/bar")))) (deftest as-aliased-var-usage-test (assert-submaps2 [{:row 1, :col 44, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) fb/bar")) (assert-submaps2 [{:row 1, :col 45, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) (fb/bar)")) (assert-submaps2 [{:file "<stdin>", :row 1, :col 47, :level :warning, :message "Namespace only aliased but wasn't loaded: foo.bar"}] (lint! "(ns foo (:require [foo.bar :as-alias fb])) `[~fb/bar]")) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) ::fb/bar"))) (is (empty? (lint! "(ns foo (:require [foo.bar :as-alias fb])) `fb/bar")))) (deftest ns-unmap-test (assert-submaps '({:file "<stdin>", :row 1, :col 32, :level :error, :message "Unresolved symbol: inc"}) (lint! "(ns foo) (ns-unmap *ns* 'inc) (inc 1)" {:linters {:unresolved-symbol {:level :error}}})) (is (empty? (lint! "(doseq [sym ['foo 'bar 'baz]] (ns-unmap *ns* sym))" {:linters {:unused-binding {:level :warning}}})))) (deftest duplicate-files (is (empty? (lint! [(io/file "corpus" "simple_test") (io/file "corpus" "simple_test" "a_test.clj")] "--config" "{:linters {:redefined-var {:level :error}}}")))) (deftest main-without-gen-class (is (= '({:file "<stdin>", :row 5, :col 1, :level :warning, :message "Main function without gen-class."}) (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}} #_(:gen-class)) (defn -main [& _args]) "))) (is (empty? (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}} (:gen-class)) (defn -main [& _args]) "))) (testing "in CLJS you'll never get a warning" (is (empty? (lint! "(ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}}) (defn -main [& _args]) " "--lang" "cljs")))) (testing "gen-class as macro outside ns form" (is (empty? (lint! " (ns foo {:clj-kondo/config {:linters {:main-without-gen-class {:level :warning}}}}) (gen-class) (defn -main []) "))))) (deftest CLJS-3330-deprecate-global-goog-modules see (assert-submaps '({:file "<stdin>", :row 1, :col 2, :level :warning, :message "Unresolved namespace goog.object. Are you missing a require?"}) (lint! "(goog.object/get #js {:a 1} \"a\")" "--lang" "cljs"))) (deftest clojure-test-check-properties-for-all-test (is (empty? (lint! "(require '[clojure.test.check.properties :refer [for-all]] '[clojure.test.check.generators :as gen]) (for-all [a gen/large-integer b gen/large-integer] (>= (+ a b) a))" {:linters {:unresolved-symbol {:level :error}}})))) (deftest special-form-test (is (empty? (lint! "(defn new [] :foo) (new js/Date 2022 1 1 1 1)" "--lang" "cljs")))) (comment (inline-def-test) (redundant-let-test) (redundant-do-test) (exit-code-test) (t/run-tests) )
4b57c5943ba4e68b2bb4a559801c903bde532174ff7d4d3ffb8100f20203df63
kappelmann/eidi2_repetitorium_tum
ha5.mli
val superfib : int -> int val inv_cantor : int -> int * int val is_insert : (int -> int -> bool) -> int -> int list -> int list val insertion_sort : int list -> (int -> int -> bool) -> int list val scale_apply : int list -> (int -> int) list -> int list type person = { name : string; age : int; } type tree = Node of tree * tree * person | Leaf val singleton : person -> tree val insert : person -> tree -> tree val to_sorted_list : tree -> person list
null
https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/additional_exercises/2016_17/Blatt%205%20L%C3%B6sungen/ocaml/ha5.mli
ocaml
val superfib : int -> int val inv_cantor : int -> int * int val is_insert : (int -> int -> bool) -> int -> int list -> int list val insertion_sort : int list -> (int -> int -> bool) -> int list val scale_apply : int list -> (int -> int) list -> int list type person = { name : string; age : int; } type tree = Node of tree * tree * person | Leaf val singleton : person -> tree val insert : person -> tree -> tree val to_sorted_list : tree -> person list
3f62e58de26e011296f4ce9cbd384192b22a9e0c2aa2529ff2dbea2e82a71f0b
malcolmreynolds/GSLL
landau.lisp
distribution , Sat Sep 30 2006 Time - stamp : < 2009 - 05 - 24 20:08:47EDT landau.lisp > $ Id$ (in-package :gsl) ;;; /usr/include/gsl/gsl_randist.h (defmfun sample ((generator random-number-generator) (type (eql 'landau)) &key) "gsl_ran_landau" (((mpointer generator) :pointer)) :definition :method :c-return :double "A random variate from the Landau distribution. The probability distribution for Landau random variates is defined analytically by the complex integral, {1 \over {2 \pi i}} \int_{c-i\infty}^{c+i\infty} ds\, \exp(s \log(s) + x s) For numerical purposes it is more convenient to use the following equivalent form of the integral, p(x) = (1/\pi) \int_0^\infty dt \exp(-t \log(t) - x t) \sin(\pi t).") (defmfun landau-pdf (x) "gsl_ran_landau_pdf" ((x :double)) :c-return :double "The probability density p(x) at x for the Landau distribution using an approximation to the formula given in #'landau.") ;;; Examples and unit test (save-test landau (let ((rng (make-random-number-generator +mt19937+ 0))) (loop for i from 0 to 10 collect (sample rng 'landau))) (landau-pdf 0.25d0))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/random/landau.lisp
lisp
/usr/include/gsl/gsl_randist.h Examples and unit test
distribution , Sat Sep 30 2006 Time - stamp : < 2009 - 05 - 24 20:08:47EDT landau.lisp > $ Id$ (in-package :gsl) (defmfun sample ((generator random-number-generator) (type (eql 'landau)) &key) "gsl_ran_landau" (((mpointer generator) :pointer)) :definition :method :c-return :double "A random variate from the Landau distribution. The probability distribution for Landau random variates is defined analytically by the complex integral, {1 \over {2 \pi i}} \int_{c-i\infty}^{c+i\infty} ds\, \exp(s \log(s) + x s) For numerical purposes it is more convenient to use the following equivalent form of the integral, p(x) = (1/\pi) \int_0^\infty dt \exp(-t \log(t) - x t) \sin(\pi t).") (defmfun landau-pdf (x) "gsl_ran_landau_pdf" ((x :double)) :c-return :double "The probability density p(x) at x for the Landau distribution using an approximation to the formula given in #'landau.") (save-test landau (let ((rng (make-random-number-generator +mt19937+ 0))) (loop for i from 0 to 10 collect (sample rng 'landau))) (landau-pdf 0.25d0))
7359ed3c7c102b386c6eacaa97fbb10b953c64760d5ca08a3f665e8083bc59fb
graninas/Hydra
Interpreter.hs
module Hydra.Core.CliHandlers.Interpreter where import Hydra.Prelude import qualified Data.Map as Map import qualified Hydra.Core.CliHandlers.Language as L import qualified Hydra.Core.Lang.Language as L type Handlers a = IORef (Map.Map String (L.LangL a)) interpretCliHandlerL :: Handlers a -> L.CliHandlerF a b -> IO b interpretCliHandlerL handlersRef (L.Cmd cmdStr method next) = do modifyIORef' handlersRef (Map.insert cmdStr method) pure $ next () runCliHandlerL :: Handlers a -> L.CliHandlerL a () -> IO () runCliHandlerL handlersRef = foldFree (interpretCliHandlerL handlersRef)
null
https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-free/src/Hydra/Core/CliHandlers/Interpreter.hs
haskell
module Hydra.Core.CliHandlers.Interpreter where import Hydra.Prelude import qualified Data.Map as Map import qualified Hydra.Core.CliHandlers.Language as L import qualified Hydra.Core.Lang.Language as L type Handlers a = IORef (Map.Map String (L.LangL a)) interpretCliHandlerL :: Handlers a -> L.CliHandlerF a b -> IO b interpretCliHandlerL handlersRef (L.Cmd cmdStr method next) = do modifyIORef' handlersRef (Map.insert cmdStr method) pure $ next () runCliHandlerL :: Handlers a -> L.CliHandlerL a () -> IO () runCliHandlerL handlersRef = foldFree (interpretCliHandlerL handlersRef)
418e48e24538fea8acb2e0f90be5f2476c9d43ce351ee5bfd390bff3884c90de
dmillett/political-canvas
ordinance.clj
(ns political-canvas.law.example.ordinance (:require [political-canvas.shared.example.ward :as local])) ;; ; This is an example of a local ordinance that restricts nightime urban ; lighting to reduce light polution, yet maintain pedestrian safety. ; ; Allow for versioning of laws and ordinances with source control (git) ; where authors/sponsors own commit history (no forced updates!) (def clean_urban_lighting "An example local ordinance which targets excessive urban lighting." {:type "LOCAL-ORDINANCE" :district local/ward1 :summary "To reduce urban light pollution while maintaining resident safety." :description "To reduce light pollution, maintain resident safety, and reduce electricity through the use of smart sidewalk lights with motion detection sensors" :examples [{}] :status "PLANNING" :effective-date "20180101" :authors [{:name "dmillett" :created "20170208"}] :sponsors [] :history [{:status "PLANNING" :date "20170208"} {:status "INTRODUCTION" :date "20170228"}]})
null
https://raw.githubusercontent.com/dmillett/political-canvas/ec59a065b832277ec06f80e67977eee196a6a194/src/political_canvas/law/example/us/local/ordinance.clj
clojure
This is an example of a local ordinance that restricts nightime urban lighting to reduce light polution, yet maintain pedestrian safety. Allow for versioning of laws and ordinances with source control (git) where authors/sponsors own commit history (no forced updates!)
(ns political-canvas.law.example.ordinance (:require [political-canvas.shared.example.ward :as local])) (def clean_urban_lighting "An example local ordinance which targets excessive urban lighting." {:type "LOCAL-ORDINANCE" :district local/ward1 :summary "To reduce urban light pollution while maintaining resident safety." :description "To reduce light pollution, maintain resident safety, and reduce electricity through the use of smart sidewalk lights with motion detection sensors" :examples [{}] :status "PLANNING" :effective-date "20180101" :authors [{:name "dmillett" :created "20170208"}] :sponsors [] :history [{:status "PLANNING" :date "20170208"} {:status "INTRODUCTION" :date "20170228"}]})
b2f90faa6d96091e67358231f44ae4bd667e6af6334d49091ef0d7275fd517c7
faylang/fay
StringForcing.hs
module StringForcing where import FFI main = do let s1 = "alma" let s2 = s1 ++ map id s1 putStrLn s1 putStrLn s2
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/StringForcing.hs
haskell
module StringForcing where import FFI main = do let s1 = "alma" let s2 = s1 ++ map id s1 putStrLn s1 putStrLn s2
4157af1c3ffc5a94cb21d3a39ccd2a2e92d01eebb4f10ee02c2778170806a5f8
crategus/cl-cffi-gtk
gtk.drawing-area.lisp
;;; ---------------------------------------------------------------------------- ;;; gtk.drawing-area.lisp ;;; The documentation of this file is taken from the GTK+ 3 Reference Manual Version 3.24 and modified to document the Lisp binding to the GTK library . ;;; See <>. The API documentation of the Lisp binding is available from < -cffi-gtk/ > . ;;; Copyright ( C ) 2009 - 2011 Copyright ( C ) 2011 - 2021 ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU Lesser General Public License for Lisp as published by the Free Software Foundation , either version 3 of the ;;; License, or (at your option) any later version and with a preamble to the GNU Lesser General Public License that clarifies the terms for use ;;; with Lisp programs and is referred as the LLGPL. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . ;;; You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser ;;; General Public License. If not, see </> ;;; and <>. ;;; ---------------------------------------------------------------------------- ;;; ;;; GtkDrawingArea ;;; ;;; A widget for custom user interface elements ;;; ;;; Values and Types ;;; ;;; GtkDrawingArea ;;; ;;; Functions ;;; ;;; gtk_drawing_area_new ;;; ;;; Object Hierarchy ;;; ;;; GObject ;;; ╰── GInitiallyUnowned ╰ ─ ─ ;;; ╰── GtkDrawingArea ;;; ;;; Implemented Interfaces ;;; ;;; GtkDrawingArea implements AtkImplementorIface and GtkBuildable. ;;; ---------------------------------------------------------------------------- (in-package :gtk) ;;; ---------------------------------------------------------------------------- ;;; struct GtkDrawingArea ;;; ---------------------------------------------------------------------------- (define-g-object-class "GtkDrawingArea" gtk-drawing-area (:superclass gtk-widget :export t :interfaces ("AtkImplementorIface" "GtkBuildable") :type-initializer "gtk_drawing_area_get_type") nil) #+cl-cffi-gtk-documentation (setf (documentation 'gtk-drawing-area 'type) "@version{*2021-11-30} @begin{short} The @sym{gtk-drawing-area} widget is used for creating custom user interface elements. It is essentially a blank widget. You can draw on it. @end{short} After creating a drawing area, the application may want to connect to: @begin{itemize} @begin{item} Mouse and button press signals to respond to input from the user. Use the @fun{gtk-widget-add-events} function to enable events you wish to receive. @end{item} @begin{item} The \"realize\" signal to take any necessary actions when the widget is instantiated on a particular display. Create GDK resources in response to this signal. @end{item} @begin{item} The \"configure-event\" signal to take any necessary actions when the widget changes size. @end{item} @begin{item} The \"draw\" signal to handle redrawing the contents of the widget. @end{item} @end{itemize} Draw signals are normally delivered when a drawing area first comes onscreen, or when it is covered by another window and then uncovered. You can also force an expose event by adding to the \"damage region\" of the drawing area's window. The @fun{gtk-widget-queue-draw-area} and @fun{gdk-window-invalidate-rect} functions are equally good ways to do this. You will then get a draw signal for the invalid region. To receive mouse events on a drawing area, you will need to enable them with the @fun{gtk-widget-add-events} function. To receive keyboard events, you will need to set the @slot[gtk-widget]{can-focus} property on the drawing area, and you should probably draw some user visible indication that the drawing area is focused. Use the @fun{gtk-widget-has-focus} function in your expose event handler to decide whether to draw the focus indicator. See the @see-function{gtk-render-focus} function for one way to draw focus. @begin[Example]{dictionary} The following example demonstrates using a drawing area to display a circle in the normal widget foreground color. Note that GDK automatically clears the exposed area before sending the expose event, and that drawing is implicitly clipped to the exposed area. If you want to have a theme-provided background, you need to call the @fun{gtk-render-background} function in your \"draw\" signal handler. @begin{pre} (defun example-drawing-area () (within-main-loop (let ((window (make-instance 'gtk-window :type :toplevel :title \"Example Drawing Area\" :default-width 400 :default-height 300)) ;; Create the drawing area (area (make-instance 'gtk-drawing-area))) Signal handler for the drawing area (g-signal-connect area \"draw\" (lambda (widget cr) (let* ((cr (pointer cr)) (width (gtk-widget-allocated-width widget)) (height (gtk-widget-allocated-height widget)) (context (gtk-widget-style-context widget)) (color (gtk-style-context-color context :focused))) ;; Set the color from the style context of the widget (gdk-cairo-set-source-rgba cr color) ;; Draw and fill a circle on the drawing area (cairo-arc cr (/ width 2.0) (/ height 2.0) (- (/ (min width height) 2.0) 12) 0.0 (* 2.0 pi)) (cairo-fill cr) Destroy the Cairo context (cairo-destroy cr)))) Signal handler for the window to handle the signal \"destroy\ " (g-signal-connect window \"destroy\" (lambda (widget) (declare (ignore widget)) (leave-gtk-main))) ;; Show the window (gtk-container-add window area) (gtk-widget-show-all window)))) @end{pre} @end{dictionary} @see-function{gtk-widget-add-events} @see-function{gtk-widget-queue-draw-area} @see-function{gdk-window-invalidate-rect} @see-function{gtk-widget-has-focus} @see-function{gtk-render-focus} @see-function{gtk-render-background}") ;;; ---------------------------------------------------------------------------- ;;; gtk_drawing_area_new () ;;; ---------------------------------------------------------------------------- (declaim (inline gtk-drawing-area-new)) (defun gtk-drawing-area-new () #+cl-cffi-gtk-documentation "@version{2021-11-30} @return{A new @class{gtk-drawing-area} widget.} @begin{short} Creates a new drawing area. @end{short} @see-class{gtk-drawing-area}" (make-instance 'gtk-drawing-area)) (export 'gtk-drawing-area-new) ;;; --- End of file gtk.drawing-area.lisp --------------------------------------
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gtk/gtk.drawing-area.lisp
lisp
---------------------------------------------------------------------------- gtk.drawing-area.lisp See <>. The API documentation of the Lisp binding is This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License for Lisp License, or (at your option) any later version and with a preamble to with Lisp programs and is referred as the LLGPL. 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 General Public License. If not, see </> and <>. ---------------------------------------------------------------------------- GtkDrawingArea A widget for custom user interface elements Values and Types GtkDrawingArea Functions gtk_drawing_area_new Object Hierarchy GObject ╰── GInitiallyUnowned ╰── GtkDrawingArea Implemented Interfaces GtkDrawingArea implements AtkImplementorIface and GtkBuildable. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- struct GtkDrawingArea ---------------------------------------------------------------------------- Create the drawing area Set the color from the style context of the widget Draw and fill a circle on the drawing area Show the window ---------------------------------------------------------------------------- gtk_drawing_area_new () ---------------------------------------------------------------------------- --- End of file gtk.drawing-area.lisp --------------------------------------
The documentation of this file is taken from the GTK+ 3 Reference Manual Version 3.24 and modified to document the Lisp binding to the GTK library . available from < -cffi-gtk/ > . Copyright ( C ) 2009 - 2011 Copyright ( C ) 2011 - 2021 as published by the Free Software Foundation , either version 3 of the the GNU Lesser General Public License that clarifies the terms for use GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser ╰ ─ ─ (in-package :gtk) (define-g-object-class "GtkDrawingArea" gtk-drawing-area (:superclass gtk-widget :export t :interfaces ("AtkImplementorIface" "GtkBuildable") :type-initializer "gtk_drawing_area_get_type") nil) #+cl-cffi-gtk-documentation (setf (documentation 'gtk-drawing-area 'type) "@version{*2021-11-30} @begin{short} The @sym{gtk-drawing-area} widget is used for creating custom user interface elements. It is essentially a blank widget. You can draw on it. @end{short} After creating a drawing area, the application may want to connect to: @begin{itemize} @begin{item} Mouse and button press signals to respond to input from the user. Use the @fun{gtk-widget-add-events} function to enable events you wish to receive. @end{item} @begin{item} The \"realize\" signal to take any necessary actions when the widget is instantiated on a particular display. Create GDK resources in response to this signal. @end{item} @begin{item} The \"configure-event\" signal to take any necessary actions when the widget changes size. @end{item} @begin{item} The \"draw\" signal to handle redrawing the contents of the widget. @end{item} @end{itemize} Draw signals are normally delivered when a drawing area first comes onscreen, or when it is covered by another window and then uncovered. You can also force an expose event by adding to the \"damage region\" of the drawing area's window. The @fun{gtk-widget-queue-draw-area} and @fun{gdk-window-invalidate-rect} functions are equally good ways to do this. You will then get a draw signal for the invalid region. To receive mouse events on a drawing area, you will need to enable them with the @fun{gtk-widget-add-events} function. To receive keyboard events, you will need to set the @slot[gtk-widget]{can-focus} property on the drawing area, and you should probably draw some user visible indication that the drawing area is focused. Use the @fun{gtk-widget-has-focus} function in your expose event handler to decide whether to draw the focus indicator. See the @see-function{gtk-render-focus} function for one way to draw focus. @begin[Example]{dictionary} The following example demonstrates using a drawing area to display a circle in the normal widget foreground color. Note that GDK automatically clears the exposed area before sending the expose event, and that drawing is implicitly clipped to the exposed area. If you want to have a theme-provided background, you need to call the @fun{gtk-render-background} function in your \"draw\" signal handler. @begin{pre} (defun example-drawing-area () (within-main-loop (let ((window (make-instance 'gtk-window :type :toplevel :title \"Example Drawing Area\" :default-width 400 :default-height 300)) (area (make-instance 'gtk-drawing-area))) Signal handler for the drawing area (g-signal-connect area \"draw\" (lambda (widget cr) (let* ((cr (pointer cr)) (width (gtk-widget-allocated-width widget)) (height (gtk-widget-allocated-height widget)) (context (gtk-widget-style-context widget)) (color (gtk-style-context-color context :focused))) (gdk-cairo-set-source-rgba cr color) (cairo-arc cr (/ width 2.0) (/ height 2.0) (- (/ (min width height) 2.0) 12) 0.0 (* 2.0 pi)) (cairo-fill cr) Destroy the Cairo context (cairo-destroy cr)))) Signal handler for the window to handle the signal \"destroy\ " (g-signal-connect window \"destroy\" (lambda (widget) (declare (ignore widget)) (leave-gtk-main))) (gtk-container-add window area) (gtk-widget-show-all window)))) @end{pre} @end{dictionary} @see-function{gtk-widget-add-events} @see-function{gtk-widget-queue-draw-area} @see-function{gdk-window-invalidate-rect} @see-function{gtk-widget-has-focus} @see-function{gtk-render-focus} @see-function{gtk-render-background}") (declaim (inline gtk-drawing-area-new)) (defun gtk-drawing-area-new () #+cl-cffi-gtk-documentation "@version{2021-11-30} @return{A new @class{gtk-drawing-area} widget.} @begin{short} Creates a new drawing area. @end{short} @see-class{gtk-drawing-area}" (make-instance 'gtk-drawing-area)) (export 'gtk-drawing-area-new)
0a18b4761c444288c64333b9d676a3199d3518fc9ca6722108051213ab98efe8
kadena-io/chainweaver
Repl.hs
# LANGUAGE DataKinds # # LANGUAGE ExtendedDefaultRules # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # -- | Copyright : ( C ) 2020 - 2022 Kadena -- License : BSD-style (see the file LICENSE) -- module Frontend.UI.Repl where ------------------------------------------------------------------------------ import Control.Lens import Control.Monad.State.Strict import qualified Data.List.Zipper as Z import Data.Maybe import Data.Text (Text) import Language.Javascript.JSaddle hiding (Object) import Reflex import Reflex.Dom.Core import GHC.Exts (toList) import GHCJS.DOM.Element (scrollIntoView) ------------------------------------------------------------------------------ import Frontend.Repl import Frontend.UI.Widgets (addNoAutofillAttrs, setFocusOn) ------------------------------------------------------------------------------ data ClickState = DownAt (Int, Int) | Clicked | Selected deriving (Eq,Ord,Show,Read) data DisplayedSnippet = InputSnippet Text | OutputSnippet Text | OldOutputSnippet Text deriving (Eq,Ord,Show,Read) staticReplHeader :: DomBuilder t m => m () staticReplHeader = divClass "repl__header" $ do let section = divClass "repl__header-section" separator = divClass "repl__header-separator" $ el "hr" blank code = divClass "repl__header-code" . text plain = divClass "repl__header-plain" . text quote = divClass "repl__header-quote" . text bannerText = divClass "repl__header-banner repl__header-banner-text" . text bannerDecoration = divClass "repl__header-banner repl__header-banner-decoration" . text section $ do bannerDecoration ".::" bannerText " Welcome to the Pact interactive REPL " bannerDecoration "::." section $ do plain "Use" quote " 'LOAD into REPL' " plain "button to execute editor text. Then just type at the " code " \"pact>\" " plain "prompt to interact!" section $ do plain "To reset the REPL type " code "'reset'" section separator snippetWidget' :: MonadWidget t m => DisplayedSnippet -> m (Element EventResult (DomBuilderSpace m) t) snippetWidget' = fmap fst . \case InputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block") $ replPrompt *> text t OutputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block") $ text t OldOutputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block code-font_old") $ text t snippetWidget :: MonadWidget t m => DisplayedSnippet -> m () snippetWidget = void . snippetWidget' displayReplOutput :: MonadWidget t m => ReplOutput -> m () displayReplOutput = snippetWidget . replOutToDisplayed where replOutToDisplayed = \case ReplOutput_Cmd t -> InputSnippet t ReplOutput_Res t -> OutputSnippet t replWidget :: (MonadWidget t m, HasWebRepl model t, HasReplCfg mConf t, Monoid mConf) => model -> m mConf replWidget m = do (e, onNewInput) <- elClass' "div" "repl" $ do staticReplHeader void $ simpleList (toList <$> m ^. repl_output) (dyn . fmap displayReplOutput) replInput m clickType <- foldDyn ($) Nothing $ leftmost [ setDown <$> domEvent Mousedown e , clickClassifier <$> domEvent Mouseup e ] let replClick = () <$ ffilter (== Just Clicked) (updated clickType) setFocusOn e "input" replClick let onReset = () <$ ffilter (== "reset") onNewInput onCmd = ffilter (/= "reset") onNewInput pure $ mempty & replCfg_sendCmd .~ onCmd & replCfg_reset .~ onReset replPrompt :: DomBuilder t m => m () replPrompt = elClass "div" "repl__prompt" $ text "pact>" replInput :: (MonadWidget t m, HasWebRepl model t) => model -> m (Event t Text) replInput m = do divClass "repl__input-controls" $ mdo replPrompt let sv = leftmost [ mempty <$ enterPressed , fromMaybe "" . Z.safeCursor <$> tagPromptlyDyn commandHistory key ] ti <- textInput (def & textInputConfig_setValue .~ sv & textInputConfig_attributes .~ pure (addNoAutofillAttrs $ "class" =: "code-font repl__input") ) let key = ffilter isMovement $ domEvent Keydown ti let enterPressed = keypress Enter ti let newCommand = tag (current $ value ti) enterPressed commandHistory <- foldDyn ($) Z.empty $ leftmost [ addToHistory <$> newCommand , moveHistory <$> key ] doScrollIntoView ti return newCommand where doScrollIntoView ti = do onPostBuild <- getPostBuild onReady <- delay 0.1 $ leftmost [onPostBuild, () <$ m ^. repl_newOutput] performEvent_ $ ffor onReady $ \_ -> liftJSM $ scrollIntoView (_textInput_element ti) True addToHistory :: Eq a => a -> Z.Zipper a -> Z.Zipper a addToHistory a z = if Just a == Z.safeCursor (Z.left zEnd) then zEnd else Z.push a zEnd where zEnd = Z.end z isMovement :: (Num a, Eq a) => a -> Bool isMovement 38 = True isMovement 40 = True isMovement _ = False moveHistory :: (Num a1, Eq a1) => a1 -> Z.Zipper a -> Z.Zipper a moveHistory 38 = Z.left moveHistory 40 = Z.right moveHistory _ = id setDown :: (Int, Int) -> t -> Maybe ClickState setDown clickLoc _ = Just $ DownAt clickLoc clickClassifier :: (Int, Int) -> Maybe ClickState -> Maybe ClickState clickClassifier clickLoc (Just (DownAt loc1)) = if clickLoc == loc1 then Just Clicked else Just Selected clickClassifier _ _ = Nothing
null
https://raw.githubusercontent.com/kadena-io/chainweaver/5d40e91411995e0a9a7e782d6bb2d89ac1c65d52/frontend/src/Frontend/UI/Repl.hs
haskell
# LANGUAGE OverloadedStrings # | License : BSD-style (see the file LICENSE) ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------------------
# LANGUAGE DataKinds # # LANGUAGE ExtendedDefaultRules # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # Copyright : ( C ) 2020 - 2022 Kadena module Frontend.UI.Repl where import Control.Lens import Control.Monad.State.Strict import qualified Data.List.Zipper as Z import Data.Maybe import Data.Text (Text) import Language.Javascript.JSaddle hiding (Object) import Reflex import Reflex.Dom.Core import GHC.Exts (toList) import GHCJS.DOM.Element (scrollIntoView) import Frontend.Repl import Frontend.UI.Widgets (addNoAutofillAttrs, setFocusOn) data ClickState = DownAt (Int, Int) | Clicked | Selected deriving (Eq,Ord,Show,Read) data DisplayedSnippet = InputSnippet Text | OutputSnippet Text | OldOutputSnippet Text deriving (Eq,Ord,Show,Read) staticReplHeader :: DomBuilder t m => m () staticReplHeader = divClass "repl__header" $ do let section = divClass "repl__header-section" separator = divClass "repl__header-separator" $ el "hr" blank code = divClass "repl__header-code" . text plain = divClass "repl__header-plain" . text quote = divClass "repl__header-quote" . text bannerText = divClass "repl__header-banner repl__header-banner-text" . text bannerDecoration = divClass "repl__header-banner repl__header-banner-decoration" . text section $ do bannerDecoration ".::" bannerText " Welcome to the Pact interactive REPL " bannerDecoration "::." section $ do plain "Use" quote " 'LOAD into REPL' " plain "button to execute editor text. Then just type at the " code " \"pact>\" " plain "prompt to interact!" section $ do plain "To reset the REPL type " code "'reset'" section separator snippetWidget' :: MonadWidget t m => DisplayedSnippet -> m (Element EventResult (DomBuilderSpace m) t) snippetWidget' = fmap fst . \case InputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block") $ replPrompt *> text t OutputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block") $ text t OldOutputSnippet t -> elAttr' "code" ("class" =: "code-font code-font_block code-font_old") $ text t snippetWidget :: MonadWidget t m => DisplayedSnippet -> m () snippetWidget = void . snippetWidget' displayReplOutput :: MonadWidget t m => ReplOutput -> m () displayReplOutput = snippetWidget . replOutToDisplayed where replOutToDisplayed = \case ReplOutput_Cmd t -> InputSnippet t ReplOutput_Res t -> OutputSnippet t replWidget :: (MonadWidget t m, HasWebRepl model t, HasReplCfg mConf t, Monoid mConf) => model -> m mConf replWidget m = do (e, onNewInput) <- elClass' "div" "repl" $ do staticReplHeader void $ simpleList (toList <$> m ^. repl_output) (dyn . fmap displayReplOutput) replInput m clickType <- foldDyn ($) Nothing $ leftmost [ setDown <$> domEvent Mousedown e , clickClassifier <$> domEvent Mouseup e ] let replClick = () <$ ffilter (== Just Clicked) (updated clickType) setFocusOn e "input" replClick let onReset = () <$ ffilter (== "reset") onNewInput onCmd = ffilter (/= "reset") onNewInput pure $ mempty & replCfg_sendCmd .~ onCmd & replCfg_reset .~ onReset replPrompt :: DomBuilder t m => m () replPrompt = elClass "div" "repl__prompt" $ text "pact>" replInput :: (MonadWidget t m, HasWebRepl model t) => model -> m (Event t Text) replInput m = do divClass "repl__input-controls" $ mdo replPrompt let sv = leftmost [ mempty <$ enterPressed , fromMaybe "" . Z.safeCursor <$> tagPromptlyDyn commandHistory key ] ti <- textInput (def & textInputConfig_setValue .~ sv & textInputConfig_attributes .~ pure (addNoAutofillAttrs $ "class" =: "code-font repl__input") ) let key = ffilter isMovement $ domEvent Keydown ti let enterPressed = keypress Enter ti let newCommand = tag (current $ value ti) enterPressed commandHistory <- foldDyn ($) Z.empty $ leftmost [ addToHistory <$> newCommand , moveHistory <$> key ] doScrollIntoView ti return newCommand where doScrollIntoView ti = do onPostBuild <- getPostBuild onReady <- delay 0.1 $ leftmost [onPostBuild, () <$ m ^. repl_newOutput] performEvent_ $ ffor onReady $ \_ -> liftJSM $ scrollIntoView (_textInput_element ti) True addToHistory :: Eq a => a -> Z.Zipper a -> Z.Zipper a addToHistory a z = if Just a == Z.safeCursor (Z.left zEnd) then zEnd else Z.push a zEnd where zEnd = Z.end z isMovement :: (Num a, Eq a) => a -> Bool isMovement 38 = True isMovement 40 = True isMovement _ = False moveHistory :: (Num a1, Eq a1) => a1 -> Z.Zipper a -> Z.Zipper a moveHistory 38 = Z.left moveHistory 40 = Z.right moveHistory _ = id setDown :: (Int, Int) -> t -> Maybe ClickState setDown clickLoc _ = Just $ DownAt clickLoc clickClassifier :: (Int, Int) -> Maybe ClickState -> Maybe ClickState clickClassifier clickLoc (Just (DownAt loc1)) = if clickLoc == loc1 then Just Clicked else Just Selected clickClassifier _ _ = Nothing
4b619a4a299ede79007023ecea0582f298329ebec1635ba65d7fc2af931a8468
PrincetonUniversity/lucid
DockerUtils.ml
(* parse command line arguments for docker. Return: spec: spec file main: main source file include: other source file include: other source file ... *) open Batteries open Dpt let cfg = Cmdline.cfg let find_spec_file dpt_file = if not (String.ends_with dpt_file ".dpt") then None else ( let json_name = String.rchop ~n:4 dpt_file ^ ".json" in if Sys.file_exists json_name then ( if not cfg.interactive then Console.report @@ "Auto-detected specification file " ^ json_name; Some json_name) else None) ;; let main () = let command = Sys.argv.(1) in Arg.current := 1; match command with | "main" -> let target_filename = Cmdline.parse () in print_endline (target_filename) | "includes" -> let target_filename = Cmdline.parse () in let source_files = Input.get_includes target_filename in String.concat ":" source_files |> print_endline | _ -> () ;; let _ = main ()
null
https://raw.githubusercontent.com/PrincetonUniversity/lucid/ae9fd967225486b1ac848f7318c08e7379832b61/src/bin/DockerUtils.ml
ocaml
parse command line arguments for docker. Return: spec: spec file main: main source file include: other source file include: other source file ...
open Batteries open Dpt let cfg = Cmdline.cfg let find_spec_file dpt_file = if not (String.ends_with dpt_file ".dpt") then None else ( let json_name = String.rchop ~n:4 dpt_file ^ ".json" in if Sys.file_exists json_name then ( if not cfg.interactive then Console.report @@ "Auto-detected specification file " ^ json_name; Some json_name) else None) ;; let main () = let command = Sys.argv.(1) in Arg.current := 1; match command with | "main" -> let target_filename = Cmdline.parse () in print_endline (target_filename) | "includes" -> let target_filename = Cmdline.parse () in let source_files = Input.get_includes target_filename in String.concat ":" source_files |> print_endline | _ -> () ;; let _ = main ()
bc227e716b302a03ff62ddfcf34f49cf150e6601785ab6ed6fb8b610766cd809
dedbox/racket-algebraic
macro.rkt
#lang racket/base (require algebraic/pretty algebraic/private racket/contract/base racket/pretty racket/syntax syntax/parse syntax/transformer (for-template racket/base) (for-syntax algebraic/product algebraic/private algebraic/syntax racket/base syntax/parse syntax/strip-context syntax/transformer) (for-meta 2 racket/base)) (provide μ0 mu0 μ mu macro μ* mu* macro* μ-parser mu-parser μ*-parser mu*-parser macro-parser macro*-parser var ...+ make-variable-like-transformer (contract-out [macro? predicate/c])) (struct mac (def impl) #:reflection-name 'macro #:property prop:procedure (λ (M . args) (apply (mac-impl M) args)) #:methods gen:custom-write [(define (write-proc M port mode) (case mode [(#t #f) (fprintf port "#<macro>")] [else (parameterize ([pretty-print-current-style-table algebraic-pretty-print-style-table]) (if (pretty-printing) (pretty-print (syntax->datum (mac-def M)) port 1) (print (syntax->datum (mac-def M)) port 1)))]))]) (define macro? mac?) (begin-for-syntax (define (make-μ options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) #`(syntax-parser #,@options #,((make-clause (λ (a) #`(_ #,(argument a))) quasi-singleton) clause))))) (define (make-μ-parser options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) #`(syntax-parser #,@options #,((make-clause argument singleton) clause))))) (define (make-μ* options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) (with-syntax ([clause ((make-clause formals quasi-singleton) clause)]) #`(syntax-parser #,@options clause))))) (define (make-μ*-parser options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) (with-syntax ([clause ((make-clause parser-formals singleton) clause)]) #`(syntax-parser #,@options clause))))) (define (make-macro options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) #`(syntax-parser #,@options #,@(map (make-clause (λ (a) #`(_ #,(argument a))) quasi-singleton) clauses))))) (define (make-macro-parser options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) #`(syntax-parser #,@options #,@(map (make-clause argument singleton) clauses))))) (define (make-macro* options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) (with-syntax ([(clause ...) (map (make-clause formals quasi-singleton) clauses)]) #`(syntax-parser #,@options clause ...))))) (define (make-macro*-parser options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) (with-syntax ([(clause ...) (map (make-clause parser-formals singleton) clauses)]) #`(syntax-parser #,@options clause ...))))) (define (skip-clauses options+clauses*) (let ([next (next-option options+clauses*)]) (if (not next) null (append (car next) (skip-clauses (cdr next)))))) (define (skip-options options+clauses*) (let ([next (next-option options+clauses*)]) (if next (skip-options (cdr next)) options+clauses*))) (define (next-option options+clauses*) (and (keyword-syntax? (car options+clauses*)) (case (keyword-syntax->string (car options+clauses*)) [("track-literals" "disable-colon-notation") (cons (list (car options+clauses*)) (cdr options+clauses*))] [("context" "literals" "datum-literals" "literal-sets" "conventions" "local-conventions") (cons (list (car options+clauses*) (cadr options+clauses*)) (cddr options+clauses*))] [else #f]))) (define ((make-clause patt-maker body-maker) clause) (let* ([clause* (syntax-e clause)] [tail (cdr clause*)]) (with-syntax ([patt (patt-maker (car clause*))] [(alias-patt ...) (map patt-maker (aliases tail))]) #`[(~and patt alias-patt ...) #,@(make-directives tail) #,(body-maker (body tail))]))) (define (make-directives tail) (cond [(or (null? tail) (not (keyword-syntax? (car tail)))) null] [(keyword-syntax=? (car tail) "do") (do-directive (cdr tail))] [(keyword-syntax=? (car tail) "if") (if-directive (cdr tail))] [(keyword-syntax=? (car tail) "with") (with-directive (cdr tail))] [else null])) (define (do-directive tail) (with-syntax ([block (car tail)]) (list* #'#:do #'block (make-directives (cdr tail))))) (define (if-directive tail) (with-syntax ([patt (car tail)]) (list* #'#:post #'(~fail #:unless patt (format "condition failed: ~a" 'patt)) (make-directives (cdr tail))))) (define (with-directive tail) (with-syntax ([patt (argument (car tail))] [expr (cadr tail)]) (list* #'#:with #'patt #'expr (make-directives (cddr tail))))) (define (quasi-singleton xs) (datum->syntax (car xs) (list #'quasisyntax (if (null? (cdr xs)) (car xs) (datum->syntax (car xs) (list* #'begin xs)))))) (define (singleton xs) (datum->syntax (car xs) (if (null? (cdr xs)) (car xs) (datum->syntax (car xs) (list* #'begin xs))))) (define (formals args) (syntax-case args () [id (wildcard? #'id) #'_] [id (variable? #'id) #'(_ . id)] [(_ ...) #`(_ #,@(map argument (syntax-e args)))] [(head ... . tail) (with-syntax ([(patt ...) (map argument (syntax-e #'(head ...)))] [rest-patt (argument #'tail)]) #'(_ patt ... . rest-patt))] [_ (raise-syntax-error #f "invalid formals syntax" args)])) (define (parser-formals args) (syntax-case args () [id (wildcard? #'id) #'_] [id (variable? #'id) #'(_ . id)] [(_ ...) (map argument (syntax-e args))] [(head ... . tail) (with-syntax ([(patt ...) (map argument (syntax-e #'(head ...)))] [rest-patt (argument #'tail)]) #'(patt ... . rest-patt))] [_ (raise-syntax-error #f "invalid formals syntax" args)])) (define (argument arg) (let ([arg* (syntax-e arg)]) (syntax-case arg (... ...+) [... arg] [...+ arg] [_ (syntax-case arg (quote quasiquote) [_ (literal-data? arg) arg] [(quote datum) #`(quote (~datum datum))] [(quasiquote datum) (let quasi ([stx #'datum]) (if (identifier? stx) #`(~datum #,stx) (syntax-case stx (unquote) [(unquote patt) (argument #'patt)] [(patt1 . patt2) #`(#,(quasi #'patt1) . #,(quasi #'patt2))] [_ stx])))] ;; composite data ;; ;; #(patt ...) ;; #&patt [_ (vector? arg*) (with-syntax ([(patt ...) (map argument (vector->list arg*))]) #'(~describe "vector" #(patt ...)))] [_ (box? arg*) (with-syntax ([patt (argument (unbox arg*))]) #'(~describe "box" #&patt))] ;; bindings [_ (wildcard? arg) #'_] [_ (variable? arg) arg] ;; algebraic data ;; ;; Π ;; (Π patt ...) [Π1 (product-identifier? #'Π1) #'(~and (~var Π2 id) (~fail #:unless (and (product-identifier? #'Π2) (equal? (syntax-local-value #'Π1) (syntax-local-value #'Π2))) (format "expected the product ~a" 'Π1)))] [(Π . _) (product-identifier? #'Π) (with-syntax ([patt (argument #'Π)]) #`(~describe (format "an instance of product ~a" 'Π) (patt ~! #,@(if (list? arg*) (map argument (cdr arg*)) (rest-args (cdr arg*))))))] ;; pattern aliases [(patt #:as alias) #`(~and #,(argument #'patt) #,(argument #'alias))] ;; pattern guards [(patt #:if expr) #`(~and #,(argument #'patt) (~fail #:unless expr (format "condition failed: ~a" 'expr)))] ;; Racket structs ;; ;; (struct-id [field-id patt] ...) ;; (struct-id patt ...) [(S _ ...) (struct-identifier? #'S) (with-syntax ([(patt ...) (map argument (cdr arg*))]) #'(~describe (format "an instance of struct ~a" 'S) ((~describe "struct name" (~literal S)) (~describe "struct field" patt) ...)))] ;; unquoted lists [(_ ...) #`#,(map argument arg*)] [(_ . _) #`#,(cons (argument (car arg*)) (argument #`#,(cdr arg*)))] [_ (raise-syntax-error #f "invalid pattern syntax" arg)])]))) (define (rest-args arg*) (if (pair? arg*) (cons (argument (car arg*)) (rest-args (cdr arg*))) (argument arg*)))) ;;; ---------------------------------------------------------------------------- Macro Expressions (define-syntax (μ0 stx) (syntax-case stx () [(_ expr) (syntax/loc stx (... (syntax-parser [:id #`expr] [(:id x ...) #`((#%expression expr) x ...)])))] [(_ expr exprs ...) (#%rewrite stx `(μ0 (begin . ,#'(expr exprs ...))))])) (define-syntax (mu0 stx) (syntax-case stx () [(_ expr exprs ...) (#%rewrite stx `(μ0 . ,#'(expr exprs ...)))])) ;;; ---------------------------------------------------------------------------- Uni - Clausal Macros ;;; Univariate (define-syntax (μ stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ #'options+clause))])) (define-syntax (mu stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ #'options+clause))])) (define-syntax (μ-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ-parser #'options+clause)])) (define-syntax (mu-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ-parser #'options+clause)])) ;;; Multivariate (define-syntax (μ* stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ* #'options+clause))])) (define-syntax (mu* stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ* #'options+clause))])) (define-syntax (μ*-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ*-parser #'options+clause)])) (define-syntax (mu*-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ*-parser #'options+clause)])) ;;; ---------------------------------------------------------------------------- Multi - clausal Macros ;;; Univariate (define-syntax (macro stx) (syntax-case stx () [(_ . options+clauses) #`(mac (quote-syntax #,stx #:local) #,(make-macro #'options+clauses))])) (define-syntax (macro-parser stx) (syntax-case stx () [(_ . options+clauses) #`#,(make-macro-parser #'options+clauses)])) ;;; Multivariate (define-syntax (macro* stx) (syntax-case stx () [(_ . options+clauses) #`(mac (quote-syntax #,stx #:local) #,(make-macro* #'options+clauses))])) (define-syntax (macro*-parser stx) (syntax-case stx () [(_ . options+clauses) #`#,(make-macro*-parser #'options+clauses)])) ;;; ---------------------------------------------------------------------------- ;;; Helpers (define-syntax-rule (var id) (syntax-local-eval #'id))
null
https://raw.githubusercontent.com/dedbox/racket-algebraic/706b2d01ab735a01e372c33da49995339194e024/algebraic/macro.rkt
racket
composite data #(patt ...) #&patt bindings algebraic data Π (Π patt ...) pattern aliases pattern guards Racket structs (struct-id [field-id patt] ...) (struct-id patt ...) unquoted lists ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Univariate Multivariate ---------------------------------------------------------------------------- Univariate Multivariate ---------------------------------------------------------------------------- Helpers
#lang racket/base (require algebraic/pretty algebraic/private racket/contract/base racket/pretty racket/syntax syntax/parse syntax/transformer (for-template racket/base) (for-syntax algebraic/product algebraic/private algebraic/syntax racket/base syntax/parse syntax/strip-context syntax/transformer) (for-meta 2 racket/base)) (provide μ0 mu0 μ mu macro μ* mu* macro* μ-parser mu-parser μ*-parser mu*-parser macro-parser macro*-parser var ...+ make-variable-like-transformer (contract-out [macro? predicate/c])) (struct mac (def impl) #:reflection-name 'macro #:property prop:procedure (λ (M . args) (apply (mac-impl M) args)) #:methods gen:custom-write [(define (write-proc M port mode) (case mode [(#t #f) (fprintf port "#<macro>")] [else (parameterize ([pretty-print-current-style-table algebraic-pretty-print-style-table]) (if (pretty-printing) (pretty-print (syntax->datum (mac-def M)) port 1) (print (syntax->datum (mac-def M)) port 1)))]))]) (define macro? mac?) (begin-for-syntax (define (make-μ options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) #`(syntax-parser #,@options #,((make-clause (λ (a) #`(_ #,(argument a))) quasi-singleton) clause))))) (define (make-μ-parser options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) #`(syntax-parser #,@options #,((make-clause argument singleton) clause))))) (define (make-μ* options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) (with-syntax ([clause ((make-clause formals quasi-singleton) clause)]) #`(syntax-parser #,@options clause))))) (define (make-μ*-parser options+clause) (let ([options+clause* (syntax-e options+clause)]) (let ([options (skip-clauses options+clause*)] [clause (datum->syntax options+clause (skip-options options+clause*))]) (with-syntax ([clause ((make-clause parser-formals singleton) clause)]) #`(syntax-parser #,@options clause))))) (define (make-macro options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) #`(syntax-parser #,@options #,@(map (make-clause (λ (a) #`(_ #,(argument a))) quasi-singleton) clauses))))) (define (make-macro-parser options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) #`(syntax-parser #,@options #,@(map (make-clause argument singleton) clauses))))) (define (make-macro* options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) (with-syntax ([(clause ...) (map (make-clause formals quasi-singleton) clauses)]) #`(syntax-parser #,@options clause ...))))) (define (make-macro*-parser options+clauses) (let ([options+clauses* (syntax-e options+clauses)]) (let ([options (skip-clauses options+clauses*)] [clauses (skip-options options+clauses*)]) (with-syntax ([(clause ...) (map (make-clause parser-formals singleton) clauses)]) #`(syntax-parser #,@options clause ...))))) (define (skip-clauses options+clauses*) (let ([next (next-option options+clauses*)]) (if (not next) null (append (car next) (skip-clauses (cdr next)))))) (define (skip-options options+clauses*) (let ([next (next-option options+clauses*)]) (if next (skip-options (cdr next)) options+clauses*))) (define (next-option options+clauses*) (and (keyword-syntax? (car options+clauses*)) (case (keyword-syntax->string (car options+clauses*)) [("track-literals" "disable-colon-notation") (cons (list (car options+clauses*)) (cdr options+clauses*))] [("context" "literals" "datum-literals" "literal-sets" "conventions" "local-conventions") (cons (list (car options+clauses*) (cadr options+clauses*)) (cddr options+clauses*))] [else #f]))) (define ((make-clause patt-maker body-maker) clause) (let* ([clause* (syntax-e clause)] [tail (cdr clause*)]) (with-syntax ([patt (patt-maker (car clause*))] [(alias-patt ...) (map patt-maker (aliases tail))]) #`[(~and patt alias-patt ...) #,@(make-directives tail) #,(body-maker (body tail))]))) (define (make-directives tail) (cond [(or (null? tail) (not (keyword-syntax? (car tail)))) null] [(keyword-syntax=? (car tail) "do") (do-directive (cdr tail))] [(keyword-syntax=? (car tail) "if") (if-directive (cdr tail))] [(keyword-syntax=? (car tail) "with") (with-directive (cdr tail))] [else null])) (define (do-directive tail) (with-syntax ([block (car tail)]) (list* #'#:do #'block (make-directives (cdr tail))))) (define (if-directive tail) (with-syntax ([patt (car tail)]) (list* #'#:post #'(~fail #:unless patt (format "condition failed: ~a" 'patt)) (make-directives (cdr tail))))) (define (with-directive tail) (with-syntax ([patt (argument (car tail))] [expr (cadr tail)]) (list* #'#:with #'patt #'expr (make-directives (cddr tail))))) (define (quasi-singleton xs) (datum->syntax (car xs) (list #'quasisyntax (if (null? (cdr xs)) (car xs) (datum->syntax (car xs) (list* #'begin xs)))))) (define (singleton xs) (datum->syntax (car xs) (if (null? (cdr xs)) (car xs) (datum->syntax (car xs) (list* #'begin xs))))) (define (formals args) (syntax-case args () [id (wildcard? #'id) #'_] [id (variable? #'id) #'(_ . id)] [(_ ...) #`(_ #,@(map argument (syntax-e args)))] [(head ... . tail) (with-syntax ([(patt ...) (map argument (syntax-e #'(head ...)))] [rest-patt (argument #'tail)]) #'(_ patt ... . rest-patt))] [_ (raise-syntax-error #f "invalid formals syntax" args)])) (define (parser-formals args) (syntax-case args () [id (wildcard? #'id) #'_] [id (variable? #'id) #'(_ . id)] [(_ ...) (map argument (syntax-e args))] [(head ... . tail) (with-syntax ([(patt ...) (map argument (syntax-e #'(head ...)))] [rest-patt (argument #'tail)]) #'(patt ... . rest-patt))] [_ (raise-syntax-error #f "invalid formals syntax" args)])) (define (argument arg) (let ([arg* (syntax-e arg)]) (syntax-case arg (... ...+) [... arg] [...+ arg] [_ (syntax-case arg (quote quasiquote) [_ (literal-data? arg) arg] [(quote datum) #`(quote (~datum datum))] [(quasiquote datum) (let quasi ([stx #'datum]) (if (identifier? stx) #`(~datum #,stx) (syntax-case stx (unquote) [(unquote patt) (argument #'patt)] [(patt1 . patt2) #`(#,(quasi #'patt1) . #,(quasi #'patt2))] [_ stx])))] [_ (vector? arg*) (with-syntax ([(patt ...) (map argument (vector->list arg*))]) #'(~describe "vector" #(patt ...)))] [_ (box? arg*) (with-syntax ([patt (argument (unbox arg*))]) #'(~describe "box" #&patt))] [_ (wildcard? arg) #'_] [_ (variable? arg) arg] [Π1 (product-identifier? #'Π1) #'(~and (~var Π2 id) (~fail #:unless (and (product-identifier? #'Π2) (equal? (syntax-local-value #'Π1) (syntax-local-value #'Π2))) (format "expected the product ~a" 'Π1)))] [(Π . _) (product-identifier? #'Π) (with-syntax ([patt (argument #'Π)]) #`(~describe (format "an instance of product ~a" 'Π) (patt ~! #,@(if (list? arg*) (map argument (cdr arg*)) (rest-args (cdr arg*))))))] [(patt #:as alias) #`(~and #,(argument #'patt) #,(argument #'alias))] [(patt #:if expr) #`(~and #,(argument #'patt) (~fail #:unless expr (format "condition failed: ~a" 'expr)))] [(S _ ...) (struct-identifier? #'S) (with-syntax ([(patt ...) (map argument (cdr arg*))]) #'(~describe (format "an instance of struct ~a" 'S) ((~describe "struct name" (~literal S)) (~describe "struct field" patt) ...)))] [(_ ...) #`#,(map argument arg*)] [(_ . _) #`#,(cons (argument (car arg*)) (argument #`#,(cdr arg*)))] [_ (raise-syntax-error #f "invalid pattern syntax" arg)])]))) (define (rest-args arg*) (if (pair? arg*) (cons (argument (car arg*)) (rest-args (cdr arg*))) (argument arg*)))) Macro Expressions (define-syntax (μ0 stx) (syntax-case stx () [(_ expr) (syntax/loc stx (... (syntax-parser [:id #`expr] [(:id x ...) #`((#%expression expr) x ...)])))] [(_ expr exprs ...) (#%rewrite stx `(μ0 (begin . ,#'(expr exprs ...))))])) (define-syntax (mu0 stx) (syntax-case stx () [(_ expr exprs ...) (#%rewrite stx `(μ0 . ,#'(expr exprs ...)))])) Uni - Clausal Macros (define-syntax (μ stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ #'options+clause))])) (define-syntax (mu stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ #'options+clause))])) (define-syntax (μ-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ-parser #'options+clause)])) (define-syntax (mu-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ-parser #'options+clause)])) (define-syntax (μ* stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ* #'options+clause))])) (define-syntax (mu* stx) (syntax-case stx () [(_ . options+clause) #`(mac (quote-syntax #,stx #:local) #,(make-μ* #'options+clause))])) (define-syntax (μ*-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ*-parser #'options+clause)])) (define-syntax (mu*-parser stx) (syntax-case stx () [(_ . options+clause) #`#,(make-μ*-parser #'options+clause)])) Multi - clausal Macros (define-syntax (macro stx) (syntax-case stx () [(_ . options+clauses) #`(mac (quote-syntax #,stx #:local) #,(make-macro #'options+clauses))])) (define-syntax (macro-parser stx) (syntax-case stx () [(_ . options+clauses) #`#,(make-macro-parser #'options+clauses)])) (define-syntax (macro* stx) (syntax-case stx () [(_ . options+clauses) #`(mac (quote-syntax #,stx #:local) #,(make-macro* #'options+clauses))])) (define-syntax (macro*-parser stx) (syntax-case stx () [(_ . options+clauses) #`#,(make-macro*-parser #'options+clauses)])) (define-syntax-rule (var id) (syntax-local-eval #'id))
6adc0cb1ad9f422c1e47d510ea3a99f0cbd600e367ee44512e24e392203be5c4
input-output-hk/cardano-ledger
Merkle.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE UndecidableInstances # -- | Merkle tree implementation. -- -- See <>. module Cardano.Chain.Common.Merkle ( * MerkleRoot MerkleRoot (..), -- * MerkleTree MerkleTree (..), mtRoot, mkMerkleTree, mkMerkleTreeDecoded, -- * MerkleNode MerkleNode (..), mkBranch, mkLeaf, mkLeafDecoded, ) where Cardano . Prelude has its own Rube Goldberg variant of ' Foldable ' which we do not -- want. It would be great if we could write import Cardano . Prelude hiding ( toList , foldMap ) but HLint insists that this is not OK because toList and foldMap are never -- used unqualified. The hiding in fact makes it clearer for the human reader -- what's going on. import Cardano.Crypto (Hash, hashDecoded, hashRaw, hashToBytes) import Cardano.Crypto.Raw (Raw) import Cardano.Ledger.Binary ( Annotated (..), DecCBOR (..), EncCBOR (..), FromCBOR (..), ToCBOR (..), byronProtVer, fromByronCBOR, serializeBuilder, toByronCBOR, ) import Cardano.Prelude import Data.Aeson (ToJSON) import Data.ByteString.Builder (Builder, byteString, word8) import qualified Data.ByteString.Builder.Extra as Builder import qualified Data.ByteString.Lazy as LBS import Data.Coerce (coerce) import qualified Data.Foldable as Foldable import Formatting.Buildable (Buildable (..)) import NoThunks.Class (NoThunks (..)) import qualified Prelude -------------------------------------------------------------------------------- MerkleRoot -------------------------------------------------------------------------------- | Data type for root of tree newtype MerkleRoot a = MerkleRoot { getMerkleRoot :: Hash Raw ^ returns root ' Hash ' of } deriving (Show, Eq, Ord, Generic) deriving anyclass (NFData, NoThunks) instance Buildable (MerkleRoot a) where build (MerkleRoot h) = "MerkleRoot|" <> build h -- Used for debugging purposes only instance ToJSON a => ToJSON (MerkleRoot a) instance EncCBOR a => ToCBOR (MerkleRoot a) where toCBOR = toByronCBOR instance DecCBOR a => FromCBOR (MerkleRoot a) where fromCBOR = fromByronCBOR instance EncCBOR a => EncCBOR (MerkleRoot a) where encCBOR = encCBOR . getMerkleRoot encodedSizeExpr size = encodedSizeExpr size . fmap getMerkleRoot instance DecCBOR a => DecCBOR (MerkleRoot a) where decCBOR = MerkleRoot <$> decCBOR merkleRootToBuilder :: MerkleRoot a -> Builder merkleRootToBuilder (MerkleRoot h) = byteString (hashToBytes h) mkRoot :: MerkleRoot a -> MerkleRoot a -> MerkleRoot a mkRoot a b = MerkleRoot . hashRaw . toLazyByteString $ mconcat [word8 1, merkleRootToBuilder a, merkleRootToBuilder b] emptyHash :: MerkleRoot a emptyHash = MerkleRoot (hashRaw mempty) -------------------------------------------------------------------------------- MerkleTree -------------------------------------------------------------------------------- data MerkleTree a = MerkleEmpty | MerkleTree !Word32 !(MerkleNode a) deriving (Eq, Generic) deriving anyclass (NFData) instance Foldable MerkleTree where foldMap _ MerkleEmpty = mempty foldMap f (MerkleTree _ n) = Foldable.foldMap f n null MerkleEmpty = True null _ = False length MerkleEmpty = 0 length (MerkleTree s _) = fromIntegral s instance Show a => Show (MerkleTree a) where show tree = "Merkle tree: " <> show (Foldable.toList tree) instance EncCBOR a => ToCBOR (MerkleTree a) where toCBOR = toByronCBOR instance (DecCBOR a, EncCBOR a) => FromCBOR (MerkleTree a) where fromCBOR = fromByronCBOR -- This instance is both faster and more space-efficient (as confirmed by a -- benchmark). Hashing turns out to be faster than decoding extra data. instance EncCBOR a => EncCBOR (MerkleTree a) where encCBOR = encCBOR . Foldable.toList instance (DecCBOR a, EncCBOR a) => DecCBOR (MerkleTree a) where decCBOR = mkMerkleTree <$> decCBOR | Smart constructor for ' MerkleTree ' mkMerkleTree :: EncCBOR a => [a] -> MerkleTree a mkMerkleTree = mkMerkleTree' (mkLeaf . getConst) . fmap Const | Reconstruct a ' MerkleTree ' from a decoded list of items mkMerkleTreeDecoded :: [Annotated a ByteString] -> MerkleTree a mkMerkleTreeDecoded = mkMerkleTree' mkLeafDecoded mkMerkleTree' :: forall f a b. (f a b -> MerkleNode a) -> [f a b] -> MerkleTree a mkMerkleTree' _ [] = MerkleEmpty mkMerkleTree' leafBuilder ls = MerkleTree (fromIntegral lsLen) (go lsLen ls) where lsLen = length ls go :: Int -> [f a b] -> MerkleNode a go _ [x] = leafBuilder x go len xs = mkBranch (go i l) (go (len - i) r) where i = powerOfTwo len (l, r) = splitAt i xs | Return the largest power of two such that it 's smaller than X. -- > > > powerOfTwo 64 32 > > > powerOfTwo 65 64 powerOfTwo :: forall a. (Bits a, Num a) => a -> a powerOfTwo n | n .&. (n - 1) == 0 = n `shiftR` 1 | otherwise = go n where “ x . & . ( x - 1 ) ” clears the least significant bit : ↓ 01101000 x 01100111 x - 1 -------- 01100000 x . & . ( x - 1 ) I could 've used something like “ until ( \x - > x*2 > w ) ( * 2 ) 1 ” , but bit tricks are fun . ↓ 01101000 x 01100111 x - 1 -------- 01100000 x .&. (x - 1) I could've used something like “until (\x -> x*2 > w) (*2) 1”, but bit tricks are fun. -} go :: a -> a go w = if w .&. (w - 1) == 0 then w else go (w .&. (w - 1)) | Returns root of tree mtRoot :: MerkleTree a -> MerkleRoot a mtRoot MerkleEmpty = emptyHash mtRoot (MerkleTree _ n) = nodeRoot n -------------------------------------------------------------------------------- MerkleNode -------------------------------------------------------------------------------- data MerkleNode a | MerkleBranch mRight MerkleBranch !(MerkleRoot a) !(MerkleNode a) !(MerkleNode a) | MerkleLeaf mRoot mVal MerkleLeaf !(MerkleRoot a) a deriving (Eq, Show, Generic) deriving anyclass (NFData) instance Foldable MerkleNode where foldMap f x = case x of MerkleLeaf _ mVal -> f mVal MerkleBranch _ mLeft mRight -> Foldable.foldMap f mLeft `mappend` Foldable.foldMap f mRight toLazyByteString :: Builder -> LBS.ByteString toLazyByteString = Builder.toLazyByteStringWith (Builder.safeStrategy 1024 4096) mempty nodeRoot :: MerkleNode a -> MerkleRoot a nodeRoot (MerkleLeaf root _) = root nodeRoot (MerkleBranch root _ _) = root mkLeaf :: forall a. EncCBOR a => a -> MerkleNode a mkLeaf a = MerkleLeaf mRoot a where mRoot :: MerkleRoot a mRoot = MerkleRoot $ hashRaw (toLazyByteString (word8 0 <> serializeBuilder byronProtVer a)) mkLeafDecoded :: Annotated a ByteString -> MerkleNode a mkLeafDecoded a = MerkleLeaf mRoot (unAnnotated a) where mRoot :: MerkleRoot a mRoot = MerkleRoot . coerce . hashDecoded $ prependTag <$> a prependTag = (LBS.toStrict (toLazyByteString (word8 0)) <>) mkBranch :: MerkleNode a -> MerkleNode a -> MerkleNode a mkBranch nodeA nodeB = MerkleBranch root nodeA nodeB where root = mkRoot (nodeRoot nodeA) (nodeRoot nodeB)
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/b9aa1ad1728c0ceeca62657ec94d6d099896c052/eras/byron/ledger/impl/src/Cardano/Chain/Common/Merkle.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # | Merkle tree implementation. See <>. * MerkleTree * MerkleNode want. It would be great if we could write used unqualified. The hiding in fact makes it clearer for the human reader what's going on. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Used for debugging purposes only ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ This instance is both faster and more space-efficient (as confirmed by a benchmark). Hashing turns out to be faster than decoding extra data. ------ ------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE UndecidableInstances # module Cardano.Chain.Common.Merkle ( * MerkleRoot MerkleRoot (..), MerkleTree (..), mtRoot, mkMerkleTree, mkMerkleTreeDecoded, MerkleNode (..), mkBranch, mkLeaf, mkLeafDecoded, ) where Cardano . Prelude has its own Rube Goldberg variant of ' Foldable ' which we do not import Cardano . Prelude hiding ( toList , foldMap ) but HLint insists that this is not OK because toList and foldMap are never import Cardano.Crypto (Hash, hashDecoded, hashRaw, hashToBytes) import Cardano.Crypto.Raw (Raw) import Cardano.Ledger.Binary ( Annotated (..), DecCBOR (..), EncCBOR (..), FromCBOR (..), ToCBOR (..), byronProtVer, fromByronCBOR, serializeBuilder, toByronCBOR, ) import Cardano.Prelude import Data.Aeson (ToJSON) import Data.ByteString.Builder (Builder, byteString, word8) import qualified Data.ByteString.Builder.Extra as Builder import qualified Data.ByteString.Lazy as LBS import Data.Coerce (coerce) import qualified Data.Foldable as Foldable import Formatting.Buildable (Buildable (..)) import NoThunks.Class (NoThunks (..)) import qualified Prelude MerkleRoot | Data type for root of tree newtype MerkleRoot a = MerkleRoot { getMerkleRoot :: Hash Raw ^ returns root ' Hash ' of } deriving (Show, Eq, Ord, Generic) deriving anyclass (NFData, NoThunks) instance Buildable (MerkleRoot a) where build (MerkleRoot h) = "MerkleRoot|" <> build h instance ToJSON a => ToJSON (MerkleRoot a) instance EncCBOR a => ToCBOR (MerkleRoot a) where toCBOR = toByronCBOR instance DecCBOR a => FromCBOR (MerkleRoot a) where fromCBOR = fromByronCBOR instance EncCBOR a => EncCBOR (MerkleRoot a) where encCBOR = encCBOR . getMerkleRoot encodedSizeExpr size = encodedSizeExpr size . fmap getMerkleRoot instance DecCBOR a => DecCBOR (MerkleRoot a) where decCBOR = MerkleRoot <$> decCBOR merkleRootToBuilder :: MerkleRoot a -> Builder merkleRootToBuilder (MerkleRoot h) = byteString (hashToBytes h) mkRoot :: MerkleRoot a -> MerkleRoot a -> MerkleRoot a mkRoot a b = MerkleRoot . hashRaw . toLazyByteString $ mconcat [word8 1, merkleRootToBuilder a, merkleRootToBuilder b] emptyHash :: MerkleRoot a emptyHash = MerkleRoot (hashRaw mempty) MerkleTree data MerkleTree a = MerkleEmpty | MerkleTree !Word32 !(MerkleNode a) deriving (Eq, Generic) deriving anyclass (NFData) instance Foldable MerkleTree where foldMap _ MerkleEmpty = mempty foldMap f (MerkleTree _ n) = Foldable.foldMap f n null MerkleEmpty = True null _ = False length MerkleEmpty = 0 length (MerkleTree s _) = fromIntegral s instance Show a => Show (MerkleTree a) where show tree = "Merkle tree: " <> show (Foldable.toList tree) instance EncCBOR a => ToCBOR (MerkleTree a) where toCBOR = toByronCBOR instance (DecCBOR a, EncCBOR a) => FromCBOR (MerkleTree a) where fromCBOR = fromByronCBOR instance EncCBOR a => EncCBOR (MerkleTree a) where encCBOR = encCBOR . Foldable.toList instance (DecCBOR a, EncCBOR a) => DecCBOR (MerkleTree a) where decCBOR = mkMerkleTree <$> decCBOR | Smart constructor for ' MerkleTree ' mkMerkleTree :: EncCBOR a => [a] -> MerkleTree a mkMerkleTree = mkMerkleTree' (mkLeaf . getConst) . fmap Const | Reconstruct a ' MerkleTree ' from a decoded list of items mkMerkleTreeDecoded :: [Annotated a ByteString] -> MerkleTree a mkMerkleTreeDecoded = mkMerkleTree' mkLeafDecoded mkMerkleTree' :: forall f a b. (f a b -> MerkleNode a) -> [f a b] -> MerkleTree a mkMerkleTree' _ [] = MerkleEmpty mkMerkleTree' leafBuilder ls = MerkleTree (fromIntegral lsLen) (go lsLen ls) where lsLen = length ls go :: Int -> [f a b] -> MerkleNode a go _ [x] = leafBuilder x go len xs = mkBranch (go i l) (go (len - i) r) where i = powerOfTwo len (l, r) = splitAt i xs | Return the largest power of two such that it 's smaller than X. > > > powerOfTwo 64 32 > > > powerOfTwo 65 64 powerOfTwo :: forall a. (Bits a, Num a) => a -> a powerOfTwo n | n .&. (n - 1) == 0 = n `shiftR` 1 | otherwise = go n where “ x . & . ( x - 1 ) ” clears the least significant bit : ↓ 01101000 x 01100111 x - 1 01100000 x . & . ( x - 1 ) I could 've used something like “ until ( \x - > x*2 > w ) ( * 2 ) 1 ” , but bit tricks are fun . ↓ 01101000 x 01100111 x - 1 01100000 x .&. (x - 1) I could've used something like “until (\x -> x*2 > w) (*2) 1”, but bit tricks are fun. -} go :: a -> a go w = if w .&. (w - 1) == 0 then w else go (w .&. (w - 1)) | Returns root of tree mtRoot :: MerkleTree a -> MerkleRoot a mtRoot MerkleEmpty = emptyHash mtRoot (MerkleTree _ n) = nodeRoot n MerkleNode data MerkleNode a | MerkleBranch mRight MerkleBranch !(MerkleRoot a) !(MerkleNode a) !(MerkleNode a) | MerkleLeaf mRoot mVal MerkleLeaf !(MerkleRoot a) a deriving (Eq, Show, Generic) deriving anyclass (NFData) instance Foldable MerkleNode where foldMap f x = case x of MerkleLeaf _ mVal -> f mVal MerkleBranch _ mLeft mRight -> Foldable.foldMap f mLeft `mappend` Foldable.foldMap f mRight toLazyByteString :: Builder -> LBS.ByteString toLazyByteString = Builder.toLazyByteStringWith (Builder.safeStrategy 1024 4096) mempty nodeRoot :: MerkleNode a -> MerkleRoot a nodeRoot (MerkleLeaf root _) = root nodeRoot (MerkleBranch root _ _) = root mkLeaf :: forall a. EncCBOR a => a -> MerkleNode a mkLeaf a = MerkleLeaf mRoot a where mRoot :: MerkleRoot a mRoot = MerkleRoot $ hashRaw (toLazyByteString (word8 0 <> serializeBuilder byronProtVer a)) mkLeafDecoded :: Annotated a ByteString -> MerkleNode a mkLeafDecoded a = MerkleLeaf mRoot (unAnnotated a) where mRoot :: MerkleRoot a mRoot = MerkleRoot . coerce . hashDecoded $ prependTag <$> a prependTag = (LBS.toStrict (toLazyByteString (word8 0)) <>) mkBranch :: MerkleNode a -> MerkleNode a -> MerkleNode a mkBranch nodeA nodeB = MerkleBranch root nodeA nodeB where root = mkRoot (nodeRoot nodeA) (nodeRoot nodeB)
eed673fd4087ddedd2d76891cb9c06f92e61cc053b8148992ef9873a4ee91e75
DSiSc/why3
bigInt.mli
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) * Wrapper for big nums , implemented either with 's [ Nums ] or [ ZArith ] type t val compare : t -> t -> int (** constants *) val zero : t val one : t val of_int : int -> t (** basic operations *) val succ : t -> t val pred : t -> t val add_int : int -> t -> t val mul_int : int -> t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val minus : t -> t val sign : t -> int (** comparisons *) val eq : t -> t -> bool val lt : t -> t -> bool val gt : t -> t -> bool val le : t -> t -> bool val ge : t -> t -> bool (** Division and modulo operators with the convention that modulo is always non-negative. It implies that division rounds down when divisor is positive, and rounds up when divisor is negative. *) val euclidean_div_mod : t -> t -> t * t val euclidean_div : t -> t -> t val euclidean_mod : t -> t -> t * " computer " division , i.e division rounds towards zero , and thus [ mod x y ] has the same sign as x x y] has the same sign as x *) val computer_div_mod : t -> t -> t * t val computer_div : t -> t -> t val computer_mod : t -> t -> t * min , , abs val min : t -> t -> t val max : t -> t -> t val abs : t -> t (** number of digits *) val num_digits : t -> int * power of small integers . Second arg must be non - negative val pow_int_pos : int -> int -> t val pow_int_pos_bigint : int -> t -> t (** conversions *) val of_string : string -> t val to_string : t -> string val to_int : t -> int
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/util/bigInt.mli
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** * constants * basic operations * comparisons * Division and modulo operators with the convention that modulo is always non-negative. It implies that division rounds down when divisor is positive, and rounds up when divisor is negative. * number of digits * conversions
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception * Wrapper for big nums , implemented either with 's [ Nums ] or [ ZArith ] type t val compare : t -> t -> int val zero : t val one : t val of_int : int -> t val succ : t -> t val pred : t -> t val add_int : int -> t -> t val mul_int : int -> t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val minus : t -> t val sign : t -> int val eq : t -> t -> bool val lt : t -> t -> bool val gt : t -> t -> bool val le : t -> t -> bool val ge : t -> t -> bool val euclidean_div_mod : t -> t -> t * t val euclidean_div : t -> t -> t val euclidean_mod : t -> t -> t * " computer " division , i.e division rounds towards zero , and thus [ mod x y ] has the same sign as x x y] has the same sign as x *) val computer_div_mod : t -> t -> t * t val computer_div : t -> t -> t val computer_mod : t -> t -> t * min , , abs val min : t -> t -> t val max : t -> t -> t val abs : t -> t val num_digits : t -> int * power of small integers . Second arg must be non - negative val pow_int_pos : int -> int -> t val pow_int_pos_bigint : int -> t -> t val of_string : string -> t val to_string : t -> string val to_int : t -> int
7308109604436c0fee16ef13cd0ca73d1b64be528bf61ebaba656bc86ed6ea1d
ijvcms/chuanqi_dev
robot_cross.erl
%%%------------------------------------------------------------------- @author yubing ( C ) 2016 , < COMPANY > %%% @doc %%% %%% @end Created : 30 . 五月 2016 16:57 %%%------------------------------------------------------------------- -module(robot_cross). -include("gameconfig_config.hrl"). -include("record.hrl"). -include("cache.hrl"). -include("common.hrl"). -include("proto.hrl"). -include("config.hrl"). %% API -export([ init/0, check_robot/1, login_out/1, check_robot/3, change_sence/1, exe_robot/2, is_robot/1, is_robot_open_id/2 ]). -export([ login/1, do_login/5, do_login_out/2, do_change_sence/4, do_is_robot/2 ]). -define(SCENEID_NEW, 20101). %% 初始化机器人账号信息 init() -> [put(X, null) || X <- robot_account_config:get_list()]. %% 执行事件 exe_robot(F, C) -> case config:get_is_robot() of true -> ?MODULE:F(C); _ -> skip end. %% 登陆记录 login([OpendId, PlayerId, ScendId, IsRobot]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_login, [OpendId, PlayerId, ScendId, IsRobot]}). do_login(_State, OpendId, PlayerId, SceneId, IsRobot) -> case IsRobot of 1 -> put(OpendId, {PlayerId, SceneId}); _Value -> skip end, check_robot(_State, SceneId, IsRobot). %% 登出记录 login_out([OpendId]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_login_out, [OpendId]}). do_login_out(_, OpendId) -> erlang:put(OpendId, null). 切换场景记录 change_sence([PlayerState]) -> case PlayerState#player_state.is_robot of 1 -> #player_state{open_id = OpenId, player_id = PlayerId, scene_id = SceneId} = PlayerState, gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_change_sence, [OpenId, PlayerId, SceneId]}); _ -> skip end. 修改 场景信息 do_change_sence(_, OpendId, PlayerId, SceneId) -> put(OpendId, {PlayerId, SceneId}). %% 添加机器人 check_robot([ScendId]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, check_robot, [ScendId, 0]}). %% 检测是否可以生成机器人 check_robot(_, SceneId, IsRobot) -> PlayerNum = scene_mgr_lib:get_scene_player_num(?SCENEID_NEW, 1), case IsRobot =:= 1 orelse SceneId /= ?SCENEID_NEW orelse PlayerNum > 15 of true -> case PlayerNum > 15 of true -> check_robot_logout(SceneId); _ -> skip end; _ -> add_robot(get()) end. 检测机器人离去 check_robot_logout(ScendId) -> logout_robot(get(), ScendId). %% 添加机器人 add_robot([]) -> skip; add_robot([{Key, _} | H]) -> case get(Key) of null -> put(Key, 0), Ip = config:get_socket_ip(), Port = config:get_socket_port(), ?ERR("~p ", [config:get_robot_path()]), rpc:call(config:get_robot_path(), client, start, [Key, Ip, Port, 10]); _ -> add_robot(H) end. %% 删除机器人 logout_robot([], _SceneId) -> skip; logout_robot([{Key, _} | H], SceneId) -> case get(Key) of {PlayerId, SceneId1} when SceneId1 =:= SceneId -> ?ERR("11112 ~p", [SceneId]), player_lib:logout(PlayerId); _ -> logout_robot(H, SceneId) end. %% 检测玩家是否机器人 is_robot(PlayerId) -> case gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_check_robot, [PlayerId]}) of {ok, 1} -> true; _ -> false end. do_is_robot(_, PlayerId) -> IsCheckRobot = lists:keymember(PlayerId, 2, get()), {ok, IsCheckRobot}. %% 检测玩家是否机器人 is_robot_open_id(OpenId, _Platform) -> util_erl:get_if(lists:member(OpenId, robot_account_config:get_list()), 1, 0).
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/cross/robot_cross.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API 初始化机器人账号信息 执行事件 登陆记录 登出记录 添加机器人 检测是否可以生成机器人 添加机器人 删除机器人 检测玩家是否机器人 检测玩家是否机器人
@author yubing ( C ) 2016 , < COMPANY > Created : 30 . 五月 2016 16:57 -module(robot_cross). -include("gameconfig_config.hrl"). -include("record.hrl"). -include("cache.hrl"). -include("common.hrl"). -include("proto.hrl"). -include("config.hrl"). -export([ init/0, check_robot/1, login_out/1, check_robot/3, change_sence/1, exe_robot/2, is_robot/1, is_robot_open_id/2 ]). -export([ login/1, do_login/5, do_login_out/2, do_change_sence/4, do_is_robot/2 ]). -define(SCENEID_NEW, 20101). init() -> [put(X, null) || X <- robot_account_config:get_list()]. exe_robot(F, C) -> case config:get_is_robot() of true -> ?MODULE:F(C); _ -> skip end. login([OpendId, PlayerId, ScendId, IsRobot]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_login, [OpendId, PlayerId, ScendId, IsRobot]}). do_login(_State, OpendId, PlayerId, SceneId, IsRobot) -> case IsRobot of 1 -> put(OpendId, {PlayerId, SceneId}); _Value -> skip end, check_robot(_State, SceneId, IsRobot). login_out([OpendId]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_login_out, [OpendId]}). do_login_out(_, OpendId) -> erlang:put(OpendId, null). 切换场景记录 change_sence([PlayerState]) -> case PlayerState#player_state.is_robot of 1 -> #player_state{open_id = OpenId, player_id = PlayerId, scene_id = SceneId} = PlayerState, gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_change_sence, [OpenId, PlayerId, SceneId]}); _ -> skip end. 修改 场景信息 do_change_sence(_, OpendId, PlayerId, SceneId) -> put(OpendId, {PlayerId, SceneId}). check_robot([ScendId]) -> gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, check_robot, [ScendId, 0]}). check_robot(_, SceneId, IsRobot) -> PlayerNum = scene_mgr_lib:get_scene_player_num(?SCENEID_NEW, 1), case IsRobot =:= 1 orelse SceneId /= ?SCENEID_NEW orelse PlayerNum > 15 of true -> case PlayerNum > 15 of true -> check_robot_logout(SceneId); _ -> skip end; _ -> add_robot(get()) end. 检测机器人离去 check_robot_logout(ScendId) -> logout_robot(get(), ScendId). add_robot([]) -> skip; add_robot([{Key, _} | H]) -> case get(Key) of null -> put(Key, 0), Ip = config:get_socket_ip(), Port = config:get_socket_port(), ?ERR("~p ", [config:get_robot_path()]), rpc:call(config:get_robot_path(), client, start, [Key, Ip, Port, 10]); _ -> add_robot(H) end. logout_robot([], _SceneId) -> skip; logout_robot([{Key, _} | H], SceneId) -> case get(Key) of {PlayerId, SceneId1} when SceneId1 =:= SceneId -> ?ERR("11112 ~p", [SceneId]), player_lib:logout(PlayerId); _ -> logout_robot(H, SceneId) end. is_robot(PlayerId) -> case gen_server2:apply_async(misc:whereis_name({local, robot_mod}), {?MODULE, do_check_robot, [PlayerId]}) of {ok, 1} -> true; _ -> false end. do_is_robot(_, PlayerId) -> IsCheckRobot = lists:keymember(PlayerId, 2, get()), {ok, IsCheckRobot}. is_robot_open_id(OpenId, _Platform) -> util_erl:get_if(lists:member(OpenId, robot_account_config:get_list()), 1, 0).
59191dbe7888968d301d17c1ba6d8ed7b915fa2edbaceb00ba7f3f0ff035a9f9
plasma-umass/compsci631
Compiler_util.mli
(** Support code for writing a simple compiler. *) type id = string [@@deriving show] type op2 = | LT | GT | Eq | Add | Sub | Mul | Div | Mod [@@deriving show] type const = | Int of int | Bool of bool [@@deriving show] type exp = | Id of id | Const of const | Op2 of op2 * exp * exp | If of exp * exp * exp | Let of id * exp * exp | Fun of id * id list * exp | App of exp * exp list | MkArray of exp * exp | GetArray of exp * exp | SetArray of exp * exp * exp | Seq of exp * exp | Abort [@@deriving show] val from_string : string -> exp val from_file : string -> exp (** Atomic expressions. *) type aexp = | AId of id | AConst of const [@@deriving show] (** Binding forms. *) and bexp = | BFun of id * id list * anfexp | BAtom of aexp | BOp2 of op2 * aexp * aexp | BMkArray of aexp * aexp | BGetArray of aexp * aexp | BSetArray of aexp * aexp * aexp | BApp of aexp * aexp list [@@deriving show] (** Expressions in A-normal form. *) and anfexp = | ELet of id * bexp * anfexp | EIf of aexp * anfexp * anfexp | EApp of aexp * aexp list | ERet of aexp | EAbort [@@deriving show] module IdSet : Set.S with type elt = id val free_vars : anfexp -> IdSet.t val rename : id -> id -> anfexp -> anfexp
null
https://raw.githubusercontent.com/plasma-umass/compsci631/d71d866460cac0659f31276cfb79afedc211481a/lib/Compiler_util.mli
ocaml
* Support code for writing a simple compiler. * Atomic expressions. * Binding forms. * Expressions in A-normal form.
type id = string [@@deriving show] type op2 = | LT | GT | Eq | Add | Sub | Mul | Div | Mod [@@deriving show] type const = | Int of int | Bool of bool [@@deriving show] type exp = | Id of id | Const of const | Op2 of op2 * exp * exp | If of exp * exp * exp | Let of id * exp * exp | Fun of id * id list * exp | App of exp * exp list | MkArray of exp * exp | GetArray of exp * exp | SetArray of exp * exp * exp | Seq of exp * exp | Abort [@@deriving show] val from_string : string -> exp val from_file : string -> exp type aexp = | AId of id | AConst of const [@@deriving show] and bexp = | BFun of id * id list * anfexp | BAtom of aexp | BOp2 of op2 * aexp * aexp | BMkArray of aexp * aexp | BGetArray of aexp * aexp | BSetArray of aexp * aexp * aexp | BApp of aexp * aexp list [@@deriving show] and anfexp = | ELet of id * bexp * anfexp | EIf of aexp * anfexp * anfexp | EApp of aexp * aexp list | ERet of aexp | EAbort [@@deriving show] module IdSet : Set.S with type elt = id val free_vars : anfexp -> IdSet.t val rename : id -> id -> anfexp -> anfexp
96735a3b9dcab4e0d81da247a041f38e01e5b22bfeebfe16039a46ca49749427
gfngfn/otfed
decodeTtf.ml
open Basic open Value open DecodeBasic open DecodeOperation.Open module Maxp = DecodeTtfMaxp let d_loca_short (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in (* The position is set to the beginning of a `loca` table. *) d_skip (gid * 2) >>= fun () -> d_uint16 >>= fun half1 -> d_uint16 >>= fun half2 -> if half1 = half2 then return None else let glyf_offset1 = half1 * 2 in let glyf_offset2 = half2 * 2 in return @@ Some(glyf_offset1, glyf_offset2 - glyf_offset1) let d_loca_long (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in (* The position is set to the beginning of a `loca` table. *) d_skip (gid * 4) >>= fun () -> d_uint32_int >>= fun glyf_offset1 -> d_uint32_int >>= fun glyf_offset2 -> if glyf_offset1 = glyf_offset2 then return None else return @@ Some(glyf_offset1, glyf_offset2 - glyf_offset1) let d_loca ~(num_glyphs : int) (loc_format : Intermediate.loc_format) (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in (* The position is set to the beginning of a `loca` table. *) if gid < 0 || num_glyphs <= gid then return None else match loc_format with | ShortLocFormat -> d_loca_short gid | LongLocFormat -> d_loca_long gid let loca (ttf : ttf_source) (gid : glyph_id) : (Intermediate.Ttf.glyph_location option) ok = let open ResultMonad in let common = ttf.ttf_common in DecodeOperation.seek_required_table common.table_directory Value.Tag.table_loca >>= fun (offset, _length) -> let num_glyphs = common.num_glyphs in d_loca ~num_glyphs common.loc_format gid |> DecodeOperation.run common.core offset >>= function | None -> return None | Some((reloffset, length)) -> return @@ Some(Intermediate.Ttf.GlyphLocation{ reloffset; length }) let d_end_points (numberOfContours : int) : (int Alist.t) decoder = let open DecodeOperation in let rec loop i acc = if i <= 0 then return acc else d_uint16 >>= fun e -> loop (i - 1) (Alist.extend acc e) in loop numberOfContours Alist.empty type flag = Intermediate.Ttf.flag let d_flags (num_points : int) : (flag Alist.t) decoder = let rec extend_repeatedly acc n x = if n <= 0 then acc else extend_repeatedly (Alist.extend acc x) (n - 1) x in let rec aux i acc = let open DecodeOperation in if i <= 0 then return acc else d_uint8 >>= fun byte -> let flag = Intermediate.Ttf.{ on_curve = (byte land 1 > 0); x_short_vector = (byte land 2 > 0); y_short_vector = (byte land 4 > 0); this_x_is_same = (byte land 16 > 0); this_y_is_same = (byte land 32 > 0); } in let does_repeat = (byte land 8 > 0) in if does_repeat then d_uint8 >>= fun n -> aux (i - 1 - n) (extend_repeatedly acc (n + 1) flag) else aux (i - 1) (Alist.extend acc flag) in aux num_points Alist.empty let d_coordinates is_short is_same (flags : flag list) : (int list) decoder = let open DecodeOperation in let rec aux x acc = function | [] -> return @@ Alist.to_list acc | flag :: flags -> begin if is_short flag then d_uint8 >>= fun dx -> return @@ x + (if is_same flag then dx else - dx) else if is_same flag then return x else d_int16 >>= fun dx -> return @@ x + dx end >>= fun x -> aux x (Alist.extend acc x) flags in aux 0 Alist.empty flags let d_x_coordinates flags = d_coordinates (fun flag -> flag.x_short_vector) (fun flag -> flag.this_x_is_same) flags let d_y_coordinates flags = d_coordinates (fun flag -> flag.y_short_vector) (fun flag -> flag.this_y_is_same) flags let combine (endPtsOfContours : int list) (num_points : int) (flags : flag list) (xCoordinates : int list) (yCoordinates : int list) : (Ttf.contour list) decoder = let open DecodeOperation in let rec aux pointacc contouracc endPtsOfContours = function | (i, [], [], []) -> if i = num_points && Alist.is_empty pointacc then return @@ Alist.to_list contouracc else err @@ Error.InconsistentNumberOfPoints{ num_points = num_points; num_flags = List.length flags; num_xs = List.length xCoordinates; num_ys = List.length yCoordinates; } | ( i, flag :: flags, xCoordinate :: xCoordinates, yCoordinate :: yCoordinates ) -> let point = Ttf.{ on_curve = flag.Intermediate.Ttf.on_curve; point = (xCoordinate, yCoordinate); } in let (is_final, endPtsOfContours) = match endPtsOfContours with | [] -> (false, []) | e :: es -> if e = i then (true, es) else (false, endPtsOfContours) in let tuple = (i + 1, flags, xCoordinates, yCoordinates) in if is_final then let contour = Alist.to_list (Alist.extend pointacc point) in aux Alist.empty (Alist.extend contouracc contour) endPtsOfContours tuple else aux (Alist.extend pointacc point) contouracc endPtsOfContours tuple | _ -> err @@ Error.InconsistentNumberOfPoints{ num_points = num_points; num_flags = List.length flags; num_xs = List.length xCoordinates; num_ys = List.length yCoordinates; } in aux Alist.empty Alist.empty endPtsOfContours (0, flags, xCoordinates, yCoordinates) let d_simple_glyph (numberOfContours : int) : Ttf.simple_glyph_description decoder = let open DecodeOperation in if numberOfContours = 0 then d_uint16 >>= fun instructionLength -> d_bytes instructionLength >>= fun instructions -> return ([], instructions) else d_end_points numberOfContours >>= fun endPtsOfContours -> (* `num_points`: the total number of points. *) let num_points = match Alist.chop_last endPtsOfContours with | None -> assert false | Some((_, e)) -> e + 1 in let endPtsOfContours = Alist.to_list endPtsOfContours in d_uint16 >>= fun instructionLength -> d_bytes instructionLength >>= fun instructions -> d_flags num_points >>= fun flagacc -> let flags = Alist.to_list flagacc in d_x_coordinates flags >>= fun xCoordinates -> d_y_coordinates flags >>= fun yCoordinates -> combine endPtsOfContours num_points flags xCoordinates yCoordinates >>= fun contours -> return (contours, instructions) type component_flag = Intermediate.Ttf.component_flag let d_component_flag : (bool * component_flag) decoder = let open DecodeOperation in d_uint16 >>= fun twobytes -> let more_components = (twobytes land 32 > 0) in let cflag = Intermediate.Ttf.{ arg_1_and_2_are_words = (twobytes land 1 > 0); args_are_xy_values = (twobytes land 2 > 0); round_xy_to_grid = (twobytes land 4 > 0); we_have_a_scale = (twobytes land 8 > 0); we_have_an_x_and_y_scale = (twobytes land 64 > 0); we_have_a_two_by_two = (twobytes land 128 > 0); we_have_instructions = (twobytes land 256 > 0); use_my_metrics = (twobytes land 512 > 0); unscaled_component_offset = (twobytes land 4096 > 0); } in return (more_components, cflag) let d_composite_glyph ~(start_offset : int) ~(length : int) : Ttf.composite_glyph_description decoder = let open DecodeOperation in let rec aux ~(start_offset : int) acc = d_component_flag >>= fun (more_components, cflags) -> d_uint16 >>= fun glyphIndex -> let dec = if cflags.arg_1_and_2_are_words then d_int16 else d_int8 in dec >>= fun argument1 -> dec >>= fun argument2 -> begin if cflags.we_have_a_scale then d_f2dot14 >>= fun scale -> return @@ Some({a = scale; b = 0.; c = 0.; d = scale}) else if cflags.we_have_an_x_and_y_scale then d_f2dot14 >>= fun xscale -> d_f2dot14 >>= fun yscale -> return @@ Some({a = xscale; b = 0.; c = 0.; d = yscale}) else if cflags.we_have_a_two_by_two then d_f2dot14 >>= fun a -> d_f2dot14 >>= fun b -> d_f2dot14 >>= fun c -> d_f2dot14 >>= fun d -> return @@ Some({a = a; b = b; c = c; d = d}) else return None end >>= fun linear_transform -> let v = if cflags.args_are_xy_values then Ttf.Vector(argument1, argument2) else Ttf.Matching(argument1, argument2) in let component = Value.Ttf.{ component_glyph_id = glyphIndex; composition = v; component_scale = linear_transform; round_xy_to_grid = cflags.round_xy_to_grid; use_my_metrics = cflags.use_my_metrics; unscaled_component_offset = cflags.unscaled_component_offset; } in let acc = Alist.extend acc component in if more_components then aux ~start_offset acc else if cflags.we_have_instructions then current >>= fun end_offset -> d_bytes (length - (end_offset - start_offset)) >>= fun instructions -> return @@ Value.Ttf.{ composite_components = Alist.to_list acc; composite_instruction = Some(instructions); } else return @@ Value.Ttf.{ composite_components = Alist.to_list acc; composite_instruction = None; } in aux ~start_offset Alist.empty let d_glyph ~(length : int) = let open DecodeOperation in The position is set to the beginning of a glyph . See 5.3.3.1 current >>= fun start_offset -> d_int16 >>= fun numberOfContours -> d_int16 >>= fun xMin -> d_int16 >>= fun yMin -> d_int16 >>= fun xMax -> d_int16 >>= fun yMax -> let bounding_box = { x_min = xMin; y_min = yMin; x_max = xMax; y_max = yMax } in if numberOfContours < -1 then err @@ Error.InvalidCompositeFormat(numberOfContours) else if numberOfContours = -1 then d_composite_glyph ~start_offset ~length >>= fun components -> return Ttf.{ description = CompositeGlyph(components); bounding_box; } else d_simple_glyph numberOfContours >>= fun contours -> return Ttf.{ description = SimpleGlyph(contours); bounding_box; } let glyf (ttf : ttf_source) (gloc : Intermediate.Ttf.glyph_location) : Ttf.glyph_info ok = let open ResultMonad in let common = ttf.ttf_common in DecodeOperation.seek_required_table common.table_directory Value.Tag.table_glyf >>= fun (offset, _length) -> let (Intermediate.Ttf.GlyphLocation{ reloffset; length }) = gloc in d_glyph ~length |> DecodeOperation.run common.core (offset + reloffset) let path_of_contour (contour : Ttf.contour) : quadratic_path ok = let open ResultMonad in begin match contour with | [] -> err Error.InvalidTtfContour | elem :: tail -> return (elem.Ttf.point, tail) end >>= fun (pt0, tail) -> let rec aux acc = function | [] -> Alist.to_list acc | Ttf.{ on_curve = true; point = (x, y) } :: tail -> aux (Alist.extend acc @@ QuadraticLineTo(x, y)) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: Ttf.{ on_curve = true; point = (x, y) } :: tail -> aux (Alist.extend acc @@ QuadraticCurveTo((x1, y1), (x, y))) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: ((Ttf.{ on_curve = false; point = (x2, y2) } :: _) as tail) -> aux (Alist.extend acc @@ QuadraticCurveTo((x1, y1), ((x1 + x2) / 2, (y1 + y2) / 2))) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: [] -> Alist.to_list (Alist.extend acc @@ QuadraticCurveTo((x1, y1), pt0)) in let elems = aux Alist.empty tail in return @@ (pt0, elems)
null
https://raw.githubusercontent.com/gfngfn/otfed/3c6d8ea0b05fc18a48cb423451da7858bf73d1d0/src/decodeTtf.ml
ocaml
The position is set to the beginning of a `loca` table. The position is set to the beginning of a `loca` table. The position is set to the beginning of a `loca` table. `num_points`: the total number of points.
open Basic open Value open DecodeBasic open DecodeOperation.Open module Maxp = DecodeTtfMaxp let d_loca_short (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in d_skip (gid * 2) >>= fun () -> d_uint16 >>= fun half1 -> d_uint16 >>= fun half2 -> if half1 = half2 then return None else let glyf_offset1 = half1 * 2 in let glyf_offset2 = half2 * 2 in return @@ Some(glyf_offset1, glyf_offset2 - glyf_offset1) let d_loca_long (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in d_skip (gid * 4) >>= fun () -> d_uint32_int >>= fun glyf_offset1 -> d_uint32_int >>= fun glyf_offset2 -> if glyf_offset1 = glyf_offset2 then return None else return @@ Some(glyf_offset1, glyf_offset2 - glyf_offset1) let d_loca ~(num_glyphs : int) (loc_format : Intermediate.loc_format) (gid : glyph_id) : ((int * int) option) decoder = let open DecodeOperation in if gid < 0 || num_glyphs <= gid then return None else match loc_format with | ShortLocFormat -> d_loca_short gid | LongLocFormat -> d_loca_long gid let loca (ttf : ttf_source) (gid : glyph_id) : (Intermediate.Ttf.glyph_location option) ok = let open ResultMonad in let common = ttf.ttf_common in DecodeOperation.seek_required_table common.table_directory Value.Tag.table_loca >>= fun (offset, _length) -> let num_glyphs = common.num_glyphs in d_loca ~num_glyphs common.loc_format gid |> DecodeOperation.run common.core offset >>= function | None -> return None | Some((reloffset, length)) -> return @@ Some(Intermediate.Ttf.GlyphLocation{ reloffset; length }) let d_end_points (numberOfContours : int) : (int Alist.t) decoder = let open DecodeOperation in let rec loop i acc = if i <= 0 then return acc else d_uint16 >>= fun e -> loop (i - 1) (Alist.extend acc e) in loop numberOfContours Alist.empty type flag = Intermediate.Ttf.flag let d_flags (num_points : int) : (flag Alist.t) decoder = let rec extend_repeatedly acc n x = if n <= 0 then acc else extend_repeatedly (Alist.extend acc x) (n - 1) x in let rec aux i acc = let open DecodeOperation in if i <= 0 then return acc else d_uint8 >>= fun byte -> let flag = Intermediate.Ttf.{ on_curve = (byte land 1 > 0); x_short_vector = (byte land 2 > 0); y_short_vector = (byte land 4 > 0); this_x_is_same = (byte land 16 > 0); this_y_is_same = (byte land 32 > 0); } in let does_repeat = (byte land 8 > 0) in if does_repeat then d_uint8 >>= fun n -> aux (i - 1 - n) (extend_repeatedly acc (n + 1) flag) else aux (i - 1) (Alist.extend acc flag) in aux num_points Alist.empty let d_coordinates is_short is_same (flags : flag list) : (int list) decoder = let open DecodeOperation in let rec aux x acc = function | [] -> return @@ Alist.to_list acc | flag :: flags -> begin if is_short flag then d_uint8 >>= fun dx -> return @@ x + (if is_same flag then dx else - dx) else if is_same flag then return x else d_int16 >>= fun dx -> return @@ x + dx end >>= fun x -> aux x (Alist.extend acc x) flags in aux 0 Alist.empty flags let d_x_coordinates flags = d_coordinates (fun flag -> flag.x_short_vector) (fun flag -> flag.this_x_is_same) flags let d_y_coordinates flags = d_coordinates (fun flag -> flag.y_short_vector) (fun flag -> flag.this_y_is_same) flags let combine (endPtsOfContours : int list) (num_points : int) (flags : flag list) (xCoordinates : int list) (yCoordinates : int list) : (Ttf.contour list) decoder = let open DecodeOperation in let rec aux pointacc contouracc endPtsOfContours = function | (i, [], [], []) -> if i = num_points && Alist.is_empty pointacc then return @@ Alist.to_list contouracc else err @@ Error.InconsistentNumberOfPoints{ num_points = num_points; num_flags = List.length flags; num_xs = List.length xCoordinates; num_ys = List.length yCoordinates; } | ( i, flag :: flags, xCoordinate :: xCoordinates, yCoordinate :: yCoordinates ) -> let point = Ttf.{ on_curve = flag.Intermediate.Ttf.on_curve; point = (xCoordinate, yCoordinate); } in let (is_final, endPtsOfContours) = match endPtsOfContours with | [] -> (false, []) | e :: es -> if e = i then (true, es) else (false, endPtsOfContours) in let tuple = (i + 1, flags, xCoordinates, yCoordinates) in if is_final then let contour = Alist.to_list (Alist.extend pointacc point) in aux Alist.empty (Alist.extend contouracc contour) endPtsOfContours tuple else aux (Alist.extend pointacc point) contouracc endPtsOfContours tuple | _ -> err @@ Error.InconsistentNumberOfPoints{ num_points = num_points; num_flags = List.length flags; num_xs = List.length xCoordinates; num_ys = List.length yCoordinates; } in aux Alist.empty Alist.empty endPtsOfContours (0, flags, xCoordinates, yCoordinates) let d_simple_glyph (numberOfContours : int) : Ttf.simple_glyph_description decoder = let open DecodeOperation in if numberOfContours = 0 then d_uint16 >>= fun instructionLength -> d_bytes instructionLength >>= fun instructions -> return ([], instructions) else d_end_points numberOfContours >>= fun endPtsOfContours -> let num_points = match Alist.chop_last endPtsOfContours with | None -> assert false | Some((_, e)) -> e + 1 in let endPtsOfContours = Alist.to_list endPtsOfContours in d_uint16 >>= fun instructionLength -> d_bytes instructionLength >>= fun instructions -> d_flags num_points >>= fun flagacc -> let flags = Alist.to_list flagacc in d_x_coordinates flags >>= fun xCoordinates -> d_y_coordinates flags >>= fun yCoordinates -> combine endPtsOfContours num_points flags xCoordinates yCoordinates >>= fun contours -> return (contours, instructions) type component_flag = Intermediate.Ttf.component_flag let d_component_flag : (bool * component_flag) decoder = let open DecodeOperation in d_uint16 >>= fun twobytes -> let more_components = (twobytes land 32 > 0) in let cflag = Intermediate.Ttf.{ arg_1_and_2_are_words = (twobytes land 1 > 0); args_are_xy_values = (twobytes land 2 > 0); round_xy_to_grid = (twobytes land 4 > 0); we_have_a_scale = (twobytes land 8 > 0); we_have_an_x_and_y_scale = (twobytes land 64 > 0); we_have_a_two_by_two = (twobytes land 128 > 0); we_have_instructions = (twobytes land 256 > 0); use_my_metrics = (twobytes land 512 > 0); unscaled_component_offset = (twobytes land 4096 > 0); } in return (more_components, cflag) let d_composite_glyph ~(start_offset : int) ~(length : int) : Ttf.composite_glyph_description decoder = let open DecodeOperation in let rec aux ~(start_offset : int) acc = d_component_flag >>= fun (more_components, cflags) -> d_uint16 >>= fun glyphIndex -> let dec = if cflags.arg_1_and_2_are_words then d_int16 else d_int8 in dec >>= fun argument1 -> dec >>= fun argument2 -> begin if cflags.we_have_a_scale then d_f2dot14 >>= fun scale -> return @@ Some({a = scale; b = 0.; c = 0.; d = scale}) else if cflags.we_have_an_x_and_y_scale then d_f2dot14 >>= fun xscale -> d_f2dot14 >>= fun yscale -> return @@ Some({a = xscale; b = 0.; c = 0.; d = yscale}) else if cflags.we_have_a_two_by_two then d_f2dot14 >>= fun a -> d_f2dot14 >>= fun b -> d_f2dot14 >>= fun c -> d_f2dot14 >>= fun d -> return @@ Some({a = a; b = b; c = c; d = d}) else return None end >>= fun linear_transform -> let v = if cflags.args_are_xy_values then Ttf.Vector(argument1, argument2) else Ttf.Matching(argument1, argument2) in let component = Value.Ttf.{ component_glyph_id = glyphIndex; composition = v; component_scale = linear_transform; round_xy_to_grid = cflags.round_xy_to_grid; use_my_metrics = cflags.use_my_metrics; unscaled_component_offset = cflags.unscaled_component_offset; } in let acc = Alist.extend acc component in if more_components then aux ~start_offset acc else if cflags.we_have_instructions then current >>= fun end_offset -> d_bytes (length - (end_offset - start_offset)) >>= fun instructions -> return @@ Value.Ttf.{ composite_components = Alist.to_list acc; composite_instruction = Some(instructions); } else return @@ Value.Ttf.{ composite_components = Alist.to_list acc; composite_instruction = None; } in aux ~start_offset Alist.empty let d_glyph ~(length : int) = let open DecodeOperation in The position is set to the beginning of a glyph . See 5.3.3.1 current >>= fun start_offset -> d_int16 >>= fun numberOfContours -> d_int16 >>= fun xMin -> d_int16 >>= fun yMin -> d_int16 >>= fun xMax -> d_int16 >>= fun yMax -> let bounding_box = { x_min = xMin; y_min = yMin; x_max = xMax; y_max = yMax } in if numberOfContours < -1 then err @@ Error.InvalidCompositeFormat(numberOfContours) else if numberOfContours = -1 then d_composite_glyph ~start_offset ~length >>= fun components -> return Ttf.{ description = CompositeGlyph(components); bounding_box; } else d_simple_glyph numberOfContours >>= fun contours -> return Ttf.{ description = SimpleGlyph(contours); bounding_box; } let glyf (ttf : ttf_source) (gloc : Intermediate.Ttf.glyph_location) : Ttf.glyph_info ok = let open ResultMonad in let common = ttf.ttf_common in DecodeOperation.seek_required_table common.table_directory Value.Tag.table_glyf >>= fun (offset, _length) -> let (Intermediate.Ttf.GlyphLocation{ reloffset; length }) = gloc in d_glyph ~length |> DecodeOperation.run common.core (offset + reloffset) let path_of_contour (contour : Ttf.contour) : quadratic_path ok = let open ResultMonad in begin match contour with | [] -> err Error.InvalidTtfContour | elem :: tail -> return (elem.Ttf.point, tail) end >>= fun (pt0, tail) -> let rec aux acc = function | [] -> Alist.to_list acc | Ttf.{ on_curve = true; point = (x, y) } :: tail -> aux (Alist.extend acc @@ QuadraticLineTo(x, y)) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: Ttf.{ on_curve = true; point = (x, y) } :: tail -> aux (Alist.extend acc @@ QuadraticCurveTo((x1, y1), (x, y))) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: ((Ttf.{ on_curve = false; point = (x2, y2) } :: _) as tail) -> aux (Alist.extend acc @@ QuadraticCurveTo((x1, y1), ((x1 + x2) / 2, (y1 + y2) / 2))) tail | Ttf.{ on_curve = false; point = (x1, y1) } :: [] -> Alist.to_list (Alist.extend acc @@ QuadraticCurveTo((x1, y1), pt0)) in let elems = aux Alist.empty tail in return @@ (pt0, elems)
5ef629980be46118425b3fede1a6392c98ce5eb245bd0fa22e2a66040cb5bade
monadbobo/ocaml-core
wait_test.ml
open Core.Std open Async.Std open Qtest_lib.Std let fast_child () = Unix.fork_exec ~prog:"/bin/true" ~args:[] () let slow_child () = let prog = "/bin/sleep" in Unix.fork_exec ~prog ~args:[ prog; "1" ] () ;; let raises_echild f = try ignore (f ()); false with | Unix.Unix_error (Unix.ECHILD, _, _) -> true ;; let test_raises_echild () = assert (raises_echild (fun () -> Unix.wait_nohang `Any )); assert (raises_echild (fun () -> Unix.wait_nohang `My_group)); assert (raises_echild (fun () -> Unix.wait_nohang_untraced `Any )); assert (raises_echild (fun () -> Unix.wait_nohang_untraced `My_group)); Deferred.unit let wait_on_fast_child wait_on = fast_child () >>= fun pid -> Unix.wait (wait_on pid) >>| fun (pid', exit_or_signal) -> assert (Result.is_ok exit_or_signal); assert (pid = pid') let wait_on_slow_child wait_on = Deferred.List.map (List.init 10 ~f:(fun _i -> slow_child ())) ~f:Fn.id >>= fun pids -> Deferred.List.iter ~how:`Parallel pids ~f:(fun pid -> let wait_on = wait_on pid in Monitor.try_with (fun () -> Unix.wait wait_on >>| fun (_, exit_or_signal) -> if not (Result.is_ok exit_or_signal) then failwith (Unix.Exit_or_signal.to_string_hum exit_or_signal)) >>| function | Ok () -> () | Error exn -> failwiths "wait for slow child" (wait_on, exn) (<:sexp_of< Unix.wait_on * exn >>)) let unsafe_tests = ("Wait_test.raises_echild", test_raises_echild) :: (List.concat_map [ ("any", (fun _ -> `Any)); ("my_group", (fun _ -> `My_group)); ("pid", (fun pid -> `Pid pid)); ] ~f:(fun (name, wait_on) -> [ "Wait_test.fast_child_" ^ name, (fun () -> wait_on_fast_child wait_on); "Wait_test.slow_child_" ^ name, (fun () -> wait_on_slow_child wait_on); ])) ;; (* Clear wait-status for any children spawned by previous tests. *) let rec clear_wait_status () = let continue = try ignore (Unix.wait_nohang `Any); true with _ -> false in if continue then clear_wait_status () let tests = List.map unsafe_tests ~f:(fun (name, test) -> name, (fun () -> clear_wait_status (); test ())) ;;
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/lib_test/wait_test.ml
ocaml
Clear wait-status for any children spawned by previous tests.
open Core.Std open Async.Std open Qtest_lib.Std let fast_child () = Unix.fork_exec ~prog:"/bin/true" ~args:[] () let slow_child () = let prog = "/bin/sleep" in Unix.fork_exec ~prog ~args:[ prog; "1" ] () ;; let raises_echild f = try ignore (f ()); false with | Unix.Unix_error (Unix.ECHILD, _, _) -> true ;; let test_raises_echild () = assert (raises_echild (fun () -> Unix.wait_nohang `Any )); assert (raises_echild (fun () -> Unix.wait_nohang `My_group)); assert (raises_echild (fun () -> Unix.wait_nohang_untraced `Any )); assert (raises_echild (fun () -> Unix.wait_nohang_untraced `My_group)); Deferred.unit let wait_on_fast_child wait_on = fast_child () >>= fun pid -> Unix.wait (wait_on pid) >>| fun (pid', exit_or_signal) -> assert (Result.is_ok exit_or_signal); assert (pid = pid') let wait_on_slow_child wait_on = Deferred.List.map (List.init 10 ~f:(fun _i -> slow_child ())) ~f:Fn.id >>= fun pids -> Deferred.List.iter ~how:`Parallel pids ~f:(fun pid -> let wait_on = wait_on pid in Monitor.try_with (fun () -> Unix.wait wait_on >>| fun (_, exit_or_signal) -> if not (Result.is_ok exit_or_signal) then failwith (Unix.Exit_or_signal.to_string_hum exit_or_signal)) >>| function | Ok () -> () | Error exn -> failwiths "wait for slow child" (wait_on, exn) (<:sexp_of< Unix.wait_on * exn >>)) let unsafe_tests = ("Wait_test.raises_echild", test_raises_echild) :: (List.concat_map [ ("any", (fun _ -> `Any)); ("my_group", (fun _ -> `My_group)); ("pid", (fun pid -> `Pid pid)); ] ~f:(fun (name, wait_on) -> [ "Wait_test.fast_child_" ^ name, (fun () -> wait_on_fast_child wait_on); "Wait_test.slow_child_" ^ name, (fun () -> wait_on_slow_child wait_on); ])) ;; let rec clear_wait_status () = let continue = try ignore (Unix.wait_nohang `Any); true with _ -> false in if continue then clear_wait_status () let tests = List.map unsafe_tests ~f:(fun (name, test) -> name, (fun () -> clear_wait_status (); test ())) ;;
396ae7b48343875292b301e8279fce5739b59ec83b4d36ae7d4447b0d7580a1f
achirkin/vulkan
VK_EXT_queue_family_foreign.hs
# OPTIONS_HADDOCK not - home # {-# LANGUAGE DataKinds #-} {-# LANGUAGE MagicHash #-} # LANGUAGE PatternSynonyms # {-# LANGUAGE Strict #-} {-# LANGUAGE ViewPatterns #-} module Graphics.Vulkan.Ext.VK_EXT_queue_family_foreign * Vulkan extension : @VK_EXT_queue_family_foreign@ -- | -- -- supported: @vulkan@ -- contact : @Chad Versace @chadversary@ -- -- author: @EXT@ -- -- type: @device@ -- -- Extension number: @127@ -- -- Required extensions: 'VK_KHR_external_memory'. -- -- ** Required extensions: 'VK_KHR_external_memory'. VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION, pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, pattern VK_QUEUE_FAMILY_FOREIGN_EXT) where import GHC.Ptr (Ptr (..)) import Graphics.Vulkan.Constants (pattern VK_QUEUE_FAMILY_FOREIGN_EXT) import Graphics.Vulkan.Marshal pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION :: (Num a, Eq a) => a pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION = 1 type VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION = 1 pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME <- (is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME -> True) where VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME {-# INLINE _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME #-} _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = Ptr "VK_EXT_queue_family_foreign\NUL"# # INLINE is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME # is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString -> Bool is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = (EQ ==) . cmpCStrings _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME type VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = "VK_EXT_queue_family_foreign"
null
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_EXT_queue_family_foreign.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE MagicHash # # LANGUAGE Strict # # LANGUAGE ViewPatterns # | supported: @vulkan@ author: @EXT@ type: @device@ Extension number: @127@ Required extensions: 'VK_KHR_external_memory'. ** Required extensions: 'VK_KHR_external_memory'. # INLINE _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME #
# OPTIONS_HADDOCK not - home # # LANGUAGE PatternSynonyms # module Graphics.Vulkan.Ext.VK_EXT_queue_family_foreign * Vulkan extension : @VK_EXT_queue_family_foreign@ contact : @Chad Versace @chadversary@ VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION, pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, pattern VK_QUEUE_FAMILY_FOREIGN_EXT) where import GHC.Ptr (Ptr (..)) import Graphics.Vulkan.Constants (pattern VK_QUEUE_FAMILY_FOREIGN_EXT) import Graphics.Vulkan.Marshal pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION :: (Num a, Eq a) => a pattern VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION = 1 type VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION = 1 pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString pattern VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME <- (is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME -> True) where VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = Ptr "VK_EXT_queue_family_foreign\NUL"# # INLINE is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME # is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME :: CString -> Bool is_VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = (EQ ==) . cmpCStrings _VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME type VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME = "VK_EXT_queue_family_foreign"
6888c8a702f9fc4d64ec670ef1b278ee23ba28e6411836f5bb8558e27f161293
lpgauth/shackle
shackle_queue.erl
-module(shackle_queue). -include("shackle_internal.hrl"). -compile(inline). -compile({inline_size, 512}). %% internal -export([ add/5, clear/2, delete/1, new/1, remove/3, table_name/1 ]). %% internal -spec add(table(), server_id(), external_request_id(), cast(), reference()) -> ok. add(Table, ServerId, ExtRequestId, Cast, TimerRef) -> Object = {{ServerId, ExtRequestId}, {Cast, TimerRef}}, ets:insert(Table, Object), ok. -spec clear(table(), server_id()) -> [{cast(), reference()}]. clear(Table, ServerId) -> Match = {{ServerId, '_'}, '_'}, case ets_match_take(Table, Match) of [] -> []; Objects -> [{Cast, TimerRef} || {_, {Cast, TimerRef}} <- Objects] end. -spec delete(pool_name()) -> ok. delete(PoolName) -> ets:delete(table_name(PoolName)), ok. -spec new(pool_name()) -> ok. new(PoolName) -> Table = ets:new(table_name(PoolName), shackle_utils:ets_options()), ets:give_away(Table, whereis(shackle_ets_manager), undefined), ok. -spec remove(table(), server_id(), external_request_id()) -> {ok, cast(), reference()} | {error, not_found}. remove(Table, ServerId, ExtRequestId) -> case ets_take(Table, {ServerId, ExtRequestId}) of [] -> {error, not_found}; [{_, {Cast, TimerRef}}] -> {ok, Cast, TimerRef} end. %% private ets_match_take(Table, Match) -> case ets:match_object(Table, Match) of [] -> []; Objects -> ets:match_delete(Table, Match), Objects end. -ifdef(ETS_TAKE). ets_take(Table, Key) -> ets:take(Table, Key). -else. ets_take(Table, Key) -> case ets:lookup(Table, Key) of [] -> []; Objects -> ets:delete(Table, Key), Objects end. -endif. -spec table_name(pool_name()) -> table(). table_name(PoolName) -> list_to_atom("shackle_queue_" ++ atom_to_list(PoolName)).
null
https://raw.githubusercontent.com/lpgauth/shackle/a498ef0fde4808fa71fd5fe1404543475aaf7043/src/shackle_queue.erl
erlang
internal internal private
-module(shackle_queue). -include("shackle_internal.hrl"). -compile(inline). -compile({inline_size, 512}). -export([ add/5, clear/2, delete/1, new/1, remove/3, table_name/1 ]). -spec add(table(), server_id(), external_request_id(), cast(), reference()) -> ok. add(Table, ServerId, ExtRequestId, Cast, TimerRef) -> Object = {{ServerId, ExtRequestId}, {Cast, TimerRef}}, ets:insert(Table, Object), ok. -spec clear(table(), server_id()) -> [{cast(), reference()}]. clear(Table, ServerId) -> Match = {{ServerId, '_'}, '_'}, case ets_match_take(Table, Match) of [] -> []; Objects -> [{Cast, TimerRef} || {_, {Cast, TimerRef}} <- Objects] end. -spec delete(pool_name()) -> ok. delete(PoolName) -> ets:delete(table_name(PoolName)), ok. -spec new(pool_name()) -> ok. new(PoolName) -> Table = ets:new(table_name(PoolName), shackle_utils:ets_options()), ets:give_away(Table, whereis(shackle_ets_manager), undefined), ok. -spec remove(table(), server_id(), external_request_id()) -> {ok, cast(), reference()} | {error, not_found}. remove(Table, ServerId, ExtRequestId) -> case ets_take(Table, {ServerId, ExtRequestId}) of [] -> {error, not_found}; [{_, {Cast, TimerRef}}] -> {ok, Cast, TimerRef} end. ets_match_take(Table, Match) -> case ets:match_object(Table, Match) of [] -> []; Objects -> ets:match_delete(Table, Match), Objects end. -ifdef(ETS_TAKE). ets_take(Table, Key) -> ets:take(Table, Key). -else. ets_take(Table, Key) -> case ets:lookup(Table, Key) of [] -> []; Objects -> ets:delete(Table, Key), Objects end. -endif. -spec table_name(pool_name()) -> table(). table_name(PoolName) -> list_to_atom("shackle_queue_" ++ atom_to_list(PoolName)).
ed6c3f34fd227b531ef6fa17af429ba67c38d881ac240fa30f669db96c278094
inaka/erlang_guidelines
record_placement.erl
-module(record_placement). -export([good/0, bad/0]). -record(good, { this_record :: any() , appears :: any() , before :: any() , the_functions :: any()}). good() -> [#good{}]. -record(bad, { this_record :: any() , appears :: any() , below :: any() , a_function :: any()}). bad() -> [#bad{}].
null
https://raw.githubusercontent.com/inaka/erlang_guidelines/7a802a23a08d120db7e94115b4600b26194dd242/src/record_placement.erl
erlang
-module(record_placement). -export([good/0, bad/0]). -record(good, { this_record :: any() , appears :: any() , before :: any() , the_functions :: any()}). good() -> [#good{}]. -record(bad, { this_record :: any() , appears :: any() , below :: any() , a_function :: any()}). bad() -> [#bad{}].
9c1194cca88a342e951ce9ee7ebec913dd75d73ff22e292d9aaf45f1988117af
eshamster/watson
export.lisp
(defpackage :watson/t/definer/export (:use #:cl #:rove #:watson/definer/export) (:import-from #:watson/env/environment #:with-cloned-wenvironment #:wsymbol-export #:intern.wat) (:import-from #:watson/env/reserved-word #:|export| #:func #:|func|)) (in-package :watson/t/definer/export) (deftest defexport.wat (let ((i32.add 'watson/env/built-in-func::|i32.add|)) (let ((tests `((:name "simple case" :init ,(lambda () (defexport.wat js-func (func hoge))) :target-sym hoge :expect (|export| "js_func" (|func| $hoge)))))) (dolist (tt tests) (destructuring-bind (&key name init target-sym expect) tt (with-cloned-wenvironment (testing name (funcall init) (ok (equalp (funcall (wsymbol-export (intern.wat target-sym))) expect)))))))))
null
https://raw.githubusercontent.com/eshamster/watson/0525f4a657298cec74121162c3cd3dec953c7a25/t/definer/export.lisp
lisp
(defpackage :watson/t/definer/export (:use #:cl #:rove #:watson/definer/export) (:import-from #:watson/env/environment #:with-cloned-wenvironment #:wsymbol-export #:intern.wat) (:import-from #:watson/env/reserved-word #:|export| #:func #:|func|)) (in-package :watson/t/definer/export) (deftest defexport.wat (let ((i32.add 'watson/env/built-in-func::|i32.add|)) (let ((tests `((:name "simple case" :init ,(lambda () (defexport.wat js-func (func hoge))) :target-sym hoge :expect (|export| "js_func" (|func| $hoge)))))) (dolist (tt tests) (destructuring-bind (&key name init target-sym expect) tt (with-cloned-wenvironment (testing name (funcall init) (ok (equalp (funcall (wsymbol-export (intern.wat target-sym))) expect)))))))))