liveBook · Manning

Syntax-quote

As explained in Clojure: The Essential Reference

Syntax-quote is Clojure reader syntax that quotes an expression while supporting symbol qualification, gensym generation, unquoting, and unquote-splicing.

Syntax-quote (`) constructs a Clojure expression as data, usually for a macro to return as code. Like quote, it prevents the whole expression from being evaluated immediately; unlike simple quoting, it can qualify symbols and selectively insert evaluated values. The resulting macro expansion is evaluated at run time. section 4.0 section 4.1

Four features make syntax-quote useful when constructing macro expansions:

  • Symbol qualification: `s/upper-case becomes clojure.string/upper-case; an unresolved `foo becomes user/foo in the shown namespace. section 4.1
  • Auto-gensym: a name ending in # becomes a generated, unqualified symbol. In `(let [x# 1] x#), both occurrences use the generated name. section 4.1
  • Unquote (~): evaluate one expression and insert its result. `(+ 1 2) remains a qualified call, while `~(+ 1 2) inserts 3. section 4.1
  • Unquote-splicing (~@): insert the elements of a collection rather than the collection as one value. It is useful for inserting a macro’s body forms. section 4.1

Insert one value or splice several

`[1 2 ~[3 4] ~@[3 (+ 1 2)]] ;; [1 2 [3 4] 3 3] The unquoted vector stays one element; the spliced vector contributes two elements. section 4.1

Qualification and auto-gensym help avoid accidental symbol capture in macros. The pattern ~'foo deliberately inserts an unqualified symbol, bypassing those protections, and is discouraged. Splicing also has limits: ~@ outside syntax-quote, a non-sequenceable value such as a keyword, or a splice with no enclosing collection produces an error. section 4.1

`[foo foo# ~'foo]
;; [user/foo foo__45__auto__ foo]

Compare the qualified symbol, generated symbol, and deliberately unqualified symbol in one result. section 4.1

How Clojure: The Essential Reference covers it

How deep it goes
Works through qualification, generated symbols, unquoting, splicing, and error cases; does not develop reader internals.
Examples
Uses qualified library symbols, generated let bindings, vector insertion and splicing, and a retry macro.
What it assumes
Assumes familiarity with Clojure expressions and namespaces while introducing syntax-quote’s notation through examples.
What you can do after
Build it from scratch: construct macro expansions with qualified references, generated locals, and inserted or spliced forms.
How it connects
Connects quote, defmacro, namespaces, gensym, unquote, unquote-splicing, and macro hygiene.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.