Giter Site home page Giter Site logo

eclipse.jdt.core's Introduction

JDT Core

This is the core part of Eclipse's Java development tools. It contains the non-UI support for compiling and working with Java code, including the following:

  • an incremental or batch Java compiler that can run standalone or as part of the Eclipse IDE
  • Java source and class file indexer and search infrastructure
  • a Java source code formatter
  • APIs for code assist, access to the AST and structured manipulation of Java source.

For more information and important links, refer to the JDT wiki page or the JDT project overview page.

Snapshot builds

Contributing

Contributions are always welcome!

Please bear in mind that this project is almost entirely developed by volunteers. If you do not provide the implementation yourself (or pay someone to do it for you), the bug might never get fixed. If it is a serious bug, other people than you might care enough to provide a fix.

License

Eclipse Public License (EPL) v2.0

Links

eclipse.jdt.core's People

Contributors

aclement avatar akurtakov avatar asbharadwaj avatar brychcy avatar dmegert avatar ecljpseb0t avatar gayanper avatar guw avatar iloveeclipse avatar jarthana avatar jespersm avatar jjohnstn avatar jukzi avatar julianjho avatar ktatavarthi avatar laeubi avatar mateusz-matela avatar mickaelistria avatar mkeller avatar mpalat avatar othomann avatar sarikasinha avatar snjeza avatar sravanlakkimsetti avatar srikanth-sankaran avatar stephan-herrmann avatar sxenos avatar trancexpress avatar vik-chand avatar vogella avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eclipse.jdt.core's Issues

DeduplicationUtilTest fails randomly

See

I believe I've saw it also failing in some gerrit recently.

expected same:<[aNeverUsedBefore]> was not:<[aNeverUsedBefore]>

junit.framework.AssertionFailedError: expected same:<[aNeverUsedBefore]> was not:<[aNeverUsedBefore]>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotSame(Assert.java:325)
at junit.framework.Assert.assertSame(Assert.java:288)
at junit.framework.Assert.assertSame(Assert.java:296)
at junit.framework.TestCase.assertSame(TestCase.java:434)
at org.eclipse.jdt.core.tests.compiler.DeduplicationUtilTest.assertDeduplicationObject(DeduplicationUtilTest.java:108)
at org.eclipse.jdt.core.tests.compiler.DeduplicationUtilTest.testDeduplication(DeduplicationUtilTest.java:40)

I assume the GC isn't executed yet, so it is still returns previously cached but yet not GC released object.
May be some extra wait time could help. I will push a PR.

Search is waiting for a background job, but no thread has any matching activity

After jumping through some more maven hoops, I managed to get stacktraces from the freeze: freeze-jstack.txt

two interesting portions extracted here:

"main" #1 prio=5 os_prio=0 cpu=32921,05ms elapsed=181,43s tid=0x00007fdd680261e0 nid=0x35536 in Object.wait()  [0x00007fdd6fb78000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
	at java.lang.Object.wait(java.base@17/Native Method)
	- waiting on <no object reference available>
	at org.eclipse.jdt.internal.core.search.processing.JobManager.performConcurrentJob(JobManager.java:284)
	- locked <0x00000000c05bbbe0> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager)
	at org.eclipse.jdt.internal.core.search.BasicSearchEngine.searchAllTypeNames(BasicSearchEngine.java:1923)
	at org.eclipse.jdt.internal.core.search.BasicSearchEngine.searchAllTypeNames(BasicSearchEngine.java:1751)
	at org.eclipse.jdt.core.search.SearchEngine.searchAllTypeNames(SearchEngine.java:1100)
	at org.eclipse.jdt.core.tests.model.AbstractJavaModelTests.waitUntilIndexesReady(AbstractJavaModelTests.java:3967)
	at org.eclipse.jdt.core.tests.dom.ASTConverterBugsTest.setUpSuite(ASTConverterBugsTest.java:41)
...
"Java indexing" #31 daemon prio=5 os_prio=0 cpu=871,25ms elapsed=178,36s tid=0x00007fdd68640200 nid=0x355bb in Object.wait()  [0x00007fdd402f9000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(java.base@17/Native Method)
	- waiting on <no object reference available>
	at java.lang.Object.wait(java.base@17/Object.java:338)
	at org.eclipse.jdt.internal.core.search.processing.JobManager.run(JobManager.java:419)
	- locked <0x00000000c05bbbe0> (a org.eclipse.jdt.internal.core.search.indexing.IndexManager)
	at java.lang.Thread.run(java.base@17/Thread.java:833)

I read this as: search is waiting for a background job, but no thread has any matching activity.

Originally posted by @stephan-herrmann in #38 (comment)

IllegalStateException: Preference node "org.eclipse.jdt.core" has been removed.

Recently I often get many errors like the one below saying Preference node "org.eclipse.jdt.core" has been removed.
The stack-trace is often different, coming from different code-paths but always ends at org.eclipse.jdt.internal.core.JavaModelManager.getOption(JavaModelManager.java:2311) trying to read from a removed preference node.

The affected project don't have project specific settings and therefore no .settings/jdt..prefs file. But that worked well in the past.
The errors mainly show up while interactive rebasing but then can be annoying because a lot of things start to fail and I get multiple windows popping up warning me about failures for example in the clean-up actions or while reconceiling the AST.

The Eclipse-IDE is Version: 2022-06 M1 (4.24.0 M1), Build id: 20220414-1707

Java Model Exception: java.lang.IllegalStateException: Preference node "org.eclipse.jdt.core" has been removed.
	at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:326)
	at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:348)
	at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:193)
	at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:94)
	at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:740)
	at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:806)
	at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1319)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:132)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:94)
	at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:91)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:158)
	at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:94)
	at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:107)
	at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:76)
	at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207)
Caused by: java.lang.IllegalStateException: Preference node "org.eclipse.jdt.core" has been removed.
	at org.eclipse.core.internal.preferences.EclipsePreferences.checkRemoved(EclipsePreferences.java:165)
	at org.eclipse.core.internal.resources.ProjectPreferences.internalGet(ProjectPreferences.java:495)
	at org.eclipse.core.internal.preferences.EclipsePreferences.get(EclipsePreferences.java:444)
	at org.eclipse.jdt.internal.core.JavaModelManager.getOption(JavaModelManager.java:2311)
	at org.eclipse.jdt.internal.core.JavaProject.getOption(JavaProject.java:2148)
	at org.eclipse.jdt.internal.core.AbstractClassFile.validateClassFile(AbstractClassFile.java:416)
	at org.eclipse.jdt.internal.core.AbstractClassFile.validateExistence(AbstractClassFile.java:498)
	at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:252)
	at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:597)
	at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:328)
	at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:314)
	at org.eclipse.jdt.internal.core.JavaElement.exists(JavaElement.java:231)
	at org.eclipse.jdt.internal.core.Openable.exists(Openable.java:208)
	at org.eclipse.jdt.internal.core.ModularClassFile.exists(ModularClassFile.java:317)
	at org.eclipse.jdt.internal.core.PackageFragmentRoot.getSourceModuleDescription(PackageFragmentRoot.java:927)
	at org.eclipse.jdt.internal.core.PackageFragmentRoot.getModuleDescription(PackageFragmentRoot.java:904)
	at org.eclipse.jdt.internal.core.JarPackageFragmentRoot.getModuleDescription(JarPackageFragmentRoot.java:307)
	at org.eclipse.jdt.internal.core.NameLookup.getModuleDescription(NameLookup.java:944)
	at org.eclipse.jdt.internal.core.SearchableEnvironment.getModuleDescription(SearchableEnvironment.java:1085)
	at org.eclipse.jdt.internal.core.SearchableEnvironment.getModulesDeclaringPackage(SearchableEnvironment.java:1015)
	at org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment.getUniqueModulesDeclaringPackage(IModuleAwareNameEnvironment.java:113)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.computePackageFrom(LookupEnvironment.java:745)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromCompoundName(LookupEnvironment.java:1771)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromConstantPoolName(LookupEnvironment.java:1821)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromConstantPoolName(LookupEnvironment.java:1829)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromSignature(LookupEnvironment.java:1899)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.createFields(BinaryTypeBinding.java:860)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.cachePartsFrom(BinaryTypeBinding.java:610)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:1055)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:1036)
	at org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:308)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:257)
	at org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:114)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:248)
	at org.eclipse.jdt.internal.compiler.lookup.PackageBinding.getTypeOrPackage(PackageBinding.java:252)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.findImport(CompilationUnitScope.java:551)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.findSingleImport(CompilationUnitScope.java:623)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.faultInImports(CompilationUnitScope.java:452)
	at org.eclipse.jdt.internal.compiler.lookup.Scope.getBinding(Scope.java:2221)
	at org.eclipse.jdt.internal.compiler.ast.FieldDeclaration.resolve(FieldDeclaration.java:235)
	at org.eclipse.jdt.internal.compiler.lookup.FieldBinding.constant(FieldBinding.java:223)
	at org.eclipse.jdt.internal.compiler.ast.FieldReference.generateCode(FieldReference.java:254)
	at org.eclipse.jdt.internal.compiler.ast.Expression.generateOptimizedStringConcatenation(Expression.java:893)
	at org.eclipse.jdt.internal.compiler.codegen.CodeStream.generateStringConcatenationAppend(CodeStream.java:2635)
	at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.generateCode(BinaryExpression.java:157)
	at org.eclipse.jdt.internal.compiler.ast.ConditionalExpression.generateCode(ConditionalExpression.java:313)
	at org.eclipse.jdt.internal.compiler.ast.Statement.generateArguments(Statement.java:443)
	at org.eclipse.jdt.internal.compiler.ast.AllocationExpression.generateCode(AllocationExpression.java:212)
	at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.generateCode(ReturnStatement.java:211)
	at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.generateCode(AbstractMethodDeclaration.java:354)
	at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.generateCode(AbstractMethodDeclaration.java:291)
	at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.generateCode(TypeDeclaration.java:761)
	at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.generateCode(TypeDeclaration.java:831)
	at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.generateCode(CompilationUnitDeclaration.java:412)
	at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1072)
	at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1108)
	at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:282)
	... 15 more
