From d89a55687c0e57dcadb3f064a680e32cd90699d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Mart=C3=AD?= <mvdan@mvdan.cc>
Date: Sun, 25 Jun 2023 14:24:38 +0100
Subject: [PATCH] add a regression test for type names and reflect

We were recently altering the logic in reflect.go for type names,
which could have broken this kind of valid use of reflection.

Add a regression test, which I verified would break before my last
change to "simplify" the logic, which actually changed the logic,
as xuannv112 correctly pointed out.

After thinking about the change in behavior for a little while,
I realised that the new behavior is more correct, hence the test.
---
 testdata/script/reflect.txtar | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/testdata/script/reflect.txtar b/testdata/script/reflect.txtar
index 094e642d..f9119ef4 100644
--- a/testdata/script/reflect.txtar
+++ b/testdata/script/reflect.txtar
@@ -140,6 +140,30 @@ func main() {
 	// Ensure the types are kept in the binary. Use an anonymous type too.
 	_ = fmt.Sprintf("%#v", EmbeddingObfuscated{})
 	_ = fmt.Sprintf("%#v", struct{ExportedLocalObfuscated}{})
+
+	// reflection can see all type names, even local ones, so they cannot be obfuscated.
+	{
+		type TypeOfNamedField struct    { NamedReflectionField int }
+		type TypeOfEmbeddedField struct { EmbeddedReflectionField int }
+		type TypeOfParent struct {
+			ReflectionField TypeOfNamedField
+			TypeOfEmbeddedField
+		}
+		t := reflect.TypeOf(TypeOfParent{})
+		fmt.Println("TypeOfParent's own name:", t.Name())
+		namedField, _ := t.FieldByName("ReflectionField")
+		namedFieldField, _ := namedField.Type.FieldByName("NamedReflectionField")
+		fmt.Println("TypeOfParent named:",
+			namedField.Type.Name(),
+			namedFieldField.Name,
+		)
+		embedField, _ := t.FieldByName("TypeOfEmbeddedField")
+		embedFieldField, _ := embedField.Type.FieldByName("EmbeddedReflectionField")
+		fmt.Println("TypeOfParent embedded:",
+			embedField.Type.Name(),
+			embedFieldField.Name,
+		)
+	}
 }
 
 type EmbeddingIndirect struct {
@@ -448,3 +472,6 @@ VariadicReflection{ReflectionField:"variadic"}
 *main.StatUser
 *main.StatCompUser
 struct { UnnamedStructField string }
+TypeOfParent's own name: TypeOfParent
+TypeOfParent named: TypeOfNamedField NamedReflectionField
+TypeOfParent embedded: TypeOfEmbeddedField EmbeddedReflectionField