
Remove Code Contracts with Roslyn

What is Code Contracts
Code Contracts was created by a team of developers from Microsoft Research in 2008. The task of Code Contracts is to describe the assumptions about the state in the code, which are subsequently used to generate documentation and check the code for correctness. It was expected that Code Contracts would become part of the .NET platform and would receive support in the compiler, platform, and Visual Studio. Unfortunately, support only appeared on the platform in the form of System.Diagnostics.Contracts namespace classes. For the rest, plugins and additional utilities are required.
At the moment, the project supports SergeyT and several other participants.
Support for Code Contracts in Mono
For projects that are developed on Windows, the Code Contracts infrastructure is understandable and more developed. There are Build Steps for MSBuild, you can rewrite / verify assemblies using utilities, there are plugins for VS and Resharper. But with Mono things are not so good, there is a home-made ccrewrite that breaks on complex code. There is no support in xbuild and MonoDevelop, and you cannot build a project in a simple way.
Reasons to remove Code Contracts from the project:
- The external dependence of the project on Code Contracts utilities, without which the project cannot be assembled.
- Compilation speed is lower due to an additional step in the form of rewriting the assembly.
- Lack of support in Mono.
“There are more inconveniences than benefits.”
Removing Code Contracts from Source
Thanks to Microsoft’s Roslyn project, analyzing and processing source code in C # / VB.NET has become a pretty trivial task. And I chose this path to remove Code Contracts from the source code. The solution itself is simple and consists of CSharpSyntaxRewriter , which runs through the code and replaces Code Contracts checks with their equivalent outside Code Contracts.
The Code Contract remover itself is designed as a Nuget package , is available as a utility, and runs under Mono.
Install-Package CodeContractsRemover
And the command to rewrite all the sources in the project directory:
# code_contracts_remover.exe [searchPattern=*.cs] [encoding=utf-8]
mono packages/CodeContractsRemover.1.0.2/tools/code_contracts_remover.exe Convert ./
If you do not want to say goodbye to contracts forever, then you can use this utility as a build step on your build server.
References
GitHub
Nuget Package Project