Caused by: java.lang.IllegalStateException: Preference node "org.eclipse.jdt.core" has been removed.
	at org.eclipse.core.internal.preferences.EclipsePreferences.checkRemoved(EclipsePreferences.java:165)
	at org.eclipse.core.internal.resources.ProjectPreferences.internalGet(ProjectPreferences.java:495)
	at org.eclipse.core.internal.preferences.EclipsePreferences.get(EclipsePreferences.java:444)
	at org.eclipse.jdt.internal.core.JavaModelManager.getOption(JavaModelManager.java:2311)
	at org.eclipse.jdt.internal.core.JavaProject.getOption(JavaProject.java:2148)
	at org.eclipse.jdt.internal.core.AbstractClassFile.validateClassFile(AbstractClassFile.java:416)
	at org.eclipse.jdt.internal.core.AbstractClassFile.validateExistence(AbstractClassFile.java:498)
	at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:252)
	at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:597)
	at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:328)
	at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:314)
	at org.eclipse.jdt.internal.core.JavaElement.exists(JavaElement.java:231)
	at org.eclipse.jdt.internal.core.Openable.exists(Openable.java:208)
	at org.eclipse.jdt.internal.core.ModularClassFile.exists(ModularClassFile.java:317)
	at org.eclipse.jdt.internal.core.PackageFragmentRoot.getSourceModuleDescription(PackageFragmentRoot.java:927)
	at org.eclipse.jdt.internal.core.PackageFragmentRoot.getModuleDescription(PackageFragmentRoot.java:904)
	at org.eclipse.jdt.internal.core.JarPackageFragmentRoot.getModuleDescription(JarPackageFragmentRoot.java:307)
	at org.eclipse.jdt.internal.core.NameLookup.getModuleDescription(NameLookup.java:944)
	at org.eclipse.jdt.internal.core.SearchableEnvironment.getModuleDescription(SearchableEnvironment.java:1085)
	at org.eclipse.jdt.internal.core.SearchableEnvironment.getModulesDeclaringPackage(SearchableEnvironment.java:1015)
	at org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment.getUniqueModulesDeclaringPackage(IModuleAwareNameEnvironment.java:113)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.computePackageFrom(LookupEnvironment.java:745)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromCompoundName(LookupEnvironment.java:1771)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromConstantPoolName(LookupEnvironment.java:1821)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromConstantPoolName(LookupEnvironment.java:1829)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getTypeFromSignature(LookupEnvironment.java:1899)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.createFields(BinaryTypeBinding.java:860)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.cachePartsFrom(BinaryTypeBinding.java:610)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:1055)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.createBinaryTypeFrom(LookupEnvironment.java:1036)
	at org.eclipse.jdt.internal.compiler.Compiler.accept(Compiler.java:308)
	at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:257)
	at org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:114)
	at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.resolveType(BinaryTypeBinding.java:248)
	at org.eclipse.jdt.internal.compiler.lookup.PackageBinding.getTypeOrPackage(PackageBinding.java:252)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.findImport(CompilationUnitScope.java:551)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.findSingleImport(CompilationUnitScope.java:623)
	at org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.faultInImports(CompilationUnitScope.java:452)
	at org.eclipse.jdt.internal.compiler.lookup.Scope.getBinding(Scope.java:2221)
	at org.eclipse.jdt.internal.compiler.ast.FieldDeclaration.resolve(FieldDeclaration.java:235)
	at org.eclipse.jdt.internal.compiler.lookup.FieldBinding.constant(FieldBinding.java:223)
	at org.eclipse.jdt.internal.compiler.ast.FieldReference.generateCode(FieldReference.java:254)
	at org.eclipse.jdt.internal.compiler.ast.Expression.generateOptimizedStringConcatenation(Expression.java:893)
	at org.eclipse.jdt.internal.compiler.codegen.CodeStream.generateStringConcatenationAppend(CodeStream.java:2635)
	at org.eclipse.jdt.internal.compiler.ast.BinaryExpression.generateCode(BinaryExpression.java:157)
	at org.eclipse.jdt.internal.compiler.ast.ConditionalExpression.generateCode(ConditionalExpression.java:313)
	at org.eclipse.jdt.internal.compiler.ast.Statement.generateArguments(Statement.java:443)
	at org.eclipse.jdt.internal.compiler.ast.AllocationExpression.generateCode(AllocationExpression.java:212)
	at org.eclipse.jdt.internal.compiler.ast.ReturnStatement.generateCode(ReturnStatement.java:211)
	at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.generateCode(AbstractMethodDeclaration.java:354)
	at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.generateCode(AbstractMethodDeclaration.java:291)
	at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.generateCode(TypeDeclaration.java:761)
	at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.generateCode(TypeDeclaration.java:831)
	at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.generateCode(CompilationUnitDeclaration.java:412)
	at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1072)
	at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1108)
	at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:282)
	at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:348)
	at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.makeConsistent(ReconcileWorkingCopyOperation.java:193)
	at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:94)
	at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:740)
	at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:806)
	at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1319)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:132)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:94)
	at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:91)
	at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:158)
	at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:94)
	at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:107)
	at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:76)
	at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:207)

Javadoc formatting escapes '{@code' sometimes

Tested with Eclipse 2022-03 and default formatting settings (and also custome ones)
When trying to use formatting the '@' in '{@code' is escaped sometimes

/**
 * <h2>Works</h2>
 * 
 * <pre>
 * {@code
final Object o = ...
 * }
 * </pre>
 *
 * <pre>
 * {@code
for (int i = 0; i< 4; i++) {
    foo();
}
 * }
 * </pre>
 *
 * <h2>Doesn't work</h2>
 * 
 * <pre>
 * {@code
final Object o = new Object();
 * }
 * </pre>
 *
 * <pre>
 * {@code
final int i = 4;
 * }
 * </pre>
 *
 * <pre>
 * {@code
class BaseImpl
        implements A, B, C {
}
class SubImpl
        extends BaseImpl
        implements X, Y, Z {
}
 * }
 * </pre>
 *
 */
public interface FormatTest {
}

the result is:

/**
 * <h2>Works</h2>
 * 
 * <pre>
 * {@code
final Object o = ...
 * }
 * </pre>
 *
 * <pre>
 * {@code
for (int i = 0; i< 4; i++) {
    foo();
}
 * }
 * </pre>
 *
 * <h2>Doesn't work</h2>
 * 
 * <pre>
 * {
 * 	&#64;code
 * 	final Object o = new Object();
 * }
 * </pre>
 *
 * <pre>
 * {
 * 	&#64;code
 * 	final int i = 4;
 * }
 * </pre>
 *
 * <pre>
 * {
 * 	&#64;code
 * 	class BaseImpl implements A, B, C {
 * 	}
 * 	class SubImpl extends BaseImpl implements X, Y, Z {
 * 	}
 * }
 * </pre>
 *
 */
public interface FormatTest {
}

Trying to create Javadoc out of the original file works without issues with javadoc (tested with javadoc from Java 8 & Java 17)

Infinite loop in rename refactor makes Eclipse 2022.3 unusable

While saving a file and letting Eclipse (2022.3) do its thing (saving, clean up, compiling) the editor of the file went blank and the GC started running awry. I was able to attach a Visual VM to the process and take two stack traces with about 1 minute time difference between one another.

I have no idea what code triggered this infinite loop, but I hope the stack traces will provide some clarity to the maintainers.

Update: Apparently I was renaming a method in a class. Also noteworthy: I had "Build automatically" turned off.

threaddump-1649936938159.tdump.txt

threaddump-1649937007990.tdump.txt

Apparently I was renaming something (a class name?) (using CTRL-1) when this infinite loop was triggered.

	at org.eclipse.jdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor.doCheckFinalConditions(RenameVirtualMethodProcessor.java:147)
	at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:51)
	at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:226)
	at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:165)
	at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:84)
	at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:41)
	at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:740)
	at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2315)
	at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2340)
	at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:5923)
	at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:108)
	at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)

Apply spec changes from JLS19 for instanceof pattern matching

Some of the changes proposed for Java 19 that will affect instanceof pattern matching are:

  1. Guard has been made specific to switch pattern matching. We no longer need to expect a guarded pattern in instanceof expressions. 2. Sec 15.20.2 - Removed restriction on pattern instanceof for total patterns. A side effect of this will be that we will now accept null references on the LHS.

There could be others. Need another closer look.

[null][external] Fine-tune merging of classpath attributes

When using https://bugs.eclipse.org/bugs/show_bug.cgi?id=526011 (to give access to external annotations of a plug-in's generated sources), we currently have a conflict with another annotation path that might be declared for the entire RequiredPluginsClasspathContainer.

In https://bugs.eclipse.org/bugs/show_bug.cgi?id=509715 I introduced a prioritization when merging classpath attributes from a referrer and a current classpath entry. The given strategy works well for transitive dependencies, but is unfortunate for classpath containers. In the latter case, the individual entry should always be considered to be more specific, and attributes on the container should only be used as a fallback.

(Later we may dive down into more fine grained merging)

ReconcilerTests.testBug36032* need the indexer

Running ReconcilerTests in isolation (i.e., outside AllJavaModelTests) hangs in testBug36032a(), stacktrace is:

        at java.lang.Thread.sleep([email protected]/Native Method)
        at org.eclipse.jdt.core.tests.model.ReconcilerTests.assertNoProblem(ReconcilerTests.java:191)
        at org.eclipse.jdt.core.tests.model.ReconcilerTests.testBug36032a(ReconcilerTests.java:3921)

In the debugger I can see four jobs in JobManager#awaitingJobs, but due to TestCase#indexDisabledForTest being true, the index manager is disabled in setUp().

1100 formatter tests failed with exact same problem on Windows/Java 11 I20220425-1800

~1100 formatter tests failed with exact same problem on Windows/Java 11 build only:

Failure seem to be a problem with restoring workspace preferences after the test. I don't think it is Windows related, it looks like some random error.

--------- Difference is ----------
expected:<... compliance level: 1[.8\n
- JDK source level: 1.8\n
- JDK target level: 1.8]\n
- verbose : OFF\...> but was:<... compliance level: 1[1\n
- JDK source level: 11\n
- JDK target level: 11]\n
- verbose : OFF\...>
at org.eclipse.jdt.core.tests.junit.extension.TestCase.assertStringEquals(TestCase.java:266)
at org.eclipse.jdt.core.tests.junit.extension.TestCase.assertEquals(TestCase.java:242)
at org.eclipse.jdt.core.tests.model.AbstractJavaModelTests.tearDown(AbstractJavaModelTests.java:3909)

Note: the code checks that JavaCore.getOptions() equals to expected defaults from org.eclipse.jdt.core.JavaCore.getDefaultOptions().

I see no immediate reason why this particular test would mess up options, nor recent related changes.

However I also do not see any code that would "fix" broken options to defaults.
I will add a change so that options are properly reset to avoid following tests might be affected by some previous failure.

[null][external] Option to refer to a dependency in a container for external annotations

Assume a set of plug-in projects that want to maintain a set of common external annotations for all their third party dependencies, because repeating the same eea in each project is cumbersome.

It is trivial to define a project / plug-in that ships eea files via (one of) its source folder.

We can also (since https://bugs.eclipse.org/574603) tell JDT to search for annotations in all classpath locations. While this is a viable solution, it may come at the price of performance, as significant more lookups need to be tried (for each type search all classpath entries for a matching .eea).

Here a new style of defining annotationPath in .classpath would help.

  • Assume your external annotations are in a plug-in my.annots
  • Assume you define a dependency on my.annots via MANIFEST.MF (i.e., let PDE figure out where to find my.annots)
  • The classpath entry for the container org.eclipse.pde.core.requiredPlugins should be able to select one of its resolved entries to contain eea for (potentially) all other entries.

I developed draft new lookup that would be able to resolve an annotation path of this shape:

	<attribute name="annotationpath" value="org.eclipse.pde.core.requiredPlugins/my.annots"/>

This would indicate:

  • resolve the annotation path relative to the container org.eclipse.pde.core.requiredPlugins
  • within the container, an entry my.annots should be searched
    • likely, any suffix indicating a version number, plus a .jar extension should be ignored during matching
    • as a heuristic, the specified name should be a prefix of the resolved container member, and the next char should not be a letter or digit (e.g., - or _ ...), so a specified my.annot matches to a resolved entry my.annot_1.0.0.202204181800.jar, while we don't need to know the actual syntax of the tail.

One might wonder if explicitly saying org.eclipse.pde.core.requiredPlugins/ is needed, because typically this declaration would happen right inside the element of that container, but also eea for the JRE could be declared using this mechanism, where the connection to the classpath container would otherwise not be given.

The nice part about using a container name to select this kind of resolving is: it can equally be used for non-plugin projects, by saying, e.g.,

	<attribute name="annotationpath" value="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER/my.annots"/>

JDT wouldn't need to know about the difference, which is key here 😄

Pattern matching for exceptions and annotation based null analysis don't play together

Consider the following code with annotation-based null-analysis enabled:

import org.eclipse.jdt.annotation.NonNullByDefault;

@NonNullByDefault
public class Test {
	private void foo(Integer param) {
		// empty
	}
	
	public void test() {
		Object o = 1;
		if (o instanceof Integer i) {
			foo(i);
		}
	}
}

i is clearly non-null because otherwise we would not enter the if block. Still the compiler does not recognize this fact an issues a warning (or error depending on project settings) The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'

"Workspace options should be back to their default" - reproducer

The infamous test failure "Workspace options should be back to their default" can be reproduced by running AllJavaModelTests with everything prior to JavaCorePreferenceModifyListenerTest disabled / commented. The sequence of JavaCorePreferenceModifyListenerTest + NullAnnotationModelTests creates the following failure (interestingly only once):

junit.framework.ComparisonFailure: Workspace options should be back to their default.
----------- Expected ------------
CompilerOptions:\n
	- local variables debug attributes: ON\n
	- line number debug attributes: ON\n
	- source debug attributes: ON\n
	- MethodParameters attributes: do not generate\n
	- Generic signature for lambda expressions: do not generate\n
	- preserve all local variables: ON\n
	- method with constructor name: warning\n
	- overridden package default method: warning\n
	- deprecation: warning\n
	- removal: warning\n
	- masked catch block: warning\n
	- unused local variable: warning\n
	- unused parameter: ignore\n
	- unused exception parameter: ignore\n
	- unused import: warning\n
	- synthetic access emulation: ignore\n
	- assignment with no effect: warning\n
	- non externalized string: ignore\n
	- static access receiver: warning\n
	- indirect static access: ignore\n
	- incompatible non inherited interface method: warning\n
	- unused private member: warning\n
	- local variable hiding another variable: ignore\n
	- field hiding another variable: ignore\n
	- type hiding another type: warning\n
	- possible accidental boolean assignment: ignore\n
	- superfluous semicolon: ignore\n
	- uncommented empty block: ignore\n
	- unnecessary type check: ignore\n
	- javadoc comment support: ON\n
		+ invalid javadoc: ignore\n
		+ report invalid javadoc tags: disabled\n
			* deprecated references: disabled\n
			* not visible references: disabled\n
		+ visibility level to report invalid javadoc tags: public\n
		+ missing javadoc tags: ignore\n
		+ visibility level to report missing javadoc tags: public\n
		+ report missing javadoc tags for method type parameters: disabled\n
		+ report missing javadoc tags in overriding methods: disabled\n
		+ missing javadoc comments: ignore\n
		+ report missing tag description option: return_tag\n
		+ visibility level to report missing javadoc comments: public\n
		+ report missing javadoc comments in overriding methods: disabled\n
	- finally block not completing normally: warning\n
	- report unused declared thrown exception: ignore\n
	- report unused declared thrown exception when overriding: disabled\n
	- report unused declared thrown exception include doc comment reference: enabled\n
	- report unused declared thrown exception exempt exception and throwable: enabled\n
	- unnecessary else: ignore\n
	- JDK compliance level: 1.8\n
	- JDK source level: 1.8\n
	- JDK target level: 1.8\n
	- verbose : OFF\n
	- produce reference info : OFF\n
	- parse literal expressions as constants : ON\n
	- encoding : UTF-8\n
	- task tags: TODO,FIXME,XXX\n
	- task priorities : NORMAL,HIGH,NORMAL\n
	- report deprecation inside deprecated code : disabled\n
	- report deprecation when overriding deprecated method : disabled\n
	- report unused parameter when implementing abstract method : disabled\n
	- report unused parameter when overriding concrete method : disabled\n
	- report unused parameter include doc comment reference : enabled\n
	- report constructor/setter parameter hiding existing field : disabled\n
	- inline JSR bytecode : enabled\n
	- share common finally blocks : disabled\n
	- report unavoidable generic type problems : enabled\n
	- unsafe type operation: warning\n
	- unsafe raw type: warning\n
	- final bound for type parameter: warning\n
	- missing serialVersionUID: warning\n
	- varargs argument need cast: warning\n
	- forbidden reference to type with access restriction: error\n
	- discouraged reference to type with access restriction: warning\n
	- null reference: warning\n
	- potential null reference: ignore\n
	- redundant null check: ignore\n
	- autoboxing: ignore\n
	- annotation super interface: warning\n
	- missing @Override annotation: ignore\n
	- missing @Override annotation for interface method implementation: enabled\n
	- missing @Deprecated annotation: ignore\n
	- incomplete enum switch: warning\n
	- raise null related warnings for variables tainted in assert statements: disabled\n
	- suppress warnings: enabled\n
	- suppress optional errors: disabled\n
	- unhandled warning token: warning\n
	- unused warning token: warning\n
	- unused label: warning\n
	- treat optional error as fatal: disabled\n
	- parameter assignment: ignore\n
	- generate class files: enabled\n
	- process annotations: disabled\n
	- unused type arguments for method/constructor invocation: warning\n
	- redundant superinterface: ignore\n
	- comparing identical expr: warning\n
	- missing synchronized on inherited method: ignore\n
	- should implement hashCode() method: ignore\n
	- dead code: warning\n
	- dead code in trivial if statement: disabled\n
	- tasks severity: warning\n
	- unused object allocation: ignore\n
	- method can be static: ignore\n
	- method can be potentially static: ignore\n
	- redundant specification of type arguments: ignore\n
	- resource is not closed: warning\n
	- resource may not be closed: ignore\n
	- resource should be handled by try-with-resources: ignore\n
	- Unused Type Parameter: ignore\n
	- pessimistic null analysis for free type variables: warning\n
	- report unsafe nonnull return from legacy method: warning\n
	- unlikely argument type for collection methods: warning\n
	- unlikely argument type for collection methods, strict check against expected type: disabled\n
	- unlikely argument types for equals(): info\n
	- API leak: warning\n
	- unstable auto module name: warning\n
	- SuppressWarnings not fully analysed: info
------------ but was ------------
CompilerOptions:\n
	- local variables debug attributes: ON\n
	- line number debug attributes: ON\n
	- source debug attributes: ON\n
	- MethodParameters attributes: do not generate\n
	- Generic signature for lambda expressions: do not generate\n
	- preserve all local variables: ON\n
	- method with constructor name: warning\n
	- overridden package default method: warning\n
	- deprecation: warning\n
	- removal: warning\n
	- masked catch block: warning\n
	- unused local variable: warning\n
	- unused parameter: ignore\n
	- unused exception parameter: ignore\n
	- unused import: warning\n
	- synthetic access emulation: ignore\n
	- assignment with no effect: warning\n
	- non externalized string: ignore\n
	- static access receiver: warning\n
	- indirect static access: ignore\n
	- incompatible non inherited interface method: warning\n
	- unused private member: warning\n
	- local variable hiding another variable: ignore\n
	- field hiding another variable: ignore\n
	- type hiding another type: warning\n
	- possible accidental boolean assignment: ignore\n
	- superfluous semicolon: ignore\n
	- uncommented empty block: ignore\n
	- unnecessary type check: ignore\n
	- javadoc comment support: ON\n
		+ invalid javadoc: ignore\n
		+ report invalid javadoc tags: disabled\n
			* deprecated references: disabled\n
			* not visible references: disabled\n
		+ visibility level to report invalid javadoc tags: public\n
		+ missing javadoc tags: ignore\n
		+ visibility level to report missing javadoc tags: public\n
		+ report missing javadoc tags for method type parameters: disabled\n
		+ report missing javadoc tags in overriding methods: disabled\n
		+ missing javadoc comments: ignore\n
		+ report missing tag description option: return_tag\n
		+ visibility level to report missing javadoc comments: public\n
		+ report missing javadoc comments in overriding methods: disabled\n
	- finally block not completing normally: warning\n
	- report unused declared thrown exception: ignore\n
	- report unused declared thrown exception when overriding: disabled\n
	- report unused declared thrown exception include doc comment reference: enabled\n
	- report unused declared thrown exception exempt exception and throwable: enabled\n
	- unnecessary else: ignore\n
	- JDK compliance level: 11\n
	- JDK source level: 11\n
	- JDK target level: 11\n
	- verbose : OFF\n
	- produce reference info : OFF\n
	- parse literal expressions as constants : ON\n
	- encoding : UTF-8\n
	- task tags: TODO,FIXME,XXX\n
	- task priorities : NORMAL,HIGH,NORMAL\n
	- report deprecation inside deprecated code : disabled\n
	- report deprecation when overriding deprecated method : disabled\n
	- report unused parameter when implementing abstract method : disabled\n
	- report unused parameter when overriding concrete method : disabled\n
	- report unused parameter include doc comment reference : enabled\n
	- report constructor/setter parameter hiding existing field : disabled\n
	- inline JSR bytecode : enabled\n
	- share common finally blocks : disabled\n
	- report unavoidable generic type problems : enabled\n
	- unsafe type operation: warning\n
	- unsafe raw type: warning\n
	- final bound for type parameter: warning\n
	- missing serialVersionUID: warning\n
	- varargs argument need cast: warning\n
	- forbidden reference to type with access restriction: error\n
	- discouraged reference to type with access restriction: warning\n
	- null reference: warning\n
	- potential null reference: ignore\n
	- redundant null check: ignore\n
	- autoboxing: ignore\n
	- annotation super interface: warning\n
	- missing @Override annotation: ignore\n
	- missing @Override annotation for interface method implementation: enabled\n
	- missing @Deprecated annotation: ignore\n
	- incomplete enum switch: warning\n
	- raise null related warnings for variables tainted in assert statements: disabled\n
	- suppress warnings: enabled\n
	- suppress optional errors: disabled\n
	- unhandled warning token: warning\n
	- unused warning token: warning\n
	- unused label: warning\n
	- treat optional error as fatal: disabled\n
	- parameter assignment: ignore\n
	- generate class files: enabled\n
	- process annotations: disabled\n
	- unused type arguments for method/constructor invocation: warning\n
	- redundant superinterface: ignore\n
	- comparing identical expr: warning\n
	- missing synchronized on inherited method: ignore\n
	- should implement hashCode() method: ignore\n
	- dead code: warning\n
	- dead code in trivial if statement: disabled\n
	- tasks severity: warning\n
	- unused object allocation: ignore\n
	- method can be static: ignore\n
	- method can be potentially static: ignore\n
	- redundant specification of type arguments: ignore\n
	- resource is not closed: warning\n
	- resource may not be closed: ignore\n
	- resource should be handled by try-with-resources: ignore\n
	- Unused Type Parameter: ignore\n
	- pessimistic null analysis for free type variables: warning\n
	- report unsafe nonnull return from legacy method: warning\n
	- unlikely argument type for collection methods: warning\n
	- unlikely argument type for collection methods, strict check against expected type: disabled\n
	- unlikely argument types for equals(): info\n
	- API leak: warning\n
	- unstable auto module name: warning\n
	- SuppressWarnings not fully analysed: info
--------- Difference is ----------
 expected:<... compliance level: 1[.8\n
	- JDK source level: 1.8\n
	- JDK target level: 1.8]\n
	- verbose : OFF\...> but was:<... compliance level: 1[1\n
	- JDK source level: 11\n
	- JDK target level: 11]\n
	- verbose : OFF\...>
	at org.eclipse.jdt.core.tests.junit.extension.TestCase.assertStringEquals(TestCase.java:266)
	at org.eclipse.jdt.core.tests.junit.extension.TestCase.assertEquals(TestCase.java:242)
	at org.eclipse.jdt.core.tests.model.AbstractJavaModelTests.tearDown(AbstractJavaModelTests.java:3936)
	at org.eclipse.jdt.core.tests.model.ReconcilerTests.tearDown(ReconcilerTests.java:334)
	at junit.framework.TestCase.runBare(TestCase.java:147)
	at junit.framework.TestResult$1.protect(TestResult.java:122)
	at junit.framework.TestResult.runProtected(TestResult.java:142)
	at junit.framework.TestResult.run(TestResult.java:125)
	at junit.framework.TestCase.run(TestCase.java:130)
	at junit.framework.TestSuite.runTest(TestSuite.java:241)
	at org.eclipse.jdt.core.tests.model.SuiteOfTestCases$Suite.runTest(SuiteOfTestCases.java:114)
	at junit.framework.TestSuite.run(TestSuite.java:236)
	at org.eclipse.jdt.core.tests.model.SuiteOfTestCases$Suite.superRun(SuiteOfTestCases.java:98)
	at org.eclipse.jdt.core.tests.model.SuiteOfTestCases$Suite$1.protect(SuiteOfTestCases.java:86)
	at junit.framework.TestResult.runProtected(TestResult.java:142)
	at org.eclipse.jdt.core.tests.model.SuiteOfTestCases$Suite.run(SuiteOfTestCases.java:95)
	at junit.framework.TestSuite.runTest(TestSuite.java:241)
	at junit.framework.TestSuite.run(TestSuite.java:236)
	at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
	at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:74)
	at org.eclipse.pde.internal.junit.runtime.CoreTestApplication.start(CoreTestApplication.java:28)
	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
	at org.eclipse.equinox.launcher.Main.run(Main.java:1467)
	at org.eclipse.equinox.launcher.Main.main(Main.java:1440)

Exception formatting code with misplaced Javadoc

Eclipse format source code breaks on an unusual example where javadoc appeared after an enum. This code is strange, but technically legal Java, I'd expect Eclipse tooling to handle it gracefully. This is a particular problem if the issue occurs in a large code base and you're trying to do a bulk format operation via source cleanup - this fails but it is not immediately clear why.

Steps

  • Try and format this with Eclipse 2021-12 (4.22.0)
public enum Test {
FOO /** random javadoc */, 
BAR
}

Expected

  • Code to be formatted

Actual

  • The formatting fails and the following exception is shown
Caused by: java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 9
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
	at java.base/java.util.Objects.checkIndex(Objects.java:372)
	at java.base/java.util.ArrayList.get(ArrayList.java:459)
	at org.eclipse.jdt.internal.formatter.TokenManager.get(TokenManager.java:76)
	at org.eclipse.jdt.internal.formatter.TokenManager.findIndex(TokenManager.java:169)
	at org.eclipse.jdt.internal.formatter.TokenManager.firstIndexBefore(TokenManager.java:213)
	at org.eclipse.jdt.internal.formatter.TokenManager.firstTokenBefore(TokenManager.java:217)
	at org.eclipse.jdt.internal.formatter.SpacePreparator.handleTokenBefore(SpacePreparator.java:1162)
	at org.eclipse.jdt.internal.formatter.SpacePreparator.handleCommas(SpacePreparator.java:1147)
	at org.eclipse.jdt.internal.formatter.SpacePreparator.visit(SpacePreparator.java:204)
	at org.eclipse.jdt.core.dom.EnumDeclaration.accept0(EnumDeclaration.java:253)
	at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:3129)
	at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:3200)
	at org.eclipse.jdt.core.dom.CompilationUnit.accept0(CompilationUnit.java:258)
	at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:3129)
	at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.prepareSpaces(DefaultCodeFormatter.java:409)
	at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.prepareFormattedCode(DefaultCodeFormatter.java:226)
	at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:183)
	at org.eclipse.jdt.internal.formatter.DefaultCodeFormatter.format(DefaultCodeFormatter.java:165)
	at org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.reformat(CodeFormatterUtil.java:361)
	at org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy.format(JavaFormattingStrategy.java:75)
	at org.eclipse.jface.text.formatter.MultiPassContentFormatter.formatMaster(MultiPassContentFormatter.java:197)
	at org.eclipse.jface.text.formatter.MultiPassContentFormatter.format(MultiPassContentFormatter.java:143)
	at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:1025)
	at org.eclipse.jface.text.source.projection.ProjectionViewer.doOperation(ProjectionViewer.java:1466)
	at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation(JavaSourceViewer.java:179)
	at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:205)
	at org.eclipse.ui.texteditor.TextOperationAction.lambda$0(TextOperationAction.java:130)
	at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:74)
	at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:130)
	at org.eclipse.jface.action.Action.runWithEvent(Action.java:474)
	at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:121)
	... 55 more

Implicit narrowing conversion in compound assignment

code assist behaves differently in two places

my usage

public class Main {

    private static void foo(String arg) {
        
    }
    
    private static void test() {
        String myArg1 = "hi";
        String myArg2 = "hi";
        // place-1
        foo(myArg1);
        foo(myArg2);
        if (true) {
            // place-2
            foo(myArg1);
            foo(myArg2);
        }
    }
}

expected behavior

I retype the method name "f|(myArg1);", auto-completion appears and I choose "foo", then I want to keep method parameters "myArg1" unchanged and get "foo(myArg1);" again.

old version

In the old version(2019-06), it seems that the settings "Fill method arguments and show guessed arguments" only take effet when type a new line "f|", not when retype "f|(myArg1);". I only need to choose "Completion overwrites", then place-1 and place-2 both work fine. The "Fill method arguments……" can be disabled.

problem

In the new version(2021-12/2022-03), it seems that the settings take effet when retype, so the auto-completed parameters is generated and not always unchanged. To keep method parameters unchanged, I must also enable "Fill method arguments……" and choose "Insert best guessed arguments"(if not, the auto-completed parameters is empty "()"). This makes place-1 works. But in place-2, the "best guessed arguments" is always "myArg2". That means I retype "foo(myArg1);" and finally get "foo(myArg2);". Is this means something wrong in the IDE's "guess strategy"? How can I keep the original arguments unchanged?

CONTRIBUTING guidelines link to outdated issue tracker URL

This repository has a CONTRIBUTING file:
https://github.com/eclipse-jdt/eclipse.jdt.core/blob/master/CONTRIBUTING

It says:

This project uses Bugzilla to track ongoing development and issues.

Both links are dead. The Bugzilla page here:
https://bugs.eclipse.org/bugs/enter_bug.cgi

Says:

JDT issues have moved to their respective repos in https://github.com/eclipse-jdt#reporting-issues

I guess the CONTRIBUTING file is outdated?

Build can't be cancelled during cleanOutputFolders() task

It is not possible to cancel autobuild, any attempts to "cancel" build job are ignored by JDT during BatchImageBuilder.cleanOutputFolders() operation.

On big projects or projects located on NFS this lead to the problem, that user can't do any task related to the workspace, not even shutdown Eclipse and have to wait till the build detects cancellation after BatchImageBuilder.cleanOutputFolders() is done.

image

Stack from debugger:

	at org.eclipse.core.internal.resources.Resource.copy(Resource.java:535)
	at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.copyResource(AbstractImageBuilder.java:394)
	at org.eclipse.jdt.internal.core.builder.BatchImageBuilder$3.visit(BatchImageBuilder.java:259)
	at org.eclipse.core.internal.resources.Resource.lambda$0(Resource.java:85)
	at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:85)
	at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:90)
	at org.eclipse.core.internal.watson.ElementTreeIterator.iterate(ElementTreeIterator.java:135)
	at org.eclipse.core.internal.resources.Resource.accept(Resource.java:94)
	at org.eclipse.core.internal.resources.Resource.accept(Resource.java:55)
	at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.copyExtraResourcesBack(BatchImageBuilder.java:227)
	at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.cleanOutputFolders(BatchImageBuilder.java:148)
	at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:65)
	at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:273)
	at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:188)
	at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:1024)
	at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
	at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:254)
	at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:311)
	at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:400)
	at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
	at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:403)
	at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:514)
	at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:462)
	at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:544)
	at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:161)
	at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:255)
	at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)

NPE in CompilationUnitResolver.getSourceClassPaths(IJavaProject) since https://bugs.eclipse.org/578928

I'm getting NPE in this call stack:

java.lang.NullPointerException
	at org.eclipse.jdt.core.dom.CompilationUnitResolver.getSourceClassPaths(CompilationUnitResolver.java:381)
	at org.eclipse.jdt.core.dom.CompilationUnitResolver.convert(CompilationUnitResolver.java:343)
	at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1272)
	at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:868)
	at org.eclipse.jdt.core.manipulation.CoreASTProvider$1.run(CoreASTProvider.java:294)
	at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
	at org.eclipse.jdt.core.manipulation.CoreASTProvider.createAST(CoreASTProvider.java:286)
	at org.eclipse.jdt.core.manipulation.CoreASTProvider.getAST(CoreASTProvider.java:199)
	at org.eclipse.jdt.core.manipulation.SharedASTProviderCore.getAST(SharedASTProviderCore.java:138)
	at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:166)
	at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup$1.run(SelectionListenerWithASTManager.java:151)
	at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)

Steps:

  • create a general project, no Java nature
  • in that project create a .java file with a minimal class declaration
  • in the (java) editor select the class name

This seems to be caused by https://git.eclipse.org/c/jdt/eclipse.jdt.core.git/commit/?id=f4c79a0498a4c3902c619d4dc7a24fa37364e908 on behalf of https://bugs.eclipse.org/578928.

I can see that the offending block existed in a different class before, but looking at the flow this looks just plain wrong:

		IClasspathEntry[] resolvedClasspath = null;
		try {
			resolvedClasspath = project.getResolvedClasspath(true);
		} catch (JavaModelException e) {
			//do nothing
		}

		for (IClasspathEntry entry : resolvedClasspath) {

Someone was literally asking for NPE on the last line shown, notably when JavaModelException actually occurs, as will be the case when !project.exists() (i.e., we're attempting to read a non-java project as a java project).

Problem opening an editor

Hello,
In that source file :

public class Test {
	
	private static final Map<String, Map<String, RErrorCode>> LOC_2_ERROR_CODES_MAP = new HashedMap<>();

	public static LabelProvider LABEL_PROVIDER = new LabelProvider() {
		public String getText(Object element) {
			return element instanceof RErrorCode ec ? ec.code() + " " + ec.text() : "?";
		};
	};
}

it causes errors when eg. I select the Test word with F3. If I put the static declaration of LABEL_PROVIDER in Comment
there is no error anymore.
See the error log in Eclipse

ava.lang.reflect.InvocationTargetException
	at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:395)
	at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:470)
	at org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog.run(ProgressMonitorJobsDialog.java:230)
	at org.eclipse.ui.internal.progress.ProgressManager.lambda$26(ProgressManager.java:821)
	at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:74)
	at org.eclipse.ui.internal.progress.ProgressManager.busyCursorWhile(ProgressManager.java:854)
	at org.eclipse.ui.internal.progress.ProgressManager.busyCursorWhile(ProgressManager.java:830)
	at org.eclipse.jdt.internal.ui.actions.SelectionConverter.performForkedCodeResolve(SelectionConverter.java:261)
	at org.eclipse.jdt.internal.ui.actions.SelectionConverter.codeResolveForked(SelectionConverter.java:173)
	at org.eclipse.jdt.ui.actions.OpenAction.run(OpenAction.java:164)
	at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:278)
	at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:252)
	at org.eclipse.jface.action.Action.runWithEvent(Action.java:474)
	at org.eclipse.jface.commands.ActionHandler.execute(ActionHandler.java:121)
	at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:97)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
	at java.base/java.lang.reflect.Method.invoke(Method.java:577)
	at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:58)
	at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:317)
	at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:251)
	at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:173)
	at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:156)
	at org.eclipse.core.commands.Command.executeWithChecks(Command.java:488)
	at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:487)
	at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
	at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.executeCommand(KeyBindingDispatcher.java:308)
	at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.press(KeyBindingDispatcher.java:580)
	at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.processKeyEvent(KeyBindingDispatcher.java:647)
	at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher.filterKeySequenceBindings(KeyBindingDispatcher.java:439)
	at org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher$KeyDownFilter.handleEvent(KeyBindingDispatcher.java:96)
	at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
	at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1937)
	at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1519)
	at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1546)
	at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1529)
	at org.eclipse.swt.widgets.Widget.sendKeyEvent(Widget.java:1568)
	at org.eclipse.swt.widgets.Widget.gtk_key_press_event(Widget.java:928)
	at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:3993)
	at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java:921)
	at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:2414)
	at org.eclipse.swt.widgets.Control.windowProc(Control.java:6834)
	at org.eclipse.swt.widgets.Display.windowProc(Display.java:6210)
	at org.eclipse.swt.internal.gtk3.GTK3.gtk_main_do_event(Native Method)
	at org.eclipse.swt.widgets.Display.eventProc(Display.java:1565)
	at org.eclipse.swt.internal.gtk3.GTK3.gtk_main_iteration_do(Native Method)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4578)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1155)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
	at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
	at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:644)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
	at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:551)
	at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:156)
	at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
	at java.base/java.lang.reflect.Method.invoke(Method.java:577)
	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
	at org.eclipse.equinox.launcher.Main.run(Main.java:1467)
	at org.eclipse.equinox.launcher.Main.main(Main.java:1440)
