v2.4.1#

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

Dang 2.4 is a new language version. Only one rule is tied to it: type patterns in case and rescue take a !, and dang migrate adds it for you. A few output changes apply to every project, whatever version it pins: values print as Dang literals instead of JSON, GraphQL objects print as their query, and the encoders keep field order. The type checker also closes every known soundness hole: a value now always has the type the checker gave it, so code that broke that is a compile error at the cause (details and the full write-up). In return you get a Decoded type for data of unknown shape, strict decoding, case as a real type switch, and Ordered/Numeric bounds with sort and sum.

Upgrade checklist#

For a typical project, in order. Steps 1–2 handle the only syntax change; steps 3–5 catch output that changed under you.

  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.4.

  2. Migrate, or pin. Preview with dang migrate, then write with -w. A project with no dang key that was written for 2.1 needs --from 2.1, because Dang can't tell. To stay on 2.1 for now, write dang = "2.1" in dang.toml; everything in What's new still works there.

    dang migrate                    # preview what would change
    dang migrate -w                 # rewrite .dang files, bump dang.toml to "2.4"
    dang migrate -w --from 2.1 .    # for projects that never declared a version
    
  3. Find JSON built with toString, join or ${…} and call JSON.encode instead (details).

  4. Find GraphQL object IDs read through toString or interpolation and select .id (details).

  5. Check goldens of JSON.encode / YAML.encode output. Keys now come out in declaration order; pass sortKeys: true for the old sorted order (details).

  6. Run it. A few stricter checks now fail at compile time with a message naming the fix (list), and the type checker no longer accepts programs whose values don't match their types at runtime (type soundness).

Which language version you get#

Dang reads each project at the version its dang.toml declares. What changed is the undeclared case: it used to stay at 2.1 forever, and now it follows the Dang you run.

Your project Read as Bare patterns (c: Cat =>)
dang.toml with dang = "2.1" 2.1 still accepted
dang.toml without a dang key 2.4 changed: was 2.1 compile error with the fix
no dang.toml (a lone script) 2.4 compile error with the fix
new project from dang init 2.4, written as dang = "2.4" compile error with the fix

Run without --from, dang migrate lists every project that declares no version, reports it as read in Dang 2.4, and suggests --from. With --from, the version applies to every undeclared project under the directories you pass, nested ones included, so pass only the directories written for that version.

Two kinds of change in these notes ignore the pin, because they change output or close holes rather than syntax. They are marked every version. The one change gated on 2.4 is marked 2.4 only. Everything new works at 2.1 as well.

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.4 and the output is quoted as printed.

Type patterns are written T! 2.4 only#

A case, rescue or decoded-data arm binds a value that is never null, so the pattern now says so. At 2.1 the bare form still works and means the same thing.

Beforev2.3 / pinned 2.1
print(case (p) {
  c: Cat => "cat " + c.name
  d: Dog => "dog " + d.name
})

let msg = { raise "boom" } rescue {
  e: Error => "caught: " + e.message
}
After2.4
print(case (p) {
  c: Cat! => "cat " + c.name
  d: Dog! => "dog " + d.name
})

let msg = { raise "boom" } rescue {
  e: Error! => "caught: " + e.message
}
The bare form under 2.4
Error: a type pattern is the non-null type its arm binds: write `c: Cat! =>`
  --> /tmp/script.dang:10:6
     |
   8 | let p: Pet! = Cat
   9 | print(case (p) {
  10 |   c: Cat => "cat " + c.name
            ^^^
  11 |   d: Dog => "dog " + d.name
  12 | })
Fix

dang migrate -w adds the ! to every pattern that lacks it, list and map patterns included (xs: [Decoded!] => becomes xs: [Decoded!]! =>), turns any leftover try { } catch { } into postfix rescue, and bumps dang.toml to "2.4". dang fmt -w adds the ! too. Or pin dang = "2.1".

The before/after pair is the shape of the migration fixture tests/testdata/migrations/2.1-to-2.4; 2.1 can't be selected without a dang.toml, so the bare form was run only under 2.4.

Values print as Dang literals, not JSON every version#

