Skip to content

Commit

Permalink
add a regression test for type names and reflect
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mvdan committed Jun 25, 2023
1 parent 8f72489 commit d89a556
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions testdata/script/reflect.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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

0 comments on commit d89a556

Please sign in to comment.