I've defined a simple Xtext grammar which looks like this (simplified):
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
import "http://www.eclipse.org/emf/2002/Ecore" as ecore
System:
'Define System'
(
'Define Components' '{' components+=Component+ '}'
)
'End'
;
Component:
'Component' name=ID 'Value' value=Double ';'
;
Double returns ecore::EDouble:
'-'? INT? '.' INT
;
The problem I like to solve is - how can I convert a simple Java Object to a valid xtext file?
To simplify my problem, lets say we create a list of components in Java:
List<Component> components = new ArrayList<Component>();
components.add(new Component("FirstComponent", 1.0));
components.add(new Component("SecondComponent", 2.0));
components.add(new Component("ThirdComponent", 3.0));
The output-file I like to create should look like this:
Define System
Define Components {
Component FirstComponent Value 1.0;
Component SecondComponent Value 2.0;
Component ThirdComponent Value 3.0;
}
End
It is important that this file is checked by the xtext grammar, so that it's valid. I Hope you have any ideas for me. Here are some of mine, but so far I don't know how to implement them:
Idea #1: I know how to read and write a file. In my head one solution could look like this: I have the list in my Java code, now I like to write a file which looks like the output-file above. Afterwards I like to read this file and check for errors by the grammar. How can I do this?
Idea #2: If I imagine I would create a xml file out of Java code using JDOM, I wish I could do the same in xtext. Just define a parent "Define System" which ends with "End" (see my output-file) and then add a child "Define Components {" which ends with "}" and then add the children to this, e.g. "Component FirstComponent Value 1.0;". I hope this isn't confusing :-)
Idea #3: I could use a template like the following and add children between the braces "{" ... "}":
Define System
Define Components { ... }
End
Btw: I already tried Linking Xtext with StringTemplate code generator, but it is kind of another problem. Hope you have any ideas.