所以你想构建一门主流的形式化可验证语言
So you want to build a mainstream formally verifiable language

原始链接: https://danilafe.com/blog/verifiable_language/

LLM 正在改变数学,这引出了一个问题:软件工程能否同样从形式化验证中受益。作者综述了创建可形式化验证的主流语言所面临的挑战。形式化方法以逻辑为基础,但规范可能与意图不符(规范鸿沟)。语言设计者必须决定构建的是对象语言还是元语言,定义精确的语义,并通过核心语言和脱糖在简单性与表达力之间取得平衡。软件变更会带来证明修复的困难;验证可以是内在的(证明与代码一起)或外在的(证明分离),各有取舍。副作用会使元语言复杂化,而纯函数式方法和线性类型可以提供帮助。主流采用需要考虑谁编写和阅读证明、LLM 的参与以及互操作性。三大工具是:用于演化系统的时序逻辑、用于堆/状态与并发的分离逻辑,以及通过 Curry-Howard 统一代码与证明的高阶依赖类型逻辑。策略有助于构造证明,并可能辅助 LLM。尽管面临这些挑战,作者谨慎乐观地认为形式化验证能够进入软件主流。

文章探讨构建主流形式可验证编程语言。评论者争论是否需要新语言,许多人认为Lean已提供强大的、高性能的函数式语言,具备元编程和证明能力,但需要更多实用库和更好的底层/操作系统/硬件支持。其他人建议将Lean与Rust桥接或在IR层面验证,而担忧包括性能、副作用、抽象不匹配和变化频率。一些人提到替代方案,如SPARK、Why3、Coq/Rocq和内生验证。总体共识倾向于改进现有生态系统而非发明不兼容的语言,同时承认主流采用中存在开放挑战。
相关文章

原文

OpenAI’s advances are all in the news these days, and so are Anthropic’s. All of a sudden we are getting hit by a never-ending stream of new mathematical discoveries mediated by large language models. Mathematicians are bracing for a world that’s wildly different from the familiar, while at the same time, we in the other fields that use LLMs are wondering: will we also get similar benefits? Will our profession be transformed the way that mathematics appears to be?

Meanwhile, some say that we are in the golden age of programming language research , and some say we need a formally-verifiable mainstream language . I agree! This is something I’ve been thinking about for some time now, and, by virtue of having played with formal verification for a few years now, I think I have something to offer. As such, I’m writing this article to provide some context and starting points for would-be creators of formal verification languages, particularly those creators that come from a software engineering background and may not (yet!) have a strong familiarity with formal methods.

Throughout, I will state open questions, which I implicitly qualify to be open to me and relevant from my point of view. These are questions I would ask myself if I were to begin working on such a new language (instead of lazily writing about it!). They are not intended to be prescriptive, nor to totally encompass the problem space. They are, however, intended to be usable for skimming this article.

Grounding In Logic

The whole purpose of formal methods is to take an informal process or framework and make it rigorous. To make this possible, we need a sufficiently rigorous, precise, and powerful foundation. In virtually every case I can think of, this foundation is that of logic.

Logic allows us to name objects and express relationships between them. It also allows us to make statements and reason about what it takes for them to be true or false. It has the distinct advantage of being unambiguous: where human language may admit several interpretations, logic forces us to be precise, sometimes to a pedantic extent. Though logic itself is, in each of its varieties, an unambiguous system, there are indeed many varieties. I once heard logic described as a “game of symbols”, and there are many ways to play such games. This, in turn, leads to a variety of ways to describe the world. There are three families of logic that I think are of broad interest to us if we talk about programming languages. I talk about each of them in more detail in the sections below.

Before I describe these in more depth, I feel I should introduce some other ideas and open questions when it comes to designing a new language amenable to formal verification.

The Specification Gap

Though I find this topic to be among the most well-understood about formal verification, I would nevertheless be remiss if I didn’t mention it here. At its core, formal verification for software is about proving that a program behaves according to a particular specification. The trouble is, of course, that the specification itself may be wrong!

This is already in the public zeitgeist when it comes to the recently published mathematical proofs. Because of their immense size, it’s not uncommon to hear the question: “Did it really prove what they claim it has proven?” The analogy for us is, “It proved the code matches the spec, but is it the spec we wanted?”

