Skip to content

Declare the Dang version per project, add dang migrate - #185

Merged
vito merged 24 commits into
mainfrom
editions
Oct 27, 2026
Merged

vito merged 24 commits into
mainfrom
editions

Conversation

@vito

@vito vito commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

A dang.toml can declare which Dang version its source is written for: the major.minor of a Dang release. Newer Dang keeps parsing older versions' syntax on the same interpreter. dang migrate rewrites a project's source for a newer version, and dang init writes the declaration.

dang = "2.1"   # omitted means "2.1"

Why

Embedders shouldn't need a second Dang runtime for old code. Dagger currently links both github.com/vito/dang and /v2 and keeps parallel core/sdk/dang/v1 and v2 implementations. With this it could delete v1 and call:

ctx = dang.ContextWithVersion(ctx, dang.Version1_0) // for modules pinned before MinimumDangV2ModuleVersion

The breakage between versions turned out not to be purely syntactic. The design is about keeping the cost of each future language change bounded, down to a single minor release.

The pattern: one AST, gated parsing

Every version parses into the same AST. When a release removes or respells a form, the old form stays in the grammar behind a version gate, and that rule's action builds the AST of the current equivalent. So:

  • Old versions cost grammar rules, never interpreter branches.
  • Migration is free: dang migrate parses as the old version and formats as the new one; there is no per-change migration code.
  • Strictness-only changes get no gate. Old code that trips them stops compiling after migrating and is fixed by hand.
  • Each gate is a named method comparing against the release that changed it, e.g. forLoops() is v.Before(Version2_1).

Gates, placed against the release tags:

