Fork me on GitHub
#clj-kondo
<
2020-01-05
>
yuhan10:01:41

Can clj-kondo infer argument/return types of a function from type hints?

yuhan10:01:28

i.e. I can see it currently doesn't, but would that be within its capabilities / design scope?

yuhan10:01:13

I recently made a typo with a clojure.string function, looked at clj-kondo's types.clojure.string namespace to see that it hadn't been specced yet, then saw from the clojure.string source that most functions were already hinted with ^String or ^CharSequence

borkdude10:01:38

This currently works:

(defn foo ^String [])
(inc (foo))

borkdude10:01:51

you'll get a warning about string instead of number

yuhan10:01:19

hmm, but (inc (string/reverse "abc")) doesn't give a warning

yuhan10:01:58

(defn ^String reverse
  "Returns s with its characters reversed."
  {:added "1.2"}
  [^CharSequence s]
  (.toString (.reverse (StringBuilder. s))))

yuhan10:01:58

huh, so there are two different places where the return type hint can go

borkdude10:01:17

that's because the var is hinted, not the return type

borkdude10:01:21

which is wrong

yuhan10:01:58

Yeah, apparently the compiler detects that as a valid type hint 😮

yuhan10:01:21

(set! *warn-on-reflection* true)
(defn f1 [])
(defn f2 ^String [])
(defn ^String f3 [])

(fn []
  (.length (f1))
  (.length (f2))
  (.length (f3)))
^ Only f1 gets a reflection warning

borkdude10:01:55

so the type hint on a var also gets used for inferring the return type? if you can confirm that this is correct behavior clj-kondo could adopt this

borkdude10:01:23

by checking this in #clojure with e.g. Alex Miller

yuhan12:01:02

Looks like the answer is yes, tags on function vars can be used to infer the return type

yuhan12:01:05

Although the arglist tag takes precedence

borkdude12:01:01

Issue welcome. After that, PR + tests also welcome.

borkdude12:01:28

Note that you have to re-run script/extract-var-info after making the change, so the tags will be picked up from the code.

Kari Marttila14:01:12

Is there a functionality in clj-kondo IntelliJ IDEA integration to have all warnings and errors listed in IDEA's "Errors box" and then double click certain error/warning and cursor would go to that row in source file?

borkdude20:01:36

I don't know IntelliJ well enough to answer this.

Kari Marttila14:01:52

I really like clj-kondo, good tool!