Top

Value Converter

Value converters are registered to convert the parsed text into a data type instance and vice versa. The primary hook is the IValueConverterService (src) and the concrete implementation can be registered via the runtime Guice module. Simply override the corresponding binding in your runtime module like shown in this example:

@Override
public Class<? extends IValueConverterService> 
        bindIValueConverterService() {
      return MySpecialValueConverterService.class;
}

The most simple way to register additional value converters is to make use of AbstractDeclarativeValueConverterService (src), which allows to declaratively register an IValueConverter (src) by means of an annotated method.

@ValueConverter(rule = "MyRuleName")
public IValueConverter<MyDataType> getMyRuleNameConverter() {
    return new MyValueConverterImplementation();
}

If you use the common terminals grammar org.eclipse.xtext.common.Terminals you should extend the DefaultTerminalConverters (src) and override or add value converters by adding the respective methods. In addition to the explicitly defined converters in the default implementation, a delegating converter is registered for each available EDataType. The delegating converter reuses the functionality of the corresponding EMF EFactory.

Many languages introduce a concept for qualified names, i.e. names composed of namespaces separated by a delimiter. Since this is such a common use case, Xtext provides an extensible converter implementation for qualified names. The QualifiedNameValueConverter (src) handles comments and white space gracefully and is capable to use the appropriate value converter for each segment of a qualified name. This allows for individually quoted segments. The domainmodel example shows how to use it.

The protocol of an IValueConverter (src) allows to throw a ValueConverterException (src) if something went wrong. The exception is propagated as a syntax error by the parser or as a validation problem by the ConcreteSyntaxValidator (src) if the value cannot be converted to a valid string. The AbstractLexerBasedConverter (src) is useful when implementing a custom value converter. If the converter needs to know about the rule that it currently works with, it may implement the interface IValueConverter.RuleSpecific (src). The framework will set the rule such as the implementation may use it afterwards.