Caused by: java.lang.ClassCastException
Root exception:
java.lang.ClassCastException

Thanks for supporting
Best Regards,
Alexandre Didiot

[19] Grammar and compiler AST changes for record patterns

Subtask of issue #85

The goals are:

  • update the grammar file so that the compiler accepts valid simple and nested record patterns.
  • record patterns should be allowed both inside instanceof expressions and switch-case
  • outermost record patterns should be allowed both with and without pattern variable
  • All existing instanceof and switch-case pattern tests should pass
  • Update the compiler AST model accordingly

ASTStructuralPropertyTest needs an update after bug 578608

AST node types introduced via https://bugs.eclipse.org/578608 are outside the range that is tested in org.eclipse.jdt.core.tests.dom.ASTStructuralPropertyTest.testNodeClassForType().

I suggest to simply increase the loop limit (now nodeType < 110) by a larger step, say 10 or even more. Then you will see that the assert also needs adjusting - to correspond to the last constant in ASTNode.

[18] ECJ rejects valid code with switch pattern and conditional expression

Migrating from Bug 578856 - [18] ECJ rejects valid code with switch pattern and conditional expression

The compiler reports a syntax error with the following code:

public void bar(Object o) {
	int i = switch(o) {
    	case String a && o != null ? true : false -> {
    		yield 0;
    	}
    	default -> 1;
	};
}

// Syntax error on token "a", delete this token

If I wrap the guard in (), like below, then the code compiles:

case String a && (o != null ? true : false) ->

Discussion Details:

@mpalat says:

@jarthana : I believe that the ecj behaviour is correct. Here’s the reasoning..

From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html we see that Conditional-And Operator “&&” has higher operator precedence than the Conditional Operator “?:” . From https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.23, we see that “The conditional-and operator is syntactically left-associative (it groups left-to-right).”
Applying the above to the case statement,
int i = switch(o) {
case String a && o != null ? true : false -> {
yield 0;
}
I would NOT expect the result to be:
case ((String a) && ((o != null) ? true : false))

rather I would expect the result to be:
case ((String a) && (o != null)) ? true : false

which is indeed a syntactical error as flagged by ecj.

By the same argument, since the Conditional-or has a lower precedence than conditional-And, the following code
case String a && b || c ->

would translate to case ((String a) && b) || c ->

and would give error.

However, in case of !=, there is no issue, since != has a higher precedence than &&

case String a && o != null

and hence this would translate to (o!= null)

Also, I don't see any mention of the precedence changes in spec 420 [latest at https://cr.openjdk.java.net/~gbierman/jep420/latest]
By the above, I believe the flagging of syntax error is the right thing to do for code in comment 0

@stephan-herrmann : Can you also please have a look and let know of comments, if any? thanks!

@stephan-herrmann replied:

I was going back and forth here:

In this example the '&&' token does not indicate a ConditionalAndExpression (since the lhs is not an expression), so the above reasoning about precedence '&&' vs. '||' falls short.

Secondly, reporting syntax error does not follow from the grammar, but it is caused by the VanguardParser failing to detect goal.hasBeenReached() during disambiguateCasePattern.

This happens, because after "case String a" the follow set doesn't include the observed token '&&'. I guess this should just be added to PatternCaseLabelFollow.

When doing so, we are able to parse more but now GuardedPattern is prematurely reduced with only "String a && o != null" leaving everything from '?' unrecognized.

This syntax error, however, seems justified, because ConditionalExpression is NOT in ConditionalAndExpression as required for GuardedPattern:

GuardedPattern:
PrimaryPattern && ConditionalAndExpression

If this reasoning is correct, then ecj should indeed report syntax error, just a little later than where it does today.

See that also this is illegal:
case String a && (o != null) || false -> {
whereas this is legal:
case String a && (o != null) | false -> {

Reason: also ConditionalOrExpression is not in ConditionalAndExpression, but InclusiveOrExpression is.

(In reply to Jay Arthanareeswaran from comment #0)

If I wrap the guard in (), like below, then the code compiles:

case String a && (o != null ? true : false) ->

Also this is correct, since PrimaryNoNewArray (which can produce 'PushLPAREN Expression_NotName PushRPAREN') is in ConditionalAndExpression (via many indirections :) ).
[tag] [reply] [−]Comment 4

@mpalat says

(In reply to Stephan Herrmann from comment #2)

Thanks Stephan for taking a look. Meanwhile there is a reponse from Gavin that has come in a few hours back in the thread - https://mail.openjdk.java.net/pipermail/amber-spec-experts/2022-March/003307.html
Looks like a conflict in the first glance - need to look into this further as well - am yet to go through your comments also

@stephan-herrmann questions:

(In reply to Manoj Palat from comment #4)

Looks like a conflict in the first glance [...]

Conflict between what?

@mpalat answers:

(In reply to Stephan Herrmann from comment #2)

I was going back and forth here:

Thanks Stephan for pitching in. Went through the comments, did another round of analysis and debugging of ecj to see where we are and here are my thoughts

In this example the '&&' token does not indicate a ConditionalAndExpression
(since the lhs is not an expression), so the above reasoning about
precedence '&&' vs. '||' falls short.

Agree - I went down through an erroneous path here - precedence doesn't have any relevance here.

Secondly, reporting syntax error does not follow from the grammar, but it is
caused by the VanguardParser failing to detect goal.hasBeenReached() during
disambiguateCasePattern.

+1

This happens, because after "case String a" the follow set doesn't include
the observed token '&&'. I guess this should just be added to
PatternCaseLabelFollow.

I had some comments about this earlier - in bug 578241 comment 4 to be precise - ie "PatternCaseLabelFollow represents the FollowSet of a CaseLabelElement for a pattern - sorry for the bad naming - So, TokenNameAND_AND is a misfit here since it cannot come in a follow set of a pattern case label. "
Can rethink about this but as mentioned did not put && since its not a FOLLOW of the case label, strictly speaking, that is.

When doing so, we are able to parse more but now GuardedPattern is
prematurely reduced with only "String a && o != null" leaving everything
from '?' unrecognized.

This syntax error, however, seems justified, because ConditionalExpression
is NOT in ConditionalAndExpression as required for GuardedPattern:

As an answer to comment 5, the conflict mentioned in comment 4 is between the response from EG group[mail thread from comment 4] where it is mentioned that javac is right in accepting for ecj this is a syntax error. I went down the path given by you in the comment and see that it should be a syntax error indeed

GuardedPattern:
PrimaryPattern && ConditionalAndExpression

.

Reason: also ConditionalOrExpression is not in ConditionalAndExpression, but
InclusiveOrExpression is.

So without parenthesis, ie the code in description :
case String a && o != null ? true : false ->

follows the path of:

666 AssignmentExpression -> ConditionalExpression
683 Expression ::= AssignmentExpression
688 ConstantExpression -> Expression

And as you mentioned this cannot be reduced to a ConditionalAndExpression and hence agree that the error is justified

Now moving to with parenthesis,
case String a && (o != null ? true : false) ->
I agree, as usual :) with your conclusion again in comment 3

Looked through the grammar in https://docs.oracle.com/javase/specs/jls/se17/html/jls-19.html and additionally the preview part (for GuardedPattern), I see that this indeed should be accepted. The ecj version given below for reference
875 ConditionalExpression_NotName ::= ConditionalOrExpression_NotName
QUESTION Expression COLON
ConditionalExpression
877 AssignmentExpression_NotName -> ConditionalExpression_NotName
879 Expression_NotName -> AssignmentExpression_NotName

This is in fact equivalent to the rules
666 AssignmentExpression -> ConditionalExpression
683 Expression ::= AssignmentExpression

And then on consumption of RParen
510 PushRPAREN ::= RPAREN

Gets to the next rule:
516 PrimaryNoNewArray ::= ‘(‘ Expression_NotName ‘)’
ie and so on..

516 PrimaryNoNewArray ::= PushLPAREN Expression_NotName PushRPAREN
511 Primary -> PrimaryNoNewArray
602 PostfixExpression -> Primary
616 UnaryExpressionNotPlusMinus -> PostfixExpression
613 UnaryExpression -> UnaryExpressionNotPlusMinus
635 MultiplicativeExpression -> UnaryExpression
639 AdditiveExpression -> MultiplicativeExpression
642 ShiftExpression -> AdditiveExpression
646 RelationalExpression -> ShiftExpression
352 InstanceofExpression -> RelationalExpression
*651 EqualityExpression -> InstanceofExpression
654 AndExpression -> EqualityExpression
656 ExclusiveOrExpression -> AndExpression
658 InclusiveOrExpression -> ExclusiveOrExpression
660 ConditionalAndExpression -> InclusiveOrExpression
366 GuardedPattern ::= PrimaryPattern AND_AND ConditionalAndExpression

[Dev Note - the numeric represents the internal state - act in Parser.consumeRule() - of ecj for the given java.g at this point in time - They may not have a direct control flow while debugging - to mandatorily (for debugging) have this flow through the states, change -> to ::= with a consume**() method - else many of these states may get optimized away]

So in conclusion, agree with your analysis:
case String a && o != null ? true : false -> // Reject
case String a && (o != null ? true : false) -> // Accept
[tag] [reply] [−]Comment 7Stephan Herrmann CLA Friend 2022-03-18 12:28:50 EDT
(In reply to Manoj Palat from comment #6)

(In reply to Stephan Herrmann from comment #2)

This happens, because after "case String a" the follow set doesn't include
the observed token '&&'. I guess this should just be added to
PatternCaseLabelFollow.

I had some comments about this earlier - in bug 578241 comment 4 to be
precise - ie "PatternCaseLabelFollow represents the FollowSet of a
CaseLabelElement for a pattern - sorry for the bad naming - So,
TokenNameAND_AND is a misfit here since it cannot come in a follow set of a
pattern case label. "
Can rethink about this but as mentioned did not put && since its not a
FOLLOW of the case label, strictly speaking, that is.

I think the confusion here stems from the fact that the grammar is not left-factored (i.e., two grammar rules PrimaryPattern and GuardedPattern have the same prefix).

The vanguard parser tries to match this goal:

BeginCaseElement Pattern

Once it has seen "case String a" it assumes matching is done and proceeds to checking the next token against the follow set.

Perhaps the following equivalent rule would produce a different result (just guessing):

Pattern:
PrimaryPattern GuardOpt

But since all the vanguard parsing is outside spec-land, I would be comfortable with opportunistically adding '&&' to the follow set, saying: when you recognized a (minimal) Pattern, the text can legally continue with '&&'. If that would lead to prematurely accepting smth that is not a GuardedPattern after all, I would be hard pressed to imagine that a different disambiguation would have produced a legal interpretation of the input. Can you think of an input that would cause this kind of trouble?
[tag] [reply] [−]Comment 8

(In reply to Stephan Herrmann from comment #7)

But since all the vanguard parsing is outside spec-land, I would be
comfortable with opportunistically adding '&&' to the follow set, saying:
when you recognized a (minimal) Pattern, the text can legally continue with
'&&'.

Yes, since vanguard is outside spec-land, we can implement this change - moving this to the 4.24 time-frame

Eclipse compiles code that shouldn't compile, when resolving overloads from inferred type

Take this file:

package p;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test {

    void m() {
        set(x(() -> map()));
        set(y(y -> map()));
    }

    Map<List<?>, Object> map() {
        return null;
    }

    <T> T x(Supplier<? extends T> f) {
        return f.get();
    }

    <T> T y(Function<?, ? extends T> f) {
        return f.apply(null);
    }

    void set(List<?> a) {
    }

    void set(Map<?, ?> map) {
    }
}

Eclipse compiles it just fine with language level 17, when javac produces this output:

$ javac p/Test.java
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
p\Test.java:12: error: reference to set is ambiguous
        set(y(y -> map()));
        ^
  both method set(List<?>) in Test and method set(Map<?,?>) in Test match
p\Test.java:12: error: incompatible types: inference variable T has incompatible bounds
        set(y(y -> map()));
             ^
    lower bounds: List<?>,Object
    lower bounds: Map<List<?>,Object>
  where T is a type-variable:
    T extends Object declared in method <T>y(Function<?,? extends T>)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors

I'm personally not convinced that this is how the language should work, but I guess the JLS specifies things this way? Note that if set(List<?>) tries to capture the wildcard in a type variable, then Eclipse also complains about the same error. With this code:

package p;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test {

    void m() {
        set(x(() -> map()));
        set(y(y -> map()));
    }

    Map<List<?>, Object> map() {
        return null;
    }

    <T> T x(Supplier<? extends T> f) {
        return f.get();
    }

    <T> T y(Function<?, ? extends T> f) {
        return f.apply(null);
    }

    <T> void set(List<T> a) {
    }

    void set(Map<?, ?> map) {
    }
}

Eclipse now produces these two errors:

The method set(List<Object>) is ambiguous for the type Test

And

Type mismatch: cannot convert from Map<List<?>,Object> to List<Object>

[Reconciler][Sealed types] Inconsistent type hierarchy with sealed classes

I recently changed a lot of interfaces in a rather large project of mine to be sealed and I think I found an ECJ bug in the process. I have 3 interfaces and 3 classes with the following hierarchy:

public sealed interface Interface1 permits Class1, Interface2
public sealed interface Interface2 extends Interface1 permits Class2, Interface3
public sealed interface Interface3 extends Interface2 permits Class3

public non-sealed class Class1 implements Interface1
public non-sealed class Class2 extends Class1 implements Interface2
public final class Class3 extends Class2 implements Interface3

In this setup Class2 will have an error which says

The hierarchy of the type Class2 is inconsistent

The thing is Class2 still successfully compiles and runs with no problem. It also shows no error in the eclipse package explorer tree, it's not until you open the class in the code viewer that this error is shown. It also builds fine with javac which is why I'm not sure if it's an ECJ bug or something else. This bug seems to be triggered by having multiple permits on Interface2. That is if I remove Interface3 from the permits list on Interface2 then the error on Class2 goes away, of course Interface3 no longer compiles but that's to be expected. Any number of permits on Interface2 will cause this with the exception of a single permit. This issue also only seems to show itself on a class which extends another class and not on Class1 for example. The eclipse version is 2022-03 with JDK 17

ExternalAnnotations18Test.testBug482242 failure in I20220427-0410

We see this in Linux/11 build:
https://download.eclipse.org/eclipse/downloads/drops4/I20220427-0410/testresults/html/org.eclipse.jdt.core.tests.model_ep424I-unit-cen64-gtk3-java11_linux.gtk.x86_64_11.html

Unexpected problem Pb(983) Unsafe null type conversion (type annotations): The value of type 'Collector<@NonNull String,capture#of ?,Set<@NonNull String>>' is made accessible using the less-annotated type 'Collector<? super String,Object,Set<@NonNull String>>' at 11

junit.framework.AssertionFailedError: Unexpected problem Pb(983) Unsafe null type conversion (type annotations): The value of type 'Collector<@NonNull String,capture#of ?,Set<@NonNull String>>' is made accessible using the less-annotated type 'Collector<? super String,Object,Set<@NonNull String>>' at 11
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.TestCase.fail(TestCase.java:223)
at org.eclipse.jdt.core.tests.model.ExternalAnnotations18Test.assertProblems(ExternalAnnotations18Test.java:483)
at org.eclipse.jdt.core.tests.model.ExternalAnnotations18Test.testBug482242(ExternalAnnotations18Test.java:2726)

@stephan-herrmann : related to #48 ?

how to get ITypeRoot

when i use ASTParser#createAST method to create a org.eclipse.jdt.core.dom.CompilationUnit with a single java file,i found that it's typeRoot field is null, but i want to use this field to call codeSelect method. What should i do to get it?

ClassCastException importing breakpoints

eclipse.buildId=4.23.0.I20220308-0310
java.version=17.0.1
java.vendor=Eclipse Adoptium
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments: -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.modeling.product
Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product -product org.eclipse.epp.package.modeling.product

org.eclipse.debug.core
Error
Mon May 09 13:29:41 EDT 2022
Error logged from Debug Core:

java.lang.reflect.InvocationTargetException
at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:443)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:352)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1033)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpointsPage.finish(WizardImportBreakpointsPage.java:210)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpoints.performFinish(WizardImportBreakpoints.java:97)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:832)
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:472)
at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619)
at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:84)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:252)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4243)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1063)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4060)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3632)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:823)
at org.eclipse.jface.window.Window.open(Window.java:799)
at org.eclipse.ui.internal.handlers.WizardHandler$Import.executeHandler(WizardHandler.java:153)
at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:283)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:283)
at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:97)
at jdk.internal.reflect.GeneratedMethodAccessor91.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:58)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:317)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:251)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:173)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:156)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:488)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:487)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:389)
at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:142)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:580)
at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:414)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4243)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1063)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4060)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3632)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1155)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:644)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:551)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:156)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
at org.eclipse.equinox.launcher.Main.run(Main.java:1467)
Caused by: java.lang.ClassCastException: class org.eclipse.jdt.internal.core.JarPackageFragmentRoot cannot be cast to class org.eclipse.jdt.core.IPackageFragment (org.eclipse.jdt.internal.core.JarPackageFragmentRoot and org.eclipse.jdt.core.IPackageFragment are in unnamed module of loader org.eclipse.osgi.internal.loader.EquinoxClassLoader @c1765ad)
at org.eclipse.jdt.internal.core.JavaModelManager.createCompilationUnitFrom(JavaModelManager.java:1094)
at org.eclipse.jdt.core.JavaCore.createCompilationUnitFrom(JavaCore.java:3730)
at org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpointImportParticipant.verify(JavaBreakpointImportParticipant.java:554)
at org.eclipse.debug.ui.actions.ImportBreakpointsOperation.restoreBreakpoint(ImportBreakpointsOperation.java:350)
at org.eclipse.debug.ui.actions.ImportBreakpointsOperation.run(ImportBreakpointsOperation.java:217)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpointsPage$1.run(WizardImportBreakpointsPage.java:218)
at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:434)
... 61 more
Root exception:
java.lang.ClassCastException: class org.eclipse.jdt.internal.core.JarPackageFragmentRoot cannot be cast to class org.eclipse.jdt.core.IPackageFragment (org.eclipse.jdt.internal.core.JarPackageFragmentRoot and org.eclipse.jdt.core.IPackageFragment are in unnamed module of loader org.eclipse.osgi.internal.loader.EquinoxClassLoader @c1765ad)
at org.eclipse.jdt.internal.core.JavaModelManager.createCompilationUnitFrom(JavaModelManager.java:1094)
at org.eclipse.jdt.core.JavaCore.createCompilationUnitFrom(JavaCore.java:3730)
at org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpointImportParticipant.verify(JavaBreakpointImportParticipant.java:554)
at org.eclipse.debug.ui.actions.ImportBreakpointsOperation.restoreBreakpoint(ImportBreakpointsOperation.java:350)
at org.eclipse.debug.ui.actions.ImportBreakpointsOperation.run(ImportBreakpointsOperation.java:217)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpointsPage$1.run(WizardImportBreakpointsPage.java:218)
at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:434)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:352)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1033)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpointsPage.finish(WizardImportBreakpointsPage.java:210)
at org.eclipse.debug.internal.ui.importexport.breakpoints.WizardImportBreakpoints.performFinish(WizardImportBreakpoints.java:97)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:832)
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:472)
at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619)
at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:84)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:252)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4243)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1063)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4060)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3632)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:823)
at org.eclipse.jface.window.Window.open(Window.java:799)
at org.eclipse.ui.internal.handlers.WizardHandler$Import.executeHandler(WizardHandler.java:153)
at org.eclipse.ui.internal.handlers.WizardHandler.execute(WizardHandler.java:283)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:283)
at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:97)
at jdk.internal.reflect.GeneratedMethodAccessor91.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:58)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:317)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:251)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:173)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:156)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:488)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:487)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.ui.internal.handlers.LegacyHandlerService.executeCommand(LegacyHandlerService.java:389)
at org.eclipse.ui.internal.actions.CommandAction.runWithEvent(CommandAction.java:142)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:580)
at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:414)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4243)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1063)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4060)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3632)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1155)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:644)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:551)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:156)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
at org.eclipse.equinox.launcher.Main.run(Main.java:1467)

