Skip to content

Restore builtin JSON/YAML/TOML scalar types - #295

Merged
vito merged 15 commits into
mainfrom
builtin-codec-scalars
Nov 11, 2026
Merged

vito merged 15 commits into
mainfrom
builtin-codec-scalars

Conversation

@vito

@vito vito commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Replaces #294 (version-gated import precedence), which stays open for reference.

Problem

v2.4.0 turned JSON, YAML and TOML into plain namespaces, with no type of their own. Released Dagger engines declare the entrypoint contract with a bare JSON (receiverValue: JSON, fnArgs: JSON!, ): JSON!). SDK-generated entrypoints (pinned dang = "2.1") end with (result :: JSON!). Under 2.4.0, a bare JSON type means the namespace, so every Dang module entrypoint fails with "type hint mismatch" or a covariance error.

Change

Each format is a builtin scalar type again, whose values are valid text in that format. As a value, the same name is the namespace of its encode/decode statics, as in v2.3. Everything goes through general mechanisms. No format is named in hm, unification, assignability, type resolution, scalar kinds, dispatch or equality.

  • Validation: each scalar has a Go-native new() hook (SetGoScalarHook, the hook Regexp already uses). It runs wherever a string becomes one: a cast, a literal at a typed boundary, decoding a string into one.
    • "{" :: JSON! raises invalid JSON: unexpected EOF.
    • YAML must parse as YAML. A multi-document stream is accepted, though YAML.decode still reads a single document.
    • TOML must parse as a document.
  • Installation: the builtin-import installer now installs each host under one name, as a type and as a value (builtinNamespaceType).
    • A scalar host keeps its statics on its meta-type and its Statics() object, as any type's name does (Regexp.escape). So JSON.encode resolves static-first, and JSON! is the scalar.
    • Random and UUID are unchanged.
  • Bare JSON is the builtin in every language version, with no gate. An unqualified import never overrides a builtin import, so with Dagger's schema auto-imported, JSON is the builtin and the schema's scalar is Dagger.JSON. An explicit [imports.JSON] still replaces the builtin.
  • Casts between custom scalars are a generic rule:
    • j :: Dagger.JSON! and d :: JSON! work, as do the same casts through list and map wrappers. The target's hook validates the text.
    • This is explicit casts only. TypeHint.Infer uses scalarCastable and marks its Coerce to convert. hm.Coercible doesn't change, because value handoffs also use it, and there distinct scalars still never mix (cannot use Blob! as JSON!).
  • None of the following comes back: the by-name schema-scalar merge (BuiltinScalarModule/attachBuiltinSchemes), codec: make JSON an untyped JSON value #257's JSONType/isJSONScalar, or any Decoded↔JSON coupling.

Conversions, compared

v2.3 v2.4.0 this PR
String! :: JSON! ✓ ✗ (no JSON type) ✓, validated
JSON! :: String! and degrade at handoffs ✓ ✗ ✓
JSON! :: Dagger.JSON! ✗ (scalar→scalar never allowed) ✗ ✓, any custom scalar → custom scalar, explicit cast only
Dagger.JSON! :: JSON! ✗ ✗ ✓, validated

In v2.3 (checked at v2.3.0 and 00dc380), the builtin JSON and a schema's scalar JSON were always distinct types. An unqualified import's type was skipped when the Prelude already resolved that name, named types compared by pointer, and a custom scalar accepted coercion only from String. So a bare JSON! never passed to a Dagger.JSON! slot, or the reverse, without a cast; #295 changes nothing there. attachBuiltinSchemes only grafted encode/decode and @field/@ignore onto a same-named scalar, which made Dagger.JSON.encode, @Dagger.JSON.field, and a user's scalar JSON with codec members work. v2.4.0 already dropped that grafting, and this PR doesn't bring it back: it was a by-name merge.

encode / decode

  • encode still returns String!. Generated entrypoints do stdin: JSON.encode(...); cast with JSON.encode(d) :: JSON! to get the scalar.
  • decode still returns Decoded and takes data: String!. JSON.decode(j) works on a JSON! value with no special case: a custom scalar already degrades to String! at a call argument.
  • JSON.encode(j) writes a JSON! value as the JSON string it is, as for any custom scalar.

