Skip to content

Java classes with annotations fail to parse #20063

Open
@noti0na1

Description

@noti0na1

Compiler version

3.3.1
3.5.0-RC1-bin-SNAPSHOT

Should happen in every version, and in Scala 2 as well

Minimized code

// JFun.java
// Other annotations also fail, for example, @Deprecated
@FunctionalInterface
public interface JFun {
    String f(String s);
}

with an empty scala file in order to trigger the compiling: Stest.scala.

Output

> scala-cli compile JFun.java Stest.scala
Compiling project (Scala 3.3.1, JVM (17))
[error] ./JFun.java:2:1
[error] package expected but public found.
[error] public interface JFun {
[error] ^^^^^^
[error] ./JFun.java:6:1
[error] identifier expected but eof found.
Error compiling project (Scala 3.3.1, JVM (17))
Compilation failed
> scala-cli compile --scala 2 JFun.java Stest.scala
Compiling project (Scala 2.13.13, JVM (17))
[error] ./JFun.java:2:1
[error] `package` expected but `public` found.
[error] public interface JFun {
[error] ^
[error] ./JFun.java:5:1
[error] identifier expected but eof found.
[error] ^
Error compiling project (Scala 2.13.13, JVM (17))
Compilation failed

Expectation

Should compile.

Analyze

In JavaParser, it tries to read annotations with the package.

/** CompilationUnit ::= [package QualId semi] TopStatSeq
  */
def compilationUnit(): Tree = {
  val start = in.offset
  val pkg: RefTree =
    if (in.token == AT || in.token == PACKAGE) {
      annotations()
      accept(PACKAGE)
      val pkg = qualId()
      accept(SEMI)
      pkg
    }
    ...

Scala 2 also has the same issue, since this part is a direct port (and there is a TODO there).

Removing in.token == AT || from the condition and annotations() from the body makes the code compile.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions