Skip to content

[core] Make visitors generic #880

@oowekyala

Description

@oowekyala

TODO

Language modules to port:

Cleanup after this:

  • [core, ...] Finish generic visitors #2746 Cleanup the wrapper scripts
  • [ ] Remove default implementation in Node "I think it's useful to have a default as some languages do not support visitors (eg we have XML)"

Use case

It's a somewhat common pattern to use a single data Object during the full visitation of a visitor, and pass it around to children to accumulate results. A Rule for instance accumulates violations in a RuleContext, whereas in the metrics framework, there are several examples (see eg ncss or cyclo) of using a visitor to eg count some nodes.

The point isn't that it's a single object that's passed around as data, but that the data object keeps the same type throughout the visitation. As you can see in the two examples with ncss and cyclo, we use data as a counter. The fact that data is of type Object instead of MutableInt obscures the code with a lot of casts though.

Generic visitor

These casts could be spared if JavaParserVisitor were generic, eg:

public interface JavaParserVisitor<T>
{
  public T visit(JavaNode node, T data);
  public T visit(ASTCompilationUnit node, T data);
  public T visit(ASTPackageDeclaration node, T data);
  // ...
}

Compatibility

Type erasure would replace T with Object in concrete subclasses, so the generic and non generic versions would be identical after compilation. A class implementing the raw type would again be identical to the original version, so AFAIK this change is free (is it?)

Implementation

The JavaParserVisitor interface is generated by JavaCC, so we can't modify it directly. We could simply create another interface based on a copy paste and generify it, but we'd need to keep it up to date by hand. Another solution would be to modify javacc itself, which looks easy enough

Metadata

Metadata

Assignees

No one assigned

    Labels

    in:astAbout the AST structure or API, the parsing step

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions