eclipse-xtext / eclipse-xtext/xtext

Adding a field to an anonymous class in a method produces invalid Java code

Open
#2,330 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug confirmed
Dominant language
Java
Stars
831
Forks
330
Avg merge
3d 7h
Merged PRs (30d)
12

Description

import org.eclipse.emf.common.util.AbstractTreeIterator

class Test {
  def test() {
    new AbstractTreeIterator(new Object()) {
      val thing = newLinkedHashSet
      override protected getChildren(Object object) {
        throw new UnsupportedOperationException("TODO: auto-generated method stub")
      }
    }
  }
}

The 2.26.0.v20220228-0901 compiler produced invalid Java for this by defining a constructor with a final ? object argument:

  public AbstractTreeIterator test() {
    abstract class __Test_1 extends AbstractTreeIterator {
      __Test_1(final ? object) {
        super(object);
      }
      
      LinkedHashSet<Object> thing;
    }
    
    Object _object = new Object();
    return new __Test_1(_object) {
      {
        thing = CollectionLiterals.<Object>newLinkedHashSet();
      }
      @Override
      protected Iterator getChildren(final Object object) {
        throw new UnsupportedOperationException("TODO: auto-generated method stub");
      }
    };
  }

It's also a bit odd that it's creating a local named class inside the method only to leave all of the initialisation and override logic in an anonymous subclass of that class it has just defined anyway. Maybe this is related, but I can live with it if it's not.

I'm sure that I've defined a field inside an anonymous class elsewhere, so I can only assume that there's something specific about AbstractTreeIterator that breaks it. new AbstractTreeIterator<Object>(new Object()) { ... } doesn't avoid the issue.

It's easy enough to define the field as a local variable outside the anonymous class, but that's a bit naff.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied Test reproducer and compare its generated Java with the expected valid output, focusing on the anonymous class created inside test(). Trace the compiler path that handles the AbstractTreeIterator constructor and the field initialization. Done means the reproducer compiles to valid Java while preserving the anonymous-class field and override behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.