简体   繁体   中英

Instantiate Xbase XExpressions programmatically

I'm working on an Xtext project that uses parts of the Xbase grammar. In my code I'm analysing the DSL program in order to generate some Java code. It's easy to turn an existing XExpression into Java code using XbaseCompiler but that's not what I need. Instead, I need to generate a different program.

Currently I'm simply generating Java code (ie constructing a String). What I'd like to do is constructing a new XExpression , maybe even using parts of the original one, and then compile it to Java.

The different XExpression s have zero-args constructors, so I tried instantiating one and even set some of the properties. However the compiler crashed and I can't work out which properties it is missing.

I would prefer to generate the expression as String and then use the Xtext parser to do the heavy lifting for you, ie 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"
        ]
    ]
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM