Suppose I want to embed literal Elixir code inside some other file format that already exists. To make it more concrete, I’m parsing (or @kip is, but we’re kinda working together) the ICU message format. The ICU message format supports interpolation using the following syntax:
"Good day, {username}"
as well as more complex elements such as plurals:
"{n, plural, one {Un ejemplo} other {# ejemplos}}
If I wantet to support something like
"Good day, {@username}"
or
"Good day, {get_username_from_context()}"
it would be helpful to have a function that parses the first valid elixir expression out of a string and returns the rest of the string. For example:
iex> Code.read_first_expression("a + b(x) the rest is not valid Elixir")
{quote(do: a + b(x)), " the rest is not valid Elixir"}
iex> Code.read_first_expression("a + b(x), plural, ...}")
{quote(do: a + b(x)), ", plural, ...}"}
Currently the only way I can think of doing this is by performing a binary search on the string while using Code.string_to_quoted/1
as an oracle.
NB: I’m aware I can do much better with simple heuristics, I’m asking more out of curiosity. NO I CAN’T AND THIS IS STUPID