The fidelity of a specification with respect to its purpose is entirely separate from the adherence of a program to that specification. My claim here is that fidelity in most existing software is grounded somehow in the interaction with an external (or, indulgently, “real”!) world. Because of this it ceases to be a directly technical matter, and is harder to address with a technical solution such as a programming language. Nevertheless, I think this is an important caveat to keep in mind, to keep ourselves honest about the exact value proposition of things we create.

Metalanguages and Object Languages

Those of us working in software engineering (or just thinking about plain English) do not often think about the distinction between “object” and “meta” languages. However, things get difficult when we need to use “language to talk about language”. A quick-and-dirty example is to note that when we say “your sentence is missing a ’the’ before the noun”, we can observe that while the literal string “the” figures twice in our sentence, it has radically different meanings. In the first, it’s referred to as something separate, while in the second, it’s “just” a part of speech. This same distinction can — but doesn’t always — apply when talking about formal verification. In fact, there are often several levels to this.

Most often, we talk about the language we are trying to prove things about (which in this case will be our programming language) as the object language. This is the thing-we’re-describing. It need not be grounded in logic at all. In the part of Software Foundations I’ve linked above, the language-in-question is C, which is far from logical. While it has some logical operations (bitwise “and” and “or”! short-circuiting “and” and “or”!), by virtue of being an imperative language (more on that later), it’s not very well suited for proving math.

Instead, we lean on the meta language (or metalanguage), which is the thing-we’re-using-to-describe-the-object-language. It can be similar to the thing-we’re-describing, but more often than not, by virtue of being something quite specialized and needing rigor, it tends to be quite different. TLA+ and Alloy, if used to model the behavior of code, are metalanguages. So are inference rules (which I have defined several times in the past), and so is plain old logic when it describes a program somehow. So the expression 1+1, if it figures in some logical or formal definition, is distinct in a way similar to the quoted “the” in the example sentence above.

If you want to be extra pedantic, you might say that English is your meta-metalanguage, since you use it to describe your logical statements, or maybe even define the behavior of your logic.

It might seem that what I’m describing is not particularly important for language design in itself. However, I think it’s crucial to ask the question:

  • open question: if you’re making a new “language for formal verification”, what are you making? Are you making a new object language (a new C to be analyzed using formal methods) or are you making a new meta language (a new TLA+, Alloy)?

You might answer “both”, and that’s not an unreasonable direction. I’d say that Lean, for one, rarely requires such a distinction or stratification.

Semantics of Languages

Ultimately, if you are trying to build a formally verifiable language for software engineering, what you are trying to do is reason about how a computer program behaves. Even before saying that the program “behaves correctly”, you must ask yourself: what does it mean for this program to “behave at all”? This is a complicated question, particularly for mainstream programming languages. Besides answering the comparatively simple questions (“what will this program do if I write 1+"1"?”, in itself a question that varies between mainstream languages), we need to think about the question “what would happen if I wrote a loop that implements the [note: Described, for instance, in its Wikipedia page, and (phew!) still unsolved at the time of writing. ] ” (in C/C++, thanks to undefined behavior, that loop could be elided and the implementation made to return 1).

One challenge in formally modeling whole programs is that the languages we conventionally use to write them in have very complicated semantics, or indeed semantics that are ill-defined. A clear example of this is “undefined behavior” in C and C++, where compilers and language implementations are free to act in whatever manner they desire. A similar concern is “unspecified behavior”; programmers are told, for example, not to rely on the order of evaluation of arguments to a C function, because it isn’t fixed.

But while the set of undefined and unspecified behaviors in C and C++ is relatively bounded, the overall behavior of these languages is encoded in huge specifications, without particular mathematical rigor. Especially in the case of C++, this specification grows with every release. Other mainstream languages (Python, Ruby, Rust, JavaScript, TypeScript) are not much better in this regard.

