[p-dev] Variable scoping

Paul Bone paul at bone.id.au
Mon May 20 23:55:57 AEST 2019


At the moment variable bindings work like:

    x = ...
    print!(x)   % We can use x here.

The variable must be bound before it can be used.  It's available lexically:

    x = ...
    if (...) { 
        print!(x)   % We can use x here.
    } else {
        ...
    }

And it's reasonable that:

    if (...) { 
        x = ...
        print!(x)   % We can use x here.
    } else {
        ...
    }
    % print!(x)   % ERROR, x is unknown

Unless the else block has a return or throw (doesn't exist) or also binds x.
So:

    if (...) { 
        x = ...
    } else {
        x = ...
    }
    print!(x)   % We can use x here.

But it was pointed out to me that this is unintuitive, by more than one
person.  In my own experience this is okay (it's how Mercury works, and no
one seems to worry about it / notice it there).  But maybe due to the
different style of syntax there are different expectations for this.

The main counter-proposal I have is:

    var x
    if (...) { 
        x = ...
    } else {
        x = ...
    }
    print!(x)   % We can use x here.

Which seems to be how many other languages work, so at least people can have
reasonable expectations.  And I've thought about this problem off-and-on for
the last few years and I'm now leaning fairly strongly for this option.

Good: Familiar
Good: Actually makes some compiler internals easier, but that's minor.
Good: Makes rules about scoping easier to describe/understand, especially
      WRT other bindings like module importing.
Bad: More verbose than necessary
Interesting: "var" is a weird keyword for something that doesn't vary.  But
             I think here's where we make another pragmatic choice and do
             call them variables.
Interesting: We need a new type of error for the case that a variable is
             introduced but not yet bound.
Interesting: May lead to other syntax forms for state variables,
             accumulators, etc. (this is good)

My previous argument for not doing this was "It shouldn't be necessary" and
"you'll get used to it".  They're not very good reasons.  I can't think of
any strong reasons for not doing this.

Thoughts?


-- 
Paul Bone
http://paul.bone.id.au


More information about the dev mailing list