Skip to content

add function scope option to the set command #565

Closed

Description

@xiaq

Doc of set builtin says:

The scoping rules when creating or updating a variable are:

  1. If a variable is explicitly set to either universal, global or local, that setting will be honored. If a variable of the same name exists in a different scope, that variable will not be changed.
  2. If a variable is not explicitly set to be either universal, global or local, but has been previously defined, the previous variable scope is used.
  3. If a variable is not explicitly set to be either universal, global or local and has never before been defined, the variable will be local to the currently executing function. Note that this is different from using the -l or –local flag. If one of those flags is used, the variable will be local to the most inner currently executing block, while without these the variable will be local to the function. If no function is executing, the variable will be global.

The upside is that well-known global variables ($PATH, $EDITOR, etc.) can be set within functions without an explicit -g. However, the behavior of the following function can be confusing:

function f
    set var val
end

If the user has a global variable named var, this function alters the global environment. Otherwise it has no impact on global environment. To make the function safe one has to always write

function f
    set -l var val
end

which is quite tedious. Therefore I propose that set should always imply function scope within functions.

Activity

  1. xiaq commented on Feb 7, 2013

    @xiaq
    ContributorAuthor

    Oops. Things are actually more confusing here. -l doesn't always put the variable in the function's scope, it puts it in the innermost scope.

  2. xiaq commented on Feb 7, 2013

    @xiaq
    ContributorAuthor

    Description updated. (imply -l -> imply function scope)

  3. JanKanis commented on Feb 7, 2013

    @JanKanis
    Contributor

    I came across this apparent inconsistency as well (see bug #482), and I considered proposing to change the scoping rules. But after thinking everything through I decided against it as I could not come up with better rules.

    It also has to do with whether the shell language is optimized for writing scripts or for interactive use. Optimizing for writing scripts, I also think that the default for set should be some scope within the function rather than global or universal. But optimizing for interactive use, I think the default for a bare set within a function should be the same as set outside of a function. It should be easy to take a piece of shell code that was previously bare and wrap it in a function. I suspect that the large majority of fish functions written are small functions written by shell users to modify their environment in some way, rather than the complex functions that are part of the shell distribution.

  4. cben commented on May 9, 2013

    @cben
    Contributor

    I think we can still do a tiny bit better while retaining this 2 axioms:

    1. set PATH ... within a function should modify global PATH.
    2. set foo ... within a function should make foo local.

    First, is block-local useful for anything?
    Python only does function scope, which is more convenient because it allows stuff like:

    if ...
        set foo bar
    else
        set foo baz
    end
    use $foo ...
    

    The only use I see for block scope is temporarily changing an env var with set -l -x but env covers 90% of that use.
    So I'd just change set -l to mean function scope.
    If not, let's expose function scope with set -f. People writing robust functions should have access to it without the risk of the default set foo behavior that you'd modify a global/exported foo if one exists.

    Second, this dilemma where just set foo mostly works but is a little bit unsafe reminds me of bash's $foo-vs-"$foo" dilemma. Could we have a safe well-defined default?
    So here is a radical idea: case sensitive default! (Somewhat inspired by Ruby)

    • set lowercase sets a function-local var.
    • set UPPERCASE sets a global [exported?] var.
    • Don't think we want a third meaning for set MixedCase. Could be a global non-exported var but I've never seen mixed case in shell scripts.
      Of course you'll still be able force any scope with a flag.
  5. dag commented on May 11, 2013

    @dag
    Contributor

    This is a tough one. Some observations:

    • It could be confusing if set inside a function behaved differently from outside a function.
    • But it can also be confusing that set inside a function can alter global variables.
    • Having to "declare" all your variables with set -l (one line for each!) in every function is... perfectly sane for a programming language, but a bit obnoxious for shell scripting.
    • That lengthy and involved description of the scoping rules is an indicator that the design is overly complex.
    • A special function scope that you can't ask for explicitly is troublesome.
    • Block-local scope (set -l) may or may not actually be useful in a shell.
    • Case sensitivity doesn't really work in Ruby and wouldn't really work well in a shell either, and would only make things more confusing and complex I think.

    Straw man proposal: Only have one scope, "local to execution context". In a function this is function scope, outside it is global scope. set -g can then be explained as "set in the outermost execution context".

    Potential problem: Arguably "context" and "scope" is the same thing and the description above is circular.

  6. ridiculousfish commented on May 12, 2013

    @ridiculousfish
    Member

    I observe that most non-scripting programming languages solve this by separating variable assignment from variable definition. That is, separate variable creation from variable assignment. I'm not arguing that's right for fish, just that it's another possible solution.

  7. dag commented on May 12, 2013

    @dag
    Contributor

    Perhaps if we could set -l a,b,c, it would be bearable. That still leaves all my bullet points above except the third, though. It also means we have to decide what set -l a,b,c val does: error or set all? Probably set all would be most consistent and also useful in some cases.

    Hm, actually this could be useful in general:

    set -gx EDITOR,VISUAL vim
    
  8. JanKanis commented on May 30, 2013

    @JanKanis
    Contributor

    I think looking at scripting languages is a better comparison for fish. In non-scripting languages it is generally also an error to use an undefined variable, in fish and other shells that is fine. Also, in many scripting languages assigning to an undeclared variable sets the global variable. Python is an exception to that, where an undeclared variable is by default function local, but that is arguably a better choice than what other scripting languages do.

    The main reason for scoping is to allow using a variable in a function without accidentally overwriting a global variable. Block scope is very sensible for a low level language where you want to conserve stack memory usage, and there is something to say from the point of consistency with function blocks, but I don't think it adds a lot of value in a scripting language. (An exception is when closures are involved such as in Python, there block scope would imo make a lot of sense, but that doesn't matter for fish.)

    My preference if I were redesigning the scoping mechanism would be to have a single scope for functions (less scopes = less confusion), and also allow top level block structures on the global level to have their own scope. That is slightly less consistent but I think it is a win for interactive usability. If you want to use a variable in a loop you type interactively on the command line you can use local variables without worrying about leaking them, and you can safely copy-paste snippets. Within a single function accidental variable clashes are not a problem.

  9. ridiculousfish commented on May 30, 2013

    @ridiculousfish
    Member

    Block scopes interact nicely with "temporarily exporting" variables, e.g.

    begin
    set -lx SHELL /bin/sh
    vim
    end
    

    The environment variable is automatically cleared when the scope ends.

  10. alphapapa commented on Sep 11, 2015

    @alphapapa

    I'm converting another Bash script to Fish, and ran into this. I used set -l in a function, and I expected it to define the variable in the function's scope. But the set -l was also inside a while loop, so it actually defined it locally to that loop.

    This is very confusing. I'm no expert, but I can't think of any other languages that have block- or loop-local variables (that are defined inside the loop, I mean; of course there is e.g. for (( i=1; i<=steps; i++ )).

    This is so unusual that I think it should be considered a bug and changed. Defining a variable with -l inside a function should use the function's scope. If the block-local behavior is desired, there should be a separate switch for that.

  11. martin-g commented on Sep 11, 2015

    @martin-g

    Java/Scala has block level variables. JavaScript/ES2015 (aka ES6/Harmony) also supports them with let someVar = someValue.

  12. alphapapa commented on Sep 11, 2015

    @alphapapa

    Ok. And sure, there are lisps with things like (let .... But I think it is very unusual for a shell scripting language to behave this way. I don't think it's worth the extra confusion (and the resulting bugs). The unusual behavior should be enabled by a separate option.

  13. ridiculousfish commented on Sep 11, 2015

    @ridiculousfish
    Member

    Note that the default behavior of set is function scoped. You have to opt in to block scoping with -l

  14. alphapapa commented on Sep 11, 2015

    @alphapapa

    Hm, I didn't realize that. That's another way that Fish somewhat confusingly differs from Bash:

    #!/bin/bash
    
    function foo {
        bar=baz
    }
    
    echo $bar
    foo
    echo $bar
    #!/usr/bin/env fish
    
    function foo
        set bar baz
    end
    
    echo $bar
    foo
    echo $bar

    I'm sure you've given all this much more thought than I have, and I'm late to the party, I know--but I just wonder if these subtle-yet-significant differences are worth it. It seems like every time I convert a little Bash script to Fish, I run into some of these gotchas, and I'm not sure how the differences help me. :)

  15. faho commented on Sep 11, 2015

    @faho
    Member

    Hm, I didn't realize that. That's another way that Fish somewhat confusingly differs from Bash:

    For those reading along at home, that code prints "" and "baz" for bash and "" and "" for fish. Essentially, both allow for a few different levels of scoping (global and local at least), only bash is global by default (change the assignment to local bar=baz to get local).

    And quite frankly, basically every other programming language behaves like fish does, and the only advantage bash has is familiarity. But if we'd see familiarity as important, we wouldn't be doing fish.

    Now, there's a few things to change here - I'd argue for a switch to set to force function-level scope, since now code like this:

    function foo
       if true
         set bar bie
       else
         set bar drink
       end
      echo $bar
    end

    can't help but change the global variable bar if it is defined. This needs an additional set -l bar before the if, and it's ugly and a real stumbling block.

    Either that or abolish block-level scope or always shadow variables (which seems overly restrictive) or make "capturing" global variables explicit.

  16. 9 remaining items

  17. added this to the fish-future milestone on Oct 16, 2016
  18. faho commented on Oct 23, 2016

    @faho
    Member

    From @krader1961 in #3465:

    make it so set -f behaves like set -l outside of a function

    I'm ambivalent. I agree that throwing errors is not friendly. On the other hand letting people shoot themselves in the foot is also not friendly. The -l and -g flags have well defined, fairly obvious, meanings outside of a function block. The same is not true for -f. Also, what does it mean to do set -qf outside of a function? Will it return all locally scoped vars? And if so then it's not consistent with the behavior we expect inside a function. And if not then why would should set -f be equivalent to set -l outside of a function body?

    These are tough questions because they have subtle implications.

    So let's first try to answer the behavior inside of a function.

    The main issue for me there is that set -f inside of a function is the same as set -l unless you are also inside of a block. I.e.

    function banana
        set -l flounder 0
        set -f arglebargle 1
    end

    Here $flounder and $arglebargle have exactly the same visibility. It's only when you do

    function apple
        if true
            set -f haberdashery 2
            set -l humpty 3
         end
        # $humpty won't be defined here anymore
    end

    The question here is how much we want "function-scope" to be its own thing, versus just a shortcut for another scope.

    • Do local variables shadow function ones?

    They probably should, so you can do easy temporary variables. Also, it's already what happens:

    function a
        set -l a 1
        if true
           set -l a 0
           echo $a # will output 0
        end
        echo $a # will output 1
    end
    • Do function variables count as local ones?

    This is obviously a new thing because we don't currently have a way to query for function-scope.

    To me the answer is no, because if you had a function var and defined a local one, it would shadow, not overwrite it. Because it is effectively its own scope, it should really count as that.

    I've said before that a set -qfl might be nice here, to see if a variable is defined either in local or function scope.

    With that in mind, let's try to tackle the behavior outside of a function:

    The -l and -g flags have well defined, fairly obvious, meanings outside of a function block.

    True.

    The same is not true for -f.

    Let's make one up, then. As we've seen above, we'd effectively understand function scope to be "a scope above the highest local scope up to a function". The only "change" needed here is that that function does not need to exist. So "function scope" outside of a function would be the highest local scope. It would shadow global and universal, and be shadowed by any local vars. So if you did

    if true
       set -f samovar 1
    end
    echo $samovar

    it would output 1. Which seems kind of useful.

    Also, what does it mean to do set -qf outside of a function? Will it return all locally scoped vars?

    Like inside of functions, it would only return true for variables defined with set -f, since they could be shadowed by locally scoped ones.

    And if so then it's not consistent with the behavior we expect inside a function.

    I believe it would be.

    And if not then why would should set -f be equivalent to set -l outside of a function body?

    That's the trick - it wouldn't be.


    Now of course there's some weirdness here, since

    set -l fruit banana
    if true
        set -f fruit orange
    end
    echo $fruit

    would print "banana".

    Personally, I can't think of any way to make it more consistent.

    Does that make sense?

  19. chamini2 commented on Oct 24, 2016

    @chamini2

    I have no objections to @faho's proposal, makes sense to me. So we would be creating a new scope instead of the having an alias for a local scope.

    Since with @faho's proposal this scope would be included outside of a function too, maybe the name of the scope should not be function scope but outer scope (bike-shedding, I know); apart from that, seems a good solution.

  20. ridiculousfish commented on Oct 24, 2016

    @ridiculousfish
    Member

    Thanks for the great and detailed proposal faho. Also see 7b12fd2 for a relevant commit. This introduced the "top level local scope."

    Let's make one up, then. As we've seen above, we'd effectively understand function scope to be "a scope above the highest local scope up to a function". The only "change" needed here is that that function does not need to exist. So "function scope" outside of a function would be the highest local scope. It would shadow global and universal, and be shadowed by any local vars

    I wonder about the behavior of unadorned (no-scope-specified) set. Today it first attempts to modify an in-scope existing variable, then if it does not exist, introduces a new variable in function scope, or global scope if not in a function. This global scope behavior is very useful, since it allows users to directly set variables without worrying about scope, e.g. by typing set -x LD_LIBRARY_PATH ~/libs and this will be global.

    A new "top level function scope" would force us to qualify this further: unadorned set introduces a new variable in the nearest function scope, except for the top level one. However maybe this isn't so bad if nobody will encounter it: users may never know the top level function scope exists.

    Is there any good reason to run set -f at top level? I can't think of any. With that in mind perhaps it's better to make set -f error at top level. We wouldn't be preventing any legitimate use cases, and we might be saving the user from themself.

  21. chamini2 commented on Nov 7, 2016

    @chamini2

    I wonder about the behavior of unadorned (no-scope-specified) set...

    This was the reason this flag is even being discussed, the unadorned set
    does this scoping rule not achievable through a flag, that's why we are
    introducing this one.

    Is there any good reason to run set -f at top level? I can't think of any. With that in mind perhaps it's better to make set -f error at top level. We wouldn't be preventing any legitimate use cases, and we might be saving the user from themself.

    This makes sense to me now that I think about it. The docs could say that an unadorned set searches an existent variable in all scopes and if none are found, it creates a variable with -f option if in a function and with -g option otherwise. Keeping -f specific for functions.

    If we defined a function scope outside of functions, it would be a new global scope that sometimes is in functions, adding more complexity to the scoping rules outside of a function, IMHO.

    Please give your opinion so we can move forward with this! :)


    Some examples

    In the top level

    set -f a 0  # error
    set -qf     # error

    In a function

    function f
      set var 0
      if true
        set -f var 1
      end
      echo $var   # 1
    end
    function f
      set -l var 0
      if true
        set -f var 1
      end
      echo $var   # 0
    end
    function f
      set -l vl 0
      set -f vf 1
      set -qf     # vf
      set -ql     # vl
    end
  22. ridiculousfish commented on Nov 8, 2016

    @ridiculousfish
    Member

    Revisiting this case:

    function f
        set -l fruit banana
        if true
            set -f fruit orange
        end
        echo $fruit #banana
    end
    

    Now the first top-level set -l looks like a footgun, forever shadowing the function-scoped variable.

    If set -f only works inside functions, is there any harm in collapsing the function scope with its outermost local scope? So that set -f just means the same as set -l at top level inside the function.

    There's also a question of --no-scope-shadowing functions, in particular eval. It's annoying today that eval 'set -l foo bar' doesn't work (it ends up setting foo inside the eval function). Here's an opportunity to rectify that.

  23. alphapapa commented on Nov 11, 2016

    @alphapapa

    If set -f only works inside functions, is there any harm in collapsing the function scope with its outermost local scope? So that set -f just means the same as set -l at top level inside the function.

    IMO it should definitely be collapsed. Having set -f within an if within a function not set the variable in the function-level scope would be extremely confusing.

    And that makes me question the whole notion of set -f in the first place. If -l and -f both exist, that would imply that code written like this would somehow be sensible:

    function peel_if
        set -f fruit apple
        if test (today) = tuesday
            set -l fruit banana
            if test $fruit = banana
                peel $fruit
            end
        end
    end

    But clearly it's not. What languages allow shadowing variables within a function's own shadowed scope, other than, e.g. Lisps, which do it explicitly with let? It's a bad idea. Just use separate variables.

    Just like it's a bad idea in most languages to give variables in a for loop the same name as variables outside of the loop, it's a bad idea to shadow variables inside control blocks. They aren't anonymous functions.

    Block-level-scope/shadowing is just asking for trouble. There should only be two scopes: global and function, so there should only be bare set and set -l (or set -l could be changed to set -f, which would be more descriptive). At least, I think this should be the long-term goal.

  24. added a commit that references this issue on Jul 15, 2021
    262889b
  25. added a commit that references this issue on Jul 23, 2021
    45fde4d
  26. added a commit that references this issue on Aug 1, 2021
    733114f
  27. modified the milestones: fish-future, fish 3.4.0 on Aug 2, 2021
  28. locked as resolved and limited conversation to collaborators on Aug 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions