Easy String Interpolation with ANTLR

As of recently, I have been working on Fray, a pet project whose goal is producing a productive language with several compile targets, and tree-shaking. The Fray compiler and interpreter use a pipeline of transformers that modify input source before execution or compilation. Several language features are implemented as transformers, most notably string interpolation. After using a tedious, regex-based solution, I ultimately migrated my string interpolation rules into an entirely new ANTLR grammar, and the results were fantastic.

In Fray, the following strings are valid:

"Hello, world!" // No interpolation
"Hello, %name!" // Shorter syntax for a single variable
"Hello, %{user.name}!" // Full expression
"Battery: 100\%" // Escaped percent symbol

The following grammar addresses this:

grammar FrayInterpolation;
SIMPLE_STRING: ((~'%')|('\\%'))+;
ID_STRING: '%' [A-Za-z_] [A-Za-z0-9_]*;
COMPLEX_STRING: '%{' ~('}'|'\n')* '}';
string: interpolationElement*; 
interpolationElement:    
SIMPLE_STRING #NoInterpolation
| ID_STRING #IdentifierInterpolation
| COMPLEX_STRING #ComplexInterpolation;

Now, I can expand interpolated strings to concatenation expressions, with zero headache.


Feel free to follow me on Twitter: @_wapaa_