RSS Amplifier

Bit Maybe Wise · Apr 22, 2026

Tsonnet #39 - Call me maybe, but make it typed, part 5

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

Tsonnet gets methods

Welcome to the Tsonnet series!

If you’re not following along, check out how it all started in the first post of the series.

In the previous post, we refactored the AST to use named records, collapsed ClosureCall into FunctionCall, and cleaned up the grammar conflict that was keeping closures as second-class citizens:

Now that we support functions, just one more thing is missing on that front: methods!

red telephone on yellow paper
Photo by Waldemar Brandt on Unsplash

The plan (such as it is)

// samples/functions/method.jsonnet
local object = {
  my_method(x): x * x,
};
object.my_method(2)

Sneaking methods past the grammar

After implementing functions and pausing for a moment to reflect on how I’d implement methods, I realised that methods can be easily represented as closures that bind to an object field. So I did it:

This approach avoids adding one more abstraction, and maps precisely onto the semantics.

Turns out, scope bugs don’t fix themselves

Cram tests corrected:

Does it work?

Yes, it does:

$ dune exec -- tsonnet samples/functions/method.jsonnet
4

Conclusion

Methods turned out to be less of a feature and more of a realisation: if you squint at them right, they’re just closures sitting inside object fields, and the parser was already halfway there. Two small grammar rules and a scope bug fix later, object.my_method(2) just works. The scope fix was an interesting part — collect_free_idents was silently dropping the receiver when traversing ObjectFieldAccess, which meant variables used as method receivers could slip past the unused-variable analysis unnoticed. Worth catching.

Here is the entire diff.

Next up, time to wrap it up!


Thanks for reading Bit Maybe Wise! object.my_method(2) now returns 4. Your inbox could return something good too -- subscribe and square up.

Read on bitmaybewise.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.