Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify redefined variables or shadowed variables

Tags:

f#

shadowing

When using the same variable twice in the same scope with the F# compiler there is no warning or feedback. e.g.

let s = "abc"
let s = "def"
printfn "%A" s

results in

def

I have seen
Is there a way to have warnings for shadowing values in F# in Visual Studio?
F# value shadowing - is it possible to disable value shadowing within the same scope

Is there a way to get feedback about shadowed variables either by a compiler warning or visually in the editor. How can this be done?

like image 761
Guy Coder Avatar asked Feb 27 '16 14:02

Guy Coder


1 Answers

First off, shadowing of variables in the same scope is not a bug or something that should be disabled. As Joel Mueller states it is legitimate, useful, and common.

Per MSDN

At any level of scope other than module scope, it is not an error to reuse a value or function name. If you reuse a name, the name declared later shadows the name declared earlier.


The Syntax Coloring feature of the Visual Studio extension F# Power Tools will highlight the current valid variable and show the shadowed variables as a light grey. e.g.

enter image description here

The extension can be installed from Visual Studio menu

Tools -> Extensions and Updates
Once the dialog opens
Select Visual Studio Gallery
In the upper right search box enter F# Power Tools
Since I have already installed it, the option to install is not shown.

enter image description here

The feature can be activated from the Visual Studio menu

Tools -> Options -> F# Power Tools -> General -> Syntax Coloring -> Grey out unused declarations

enter image description here

With option off:

enter image description here

with option on:

enter image description here

Note: After changing the option the source file(s) must be closed and then reopened for the change to take effect. Visual Studio does not need to be restarted for this but doing so will have the same effect.

Thanks to Ringil for noting my earlier invalid statement.

Note from source code:

Graying out unused declarations


Currently unused non public types, methods, functions and values declarations are checked. Beware that this feature is only 100% reliable when the code has no type error. This setting is available in General options. It is disabled by default because there might be performance issues on large files.

F# Power Tools features list

like image 200
Guy Coder Avatar answered Oct 06 '22 00:10

Guy Coder