Skip to content

feat(parser): make pub keyword optional, default public - #92

Merged
vito merged 19 commits into
mainfrom
optional-pub-keyword
Jun 8, 2026
Merged

vito merged 19 commits into
mainfrom
optional-pub-keyword

Conversation

@vito

@vito vito commented Jun 4, 2026 •

Copy link
Copy Markdown
Owner

Human note: after letting this bake for a while, this feels obvious in hindsight, especially after viewing the docs preview for this PR and seeing the 'first impression' code snippet. The pub keyword predated the GraphQL-alignment pivot and was most likely just kept for soft reasons ("explicit", "it works", "leading keywords are easier to parse", working on other things, etc.).

LLM-written below:


What

Makes the pub visibility keyword optional, with public as the default, and starts moving the language toward dropping it entirely. A member written with no keyword is public; let still marks a member private (and is also how you declare a local). The motivating shape — clean, keyword-free types for the docs and the in-browser playground:

type Greeter {
  name: String!
  greet: String! { `Hello, ${name}!` }
}

["world", "Dang", "you"].map { who => Greeter(who).greet }

This fits Dang's GraphQL target: a type compiles to a GraphQL type, where every field is public and there is no notion of private. So bare/pub means "in the schema" and let means "implementation detail" — public-by-default matches the thing being emitted.

Direction

  • pub still works and is fully supported for now, for backwards compatibility.
  • dang fmt and the LSP format pub away — the canonical style is bare for public, let for private. Formatting on save / via the formatter will strip redundant pub over time.
  • Eventually pub is retired, leaving only bare declarations (public) and let (local / private) declarations.

Behavior

The keyword is optional on every form that has a disambiguating token — a : type annotation, (args), or a { block }:

name: String!                 # public field
greet: String! { ... }        # public method
add(x: Int!): Int! { ... }    # public method with args
count: Int! = 0               # public field with default
let secret = "..."            # private (or a local binding)

The one form that still needs a keyword is the bare, untyped name = value: without one it is indistinguishable from a reassignment (x = 5), so it stays pub x = 5 / let x = 5. Adding a type annotation removes the need for a keyword — the rule a user remembers is simply "if it has a :, you never need a keyword."

Parser / tree-sitter

The pigeon (PEG) and tree-sitter grammars are both derived from the same rules. Two things surfaced on the tree-sitter side that the PEG hides (GLR is a stricter ambiguity detector), both resolved:

  1. A factored-out optional-visibility rule matched the empty string, which tree-sitter forbids; inlined vis:Visibility? _ into each field rule instead.
  2. Once name(args) can begin a declaration, a bare name(arg: ...) is ambiguous between a method-with-args declaration and a call with a named argument. Declared an Id/KeyValue conflict; GLR disambiguates on the trailing : Type.

