Last active
September 8, 2020 21:37
-
-
Save borkdude/c0987707ed0a1de0ab3a4c27c3affb03 to your computer and use it in GitHub Desktop.
Spec -> type information for clj-kondo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.java.io :as io] | |
'[clojure.spec.alpha :as s]) | |
(defn foo [x y] | |
(+ x y)) | |
(s/def ::x string?) | |
(s/def ::y ::x) | |
(s/fdef foo :args (s/cat :x int? :y ::y)) | |
(comment | |
(foo 1 :foo)) | |
(defn bar [m] | |
m) | |
(s/def ::z string?) | |
(s/fdef bar :args (s/cat :m (s/keys :req-un [::x ::y] | |
:opt-un [::z]))) | |
(bar {:x 1 :z :foo}) | |
(def fn->k | |
{'clojure.core/int? :int | |
'clojure.core/string? :string}) | |
(declare resolve-spec) | |
(defn cat* [& forms] | |
(let [specs (take-nth 2 (rest forms)) | |
resolved (map resolve-spec specs)] | |
resolved)) | |
(defn unqualify [k] | |
(keyword (name k))) | |
(defn keys* [& {:keys [:req-un :opt-un]}] | |
(let [required (map resolve-spec req-un) | |
optional (map resolve-spec opt-un)] | |
{:op :keys | |
:req (zipmap (map unqualify req-un) required) | |
:opt (zipmap (map unqualify opt-un) optional)})) | |
(defn dispatch [[op & args]] | |
(case op | |
clojure.spec.alpha/cat (apply cat* args) | |
clojure.spec.alpha/keys (apply keys* args) | |
nil)) | |
(defn resolve-spec [x] | |
(cond (qualified-keyword? x) | |
(resolve-spec (s/form (s/spec x))) | |
(seq? x) (dispatch x) | |
(symbol? x) (fn->k x) | |
:else x)) | |
(defn emit-kondo-types [& syms] | |
(let [spec-dir (io/file ".clj-kondo/spec/config.edn") | |
config | |
(reduce (fn [acc sym] | |
(let [sym-ns (symbol (namespace sym)) | |
sym-name (symbol (name sym)) | |
[_fspec _:args args-spec] (s/form (s/get-spec sym))] | |
(when (seq? args-spec) | |
(let [arg-types (resolve-spec args-spec) | |
arity (count arg-types)] | |
(assoc-in acc [:linters :type-mismatch :namespaces | |
sym-ns sym-name :arities arity :args] arg-types))))) | |
{} | |
syms)] | |
(prn config) | |
(io/make-parents spec-dir) | |
(spit spec-dir config))) | |
(emit-kondo-types 'user/foo 'user/bar) |
Author
borkdude
commented
Sep 7, 2020
•
Interesting work in this context: https://github.com/metosin/spec-tools/blob/master/test/cljc/spec_tools/visitor_all_test.cljc
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment