Search code examples
clojureclojurescript

How is the host interop dot macro implemented in clojure


I'm learning clojure and came across this syntax for interoping with host platform.

(.toUpperCase "fred")
-> "FRED"
(.getName String)
-> "java.lang.String"

I am curious how this is implemented. The docs say they are expanded to the dot special form at expansion time like this

(.instanceMember instance args*) ==> (. instance instanceMember args*)

There seems to be special behavior going on here. Normally the first argument in a macro invocation is just the macro symbol. In this case however, (. is somehow a generic macro that expands to something different based on the first argument in in the invocation immediately after (. like (.toUpperCase ... or (.getName ....

So how is this implemented? Does the implementation macro use some special syntax i'm not aware of it to get that behavior, or is that type of macro implementation behavior not available in userspace. Does it use an actual macro, or a reader macro?


Solution

  • These are described under the Java Interop section of the manual under Member Accress These are special forms that are expanded at macro expansion time.

    The instanceField form is preferred for fields and required if both a field and a 0-argument method of the same name exist. They all expand into calls to the dot operator (described below) at macroexpansion time. The expansions are as follows:

    (.instanceMember instance args*)  ==> (. instance instanceMember args*)
    (.instanceMember Classname args*) ==> (. (identity Classname) instanceMember args*)
    (.-instanceField instance)        ==> (. instance -instanceField)
    (Classname/staticMethod args*)    ==> (. Classname staticMethod args*)
    Classname/staticField             ==> (. Classname staticField)
    

    There are several forms of maco in Clojure:

    1. The normal kind or just "macros". You can write these.
    2. reader macros, which you can extend some of using tagged literals
    3. These special forms with macro expansion time evaluation. see also the expansion for the new special form