Before I go further, I should supplement the ways in which languages can be poorly defined with a list of ways in which we can rigorously specify them. The three classic approaches to program semantics as known in PL literature are:

  • Operational semantics, which describes how a language is evaluated by some abstract machine. It comes in two varieties, big-step and small-step operational semantics. The former describes the final result of evaluating a program (most commonly in terms of evaluating smaller pieces of it); the latter describes program evaluation one atomic step at a time. Small-step semantics is oftentimes chosen for languages where things can happen concurrently, since the individual steps are easier to interleave.
  • Denotational semantics, which describes a language in terms of how its constructs map to a mathematical semantic domain (e.g., a def in Python may map to a mathematical function). I posit that this is less relevant to our practical interests today.
  • Axiomatic semantics, which describes a language in terms of how each of its constructs affects the program state, encoded in logical descriptions thereof. In this, it is very closely related to separation logic, which I introduced above and will elaborate on further below.

Towards Core Languages

We find that simpler languages are easier to reason about, because the fewer the concepts in the language, the less it takes to precisely describe what all of them do. There is, however, a tension here: simple and bare-bones languages are easy to specify, but harder to write code in.

Here, your opinions might diverge on whether this matters in a post-LLM world. A full-on “agentic development without human supervision” proponent might say that it doesn’t matter that the language is simple; LLMs can write code at lightning speed, so why not make them write more of the simple, well-specified language? A “human review is now the new bottleneck” believer might say instead that we need highly expressive languages, such that complex ideas and behaviors can be expressed in ways that are easy to read in a diff viewer.

In any case, the trade-off between “simple” and “powerful” is not direct, thanks to the existence of syntactic sugar. If you can provide a simplification from a “powerful” version of your language into a weaker, simpler, more specified form, you get a specification of the complex language more or less for free: the semantics of a complex construct are “just” the combined semantics of the pieces to which it desugars.

In fact, this is the approach taken in the Lean language itself (which, I might say, is quite close to a general-purpose, formally verifiable language anyway; more on this another time). Lean has a “core language” (or maybe several core languages), each of which are extremely simple. The full, powerful version of Lean is elaborated into these simpler core languages. Because of Gödel’s well-known incompleteness theorem, we can’t prove these languages to be logically consistent from Lean itself (and thus, we have to trust them to be), but because of their simplicity, their correctness is commonly accepted.

  • open question: if you’re making an object language, how can you make its semantics amenable to formal verification?
  • open question: if you’re making a metalanguage, how will it know about the semantics of the software it’s describing? Will it know and understand the code-to-be-verified at all?
  • open question: for an industry-capable programming language, where is the right balance between simplicity of specification and power of expression? Does this change with the presence of LLMs?

Proof Repair

When observing the tremendous success of AI in mathematics, we may be led to forget the ways in which mathematics (despite being deeply connected to programming through both the theory of computation and the Curry-Howard isomorphism) differs from the practices of software engineering. In fact, I believe that one crucial distinction is preventing the meteoric ascent of AI in software of the formally verified kind: the everpresence of change.

Once a mathematical theorem has been proven, you are ‘more or less done’. You may clean up the theorems (if in the process of struggling towards a solution you have produced extraneous statements, constraints, or diversions), and you may try to understand the proof (if it was constructed with the help of an LLM, or if you used methods from other mathematicians without a deep understanding — a perfectly valid approach). However, this boils down to “refactoring the math” (in fact, there is a deep connection here which makes this description quite apt).

However, in software engineering it is very often the case that the thing you built is not the right thing. The theorem is not the one that needed to be proven at all. Historically, this has been a big challenge, because seemingly small changes to the code can drastically affect its behavior and correctness. The act of taking a proof that used to describe a piece of software and adapting it to the new, updated version is called proof repair, and it is a whole area of research in PL literature. Although there are techniques to perform this automatically (especially in simple cases), in general, this is a very difficult problem.

This relative difficulty of adapting formal specifications to changes in code is significant because it can drastically slow down the speed at which software is iterated on, and even become a source of friction when dealing with technical debt. As a result, creators of languages that have formal verification components must have some picture of what should happen when code changes. I view this as an open question that could be addressed by a novel language.

  • open question: if your code changes, do the specifications have to change immediately to preserve the correctness of the program?
    • If yes, how do you make this as effortless as possible?
    • If no, how do you ensure that specifications eventually keep up with the actual program, and thus are describing the thing being developed?

Intrinsic and Extrinsic Verification

