0

我想写一个翻译。这个想法是将特殊形成的 C++ 接口转换为 C++/CLI。我有一个 antlr 语法,可以解析所有内容并生成 AST。现在我想使用这些信息和一些字符串模板来发出源代码。

我的想法是在某种具有属性的对象层次结构中转换 AST(例如,包含索引属性方法的接口对象,其中包含方法描述对象。主字符串模板然后被提供根对象并将属性插入到正确的位置或将它们传递给子模板。

现在我的问题是:如何编写一个需要调用未定义次数的字符串模板/属性?示例:一个接口包含许多方法。这意味着,方法的子模板需要多次调用,每次使用不同的属性。我怎样才能把它写成字符串模板和索引属性的组合?

感谢您的帮助托比亚斯

4

1 回答 1

0

I'm doing something very similar. The basic idea is that your model must expose a list of some object, and you use that list within your string templates. For instance, let's say I have a very braindead implementation. I'm going to use Java because that's what I know best; you should get the idea.

https://gist.github.com/894632

public class GeneratedClass {
    private String accessModifier;
    private String name;
    private String superClass;
    private List<Method> methods;
}

public class Method {
    private String comments;
    private String name;
    private String accessModifier;
    private Type returnType;
    private List<Argument> arguments;
    private String body;
}

public class Argument {
    private Type type;
    private String name;
}

public class Type {
    private String name;
}

For my template I might have the following:

group Java;

class(accessModifier, name, superclass, methods)::=<<

$accessModifier$ class $name$ extends $superclass$ {

    $methods:method(); separator="\n"$

}
>>

method(method)::=<<
/**
 $method.comments$
*/
$method.accessModifier$ $method.returnType.name$ $name$ ($method.arguments:argument(); separator=","$) {
    $method.body$
}
>>

argument(argument)::=<<
$argument.type.name$ $argument.name$
>>

The key is that I functionally apply a template for each method object I have; that's what $methods:method() does. If I had an empty list, no template would be invoked at all. This handles the variable size problem. I do a similar thing within the method definition; ($method.arguments:argument(); separator=","$). This is going to create a comma separated list of method parameters in between parentheses, just like you'd expect.

于 2011-03-30T15:45:11.967 回答