Before Old form Parses as (and migrates to)
2.0 recv.{ a, b } recv.{{ a, b }}
2.1 ... on User { name } inside a selection ... on User {{ name }}
2.1 for (c) { body } loop { if (c) { body } else { break } } (keeps the condition's narrowing)
2.1 for { body } loop { body }
2.1 { let x = 1, x } (comma separators) ; / newline
2.1 case with no else adds else => raise "no case clause matched" (old versions raised; 2.1 yields null)
2.1 clauses after else dropped (they never ran)

Versions

  • The value is the release's major.minor, e.g. dang = "2.1". A leading v and a patch are accepted, and the patch is dropped ("v2.1.4" is 2.1). Patch releases must not change the language from now on. Before versions were declared some did: 2.1.x patches changed fragment braces and reserved rescue. So a version means its minor's latest release, and 2.1 is 2.1.4's syntax.
  • Accepted range: 1.0 up to CurrentVersion (2.1). A newer value is an error asking you to upgrade Dang, and a non-string value is rejected.
  • Bumping CurrentVersion: do it in the commit that adds the first gate for a new version, since a gate on a version newer than CurrentVersion can never be enabled.
  • A missing dang key means 2.1, permanently (DefaultVersion), unless an embedder set a version with ContextWithVersion. That's what Dang did when the key arrived, so existing dang.toml files keep their meaning.
  • Which version applies depends only on the source's path (VersionForDir):
    • The nearest dang.toml walking up from the file decides.
    • If the walk reaches a .git boundary or the filesystem root first, the source has no governing dang.toml. It is CurrentVersion, unless an embedder set a version with ContextWithVersion.
    • ContextWithVersion never overrides a version a dang.toml declares, but it does decide the version under a dang.toml without the key. Old Dagger modules may have one just for imports, written before the key existed.
    • The pin applies to everything that keyless dang.toml governs, including modules it imports by path. Any other import doesn't get it.
    • Path-less source (REPL input, LSP completion fragments) uses the version of the directory it belongs to.
  • Imports: a path import's version comes from its own path, not from whoever imports it. Modules of different versions import each other freely.
  • A dang.toml doesn't turn on Dagger by itself. dang runs a script with Dagger only when dang.toml declares a Dagger import. A nearby dagger.json or dagger.toml no longer triggers the auto-import just because a dang.toml exists, so dang init doesn't change how scripts run. The REPL and LSP still detect Dagger modules.
  • Writing the version happens only in commands that set up or change a project (dang init, dang migrate), never when running code.

Commands

dang init [dir]

  • With no dang.toml, it creates one declaring CurrentVersion.
  • A dang.toml without the key is stamped with the version it already means (2.1).
  • It refuses a directory that is already part of a project further up.

dang migrate [--to X.Y] [--from X.Y] [-w] [--skip-unparseable] [dir...]

  • Per project: every .dang file a dang.toml governs is migrated together with its dang key. The key is edited in place, and comments and CRLF line endings are kept.
  • Dry run by default: it plans everything before writing anything.
  • Untouched files: files that don't use any changed syntax are left exactly as they are, so a bump with no syntax change only edits dang.toml.
  • Refusals: it refuses a project whose dang.toml is above the given directory. It reports files that don't parse in their version and only writes them with --skip-unparseable.
  • Directories only: passing a file is an error.
  • --from X.Y: for source whose version nothing declares. That's source with no dang.toml (e.g. a Dagger module pinned by engine version), or an older project whose dang.toml predates the key.
    • It applies to the given directory's own project (its dang.toml is in or above it) and to source with no dang.toml.
    • Projects nested below that have no dang key keep 2.1, since they may really be 2.1. They're listed so you can migrate them by passing their directory.
  • Output targets this Dang: migrating to an older version can print spellings that old release didn't have.

MigrateSource checks every file in two ways:

  • Same meaning: the result, parsed in the target version, must be the same AST (locations aside) as the source formatted in its own version.
  • Stable: formatting the result again must not change it.

The first check guards text the formatter copies verbatim. #nofmt regions stay verbatim, and a file is refused if one would change meaning. Template interpolations are re-printed in the target version.

Changes

  • Version type: pkg/dang/version.go defines Version, ParseVersion, the gates and the desugarings.
  • Parser (dang.peg): gates for each row of the table, passed in with the WithVersion option.
  • Formatter: FormatFileWithVersion prints the version's spelling.
  • Migration: pkg/dang/migrate.go (MigrateSource, PlanMigrations, InitProject), plus cmd/dang/migrate.go and cmd/dang/init.go.
  • Tree-sitter: the grammar generator resolves the gates statically for CurrentVersion, so grammar.json is unchanged.
  • Threaded through: RunFile, RunDir/DeclareDir, path imports, dang fmt, the REPL and :type, LSP parsing/formatting/completion. The LSP reads dang.toml once per analysis, and its parse cache includes the version.
  • Docs: the dang.toml and CLI reference pages and the agent skill files cover the key and both commands.
  • Tests:
    • pkg/dang/version_test.go, version_config_test.go and migrate_test.go cover the gates, parsing and resolving versions, MigrateSource's checks, project planning and InitProject.
    • tests/version_test.go runs mixed-version modules end to end.
    • tests/migrations_test.go covers each migration path (1.0-to-2.0, 2.0-to-2.1) with fixture pairs in tests/testdata/migrations/<from>-to-<to>/{before,after}. Migrating before/ must give the golden after/, and both versions are run. Adding a gate means adding a before/ script.

Known limitations

  • Formatting old versions prints the current spelling. dang fmt on a pre-2.1 file prints loop and the added else, because formatting works on the shared AST.
  • Syntax errors in old-version files are positioned using the current tree-sitter grammar, so they can be reported at the wrong spot.
  • Remaining differences from old releases:
    • A for loop evaluates to null where it used to give the last body value; only break value matches.
    • A module that defines its own loop captures migrated loops.
    • rescue used as a name has no gate.
    • Outer-variable writes in case/catch arms now apply; in v1 they were silently lost.
  • When a file is refused, the reported line number points into the formatted source.
  • Writes aren't atomic: migrate -w writes file by file.

dang.toml can now declare `edition = "1"` to parse source with the Dang v1
syntax, where `recv.{ a, b }` is object selection and there is no dot-block
application. Omitting it means edition "2", permanently, so existing
configs and scripts never change meaning when a later edition lands.

Editions only change parsing and formatting; everything runs on the one
interpreter, so modules of different editions import each other freely. A
`path` import without its own dang.toml inherits the importer's edition.
Embedders that never read a dang.toml (e.g. Dagger, which today links both
github.com/vito/dang and /v2 to keep v1 modules working) can choose the
edition with ContextWithEdition instead.

Editions are strings so future ones can be named by date or semver; code
gates behavior on feature methods rather than ordering comparisons.

Signed-off-by: Alex Suraci <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 57bb629
Status: ✅  Deploy successful!
Preview URL: https://5fb8b405.dang-3kk.pages.dev
Branch Preview URL: https://editions.dang-3kk.pages.dev

View logs

vito added 11 commits October 20, 2026 18:49
Signed-off-by: Alex Suraci <[email protected]>
The edition-aware PEG rules (SingleBraceSelection, SelectionOpen,
SelectionClose, DotBlockArg) broke grammar generation: the predicate rule
has no tree-sitter equivalent and was dropped, leaving dangling references
to it.

Tree-sitter can't switch syntax at parse time, so the generator now
resolves these rules for the default edition: predicates are evaluated
statically, pruning the alternatives they rule out, and the switching
rules are inlined rather than becoming named nodes. They also don't count
toward rule precedence, so the generated grammar is byte-identical to the
one before editions were added.

Signed-off-by: Alex Suraci <[email protected]>
A source file's edition was taken from whichever project config happened to
be on the context. That broke in two ways: when an embedder (e.g. the
Dagger SDK) preset import configs, dang.toml was never loaded and its
`edition` was silently ignored; and a path import without its own
dang.toml inherited its importer's edition, so the same directory could
parse differently depending on who imported it, and differently again
under `dang fmt` and the LSP, which walk up from the file.

Now EditionForDir is the one rule everywhere: the nearest dang.toml
walking up from the source decides (DefaultEdition if it has no `edition`
key). If discovery reaches a .git boundary or the filesystem root first,
the source is ungoverned and gets LatestEdition, or the edition an
embedder set with ContextWithEdition. ContextWithEdition never overrides a
dang.toml. Path-less source (REPL input, LSP completion fragments) uses
ContextWithEdition, set from the directory it belongs to.

LatestEdition is new and separate from DefaultEdition: a dang.toml
without an `edition` key stays pinned, while ungoverned source follows the
newest edition.

Also, the LSP now looks up dang.toml once per directory analysis and
shares it between the edition and import resolution, instead of decoding
it once per file on every keystroke.

Signed-off-by: Alex Suraci <[email protected]>
ContextWithEdition was the fallback for every ungoverned directory
reached from the context, so an embedder's pin, or the REPL's cwd edition
(which the REPL puts on the context for its input), leaked into
path-imported modules that no dang.toml governs. The same import could
then parse as edition 1 in the REPL and as the latest edition under `dang
run`.

moduleImportContext now clears it, like the importer's import configs:
the pin applies to the source evaluated directly with the context, and an
imported module's edition depends only on its own path.

Signed-off-by: Alex Suraci <[email protected]>
Every edition now parses into the same AST: a form a newer edition
removed or changed stays in the grammar behind an edition gate (a named
feature method, defined by edition order), and the gated rule builds the
AST of its current equivalent. Old editions cost parsing rules, never
interpreter branches, and migrating needs no per-change code: parse as
the old edition, format as the new one.

Edition 1 gates:
- `.{ }` object selection (already there; `{{ }}` in edition 2)
- `for (c) { body }` as `loop { if (c) { body } else { break } }`,
  keeping the condition's narrowing of the body; `for { }` as `loop { }`
- commas between forms in blocks, block arguments and the file
- a case with no else gets `else => raise "no case clause matched"`, so
  it raises and stays non-null as it did
- clauses after a case's else are dropped; they never ran

Strictness-only changes (e.g. `rescue` becoming reserved) get no gate:
old code that trips them stops compiling and is fixed by hand.

`dang migrate [--to E] [--from E] [-w] [dir...]` migrates per project:
every .dang file a dang.toml governs, together with the dang.toml's
`edition` key, edited in place. It plans everything before writing,
refuses a project whose dang.toml is above the given directory, reports
files that don't parse in their edition (writing only with
--skip-unparseable), and with --from migrates ungoverned source of a
known edition, creating a dang.toml that beats an embedder's pin.