Tangentially related to the notion of proof repair is the distinction between intrinsic and extrinsic verification. There is, broadly speaking, a distinction between proving the program you’re writing correct as part of the program or, alternatively, completely separately from the program. Proofs that ride along with the program itself are typically called “intrinsic verification”, whereas proofs that occur “out of band” are called extrinsic verification. The two approaches have their own distinct advantages and tend to be favored differently by [note: Interestingly, AI agents using systems that are capable of both modes (I have Lean in mind here) seem to prefer extrinsic verification. Personally, I favor intrinsic verification instead, and it has been interesting to watch Claude and Codex continuously try to rewrite my code to separate correctness from implementation. ]

Intrinsic verification often requires one to pay effort upfront. This may come in the form of thinking about the types, preconditions, and postconditions of each function and making them immediately explicit. Insofar as this is an even more rigorous version of immediate, strong typing, this can produce the same sort of discomfort as having to write in a typed language (e.g., TypeScript with strict typing requirements) compared to a more or less untyped language (JavaScript). In fact, the effort required is probably considerably higher, because you are required upfront to state precisely how you might expect a function to behave. In certain forms of intrinsic verification (correctness by construction in particular), the difficulty lies not only in knowing exactly what the code will do but also in [note: It might seem at first that this would introduce performance penalties, since we are introducing additional code, potentially in the form of arguments or definitions. However, it is common for languages with intrinsic verification to perform a process called proof erasure, which strips proof-related code from the program being compiled. The net result is a formally verified program that pays a lesser runtime penalty for the surrounding rigor. ] . This is an extreme version of making illegal states unrepresentable . Additional difficulties arise, of course, when the code has to change, as we have discussed in the previous section. In that case, you may find that the specifications you had previously written, or the types you had devised, no longer apply, but you must immediately pay the cost of fixing them, or your code will not compile.

  • open question: is there room for an intrinsically verified language that is gradually verified, akin to gradual typing? We have, for example, seen that gradual typing can enable incremental migration of codebases from (e.g.) JavaScript to TypeScript and from untyped Python to Python with type hints.

Extrinsic verification separates proofs from the code they describe. Thus, you might write the program “normally” and then separately construct a specification for what your code should be doing. You pay no cost upfront, and moreover, the reader of your code does not necessarily pay the cognitive burden of having to understand both the specification and the code (though one might argue doing so is desirable for proper review). An even more “extrinsic” version is one in which the correct behavior of the exact code is never verified at all. Instead, the system is described at a higher level of abstraction, glossing over the details of assignments, functions, expressions, and so on, in favor of a more condensed (and easier to digest, perhaps) ideal representation. Of course, both of these directions introduce the possibility of drift: do you check your formal specifications against your code each time it changes? Does the code you write still match an abstract system you may be trying to model?

  • open question: in a language with extrinsic verification, how do you ensure that the description continues to match and verify the implementation?

Referential Transparency in Metalanguages

Some languages are easier to reason about than others. It is no accident that many proof assistants (Agda, Rocq, Lean as canonical examples) have surprisingly similar underlying theories. The most commonly cited property is that of referential transparency. This property asks: if a variable I have was defined as x = foo(), can I replace x with foo() everywhere, and will everything work exactly the same? In most mainstream languages the answer is “no”, for a variety of reasons. Perhaps the simplest example is this:

def foo():
  print("Hey!")
  return 1;
x = foo()
print(x+x+x+x)

