Schooner.Pretty (schooner v1.2.0)

Copy Markdown View Source

Pretty-printing for Scheme data and code, such as the forms returned by Schooner.expand/3.

A form that fits on one line is printed on one line. A longer one is broken across lines and indented the way Scheme code usually is: the body of a lambda, define, let and the other binding and body forms is indented by two spaces, and the arguments of other calls are lined up under the first.

iex> form = Schooner.Value.list([
...>   {:sym, "define"},
...>   Schooner.Value.list([{:sym, "area"}, {:sym, "r"}]),
...>   Schooner.Value.list([{:sym, "*"}, {:sym, "pi"}, {:sym, "r"}, {:sym, "r"}])
...> ])
iex> Schooner.Pretty.format(form)
"(define (area r) (* pi r r))"
iex> Schooner.Pretty.format(form, width: 20)
"(define (area r)\n  (* pi r r))"

(quote x), (quasiquote x), (unquote x) and (unquote-splicing x) are printed as 'x, `x, ,x and ,@x. Everything else that has a written form is printed as Schooner.Value.write/1 would print it, so reading the output back gives a datum equal? to the one printed, unless it contains renamed identifiers (below).

Renamed identifiers

An identifier that a macro introduces is renamed during expansion, so it can't capture, or be captured by, an identifier of the same name in the code that uses the macro. By default it is printed as its name and a number, joined by a middle dot (tmp·1), so it can be told apart from the code's own tmp. With names: :plain it is printed as its name alone (tmp).

A renamed identifier has no written form, so neither way of printing it reads back as the same identifier: tmp·1 reads as an ordinary symbol with that name, which a symbol of the code's own could share, and tmp reads as the code's tmp. The output is for people to read. Don't read it back as code, because a macro's identifier could then capture, or be captured by, the code's own.

Summary

Functions

Format value as text.

Functions

format(value, opts \\ [])

@spec format(
  Schooner.Value.t(),
  keyword()
) :: binary()

Format value as text.

Options:

  • :width — the line width to fit forms in, a positive integer. A form that can't fit, such as a long symbol, is printed anyway. Defaults to 80.
  • :names — how to print identifiers renamed by macro expansion: :marked (the default) adds their number (tmp·1), and :plain prints the name alone (tmp).

Values with no written form, such as procedures and the record type in an expanded define-record-type, are printed as #<...>.