munificent / craftinginterpreters

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

Wrong output for ASTPrinter on CallExpression. #855

Closed nicdard closed 3 years ago

nicdard commented 3 years ago

https://github.com/munificent/craftinginterpreters/blob/cc8a0803abfa547bbb2bf1fa4b7847efd510d2cb/java/com/craftinginterpreters/lox/AstPrinter.java#L145-L147

The list of arguments when passed to the parenthesize2 function is interpreted as an object (not as a list of expressions) and the individual elements are not then printed.

I would suggest to change the parenthesize2 function body to handle a List Object using a recursive helper function:

 private String parenthesize2(String name, Object ...parts) {
        StringBuilder builder = new StringBuilder();
        builder.append("(").append(name);
        transform(builder, parts);
        builder.append(")");
        return builder.toString();
 }

The helper function:

private void transform(StringBuilder builder, Object... parts) {
        for (Object part : parts) {
            builder.append(" ");
            if (part instanceof Expr) {
                builder.append(((Expr)part).accept(this));
            } else if (part instanceof Stmt) {
                builder.append(((Stmt) part).accept(this));
            } else if (part instanceof Token) {
                builder.append(((Token) part).lexeme);
            } else if (part instanceof List) {
                transform(builder, ((List) part).toArray());
            } else {
                builder.append(part);
            }
        }
    }

P.S. Thank you for the marvelous book, I find it a precious resource!

munificent commented 3 years ago

Thanks for the fix!