1

For testing purposes, I would like to parse a stand-alone expression in my Xtext language.

In my tests, I can parse a complete model using a ParseHelper<Model>, e.g.,

val model = parseHelper.parse('''function { 1 + 2 }''')

Is it possible to parse a stand-alone expression in a similar way? I have tried injecting a ParseHelper<Expression> and writing

val expr = parseHelper.parse('''1 + 2''')

but this returns null for some reason.


The examples above are based on the following dummy grammar.

Model:
    functions+=Function*
;

Function:
    'function' '{' Expression '}'
;

Expression:
      Addition
;
Addition returns Expression:
    Literal (=>({Addition.left=current} '+') right=Literal)*
;
Literal returns Expression:
    INT
;
Christian Dietrich
  • 11,778
  • 4
  • 24
  • 32
Safron
  • 802
  • 1
  • 11
  • 23
  • https://stackoverflow.com/questions/41629743/access-parserrules-in-xtext-2-11 so you might do the parse for test manually. Inject `Provider rsp`, ask rsp for resourceset, in resourceset createResource with dummy.mydsl uri, on resource call setEntryRule, call resource.load with string input stream, inspect resource.contents.get(0) – Christian Dietrich Mar 04 '22 at 05:47

1 Answers1

2

You can also use the IParser directly. To parse one rule you can do the following:

@Inject IParser parser  // inject the parser
@Inject <Your-Lang-Name-Here>GrammarAccess grammar  // inject your IGrammarAccess

@Test
def void testPartialParse() {
    val expression = '''1 + 2'''
    val IParseResult result = parser.parse(grammar.expressionRule, new StringReader(expression)) // partial parsing here
    assertNotNull(result.rootASTElement)  // rootASTElement should be your Addition
}