by Touche · 12y ago · 0 comments
For example, you could use the "compiler as a service" to create a semantic model from source code and then query it for "all classes that contain a public method that accept an int and return a bool". This might sound trivial, but using a tool like Roslyn to do this is much easier than writing a parser that handles a language and then doing the same thing.
1. It's nice to have the same view of the code that your compiler has. This matters less for C# than it would for C++, but it's nice to know you handle the edge cases in a consistent fashion.
2. Invalid code. Since Rosalyn is designed for being used in VS while you're in the middle of typing, it has advanced functionality for handling incomplete or erroneous code. If building your own parser for valid code is hard, building a parser that also gracefully handles half-finished lines is an order of magnitude harder. And having it handle half-lines in a fashion consistent with how VS handles it is another order of magnitude.
This also means that the general bar for building code analysis tools has been lowered by quite a bit
If a traditional compiler has an API of "source files and configuration flags in, object files out", the Roslyn API is completely different. Roslyn is about designing and providing a semantic API over C# language analysis and compiler services.
http://go.microsoft.com/fwlink/?LinkID=230702
Some of the features of the reference source website enabled by Roslyn's semantic understanding of symbols (assemblies, namespaces, types, members) are color-coding, search, browse, jump-to-definition, and deep-linking.
For example, I can deep-link to part of WPF like so:
http://referencesource-beta.microsoft.com/#PresentationFrame...
I can see which assemblies depend on it, which assemblies it depends on, and browse the source of the assembly in a tree view either by source file or by namespace -> type -> member name.
SELECT MyClass1.Method1(ColumnA, Math.Round(ColumnB))
FROM Table1
Another example is you can extend your scripting language so that user can use full power of Linq.So in otherwords, you can extend any of your little languages so that you can mix C# in it. Considering C# supports tons of functional features, Linq, anonymous types, dynamic types etc this can really beef up host language.
E.g. If you're writing a BASIC interpreter:
10 PRINT "Hello World"
20 CSHARP "Console.WriteLine(42);"
30 GOTO 10
You call Roslyn on line 2 with the expression to parse and execute.However what Roslyn does support is "transform this snippet for me", which is useful if you know the boundary between your code and code it cares about.