Hi. I have recently encountered a small usability problem where I could not in a glance decide if I have shadowed an existing variable while writing a parser by hand (which involved multiple nested switch and if statements).
I believe it would be an easy usability win if the LSP could report if the variable declaration shadows an existing one when you hover over its declaration.
Shadowing of variables is an explicit feature of Swift and we don’t want to unconditionally warn about it. If that’s what you’re asking for, it’s not something we plan to support.
LSP is able to tell you which line defined the variable if you jump-to-definition on one of its references. Similarly, if you put your cursor on one of the variables in VS Code (and probably also other LSP editors), it will highlight all the other references to it and you can tell that it’s not highlighting the outer, shadowed references.
You slightly misunderstood me. It is legal to shadow a variable (simply like this: let name = "My Name") in an inner scope, but if the function is long and deep enough, it can get tricky to figure out if a variable called name exist in an outer scope. Precisely because you can only jump to the innermost declaration of the selected variable.
This may result in accidental shadowing of a wrong or unintended variable, after all, naming things is one of the hardest things in computer science. And you may have just way too many variables called name in the scope.
What I suggest is to show (on hover, when a type is shown) a note that it is a shadow, and hence allowing greater vigilance against accidental shadowing.
Or possibly, even an ability to jump to the next outer scope declaration of this variable. It will hopefully reduce a need for manual cmd+f and then scrolling in search of accidental shadowing.
It will still require manual scrolling through the file in VS Code, and I do not think Xcode does this. Or am I mistaken?
UPD: I just checked and Xcode does it too. I have no idea why I have never noticed it... Sorry about that.
UPD2: I figured why... I carefully observed what I was doing, and I realised that I tend to double-click on a variable when I select it. And if I do that, then it will not show other variables with the same name.
Technically, python has global keyword, which is not the same but at least leans towards an explicit control of shadowing.
Well, in any case, I was not hoping for a new keyword or syntax at this stage. Just that, the LSP could add an extra line to the triple slash comments implicitly, stating there that the variable is shadowing another one.
class A {
static var x: Int = 0
}
class B {
static var x: Int = 0
}
class C: A {
class D: B {
static func foo() {
x = 1 // 🛑 Error, x is shadowed [Fixit: D.x C.x]
D.x = 1 // ✅
C.x = 1 // ✅
}
}
}
Ah, got you. Could you file an issues for this on Issues · apple/sourcekit-lsp · GitHub. That way we have a ticket tracking it and can discuss if and how best to present this.