Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting implicit casts in a Roslyn diagnostic analyzer

Tags:

c#

roslyn

I want to create a Roslyn diagnostic analyzer to find implicit casts, specifically constructs like:

DateTimeOffset v = new DateTime();

This means that I either have to detect implicit casts, or find references to DateTimeOffset.op_Implicit(DateTime).

The problem though is that Roslyn diagnostic analyzers work on syntax, not the semantic model. So, the only approach I can think of is to figure out all syntax constructs that could potentially have an implicit cast in them, and run semantic analysis on those. This however is pretty tricky since even if I would be able to create an exhaustive list of syntax constructs that can generate an implicit cast, changes to the language can easily introduce new ones.

My question is whether there is an alternative approach to the one described above. Specifically, is it possible to write a Roslyn diagnostic analyzer that runs against the semantic model? Or have I missed something and are there better alternatives than what I described above?

like image 749
Pieter van Ginkel Avatar asked Sep 06 '25 14:09

Pieter van Ginkel


1 Answers

I believe you're incorrect here:

The problem though is that Roslyn diagnostic analyzers work on syntax, not the semantic model.

You can register diagnostic analyzers to work against the syntax, or the semantic model, or the even higher level "operation" kind. For example, Kasey Uhlenhuth has an example detecting the creation of zero-length arrays.

You can call AnalysisContext.RegisterSemanticModelAction or AnalysisContext.RegisterOperationAction. You may well want to register for operations with an operation kind of Conversion - that would probably remove a lot of the work.

like image 167
Jon Skeet Avatar answered Sep 09 '25 00:09

Jon Skeet