`continue` without label is incorrectly handled in a switch expression

Tested on Eclipse 2022-03; jdt.core version 3.29.0.v20220214-1307.

The JDT compiler allows a continue statement inside a (case of a) switch expression to continue to a loop declared outside of the switch expression, iff that continue doesn't target an explicit label.
The JLS clearly forbids this: "It is a compile-time error if the continue target contains any [...] switch expression that encloses the continue statement. That is, there are no non-local jumps." in https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.16 / https://docs.oracle.com/javase/specs/jls/se18/html/jls-14.html#jls-14.16

MWE:

public class ContinueFromSwitchExpression
{
    public static String string = "a";

    public static void main(String[] args)
    {
        loop: for(;;)
        {
            System.out.println("In loop before switch");
            int result = 123 + switch(string)
            {
                case "a" ->
                {
                    continue; // incorrectly compiles in JDT
                    //continue loop; // correctly flagged as error ("Continue out of switch expressions not permitted")
                    // javac (correctly) outputs "error: attempt to continue out of a switch expression" for both continue statements
                }
                default -> 456;
            };
            System.out.println("After switch. result: " + result);
        }
    }
}

Resulting classfile:

public class ContinueFromSwitchExpression {
  public static java.lang.String string;

[... default constructor and <clinit> ...]

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #23                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #29                 // String In loop before switch
       5: invokevirtual #31                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: bipush        123
      10: getstatic     #12                 // Field string:Ljava/lang/String;
      13: dup
      14: astore_2
      15: invokevirtual #37                 // Method java/lang/String.hashCode:()I
      18: lookupswitch  { // 1
                    97: 36
               default: 45
          }
      36: aload_2
      37: ldc           #10                 // String a
      39: invokevirtual #43                 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
      42: ifne          0
      45: sipush        456
      48: iadd
      49: istore_1
      50: getstatic     #23                 // Field java/lang/System.out:Ljava/io/PrintStream;
      53: new           #47                 // class java/lang/StringBuilder
      56: dup
      57: ldc           #49                 // String After switch. result:
      59: invokespecial #51                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
      62: iload_1
      63: invokevirtual #53                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      66: invokevirtual #57                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      69: invokevirtual #31                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      72: goto          0
}

Trying to run the resulting classfile throws a verification error because of the value 123 remaining on the stack when the continue jumps to the loop beginning. Removing 123 + causes the JVM to not throw any errors; it then prints "In loop before switch" repeatedly and indefinitely as expected (but still incorrectly).

Revisit formatter changes with introduction of 'when' clause in switch pattern expressions

During the PR #74 , I left a failing test untouched since it may need some bigger formatter changes (not entirely sure). At the moment, it's only one test in FormatterRegressionTests._testBug573949(), but there could be others too. This needs investigation. Although I updated SpacePreparator.visit(GuardedPattern) to replace with the new token, this might more attention.

@mateusz-matela Please take a look.

AttachedJavadocTests spawn a thread that never ends

But AttachedJavadocTests code is still running too ???

15:27:28  "Thread-4": TIMED_WAITING
15:27:28      [email protected]/java.lang.Thread.sleep(Native Method)
15:27:28      org.eclipse.jdt.core.tests.model.AttachedJavadocTests$1.run(AttachedJavadocTests.java:770)
15:27:28  

That's a very interesting observation! Here's what AttachedJavadocTests$1 is doing (in a thread of its own):

				public void run() {
					Object javadocContent = projectInfo.javadocCache.get(type);
					while(javadocContent == null || javadocContent == BinaryType.EMPTY_JAVADOC) {
						try {
							Thread.sleep(50);
							javadocContent = projectInfo.javadocCache.get(type);
						} catch (InterruptedException e) {
						}
						synchronized (varThis) {
							varThis.notify();
						}
					}
				}

Interestingly, the enclosing test testBug329671() succeeded even though it's temp thread never got the expected result. OTOH, my stacktrace in #38 (comment) does not show this test, so it can't be the root cause here.

Originally posted by @stephan-herrmann in #38 (comment)

Organize imports doesn't honor setting for .*

I noticed that since 2022.3 our automatic clean up procedures mess up the imports and with some experimentation that the setting for "Number of imports needed for .* (e.g. 'org.eclipse.*'):" is no longer honored. The example screen shot shows that the number of imports needed is set to 2, but the organizer (either manually triggered, or using auto clean up actions) keeps expanding the imports, nor collapsing them.

image

This is quite annoying as this will trigger many an update war in the git history.

I've also checked my general settings, which stated '99' imports required for .* but changing that to 2 also didn't work. It appears that the organize imports completely ignores these settings.

APIDocumentationTests#testTestDefaultCompliance() fails with tycho 3.0.0

See eclipse-tycho/tycho#879 (comment)

Additionally to OOM errors (they disappear after bumping max heap to 2 GB), there is one test that is now always failing with tycho 3.0.0: org.eclipse.jdt.core.tests.dom.APIDocumentationTests#testTestDefaultCompliance()

junit.framework.ComparisonFailure: 
Tests should run at default compliance 1.8.
----------- Expected ------------
1.8
------------ but was ------------
1.4
--------- Difference is ----------
 expected:<1.[8]> but was:<1.[4]>

I haven't had time to analyze this failure yet.

[Patterns] Suggest identifier completion for `obj instanceof Dog`

Similarly to how identifier completion (usually derived from type) is available when declaring a variable, it would be nice to get similar completion after the obj instanceof Dog to completion (when using recent enough Java), would suggest if (obj isntanceof Dog dog).

[19] JEP 405: Record Patterns (First Preview)

JEP 405: Record Patterns has been targeted for Java 19 as a preview feature. This will require considerable changes from grammar all the way up to the code generation and DOM model. The specification is here

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.