tree-sitter generate succeeds, all corpus tests pass, and the full tests/*.dang corpus parses with no new regressions. The playground's tree-sitter-dang.wasm is regenerated to match.

Reformat scope

dang fmt was run across the repository sources to adopt the new style. Intentionally not reformatted:

  • Dagger modules (.dagger, mod/*) — keep pub for now, until the engine bumps its embedded Dang to a version that accepts bare declarations.
  • Position-sensitive fixtures — tests/errors/* (error-message goldens encode source offsets) and pkg/lsp/testdata/* (cursor coordinates the LSP tests assert on).

Tests

  • New tests/test_optional_pub.dang (the motivating example + typed defaults, bare methods-with-args, let-private, explicit pub) and TestVisibilityFormatting pinning strip-on-typed / keep-on-value-only.
  • pkg/dang units, language exec, format round-trip, and error goldens all pass. Formatting is idempotent and preserves the syntax tree.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: f9270e8
Status: ✅  Deploy successful!
Preview URL: https://b0f99535.dang-3kk.pages.dev
Branch Preview URL: https://optional-pub-keyword.dang-3kk.pages.dev

View logs

@vito

vito commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

Added a second commit (6a0a412) that flips the formatter to retire pub from the canonical style: public is now left implicit and only let (private) is printed.

It's dropped on every form with a disambiguating token (type annotation or method/block body). The one exception is the bare name = value field — it has no type annotation, so dropping the keyword would re-parse it as a reassignment, and it keeps an explicit pub. Added TestVisibilityFormatting pinning both the strip-on-typed and keep-on-value-only behaviors; updated the existing format corpus to the new style. All format/language/error suites pass.

Note: existing .dang sources are left untouched here — 221/380 files would change, which is a mechanical dang fmt ./... pass best done as its own commit so this PR stays reviewable.

@sagikazarmark

Copy link
Copy Markdown
Contributor

Personally, I like explicit declarations, but that's just me.

@vito

vito commented Jun 5, 2026 •

Copy link
Copy Markdown
Owner Author

@sagikazarmark Thanks for your input - yeah, I'm hesitating for similar reasons, but I want to take the time to seriously consider the upside.

Even I have sometimes written type Foo { bar: Int! } and had to go back and add pub so I think there's some merit to it.

Pros/cons I see:

  • 👍 Alignment with GraphQL - helps sell the "GraphQL++" concept
  • 👍 Cleaner syntax for defining dumb data structures (no pub pub pub)
  • 👍 Eliminates awkward fact that pub is valid inside of lexical blocks but has no real effect - let becomes private or lexical declaration
  • 👎 Introduces awkward(?) fact that foo: Int! = 42 is valid inside of lexical blocks
  • 👎 Harder to skim and look for definitions (Ctrl+F pub, next, next, next) - though LSP can help here ("outline" feature, which is ctags-like, though I rarely actually use it)
  • 👎 Harder to parse reliably - leading keywords help a ton to eliminate ambiguity. The ambiguity is resolved in this PR by adding exceptions to Tree-sitter, but it may be an ongoing issue for later grammar changes, and it may be a challenge for anyone implementing a Dang parser, or editor highlighting, or [...]

(edit: and to be clear, not all 👍 / 👎 s are created equal)

@sagikazarmark

Copy link
Copy Markdown
Contributor

I would probably delay this decision.

Removing it is backward compatible. Adding it back is not.

I think there are more important stuff to do than this. (See my pending PRs 😝 )

@vito
vito force-pushed the optional-pub-keyword branch from 8bd5859 to 155b153 Compare June 5, 2026 22:20
vito added 10 commits June 7, 2026 00:38
Field, method, and interface declarations may now omit the pub/let
visibility keyword, defaulting to public. This enables cleaner type
definitions for docs and the browser playground, e.g. a Greeter type
whose members carry no visibility keyword at all.

Visibility stays required only on the bare `name = value` form, which
would otherwise be indistinguishable from a reassignment; every other
field form has a disambiguating token (a colon type annotation, args,
or a block) so the keyword is safely optional there.

The optional keyword is inlined as `vis:Visibility? _` rather than a
named rule because tree-sitter forbids a named rule that matches the
empty string. Making `name(args)` able to begin a declaration also
makes it ambiguous with a call carrying a named argument, so the
tree-sitter grammar declares an Id/KeyValue conflict that GLR resolves
on the trailing type annotation. Regenerated pigeon and tree-sitter
artifacts; the full tests/*.dang corpus parses with no new regressions.

Signed-off-by: Alex Suraci <[email protected]>
Now that public is the default visibility, the formatter leaves it
implicit instead of writing pub on every public member. Public is
dropped wherever the declaration has a disambiguating token (a type
annotation, or a method/block body), which is every form except the
bare name = value field. That one form has no type annotation, so
dropping the keyword would make it re-parse as a reassignment; it keeps
an explicit pub. Private members still print let.

Updates the format test corpus to the new canonical style and adds a
focused test pinning both the strip-on-typed and keep-on-value-only
cases. Existing .dang sources are left untouched here; reformatting
them is a mechanical dang fmt pass best done separately.

Signed-off-by: Alex Suraci <[email protected]>
Mechanical dang fmt pass now that public is the default visibility and
the formatter leaves it implicit. The pub keyword is removed from every
typed field and method; it is kept only on the bare name = value form,
where it is still load-bearing, and let still marks private members.

Covers the repository sources (.dagger, demos, mod, docs, and the
language test files). Error-message fixtures under tests/errors and the
position-sensitive LSP testdata are intentionally left as-is, since
reformatting them would churn goldens and cursor offsets without
benefit. No behavior change: formatting preserves the syntax tree and
is idempotent.

Signed-off-by: Alex Suraci <[email protected]>
until the engine bumps dang

Signed-off-by: Alex Suraci <[email protected]>
Signed-off-by: Alex Suraci <[email protected]>
Public is now the default visibility, so the docs no longer teach pub
and let as the keywords that declare a field. A field is introduced as
a structural declaration (name plus a type, value, args, or block), with
public the default and let marking the private/local case.

fields.md is reworked end to end: a new Visibility section, and a
Declaration-vs-reassignment section stating the rule that a type
annotation, args, or block makes a declaration unambiguous, while the
bare untyped name = value still needs a keyword or it reads as a
reassignment ("if it has a :, you never need a keyword"). objects,
modules, overview, and blocks are reframed to match, with module export
described as "everything not let" and let presented as the way to
declare a local. pub is dropped from typed samples throughout and kept
only on the untyped value-field illustrations where it is still
required. The keyword lists note pub is optional and being retired.

Signed-off-by: Alex Suraci <[email protected]>
The fields docs called the untyped name = value form "the one exception"
to optional pub, which makes the rule feel ragged. Reframe the keyword as
a binding introducer that is needed exactly when a line would otherwise
read as a reassignment: shapes with a colon, args, or block self-announce
as declarations and need no keyword, while bare name = value is plain
assignment syntax and so takes an introducer to declare a fresh field.

This is the same rule that already governs locals, so the untyped field
stops reading as a special case and becomes the one shape that does not
self-announce.

Signed-off-by: Alex Suraci <[email protected]>
The shortcut implied a colon is the tell for "no keyword needed", but
argument lists carry colons too, and an args-only or block-only form
self-announces without any return-type colon at all. The preceding
paragraphs already explain the rule by shape, so the lossy one-liner only
invites the wrong reading. Remove it rather than patch it.

Signed-off-by: Alex Suraci <[email protected]>
An earlier pass claimed an argument list or block body announces a
declaration by shape. The grammar disagrees: every keyword-optional field
form carries a colon token in type position, and the only keyword-required
form is the bare name = value with no type. A method always declares a
return type, so args or a block on their own are calls, not declarations.

Rewrite the section around the real tell, a type in type position (a field
annotation or a method return type), and restore the rule of thumb in that
corrected form: if it names a type, you never need a keyword.

Signed-off-by: Alex Suraci <[email protected]>
The fields page had grown into a long argument about introducers, type
positions, and why the untyped form isn't an exception, which buried a
simple rule under justification. Cut it back to confident, example-led
prose: a field is public when it declares a type and local when it starts
with let, and a bare name = value reassigns.

Stop mentioning pub anywhere in the prose, since it is legacy and the
formatter strips it, and let the code samples carry the explanation rather
than narrating every case.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the optional-pub-keyword branch from 68482d5 to 2f46d76 Compare June 7, 2026 00:43
vito added 2 commits June 7, 2026 00:55
The public type shape powers LSP hover and the module interface view.
It now renders members bare (name: Type) instead of pub name: Type, to
match the source formatter and the canonical style where public is the
default. Only let (private) members carry a keyword, and they are
already omitted from the public shape entirely.

Updates the shape and hover test expectations accordingly. Dagger module
sources still keep pub in their own files until the engine bumps Dang;
that is unaffected here, since this is a rendered view, not source.

Signed-off-by: Alex Suraci <[email protected]>
Replaces the visibility keyword only where a binding is genuinely local
or its public-ness does not matter: top-level bindings in test scripts
(which nothing imports) and block-local declarations become let. Public
type members stay pub, because they are untyped value fields — bare
name = value inside a type parses as a reassignment, so they cannot drop
the keyword and default to public the way an annotated field can.

This corrects an earlier over-broad swap that turned public type members
(e.g. MyClass.val) into private let. test_nonnull_assert.dang is
formatted so its typed pub members go bare, and test_optional_pub.dang
keeps one explicit pub to prove the keyword is still accepted. LSP
testdata and the embedded sources in the Go tests are left as pub: those
members are public and the fixtures are position-sensitive. Error
fixtures and the formatter tests, which assert on pub, are untouched.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the optional-pub-keyword branch from 1a30629 to 3a94a3b Compare June 7, 2026 01:35
vito added 7 commits June 7, 2026 02:10
Removes the visibility keyword from every typed member that can take the
bare default-public form (pub name: Type / pub name(args): Type) across
the LSP testdata, the error fixtures, and the embedded sources in the Go
tests. Bare keeps the member public, so this is purely a spelling change.

For the LSP testdata the declarations and their echoed goto/rename
assertions are updated together; the harness resolves cursor columns by
locating the target text and adding the marker offset, so both sides
shift by the same four characters and stay aligned. Error golden files
are regenerated: because bare stays public, the type-checking output is
unchanged except for the quoted source lines and their carets shifting
left. Untyped value fields (pub x = value) keep pub, since bare x = value
parses as a reassignment; constructor_pub_new and test_optional_pub keep
an explicit pub on purpose to exercise the keyword.

Signed-off-by: Alex Suraci <[email protected]>
Adds a `fmt` generator that builds the dang binary and runs `dang fmt`
in place across every .dang file in the repo, exporting the result as a
changeset. This lets `dagger generate dang:fmt -y` automate the bulk of
the redundant-pub removal and exercises the formatter's pub handling as
a side effect.

It skips the Dagger module sources under mod/, which must keep their
explicit pub keywords until the engine bumps its embedded dang, and
tolerates files that don't parse so the deliberately-malformed syntax
fixtures under tests/errors/ don't fail the run.

Signed-off-by: Alex Suraci <[email protected]>
Runs the new dang:fmt generator over the test fixtures, dropping the now
redundant pub keyword from members that carry a type annotation or block
body. The constructor_pub_new fixture still triggers its error because a
typed `new` member is rejected regardless of visibility, and the message
reports the default public visibility either way.

Regenerates the affected error-message golden specimens, which embed the
reformatted source snippets.

Signed-off-by: Alex Suraci <[email protected]>
Drops the now-redundant pub keyword from top-level (column-0) bindings in
test fixtures, error specimens, the GitHub demo, and the LSP diagnostics
testdata, replacing it with let. At script and block scope these aren't
module exports, so let is the right introducer; the formatter keeps pub
on the bare `name = value` form because dropping it alone would re-parse
as a reassignment.

Regenerates the error-message golden specimens, which embed the updated
source snippets.

Signed-off-by: Alex Suraci <[email protected]>
Gives the untyped public members of test fixture types an explicit type
annotation, which keeps them public without the pub keyword now that a
type annotation is the disambiguating token. Object-literal fields are
left on pub for now, since their inferred shapes are awkward to spell
out and exercise inference on purpose.

The Empty.val field has no inferable type from its null default, so it
takes an arbitrary nullable String; the test only checks it equals null.

Signed-off-by: Alex Suraci <[email protected]>
Dropping the pub keyword from the sub declaration in the rename fixture
left the function name at the start of the line, but its rename test kept
the ^w motion that used to step over "pub " to reach the name. Without
the prefix that w overshoots onto the opening paren, so after the rename
the cursor lands mid-token instead of at the start, failing the position
assertion. Drop the now-redundant w so the motion lands on sub directly.

Signed-off-by: Alex Suraci <[email protected]>
The optional-pub work makes a type annotation the marker of a public
field and retires the pub keyword, which dang fmt now strips. Update the
agent skills to match: public members are written with their type (or an
arg list / block body), let marks a local, and a bare name = value
reassigns. Reframe the objects.md fields section around that rule and
sweep pub out of every example, keyword list, and prose mention across
the dang-language and dang-internals skills, so the skills teach only the
forms that survive.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito merged commit 07e377a into main Jun 8, 2026
8 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.

2 participants