javaparsingxtextxtend

Xtext Parse text using another parser rule than the top one


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
;

Solution

  • 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
    }