Search code examples
compiler-constructionstatic-analysiserror-detection

Automatic compiler detection of the addition of the same object instance to a container in a loop


This is a dumb mistake:

List<Foo> fooList = new List<Foo>();
Foo f = new Foo();
while (something.Read()) {
    f.Fill(something.GetRecord());
    fooList.Add(f);
}

Of course, I should instantiate a new Foo inside the loop.

Can a compiler detect this kind of mistake at compile time?

To naïve eyes it looks like it should be able to detect this behavior (filling a List with instances of the same object in a loop). It should then issue a warning like "You are filling a container with the same instance more than once.".

So, how naïve am I being? Do you know of a language where something like this exists?


Solution

  • Yes, this is possible.

    However, I don't think a tool or compiler would warn about this themselves, so you'd have to use a tool which can be extended with your own analyses. For Java, FindBugs is such a tool. For C,C++, etc, gcc 4.5 will allow plugins for people to write their own extensions, and clang from LLVM is designed for this too. There is also Dehydra from Mozilla, again for C++. For MS languages, there is the Phoenix framework.

    So the question is, how do you write this analysis? Thats a little more tricky, and depends on the tool. But basically:

    • you can detect loops fairly easily (look for "Strongly-connected components"),
    • alias analysis can tell you if a particular variable or parameter refers to just one object, or many objects (look for "abstract objects", perhaps),
    • you can find the right container using the static type of an object or variable.

    So you could quite easily detect a call to List<>.append(x) in a loop, where x can refer to only one object.