I would prefer to generate the expression as String and then use the Xtext parser to do the heavy lifting for you, i.e. let it parse the String and create the corresponding XExpression
objects for you. How you do that properly depends on the context you're in (OSGI or standalone).
Here is a standalone example (can be run from a simple main
method) for the "Scripting Language" from the Xtext documentation:
public class StandaloneParser {
@Inject
private IParser parser;
public StandaloneParser() {
Injector injector = new ScriptingStandaloneSetup().createInjectorAndDoEMFRegistration();
injector.injectMembers(this);
}
public EObject parse(String input) {
IParseResult result = parser.parse(new StringReader(input));
if (result.hasSyntaxErrors()) {
throw new RuntimeException("Syntax errors");
}
return result.getRootASTElement();
}
}
Example for a caller:
public class Main {
public static void main(String[] args) {
StandaloneParser parser = new StandaloneParser();
EObject result = parser.parse("val answer = 7 * 6;");
System.out.println(result);
}
}
If you try to create such an expression programatically you'll have a hard time. It could look like this (Xtend code):
val factory = XbaseFactory.eINSTANCE
val expression = factory.createXVariableDeclaration => [
name = "answer"
right = factory.createXBinaryOperation => [
leftOperand = factory.createXNumberLiteral => [
value = "7"
]
feature = // TODO retrieve the JvmOperation: org.eclipse.xtext.xbase.lib.IntegerExtensions.operator_multiply(int,int)
rightOperand = factory.createXNumberLiteral => [
value = "6"
]
]
]