Search code examples
xtext

Including a grammar into another grammar


I would like to reuse grammar definitions.

I have a grammar like this:

Person:
  'contact' name=ID '{'
    'phone' phone=INT
  '}'
;

I would like to have another grammar like this:

include "uri/to/other/project/to/other/grammar/definitions"

Call:
  'call' person=Person
;

Person is not known by the second grammar. Is Xtext therefore able to insert or include the Person definition from the first grammar into the second grammar?

A further step is the generation of the Person. I would like to know how to accomplish that too.


Solution

  • I found the solution. You can use the keyword "with" as it is used to include the Terminals.

    The necessary steps:

    1. Create Xtext Project com.mydsl.A (A) and com.mydsl.B (B)
    2. Write grammar for A
    3. Add A as dependency in META-INF/MANIFEST of B
    4. Add A.ui as dependency in META-INF/MANIFEST of B.ui
    5. Add registration of A's genmodel in B's workflow like that: In StandaloneSetup: registerGenModelFile = "platform:/resource/A/src-gen/path/to/A.genmodel"
    6. Change first line of B to grammar B with A
    7. You can use EClasses of A now while writing grammar B

    with cannot be used to include more than one grammar, so the terminal definitions must be stated in A.

    The generation is executed in B's IGenerator, but you can reuse generation of A's EClasses if you extend A's Generator.

    This approach is a kind of inheritance, since proposal, validation, etc classes are extended by A's counterparts. I didn't find out if multiple inheritance is supported. You can place a comma after with A but it doesn't work.