📜 ⬆️ ⬇️

Uninstalling Code Contracts with Roslyn

image

What is Code Contracts?


Code Contracts were created by the Microsoft Research development team 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 assumed that Code Contracts will become part of the .NET platform and will receive support in the compiler, the platform and Visual Studio. Unfortunately, support appeared only on the platform in the form of the System.Diagnostics.Contracts namespace classes. The rest requires plug-ins and additional utilities.
At the moment, the project supports SergeyT and several more participants.

Code Contracts Support in Mono


For projects that are developed on Windows, the Code Contracts infrastructure is clear and more developed. There are Build Steps for MSBuild, you can rewrite / verify assemblies using utilities, there are plug-ins for VS and Resharper. But with Mono, things are not so good, there is a self-made ccrewrite , which breaks down on complex code. There is no support for xbuild and MonoDevelop, and you cannot build a project in a simple way.

Reasons for removing Code Contracts from the project:


- External dependence of the project on Code Contracts utilities, without which the project cannot be built.
- Compilation speed is lower due to the additional step in the form of rewriting the assembly.
- Lack of support in Mono.
- There are more inconveniences than benefits.
')

Remove Code Contracts from Source Code


Thanks to Microsoft's Roslyn project, analyzing and processing source code in C # / VB.NET has become a rather trivial task. And I chose this path to remove Code Contracts from the source code. The solution itself is simple and consists of a CSharpSyntaxRewriter , which runs through the code and replaces Code Contracts checks with their equivalent outside of Contract Contracts.

The Code Contract remover itself is designed as a Nuget package , available as a utility and works under Mono.
Install-Package CodeContractsRemover 

And the team to rewrite all the sources in the project directory:
 # code_contracts_remover.exe <Convert|Remove> <directoryPath> [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, you can use this utility as a build step on your build server.

Links


GitHub project
Nuget package

Source: https://habr.com/ru/post/302516/


All Articles