1/31/2011
Dissecting Razor, part 1: Parts of the framework

Razor involves two distinct components: The Razor engine and the WebPages framework.

The Razor engine, in System.Web.Razor.dll, parses CSHTML (and VBHTML) files into CodeDOM trees. Except for the word Web in project name, the engine has nothing to do with ASP.Net; it doesn’t even reference System.Web.dll. In fact, it targets the .Net Client Profile, and only references mscorlib and System.dll.

The Razor engine is aware of all of Razor’s syntax-level features (code nuggets, sections, helpers), but is not aware of what they mean; it blindly transforms them into function calls.

The Razor engine can be used without ASP.Net for any kind of templating system. This is done by inheriting the RazorEngineHost class to provide default code-generation settings (such as base class and method name), then passing the host to a RazorTemplateParser.

The standard syntax will be annoying when generating non-XML-like content. To avoid this, one can write a custom MarkupParser to define a Razor syntax for a different markup language (such as CSS).

The WebPages framework, in System.Web.Webpages.dll, is a set of classes to use with the Razor parser. It contains the WebPage class which standard Razor pages inherit. This class defines the methods which are blindly called by the Razor parser, such as DefineSection and WriteLiteral. This framework also handles _PageStart and _AppStart pages and contains the HtmlHelper infrastructure.

The WebPages framework is not directly connected to the Razor parser. It could theoretically be used with a different template engine, as long as the template engine emits the correct method calls and class definitions. (more on this later)

The WebPages framework also contains two sets of utility methods. System.Web.Helpers.dll contains miscellaneous utility classes, such as Crypto and WebMail wrappers, plus grid and chart implementations. Microsoft.Web.Helpers.dll contains HTML helper classes which integrate with various third-party services, including Twitter, ReCaptcha, Google Analytics, and more. Most of these helpers can also be used in ordinary ASPX pages.

As I mentioned in the post, you would need to write a CssMarkupParser; this class would re-implement all of Razor's markup-side features (tag nesting and transitions to server-side code, plus and @:) for CSS.

Since CSS doesn't support arbitrary nesting, this would be simpler than HtmlMakrupParser.

I don't know of anyone who has done this; if you're interested, download the source and look at mvc3-rtm-sources\webpages\src\System.Web.Razor\Parser\HtmlMarkupParser.cs.