Search code examples
inheritancextextecore

Ecore EClass inheritance in Xtext


Consider the following Ecore model (in Xcore notation):

class Foo {
    contains Element[] elements
}
class Bar extends Foo {
    int n
}
class Element {
    String name
}

and the following Xtext rules:

FooBar: Foo | Bar;
Foo: {Foo} 'foo' '{' elements+=Element (',' elements+=Element)* '}';
Foo: {Bar} 'bar' n=INT '{' elements+=Element (',' elements+=Element)* '}';
Element: {Element} name=ID;

such that textual models are like this:

foo {one, two}
bar 2 {three, four}

Is there a way to refactor the repetition away from the rules? I know I could introduce a new EClass ElementContain and make rules for Foo and Bar refer to its rule, however, that would clutter the metamodel.


Solution

  • generally: no. but if the only difference is the first keyword:

    FooBar:
     ({Foo} 'foo' | {Bar}'bar') '{' elements+=Element (',' elements+=Element)* '}';
    Element: {Element} name=ID;