开发者

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

开发者 https://www.devze.com 2022-12-22 07:58 出处:网络
I am currently working on a project that is acce开发者_开发问答ssing a piece of hardware using tons of hard coded memory locations.These locations can change based upon the electrical engineer\'s whim

I am currently working on a project that is acce开发者_开发问答ssing 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?


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消