[antlr-interest] multiple text outputs of ANTLR3+ST in a single pass
Arnulf Heller
aheller at gmx.at
Thu May 25 10:55:47 PDT 2006
We are using ANTLR3+ST to convert textual descriptions of a simple
protocol into C++ code which generates/parses messages of this protocol.
Currently, we use the grammar along with the protocol description
file four times with alternating string template files in order to
produce server/client side header/implementation files (which works great BTW).
What we would like to change is to pass the protocol file through
ANTLR and StringTemplate only once and produce all four C++ files in
a single pass. From a post a while ago I know that there are no means
to do that now with ANTLR+ST, but maybe I have a trivial solution for
that scenario.
The only missing link is access to sub-templates within a
StringTemplate. I have sketched that in the commented lines in
"Test.java" below.
Would that be a viable solution? Or is there another trivial solution
that I am not aware of?
Thx,
Arnulf
---- Cpp.stg (removed some WS here) ------------
group Cpp;
program(classname) ::= <<
<definition(...)>
<implementation(...)>
>>
definition(classname) ::= << <classname:classdef()> >>
classdef(classname) ::= <<
class <classname>
{ public: <classname>(); };
>>
implementation(classname) ::= <<
<classname:include()>
<classname:classdecl()>
>>
include(classname) ::= << #include "<classname>.h" >>
classdecl(classname) ::= << <classname>::<classname> {} >>
--- Test.java ---
import java.io.*;
import org.antlr.stringtemplate.*;
import org.antlr.stringtemplate.language.*;
public class Test {
public static StringTemplateGroup templates;
public static void main(String[] args) throws Exception {
templates = new StringTemplateGroup(new FileReader("Cpp.stg"),
AngleBracketTemplateLexer.class);
StringTemplate stProgram = templates.getInstanceOf("program");
stProgram.setAttribute("classname","MyFirstClass");
stProgram.setAttribute("classname","MySecondClass");
System.out.println(stProgram.toString()); // produces header and
implementation in a single string
// StringTemplate stDef = st.getTemplate("definition"); // get definition part
// System.out.println(stDef.toString());
// StringTemplate stImpl = st.getTemplate("implementation"); // get
implementation part
// System.out.println(stImpl.toString());
}
}
--- output (removed some WS here) ---
class MyFirstClass { public: MyFirstClass(); };
class MySecondClass { public: MySecondClass(); };
#include "MyFirstClass.h"
#include "MySecondClass.h"
MyFirstClass::MyFirstClass {}
MySecondClass::MySecondClass {}
More information about the antlr-interest
mailing list