Code fixes are suggestions provided by IDEs to automatically address coding issues. In Visual Studio, they fall under the category of Quick Actions and are displayed within the light bulb icon menu.
- Code fixes are triggered by one or more diagnostics (e.g., FS0039 and/or IDE0005).
- If there are multiple diagnostics, they are guaranteed to share the same span (the red squiggly).
- Every code fix can produce:
- No suggestions (got triggered but couldn't come up with a suitable suggestion for a fix).
- One suggestion (e.g., "Discard unused value").
- Multiple suggestions (e.g., "Open namespace X" or "Fully qualify namespace X").
Bulk code fixes perform the same actions for identical diagnostics across a document/project/solution:
- Code fixes need to adhere to certain Visual Studio API requirements:
- Have the
[<ExportCodeFixProvider>]
attribute. - Inherit from the
CodeFixProvider
class.
- Have the
- When inheriting
CodeFixProvider
, a few members should be overridden:FixableDiagnosticIds
- lists all diagnostics triggering the code fix.RegisterCodeFixesAsync
- has the primary code fix logic.GetFixAllProvider
- needed for those with bulk behavior.
- On top of that, we have our own framework for F# code fixes, found in the
IFSharpCodeFix.fs
file. In that regard, code fixes should implement one of:- The
IFSharpCodeFixProvider
interface - for those generating at most one suggestion (the majority). - The
IFSharpMultiCodeFixProvider
interface - for those able to produce several suggestions.
- The
- Code fixes within the above framework can and should be unit tested.
- Find the corresponding unit test suite.
- Introduce a test featuring the code with the diagnostic alongside the expected code fix behavior (0, 1, or multiple suggestions).
- Adopt a TDD approach and modify the code fix logic. Keep in mind that occasionally, issues might originate in the compiler layer.
- Create a matching unit test suite with both positive and negative cases.
- Seek a similar code fix for inspiration.
- Craft your new code fix, ensuring compliance with the framework described above.
- Just before submitting the code fix, manually double-check that it works in VS - demo videos are welcome.
- Code fix tracking issue - tracks bugs, enhancements, and suggestions for new code fixes.
- A session from Amplifying F# that largely focuses on crafting code fixes.