r/ProgrammingLanguages • u/Norphesius • Sep 13 '26
Discussion Are restricted automata useful for driving program correctness?
I originally started writing this as a comment on the "Best way to do formal verification..." post, but realized it should probably be its own.
There's an idea I've been (slowly) trying to explore that I think has the potential for a lot of utility, but it uses concepts that are already well understood in computer science, making me suspicious that I am missing something: Why aren't less powerful automata (i.e. regular and context free) used for more general applications?
In the computational hierarchy Turing machines are the most powerful, but also the hardest to prove things about. Regular grammars (and their finite state machines) and context free grammars (and their push-down automata) are much more restrictive in what they can compute, but have tons of useful, easy to verify properties. Whenever I see discussion on formal verification of programs or program correctness, it seems like everyone wants to stay in Turing completeness land as much as possible, but I don't think everything a program does needs that level computational power. I understand when trying to verify older languages that there isn't a choice, but I am surprised to find that it seems like almost every language new or old is ignoring these lower level automata. I've seen languages that as a whole that aren't Turing complete, and things like total languages with more provable properties, but I don't see any languages that have these less powerful constructs you could "step down" into. You could express some functionality that doesn't need to be expressed in a Turing complete way in these constructs and get a ton of assurances (halting, state minimization, inexpressible invalid states, purity) about that code, then the rest of your code that needs to be Turing complete can use it seamlessly. They're even composable, in the sense that you can easily combine/subtract/invert regular grammars, and that a push-down automata is just a finite state machine with stack glued to it (and can become a Turing machine with an additional stack).
None of this is new, regexes are ubiquitous, and programming language creators in particular know about context free grammars, yet they aren't being used much beyond text searching and parsing. State machines are widespread and massively useful, but as far as I can find, not only do no languages have syntax for constructing them, they don't even have such a thing in their standard libraries. A regex (a proper one) is just a state machine under the hood, and they've been used widely for over 40 years, so why has no one (seemingly) even tried to generalize them for creating state machines? Even if the practical implementation isn't perfect, surely its better than all these state machine management libraries, or worse, people rolling it themselves, without any guarantee of their properties being upheld.
So we've known about these automata for ages, use them regularly, even more so in programming language development, and they have relevant applications for more general code, yet it seems like no language has even attempted to integrate them in either a first class or generalized way. So what's the catch?
A few potential reasons I can think of:
- They aren't actually that generally useful: Text processing was in fact the best use case for them, the other cases aren't worth it or are too few to warrant the effort.
- The syntactic constructs for them would be very cumbersome: As I am exploring this idea, I'm finding that the normal syntax for regexes, applied generally beyond stuff that isn't text or larger state machines, gets very messy. Its also hard to intuit what the state machine graph looks like for a given regex. Applying logic to state transitions is also syntactically odd, as well as syntax for expressing push-down automata.
- The lower level automata wouldn't mesh that well with Turing complete code: You can guarantee the state machine can only move between certain states, but you likely want the state or state transition to mean or do something with the surrounding code/data, which doesn't necessarily have any guarantees on it.
- Programmers don't consider/dismiss lower level automata when solving a problem: Most programmers just want to write the quick solution, and Turing complete land gives them all the tools they need. No one thinks "Could I turn this into a state machine?" when starting to write a complicated while loop, they just write the loop. Also, the stigma of regexes ("...now you have two problems").
- These automata are being used extensively in languages, I am just unfamiliar with them/blind: I know languages use state machines under the hood in some places (ex. compilation of async functions into state machines). It may be the case that they are being used a lot, but are abstracted away, or express themselves in forms I don't recognize.
- It is a good idea and all the smart people just missed it for 50 years: Seems very unlikely.
So has anyone thought about this except me? Any insights or resources I've missed? Glaring foundational issues? Good idea? Bad idea? I wish I had some code or syntax examples to accompany this post, but like I said, I've not had a lot of time to explore the concept in a practical way.
5
u/ianzen Sep 13 '26 edited Sep 13 '26
Yes, automata is both widely known and used for verifying program correctness. Just few examples:
2
u/Clementsparrow Sep 13 '26 edited Sep 13 '26
I agree with you. One area where we almost have state machines / regex-like features is the definition of data types:
(int, float, int, bool)is a sequence of types like a word in a regex is a sequence of characters (/ifib/).|operator.float[5]is like/f[5]/. For arrays of unknown size it's also similar and the star is even on the right side in C-like syntax:float*corresponds to/f*/. Some languages have afloat?syntax that can mean that the type can be missing (although it can also mean the data can be null). What we usually don't have is the range syntax like/f[3;5]/.template<A> (A, float, A)could correspond to/(...some pattern...)f\1/.Now, I am not sure how we can push the analogy further in the direction of context-free grammars, or if it's worth it. I feel like it's what templates and classes are doing, though.
PS: I'd love to have support for regexes that can parse text to extract data directly defined by the type of data specified in the regex, and the result of the match operation would be correctly typed.
2
u/phischu Effekt Sep 14 '26
You are asking an interesting general question, but I only want to comment on the part about state machines specifically.
The best way to define a state machine is through mutually recursive functions that tail call each other. Consider a two-state machine that prints
0and1interleaved.This is very lightweight and direct, yet easily scales to other uses like lexers and communicating systems. Sadly many main stream languages cannot express state machines in this way.
2
u/Infamous_Bread_6020 Sep 14 '26
Proving properties using state machines are actually quite widely used. For instance UPPAAL is a timed automata modelling tool. And I think EventB also falls in this category.
The problem and the answer to your question boils down to the “what”. What is it that you are trying to prove? State machines are useful for proving systems that are stateful like a protocol or a mutual exclusion mechanism. Many formal verification languages, after some fashion, can model state machines. From my comment on the same post you are referring to, Dafny is quite good at modelling systems as a state transition machines and proving temporal properties about them. Dafny is also pretty cool for proving properties of programs that cannot be modelled as a state machine.
But state machines are not useful if you want to prove, for instance, a cryptographic algorithm because that’s algebra (look up ANBD Encoding).
As I said in one of my comments in that post, every approach and calculus and tool is better at doing somethings and worse at some others. It really depends what you want to prove.
1
u/marshaharsha Sep 16 '26
I can think of another reason, not on your list, that such an attempt might fail: fineness of the interleaving of those parts of the system that can be expressed in the restricted formalism (“RF”) conveniently and those that “cannot.” Here are some flavors of “cannot”: (a) Fundamental cannot: Some parts of a system truly need full Turing power (FT). (b) Some parts of a system can be written in RF, but it’s too much work. (c) Some parts can be written in RF at reasonable cost, but that’s not obvious, and past bad experiences or propaganda dissuade people from trying. (d) Some parts depend on third-party code that hasn’t been written in RF.
I have tried a few times to extract into an elegant formalism those parts of a system that clearly can be, and I have usually found that it’s not worth the effort. The parts that “cannot” be extracted are too numerous and too finely intertwined with those that I could see how to extract. Plus my peers glared at me and made comments about “trying to be too smart.”
A second, related reason is that you might end up with a giant, clunky framework in which everything you could possibly need was available everywhere, so you could “shell out” to Full Turing code as necessary.
And that brings me to my last reason. If you are going to allow shelling out to FT everywhere, how do you keep the FT code from messing with the invariants that the RF code relies on? Even if your FT sublanguage is nice and safe (and doesn’t have C’s power to scribble on any data at any time), you would need some notion of isolation of data. How do you separate the data that can be safely handed to FT code from the data that needs to be kept in the control of RF? And what do you do about the users who promise, incorrectly, that their FT code would never do anything bad to the data you are trying to keep away from them?
1
u/joao_rosac Sep 23 '26
De forma bem simples, não participei da discussão anterior, mas:
A sua ideia está correta, mas a aplicação direta na programação geral esbarrou em dois grandes obstáculos práticos:
O choque com o mundo real: Autômatos restritos perdem suas garantias matemáticas e sofrem uma "explosão de estados" assim que precisam interagir com variáveis comuns, memória do sistema ou chamadas de rede.
Péssima ergonomia: Escrever regras de negócios diárias usando transições de estados puras gera um código muito mais confuso e lento de produzir do que a programação tradicional (com if, for, while).
A solução da indústria: Em vez de criar uma sintaxe explícita para autômatos, nós os embutimos nos compiladores e sistemas de tipos (como em Rust e Haskell). O compilador atua como a máquina de estados, impedindo ações inválidas, enquanto você escreve um código normal. Os autômatos só são usados de forma explícita onde a restrição é absolutamente necessária, como em interfaces de usuário (XState) e segurança de sistemas (eBPF no Linux).
1
u/pthierry Sep 14 '26
I think you've spotted just one instance of a more general issue: there are lots to ways to restrict what a program can do to gain huge benefits in guarantees.
Functional Programming and Object-Capabilities are two of them with massive benefits at the PL level. Event Sourcing is one at the storage level and ocaps can also be used at the OS level.
But the overall reaction of the industry is to give bullshit arguments why any new restriction is unreasonable (and 40 years later, when it's not new anymore, it's mainstream…).
I would guess that the average lack of formal education doesn't help. In my previous team, where devs where either well versed in CS or genuinely curious, we used automata to model a few things and it helped enormously to get things right (and we used FP, ocaps and ES…).