I don't truly need linear types, so take everything that follows with a little grain of salt. I do want them, to be clear.
What's a linear type? See https://en.wikipedia.org/wiki/Substructural_type_system for more details. A linear type is a type whose values can only be used exactly once.
When would one use them? You can use linear types to more easily write robust code. Quoting from wikipedia above: [Linear types] allow the system to safely allocate an object after its use, or to design software interfaces that guarantee a resource cannot be used once it has been closed or transitioned to a different state.
They can also prevent performance issues from mistakenly using the same values multiple times. This is particularly interesting in Roc, as it ties to the behavior where the compiler mutates objects in place under the hood.
Where have I used them? I have played with the Cobblestone language that's written by Damian Tedrow. https://github.com/damiant3/Cobblestone
His language is fairly similar to Roc. To quote his page:
Resources are linear. Acquired, used, released. Use-after-free and double-free are type errors, not runtime surprises.
Why do I want them? My particular use case is motivated by the need to auto-close resources in my Roc-based chat program with the idiom enforced by the type system. I don't need them, because I have other mechanisms outside the type system to enforce that objects get proper cleanup. For more details, see this article written by Claude for me: https://roc.lynrummy.com/security-idioms/
I don't have a compelling enough use case to really lobby for them, but I have missed them in Roc. For example, in my BASIC interpreter it was difficult to achieve performance for certain things, so roc-chat is not the first time I have wanted them. I don't understand the Claude-written code well enough to fully claim that they would help there, but we certainly had issues trying to ensure that values weren't used in a way that led to quadratic behavior.
So I am posting this here to find out if other people have yearned for them.
Here's example Roc from Claude that illustrates the chat use case:
# Today: this compiles, and the other devices' open streams
# outlive the sign-out. Only an outside Shale check catches it.
sign_out_others! = |user|
DeviceKeys.revoke_all!(user)
Ok({}) # forgot UserStreams.end_every_stream!(user)
# With a linear type (made-up syntax): revoking hands back a
# value that must be used exactly once, and the only thing
# that can use it is ending the streams.
DeviceKeys.revoke_all! : UserId => linear OpenStreams
UserStreams.end_every_stream! : linear OpenStreams => {}
sign_out_others! = |user|
streams = DeviceKeys.revoke_all!(user)
Ok({}) # compile error: `streams` is never used
For preventing quadratic behavior (my BASIC use case) the broader term is uniqueness types. https://en.wikipedia.org/wiki/Uniqueness_type
Other languages with uniqueness types (same source): Uniqueness types are implemented in functional programming languages such as Clean, Mercury, SAC and Idris.
For the not-closing-things use case, I asked Claude whether defer would make sense for Roc, and Claude suggested a bracket idiom.
roc
with_streams_ended! : UserId, ({} => Try(a, e)) => Try(a, e)
with_streams_ended! = |user, body!|
result = body!({})
UserStreams.end_every_stream!(user)
result
I've written very similar things in other languages like Python and JS in the past, so I am pushing on Claude to try that out in Roc.
Steve Howell said:
Why do I want them? My particular use case is motivated by the need to auto-close resources in my Roc-based chat program with the idiom enforced by the type system. I don't need them, because I have other mechanisms outside the type system to enforce that objects get proper cleanup. For more details, see this article written by Claude for me: https://roc.lynrummy.com/security-idioms/
I don't want to read this novel that Claude wrote. :sweat_smile:
can you explain what your use case is and why linear types would help?
This isn't Claude-written. I mostly collected the info I needed from wikipedia and from my experience working on Cobblestone. As I said at the top, I'm not lobbying hard for this. I will resolve this. I did follow-up searches to see if either unique types or linear types had been brought up here before, and it's never come up under those names, so I suspect there will be minimal interest.
Steve Howell has marked this topic as resolved.
One quick update is that the Idris docs are better than anything from above: https://docs.idris-lang.org/en/latest/reference/uniqueness-types.html
Uniqueness Types are an experimental feature available from Idris 0.9.15. A value with a unique type is guaranteed to have at most one reference to it at run-time, which means that it can safely be updated in-place, reducing the need for memory allocation and garbage collection.
It would be nice if there was someway to guarantee a value has only a single reference and is never copied. I'm not sure how we could make that happen. I spend a lot of time writing tests just to catch this and allocations or clones that I dont want to occur
Would implementing enforcement of single-reference types complicate the compiler to the level of Rust's borrow checker? Or that's a different beast?
Yeah, I'm not sure about the design or implementation details at all. Just from an authoring perspective it would be nice to have.
Karakatiza said:
Would implementing enforcement of single-reference types complicate the compiler to the level of Rust's borrow checker? Or that's a different beast?
yeah it's been a common feature request over the years, and my conclusion always ends up "be careful what you wish for" :laughing:
it sounds like it would be a nice-to-have, but I think actually it would be "the cure is worse than the disease" if we added it
there have been discussions in Zulip in various places over the years about it
Steve Howell has marked this topic as unresolved.
Richard Feldman said:
yeah it's been a common feature request over the years, and my conclusion always ends up "be careful what you wish for" :laughing:
What's the downside? Compiler complexity?
The downside is they make the language more complicated to use.
The compiler uses perceus style reference counting which gets a lot of the benefits of linear types without the added language complexity.
I get that Roc often gets the benefits of linear types without you having to specify anything, but then how can you get the compiler to enforce the semantics? If you have a performance-sensitive program, do you just measure O(N) copies from the outside?
Luke and I are doing the measure-from-outside approach now.
from Luke:
I spend a lot of time writing tests just to catch this and allocations or clones that I dont want to occur
I do measure-from-the-outside mostly in my BASIC interpreter, which is more than just a toy. It's a test of Roc's power and ease of use.
I learned a new acronym today: FBIP = Functional But In-Place
Koka does the same thing as Roc.
so the broad strokes problem is:
(foo, foo) in a tuple - now there are 2 references, so foo isn't unique anymoreFoo -> Bar, is Foo still unique? It depends. If Bar contains a Foo, and the function stores the given Foo inside the Bar, then Foo is no longer unique. but maybe the function just looks at the Foo and doesn't put it in Bar at all. So we need some way of typing the function to say "I accept Foo but don't affect its uniqueness."I'm oversimplifying a bit there, but basically the reason Rust's type system looks and works the way it does is that if you want to say "I can verify at compile-time that this value is unique," either you need a very restrictive memory model (e.g. Goose) or else you need approximately the same amount of type-system complexity and annotation verbosity as Rust
Steve Howell said:
I learned a new acronym today: FBIP = Functional But In-Place
Koka does the same thing as Roc.
we didn't come up with the idea - Folkert's Master's Thesis adviser worked on Koka and told him about it, who told me about it :smile:
As an aside, I should point out that some of the September workarounds for BASIC are no longer necessary in November.
I'm having Claude build a JS interpreter in Roc today. (simplified version)
Our mission is to use Unique(a) :: a.{ ... } as a marker in places where we need certain guarantees. And then we'll write tools with my roc-ast and roc-types tools to determine as much as we can statically. I suspect Claude knows things like the {foo, foo} pitfall, but that's super helpful for me to understand, and I'm relaying this topic to Claude.
Maybe the practical solution here is to expose the post-arc LIR and the pre arc uniqueness analysis through the roc CLI:
roc build main.roc --emit=post-arc-lir
roc build main.roc --emit=arc-uniqueness
which could generate something like
├── post-arc.lir # Serialized post-ARC LIR
├── uniqueness.json # Pre-ARC solver results
└── manifest.json # Compiler version, target,
# source mappings, specialization IDs
With this information it would be straightforward to write a tool that can infer ownership and reuse questions that you have. This would make it easy to write tests and debug performance issues without extending the type system.
A tool with an api something like this:
roc-inspect sites program.rlir --kind=mutation
roc-inspect explain program.rlir \
--function=Main.update \
--property=uniqueness_check_elided
roc-inspect summary program.rlir \
--function=Main.update
Would that solve the problems you are having?
I already have a solution, I use roc-fuzz to assert the allocation properties I want... alonsgide the correctness etc
I feel like that roc tooling API we've discussed previously might be an option for making tools too
Claude distilled our main want as follows:
a dev-mode report of each checked mutation that took its copy path, with its source location, like Lean's
dbgTraceIfShared
We're building that on our end now. Not for upstream but as an oracle for whatever we build on top of roc-ast and roc-types. See #contributing > roc-types tool
High level, I support more introspection into the compiler's middle phases.
Just to be clear, roc-ast and roc-types already don't have to reinvent major wheels. They mostly build from the actual Roc compiler codebase with a little bit of Claude-written zig glue.
Jack Scully said:
Maybe the practical solution here is to expose the post-arc LIR and the pre arc uniqueness analysis through the roc CLI: [...]
Would that solve the problems you are having?
It would help me.
yeah I think there's some tooling improvement opportunity here, but I'm not sure exactly what the right shape is yet.
exposing IR directly is risky because then changing the IR e.g. to make performance or correctness improvements becomes a breaking change :sweat_smile:
among other downsides haha
Richard Feldman Have you looked at roc-types or roc-ast at all? I can provide more background on them. I use these to write Roc scripts such as https://roc.lynrummy.com/roc-on-shale/#find_names_that_disagree_with_their_types
Richard Feldman said:
exposing IR directly is risky because then changing the IR e.g. to make performance or correctness improvements becomes a breaking change :sweat_smile:
I'll give the counterpoint. Changing the IR is risky even when you don't expose it. If core developers can more easily build tools around the IR, the tools can spot pitfalls of IR changes more quickly, even if it's just the tools breaking on them as a forcing function to understand IR changes.
I think the answer is to be really careful about what APIs to expose for people to build tools around
as a memorable example from my employer: a main reason the Atom code editor ended up getting surpassed in popularity by VS Code, which was a very similar IDE built on Atom's underlying Electron framework, is that one of Atom's foundational goals was "be hackable" - and then after it turned out there were a bunch of internals that couldn't be changed without breaking a bunch of extensions, it was impossible to improve performance past a certain point (or solve problems around extensions interacting with each other in undesirable ways), and VS code ended up eating its lunch
"just expose _______" sounds nice in theory but is a long-term recipe for disaster by default. I want to be very careful about what we expose!
Just to be clear, we're talking about compiler tooling. I only run roc-ast and roc-types to build apps. They never live in the apps. To be fair, it's actually not a huge burden to just maintain my own suite of tools. The main nuisance has been keeping the two tools aligned with the compiler during some of the recent churn. Once 0.10 goes out, that should be even more easy to manage.
To resonate with the tooling direction here - since the Roc compiler already does the work, there could already be an e.g. roc check mode that reports linearity. To avoid having to dump the information about the whole program, the input to this checker could be e.g. a user-space type that wraps values, that the user uses as a marker for linearity in their program, and the checker would then report occurrences of this type which are not "linear". This way you'd get a precise report without type system changes, or even reserving a type name like Unique
find_uses_after_a_consume is my home-grown solution to the "copy cliffs" problem, written by Claude. It's still a work in progress. It's being battle-tested by a Roc program that interprets a decent subset of JS with a VM architecture.
roc-alloc-trace is the runtime tool that complements the static checks above.
it's a small C tool (not a platform) that runs a Roc program on Linux and counts its allocations. It shows the line of Roc for each builtin that copied a list.
It's gdb-inspired. Claude used a 1978 debugger trick: overwrite one byte of a function with 0xCC, the x86 breakpoint instruction, and the CPU stops there for you. We first tried it out against my BASIC interpreter, so it was two old-school throwbacks at one.
Both are under UPL. Both are kinda specific to my workflow and setup, but roc-alloc-trace is pretty well packaged as a standalone thing.
Richard Feldman said:
so the broad strokes problem is:
- let's say I write a function that says "you have to give me a unique Foo, and if it's not unique, I get a compile error rather than silent runtime cloning"
- now we need a formal way in the type system to say "this is not just a Foo, but a Unique Foo" which follows the type around
- to enforce this, we have to have a concept of "references" which make something be not unique anymore - e.g. I return
(foo, foo)in a tuple - now there are 2 references, sofooisn't unique anymore- also, passing something to a function may sometimes affect uniqueness and other times not. for example, if I pass a Unique Foo to a function of the type
Foo -> Bar, is Foo still unique? It depends. If Bar contains a Foo, and the function stores the given Foo inside the Bar, then Foo is no longer unique. but maybe the function just looks at the Foo and doesn't put it in Bar at all. So we need some way of typing the function to say "I accept Foo but don't affect its uniqueness."- the solution to all of these problems means you end up with approximately Rust's type system
isn't roc already doing this refcount == 1 check at compile time to evaluate what can be mutated inplace ?
then the restriction might be: if it ever gets mutated, check that it is unique or fail.
Linear typing can be useful, as I really need to FBIP in all possible places to keep the perf.
Last updated: Nov 26 2026 at 20:35 UTC