Dagger engine compatibility

  • The builtin JSON is a ScalarKind *dang.Type named JSON at every version, so dangConverter.convertString builds ScalarValue{Val, ScalarType: JSON} for it, and dangTypeToTypeDef exposes it as a String typedef.
  • String! :: JSON! yields a ScalarValue whose ScalarType.Name() == "JSON", as entrypointJSONResult requires, and its text is valid JSON.
  • The request that JSON.encode builds carries receiverValue/fnArgs as JSON text in strings, as in v2.3. The generated dispatcher accepts that ("each JSON value as JSON text in a string; a JSON value is accepted too").
  • Private state fields (let meta: JSON): a builtin JSON value is a plain, not Encoded, ScalarValue, so it marshals as a JSON string of its text. On load, convertString rebuilds ScalarValue{Val: text, ScalarType: <the field's type, JSON>}. The text round-trips unchanged. Values the engine builds skip materialization, so no hook runs on load and stored text is trusted.

Edges worth knowing

  • YAML! holds a stream of documents, but YAML.decode reads a single one and says so: YAML.decode: the text holds more than one document, but only a single document decodes. Empty or null documents after the first don't count, so a manifest ending in --- decodes.
  • A string literal (quoted, or a template with no interpolations) given to an enum or to a builtin scalar whose new() hook is Go-native (Regexp, JSON, YAML, TOML) is checked at compile time, in casts, ==/!=, arguments, typed slots and case patterns alike: "{" :: JSON!, j == "", s == `PASSD`. A computed string is validated when it converts at runtime and raises if rejected (j == `${s}`), as enums always did.
  • A server that sends its scalar as raw JSON on the wire stores a string value bare, so opaqueString :: JSON! fails validation while numbers and objects work. Use JSON.encode(x) :: JSON! for such servers.
  • A cast carries text. A schema scalar's value that the server sent as data becomes its JSON text in JSON!. A schema scalar cast from text is sent to the server as a string, whatever wire form the server's scalar takes (JSON.encode(d) :: Dagger.JSON! already did this). Recorded in stdlib.md.
  • Dang-owned scalars, JSON included, decode only from a string. A JSON! field decodes from a string that holds JSON text, not from nested data. Use Decoded for nested data.
  • let JSON = 3 shadows only the value. JSON.encode still resolves through the type's statics, as Regexp.escape does.

Tests

  • pkg/dang/builtin_codec_scalars_test.go, ported from Gate builtin import types before Dang 2.4 #294's end-to-end test. The engine's ModuleEntrypoint contract, plus an implementing call that ends in (request :: JSON!) from a String!, with a Dagger-like schema (scalar JSON) auto-imported:
    • runs at Dang 2.1, 2.4 and unpinned, under RunDir, RunFile, DeclareDir (signature), a LoadDir session, a ContextWithVersion-pinned unpinned directory, and the REPL's BuildScopesFromImports;
    • is called with the arguments the engine passes, and its result is checked the way entrypointJSONResult reads it;
    • checks JSON! :: Dagger.JSON! and back (validated);
    • at 2.1 and 2.4, checks that ("{}" :: JSON!) (and YAML!/TOML!) is a ScalarValue of a ScalarKind *Type named JSON;
    • checks validation errors, and an explicit import JSON replacing the builtin.
  • Analysis: TestBuiltinJSONScalarBesideSchemaJSON checks 2.1 and 2.4: no diagnostics, bare JSON is the builtin, JSON.encode is its static.
  • Language tests:
    • tests/test_codec_scalars.dang covers construction, validation, degrade, decode of a JSON!, casts and directives.
    • tests/test_json_import.dang covers a schema scalar JSON beside the builtin.
    • New error goldens: json_scalar_invalid, scalar_handoff_needs_cast, and json_scalar_invalid_body, regexp_scalar_invalid_return, json_scalar_invalid_field (a rejected literal returned by a function body, an explicit return, or a typed computed field reports the hook's error, not a return type mismatch).
  • Ran:
    • go test for pkg/dang, pkg/dang/analysis, pkg/lsp, cmd/dang, pkg/repl, docs/go, and tests (TestDang, incl. migrations);
    • the pkg/dang generate/stale check, the docs build (literate snippets), and dang fmt.

Release notes (v2.4.1)

  • JSON, YAML and TOML are builtin scalar types again, in every language version: JSON! is valid JSON text, and likewise YAML! and TOML!. The text is checked when a value is created: a literal that isn't JSON ("{" :: JSON!) is a compile error (invalid JSON: …), and a computed string that isn't raises at runtime. String literals for enums and Regexp, including backtick ones with no interpolations, are now also checked at compile time in comparisons and case patterns. The same names still hold encode/decode (JSON.encode returns String!, JSON.decode returns Decoded and accepts a JSON! value). This fixes Dagger module entrypoints, which spell JSON bare and broke in 2.4.0.
  • A bare JSON type is always Dang's own, even when an import (such as Dagger's schema) brings in a scalar JSON. Reach the schema's as Dagger.JSON.
  • An explicit cast now converts one custom scalar to another, validating at the target: j :: Dagger.JSON!, d :: JSON!. Without a cast, distinct scalars still never mix.

vito added 7 commits November 10, 2026 15:22
Every custom scalar is text underneath, so an explicit `::` cast now
converts one to another (`j :: Dagger.JSON!`, `d :: JSON!`), through
non-null, list and map wrappers, without dropping nullability. The
target's new() hook validates the text, as it does for a String; a target
without one keeps the text and how it is held (Encoded).

The rule lives in TypeHint.Infer (scalarCastable), which marks its Coerce
to convert at runtime (convertScalars). It is not part of hm.Coercible,
which value handoffs also use: there, distinct scalars still never mix.

Signed-off-by: Alex Suraci <[email protected]>
Each format is again a builtin scalar type of valid text in that format,
and, as a value, the namespace of its encode/decode statics, under one
name, as in v2.3. Released Dagger engines declare the entrypoint contract
with bare `JSON` and SDK-generated entrypoints cast `(result :: JSON!)`, so
since v2.4.0 every Dang module entrypoint failed to type-check.

It goes through general mechanisms only:

- The scalars validate on construction with Go-native new() hooks
  (SetGoScalarHook, as Regexp does): `"{" :: JSON!` raises
  `invalid JSON: ...`.
- The builtin-import installer installs each host as a type and, as a
  value, its namespace (builtinNamespaceType): a scalar's statics live on
  its meta-type and Statics(), as any type's do, so `JSON.encode` resolves
  static-first. Random and UUID are unchanged.
- Bare `JSON` stays the builtin in every language version, also beside a
  schema's `scalar JSON`: an unqualified import never overrides a builtin
  import, as before. `[imports.JSON]` still replaces it.

encode still returns String!, and decode still takes a String! and
returns Decoded; a JSON! value degrades to String!, so `JSON.decode(j)`
works with no special case. Select.StaticOwner lets the docs linker link
static calls such as `JSON.encode`.

Signed-off-by: Alex Suraci <[email protected]>
The engine's ModuleEntrypoint contract and the entrypoints its SDKs
generate spell the builtin JSON scalar bare, with Dagger's schema (which
has a `scalar JSON` of its own) auto-imported, pinned to Dang 2.1 or
unpinned. Ported from #294's end-to-end test: the contract and a
`call` implementing it run at 2.1, 2.4 and unpinned, with the engine's
arguments, under RunDir, RunFile, DeclareDir (signature), a LoadDir
session, a ContextWithVersion-pinned unpinned directory and the REPL's
scopes, and the result is what the engine reads: a ScalarValue of a
ScalarKind *Type named JSON. Analysis resolves the same way, and the
schema's JSON converts both ways with a cast.

