Search code examples
xtext

Allow multiline String in xtext grammar to embed javascript code


I am writing a small "language" to create javascript code. Essentially it is hiding/showing some html form elements. But i need to add custom javascript code to some, e.g. what to do on a click-event.

Action:
  'on' eventName=ID 'do' code=CODE
;

terminal BEGIN: "!$";
terminal END: "$!";

terminal CODE:
  BEGIN -> END
;

I can now create an Eclipse-Plugin and code in my language, but the value of the field code contains the BEGIN and END characters.

on eventName do !$
    var x = thisIsJavaScript();
    console.log(x); 
$!

My value is:

!$
var x = thisIsJavaScript();
console.log(x);             
$!

I want only the part in between without !$ and $!.

Any hint is appreciated.

Thank you very much!


Solution

  • you should write a valueconverter for your terminal rule

    import org.eclipse.xtext.common.services.DefaultTerminalConverters;
    import org.eclipse.xtext.conversion.IValueConverter;
    import org.eclipse.xtext.conversion.ValueConverter;
    import org.eclipse.xtext.conversion.ValueConverterException;
    import org.eclipse.xtext.nodemodel.INode;
    
    import com.google.inject.Inject;
    
    public class MyDslConverters extends DefaultTerminalConverters {
    
        @Inject
        private CODEValueConverter codeValueConverter;
    
        @ValueConverter(rule = "CODE")
        public IValueConverter<String> CODE() {
            return codeValueConverter;
        }
    
        public static class CODEValueConverter implements IValueConverter<String> {
    
            @Override
            public String toValue(String string, INode node) throws ValueConverterException {
                return string.substring(2, string.length()-2);
            }
    
            @Override
            public String toString(String value) throws ValueConverterException {
                return "!$" + value + "$!";
            }
    
        }
    
    }