MigrateSource checks each result twice: parsed as the target edition it
must be the same AST, locations aside, as the source formatted in its own
edition, and formatting it again must be a no-op. The first check guards
text the formatter echoes verbatim: #nofmt regions stay verbatim and are
refused if their meaning changes, and template interpolations are
re-printed in the target edition inside the template's original text.

Also fixes a formatter bug the stability check exposed: a comment after a
case's last clause was moved past the case on every format.

Signed-off-by: Alex Suraci <[email protected]>
Each migration path between editions gets a directory under
tests/testdata/migrations/<from>-to-<to>: before/ holds one script per
form the migration rewrites, written the old way, and after/ holds what
`dang migrate` makes of it (golden, -update regenerates). Both are run,
and each script asserts its own behaviour, so a migration is pinned in
text and in behaviour, and adding an edition gate means adding one script.

The before/ halves are excluded from `dang fmt`, which would print them in
the current spelling.

Signed-off-by: Alex Suraci <[email protected]>
Editions become Dang language versions: the major.minor of the Dang
release whose syntax a project is written in, declared in dang.toml as
`dang = "2.1"` (the key isn't `version`, which reads as the project's
own). Gates compare against the version that changed the syntax, e.g.
v.Before(Version2_0), so every minor release can gate changes without
separate edition bookkeeping.

