TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: Is it possible to perform compile-time checks for all invariants?

2 点作者 blenderob3 个月前
Static typing helps with compile-time checks for types. I&#x27;d like to know from the community here if it&#x27;s possible to check for other types of invariants at compile-time?<p>Let&#x27;s say, I&#x27;ve got a function increase_balance(increment_value: int) but instead of allowing all possible integer values, I want the compiler to check that anytime this function is called, it is called with increment_value in the range 1 to 10000.<p>Is it theoretically possible to do such checks at compile-time? I mean the compiler has to check every code path and verify that all code paths leading to increase_balance() leads to value that is neither &lt;= 0 nor &gt;= 10001. Is this is a problem that can be solved at compile-time? Does any programming language provide such features?<p>While I&#x27;ve your attention, are there other such invariants you&#x27;re aware of that can be checked during compile-time?

4 条评论

KsassPeuk3 个月前
In all its generality, the problem is undecidable. But there are quite a lot of tools that are meant to formally verify properties about programs. Proof assistants, of course, but there are also tools for more mainstream languages, like Frama-C, Ada&#x2F;Spark, Java&#x2F;KeY, Creusot (Rust), etc.
edwcross3 个月前
It _is_ possible to do some checks at compile time, but not for all programs. Or, you can check all programs, but only be _sure_ about your results on some of them. Or, you can add some constraints and force the programmer to write extra information so that you can make it work on more programs.<p>Overall, there&#x27;s no free lunch: somewhere, someone will have to do some extra work.<p>Other useful invariants include some RAII idioms, Rust memory checks, resource usage (e.g. locks), etc.
stefanos823 个月前
I could be wrong, but I have the impression what you are looking for is how constexpr and consteval work in C++ <a href="https:&#x2F;&#x2F;en.cppreference.com&#x2F;w&#x2F;cpp&#x2F;language&#x2F;consteval" rel="nofollow">https:&#x2F;&#x2F;en.cppreference.com&#x2F;w&#x2F;cpp&#x2F;language&#x2F;consteval</a>
Davidbrcz3 个月前
You can look into theorem proover (Coq, lean ...) and code extracted from them. A middle ground is FramaC+WP plugin for hoare logic for C.<p>Some languages like F* are also proof oriented.