Search code examples
grammarxtext

Generate names for nested element


I have a grammar like this:

Entity:
    'entity' name=ID '{'
        (properties+=Property)*

        (revision=Revision)?
    '}'

Revision:
    'revision' '{'
        (properties+=Property)+
    '}'

The editor gives me lots of errors for the revisions because they don't have a name. Since a revision is always a child of Entity, can I assign it a name automatically? Something like name=this.parent.name + "_REV"?


Solution

  • The solution is to extend DefaultDeclarativeQualifiedNameProvider:

    import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider;
    import org.eclipse.xtext.naming.QualifiedName;
    import model.Revision;
    
    public class ModelQualifiedNameProvider extends DefaultDeclarativeQualifiedNameProvider {
    
        public final static String REVISION_TABLE_EXTENSION = "_REV";
        public final static String REVISION_TYPE_EXTENSION = "Rev";
    
        public QualifiedName qualifiedName( Revision obj ) {
            QualifiedName qn = getFullyQualifiedName( obj.eContainer() );
    
            String typeName = qn.getLastSegment() + REVISION_TABLE_EXTENSION;
    
            QualifiedName result = qn.skipLast( 1 );
            result = result.append( typeName );
    
            return result;
        }
    
    }
    

    Make sure you get the method signature right! Xtext reflectively invokes QualifiedName qualifiedName(MyType ele) and if you upgrade from 1.0 to 2.0, don't forget to update the signature: Change the return type from String to QualifiedName