Signed-off-by: Alex Suraci <[email protected]>
The skills and lit docs said JSON/YAML/TOML were plain namespaces with
no type of their own. Describe the scalars of validated text, their
statics, how bare JSON relates to a schema's `scalar JSON`, and explicit
casts between custom scalars.

Signed-off-by: Alex Suraci <[email protected]>
A schema scalar's value the server sent as data (Encoded) kept that flag
when cast to a Dang-owned scalar without a hook, so it displayed and
encoded as data and compared unequal to the same text cast from a String.
Only a schema scalar target keeps Encoded now.

Signed-off-by: Alex Suraci <[email protected]>
YAML! held a single document because its hook reused decode's parser,
though a multi-document stream (Kubernetes manifests) is YAML: the hook
now checks every document. The JSON hook checks with json.Valid first and
decodes only to report why text is invalid, since every Dagger entrypoint
call ends in `(result :: JSON!)`.

Signed-off-by: Alex Suraci <[email protected]>
Also update the remaining mentions of codec namespaces and of String
being the only value that converts to a scalar.

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

cloudflare-workers-and-pages Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 104f1c0
Status: ✅  Deploy successful!
Preview URL: https://a4ec9192.dang-3kk.pages.dev
Branch Preview URL: https://builtin-codec-scalars.dang-3kk.pages.dev

View logs

vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added 3 commits November 10, 2026 15:51
A YAML! value may hold a stream of documents, but YAML.decode raised
`invalid YAML: trailing document` for one, as if the text were invalid. It
now says `YAML.decode: the text holds more than one document;
YAML.decode reads a single document`.

