r/ProgrammingLanguages • • 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

23 Upvotes

39 comments sorted by

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.

5

u/reflexive-polytope 28d ago

Runtime bounds checks are what I call "artificial safety" in the post. I don't want artificial safety.

Not sure what you mean by "higher-order" length calculations.

I'm purposefully aiming for a first-order language. No first-class functions, no objects with virtual methods, no function pointers, no dynamic dispatch in any form.

12

u/alphaglosined 28d ago

It's not artificial; it prevents bad things from happening as a last resort and is substantially better than the alternative of just letting the program get into a corrupt state. These runtime checks, including null deref, bounds check and so on, are all very useful because after this point we can observe that a given fact must be true, so it feeds into the analysis implicitly. But the user can write their own by using say an assert expression to express their own facts which you have started to see as being useful.

What I refer to when I say higher-order length calculations is you are not dealing with simple constants, but you are dealing with sentinels and relations to determine what the current state is. A length-calculation delta for a given object would come under that.

Yes, any kind of function pointer makes interprocedural analysis substantially harder; it's very lossy as a synchronisation point. However, you still require interprocedural analysis because you support functions, and that is still an active area of research in the abstract interpretation domain.

Oh and for reference I have written in a production compiler a static analyzer doing stuff like null deref and bounds checks.

5

u/reflexive-polytope 28d ago

IMO, a wrong program is a wrong program. The exact way in which it's wrong doesn't really matter.

Safety does matter to me, but not for its own sake. Safety matters to the extent that it can become a part of your program's proof of correctness.

For example, you can do case analyses using algebraic data types and pattern matching. But you can also do case analyses using Java-style subclasses and instanceof. From the point of view of mere safety, neither is better than the other. But only pattern matching gives you exhaustiveness checks, which feed into the program's proof of correctness.

For another example, you can prevent data races with Rust's borrow checker. But you can also mitigate the consequences of data races with Java's OOTA guarantee. Again, from the point of view of mere safety, neither is better than the other. But only data race freedom lets you build library abstractions that can't be broken by data races, which again feed into a concurrent program's proof of correctness.

I don't support any kind of recursion other than tail self-recursion (not even tail mutual recursion!), so I only need to analyze one function at a time.

5

u/alphaglosined 28d ago

There is two things in there that I really need to correct you on.

In regard to Rust, the borrow checker does not introduce any guarantees; it could be removed, and you would still have no data races. This is because the guarantees come the ownership transfer system, who by default have very strict rules around aliasing. The borrow checker's job is to relax these restrictions to allow more code to be valid. A lot of people have a very poor understanding and mix these two features up.

The second is about function analysis, if you support analysing one function, and feeding information from that function into another function's analysis, that is called interprocedural analysis. Behaviours like cyclicity do not define interprocedural analysis, it is solely defined by the fact that you have information crossing the function declaration boundary. You can have an acyclic graph of functions and still analyse it interprocedurally not just intraprocedurally.

1

u/reflexive-polytope 28d ago edited 28d ago

Rust's absence of data races absolutely comes from the borrow checker. Without the borrow checker, you create two mutable references to the same thing, then move each reference to a different worker thread, and then you'd have your tasty data race to enjoy.

Also, checking arithmetic conditions doesn't have to be "interprocedural analysis". At least no more than type checking already is.

If you define a procedure foo that takes a string argument, and then indeed enforce that every caller passes it a string argument, do you call it "interprocedural analysis"?

Well, my partition procedure takes an int slice[n] argument with a constraint that n > 0.

It's not "interprocedural analysis". It's just ordinary dependent type checking.

EDIT: s/intraprocedural/interprocedural/g

5

u/alphaglosined 28d ago

Rust's absence of data races absolutely comes from the borrow checker. Without the borrow checker, you create two mutable references to the same thing, then move each reference to a different worker thread, and then you'd have your tasty data race to enjoy.

Remove the borrow checker, then you can't create two mutable references either. Because the ownership transfer system moves the reference leaving the old value back to init rather than copies. If you try to pass it by-ref it is an error. Aliasing simply doesn't exist in an ownership transfer system unless you break it.

If you define a procedure foo that takes a string argument, and then indeed enforce that every caller passes it a string argument, do you call it "interprocedural analysis"?

No, that is type checking and happens before static analysis takes place as part of semantic analysis.

Well, my partition procedure takes an int slice[n] argument with a constraint that n > 0.

If that is a static array, then that is part of the type system. If instead it is a slice or a pointer, then no, that is contract-based programming and that comes under interprocedural analysis as you would have no way to evaluate the input contract.

For anyone who is reading this, I suggest reading Principles of Abstract Interpretation by Patrick Cousot, he is the person who coined the term 50 years ago.

3

u/Kaisha001 27d ago

For anyone who is reading this, I suggest reading Principles of Abstract Interpretation by Patrick Cousot, he is the person who coined the term 50 years ago.

Thank-you! I was just going to ask if there was any additional reading material around this :)

1

u/reflexive-polytope 28d ago edited 28d ago

