# How to compute whether it is guaranteed the variable is set?

Assuming declarations are expressions consider such code:

``````if ((var x = foo()) and (var y = x)) or (var z = bar()) then
println(z);
end
``````

The reference to `x` is OK, because at this point `x` has to be set, but the reference to `z` (in `println`) is not. It can be valid or not.

I would like to compute those two "states" of variables -- whether it is OK to reference variable (it is guaranteed it is set) or no (it is not set for sure, or it is maybe set).

How to do it?

Update: I found this wiki page https://en.wikipedia.org/wiki/Definite_assignment_analysis and I think my case is much easier. I need to keep track of 4 kinds of flow -- and, or, xor, next (comma operator, from predicate to body). I hope I am right :-)

## 1 Answer

What you're asking about is a form of data flow analysis. The code could be translated into some form of basic blocks (or other intermediate data structure). There will be flow of control (branches) associated with the AND and OR expressions in the if-condition-test (as well as branches associated with skipping around the then-part). The basic blocks are analyzed to generate and use a data structure that has one bit of state for each variable that says whether it is initialized or not.

If there's potentially loops in the basic blocks being analyzed things get more complicated, you may have to iterate (e.g. until no changes).

When basic blocks merge (i.e. from the "or"), or after an if-then or if-then-else, then you effectively AND these bits together, such that when a bit for a particular variable on one of the merging paths is clear, then the result at the merge is that the bit for that variable is clear. Whenever a variable is used (i.e. in your case as in the then-part) you check the current status of the bit for that variable and report error if the bit is clear.

• Yes, thank you, I know that, I am looking for something ready (or almost ready) to implement -- I am sure I am not the first one who faces this problem :-) Book reference is fine as well. Mar 26, 2016 at 17:21