- ParseVersion accepts major.minor from 1.0 up to CurrentVersion (2.1, the
  latest release); a newer one asks to upgrade Dang. Patch releases never
  change the language.
- A dang.toml without the key still means 2.0 (DefaultVersion), pinned so
  that existing configs keep their meaning.
- Ungoverned source is CurrentVersion, or the embedder's
  ContextWithVersion pin, as before.

`dang init [dir]` stamps the version: it creates a dang.toml declaring
CurrentVersion (what ungoverned source already means), or stamps an
unversioned one with the version it already means, 2.0. A directory inside
another project is refused, since a nested dang.toml would cut it off from
that project's version and imports. `dang migrate` stamps as it migrates,
creating the dang.toml with --from.

Stamping happens in those commands only, not when running code: there is
no good place to create a dang.toml for a loose script, and running
shouldn't write files (read-only checkouts, CI, the Dagger engine, the
LSP).

CurrentVersion must be bumped when cutting a minor or major release.

Signed-off-by: Alex Suraci <[email protected]>
Review fixes for the version rename:

- With DefaultVersion at 2.0 and CurrentVersion at 2.1, a plain `dang
  migrate` turned every unversioned project into a 2.0 -> 2.1 migration
  that reformatted all its files, though 2.1 changed no syntax.
  MigrateSource now returns a file as is when it is spelled the same in
  both versions: its formatted text agrees and the original text parses
  to the same AST in the target version. The second condition matters:
  formatting already prints 1.0's comma separators as `;`, but the comma
  itself doesn't parse in 2.0. A version bump with no syntax change now
  only rewrites the dang.toml.
- setConfigVersion replaces only the key's value, keeping a trailing
  comment and CRLF line endings.
- ParseVersion rejected "0.0" through Before, which reads the zero Version
  as CurrentVersion; it compares the major directly now.
- CurrentVersion's comment said to bump it at release, but a gate on a
  version newer than CurrentVersion can never be enabled (ParseVersion
  refuses that version), so it now says to bump it with the first gate
  for a new version. DefaultVersion's comment now says why it is 2.0
  rather than the version current when the key arrived.

Signed-off-by: Alex Suraci <[email protected]>
Adds the top-level `dang = "X.Y"` key to the dang.toml docs and both new
subcommands to the CLI reference, in the docs site and the
dang-language skill.

