Skip to content

Macros

LisPy's macro system is highly inspired by Clojure's macro system. You can check out the Chapter 7 and Chapter 8 of "Brave Clojure" for more information about Clojure's macro system.

Expression Nodes

These nodes are defined in src/lispy/core/nodes.py.

You can check out how to manipulate these nodes in

  • the definitions of nodes themselves
  • the definitions of built-in macros in src/lispy/macros/sugar.lpy.

quote

'expr

syntax-quote

`expr

unquote

~expr

unquote-splicing

~@expr

Macro Definition

Just change def in function definition to defmacro. And macros usually return a quoted expression.

(defmacro name [args*]
  body*)

Macro Example

(defmacro unless [test *body]
  (return `(if (not ~test)
             (do ~@body))))

(unless done
  (print "working"))
Python version
if not done:
    print("working")
The built-in macros (below) are written the same way; their definitions are in src/lispy/macros/sugar.lpy.

require

Loads the macros of a module so the file can use them. Macros are compile-time only: require leaves no runtime import behind.

LisPy version

(require mod)          ; every macro, as mod.name
(require mod *)        ; every macro, unqualified
(require mod [a b])    ; only a and b, unqualified
(require mod [])       ; none
- (require mod) registers each macro of mod under the qualified name mod.name, so it is called as (mod.name ...). - (require mod *) registers every macro under its own name. - (require mod [a b]) registers just the listed macros under their own names. - (require mod []) registers nothing.

A module that cannot be found is a warning (could not load macros from 'mod' (module not found)), not an error; a macro that was never registered then fails where it is used.

Built-in macros

The built-in macros are loaded in every module and in the REPL with no require. A module's own defmacros and explicit requires add to them, and (require mod *) never re-exports the built-ins.

To load only some of them, make (require lispy.macros <selection>) the module's first form (after an optional docstring); the selection replaces the built-ins:

(require lispy.macros [-> when])   ; only -> and when
(require lispy.macros [])          ; none
(require lispy.macros *)           ; all (the default)
A bare (require lispy.macros) leaves only the qualified (lispy.macros.inc ...) names. A later require of lispy.macros only adds macros.

Binding a name that is an active macro (def, class, =, parameters, a defmacro's parameters and locals, loop and with targets, imports, match captures, ...) is a compile error, because (inc ...) would still expand the macro. Rename the binding, or opt out of that macro with a selection that omits it. A hyphenated name is one name with its Python name, so a binding my_x clashes with a macro my-x and a binding my-x with a macro my_x; any other spelling (->, --, ok?) clashes only with that same spelling, not with the name it mangles to (_to_, __, ok_p).

The Python version in each example is what l2py prints.

cond

(cond test then test then ... else)

Nested if statements: each test/then pair is one branch (elif after the first) and a trailing odd operand is the final else. It is a statement and yields no value: use conde for a value, and (do ...) for a branch of several forms.

LisPy version

(cond (< x 0) (print "neg")
      (== x 0) (print "zero")
      (print "pos"))
Python version
if x < 0:
    print("neg")
elif x == 0:
    print("zero")
else:
    print("pos")

conde

(conde test then test then ... else)

The expression form of cond: a chain of ife whose trailing odd operand is the final else. An expression needs a value on every path, so an even number of operands (no else) is a compile error, like Python's x if c.

LisPy version

(= label (conde (< x 0) "neg"
                (== x 0) "zero"
                "pos"))
Python version
label = "neg" if x < 0 else "zero" if x == 0 else "pos"

The final else is required: (conde x 1 y 2) is a compile error, as 1 if x else 2 if y is in Python.

->

(-> value form ...)

Thread-first: insert value as the first argument of the first form, that result as the first argument of the next, and so on. A form that is not a parenthesised call, such as a bare name, is called with the value: (-> x f (g 2)) is g(f(x), 2).

LisPy version

(-> x (f 1) (g 2))
Python version
g(f(x, 1), 2)

->>

(->> value form ...)

Thread-last: insert value as the last argument of the first form, that result as the last argument of the next, and so on. A form that is not a parenthesised call, such as a bare name, is called with the value: (->> x f (g 1)) is g(1, f(x)).

LisPy version

(->> x (f 1) (g 2))
Python version
g(2, f(1, x))

A bare name is called with the value and threading stays last: (->> x f (g 1)) is g(1, f(x)).

as->

(as-> value name form ...)

Bind name to value, then to each form's result in turn, and yield the last result, so name can stand anywhere in a form. An expression: each form is evaluated once, left to right, in the caller's scope.

Unlike -> (thread first) and ->> (thread last), as-> lets you name the threaded value and place it anywhere in each form:

(as-> 0 x
  (+ x 10)     ;; x = 10
  (* 2 x)      ;; x = 20
  (str x))     ;; x = "20"

This expands to a single expression, a tuple of walrus assignments indexed with -1:

((__x_0 := 0), (__x_0 := (__x_0 + 10)), (__x_0 := (2 * __x_0)), str(__x_0))[-1]

Because it is an expression, as-> works anywhere: as a return value, a call argument, a lambda body, or nested. CPython refuses := in some positions (e.g. a comprehension's iterable, annotations, type-alias values); there it is a loud compile error, so bind the value first.

The name is replaced only where it is read as a variable, not in keyword-argument names, quoted data, or the body of a fn/lambda that rebinds it.

Useful when the threaded value doesn't always go in the first or last position.

fn

(fn [args] body)

Alias of lambda: an anonymous function whose body is one expression.

LisPy version

(= double (fn [x] (* 2 x)))
Python version
double = lambda x: 2 * x

comment

(comment body...)

Ignore the body: nothing in it is compiled or evaluated, and the form expands to None.

LisPy version

(comment (print "never runs") (undefined-name))
(print "done")
Python version
None
print("done")

when

(when test body...)

An if statement with no else, whose branch runs every body form in order. A statement: it yields no value. The body must hold a statement, as Python's if does: (when test) is a compile error.

LisPy version

(when (> x 0)
  (print "positive")
  (= y x))
Python version
if x > 0:
    print("positive")
    y = x

inc

(inc value)

The expression value + 1; value itself is left unchanged.

LisPy version

(= y (inc x))
Python version
y = x + 1

dec

(dec value)

The expression value - 1; value itself is left unchanged.

LisPy version

(= z (dec x))
Python version
z = x - 1

++

(++ target)

The statement target += 1.

LisPy version

(++ n)
Python version
n += 1

--

(-- target)

The statement target -= 1.

LisPy version

(-- n)
Python version
n -= 1

gensym

gensym generates unique symbols to avoid variable name collisions in macros. It is automatically available inside defmacro bodies.

(gensym)          ;; => Symbol("__gensym_0")
(gensym "tmp")    ;; => Symbol("__tmp_1")
(gensym 'tmp)     ;; => Symbol("__tmp_2")  (also accepts a quoted Symbol)

The prefix can be a string or a symbol. Each call increments a global counter, so every generated symbol is unique.

Why gensym?

Without gensym, a macro that introduces a local variable can accidentally shadow a variable in the caller's scope:

;; BAD: if the caller has a variable named `tmp`, this breaks
(defmacro broken-swap [a b]
  (return `(do (= tmp ~a)
               (= ~a ~b)
               (= ~b tmp))))

Using gensym prevents this:

(defmacro swap [a b]
  (= tmp (gensym "tmp"))
  (return `(do (= ~tmp ~a)
               (= ~a ~b)
               (= ~b ~tmp))))

Now (swap x y) expands to something like:

__tmp_0 = x
x = y
y = __tmp_0
The generated name __tmp_0 won't collide with user variables.