Scenarios and samples

A compiler may find it much easier to transform or project its internal AST into a code model, than to translate it directly into IL. For example, in the code model, there is a single way to express the concept of dereferencing a pointer, while in IL, there are 16 different opcodes. The code model to IL translator captures all of these nuances and factors out the common patterns of code generation for conditional control flow, loops, closures, exception handlers and so on.

When starting a compiler from scratch, it will make a lot of sense to express the AST classes of the new compiler as subclasses of the AST base classes defined in AstsProjectedAsCodeModel. The base classes take care of a lot boiler plate functionality to do with name lookup, type conversion, overload resolution, error reporting and the process of projecting the AST nodes onto code model nodes. More importantly perhaps, the AST base classes provide a pattern for incremental compilation.

Another scenario is the System.CodeDom scenario, where a tool (such as a designer) needs to generate code for use by any of the languages supported by the designer.
Because the code model provides a single unambiguous representation for code, using the Code model rather than System.CodeDom will not run into the issue of different languages having different rules for looking up names, doing type conversions, resolving overloads, and so on. And, if the tool is used together with a compiler that uses the code model to produce its own code, there is no need to convert the tool generated object model to source, parse it as an AST and then convert that back to an intermediate representation to write out into an assembly.

Perhaps the most common usage scenario for the code model is writing a simple flow-insentive anti-pattern checker such as FxCop.

Tools that operate by modifying assemblies after they have been compiled, for example by injecting logging code or by injecting error checks, tend to be easier to write if they operate on a tree like object model, such as the code model, rather than operating on a flat list of low level instructions such as IL. To build such a tool, consider using the PetoPE sample as a starting point. An example of such a tool is the runtime checker found in Code contracts tool.

To better understand the code model, have a look at the PeToText sample, which is a simple decompiler for CLR PE files.

Last edited Apr 8, 2009 at 11:41 PM by hermanv, version 2

Comments

No comments yet.