6

Is it a lexer's job to undo any escaping done to a string literal? For example:

"Me: \"Hello World!\""

Becomes:

Me: "Hello World!"

Should this conversion be done inside the lexer? I am guessing it should, because it'd allow for a more abstract and modular design. You could add ways to represent strings and you won't have to update every component.

1 Answer 1

4

If you are implementing something close to string literals in C, then yes. This is because at the level of the parser, you are only concerned about something being a string literal and not how they are implemented.

But if you have some additional requirement such as the double quotes appearing inside the string literal must be matched (i.e., "\"" is invalid). Then this can only be captured only using a context free grammar and can only be handled by a parser.

5
  • 2
    The second paragraph is incorrect. Escapes can be handled easily by the lexer, as shown in this Lex/Flex example: stackoverflow.com/questions/5418181/… Commented May 3, 2014 at 12:24
  • @Blrfl: Please re-read that second paragraph. It isn't about handling escapes, but about the fact that a lexer can't deal with a balanced quotes/parentheses problem, even within a string-literal. Commented May 3, 2014 at 12:52
  • 1
    What kind of language permits arbitrarily nested balanced quotes? I only know of "using "" to signify a single quote". Commented May 3, 2014 at 13:05
  • @BartvanIngenSchenau: You're right that I misinterpreted the paragraph, but it's still bogus. You couldn't write a (correct) parser for a requirement like that because "foo" bar "baz" would be valid but ambiguous. Commented May 3, 2014 at 17:29
  • @BartvanIngenSchenau Lexers can handle balanced constructs using the starting condition stack, i.e. yy_push_state() and yy_pop_state(), etc. Commented Aug 2, 2015 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.