需求
将 var a,b,c= 3,4,5 改为 a,b,c :=3,4,5
将var m = 99 改为 m := 99
这种结构如果采用普通的正则替换是很难的,但是采用tree-sitter去做确实很容易实现的
请看下面的实例
package main
import (
"fmt"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
tree_sitter_go "github.com/tree-sitter/tree-sitter-go/bindings/go"
)
var (
abc int
)
func main() {
code := []byte(`
package main
import (
"abcd"
"fmt"
)
func main() {
fmt.Println("Hello, world!123")
var a,b,c =3,4,5;var test=88
var kk =9
var mm,ff,ll=88,99,100
}
`)
parser := tree_sitter.NewParser()
defer parser.Close()
parser.SetLanguage(tree_sitter.NewLanguage(tree_sitter_go.Language()))
tree := parser.Parse(code, nil)
defer tree.Close()
var walk func(node *tree_sitter.Node)
walk = func(node *tree_sitter.Node) {
if node.GrammarName() == "var_declaration" {
var oldVarDeclarationRange = node.Range()
varNode := node.Child(0)
varNodeByteStart, varNodeByteEnd := varNode.ByteRange()
for i := varNodeByteStart; i < varNodeByteEnd; i++ {
code[i] = 0
}
childTwo := node.Child(1)
if childTwo.Kind() == "var_spec" {
varSpecNode := childTwo
var i uint
for i = 0; i < varSpecNode.ChildCount(); i++ {
if varSpecNode.Child(i).Kind() == "=" {
equalNode := varSpecNode.Child(i)
equalNodeByteStart, equalNodeByteEnd := equalNode.ByteRange()
code = append(code[:equalNodeByteStart], append([]byte(":="), code[equalNodeByteEnd:]...)...)
break
}
}
tree.Edit(&tree_sitter.InputEdit{
StartByte: oldVarDeclarationRange.StartByte,
OldEndByte: oldVarDeclarationRange.EndByte,
NewEndByte: oldVarDeclarationRange.EndByte + 1,
StartPosition: tree_sitter.Point{
Row: oldVarDeclarationRange.StartPoint.Row,
Column: oldVarDeclarationRange.StartPoint.Column,
},
OldEndPosition: tree_sitter.Point{
Row: oldVarDeclarationRange.EndPoint.Row,
Column: oldVarDeclarationRange.EndPoint.Column,
},
NewEndPosition: tree_sitter.Point{
Row: oldVarDeclarationRange.EndPoint.Row,
Column: oldVarDeclarationRange.EndPoint.Column + 1,
},
})
} else {
}
} else {
childNum := node.ChildCount()
if childNum == 0 {
} else {
var i uint
for i = 0; i < (childNum); i++ {
walk(node.Child(i))
}
}
}
}
walk(tree.RootNode())
fmt.Println(string(code))
}
结果
package main
import (
"abcd"
"fmt"
)
func main() {
fmt.Println("Hello, world!123")
a,b,c :=3,4,5; test:=88
kk :=9
mm,ff,ll:=88,99,100
}