r/ProgrammingLanguages • • Oct 02 '26

Please advise on adding string interpolation to my Crafting Interpreters project.

I'm about to start chapter 21 of Crafting Interpreters. I'm using modern C++ instead of C. I am attempting to add string interpolation to the compiler.

My goal is to have a string that looks like this:

"Five plus ${ 10 - 5 } == 10."

Desugar to this after the expression in the braces is evaluated:

"Five plus " + 5 + " == 10."

I have code that is correctly parsing strings and concatenating them if there isn't any string interpolation.

I have a custom token added that is produced if the string contains a ${. It calls a custom string interpolation parser rule that is different than my standard string parser rule.

In that function I push the first part of the string to the stack. It then pushes a plus opcode and Recursively parses the expression in the braces adding that expression to the stack. It then adds another opcode to add and this is where I'm stuck.

I can't come up with a solution for pushing the remaining piece of the string to the stack from inside the string interpolation parser rule function. After I call the books expression function and consume the right brace token using the books consume function the parser nolonger knows we are still inside a string. If the next character after the brace is a space it's skipped. In my above example it assumes I want equal equal.

How would you set the current token back to string so I can push any remaining characters onto the stack as another string? Should I just insert a new string token into the parser? This seems wrong to me. The current and previous tokens are private members of my parser class for a reason and I've not needed setter member functions so far.

Sorry I don't have code to show. I'd like to try and get help that isn't code specific so that I have to implement this myself.

Any input would be helpful.

Thanks.

13 Upvotes

14 comments sorted by

View all comments

2

u/joao_rosac Oct 06 '26

O problema é que o seu Scanner não tem memória: quando ele esbarra no }, ele simplesmente esquece que estava no meio de uma string e volta a ler código normal.

Como o seu Parser (que está avaliando o 10 - 5) sabe exatamente quando a expressão termina, cria uma função para ele forçar o Scanner. Assim que o Parser consumir o }, ele grita pro Scanner: "Volta a ler o próximo caractere como continuação de string".

Você cria uma máquina de estados dentro do Scanner. Ele entra no "Modo String". Quando vê ${, muda pro "Modo Código" e começa a contar quantas chaves { } abrem e fecham. Quando a conta zera, ele volta pro "Modo String" sozinho.

1

u/Usual_Office_1740 Oct 06 '26

What I'm reading in this post is that I get to once again write some std::variant and std::visitor code because I'm going to have the same problem with the dynamic array, map and custom object scanning that I am about to implement. Thanks for pointing this out.