Tech Off Post

Single Post Permalink

View Thread: C# Syntactic Macros
  • User profile image
    Andrew Davey

    After a late night hacking session, I finally have a working syntactic macro system for C#! It is comprised of a VS custom tool that uses the CSparser. The end result allows me to do this:

    using System;
    public interface IModel
      string FirstName { get; set; }
      string Surname { get; set; }
      int ID { get; }
      event EventHandler FirstNameChanged;
      event EventHandler SurnameChanged;

    The CustomTool property of the IModel.cs file is set to "MacroExpander" and the Build action is set to None. This then generates a new file "under" the source file, called for example "IModel.generated.cs". This generated file contains the original interface (minus the bogus attribute) and a new class called "Model" that provides a stanard implementation of IModel. It includes private fields, a constructor, properties, events and event raising methods. The class is partial so you can still create a file called "Model.cs" alongside the interface and implement any methods. In addition, if you enter implementations of the interface properties/events in Model.cs then the generated class will not contain them. So it is easy to generate the 80% of standard members and custom write the others as required.

    The sharp-minded out there will note that "AutoClass" is a parameter passed to the Macro attribute. The expansion process is able to load any IMacro implementation I care to write. The macro implementation is handed the parsed source tree and allowed to modify it as required. After all macros have expanded, the source tree is converted back to CS source text and outputted from the VS custom tool. This generated file is compiled by VS as usual.

    I'm going to start using this AutoClass macro to generate most of my Model code (in the Model-View-Presenter architecture). Anywhere else I need code generation at this level I can create more macros easily.

    If people are interested in seeing this product released in some way please get in contact. I will perhaps get a screen cast made up to show it in action.

    I'll post details on my blog: