proto: add Clone function and MergeOptions.Clone method

We resisted adding Clone for a while since:
* It is a function that is perfectly suited for generics.
However, generics probably still won't be available in Go for some time
and it is impractical to block addition of this function when it is very
widely used and will be necessary for the v1 to v2 migration.
* In the past, there was no protoreflect.Message.IsValid, so there was
no proper API to detect invalid top-level messages and return them as such.

Since Clone relies on certain properties about proper round-tripping
of ProtoMessage.ProtoReflect <-> Message.Interface, we add a test
in testing/prototest to check for this.

Change-Id: Ic492b68f27b8b88322a6a3fa3a5e492228db79d9
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/213297
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/proto/merge.go b/proto/merge.go
index fbd9c73..772a8f4 100644
--- a/proto/merge.go
+++ b/proto/merge.go
@@ -34,12 +34,42 @@
 	Shallow bool
 }
 
+// Clone returns a deep copy of m.
+// See MergeOptions.Clone for details.
+func Clone(m Message) Message {
+	return MergeOptions{}.Clone(m)
+}
+
 // Merge merges src into dst, which must be messages with the same descriptor.
 // See MergeOptions.Merge for details.
 func Merge(dst, src Message) {
 	MergeOptions{}.Merge(dst, src)
 }
 
+// Clone returns a copy of m.
+// If Shallow is specified it makes a new message and shallow copies m into it.
+// If the top-level message is invalid, it returns an invalid message as well.
+func (o MergeOptions) Clone(m Message) Message {
+	// NOTE: Most usages of Clone assume the following properties:
+	//	t := reflect.TypeOf(m)
+	//	t == reflect.TypeOf(m.ProtoReflect().New().Interface())
+	//	t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface())
+	//
+	// Embedding protobuf messages breaks this since the parent type will have
+	// a forwarded ProtoReflect method, but the Interface method will return
+	// the underlying embedded message type.
+	return o.cloneMessage(m.ProtoReflect()).Interface()
+}
+
+func (o MergeOptions) cloneMessage(src protoreflect.Message) (dst protoreflect.Message) {
+	if !src.IsValid() {
+		return src.Type().Zero()
+	}
+	dst = src.New()
+	o.mergeMessage(dst, src)
+	return dst
+}
+
 // Merge merges src into dst, which must be messages with the same descriptor.
 //
 // Populated scalar fields in src are copied to dst, while populated