Accessibility levels and local procedure variables lifetime

Viewed 72

I do not understand accessibility levels, while watching tutorial videos from AdaCore, in particular this one: https://youtu.be/nfBwXxAf7UE?t=1418

The example is as follows:

type An_Access is access all Integer;
procedure Proc is
    W : aliased Integer;
    X : An_Access := W'Access;
begin
    null;
end Proc;

The tutorial says "X is of accessibility level 0, W is of accessibility level 1. Allowing this declaration would permit reference to the object outside of the scope."

Why would the point at which the access type is declared affect the access variables in different scopes? I mean, both W and X are local to Proc and will go out of scope and will not be usable once Proc is finished. So why would it matter, where the type of X is declared?

2 Answers

The primary reason is simplicity. The existing rule is easy to understand (you clearly understand it) and easy to implement. The data-flow analysis required (to distinguish between acceptable and unacceptable uses in general) is complex and not normally necessary for a compiler, so it was thought a bad idea to require it of compilers.

Another consideration is Ada's compilation rules. If Proc passes X to another subprogram declared in another package, the data-flow analysis would require the body of that subprogram, but Ada requires that it be possible to compile Proc without the body of the other package.

Finally, the only time* you'll ever need access-to-object types is if you need to declare a large object that won't fit on the stack, and in that case you won't need access all or 'access, so you won't have to deal with this.

*True as a 1st-order approximation (probably true at 2nd- and 3rd-order, too)

In Ada, when you try to think about accessibility, you have to do it in terms of access types instead of variables. There's no lifetime analysis of variables (contrarily to what Rust does, I think). So, what's the worst that could happen? If your pointer type level is less than the target variable level, accessibility checks will fail because the pointer might outlive the target.

I'm not sure what goes on with anonymous access types, but that's a whole different mess from what I pick here and there. Some people recommend not using them at all for variables.

Related