v2.2.0#
Upgrading from v2.1.4: what breaks, how to fix it, and what to try.
Dang always promised value semantics: a method works on its own copy of self, a block sees the variables where it was written, and nothing you hold changes under you. Before 2.2 the interpreter broke that promise in a dozen quiet ways. In 2.2 the runtime keeps it and the compiler checks it: a write that could reach past its own scope is a compile error with a message naming the fix, and several programs that compiled before now give a different, correct answer. Around that, projects can declare which Dang version they're written for, dang migrate brings Dang 1.0 and 2.0 code forward, nullable GraphQL object fields can finally be null, failed asserts show their values, and Dagger imports can pin an API version.
There is no language 2.2. v2.2.0 still implements language 2.1: dang init writes dang = "2.1", and a project declaring dang = "2.2" is refused with this project needs Dang 2.2, but this is Dang 2.1; upgrade Dang. Nothing in this release is tied to a version. The mutation rules are stricter checks, not syntax, so they apply to every project, whatever it pins.
Upgrade checklist#
For a typical 2.1 project, in order. There's no syntax to migrate; the work is in steps 1–4.
Type-check everything. Run each script and module once. The new mutation rules fail at compile time, each with a message naming the fix (the rules). The usual one: a function or method that bumps a top-level counter.
Look for code whose answer changed. Some programs still compile but now give the right answer instead of the old one: callees see a snapshot of their receiver, nested functions share the method's copy,
rescueandcasearms can update outer variables (table). Tests that pinned the old answer will fail.Re-check files
dang fmthas rewritten. It used to printname: T = { … }asname: T { … }, turning a default into a computed field (details).Scripts in a Dagger module that use Dagger: declare the import in
dang.toml. Adang.tomlno longer turns Dagger on just because adagger.jsonis nearby (details).# dang.toml dang = "2.1" [imports.Dagger] dagger = "v0.19.0" # or `true` for the old, unversioned behaviorStamp the version:
dang initwritesdang = "2.1"into yourdang.toml. A keylessdang.tomlmeans 2.1 today, but later releases read it as the running Dang, so pin it. Code from Dang 1.0 or 2.0 can declare that version and keep running, or move forward withdang migrate(details).
Mutation is checked every version#
The headline of 2.2: the stack #199 → #200 → #202 → #190. The whole model is one sentence:
A write changes only the writer's own copy of self, or a local of the scope it runs in. Never a value someone else holds.
The runtime now does exactly that (#199): receivers are snapshots taken at the call, bare and self. writes copy, and blocks, nested functions and &refs run against the scope they were written in. Four compile-time rules keep a write from leaking anywhere else:
- Functions and methods can't write top-level bindings, and nothing can write statics. Top-level script code still can. (→)
- A closure that writes outside itself can't escape: it can be called or passed as an argument, not stored, returned or put in a collection. (→)
{{ }}fields can't write outside themselves, because they run concurrently. (→)- Field defaults see only values: no
self, no methods, no fields onlynew()sets, and no reassigning fields in a type body. (→)
Together they mean checked programs have no {{ }} races and no hidden shared state. The LSP shows what limits a closure on hover, e.g. // Effects: writes n; calls block. The rules as they stand today are documented in Mutation and copy-on-write.
The deep dive: a gallery of before/after programs from the PRs' tests, who-can-write-what and what-each-construct-sees tables, why the four rules add up, benchmarks, and the deliberate semantic changes.
Below are the changes most likely to hit existing code. Programs were run with dang built at v2.1.4 and at v2.2.0; output is quoted as printed.
Functions and methods can't write top-level bindings compile error#
In 2.1 a free function's write changed the global as a hidden side effect, and the same write in a method silently became a local. Both are now errors. Top-level script code (top-level forms, the blocks inside them, the REPL) may still reassign: that counts as initializing the module.
1
2
1The function wrote the global; the method's write went nowhere.
3 inference errors:
Error 1:
Error: cannot assign to `count`: top-level bindings are immutable once initialized; use a local `let`, a field, or return the new value
--> /tmp/script.dang:3:25
|
1 | let count = 0
2 | bump: Int! { count += 1; count }
3 | type Foo { bump: Int! { count += 1; count } }
^^^^^^^^^^
4 | print(bump)
5 | print(Foo.bump)
Statics (self { } members) are immutable from everywhere. Counter.count = 5 panicked the v2.1.4 interpreter (interface conversion: *dang.ConstructorFunction is not dang.ValueScope); it is now cannot assign to `Counter.count`: static members are immutable once initialized; a static method's writes to `self` stay in that call's copy.
2
6
Keep the state in a field and return self, return the new value (count = bump(count)), or use a local let.
Read more: Functions return, they don't write.
Closures that write can't escape compile error#
A block, nested function or &ref that writes a variable of its enclosing scope can only run while that scope does. Stored on an object, it used to keep writing the state of a method that had already returned: a mutable cell hidden inside a value.
11
12Calling the same value twice gave two answers.
Error: `Host.store` stores, returns, or collects `cb`, so this block must not write outer state, but it writes `n`
--> /tmp/script.dang:8:30
|
6 | type Guest {
7 | n: Int! = 10
8 | escape: Host! { Host.store { x => n += x; n } }
^^^^^^^^^^^^^^^^^^
9 | }
10 | let h = Guest.escape
counter: Int! {
let n = 0
bump(x: Int!): Int! { n += x; n }
bump(1)
let saved = &bump
n
}
Error: `bump` writes `n`, which is declared outside it, so it can only be called or passed as an argument, not stored, returned, or put in a collection
Make the stored closure pure (Host.store { x => n + x } prints 11), or call it in place. Named functions and methods, and refs to them, can always be stored: they only write their own locals and their own copy of self. An escaping block that uses return or break is now a compile error too, instead of the runtime return from expired function.
Read more: Closures that write can't escape.
{{ }} fields can't write outside themselves compile error#
Every {{ }} runs its fields concurrently, each with a private copy. A write to anything declared outside the field, including the method's own locals and self, was silently thrown away, or raced when it went through a shared closure.
let counter = 0
let pair = {{
a: { counter += 1; counter },
b: { counter += 10; counter }
}}
print([pair.a, pair.b, counter])
[1, 10, 0]Both writes were lost: counter is still 0.
bError: {{ }} fields run concurrently; this assignment writes `counter`, which is declared outside the field
--> /tmp/script.dang:3:8
|
1 | let counter = 0
2 | let pair = {{
3 | a: { counter += 1; counter },
^^^^^^^^^^^^
4 | b: { counter += 10; counter }
5 | }}
Calling a closure from outside the field that writes, or a block parameter whose block writes, is rejected the same way; the block case is reported where the block is passed:
both(&block(x: Int!): Int!): Int! {
let r = {{ a: block(1), b: block(2) }}
r.a + r.b
}
type Acc {
total: Int! = 0
runBoth: Acc! {
both { x => total += x; total }
self
}
}
Error: `both` calls `block` inside {{ }}, whose fields run concurrently, so this block must not write outer state, but it writes `total`Both fields would write total in an unspecified order, and += could lose an update. both { x => x * 10 } is fine.
Fields communicate by producing values: {{ a: counter + 1, b: counter + 10 }} gives [1, 10, 0] and says so. State declared inside a field belongs to it and can be written freely.
Read more: {{ }} fields only produce values.
Field defaults see only values compile error#
Field defaults, and every other non-method form in a type body, run while the object is being built. They now follow the rule for constructor parameter defaults: they see the other fields' values and the enclosing scope, and nothing else. That rules out self, the type's methods and computed fields, and fields only new() sets, anywhere inside the default. new()'s own parameter defaults follow the same rule.
| Program | v2.1.4 | v2.2.0 |
|---|---|---|
type Gauge { level: Int! = 1; read(x: Int!): Int! { level + x }; let reader = &read; … } |
ran: with viaReader: Int! { reader(1) }, g.level = 7; g.viaReader printed 8 |
field defaults can't use `read`, a method of Gauge: they run while the object is being built, so they only see the other fields' values; use a computed field or new() |
type Dial { level: Int!; let doubled = level * 2; new(level: Int!) { self.level = level; self } } then Dial(3).doubled |
runtime error: Symbol.Eval: "level" not found in env: … |
field defaults can't use `level`: it has no default, so only Dial's new() sets it, after the defaults run; use it in new() or a computed field |
type Gauge { level: Int! = 1; level = 5 } then Gauge(level: 100).level |
5: the body overrode the argument |
fields can't be reassigned in a type body, which runs while the object is being built; give `level` a different default, or set it in new() |
let level = 7 and type Dial { level: Int! = 1; out: Int!; new(k: Int! = level) { self.out = k; self } } then Dial.out |
7: the top-level level |
1: the field, as the checker always meant. Dial(null).out also gives 1; explicit null takes the default. |
Use a computed field or a method when you need the finished object: viaReader: Int! { read(1) }, doubled: Int! { level * 2 }. A closure over field values, like let held = Host.store { x => level + x }, is fine and can go anywhere.
Read more: Defaults see only values.
Same code, new answer no error#
These compile under both releases, and 2.2 gives the answer the model promises. They are the ones to look for in tests.
type Acc {
total: Int! = 0
twice(&block(x: Int!): Int!): Int! { block(1); block(2); total }
run: Int! { twice { x => total += x; total } }
peek: Int! { let r = self; total += 1; r.total }
read: Int! { self.total = 5; total }
}
print(Acc(0).run)
print(Acc.peek)
print(Acc.read)
type Shadow {
n: Int! = 0
inlineHelper: [Int!]! {
let bump: Int! { n += 1; n }
let a = bump
let b = bump
[a, b, n]
}
}
print(Shadow.inlineHelper)
type Host {
n: Int! = 100
hook(x: Int!): Int! { x }
fire(x: Int!): Int! { hook(x) }
}
type Guest {
n: Int! = 10
helper(x: Int!): Int! { n + x }
refFire: Int! { let h = Host; h.hook = &helper; h.fire(1) }
nested: Int! {
let n = 5
inner(x: Int!): Int! { n + x }
inner(1)
}
}
print(Guest.refFire)
print(Guest.nested)
let retries = 0
[1, 2, 3].each { _ =>
{ raise "flaky" } rescue {
e: Error => { retries += 1; null }
}
}
print(retries)
| Line | v2.1.4 | v2.2.0 |
|---|---|---|
Acc(0).run |
3 |
0 |
Acc.peek |
1 |
0 |
Acc.read |
0 |
5 |
inlineHelper |
[1, 1, 0] |
[1, 2, 2] |
refFire |
101 |
11 |
nested |
11 |
6 |
retries |
0 |
3 |
- run: a callee gets a snapshot of its receiver taken at the call, so
twiceno longer sees the block's writes. - peek: bare field writes copy
selflikeself.x =does, so an alias keeps its value. - read: bare
xandself.xare one view. - inlineHelper: nested functions share the method's copy, like blocks, so they work as inline helpers.
- refFire: a stored
&helperkeeps theselfit came from (it used to read the calling object'sn). - nested: a nested function sees the method's locals before the receiver's fields.
- retries:
rescuearms (#184) andcasetype-pattern arms (#181) can update outer variables; the write used to land in a private copy.
Also: a new() body resolves fields through self and copies on write, so methods called from new() no longer see later constructor writes; {{s: self}}.s.total in a method works (it type-checked and then failed at runtime with 'self' is not available); and writing through a null link (a.maybe.x = 4) raises a catchable error instead of panicking.
Language versions and dang migrate#
A dang.toml can declare the Dang version its source is written for (#185). Every version parses into the same AST, so newer Dang keeps running older code on one interpreter, and modules of different versions import each other.
| Your project | Read as |
|---|---|
dang.toml with dang = "1.0", "2.0" or "2.1" |
that version |
dang.toml without a dang key |
2.1 in this release. v2.4 changed this case to follow the running Dang (2.4 notes), so pin the version |
no dang.toml (a lone script) |
the running Dang's version: 2.1 |
dang = "2.2" or newer |
an error asking you to upgrade Dang |
The value is a release's major.minor. A leading v and a patch are accepted and the patch dropped ("v2.1.4" is 2.1): from now on, patch releases don't change the language. The nearest dang.toml walking up from a file decides, stopping at a .git boundary; a path import gets its version from its own path.
Old forms parse behind version gates and build the current equivalent, which is what dang migrate prints:
| Replaced in | Old form | Migrates to |
|---|---|---|
| 2.0 | recv.{ a, b } |
recv.{{ a, b }} |
| 2.1 | ... on User { name } in a selection |
... on User {{ name }} |
| 2.1 | for (c) { body } / for { body } |
loop { if (c) { body } else { break } } / loop { body } |
| 2.1 | commas between forms: { let x = 1, x } |
; or a newline |
| 2.1 | case with no else (raised on no match) |
adds else => raise "no case clause matched" |
| 2.1 | clauses after else |
dropped (they never ran) |
dang = "2.0"classify(x: Int!): String! {
case (x) {
0 => "zero"
1 => "one"
}
}
dang = "2.1"classify(x: Int!): String! {
case (x) {
0 => "zero"
1 => "one"
else => raise "no case clause matched"
}
}
From the migration fixtures tests/testdata/migrations/2.0-to-2.1 at v2.2.0; the CLI can't be run with the script runner used for these notes.
dang init # create dang.toml with dang = "2.1", or stamp a keyless one
dang migrate # dry run: list each project and file that would change
dang migrate -w # rewrite .dang files and bump each dang.toml
dang migrate -w --from 2.0 ./old # source whose version nothing declares
dang migrate ./old/main.dang # preview one file's migration, writes nothing
migrate works per project and plans everything before writing. Files that use no changed syntax are left byte-for-byte alone. Each result must parse to the same AST in the target version and be stable under formatting; a file whose meaning would change (old syntax in a #nofmt region) is refused. It rewrites syntax only: code that trips a stricter check, like the mutation rules above, is yours to fix.
Other changes that can bite#
Smaller than the mutation rules, each still able to change what existing code does.
A dang.toml no longer turns on Dagger by itself every version#
Running a script or directory used to auto-import Dagger from a nearby dagger.json or dagger.toml whenever any dang.toml governed it. Now dang starts a Dagger session only when dang.toml declares a Dagger import, so writing one to declare the version (as dang init does) doesn't change how scripts run. The REPL and LSP still detect Dagger modules on their own.
Add [imports.Dagger] with dagger = "vX.Y.Z" or dagger = true (details).
Nullable GraphQL object fields can be null every version#
A nullable object, interface or union field used to be a lazy handle that never equalled null, so == null, ??, !, null patterns and narrowing all took the wrong branch, and a {{ }} selection of a null turned into an empty record (#187). Such a field is now checked when its value leaves the chain, with one { id __typename } request, and loaded by ID; chained selections let the leaf report the null instead. A value of an interface or union type now has its concrete type, so case type patterns match it, nullable or not.
# from tests/test_graphql_nullable_object.dang
let m = user(id: "User:1").manager
assert { m == null }
assert { (user(id: "User:1").manager ?? user(id: "User:2")).name == "Jane Smith" }
assert { user(id: "User:2").manager.manager.name == null }
assert { kind(node(id: "Post:1")) == "post First Post" } # case n { p: Post => … }
Fields reached through a mutation are never checked, since the check would re-send the mutation; they stay lazy. Read more: Nullable object fields.
Needs a GraphQL schema, so quoted from the test suite at v2.2.0 rather than run here.
Stricter checks every version#
| You wrote | You now see | Fix |
|---|---|---|
Calculator.{{add(amount: value)}} in a method of a type whose value is a String! |
cannot use String! as Int! — selection arguments are typed in the scope they run in, not against the receiver's fields |
pass the value you mean |
let a: HasX! = Bar(1); a.x = 2 |
cannot assign to a.x: fields of interface HasX are read-only |
write through the concrete type |
Lib.Greeter("Dang").{{secret}} where secret is a let member of another module |
rejected on both selection paths (it was accepted on one) | make it pub, or don't select it |
dang fmt keeps the = on block defaults fix#
dang fmt printed once: Int! = { n + 1 } as once: Int! { n + 1 }. Without the = that's a computed field: a default evaluated once became a body evaluated on every read. It now keeps the =. Files it already rewrote can't be told apart from intentional computed fields, so check the ones that matter. It also no longer corrupts files with non-ASCII text before a template (#173).
Dagger: declare the API version#
A Dagger import's dagger key takes the Dagger API version the code is written against, the way dang takes the Dang version (#206, #208).
[imports.Dagger]
dagger = "v1.0.0-beta.21" # a module's engineVersion, copied as is
- Session: Dang starts
dagger session --version v1.0.0-beta.21, so a newer engine keeps serving that API, and introspects a Dagger module's schema at it. The prerelease is kept, since Dagger serves its v1.0.0 betas different APIs; build metadata is dropped."0.19"becomesv0.19.0. - Engine check: an engine of an older release fails with
this project's Dagger version is …, but the Dagger engine is …; upgrade Dagger. As in Dagger, a later prerelease of the engine's own release passes and gets the engine's newest API. dagger = truestill works: no version is sent and the API follows thedaggerCLI. It's the form to use withendpoint, which can't take a version.
What's new and worth trying#
Every example below was run at v2.2.0.
Failed asserts show their values new#
A failed assert shows method receivers and every operand of and/or/! and comparisons, marking operands that short-circuiting skipped (#209).
let report = "hello world"
let count = 3
assert("report should mention x") { report.contains("x") and count == 3 }
Error: Assertion failed: report should mention x
Expression: *dang.LogicalAnd
Error: Assertion failed: report should mention x
Expression: report.contains("x") and count == 3
Values:
report.contains("x"): false
receiver: "hello world"
count == 3: (not evaluated)
Runaway recursion is an error, not a crash new#
Unbounded recursion used to grow the Go stack until the process died with fatal error: stack overflow, taking an embedding host (a Dagger engine, in practice) down with it. Calls now stop at a depth of 10000 with an error rescue can catch (#188).
loopy(n: Int!): Int! { loopy(n + 1) }
print(loopy(0) rescue {
e: Error => e.message
})
stack overflow: exceeded maximum call depth of 10000 (infinite recursion?)
Faster, and no more deep-chain crashes new#
- Recursion is linear. Runtime state lives in one frame per call instead of a context layer per AST node: function recursion at depth 1000 went from 115 ms to 2.8 ms (#189). Scope walks are loops, so deep chains no longer exhaust the Go stack, and writes are linear in chain length (#190).
- Loops of writes stay flat. Every write used to stack a scope layer, so a 20–40k-iteration loop took seconds (#199).
- Parsing is about a third faster and allocates less, from pigeon's
-optimize-parser(#204).
Go embedders Go API#
| Removed or changed | Use instead |
|---|---|
The generated parser's Debug, Memoize and Statistics options |
Gone with -optimize-parser; regenerate without the flag to debug the grammar |
ImportSource.Dagger (a bool) |
A DaggerSource{Enabled, Version}; ImportConfig gains DaggerVersion. Read it as vX.Y.Z[-pre] with DaggerSource.VersionString() / DaggerVersionString, not Version.String() |
Calling a node's Infer directly |
Skips the mutation checks; go through InferTopLevel, RunFile or RunDir |
New: ContextWithVersion(ctx, dang.Version1_0) to run a module at a language version (a dang.toml that declares one still wins), with VersionForDir, MigrateSource, PlanMigrations, InitProject and FormatFileWithVersion; ContextWithMaxCallDepth and *StackOverflowError; WithSyntaxCache(ctx, NewSyntaxCache()) to reuse parsed source across RunDir calls (#205); and InferTopLevel, which runs the mutation checks for REPLs and doc tools. SchemaFromSDL keeps interface X implements Y edges (#180).
Sources and verification#
Sources. The vito/dang pull requests merged between v2.1.4 (bc6a757) and v2.2.0 (10fb92d), each confirmed in range with the GitHub compare API: #199/#200/#202/#190 (mutation and scoping), #203 (its docs), #181/#184 (arm writes), #185 (versions, dang migrate), #187 (nullable GraphQL fields), #188/#189 (recursion), #204/#205 (parsing), #206/#208 (Dagger version), #209 (assert), #173 (fmt), #180 (SDL); and the scoping & safety write-up.
Verification. Every program not otherwise marked was run with dang built from source at v2.1.4 and at v2.2.0, with no dang.toml (so language 2.1), and output is quoted as printed; where a program printed several errors, the first is quoted and the rest described. The fixes, the stricter-check messages, the block-parameter error, {{s: self}} and the recursion example were run at v2.2.0 only. Messages that need a dang.toml, a GraphQL server or a Dagger engine are quoted from the v2.2.0 source (pkg/dang/version.go, pkg/dang/dagger.go), tests and migration fixtures. From the PR descriptions: performance numbers, the private-member rejection, the old runtime failures of {{s: self}}, null-link writes and escaped return, and the dang fmt fix.