Signed-off-by: Alex Suraci <[email protected]>
Checking the release tags showed the rename labelled the wrong releases:
Dang v2.0.x still had `for` loops, commas between forms and a raising
unmatched case (v2.0.2's grammar has ForConditionLoop and comma-separated
blocks; its case raised "no case clause matched the value"). Those went
in v2.1.0, and the unreachable-clause error after `else` arrived during
2.1.x. With the gates at 2.0, `dang = "2.0"` parsed 2.1 syntax, and valid
2.0.x source failed to parse: a meaning baked into every stamped dang.toml
and embedder pin.

Single braces stay gated on 2.0. `for`, comma separators, the raising
case and dropped dead clauses are gated on the new Version2_1, and the
fixtures split into 1.0-to-2.0 (selection) and 2.0-to-2.1 (the rest).

DefaultVersion becomes 2.1: an unversioned dang.toml means what Dang did
when the key arrived, which is 2.1 semantics (unmatched case is null), not
2.0's. It now equals CurrentVersion, so `dang migrate` no longer plans
a version bump for every unversioned project.

Also from review: the "left alone" check compared migration output, which
re-prints template interpolations, against plain formatting, which echoes
them, so any file whose interpolations the formatter would respell got
rewritten. The comparison now re-prints them on both sides. And a dang.toml
with CRLF line endings gets the inserted key with CRLF too.

Signed-off-by: Alex Suraci <[email protected]>
Review against the tags found two more gaps:

- Inline fragment bodies were single-brace inside `{{ }}` selections in
  v2.0.x and v2.1.0 (`node.{{... on User { name }}}`), and switched to
  `{{ }}` during 2.1.x. Head required `{{ }}` from 2.0 on, so real 2.0 code
  using fragments failed to parse. A new SingleBraceFragment gate (before
  2.1) and fragmentBraces cover it, separately from the selection braces.
- Projects from before the key already had a dang.toml (for imports), and
  that means 2.1 now, so a 2.0 project with `for` loops had no tool path:
  --from only covered ungoverned source. MigrateOptions.UndeclaredFrom
  (renamed from UngovernedFrom) now also applies to a dang.toml without a
  `dang` key, and the init/migrate help point those projects at it.

Since 2.1.x patches changed syntax (fragment braces, reserving `rescue`)
before versions were declared, the Version doc now records that a version
means the syntax of its minor's latest release, 2.1 being 2.1.4's, and
that `rescue` used as a name has no gate. migrate's help also says that its
output targets this Dang, so migrating to an older version can print
spellings that old release did not have; the `--to 2.0` example, which
suggested otherwise, is gone.

Signed-off-by: Alex Suraci <[email protected]>
@vito vito changed the title Add per-project language editions Declare the Dang version per project, add dang migrate Oct 21, 2026
vito added 5 commits October 21, 2026 04:34
A contributor skill for the version system, so changing the language
doesn't depend on remembering it: how to classify a change (gate,
desugar, or strictness-only), the checklist for adding a gate (version
constant and CurrentVersion bump, feature method, gated rule building the
current AST, formatter, tree-sitter registration, unit tests, migration
fixture), what releasing implies, and the invariants. dang-internals,
editor-syntaxes and dang-language point to it.

Signed-off-by: Alex Suraci <[email protected]>
RunFile and RunDir only auto-imported Dagger from a dagger.json or
dagger.toml when a dang.toml governed the script, so writing one just to
declare the Dang version (as `dang init` does) made existing scripts start
`dagger session`. Only a Dagger import dang.toml declares is resolved now;
the REPL and LSP keep their own auto-detection.

Signed-off-by: Alex Suraci <[email protected]>
An embedder's version pin was ignored whenever the module had a dang.toml
without a `dang` key, though Dang 1.0 and 2.0 already read dang.toml for
imports: a Dagger module pinned to 1.0 with an import-only dang.toml
parsed as 2.1. ContextWithVersion now decides the version of such a
dang.toml; a declared version still always wins.

