You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The scoping rules when creating or updating a variable are:
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.
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.
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.
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.
I think we can still do a tiny bit better while retaining this 2 axioms:
set PATH ... within a function should modify global PATH.
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.
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.
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.
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.
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.
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.
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.
#!/usr/bin/env fishfunction foo
set bar baz
endecho$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. :)
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
iftrueset bar bie
elseset bar drink
endecho$barend
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.
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
iftrueset-f haberdashery 2
set-l humpty 3
end# $humpty won't be defined here anymoreend
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
iftrueset-l a 0
echo$a# will output 0endecho$a# will output 1end
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
iftrueset-f samovar 1
endecho$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
iftrueset-f fruit orange
endecho$fruit
would print "banana".
Personally, I can't think of any way to make it more consistent.
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.
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.
Reacted by Adam Porter, David Adam and Kurtis Rader
I wonder about the behavior of unadorned (no-scope-specified) set...
This was the reason this flag is even being discussed, the unadornedset
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 unadornedset 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 # errorset -qf # error
In a function
functionfset var 0
iftrueset -f var 1
end
echo$var# 1
end
functionfset -l var 0
iftrueset -f var 1
end
echo$var# 0
end
functionfset -l vl 0
set -f vf 1
set -qf # vfset -ql # vl
end
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.
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
iftest (today) = tuesday
set-l fruit banana
iftest$fruit = banana
peel $fruitendendend
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.
Activity
xiaq commentedon Feb 7, 2013
Oops. Things are actually more confusing here.
-ldoesn't always put the variable in the function's scope, it puts it in the innermost scope.xiaq commentedon Feb 7, 2013
Description updated. (imply -l -> imply function scope)
JanKanis commentedon Feb 7, 2013
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
setshould be some scope within the function rather than global or universal. But optimizing for interactive use, I think the default for a baresetwithin a function should be the same assetoutside 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.cben commentedon May 9, 2013
I think we can still do a tiny bit better while retaining this 2 axioms:
set PATH ...within a function should modify global PATH.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:
The only use I see for block scope is temporarily changing an env var with
set -l -xbutenvcovers 90% of that use.So I'd just change
set -lto 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 defaultset foobehavior that you'd modify a global/exportedfooif one exists.Second, this dilemma where just
set foomostly 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 lowercasesets a function-local var.set UPPERCASEsets a global [exported?] var.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.
dag commentedon May 11, 2013
This is a tough one. Some observations:
setinside a function behaved differently from outside a function.setinside a function can alter global variables.set -l(one line for each!) in every function is... perfectly sane for a programming language, but a bit obnoxious for shell scripting.set -l) may or may not actually be useful in a shell.Straw man proposal: Only have one scope, "local to execution context". In a function this is function scope, outside it is global scope.
set -gcan 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.
ridiculousfish commentedon May 12, 2013
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.
dag commentedon May 12, 2013
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 whatset -l a,b,c valdoes: 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:
JanKanis commentedon May 30, 2013
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.
ridiculousfish commentedon May 30, 2013
Block scopes interact nicely with "temporarily exporting" variables, e.g.
The environment variable is automatically cleared when the scope ends.
alphapapa commentedon Sep 11, 2015
I'm converting another Bash script to Fish, and ran into this. I used
set -lin a function, and I expected it to define the variable in the function's scope. But theset -lwas also inside awhileloop, 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
-linside a function should use the function's scope. If the block-local behavior is desired, there should be a separate switch for that.martin-g commentedon Sep 11, 2015
Java/Scala has block level variables. JavaScript/ES2015 (aka ES6/Harmony) also supports them with
let someVar = someValue.alphapapa commentedon Sep 11, 2015
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.ridiculousfish commentedon Sep 11, 2015
Note that the default behavior of
setis function scoped. You have to opt in to block scoping with-lalphapapa commentedon Sep 11, 2015
Hm, I didn't realize that. That's another way that Fish somewhat confusingly differs from Bash:
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. :)
faho commentedon Sep 11, 2015
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=bazto 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
setto force function-level scope, since now code like this:can't help but change the global variable bar if it is defined. This needs an additional
set -l barbefore theif, 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.
9 remaining items
faho commentedon Oct 23, 2016
From @krader1961 in #3465:
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 -finside of a function is the same asset -lunless you are also inside of a block. I.e.Here $flounder and $arglebargle have exactly the same visibility. It's only when you do
The question here is how much we want "function-scope" to be its own thing, versus just a shortcut for another scope.
They probably should, so you can do easy temporary variables. Also, it's already what happens:
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 -qflmight 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:
True.
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
it would output 1. Which seems kind of useful.
Like inside of functions, it would only return true for variables defined with
set -f, since they could be shadowed by locally scoped ones.I believe it would be.
That's the trick - it wouldn't be.
Now of course there's some weirdness here, since
would print "banana".
Personally, I can't think of any way to make it more consistent.
Does that make sense?
chamini2 commentedon Oct 24, 2016
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 scopebutouter scope(bike-shedding, I know); apart from that, seems a good solution.ridiculousfish commentedon Oct 24, 2016
Thanks for the great and detailed proposal faho. Also see 7b12fd2 for a relevant commit. This introduced the "top level local scope."
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 typingset -x LD_LIBRARY_PATH ~/libsand this will be global.A new "top level function scope" would force us to qualify this further: unadorned
setintroduces 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 -fat top level? I can't think of any. With that in mind perhaps it's better to makeset -ferror at top level. We wouldn't be preventing any legitimate use cases, and we might be saving the user from themself.chamini2 commentedon Nov 7, 2016
This was the reason this flag is even being discussed, the unadorned
setdoes this scoping rule not achievable through a flag, that's why we are
introducing this one.
This makes sense to me now that I think about it. The docs could say that an unadorned
setsearches an existent variable in all scopes and if none are found, it creates a variable with-foption if in a function and with-goption otherwise. Keeping-fspecific for functions.If we defined a
function scopeoutside 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
In a function
ridiculousfish commentedon Nov 8, 2016
Revisiting this case:
Now the first top-level
set -llooks like a footgun, forever shadowing the function-scoped variable.If
set -fonly works inside functions, is there any harm in collapsing the function scope with its outermost local scope? So thatset -fjust means the same asset -lat top level inside the function.There's also a question of
--no-scope-shadowingfunctions, in particulareval. It's annoying today thateval 'set -l foo bar'doesn't work (it ends up settingfooinside theevalfunction). Here's an opportunity to rectify that.alphapapa commentedon Nov 11, 2016
IMO it should definitely be collapsed. Having
set -fwithin anifwithin 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 -fin the first place. If-land-fboth exist, that would imply that code written like this would somehow be sensible: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
forloop 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
setandset -l(orset -lcould be changed toset -f, which would be more descriptive). At least, I think this should be the long-term goal.Add `set --function`
Add `set --function`
Add `set --function` (#8145)