3

I'm trying to get my head around how to write grammar which will first parse an input for strings, and then when strings are found, parse that string.

For example, if I had an input such as:

var1 = "world"
someVariable = "hello {{var1}}"

The result I want is for someVariable to be equal to "hello world".

Now, I understand how to write the grammar to set a variable to a string, but what I cannot figure out is how to parse that string for the mustache syntax in order to inject the value inside of var1.

Thanks in advance!

Shawn Clake
  • 181
  • 1
  • 7

2 Answers2

1

It's easier to do this in two steps:

  • Parse the input as usual (i.e. to determine the assignments, without analyzing the contents of the strings)
  • Then evaluate the assignments
    • While assigning a string to a variable, parse its contents with another parser (or perhaps even just with regex if the syntax is simple enough) to determine any replacements.
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
  • Thanks, I ended up implementing this functionality with regex. Out of curiosity, is having multiple parsers good practice in Antlr? – Shawn Clake Jun 05 '18 at 13:53
  • I don't know about "good practice in ANTLR", but the two are principally two different languages, one interpreting strings that the other considers just data with no inner semantics. – Jiri Tousek Jun 05 '18 at 17:40
0

That is not what ANTLR does. ANTLR can surely parse your input, and even tokenise "hello {{var1}}" separately1, but it does not evaluate var1 and substitute it. That is something you will need to do after ANTLR is done parsing2.

  1. checkout the docs on lexical modes: https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md#lexical-modes
  2. this Q&A shows a simple example how to evaluate something using a visitor: If/else statements in ANTLR using listeners
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • I agree with you. I suppose I could've been more specific with my question. I already have the visitor pattern built and working for utilizing variables. What I can't figure out is how to parse the contents of those strings seperately using lexical modes. The documentation is quite sparse. – Shawn Clake Jun 05 '18 at 01:57