New scope solution

@PetrKryslUCSD, based on your suggestion and the many excellent problematic examples in this thread—thank you, everyone who posted of nasty corner cases—@jeff.bezanson and I are currently leaning towards the following rules:

  • if the first use of x on every path is a read, then x is global
  • if the first use of x on every path is a write and there’s a read somewhere, then x is local
  • otherwise x must have an explicit local or global annotation

This is a bit breaking since some code that previously worked will now error because it needs an explicit local or global annotation, but since we were willing to make a much more breaking change previously, that isn’t the end of the world. Although we would, of course, have to assess the extent of the change.

This rule is both less clever and less brittle than the original idea in the first post of this thread. Most of the brittleness and possibly confusing cases in the thread seems to be much better under these criteria. The common accumulator examples are read-first, so they make the accumulator global by default and therefore work. Cases where someone writes a variable and uses it later in the local scope continue to work as they currently do, defaulting to local, thereby avoiding leaking these variables as globals. Examples where a global is used in a write-only fashion inside of a loop require an explicit global annotation in order not to error, which makes them less brittle in case you insert a debug read. We could make an exception for the write-only case and default to global, but as has been pointed out, that’s quite dangerous since putting an innocuous-seeming debug statement then changes the behavior. It’s also quite easy to delete the last use of a local but forget to remove the initialization, which would, under a “write-only is global” rule make it accidentally global—oops! On the other hand, this proposal would give a clear error message instead, prompting you to explicitly annotate the variable as global or local—or delete the unused assignment.

Further hole-poking and counter-examples are welcomed!

26 Likes