如何比较两个源代码文件/ast 树?

How can I compare two source code files/ ast trees?

我正在使用 templates 包生成一些源代码(有更好的方法吗?)和部分测试我需要检查输出是否与预期的源代码匹配。

Playground

好吧,一个简单的实现方法是使用 go/printer 库,它可以让您更好地控制输出格式,并且基本上类似于源代码中的 运行 gofmt ,标准化两棵树:

package main
import (
    "fmt"
    "go/parser"
    "go/token"
    "go/printer"
    //"reflect"
    "bytes"
)

func main() {
    stub1 := `package main
     func myfunc(s string) error {
        return nil  
    }`
    stub2 := `package main

     func myfunc(s string) error {

        return nil

    }`

    fset1 := token.NewFileSet()
    r1, err := parser.ParseFile(fset1, "", stub1, parser.AllErrors)
    if err != nil {
        panic(err)
    }
    fset2 := token.NewFileSet()
    r2, err := parser.ParseFile(fset1, "", stub2, parser.AllErrors)
    if err != nil {
        panic(err)
    }

    // we create two output buffers for each source tree
    out1 := bytes.NewBuffer(nil)
    out2 := bytes.NewBuffer(nil)

    // we use the same printer config for both
    conf := &printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}

    // print to both outputs
    if err := conf.Fprint(out1, fset1, r1); err != nil {
        panic(err)
    }
    if err := conf.Fprint(out2, fset2, r2); err != nil {
        panic(err)
    }


    // they should be identical!
    if string(out1.Bytes()) != string(out2.Bytes()) {
        panic(string(out1.Bytes()) +"\n" + string(out2.Bytes()))
    } else {
        fmt.Println("A-OKAY!")
    }
}

当然,这段代码需要重构才能看起来不那么愚蠢。另一种方法是不使用 DeepEqual,而是自己创建一个树比较函数,它会跳过不相关的节点。

这比我想象的要容易。我所要做的就是删除空的新行(格式化后)。下面是代码。

    package main

    import (
        "fmt"
        "go/format"
        "strings"
    )

    func main() {
        a, err := fmtSource(stub1)
        if err != nil {
            panic(err)
        }
        b, err := fmtSource(stub2)
        if err != nil {
            panic(err)
        }
        if a != b {
            fmt.Printf("a %v, \n b %v", a, b)
        }
    }

func fmtSource(source string) (string, error) {
    if !strings.Contains(source, "package") {
        source = "package main\n" + source
    }
    b, err := format.Source([]byte(source))
    if err != nil {
        return "", err
    }
    // cleanLine replaces double space with one space
    cleanLine := func(s string)string{
        sa := strings.Fields(s)
        return strings.Join(sa, " ")
    }
    lines := strings.Split(string(b), "\n")
    n := 0
    var startLn *int
    for _, line := range lines {
        if line != "" {
            line = cleanLine(line)
            lines[n] = line
            if startLn == nil {
                x := n
                startLn = &x
            }
            n++
        }
    }
    lines = lines[*startLn:n]
    // Add final "" entry to get trailing newline from Join.
    if n > 0 && lines[n-1] != "" {
        lines = append(lines, "")
    }


    // Make it pretty 
    b, err = format.Source([]byte(strings.Join(lines, "\n")))
    if err != nil {
        return "", err
    }
    return string(b), nil
}