views:

110

answers:

4

I am currently working on a project that is accessing a piece of hardware using tons of hard coded memory locations. These locations can change based upon the electrical engineer's whim, so I'm looking to generate code from the engineer's memory map. Let's say the map is a simple text file like:

Name, Type, Address, Description
Foo, int, A001, Foo integer variable
Bar, float, A002, Bar float variable

I would like to automatically generate code (not IL) similar to:

class MachineMap
{
  /// <summary>
  /// Foo integer variable
  /// </summary>
  public readonly Addressable<int> Foo = new Addressable<int>("A001");
  /// <summary>
  /// Bar float variable
  /// </summary>
  public readonly Addressable<float> Bar = new Addressable<float>("A002");
}

Does anyone have ideas on tools that would make this task easy, or easier?

+4  A: 

Have a look at the built-in code generation ability of Visual Studio called T4. Or another option might be commercial product such as CodeSmith.

Have a look at this article from Scott Hanselman:
T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret

Philip Fourie
Do you know if T4 / CodeSmith allows you to generate code from another source, an Excel sheet for example?
Scott P
Thanks for the Hanselman link. I was looking at T4, but didn't grasp that you can essentially write any c# code as part of the template. This tutorial relates pretty well to what I'm trying to do: http://aabs.wordpress.com/2008/06/26/state-machines-in-c-30-using-t4-templates/
Scott P
A: 

You might be able to craft a DSL of your choosing, and then use M Grammar (part of Oslo) to parse it.

Nick
A: 

Similar to Nick's Oslo suggestion, StringTemplate is another way to create template-based source code from a well-defined grammar. It has a C# port, so it's easy enough to use from .NET.

Chris Farmer
+3  A: 

Use a regular expression like this (using gvim or vim):

:%s/\(.*\), \(.*\), \(.*\), \(.*\)/public readonly Addressable<\2> \1 = new Addressable<\2>("\3")/g

This solves the main parsing part. You then concatenate the contents with the header and footer files:

type header.txt converted.txt footer.txt > source.c

If the map is more complex, then use a tool made for grammar parsing. Otherwise, if it truly is that simple, avoid using a tank for such a tiny nail.

Dave Jarvis
+1 This and some reflection to dynamically create the Addressable<> objects and you're done.
kenny