Syntax and literals#

Meta: this page is the boring foundation. Focus on what would surprise someone coming from JS/Go/Python (semicolons-optional, newline-as-separator, # not //, no trailing commas in formatted output). Grammar rules live in Grammar notes.

The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.

File layout#

let width = 3; let height = 4
area: Int! { width * height }

area
=> 12

Comments#

# starts a comment that runs to the end of the line; // is not a comment. Comments can sit on their own line or trail code, and the formatter keeps them next to the code they're attached to:

# the number of retries before giving up
let retries = 3   # trailing comments are fine too

retries
=> 3

Meta: /// doc comments don't exist — docstrings are real triple-quoted strings attached to declarations (covered in Fields and Functions).

Identifiers#

Reserved words#

Separators and trailing commas#

Forms in blocks and at the top level are separated by newlines or ;. Inside lists, argument lists, and record literals, newlines and commas are interchangeable. The formatter strips trailing commas.

[
  "one"
  "two",
  "three",
]
=> ["one", "two", "three"]

Literals#

Meta: one short subsection per literal kind, with one example each. The three string flavors sit side-by-side so the differences are obvious.

Numbers#

Int! literals are decimal, signed 64-bit. A Float! literal has a fraction (a digit on both sides of the .), an exponent (e or E, with an optional sign), or both:

[3.14, 1e5, 2.5e-3]
=> [3.14, 100000.0, 0.0025]

There are no hex, octal, or binary literals:

0x1F
Parse error: syntax error: unexpected '0'

Booleans and null#

true and false are Boolean!. null fits only a nullable type (see Types and nullability):

let ready = true
let nickname: String = null

[ready, nickname == null]
=> [true, true]

String literals#

See Strings for the full method reference.

The delimiter decides how a string's contents are read, and tripling it makes the string multi-line:

Delimiter Single-line Multi-line, dedented, optional language tag
" escapes and ${...} """: escapes and ${...}
' verbatim ''': verbatim
` raw, with ${...} ```: raw, with ${...}

The rule of thumb: quotes are for text and backticks are for code. Double quotes interpolate; single quotes don't.

Double-quoted strings process escapes: \a \b \f \n \r \t \v \" \\ \/ \$, \ooo (octal), \xNN, \uNNNN, \UNNNNNNNN. Any other backslash is a syntax error. \/ is just /, as in JSON:

["tab\there, \x41, \u00e9", "https:\/\/danglang.org"]
=> ["tab\there, A, é", "https://danglang.org"]

They interpolate ${...}. Only ${ starts an interpolation, never a bare $name, and \$ is a literal dollar sign, so \${ is a literal ${:

let name = "Ada"

"hello, ${name}! that's $5, not \${name}"
=> "hello, Ada! that's $5, not \${name}"

Interpolated values are turned into text: strings as-is, null as "null", and other values as they print:

"count: ${3}, missing: ${nickname}, list: ${[1, 2]}"
=> "count: 3, missing: null, list: [1, 2]"

Single-quoted strings are verbatim: no escapes and no interpolation, so a backslash or a ${ is just text. A ' would end one, so text holding a quote goes in '''...''', which can hold quotes even on one line ('''it's'''), or in "...". They're the natural fit for shell-ish text that must keep its ${VAR}, like .withEnvVariable("PATH", '${GOBIN}:${PATH}', expand: true):

'${HOME}\bin'
=> "\${HOME}\\bin"

Triple-quoted strings, """...""" and '''...''', span lines. They follow the same rules as their single-line forms, and are dedented by their minimum indent. The newline after the opening quotes and the one before the closing quotes are dropped (so """\nhello\n""" == "hello"):

"""
  first
    indented: ${name}
  last
"""
=> "first\n indented: Ada\nlast"

A """ string is dedented before its escapes are decoded, so \t at the start of a line is text, not indentation, and an escape keeps trailing whitespace that would otherwise be easy to lose:

"""
  \tone tab
  two spaces:\x20\x20
"""
=> "\tone tab\ntwo spaces: "

A ''' string keeps everything as written, which suits shell scripts:

'''sh
  echo "${HOME}" | tr -d '\n'
'''
=> "echo \"\${HOME}\" | tr -d '\\n'"

The opening line of a multi-line string holds at most a language tag, like sh above or """sql. It doesn't change the value; editors use it to highlight the contents. Any other text there is an error, unless the string closes on the same line:

"""Summary.
more
"""
Parse error: syntax error: text on the opening line of a multi-line string: start it on the next line (only a language tag may follow the opening """, like """sh)
"""inline ${name}"""
=> "inline Ada"

Docstrings (see Comments above) are triple-quoted too, but they're always verbatim, with no escapes, interpolation or language tag, and their text may start on the opening line.

Backtick templates are for code. Backticks switch the lexer into template mode:

`# ${name} owes $5 \${not interpolated} \d+`
=> "# Ada owes $5 \${not interpolated} \\d+"
```go
  fmt.Println("hi, ${name}")
```
=> "fmt.Println(\"hi, Ada\")"

Before Dang 2.5 (a dang.toml pinning dang = "2.4" or older), "..." takes ${ literally and """...""" is raw: no escapes, no interpolation and no language tag. dang migrate moves such code to 2.5 without changing any string's value (see v2.5.0).

Lists#

[[1, 2], [3]]
=> [[1, 2], [3]]

An empty list takes its element type from context: a typed slot or argument, the other side of ?? or +, the other branch of an if, or a later use of the binding. A hint ([] :: [String!]!) is only needed when one untyped binding has to serve two element types. It can be compared directly:

let tags = []
tags += ["a"]

[tags == [], [1] == []]
=> [false, false]

Objects (record literals)#

A record literal is {{ key: value, other: value }}, and is always non-null. A bare name is shorthand for name: name, taking the value from a variable in scope. This mirrors object selection, where recv.{{ name }} is shorthand for recv.{{ name: name }} (see GraphQL interop):

let age = 36
let person = {{ name, age }}

person.name
=> "Ada"
let point: {{x: Int!, y: Int!}}! = {{y: 2, x: 1}}

[point == {{x: 1, y: 2}}, JSON.encode(point) == """{"y":2,"x":1}"""]
=> [true, true]

Fields may reference each other in any order:

{{ total: a + b, a: 1, b: 2 }}.total
=> 3

A field's own name refers to the enclosing scope, not the field being defined, so this age reads the variable from above:

{{ age: age + 1 }}.age
=> 37

A cyclic reference is a compile error:

{{ x: y, y: x }}
Type error: object literal has cyclic field dependencies: x -> y -> x

Meta: explicitly call out the double-brace syntax — it's the unusual one and the first reaction is "is that a typo?"