awalterschulze / goderive

Derives and generates mundane golang functions that you do not want to maintain yourself
Apache License 2.0
1.24k stars 43 forks source link

deriveSorted does not handle type aliases for elements #60

Closed deosjr closed 3 years ago

deosjr commented 4 years ago

Consider the following program

package main

import (
    "fmt"
)

type X struct {}

type Y int

type Z map[Y]*X

func test(z Z) {
    for _, k := range deriveSorted(deriveKeys(z)) {
        fmt.Println(z[k])
    }
}

func main() {
    z := map[Y]*X{}
    test(z)
    fmt.Println("Succes")
}

Running goderive runs fine, but subsequently the program fails to compile, with the following error:

./derived.gen.go:11:11: cannot use list (type []Y) as type []int in argument to sort.Ints

deriveSorted has been generated as:

func deriveSorted(list []Y) []Y {
    sort.Ints(list)
    return list
}

and it is sort.Ints that is throwing the error

awalterschulze commented 4 years ago

Good catch. Yes deriveSort should be made to be able to generate this without an error. Thank you for reporting. I clearly didn't test type aliases enough :)

deosjr commented 4 years ago

I don't think I'll be diving into this deep enough to fix it. Did create a few test cases to illustrate, which I include here

type stringalias string

func TestSortedMapKeysTypeAliasKey(t *testing.T) {
    var m map[stringalias]string
    m = random(m).(map[stringalias]string)
    keys := deriveSortedAlias(deriveKeysForMapAliasToString(m))

This test case will fail because of the stated issue: deriveSortedAlias is never generated. The analogous TestSortedMapKeysTypeAliasValue does succeed but is currently missing from the test suite.

func TestSortedMapKeysTypeAliasInScope(t *testing.T) {
    type stringalias string
    var m map[string]stringalias
    m = random(m).(map[string]stringalias)
    keys := deriveSorted(deriveKeysForMapStringToAlias(m))

This test I made by mistake, and fails for a different reason. deriveSorted is generated, but the alias is only defined in scope of the test. Running goderive therefore succeeds but the program won't compile.

awalterschulze commented 4 years ago

No problem. The report is already very helpful, thank you :) Especially providing test cases, is even more useful. Thanks for all your help here.