Idea: Figuring out lifetimes by example


#1

Could a tool / compiler plugin be devised which would help figure out lifetime annotations by working backwards from example,

I get the impression polymorphism especially demands lifetimes: The declaration must bound future potential uses, aswell as potential use with vtables with no known callgraph.

In the case of a static call graph and concrete code, it seems like it should be able to figure out more from whole-program knowledge? - but even then, the up-front bounds might make the error messages more workable.

e.g.

step 1: write declarations without lifetime annotations… the compiler has no idea whats going on.
step 2: you write concrete test-cases that do something,
step 3: the compiler/tool works backwards from the example to report ‘what the annotations would have to have been, for the given tests to work’

(“this example breaks the 'self assumption; as such you’ll need to add blah blah blah for it to have worked.”)

the examples would of course have to be well thought out to be exhaustive.

The idea here is that sometimes rust is trying to figure something out in isolation, but we can and do create broader context (… e.g. often we are going to write tests and example code for other purposes: Given an overlapping set of demands. )

(* … as I write this, I wonder if this sort of approach could be extended to assist with trait bounds generally…
e.g. r.e error messages: C++ templates are not so hard to write, because you can do them by example: “here’s a test case showing how it works with one concrete set of types: this establishes the pattern, later we will substitute other types in…”… a viable workflow is basically 'write something with concrete types , then stick ‘template’ infront of it '. The example documents what methods/functions are expected.


#2

Do you mean that by looking at the usage of generic code, rustc could make more insightful suggestions about traits and lifetime bounds than it currently does by looking at the implementation alone? If so, I agree that this would be a great idea, provided of course that this can be done without exponentially increasing compilation times :slight_smile:


#3

provided of course that this can be done without exponentially increasing compilation times

What I have in mind here is an interactive intermediate step/assist toward writing the annotations.

“here’s some un-annotated code, but in C++ it would compile and run and do something, and get through these empirical tests…
… so lets use that to help figure out what the annotations would have to have been to compile in Rust”