Give a more clear error message when Java gencode will break due to an enum being nested inside a message of the same name.

This shape of .proto file does not and has never worked in JavaProto, but the error will occur when javac attempts to compile the gencode and may be a bit obtuse to users.

PiperOrigin-RevId: 855349686
diff --git a/src/google/protobuf/compiler/java/file.cc b/src/google/protobuf/compiler/java/file.cc
index a4880e3..a660489 100644
--- a/src/google/protobuf/compiler/java/file.cc
+++ b/src/google/protobuf/compiler/java/file.cc
@@ -266,6 +266,18 @@
         << "name for the .proto file to be safe.";
   }
 
+  google::protobuf::internal::VisitDescriptors(*file_, [&](const EnumDescriptor& enm) {
+    if (enm.containing_type() != nullptr &&
+        enm.containing_type()->name() == enm.name()) {
+      absl::StrAppend(
+          error, file_->name(),
+          ": Cannot generate Java output because the enum \"", enm.full_name(),
+          "\" would be an enum nested inside a class with the same name, "
+          "which is not allowed in the Java language. "
+          "Please rename either the enum or containing message name.\n");
+    }
+  });
+
   // Check that no field is a closed enum with implicit presence. For normal
   // cases this will be rejected by protoc before the generator is invoked, but
   // for cases like legacy_closed_enum it may reach the generator.
diff --git a/src/google/protobuf/compiler/java/generator_unittest.cc b/src/google/protobuf/compiler/java/generator_unittest.cc
index 13781c0..ec7c3a8 100644
--- a/src/google/protobuf/compiler/java/generator_unittest.cc
+++ b/src/google/protobuf/compiler/java/generator_unittest.cc
@@ -379,6 +379,26 @@
       "of one of the types declared inside it");
 }
 
+TEST_F(JavaGeneratorTest, InvalidConflictingNestedEnumName) {
+  CreateTempFile("test_file_name.proto",
+                 R"schema(
+      edition = "2024";
+      package foo;
+      message TestNameConflict {
+        enum TestNameConflict {
+          UNSPECIFIED = 0;
+        }
+      }
+      )schema");
+
+  RunProtoc(
+      "protocol_compiler --experimental_editions --java_out=$tmpdir "
+      "-I$tmpdir test_file_name.proto");
+
+  ExpectErrorSubstring(
+      "would be an enum nested inside a class with the same name");
+}
+
 TEST_F(JavaGeneratorTest, ExtensionsOptionImportsAreUnknown) {
   CreateTempFile("custom_option.proto", R"schema(
       edition = "2024";