v2.5.0#

Upgrading from v2.4.1: what breaks, how to fix it, and what to try.

Dang 2.5 is a new language version, and it changes how strings are written. The delimiter now decides how a string's contents are read: double quotes process escapes and interpolate ${...}, the new single quotes are verbatim, and backticks stay raw text with ${...} for code. Quotes are for text and backticks are for code. Code written for 2.4 can change meaning under 2.5, so dang migrate rewrites it, keeping every string's value. At every version, interfaces declared in Dang are now structural: any type with an interface's fields is a value of it, whichever schema it comes from, so any value with a message: String! can be raised. A declaration may now also take a snapshot of a binding that top-level statements write, errors for habits from other languages come with a hint, Dagger modules run faster, and Dang no longer needs cgo.

Upgrade checklist#

For a typical project, in order.

  1. Find out which language version your project gets (table below). A dang.toml without a dang = "…" key, or no dang.toml at all, now means 2.5.

  2. Migrate, or pin. Preview with dang migrate, then write with -w. A project with no dang key that was written for 2.4 needs --from 2.4, because Dang can't tell. To stay on 2.4 for now, write dang = "2.4" in dang.toml; single-quoted strings still work there.

    dang migrate                    # preview what would change
    dang migrate -w                 # rewrite .dang files, bump dang.toml to "2.5"
    dang migrate -w --from 2.4 .    # for projects that never declared a version
    
  3. Check goldens of printed collections. The REPL, toString and print now quote a string holding ${ with the $ escaped, at every version (details).

  4. Run it. A case or rescue arm that follows an arm on a Dang interface may now be unreachable, because the interface's arm takes every type of its shape; put the specific arms first (details).

Which language version you get#

Your project Read as "${x}" and """..."""
dang.toml with dang = "2.4" (or older) 2.4 literal ${; """ is raw
dang.toml without a dang key 2.5 changed: was 2.4 escapes and interpolation
no dang.toml (a lone script) 2.5 escapes and interpolation
new project from dang init 2.5, written as dang = "2.5" escapes and interpolation

Run without --from, dang migrate lists every project that declares no version and suggests --from, as in 2.4.

Dagger modules are the exception: Dagger's Dang SDK picks the version for a module whose dang.toml declares none, from its engineVersion (as in 2.4). Such a module moves to 2.5 only once its engine embeds Dang 2.5. Until then, don't migrate it: a dang = "2.5" is newer than its engine's Dang, which is an error.

What breaks, and how to fix it#

In order of how likely each is to hit existing code. Unless marked, examples were run with Dang 2.5 and the output is quoted as printed.

"..." interpolates ${...} 2.5 only#

At 2.4, a double-quoted string took ${ as text. At 2.5 it starts an interpolation, as in a backtick template. Only ${ does, never a bare $name, and \$ escapes a dollar sign.

Before2.4
let path = "${GOBIN}:${PATH}"
let note = "it's ${HOME}\n"
Afterdang migrate -w
let path = '${GOBIN}:${PATH}'
let note = "it's \${HOME}\n"
The 2.4 spelling under 2.5
Error: "HOME" not found; to write ${HOME} as text, single-quote the string or escape it as \${HOME}
  --> /tmp/script.dang:1:10
     |
   1 | print("${HOME}")
                ^^^^

A name that happens to be in scope interpolates without an error, so read the migration's diff rather than relying on the compiler.

Fix

dang migrate -w turns a "..." holding ${ into a single-quoted string where it can, and escapes the $ where it can't (a string holding a ' or an escape). Shell-ish text like .withEnvVariable("PATH", '${GOBIN}:${PATH}', expand: true) reads best in single quotes.

""" processes escapes and interpolates 2.5 only#

At 2.4, a """ string was raw: no escapes, no interpolation. At 2.5 it follows the same rules as "...", so a backslash in it is an escape, and an unknown one is a syntax error. A \n or \t would silently become a newline or a tab.

Before2.4
let pattern = """\d+\.\d+"""
let script = """
  echo "${HOME}" \
    done
"""
Afterdang migrate -w
let pattern = '''\d+\.\d+'''
let script = '''
  echo "${HOME}" \
    done
'''
Fix

dang migrate -w turns a """ string holding \ or ${ into ''', which is verbatim in every version. Where ''' can't hold the text (it would end the string early), it keeps """ and escapes the backslashes and dollar signs instead. A """ with neither is left alone: it means the same thing at both versions.

A multi-line string's opening line holds at most a language tag 2.5 only#

At 2.4, text could follow the opening """ or ``` and start the value. At 2.5 the opening line of any multi-line string holds at most a language tag ("""sql, '''sh, ```go). Anything else there is an error, unless the string closes on the same line ("""inline"""):

Text on the opening line under 2.5
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)
  --> /tmp/script.dang:1:7
     |
   1 | print("""Summary.
             ^^^^^^^^^^^
   2 | more
   3 | """)

A single word there is a tag, not text: at 2.4, """sql followed by select on the next line was "sql\nselect", and at 2.5 it is "select", tagged sql.

Fix

dang migrate -w moves text on an opening line to the next line, so """sql + select becomes a """ whose first line is sql. Docstrings are not affected: they may still start on the opening line, and stay verbatim.

Quoted strings escape ${ when printed every version#

The REPL, toString, print and interpolation quote the strings inside a collection as the Dang literal you'd write. Now that "${ interpolates, they escape it, so the output reads back as the same value. A string printed on its own is still its bare text.

Program
print(toString(['${HOME}']))
print('${HOME}')
Output
["\${HOME}"]
${HOME}
FixUpdate goldens that quote such strings.

Type patterns on Dang interfaces match by shape every version#

Interfaces declared in Dang are now structural (below), at every language version, since every version runs on the same interpreter. Most code that compiled still compiles and means the same: values that used to be refused now pass. Two kinds of case and rescue can change:

Fix

Put the arms for specific types first. Where an arm on an interface must not take a type of its shape, match that type before it.

What's new and worth trying#

Structural interfaces, across schemas new#

An interface declared in Dang is satisfied by any type with its fields, public and of fitting types, whether or not the type says implements, and whichever schema it comes from. Interfaces a GraphQL schema declares stay nominal. The prelude's Error is one, so any type with a message: String! can be raised, a schema's own error type included: in a Dagger module, a Dagger.Error raises and rescues as an Error, and the host gets the very object raised, values and all. See Structural: interfaces across schemas.

Program
interface Named {
  name: String!
}

type Person {
  name: String!
}

type Oops {
  message: String!
  code: Int!
}

greet(n: Named!): String! { `hello, ${n.name}` }

print(greet(Person("Ada")))
print({ raise Oops("boom", 7) } rescue {
  e: Error! => e.message
})
Output
hello, Ada
boom

A rescued error raised again as it was keeps the error it was made of (RaisedError.Origin), so a host can report it as it would have had nothing rescued it: the GraphQL error behind a GraphQLError, extensions and all.

Verbatim strings: '...' and '''...''' new#

Single-quoted strings keep their text exactly as written: no escapes, no interpolation. A ' would end '...', so text holding one goes in '''...''', which can hold quotes even on one line ('''it's'''). The multi-line ''' form dedents and takes a language tag like the others, which suits shell scripts. Both work at every language version, 2.4 pins included.

Program
print('C:\Users\${USER}')
print('''sh
  for f in *.txt; do
    echo "${f%.txt}" \
      >> list
  done
''')
Output
C:\Users\${USER}
for f in *.txt; do
  echo "${f%.txt}" \
    >> list
done

""" strings interpolate and take a language tag 2.5 only#

A """ string dedents first and decodes its escapes after, so \t at the start of a line is text, not indentation. The language tag tells editors how to highlight the contents; it doesn't change the value.

Program
let table = "users"
let limit = 10
print("""sql
  select name
  from ${table}
  limit ${limit}
""")
print("""
  \tindented with a tab
  costs \$5, not \${limit}
""")
Output
select name
from users
limit 10
	indented with a tab
costs $5, not ${limit}

The full rules, side by side, are in Literals.

Declarations can snapshot statement-written state every version#

2.4 rejected every read, from a declaration's initializer, of a binding that top-level statements write. A declaration that reads it before every write now works, and sees the value from before the writes, as its place in the source says. The read must be written directly in the initializer (not in a block argument, a {{ }} field or a function) and every write must be in the same file.

Program
let count = 1
let first = count
count += 1
count += 1
print([first, count])
Output
[1, 3]

A read after a write would be misleading, so it is still an error, as is any read from a function:

Read after a write
Error: `latest`'s initializer reads `total`, which a top-level statement writes (line 2), but top-level declarations run before top-level statements, so it would see the value from before the write; read `total` in a top-level statement instead, or compute it in a declaration rather than writing it from statements
  --> /tmp/script.dang:3:14
     |
   1 | let total = 1
   2 | total += 1
   3 | let latest = total
                    ^^^^^

The rules are in Functions return, they don't write.

Hints for common mistakes every version#

Some errors come from habits other languages teach. Dang now recognizes a few of them precisely and adds a one-line hint and a link to the docs, in the CLI, the LSP, the REPL and the playground: // comments, && and ||, for and while loops, {a: 1} records, and non-Boolean conditions. Look-alike code that isn't the mistake, like n // 2 written by a Python habit, is left alone.

Program
let a = true
let b = false
print(a && b)
Output
Error: syntax error: `&&` is not an operator
  --> /tmp/script.dang:3:9
     |
   1 | let a = true
   2 | let b = false
   3 | print(a && b)
               ^^
     |
     = hint: the logical operators are the keywords `and` and `or` (and `!` to negate)
     = docs: https://danglang.org/operators#logical
No truthiness
Error: condition must be Boolean!, got Int!
  --> /tmp/script.dang:2:5
     |
   1 | let n = 3
   2 | if (n) { print("yes") }
           ^
     |
     = hint: there is no truthiness: test explicitly, e.g. `x != null` or `!xs.isEmpty`
     = docs: https://danglang.org/control-flow#if-else

Smaller changes#

Go embedders Go API#

Removed or changed Use instead
dang.CurrentVersion is now dang.Version2_5 dang.Version2_4 where you mean a fixed version; ContextWithVersion to pin a module, unchanged
Every "..." literal parses to a *dang.String At 2.5, one that interpolates is a *dang.Template with Quote == '"'. *dang.String gains Quote, Verbatim and Lang, which record spelling only
Tree-sitter through cgo and github.com/tree-sitter/go-tree-sitter Nothing: tree-sitter now runs as WebAssembly, under wazero

No more cgo. Dang's tree-sitter is compiled to WebAssembly (pkg/dang/tswasm), so completion, the LSP, analysis.Complete, REPL highlighting and precise parse errors all work in CGO_ENABLED=0 builds, the Dagger engine's included. The first use compiles the module, about 50 ms, and caches it (about 800 KB, under the user cache directory's dang/wazero), so later processes take about 2 ms. Call dang.LoadTreeSitter() to compile it ahead of the first request, as the LSP does on initialize. Completion now reparses an edited document incrementally, so it is faster than before on large files.

New: analysis.Options{DiagnosticContext: true} fills Diagnostic.Context for type errors about a name: the closest names by spelling, the receiver's members, and docs that mention it. It is off by default and costs nothing when off. analysis.Render and Diagnostic.Format print diagnostics with that context:

main.dang:2:1: error: list does not have method "findFirst"
  closest: find { item: a => Boolean! }: a?  returns the first element for which the predicate returns true, or null if none…
  [String!]! has 25 members: all any contains dropFirst dropLast dropWhile each filter find flatMap
    indexOf isEmpty join length map reduce reject reverse sort sortBy sum takeFirst takeLast
    takeWhile uniq
Quoted from #298's description; no CLI prints this yet.

Module.Eval and Session snippets accept declaration snapshots too, and give the same values a script would.

A rescued error raised again unchanged keeps the Go error it was classified from, as RaisedError.Origin(), so a host can report, say, the GraphQL error behind a GraphQLError with its extensions. It is deliberately not Unwrap, which would let errors.As find the original failure's source location instead of the raise site.

Sources and verification#

Sources. The vito/dang pull requests merged between v2.4.1 (247f410) and 2918064: #300 (strings and the Version2_5 gate), #306 (structural interfaces and raising), #302 (hints for common mistakes), #301 (declaration snapshots), #308 (receivers running ahead), #309 (checker diagnostics), #307 and #314 (tree-sitter as WebAssembly) and #298 (diagnostic context).

Verification. Every program and output not otherwise marked was run with dang built at 2918064, with no dang.toml (so language 2.5). The 2.4 behaviour and the before/after migrations are the cases TestVersionQuotes (pkg/dang/version_test.go) pins, since run can't select 2.4 without a dang.toml. The GraphQL object list hint is quoted from the select_on_graphql_object_list golden, and the Dagger timing and wasm costs from #308's and #307's descriptions.