Search code examples
code-generationxtextxtend

How can I generate in Xtext with the the Xtend Generator code as it was written?


I have this grammar defined in Xtext and when generating code with Xtend I want to get the Selection Expression as it was written.

So that when a selection expression like x = "abc" || (y="pqr" && z = "lmn") is written with that grammar, the Generator Code prepares the expression as a String like "x = "abc" || (y="pqr" && z = "lmn")". How could this be done?

Queries:
    (query+=Query)*;
Query:
    'get' 'patient' selection = Selection ('view' view = View)? ';'
;
View:
    'examination'| 'bill' | 'illness' | 'prescription'
;
Selection:
    OrSelection | {Selection} '*'
;   
OrSelection returns Selection:
    AndSelection ({OrSelection.left=current} "||" right=AndSelection)*  
;   
AndSelection returns Selection:
    PrimarySelection ({AndSelection.left=current} "&&" right=PrimarySelection)*  
;
PrimarySelection returns Selection:
    "(" Selection ")"
| Literal
;
Literal returns Selection:
   {Literal}  attribute = Attribute '=' value = Value 
;
Attribute:
   name = ID
;
Value:
    name = STRING
;

Solution

  • You can use NodeModelUtils to obtain the INode for an EObject and then ask the Node for its text

    NodeModelUtils.findActualNodeFor(obj).getText()
    

    or

    NodeModelUtils.getNode(obj).getText()
    

    the latter may include comments etc.