cmd/protoc-gen-go: correlate v1 ExtensionDesc with v2 ExtensionType

Unfortunately a good amount of code uses pointer comparisons on the
v1 ExtensionDesc to determine exactly which extension field is set,
rather than checking whether the extension descriptor semantically
describes the field that they are interested in.

To preserve this behavior in v1, we need a 1:1 mapping between
a v2 ExtensionType and a specific v1 ExtensionDesc.

Change-Id: I852b3cefb4585bd656e48e5adad6cc28795d02df
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/167759
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/legacy/extension.go b/internal/legacy/extension.go
index 1626702..839d597 100644
--- a/internal/legacy/extension.go
+++ b/internal/legacy/extension.go
@@ -47,6 +47,13 @@
 // extensionDescFromType converts a v2 protoreflect.ExtensionType to a
 // v1 protoapi.ExtensionDesc. The returned ExtensionDesc must not be mutated.
 func extensionDescFromType(t pref.ExtensionType) *papi.ExtensionDesc {
+	// Fast-path: check whether an extension desc is already nested within.
+	if t, ok := t.(interface{ ProtoLegacyExtensionDesc() *papi.ExtensionDesc }); ok {
+		if d := t.ProtoLegacyExtensionDesc(); d != nil {
+			return d
+		}
+	}
+
 	// Fast-path: check the cache for whether this ExtensionType has already
 	// been converted to a legacy descriptor.
 	if d, ok := extensionDescCache.Load(t); ok {