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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With