1

How to forward the part of the parsed tree from input to output in xtend generator?

For instance, in some cases of output code generation, I do not need to parse the parameters of some constructor/functions. I only need to put this constants, variables names, expessions, etc. directly to the output code (forward all inside braces):

input DSL code:

CREATE_OBJECT_O(3, a, 5+6 )

output(may be some Java or C++ code):

Object o = new Object_Impl(3, a, 5+6 )

some part of xtext grammar:

ParameterList:
    (parameter+=Parameter ( "," parameter+=Parameter)* )?
    ;
Parameter:
    variableExpression=VariableExpression |(texts+=TextInParameter | macroSubstitutions+=MacroSubstitution)*;
Lev
  • 921
  • 7
  • 15

1 Answers1

3

There are two different services for doing that in Xtext:

  1. You can inject the org.eclipse.xtext.serializer.ISerializer service, and then call serializer.serialize(EObject) for outputting the object in a textual format. This uses serialization rules, however, if it does not work during editing (e.g. when using inside a JVMModelInferrer).
  2. The class org.eclipse.xtext.nodemodel.util.NodeModelUtils that contains static methods useful here. These methods use the original textual format, keeping the original formatting, so it is usable during editing.

    val eObjectNode = NodeModelUtils::getNode(eObject)
    eObjectNode.text //this is the output
    
    // Or alternatively getTokenText returns the string without hidden tokens
    NodeModelUtils::getTokenText(NodeModelUtils::getNode(eObject))
    
Zoltán Ujhelyi
  • 13,788
  • 2
  • 32
  • 37