munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.42k stars 1.01k forks source link

Regular block comment nesting #1150

Closed AlexanderFarkas closed 6 months ago

AlexanderFarkas commented 6 months ago

I'm currently reading this beautiful book, and was a bit curious about this task:

Add support to Lox’s scanner for C-style / ... / block comments. Make sure to handle newlines in them. Consider allowing them to nest. Is adding support for nesting more work than you expected? Why?

I managed to do it without additional variable tracking nesting. In Java:

private void skipBlockComment() {
        while (!isAtEnd()) {
            if (peek() == '/' && peekNext() == '*') {
                advance();
                advance();
                skipBlockComment();
            }
            if (peek() == '*' && peekNext() == '/') {
                break;
            }
            if (peek() == '\n') {
                line++;
            }
            advance();
        }

        if (isAtEnd()) {
            Lox.error(line, "Unclosed block comment");
        } else {
            advance();
            advance();
        }
    }

Is recursion considered additional state? Or my implementation is just wrong?

munificent commented 6 months ago

Is recursion considered additional state?

Yes. :)

Or my implementation is just wrong?

Your implementation works.