Remove the borrow checker, then you can't create two mutable references either. Because the ownership transfer system moves the reference leaving the old value back to init rather than copies.

You don't create the second reference by copying the first one. That's indeed impossible because &mut T isn't Copy.

But, without the borrow checker, you can create the second reference directly from the object being referenced:

let mut foo = ...;
let x = &mut foo;
let y = &mut foo;
use(x, y);

The borrow checker is the one that prevents this.

If that is a static array...

It's not. It's an ordinary runtime array slice. The slice's type includes the length, and the length itself is also a runtime value.

Of course it needs a dependent type system.

1

u/flatfinger 27d ago

I would view many programs and subprograms as having two primary requirements:

  1. Behave usefully when able.

  2. When unable to behave usefully, behave in a manner that is at worst tolerably useless.

In some circumstances, code which receives invalid input might be able to usefully report that the input is invalid. In some other circumstances, however, the best possible outcome would be "tolerably useless", and a wide range of possible behaviors would satisfy that requirement essentially equally well.

Program execution could thus be viewed as having five possible states:

  1. The program might behave usefully and hasn't done anything that is intolerably worse than useless (IWTW).

  2. The program has behaved usefully and would be incapable of doing anything IWTW.

  3. The program cannot behave usefully, but might avoid doing anything IWTW.

  4. The program cannot behave usefully, but would be incapable of doing anything IWTW.

  5. The program has done something intolerably worse than useless.

Some people would view #3-#5 as equivalent, but many sets of application requirements often treat #5 as very different from #3-#4.

2

u/reflexive-polytope 27d ago

Your classification is way too complicated for me. I'm sorry, but I can only hold so much complexity in my brain.

My classification is simpler: the program is correct or it's wrong for a given specification.

And, from a type checker's point of view, the specification is that the program must have a well-defined behavior.

1

u/flatfinger 27d ago

The basic idea is that if a program has received inputs that would make it impossible for it to behave usefully, it would still matter for many purposes whether the program can avoid doing anything that is intolerably worse than useless.

1

u/reflexive-polytope 27d ago

If the program takes input from the user, then it's the program's responsibility to check that the input is valid before using it.

On the language side, the compiler's responsibility is to check that the program has a well-defined behavior.

So, for example, if array indexing only has a defined behavior at valid array indices, then the compiler must check that the program always indexes at valid indices. If the compiler can't prove this using the information supplied by the programmer, then the compiler must reject the program altogether.

1

u/flatfinger 27d ago

Many tasks involve processing a mixture of correct inputs and nonsense. For example, a program which is supposed to determine whether a directory contains any JPEG files satisfying certain criteria might expect to receive a mixture of JPEG files that satisfy the criteria, JPEG files that don't satisfy the criteria, things that don't look anything like JPEG files, and things whose bit patterns happen to resemble JPEG files but actually represent something else entirely. If the answer to the question "Is this a JPEG file that satisfies the criteria of interest" can be answered "no" is less time than it would take to answer the question "Is this a valid JPEG file", then it might make sense to answer "If this thing were a JPEG file, might it satisfy the criteria" before validating the input.

1

u/reflexive-polytope 27d ago

A programming language implementation doesn't have to care about this or that file format or network protocol. It cares about the language's basic operations, such as array indexing, and the conditions under which you may safely perform them. How on Earth you prove your indices are valid is largely your problem, not the compiler's. That's why you have to annotate your inductive invariants.

Think about the analogous situation for basic arithmetic operations. The language only cares that arithmetic operations can only be performed on numbers. How on Earth you come up with those numbers is your problem, not the compiler's.

→ More replies (0)

1

u/tending 27d ago

I'm purposefully aiming for a first-order language.

Why? This is incredibly limiting. You can't handle callbacks!

2

u/reflexive-polytope 27d ago

I prefer first-order state machines (states are abstract types and state transitions are exported functions) to higher-order nonsense like callbacks and recursion schemes.

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 xs

An 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 prf

EDIT: 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, obtaining e2 >= e1. But you can't negate an integer equality e1 = e2, because the equality itself is just the conjunction of e1 <= e2 and e2 <= 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 = 0 is equivalent to the disjunction of the equations x = 0 and y = 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 = 3 and val 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

u/reflexive-polytope 27d ago

Thanks! DM sent.

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 the FooArray that the program is going to read in from foo.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 the Foos 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 of Foo[N], where N is 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 foos are 0 .. N-1.

There's still a check that n < N in the runtime - but only in one place - the test whether to continue looping or not - we shouldn't need to check again N times that foos[n] is invoked.

What we're really trying to test is, the type of n must be a subtype (<=) of the type of N, which is true if n < N due to 0-based indexing, and ideally we want to infer the type of n from for (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 if N = 0, the type of n would not be a subtype of the type of N, but a supertype of it - accepting 0..SIZE_MAX due to overflow. All these additional runtime checks on arithmetic operations may end up being more expensive than runtime bounds checks on subscripting.

2

u/phischu Effekt 26d ago

Super interesting! I might steal it in the future. Great stuff!