Scott P
Scott P

Reputation: 3782

Is there an easy way to generate code from a text file?

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?

Upvotes: 9

Views: 586

Answers (4)

Dave Jarvis
Dave Jarvis

Reputation: 31211

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.

Upvotes: 3

Philip Fourie
Philip Fourie

Reputation: 117027

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

Upvotes: 4

Chris Farmer
Chris Farmer

Reputation: 25415

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.

Upvotes: 0

Nick
Nick

Reputation: 5955

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

Upvotes: 0

Related Questions