toString, ${…} interpolation, List.join, print and the REPL share one rendering: the Dang literal you would write. Strings, enum values and custom scalars still print as their bare text.

Expression v2.3 (from #284) v2.4
toString([1, 2]) [1,2] [1, 2]
toString({{a: 1}}) {"a":1} {{a: 1}}
`${["a"]}` [a] ["a"]
print(User(name: "alice")) module User {{name: "alice"}}
More of the new form
type User {
  name: String!
  let secret = 42
}
enum Color { RED GREEN }

print(`tags: ${["a", "b"]}`)
print(["k": 1.0])
print(User(name: "alice"))
print([Color.RED, Color.GREEN])
print(JSON.encode({{a: 1, b: "x"}}))
Output
tags: ["a", "b"]
["k": 1.0]
{{name: "alice"}}
[Color.RED, Color.GREEN]
{"a":1,"b":"x"}

Objects show their public fields only (the private let secret is left out), floats always keep a fraction, and an enum inside a collection reads back as Color.RED.

FixWhere you meant JSON, say so: JSON.encode(x).

GraphQL objects print as their query, not their ID every version#

Showing a GraphQL object (a Dagger Container, say) used to fetch and print its ID. It now prints the lazy query it is, with argument names but never their values, and sends nothing to the server.

# from tests/test_graphql_object_tostring.dang
assert { toString(primaryUser) == "<User: primaryUser>" }
assert { `${primaryUser}` == "<User: primaryUser>" }
assert { toString(Mutation.touchNode(id: "Post:1")) == "<Node: mutation.touchNode(id: …)>" }

# Code that wants the ID selects it.
assert { toString(primaryUser.id) == "User:1" }

In a Dagger module, print(ctr) shows something like <Container: container.from(address: …).withEnv(name: …, value: …)> (from #289).

FixSelect .id wherever you relied on the ID.
Needs a GraphQL schema, so quoted from the test suite rather than run here.

Encoders keep field order every version#

JSON.encode and YAML.encode used to sort every object's keys. They now write a type's fields in declaration order, a record's as written, and a map's in insertion order.

Program
type Module {
  name: String!
  source: String!
  deps: [String!]! = []
}
let m = Module(name: "web", source: "./web")
print(JSON.encode(m))
print(JSON.encode(m, sortKeys: true))
print(YAML.encode({{name: "x", count: 1}}))
Output
{"name":"web","source":"./web","deps":[]}
{"deps":[],"name":"web","source":"./web"}
name: x
count: 1
Fix

Pass sortKeys: true to either encoder for the old order, or update your goldens.

Stricter checks every version#

Each of these used to type-check and then fail at runtime, return a wrong answer, or reach something it shouldn't. Each is now a compile error at the cause. Messages are as printed by Dang 2.4.

You wrote You now see Fix
let n: Int! = counts.get("a") cannot use Int as Int! — Map.get is nullable, like m["a"] counts.get("a") ?? 0
JSON.decode("1") :: Random! cannot decode into Random: it has no constructor decode into Decoded! or a real type
"{" :: JSON! invalid JSON: unexpected EOF — string literals cast to JSON!, YAML!, TOML! are validated fix the literal; computed strings raise at runtime instead
status == "PASSD" on an enum "PASSD" is not a value of Status; expected one of PASSED, FAILED — also in case patterns, and for Regexp literals fix the typo
scalar JSON then JSON.encode(…) field "encode" not found in JSON; the JSON declared here shadows the builtin JSON, which has it; rename the declaration to use the builtin rename your scalar
import Lib then Lib.toString(1) field "toString" not found in Lib — an import exposes only its own pub declarations (golden import_dang_qualified_builtin) call builtins unqualified
an interface member f(x: Int!, y: String!): Int! implemented as f(x: c!, y: c!): c! { y } field "f", argument "y": type c! (here Int!) doesn't fit interface type String! — this returned a String as Int! match the interface's types

The type-soundness fixes are a larger set of stricter checks; they have their own section.

One runtime change: decoding an explicit null into a non-null field with a default now takes the default ({"retries": null} into retries: Int! = 3 gives 3), where it used to leave null in an Int!.

Type soundness every version#

Every known case of a value not matching the type the checker gave it is now caught at compile time.

A type checker is sound when the type it gives a value is the type the value has at runtime: a T! is never null, an Int! is never a String. Before 2.4, Dang's checker accepted dozens of programs that broke this. Some were caught later by a runtime check, others failed somewhere unrelated, gave a wrong answer, or panicked the interpreter. A sweep across generics, nulls, builtins, subtyping and control flow (#219–#249) fixed every case it found. Each one is now a compile error at the cause, or runs and gives the right answer. A few valid programs that the old checker rejected now compile.

Closing soundness holes in Dang's type checker

The full write-up: a before/after gallery of every case, how each area was fixed, the decisions made along the way, and the measured breaking-change risk.

Read the full write-up

The changes most likely to reach existing code are listed below. The write-up's search of about 455 .dang files across 60 repositories found confirmed breaks in only two of them. Messages are as printed by Dang 2.4.

You wrote You now see Fix
In a function body: let xs = [], then xs += ["a"], then let n: Int! = xs[0]! cannot use String! as Int! at xs[0]!. A binding that starts open ([], null) keeps the first type a use pins it to (here String!); it used to accept any type at every use use one element type, or annotate let xs: [Int!]! = []
first[a](xs: [a]!): a { xs[0] } cannot use a possibly-null value as a: callers may pick a non-null type for a; assert it with `xs[0]!`, …. A type variable a may stand for a non-null type xs[0]!, ?? other, or a null check
let p: Int = null then p + 1 operator addition is not defined for nullable type Int: check it for null first, supply a default with ??, or assert it with ! p! + 1 or (p ?? 0) + 1
c == s with c: Color!, s: String! cannot compare Color! with String!: they are unrelated types; compare with a Color value, like Color.RED, or cast the string: (s :: Color!). This was always false; a string literal still converts c == Color.GREEN or (s :: Color!)
o.maybe.x = 4 with maybe: Inner cannot assign to o.maybe.x: o.maybe may be null; assert it with ! to raise if it is (`o.maybe!.x = ...`), or check it for null first o.maybe!.x = 4
A script's helper report reading total, which a top-level statement updates `report` reads `total`, which a top-level statement writes (line 3), but functions may be called while top-level declarations are initialized, before any statement, so it could see the value from before the write; pass `total` as an argument instead pass the value as an argument

Null checks now also stop applying once something could set the name back to null, such as a reassignment, a closure or a loop. A case that covers every value of an enum or Boolean is non-null without an else. Strings gain .length and .isEmpty, counting Unicode code points. Parser errors that used to panic are now reported. The write-up covers all of it.

Dagger module authors#

Dagger's Dang SDK embeds Dang and picks the language version for you. These rules apply to Dagger engines that embed Dang 2.4, starting with v1.0.0-beta.28 (introduced by dagger/dagger#15128).

Module's engineVersion Dang version when dang.toml declares none
below v0.21.5 1.0 (unchanged)
v0.21.5 up to, not including, v1.0.0-beta.28 2.1: what these modules always got
v1.0.0-beta.28 and later 2.4
SDK-generated entrypoints 2.1 (they pin dang = "2.1")

What's new and worth trying#

All of it is available at every language version, 2.1 pins included. Every example below was run with Dang 2.4.

Data you haven't typed yet: Decoded new#

Decoded is the type of decoded data whose shape you haven't fixed. Cast it one level at a time. It compares as data, so key order, number spelling and the source format don't matter, and a Decoded! field encodes back exactly as it came in.

Program
let text = """{"modules": [{"name": "a", "pin": {"rev": 3}}]}"""
let config = JSON.decode(text) :: Map[Decoded!]!
let modules = config["modules"]! :: [Map[Decoded!]!]!
let pin = modules[0]!["pin"]! :: Map[Int!]!
print(pin["rev"])
print(config)

let a = JSON.decode("{\"b\": 1.50, \"a\": [1]}") :: Decoded!
let b = YAML.decode("a: [1]\nb: 1.5") :: Decoded!
print(a == b)
Output
3
["modules": [["name": "a", "pin": ["rev": 3]]]]
true
Strict decoding new

strict: true rejects unknown and duplicate keys, all reported at once with their paths.

# text: "- name: a\n  nmae: b\n  source:\n    url: x\n    tomlTabel: y"
YAML.decode(text, strict: true) :: [Module!]!
[0]: field nmae not found
[0].source: field tomlTabel not found

Without strict, the typos are silently dropped.

Map[T] targets and YAML merge keys

Decode straight into a map of a type; <<: *anchor merges, with the mapping's own keys winning.

type Service {
  image: String!
  port: Int! = 80
}
let text = "base: &base\n  image: nginx\nweb:\n  <<: *base\n  port: 8080"
let svcs = YAML.decode(text) :: Map[Service!]!
print(svcs["web"])
{{image: "nginx", port: 8080}}

The encoders also take indent:, escapeHTML: and sortKeys:, matching Go's MarshalIndent and SetEscapeHTML. TOML.decode accepts nan and inf.

JSON!, YAML!, TOML! hold checked text new#

The same names are both the codec (JSON.encode, JSON.decode) and a scalar type of text in that format. The text is checked when a value is created: a bad literal is a compile error (see above), a bad computed string raises. For nested data, use Decoded!: a JSON! holds text, so Map[JSON!]! fails on {"a": [1, 2]} with ["a"]: expected string for scalar JSON, got array.

Program
let j = "{\"a\": [1, 2]}" :: JSON!
print(JSON.decode(j) :: Map[[Int!]!]!)
print(JSON.encode({{n: 1}}) :: JSON!)

parse(s: String!): String! {
  ((s :: JSON!) :: String!) rescue {
    e: Error! => e.message
  }
}
print(parse("[1, 2]"))
print(parse("{"))

let stream = "a: 1\n---\nb: 2\n" :: YAML!
Output
["a": [1, 2]]
{"n":1}
[1, 2]
invalid JSON: unexpected EOF

A multi-document stream is valid YAML!, but YAML.decode reads one document and says so: YAML.decode: the text holds more than one document, but only a single document decodes. Empty trailing documents are ignored, so a manifest ending in --- decodes.

Every custom scalar is text underneath, so an explicit :: cast converts one to another, through !, list and map wrappers. The target checks the text, as it does a String's. Passing one scalar where another is expected is still an error; only the cast converts. This is how a Dagger module moves between Dang's JSON! and the schema's Dagger.JSON! (below).

Program
scalar Blob
let b = "x" :: Blob!
print((b :: JSON!) rescue { e: Error! => e.message })
let ok = "[1]" :: Blob!
print(ok :: JSON!)
let j = "{}" :: JSON!
print(j :: Blob!)
Output
invalid JSON: invalid character 'x' looking for beginning of value
[1]
{}

case is a type switch new#

Any type can be a pattern: named types, lists, maps, records, and decoded data, which matches by shape. Coverage is checked, so an inline union of list types needs no else, and a pattern that can never match is a compile error.

Program
describe(d: Decoded!): String! {
  case (d) {
    n: Int! => `the number ${n}`
    items: [Decoded!]! => `${items.length} items`
    fields: Map[Decoded!]! => `fields ${fields.keys.join(", ")}`
    else => "something else"
  }
}
print(describe(JSON.decode("42")))
print(describe(JSON.decode("[1, 2, 3]")))
print(describe(YAML.decode("b: 1\na: 2")))

kinds(ints: Boolean!): String! {
  let xs = if (ints) { [1, 2] } else { ["a"] }
  case (xs) {          # no else needed
    is: [Int!]! => `ints ${is.length}`
    ss: [String!]! => `strings ${ss.join(",")}`
  }
}
print(kinds(false))

print(case ({{name: "a", n: 1}}) {
  r: {{name: String!, n: Int!}}! => `record ${r.name}`
})
Output
the number 42
3 items
fields a, b
strings a
record a
A pattern that can't match
let n = 1
print(case (n) {
  s: String! => s
  else => "not a string"
})

Error: pattern String! can't match a value of type Int!

A case on decoded data needs an else. Lists match by the element type they were built with: a list annotated [Animal!]! doesn't match [Cat!]! even if it holds only cats.

Bounded generics, sort and sum new#

A type variable can declare what it supports: Ordered for comparison, Numeric for arithmetic (exactly Int! and Float!), or both with &. Interface members take type parameters too. Lists gain stable sort and sortBy (enums sort in declaration order, records field by field) and sum.

Program
mySum[a: Numeric](xs: [a!]!, zero: a!): a! {
  xs.reduce(zero) { acc, x => acc + x }
}
abs[a: Ordered & Numeric](x: a!): a! {
  if (x < 0) { -x } else { x }
}
print(mySum([0.5, 0.25], 0.0))
print(abs(-4))
print([3, 1, 2].sort(descending: true))
print([1.5, 2.0].sum)

enum Role { ADMIN USER GUEST }
let entries = [
  {{role: Role.GUEST, uri: "b"}},
  {{role: Role.ADMIN, uri: "z"}},
  {{role: Role.GUEST, uri: "a"}},
]
print(entries.sortBy { e => {{role: e.role, uri: e.uri}} }
  .map { e => e.uri })
Output
0.75
4
[3, 2, 1]
3.5
["z", "a", "b"]
Forgot the bound?
twice(x: a!): a! { x + x }

Error: operator addition is not defined for the generic type a: a type variable supports no operations; declare it `[a: Numeric]` to use it
interface Ranker {
  best[a: Ordered](x: a!, y: a!): a!
}
type ByMax implements Ranker {
  pub best[a: Ordered](x: a!, y: a!): a! { if (x > y) { x } else { y } }
}
let r: Ranker! = ByMax
print(r.best(3, 7))      # 7
print(r.best("a", "b"))  # b

Smaller additions new#

let roles = ["admin", "user"]
print(roles.indexOf("user"))
print(roles.indexOf("guest") ?? -1)
print([[1, 2], [3]].flatMap { xs => xs })
print("ff".toInt(base: 16))
print("42".toInt)
print("0x10".toInt(base: 16) rescue {
  e: Error! => e.message
})
1
-1
[1, 2, 3]
255
42
toInt: "0x10" is not a base-16 integer

Go embedders Go API#

Removed or changed Use instead
dang.DefaultVersion, ProjectConfig.EffectiveVersion dang.Version2_1 (or your own constant) where you mean a fixed version; ContextWithVersion to pin a module, unchanged
DeclareDir's scope binding every file's imports Imports are file-local. Evaluate declaration-time arguments (e.g. interface directive args) in dang.DeclarationScope(env, name)
JSON, YAML, TOML, Random, UUID in Module.TypeEnv/ValueEnv and RunDir's scope They are per-file builtin imports now, absent from those scopes

New: evaluation stops when its context is cancelled (a *CancelledError that rescue can't catch); LoadDir → Module → Session → Snippet for checking and running snippets inside a module; Describe for capped TYPE = VALUE rendering; PrepareDir to check once and evaluate many times; and pkg/dang/analysis, a transport-free language service the LSP now runs on.

Sources and verification#

Sources. The vito/dang pull requests merged between v2.3.0 (3ee188d) and v2.4.1 (247f410), chiefly #286 (T! patterns, type switch), #287 (undeclared means current), #284 and #289 (display), #255/#283 (encoding order), #277/#281 (Decoded), #254 (strict decoding), #272/#274/#290/#293 (bounds), #258/#263 (stdlib), #291/#292 (imports), #219–#249 (type soundness), #295 (codec scalar types); and dagger/dagger#15128 for the Dagger version rules.

Verification. Every program and output not otherwise marked was run with dang built at v2.4.1 (247f410), with no dang.toml (so language 2.4). GraphQL display is quoted from tests/test_graphql_object_tostring.dang, the Dagger.JSON casts from pkg/dang/builtin_codec_scalars_test.go, the Lib.toString error from the import_dang_qualified_builtin golden, and v2.3 output from #284's description.