Signed-off-by: Alex Suraci <[email protected]>
An unannotated field's value is inferred more than once. On the second
pass a scalar-to-scalar cast saw its own Coerce, which reports the cast's
type, so it found nothing to convert and cleared ConvertScalars: the value
kept its old scalar, unvalidated (`(("x" :: Blob!) :: JSON!)` held `x`).
TypeHint now decides the cast from the expression under its Coerce every
time, and wrapCoerce wraps a converting Coerce instead of retargeting it.

Signed-off-by: Alex Suraci <[email protected]>
Say YAML.decode rejects more than one document, that only a String
converts to an enum, and that a raw-JSON server's string scalar values
need `JSON.encode(x) :: JSON!`; group the stdlib reference's JSON, YAML
and TOML sections under one heading.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added 2 commits November 10, 2026 16:03
errYAMLStream is also returned to fromYAML, and every caller prefixes its
own name, so the message no longer names YAML.decode.

Signed-off-by: Alex Suraci <[email protected]>
Comparing a JSON!/YAML!/TOML! value with a string ran the string through
the scalar's hook at runtime, so `j == ""` raised `invalid JSON: EOF`
instead of being false.

- A string literal handed to a builtin scalar whose new() hook is
  Go-native (GoScalarHook: Regexp, JSON, YAML, TOML) is now checked at
  compile time, beside enum literals (checkEnumLiterals becomes
  checkLiterals): in `==`/`!=`, `::`, arguments and typed slots. Such a
  hook is a pure function of the text; a Dang-defined new() is never run
  at inference.
- Any other string compared with a scalar or enum (a template; a
  non-literal String is already a type error) is a Coerce marked
  Compared: text the target rejects stays the string it is and compares
  as that text, rather than raising.

Also drop wrapCoerce's ConvertScalars guard: no caller reaches a cast's
Coerce, since TypeHint.Infer updates its own.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
The Compared fallback let a string a scalar rejects compare as text, but
it skipped a backtick literal (a *Template), so `` s == `PASSD` `` became
silently false where it raised before; it swallowed every error of a Dang
new() hook; and `case` patterns still raised. Drop it: a computed string
converts at runtime and raises when rejected, as enums always did.

checkLiterals now reads a template with no interpolations as the literal
it is (literalText), so `==`, `::`, arguments, typed slots and `case`
value patterns all check a quoted or backtick literal at compile time.
regexp_invalid_pattern's backtick pattern is now caught statically.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 10, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added a commit to dagger/dagger that referenced this pull request Nov 11, 2026
Dang 2.4 requires `!` on type patterns, drops dang.DefaultVersion (a
dang.toml without a `dang` key now means the current version), keeps
data as Decoded with the builtin codec namespaces as automatic imports,
restores builtin `JSON`/`YAML`/`TOML` scalar types (vito/dang#295),
scopes DeclareDir's imports per file and displays GraphQL objects as
their pending query. The following commits adapt the Dang SDK.

The pin is vito/dang#295's head, ahead of v2.4.1; retarget it to the tag
once released.

Signed-off-by: Alex Suraci <[email protected]>
vito added 2 commits November 11, 2026 03:04
A literal that checkLiterals rejects (text a Go scalar hook refuses, or a
name an enum lacks) returned by a function body, an explicit `return` or a
typed computed field was reported as `return type mismatch: declared
JSON!, inferred String!`. Pass its own error through instead, pointing at
the literal, as Case.Infer already does.

Signed-off-by: Alex Suraci <[email protected]>
Text ending in `---`, as Kubernetes-style manifests often do, holds a
trailing empty document, which made YAML.decode reject it as a stream
although only one document has content. Documents after the first are now
skipped while they are empty or null; a second one with content is still
rejected.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito marked this pull request as ready for review November 11, 2026 03:08
@vito
vito merged commit 247f410 into main Nov 11, 2026
9 checks passed
vito added a commit to dagger/dagger that referenced this pull request Nov 11, 2026
Retarget from the v2.4.1-0.20261110161231-fcb24298b2d7 pseudo-version to
the v2.4.1 tag (247f410, the merge of vito/dang#295). It adds, past
fcb2429: rejected scalar/enum literals at returns reported as the literal's
own error rather than `return type mismatch`, YAML.decode ignoring empty
trailing documents, and dang's own CLI querying `introspectionSchemaJson`,
which this engine serves in every view. go.sum now verifies against
sum.golang.org.

Signed-off-by: Alex Suraci <[email protected]>
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