r/ProgrammingLanguages • u/reflexive-polytope • 28d ago
Index safety with proofs NSFW
I'm still investigating how to index array safely without runtime bounds checks. In my previous attempt, I tried not to use any programmer-supplied proofs whatsoever. In my current attempt, I accept that sometimes programmers have to supply hints to the type checker, but I try to find out how to keep the hint annotations to a minimum.
https://gist.github.com/eduardoleon/dfb47b0662d9eeaa3304bd0b53b4dbc1
7
u/SwingOutStateMachine 27d ago edited 27d ago
Are you familiar with dependent types? Encoding valid values in a type system is a common approach, and through that, you are able to show that a program is correct by construction.
For example, one could define an "Finite" (Fin)S type that is provably always less than a given bound, and use that to index into an array type:
-- Taken from Idris' standard library
data Fin : Nat -> Type where
FZ : Fin (S n)
FS : Fin n -> Fin (S n)
index : Fin n -> Vect n a -> a
index FZ (x :: _) = x
index (FS i) (_ :: xs) = index i xsAn alternative approach (again, in Idris) is to provide a proof that some argument is less than another argument, which I think is more what you are proposing. In this example, however, it is the programmers responsibility to pass said proof into the function:
index : (i : Nat) -> Vect n a -> LT i n -> a
index Z (x :: _) (LTESucc _) = x
index (S i) (_ :: xs) (LTESucc prf) = index i xs prfEDIT: I forgot to mention, there does need to be some sort of runtime checking, but this can be "hoisted" to the top level of a program where possible. Idris does this through the isLTE method (on Data.Nat), which provides a Dec (LTE n m) - i.e. a potential proof that n < m. It is possible to pattern match on Dec, and if a valid proof is there, continue with the rest of the program (or otherwise report an error, or some other application-specific logic).
8
u/reflexive-polytope 27d ago
I am familiar with dependent types. I even said "I'm looking at you, Ltac!" in the post, which outs me as a Rocq user.
In fact, I know that I'm designing a dependent type system. But I'm making a different tradeoff from the usual suspects (Agda, Rocq, Lean, etc.)
Instead of expressing arbitrary mathematical propositions in types, I'm sticking to propositions for which inference is possible in the vast majority of cases, and minimal proof hints are needed when unguided inference isn't possible.
What I'm using so far is the conjunctive, quantifier-free subset of linear integer arithmetic, with negation restricted to inequalities. That is, you can negate
e1 < e2, obtaininge2 >= e1. But you can't negate an integer equalitye1 = e2, because the equality itself is just the conjunction ofe1 <= e2ande2 <= e1, so by De Morgan its negation is a disjunction, which I purposefully don't allow.3
u/SwingOutStateMachine 27d ago
I even said "I'm looking at you, Ltac!" in the post
Ah, I missed the reference, my bad!
Your approach does sound interesting indeed. I would be interested in the underlying theory that makes inference possible - and particularly proofs that it is indeed sound and complete.
As a total aside, I wonder if it would be possible to generically identify fragments of logic that allow for total inference, and then extend that into type systems for domain specific languages.
1
u/reflexive-polytope 27d ago
I don't know enough mathematical logic to answer your last question, so I conservatively use the principle that logical refinements mustn't be able to express a disjunction. If you want to express a disjunction, you have to use algebraic data types, and the type checker will never perform a case analysis that isn't explicitly written as a pattern match in the source code.
For example, I can't support multiplication in type-level arithmetic, because the equation
xy = 0is equivalent to the disjunction of the equationsx = 0andy = 0, neither of which is a more general solution than the other. More generally, from a geometric point of view, the solution space of a system of polynomial equations needn't be irreducible, and each irreducible component is a maximally general solution that's not subsumed by the union of the others.But I can support nonstrict linear inequalities in type-level arithmetic, because a system of nonstrict linear inequalities has a unique most general solution over the rationals, which is a polyhedron (or empty). If you try to express a polyhedron as a finite union of nested polyhedra, then one of these nested polyhedra will be your original polyhedron anyway.
Then, to “deduce” a nonstrict linear inequality is to express it as a positive linear combination of the known nonstrict linear inequalities in the typing context, and to refute it is to produce a Farkas certificate that your nonstrict linear inequality isn't a positive linear combination of the known ones.
2
u/ryo33h 27d ago
Interesting tradeoff! im working on a language that allows general propositions with explicit, kernel-checked proofs, and refinement types. Do you see any downsides to keeping the logic unrestricted?
4
u/reflexive-polytope 27d ago
Manually proving arithmetic trivialities is tedious enough that it's a major barrier to adopting dependent types in systems programming. That's why I highly value automation, i.e., inferring as much as possible of the proof that the program has a well-defined behavior.
If you have several proof strategies available at any point, then your type checker has to make a decision: which proof strategy do I use right now? This decision shouldn't depend on contingent facts, such as the order in which your hypotheses were introduced into the typing context. Because, with such a dependency, your type checker's answer becomes non-canonical in a way that's surprising to the programmer.
For example, if you define
val x = 3andval y = 4, then it's “obvious” that the order of these definitions doesn't matter. So you would be surprised if swapping these definitions caused the type checker to infer a different type for the whole routine.These are my main reasons for restricting the logical expressiveness of a dependent type system. If you don't care about automation, or if you don't care about the canonicity of the type checker's answer, then you can afford to use a more expressive system.
2
u/ryo33h 27d ago
What about a built-in arithmetic solver like Lean 4's omega, and rejecting programs when it can't prove the required properties? I haven't tested how it's capable, though. Would that address your concerns?
3
u/reflexive-polytope 27d ago
That works under two assumptions:
First, that I don't mind the atrocious time complexity of deciding arbitrary linear arithmetic statements (possibly containing disjunctions). I do.
Second, that I never, ever, ever plan to extend the type system with anything else. The fact that I'm using quicksort as a test case says otherwise. I also have the theory of strict weak orderings (not necessarily on the integers) in sight.
4
u/Diffidente 27d ago
In my PL called Lain I'm investigating how to remove runtime checks in array accesses. And, unlike Rust, I was able to remove them in the case of inequalities such as ±x ± y <= c thanks to the Octagon Abstract Domain (Miné, 2006). Feel free to DM me, I'll link to you a Linekdin post I wrote on this.
1
3
u/6502zx81 27d ago
I think you'll always need help from the programmer. Since real programs do I/O only they can tell what ranges values fall within.
5
u/reflexive-polytope 27d ago
That's not a problem per se. Data obtained from the user should be checked at runtime anyway. The type system can record the fact that the check has been performed.
1
u/Inconstant_Moo 🧿 Pipefish 27d ago
But this isn't going to let the compiler know in advance how many
Foos there are in theFooArraythat the program is going to read in fromfoo.csv.5
u/reflexive-polytope 27d ago
Obviously, a compiler can't know in advance the contents of a file that you're reading at runtime. But if, for example, you need there to be between 5 and 293
Foos, the compiler can force you to write the check, and to only operate on theFoos if there are indeed between 5 and 293 of them.5
u/WittyStick 27d ago edited 27d ago
Consider it like,
readFoos()returns a type ofFoo[N], whereNis a variable in the type system - some refined unsigned integer type. The compiler doesn't need to know what the value of N is though.If we attempt to say
foos[N] = readFoos(); do_something(foos[10]);The compiler can reject this program, because it doesn't have any way to know
10 <= N. However, if we trivially check beforehand:foos[N] = readFoos(); if (10 <= N) do_something(foos[10]);Then the compiler can accept this program. It doesn't need to do a runtime bounds check on the subscripting operation
foos[10], because a check has already been done by the programmer.
Foo[N]is obviously a dependent type - it depends on a runtime value.More realistically, you would have something like:
for (n = 0; n < N; n++) do_something(foos[n]);But if we accidentally wrote:
for (n = 0; n <= N; n++) do_something(foos[n]);The compiler should be able to detect the off-by-1 error, because the only valid indices of
foosare0 .. N-1.There's still a check that
n < Nin the runtime - but only in one place - the test whether to continue looping or not - we shouldn't need to check againNtimes thatfoos[n]is invoked.What we're really trying to test is, the type of
nmust be a subtype (<=) of the type ofN, which is true ifn < Ndue to 0-based indexing, and ideally we want to infer the type ofnfromfor (n = 0; n < N; n++)to avoid annotating it - though if we were annotating it we could perhaps use:for (typeof(N) n = 0; n < N; n++).We basically want to extend flow-sensitive typing to include dependent types.
One issue is we would necessarily need checked or saturating arithmetic, or require the programmer to check each arithmetic operation. Without, if we wrote
for (n = 0; n < N - 1; n++), then ifN = 0, the type ofnwould not be a subtype of the type ofN, but a supertype of it - accepting0..SIZE_MAXdue to overflow. All these additional runtime checks on arithmetic operations may end up being more expensive than runtime bounds checks on subscripting.
14
u/alphaglosined 28d ago
I would suggest starting with the runtime checks, then using the abstract interpretation to prove that they are not necessary.
This way, you get all possible safety improvements.
But even so, it does appear that you're figuring out some of the higher-order length calculations, which is impressive, even if what you demonstrated is only intraprocedural.