Roslyn - Semantics

I've been getting to know Roslyn the past couple of weeks. It's a little frustrating as the documentation has been cleansed of any useful examples, but luckily there is stackoverflow and gitter and google :o)

I initially began writing about a concrete problem I had to solve: Extract the interface of a class and put it somewhere else in the solution. And came to the conclusion, that I spent too much time explaining the difference between syntax and semantics. Eventually I deleted everything and started writing this.

Semantics is the birds-eye-view of your code, that is to say the definitions that make up your code and how it fits together. We're talking namespaces, interfaces, types and methods. The actual implementation of a method, which may indeed involve types is irrelevant to the semantic model.

Syntax is the representation of your code as the compiler sees it. It contains everything, even the white space (or lack there-of) between keywords in your code. When coding Roslyn Analyzers/CodeFixes you will want to know if you're trying to fix the semantics of your code or the syntax. A good example is mine from above: Extract the interface of a class. The extraction of an interface is an exercise in sematics (how to interact with my class at a high level).

Now, I tried to extract an interface from syntax, but inevitably had to fail, because the syntax tree lacks a higher understanding of types and their origin - which led to missing namespace imports - as well as understanding of partial classes - which led to missing methods in the interfaces.

With that out of the way, hopefully I can now share what I learned while building my interface extractor.



Comments are closed