Welcome! Please see the About page for a little more info on how this works.

0 votes
in Syntax and reader by

I was curious if a function could be defined like the following:

(defn my-cli-func
  (docstr 
    :description "Some CLI function with complex args to do something cool"
    [["-p" "--port" :port "Port to listen for connections on"]])
  [args]
  "...")

The intention is that docstr could generate a docstring in a consistent format I can validate and such. That did not work as I get an error about where the Parameter declaration should be.

I'm guessing it could be done with a defn wrapper macro but probably not worth the hassle right now.

I was curious if there was a design decision to not allow meta programming there or if it's some kind of mechanical restriction due to the implementation.

1 Answer

+1 vote
by
selected by
 
Best answer
 ~ % clj
Clojure 1.10.1
user=> (defn ^{:doc (str "foo" "bar")} f [x] x)
#'user/f
user=> (doc f)
-------------------------
user/f
([x])
  foobar
nil
user=>

replace the call to str with whatever you want. you can also change the docstring after the fact.

user=> (alter-meta! #'f assoc :doc "something")
{:doc "something", :arglists ([x]), :line 1, :column 1, :file "NO_SOURCE_PATH", :name f, :ns #object[clojure.lang.Namespace 0x72ba28ee "user"]}
user=> (doc f)
-------------------------
user/f
([x])
  something
nil
user=>
by
Re the "validate and such" part of the query:  The alter-meta! way works (and is more a base case than an exceptional case) because in Clojure you are at liberty to establish vars in any way that suits you. Indeed Clojure provides multiple ways as examples, including defn, defrecord, defmulti, etc., and by no means is it a closed set.  Consequently, the only way, strictly, to find and check docstrings is to eval the forms and then query the Clojure environment for vars' metadata.
by
Oh right I forgot about that API. That’s really amazing. Thanks!
by
Somewhat on a tangent, but I made this thing some years ago (which I have of course never used) https://github.com/slipset/checkdoc
...