Introducing the Q# Formatter
Over the past several years, as Q# has evolved, its syntax has evolved with it. There have been several syntax changes that have resulted in deprecated ways of doing common things in Q#, such as the removal of parenthesis around for-loop conditions. To help our users keep their code up to date with the latest syntax, we have added several new features to the QDK.
When you use the Q# extensions for Visual Studio or Visual Studio Code to edit Q# code with deprecated syntax, the code in question will be underlined with green squiggles, and code suggestions will be available to update the syntax. In the past we’ve already had code suggestions to update each deprecated code fragment. In release 0.21 we added a code action to update all deprecated syntax in a file:
You can also update the syntax through the Edit menu, or with the appropriate keyboard shortcut. When you update syntax through this method, the code in the file will also be auto-formatted, removing extra spaces and correcting indentation. This extra formatting is specific to the Edit menu option.
Outside of the Q# extensions, we have also added this update functionality to the SDK for Q# by adding a build target called UpdateSyntax. When targeting this with msbuild, all files in a Q# project can have their syntax updated in one go. This target can be invoked with from a command prompt at the location of a Q# project with the command
dotnet msbuild -t:UpdateSyntax
The Q# Formatter addresses several deprecated syntaxes and updates them to the supported syntaxes. These currently include:
- Qubit Binding – Replaces the
borrowrespectively as well as removes the unneeded parentheses around the binding.
- Unit Type References – Replaces
Unitwhen referencing the Unit type (for example, in callable signatures). This will not affect the Unit value literal (for example, in return statements).
- For-Loops – Removes the deprecated parentheses around the for-loop ranges and loop-variables.
- Specialization Parameters – Updates deprecated specialization declarations to include the
- New Arrays – Updates the
new <Type>[n]array syntax to the new
[val, size = n]array syntax.
- Boolean Operators – Replaces deprecated use of Boolean operators
!with their keyword equivalents
In this pull request on the Quantum Katas as repository, we show what kinds of changes running the Q# Formatter can produce. In this case, the code was up to date on most of the deprecated syntaxes, so the only change the Q# Formatter did was the new array syntax update.
By providing these methods of updating Q# code, we hope to help you keep your code up to date and take advantage of the latest features of Q#!