Skip to content

Java: add foldInit to FoldVisitor#570

Open
zafer-esen wants to merge 1 commit into
BNFC:masterfrom
zafer-esen:java-fold-paramorphism
Open

Java: add foldInit to FoldVisitor#570
zafer-esen wants to merge 1 commit into
BNFC:masterfrom
zafer-esen:java-fold-paramorphism

Conversation

@zafer-esen

Copy link
Copy Markdown

FoldVisitor folds over the AST using leaf(arg) (as base value) and combine. This works well, but sometimes accessing the node itself is useful, this is currently not possible without overriding every single visit method.

This PR adds foldInit(Object p, A arg), defaulting to leaf(arg) . Visit methods now use R r = foldInit(p, arg) instead of R r = leaf(arg). Existing subclasses are unaffected. foldInit takes Object because AST classes don't share a common base type (a common base type would also be useful, for instance to easily access line numbers, although I am not sure how that would be best implemented).

(This change extends the fold from a catamorphism to a paramorphism.)

For example, counting AST nodes of a specific type using the proposed extension:

new FoldVisitor<Integer, Void>() {
    public Integer leaf(Void arg) { return 0; }
    public Integer combine(Integer x, Integer r, Void arg) { return x + r; }
    public Integer foldInit(Object p, Void arg) {
        return (p instanceof EInt) ? 1 : 0;
    }
}

Without foldInit, this requires overriding visit for every AST class, because leaf only receives arg, not the node p.

Includes a doctest and a changelog entry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant