Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

[lint] Implement Kondo hooks for metabase.util.match macros (#73986)

Oleksandr Yakushev7afc643c0c7a
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 2117fb5fcf0..7bc4b748e40 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -252,9 +252,6 @@
;; misc config for built-in linters
;;
- :invalid-arity {:skip-args [metabase.util.match/match-one
- metabase.util.match/match-many
- metabase.util.match/replace]} ; TODO (cam): can we fix these?
:refer-all {:level :warning, :exclude [clojure.test]}
:unused-referred-var {:exclude {compojure.core [GET DELETE POST PUT]}}
@@ -708,6 +705,10 @@
metabase.util.log/warn hooks.metabase.util.log/info
metabase.util.log/warnf hooks.metabase.util.log/infof
metabase.util.malli.registry/def hooks.metabase.util.malli.registry/def
+ metabase.util.match/match-one hooks.metabase.util.match/match-one
+ metabase.util.match/match-many hooks.metabase.util.match/match-many
+ metabase.util.match/replace hooks.metabase.util.match/replace
+ metabase.util.match/replace-in hooks.metabase.util.match/replace-in
metabase.util/case-enum hooks.metabase.util/case-enum
metabase.util/format-color hooks.metabase.util/format-color
metabase.xrays.api.automagic-dashboards-test/with-indexed-model! hooks.metabase.xrays.api.automagic-dashboards-test/with-indexed-model!
diff --git a/.clj-kondo/src/hooks/metabase/util/match.clj b/.clj-kondo/src/hooks/metabase/util/match.clj
new file mode 100644
index 00000000000..69c62cfe29f
--- /dev/null
+++ b/.clj-kondo/src/hooks/metabase/util/match.clj
@@ -0,0 +1,132 @@
+(ns hooks.metabase.util.match
+ (:require [clj-kondo.hooks-api :as api]))
+
+(defn- token-node? [node token-name]
+ (and (api/token-node? node)
+ (= (str (:value node)) token-name)))
+
+(defn- keyword-node? [node k]
+ (and (api/keyword-node? node)
+ (= (:k node) k)))
+
+(defn- binding-symbol?
+ "True when the token is a plain symbol that should be treated as a binding
+ (not a keyword, not a boolean literal, not nil, not a number, not `_`)."
+ [node]
+ (and (api/token-node? node)
+ (let [v (:value node)]
+ (and (symbol? v)
+ (not (contains? '#{_ nil true false} v))))))
+
+;; To establish fake let bindings, we need to bind them to something. This "something" has to be vague enough to trick
+;; kondo into not looking too much into it. E.g., if we bind everything to `nil`, Kondo linters will get fired up.
+(def opaque-node (api/list-node (list (api/token-node 'rand-nth) (api/list-node []))))
+
+(defn collect-bindings
+ "Return a list of token nodes (symbols) introduced as bindings by `pattern`."
+ [pattern]
+ (cond
+ (binding-symbol? pattern)
+ [[pattern opaque-node]]
+
+ ;; Lists: (:or ...), (:and ...), (sym :guard pred ...), or a quoted symbol.
+ (api/list-node? pattern)
+ (let [[head & rst] (:children pattern)]
+ (cond (or (keyword-node? head :or)
+ (keyword-node? head :and))
+ (mapcat collect-bindings rst)
+
+ (api/token-node? head)
+ (cond-> []
+ (binding-symbol? head) (conj [head opaque-node])
+ (keyword-node? (first rst) :guard) (conj [(api/token-node '_) (second rst)]))
+
+ ;; anything else (e.g. a function call used as predicate) — no bindings
+ :else []))
+
+ (api/vector-node? pattern)
+ (mapcat (fn [node]
+ (when-not (token-node? node "&")
+ (collect-bindings node)))
+ (:children pattern))
+
+ ;; Maps: keys are literal selectors, values are sub-patterns.
+ ;; Special value-symbols &truthy and _ are NOT user bindings.
+ (api/map-node? pattern)
+ (let [children (:children pattern)
+ pairs (partition 2 children)]
+ (mapcat (fn [[_k v]]
+ (when-not (or (token-node? v "&truthy")
+ (token-node? v "_"))
+ (collect-bindings v)))
+ pairs))
+
+ ;; For sets, make sure to use them because they may reference some of the outer local bindings, so if we don't
+ ;; include them, Kondo will complain about those bindings being unused.
+ (api/set-node? pattern)
+ [[(api/token-node '_) pattern]]
+
+ ;; Anything else — no bindings.
+ :else []))
+
+(defn- dedupe-bindings
+ "Prevent Kondo complaining that we have multiple fake bindings."
+ [pairs]
+ (loop [[[sym v] & r] pairs, seen #{}, result []]
+ (cond (nil? sym) result
+ (and (seen sym) (not (token-node? sym "_"))) (recur r seen result)
+ :else (recur r (conj seen sym) (conj result sym v)))))
+
+(defn match-one
+ "clj-kondo :analyze-call hook for match-one.
+
+ Rewrites
+
+ (match-one value
+ pat1 ret1
+ pat2 ret2
+ ...)
+
+ into a `let` form that declares all binding symbols introduced by the patterns, so clj-kondo knows they are
+ legitimate and won't warn about unresolved/unused symbols:
+
+ (let [<all-bindings> (rand-nth []) ...]
+ (or ret1 ret2 ...))"
+ [{:keys [node]}]
+ (let [[_ value & clauses] (:children node)]
+ (when (odd? (count clauses))
+ (api/reg-finding!
+ {:message "match-one/match-many/replace requires an even number of pattern/result pairs"
+ :type :metabase/match-odd-clauses
+ :row (:row node)
+ :col (:col node)
+ :filename (-> node meta :filename)}))
+ (let [pairs (partition 2 clauses)
+ all-bindings (->> pairs
+ (mapcat (fn [[pat _ret]] (collect-bindings pat)))
+ dedupe-bindings)
+ special-bindings [(api/token-node '_) value
+ (api/token-node '&match) opaque-node
+ (api/token-node '&parents) opaque-node
+ (api/token-node '&recur) opaque-node
+ ;; Pretend to use &match, &parents, and &recur so that Kondo doesn't complain about them
+ ;; if they are not used by the user code.
+ (api/token-node '_) (api/token-node '&match)
+ (api/token-node '_) (api/token-node '&parents)
+ (api/token-node '_) (api/token-node '&recur)]
+ binding-nodes (into special-bindings all-bindings)
+ result-exprs (map second pairs)
+ new-node (api/list-node
+ (list
+ (api/token-node 'let)
+ (api/vector-node binding-nodes)
+ (api/list-node
+ (concat [(api/token-node 'clojure.core/or)] result-exprs [opaque-node]))))]
+ {:node new-node})))
+
+(def match-many match-one)
+(def replace match-one)
+
+(defn replace-in [context]
+ ;; Everything is the same as in match-one, just drop the middle argument.
+ (match-one (update-in context [:node :children] (fn [[sym value path & clauses]] (list* sym value clauses)))))
diff --git a/.clj-kondo/test/hooks/metabase/util/match_test.clj b/.clj-kondo/test/hooks/metabase/util/match_test.clj
new file mode 100644
index 00000000000..2c41c059afd
--- /dev/null
+++ b/.clj-kondo/test/hooks/metabase/util/match_test.clj
@@ -0,0 +1,59 @@
+(ns hooks.metabase.util.match-test
+ (:require
+ [clj-kondo.hooks-api :as hooks]
+ [clj-kondo.impl.utils]
+ [clojure.test :refer :all]
+ [hooks.metabase.util.match :as sut]))
+
+(defn- expand [src]
+ (-> (sut/match-one {:node (hooks/parse-string (pr-str src))})
+ :node
+ hooks/sexpr))
+
+(defn- lint [src]
+ (binding [clj-kondo.impl.utils/*ctx* {:config {:linters {:metabase/match-odd-clauses {:level :warning}}}
+ :ignores (atom nil)
+ :findings (atom [])
+ :namespaces (atom {})}]
+ (expand src)
+ @(:findings clj-kondo.impl.utils/*ctx*)))
+
+(deftest odd-clauses-triggers-warning-test
+ (is (=? [{:type :metabase/match-odd-clauses}]
+ (lint '(metabase.util.match/match-one [] [a b c])))))
+
+(deftest expansion-test
+ (testing "simple expansion example"
+ (is (= '(let [_ []
+ &match (rand-nth ())
+ &parents (rand-nth ())
+ &recur (rand-nth ())
+ _ &match
+ _ &parents
+ _ &recur
+ a (rand-nth ())
+ b (rand-nth ())
+ c (rand-nth ())]
+ (clojure.core/or (+ a b) (rand-nth ())))
+ (expand '(match-one [] [a b c] (+ a b))))))
+ (testing "complicated expansion example that uses most match-one macro features, and also binding deduplication by the rewriter"
+ (is (= '(let [_ []
+ &match (rand-nth ())
+ &parents (rand-nth ())
+ &recur (rand-nth ())
+ _ &match
+ _ &parents
+ _ &recur
+ val1 (rand-nth ())
+ a (rand-nth ())
+ _ #{maybe important}
+ rst (rand-nth ())
+ x (rand-nth ())
+ _ (= x 3)
+ b (rand-nth ())]
+ (clojure.core/or (+ a val1) (rand-nth ())))
+ (expand '(match-one []
+ (:or [{:key1 val1, :key2 &truthy, :key3 _} _ a #{maybe important} & rst]
+ (:and (x :guard (= x 3))
+ [a b]))
+ (+ a val1)))))))
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
index bdf41125458..b894bc43730 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
@@ -1483,10 +1483,7 @@ function(bin) {
(assoc-in
m
(match/match-one field-clause
- [:field (field-id :guard integer?) _]
- (str/split (field-alias field-clause) #"\.")
-
- [:field (field-name :guard string?) _]
+ [:field (id :guard (or (integer? id) (string? id))) _]
(str/split (field-alias field-clause) #"\.")
[:expression expr-name _]
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index 734f463e492..483d437fa92 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -1461,7 +1461,7 @@
[:aggregation-options ag {:name name}]
(->honeysql driver (h2x/identifier :field-alias name))
- [:aggregation-options ag options]
+ [:aggregation-options ag _]
(&recur ag)
;; For some arcane reason we name the results of a distinct aggregation "count", everything else is named the
diff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljc
index 576abdb0280..6eccb57b92d 100644
--- a/src/metabase/lib/fe_util.cljc
+++ b/src/metabase/lib/fe_util.cljc
@@ -631,15 +631,15 @@
:get-quarter :quarter-of-year}]
(match/match-one filter-clause
;; no arguments
- [(op :guard #{:is-null :not-null}) _ (col-ref :guard date-col?) & (args :len 0 :guard (every? int? args))]
+ [(op :guard #{:is-null :not-null}) _ (col-ref :guard date-col?)]
{:operator op, :column (ref->col col-ref), :values []}
;; without `mode`
- [(_ :guard #{:!= :not-in}) _ [(op :guard #{:get-hour :get-month :get-quarter}) _ (col-ref :guard date-col?)] & (args :guard (every? int? args))]
+ [#{:!= :not-in} _ [(op :guard #{:get-hour :get-month :get-quarter}) _ (col-ref :guard date-col?)] & (args :guard (every? int? args))]
{:operator :!=, :column (ref->col col-ref), :unit (op->unit op), :values args}
;; with `:mode`
- [(_ :guard #{:!= :not-in}) _ [:get-day-of-week _ (col-ref :guard date-col?) :iso] & (args :guard (every? int? args))]
+ [#{:!= :not-in} _ [:get-day-of-week _ (col-ref :guard date-col?) :iso] & (args :guard (every? int? args))]
{:operator :!=, :column (ref->col col-ref), :unit :day-of-week, :values args}
;; do not match inner clauses
diff --git a/src/metabase/lib/filter/update.cljc b/src/metabase/lib/filter/update.cljc
index d6e1be0b9fd..95095b5bf68 100644
--- a/src/metabase/lib/filter/update.cljc
+++ b/src/metabase/lib/filter/update.cljc
@@ -37,10 +37,8 @@
(lib.equality/find-matching-column expr [column])))
(defn- contains-ref-for-column? [expr column]
- (letfn [(ref-for-column? [expr]
- (is-ref-for-column? expr column))]
- (match/match-one expr
- (x :guard ref-for-column?) true)))
+ (match/match-one expr
+ (x :guard (is-ref-for-column? x column)) true))
(mu/defn- remove-existing-filters-against-column* :- ::lib.schema/query
[query :- ::lib.schema/query
diff --git a/src/metabase/lib/order_by.cljc b/src/metabase/lib/order_by.cljc
index e2ddbce9047..1629de8b718 100644
--- a/src/metabase/lib/order_by.cljc
+++ b/src/metabase/lib/order_by.cljc
@@ -190,7 +190,7 @@
current-order-by :- ::lib.schema.order-by/order-by]
(let [lib-uuid (lib.options/uuid current-order-by)]
(match/replace query
- [direction {:lib/uuid (uuid :guard (= uuid lib-uuid))} _]
+ [direction {:lib/uuid (id :guard (= id lib-uuid))} _]
(assoc &match 0 (opposite-direction direction))))))
(mu/defn remove-all-order-bys :- ::lib.schema/query
diff --git a/src/metabase/lib/query.cljc b/src/metabase/lib/query.cljc
index 4f701f6a929..89b3a7a3530 100644
--- a/src/metabase/lib/query.cljc
+++ b/src/metabase/lib/query.cljc
@@ -127,7 +127,7 @@
[x metadata-provider :- ::lib.schema.metadata/metadata-provider]
(if-let [field-ids (match/match-many x
[:field
- (_opts :guard (and (map? _opts) (not (and (:base-type _opts) (:effective-type _opts)))))
+ (opts :guard (and (map? opts) (not (and (:base-type opts) (:effective-type opts)))))
(id :guard (and (integer? id) (pos? id)))]
(when-not (some #{:mbql/stage-metadata} &parents)
id))]
diff --git a/src/metabase/lib/walk/util.cljc b/src/metabase/lib/walk/util.cljc
index 00c9d426f0a..fe9b100c4e3 100644
--- a/src/metabase/lib/walk/util.cljc
+++ b/src/metabase/lib/walk/util.cljc
@@ -186,7 +186,7 @@
implicit-join-field-opt? #(and (:source-field %) (not (:join-alias %)))
walk-clause (fn [clause]
(match/match-one clause
- [:field (opts :guard implicit-join-field-opt?) (id :guard pos-int?)]
+ [:field (_opts :guard implicit-join-field-opt?) (id :guard pos-int?)]
(vswap! joined-field-ids conj! id)
_ nil)
diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.clj
index ebb93b04ea6..301a15d8c90 100644
--- a/src/metabase/models/serialization.clj
+++ b/src/metabase/models/serialization.clj
@@ -1291,7 +1291,7 @@
[:field (export-mbql-map opts) id]
;; legacy (MBQL 4) field refs are still supported in parameter targets and in result metadata `field_ref`...
- [:field (id :guard pos-int?) (opts :guard (some-fn map? nil?))]
+ [:field (id :guard pos-int?) (opts :guard (or (map? opts) (nil? opts)))]
[:field (*export-field-fk* id) (export-mbql-map opts)]
;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.
@@ -1381,11 +1381,11 @@
[:field (import-mbql-map opts) (*import-field-fk* fully-qualified-name)]
;; legacy field refs, still used in parameters and result metadata `field_ref`
- [#{:field "field"} (fully-qualified-name :guard vector?) (opts :guard (some-fn map? nil))]
+ [#{:field "field"} (fully-qualified-name :guard vector?) (opts :guard (or (map? opts) (nil? opts)))]
[:field (*import-field-fk* fully-qualified-name) (some-> opts import-mbql-update-refs)]
;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.
- [(tag :guard #{:field :field-id "field" "field-id"}) (id :guard vector?)]
+ [#{:field :field-id "field" "field-id"} (id :guard vector?)]
[:field (*import-field-fk* id) nil]
[#{:metric "metric"} opts (entity-id :guard portable-id?)]
diff --git a/src/metabase/models/serialization/resolve.clj b/src/metabase/models/serialization/resolve.clj
index 1ac41ca0138..27dbbd04003 100644
--- a/src/metabase/models/serialization/resolve.clj
+++ b/src/metabase/models/serialization/resolve.clj
@@ -89,11 +89,11 @@
(import-field-fk resolver fully-qualified-name)]
;; legacy field refs, still used in parameters and result metadata `field_ref`
- [#{:field "field"} (fully-qualified-name :guard vector?) (opts :guard (some-fn map? nil))]
+ [#{:field "field"} (fully-qualified-name :guard vector?) (opts :guard (or (map? opts) (nil? opts)))]
[:field (import-field-fk resolver fully-qualified-name) (some->> opts (mbql-fully-qualified-names->ids* resolver))]
;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.
- [(tag :guard #{:field :field-id "field" "field-id"}) (id :guard vector?)]
+ [#{:field :field-id "field" "field-id"} (id :guard vector?)]
[:field (import-field-fk resolver id) nil]
;; source-field is also used within parameter mapping dimensions
@@ -200,7 +200,7 @@
[:field (mbql-id->fully-qualified-name resolver opts) (export-field-fk resolver id)]
;; legacy (MBQL 4) field refs are still supported in parameter targets and in result metadata `field_ref`...
- [:field (id :guard pos-int?) (opts :guard (some-fn map? nil?))]
+ [:field (id :guard pos-int?) (opts :guard (or (map? opts) (nil? opts)))]
[:field (export-field-fk resolver id) (mbql-id->fully-qualified-name resolver opts)]
;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.
diff --git a/src/metabase/query_processor/middleware/add_implicit_joins.clj b/src/metabase/query_processor/middleware/add_implicit_joins.clj
index 1372343a1cf..1e881f24121 100644
--- a/src/metabase/query_processor/middleware/add_implicit_joins.clj
+++ b/src/metabase/query_processor/middleware/add_implicit_joins.clj
@@ -129,7 +129,7 @@
(let [fk-field-infos (->> field-clauses-with-source-field
(keep (fn [clause]
(match/match-one clause
- [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) (id :guard integer?)]
+ [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) (_id :guard integer?)]
(field-opts->fk-field-info metadata-providerable opts))))
distinct
not-empty)
@@ -180,7 +180,7 @@
stage :- ::lib.schema/stage]
(or (when-let [fk-field-info->join-alias (not-empty (construct-fk-field-info->join-alias query path stage))]
(let [stage' (match/replace stage
- [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) id-or-name]
+ [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) _id-or-name]
(if-not (some #{:lib/stage-metadata} &parents)
(let [join-alias (or (fk-field-info->join-alias (field-opts->fk-field-info query opts))
(throw (ex-info (tru "Cannot find matching FK Table ID for FK Field {0}"
diff --git a/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj b/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
index d665f482776..bb8efb88bde 100644
--- a/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
+++ b/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
@@ -19,7 +19,7 @@
query
(fn [query _path-type path clause]
(match/match-one clause
- [:field (:and opts {:temporal-unit temporal-unit}) _id-or-name]
+ [:field {:temporal-unit temporal-unit} _id-or-name]
(let [effective-type (lib.walk/apply-f-for-stage-at-path lib/type-of query path clause)
valid-units (lib.temporal-bucket/valid-units-for-type effective-type)]
(when-not (valid-units temporal-unit)
diff --git a/test/metabase/util/match_test.cljc b/test/metabase/util/match_test.cljc
index 58ce8267068..2b74309cfa4 100644
--- a/test/metabase/util/match_test.cljc
+++ b/test/metabase/util/match_test.cljc
@@ -1,4 +1,5 @@
(ns metabase.util.match-test
+ {:clj-kondo/config '{:linters {:unused-binding {:level :off}}}}
(:require
[clojure.test :as t]
[metabase.util.match :as match]))