As written, this program prints “Hey!” once, then prints 4. Meanwhile, replacing x with foo() in the last statement will cause “Hey!” to be printed four times! Things would similarly go awry if foo() generated and returned a random number, or if it allocated a fresh object in its body. In general, the issue is that of side effects: things that the function does “in addition” to a naive computation. Console output, random number generation, and memory allocation are all side effects. It is entirely possible to reason about such functions at the object level; this is the subject of Hoare logic and, more generally, separation logic. However, side effects are very strange for a formal metalanguage, because they prevent exactly the sort of algebraic manipulation (e.g., substituting a variable for its definition) we may be used to in plain mathematics. As a result, metalanguages (like TLA+ or Alloy) and proof assistants which offer a single language for both the code and the theorem proving (Agda, Lean) do not [note: Effects can, however, be quite elegantly modeled with monads, as Haskell users will not hesitate to tell you. Further techniques, such as monad transformers and the MTL (for "monad transformer library") style can further improve side-effect-free code that models effects.

Algebraic effects are another approach to solving this problem, though one that I haven't seen in a metalanguage. ] If your goal is a new metalanguage or a unified system, you will likely want to do the same.

Can a side-effect-free language still be fast?

Mutation is a side effect, and as a result, data structures in languages without side effects are immutable. However, whereas the semantics of a language do not allow for mutation, it is possible to leverage properties of the type system to allow for an efficient implementation (which uses mutation) of such languages. The canonical example here is that of linear types.

A value with a linear type must be used exactly once (less strictly, values with an affine type may be used at most once). Thus, if you, for example, ask for “a copy of this linearly-typed array whose first element is modified”, you are spending your one and only use; nothing else can ever use your original array. As a result, the implementation can perform the update in-place, without copying. An O(n)O(n) copy turns into an O(1)O(1) update, but crucially, no observable side effects occur.

In general, invariants about programs in a language can be used to perform effectful optimizations, though I do not claim here that this makes it easy (or possible) to recover the performance of a plain effectful algorithm.

On “Mainstream”

It’s one thing to construct a language for formal verification. It’s a whole other thing to construct a mainstream language that accomplishes the same goal. Breaking into the mainstream is difficult in its own right, but for formal methods there are additional challenges.

I think it’s fundamentally true that proving program properties requires more precise and rigorous thinking; this is an inherent requirement to show that a property holds in all possible cases or for all possible inputs. I think that this creates an inherent barrier to entry. LLMs can, of course, take care of this thinking — we have clearly seen evidence of this in mathematics! But in leaning heavily in this direction, you may be inventing a language that is not intended to be read by humans. This is another defensible direction given the current climate and the analogy to assembly/compilers (how many people know nowadays to read assembly fluently?), but it is a choice that should be made deliberately.

  • open question: if your language goes mainstream, who writes it, who engages in formal verification, and who reads the results? Where should the balance fall when choosing between human and machine?

Separately, there is the matter of interoperability. A novel language fighting for adoption is at a significant disadvantage when it comes to its ecosystem. A programmer taking Python off the shelf can pip install packages for LLMs, machine learning, statistics, and virtually anything else under the sun. The user of a new language rarely has such a luxury — unless it can interoperate with other languages. But in the context of formal verification, interoperability becomes more than a matter of technical implementation: it may require that your formal system can reason about the semantics of the interoperating languages, too. If your goal in inventing a new language is to build up a small and stable foundation, having to reason about the semantics of (say) Python directly undermines that goal and forces you to ask: “if I have to think about Python’s [say] semantics, why don’t I just create a formal verification framework for Python, instead of a new language?”

  • open question: how does your language handle interoperability? Do you try to reason about the correctness of other-language dependencies? If yes, why use your language? If no, can real-world, “not-invented-here” software still be verified? How?
A note on domain-specificityYou may decide to invert the dependency: rather than your language using other languages, you may want it to be called into as a dependency. This places the burden of “reasoning about foreign language semantics” on the callers (like Python). This is another viable direction (perhaps we need specific languages for formally-verifying critical components, as has been the idea behind Cryptol , for example). However, it is important to note that this defeats the purpose of “interoperability as an adoption mechanism” — in taking this stance, you are still constructing a language for which common libraries, some of which have seen thousands of engineer-hours, need to be re-implemented, and this will very likely be a barrier to adoption.

More on our Tools

I will now finally give a deeper overview of the three sorts of logic that I have called out as relevant for our purposes.

Temporal Logic

As the name might suggest, the class of temporal logics (indeed, itself a subset of modal logics) deals with statements about events in time. Most commonly, logical expressions like “this and that” or “if this then that” are extended with an additional modality (kind of like an operator) that makes what was to be read as “something” instead say “always something” or “eventually something”. Thus, instead of simply making claims about what’s true “right now”, you can make claims about the behavior of your system as it evolves. This is useful for proving behaviors such as eventual consistency for distributed systems (indeed, a canonical use case of TLA+ is the validation of the Paxos consensus algorithm). For example, here is a claim stated in temporal logic:

□(acquire(m)  ⟹  ◊release(m)) \Box(\text{acquire}(m)\implies\Diamond\text{release}(m))
联系我们 contact @ memedata.com