Skip to content

Parsing

Jude Payne edited this page Sep 7, 2024 · 9 revisions

The dictim.parse namespace exposes one public function dictim for converting a d2 string to dictim syntax.

user> (use 'dictim.parse)
nil
user> (dictim "gerbil \nhamster: Hamster {shape: person}")
(["gerbil"] ["hamster" "Hamster" {"shape" "person"}])

The dictim function can take optional keyword arguments for key-fn, label-fn to convert keys and labels during parsing. Each of those functions should be a function of one argument. dicitm can also take keyword arguments for flatten-lists? (true/ false) and show-empty-lines? (true/ false).

flatten-lists?

As per the Syntax page, multiple d2 elements are allowed on one line when separated with a ;. This is a [:list ...] dictim element.

When flatten-lists? is true, a line in d2 like a; b; c with shapes that are all only denoted by their keys is parsed to [:list "a" "b" "c"] rather than [:list ["a"] ["b"] ["c"]].

Internally, in the codebase, these are called quickshapes. It's a less clunky representation where possible. The use in d2 of a list like this is to specify the ordering of actors in a sequence diagram.

show-empty-lines?

When retain-empty-lines? is true, empty lines/ line breaks in the d2 are captured in an [:empty-lines <n>] dictim vector, where <n> is the nmber of empty lines in a row at that point of the d2.

Example of using keyword arguments

Use of the key-fn optional keyword argument:

user> (dictim
        "ctr: Container {
	gerbil: ;hamster: Hamster {shape: person;};a->b: {link: 23}};"
	:key-fn keyword)
([:ctr
  "Container"
  [:gerbil]
  [:hamster "Hamster" {:shape "person"}]
  [:a "->" :b {:link "23"}]])

The syntax of d2 is quite minimal. For example the parser can only tell the difference between shapes and attribute maps by knowing all of the d2 reserved keywords, so again it is worth noting that shapes, connections and containers should nver use keys which are d2 reserved keywords as detailed on the Dictim Syntax wiki page.

Each element in d2 must be separated by a valid separator character, either ; or \n, but note that if multiple elements on a line of d2 are separated by a ;, dictim assumes that is meaningful and gathers them in a :list (see Dictim syntax page).

Clone this wiki locally