Signed-off-by: Alex Suraci <[email protected]>
--from applied to every dang.toml without a `dang` key under the target
directory, so a nested project really written for 2.1 was re-read as the
older version and rewritten: a case without an else, which yields null,
gained a raising else. It now applies only to ungoverned source and the
directory's own project (its dang.toml in or above it). Nested keyless
projects keep DefaultVersion; PlanMigrations returns them in
MigrationPlan.Undeclared, and `dang migrate` reports them unless another
argument names them.

PlanMigrations also rejects a non-directory root, which used to fail with
`open script.dang/dang.toml: not a directory`.

Signed-off-by: Alex Suraci <[email protected]>
With a version pin and a keyless dang.toml, the entry directory parsed at
the pin, but a module it imported by path under that same dang.toml was
parsed at DefaultVersion, since imports cleared the pin, while
VersionForDir and `migrate --from` both gave it the pin. The pin is now
bound to the keyless dang.toml that governs the source it was set for,
and carries into imports that dang.toml also governs.

Signed-off-by: Alex Suraci <[email protected]>
dang.toml versions now share one parser, so `dang = "..."` and the Dagger
version the next change adds are written by the same rules: an optional
leading v, major.minor with an optional patch, and optional prerelease and
build suffixes, which are dropped. Version gains a Patch for versions that
need it. A Dang version still means its major.minor, so ParseVersion
drops the patch: "v2.1.4" is 2.1.

Signed-off-by: Alex Suraci <[email protected]>
vito added 3 commits October 27, 2026 11:33
Given a file, `dang migrate` prints what migrating it makes of it,
writing nothing, which is handy for testing a migration. -w still
refuses files: a version belongs to a whole project, so migrating one
file alone would leave the rest of the project read in the new version
without having been rewritten for it, and some changes (a case without
an else) would change meaning silently rather than fail to parse.

Signed-off-by: Alex Suraci <[email protected]>
moved to user-level config

Signed-off-by: Alex Suraci <[email protected]>
vito added 3 commits October 27, 2026 12:31
Signed-off-by: Alex Suraci <[email protected]>
`dang migrate` refused, and so aborted the whole plan for, any 2.0 file
whose case without an `else` either ended in a multi-line clause or sat in
a one-line block: formatting the migrated source again changed it. Both
are formatter bugs that 2.1 code hits too; the added `else` just made them
common.

- After a clause, lastLine now moves to the clause's last line, not its
  first, so the formatter no longer sees a gap before the next clause and
  inserts a blank line after every multi-line clause.
- A one-line block argument stays on one line only if its body renders on
  one line. A case always spans lines, so `{ x => case (x) { ... } }`
  printed as `{ x => case (x) {` ... `} }`, which the next format broke
  open. The inline trial render is shared with formatBlockContents, and
  now works on copies of the pending comments rather than sharing them.

The 2.0-to-2.1 case fixture covers both shapes.

Signed-off-by: Alex Suraci <[email protected]>
Follow-ups from reviewing the previous commit: more shapes in which a 2.0
case without an `else` made the migration fail, or lose text.

- Trial renders now print like the real one: starting at the body's real
  column and indent (a one-line block argument that only breaks because of
  where it sits on a long line took the single-line path, then broke
  differently next time), and in the same version, re-printing
  interpolations when migrating (a case in a template in a one-line block
  was trialled as its original one-line text).
- One-line parentheses and object literals holding a value that prints
  across lines (a case) now go multiline at once, instead of on the next
  format.
- A trailing comment on the closing line of a multi-line clause
  (`} # done`) was dropped; with the migration no longer refusing such
  cases, it was lost silently. It is now kept.
- The else added to a pre-2.1 case is located at the last clause and ends
  on the case's last line, so it no longer moves lastLine: a blank line
  before a comment closing the case is kept, and none is added.

Trials don't nest: within one (or within estimateLength's measuring),
renderInline reports inline without rendering, since the trial's own
output shows any line break. Otherwise every nested one-line block, paren
group or call argument multiplies the work. A trial copies only the
pending comments up to the node's last line, not all of them.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit 3dcf5cc into main Oct 27, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant