antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.03k stars 3.27k forks source link

Generate Java 17 sealed classes? #3282

Open ice1000 opened 3 years ago

ice1000 commented 3 years ago

So for code like this:

expr : atom                            # single
     | expr argument+                  # app
     | NEW_KW expr LBRACE newArg* RBRACE # new
     | <assoc=right> expr TO expr      # arr
     | expr projFix                    # proj
     | LSUC_KW atom                    # lsuc
     | LMAX_KW atom+                   # lmax
     | PI tele+ TO expr                # pi
     | SIGMA tele+ SUCHTHAT expr       # sigma
     | LAMBDA tele+ (IMPLIES expr?)?   # lam
     | MATCH exprList clauses          # match
     ;

ANTLR4 generate some abstract 'XXContext` classes as AST representations, extended by a fixed number of subclasses: image

But with modern versions of Java, we have sealed classes that allow us to pattern match against them. Would you consider adding an option to add a sealed modifier to these generated superclasses?

It is very easy to do: just add a modifier sealed to the classes with subclasses and you're done :wink:.

ice1000 commented 3 years ago

I think it's this line: https://github.com/antlr/antlr4/blob/ce3c483ec50592d8e265c644e31ec5e8261c87fb/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg#L787

We need to add a sealed modifier when the option is turned on and there are subclasses of it. I am unsure if it sounds ok to do, but I've just made sure myself that this is not very hard (technically)