首页 > 代码库 > 用Python解析Golang源文件

用Python解析Golang源文件

在给ulipad代码编辑器做一个支持Golang的plugin,这个文件是plugin所需的mClassBrowser.py文件的一部分

GolangParse.py

import redef parseFile(filename):    dict = {import:[], struct:{}, func:[]}        in_import = False        lines = open(filename).readlines()        for linen in range(0, len(lines)):        line = lines[linen].lstrip()                match = re.match(rimport\s+(\w*\s*)"(\w+)", line)        if match != None:            dict[import].append((match.groups()[-1], linen))        elif re.match(rimport\s+\(, line) != None:            in_import = True        elif in_import:            match = re.match(r(\w*\s*)"(\w+)", line)            if match != None:                dict[import].append((match.groups()[-1], linen))            elif re.match(r\), line):                in_import = False        else:            match = re.match(rtype\s+(\w+)\s+struct, line)            if match != None:                dict[struct][match.groups()[-1]] = {linen:linen, method:[]}            else:                match = re.match(rfunc\s+(\w+)\(.*\), line)                if match != None:                    dict[func].append((match.groups()[-1], linen))                else:                    match = re.match(rfunc\s+\(\w+\s+\*(\w+)\)\s+(\w+)\(.*\), line)                    if match != None:                        dict[struct][match.groups()[0]][method].append((match.groups()[-1], linen))    return dictif __name__ == "__main__":    dict = parseFile(test.go)    print ----- import -----    for name, linen in dict[import]:        print name, linen    print ----- struct -----    for name in dict[struct]:        print name, dict[struct][name][linen]        print \t, ----- method -----        for name, linen in dict[struct][name][method]:            print \t, name, linen    print ------ func ------    for name, linen in dict[func]:        print name, linen


被解析文件test.go

package mainimport "fmt"import "sex"import (    "log"    "time")type Person struct {    Name string    Age  uint    Sex  sex.Sex}func (self *Person) SayHi() {    fmt.Printf("Hi from %T\n", *self)}func (self *Person) SayHello() {    fmt.Printf("Hello from %T\n", *self)}type Student struct {    Person    School string}func (self *Student) SayHello() {    fmt.Printf("Hello from %T\n", *self)}func main() {    lucy := Student{Person: Person{Name: "Lucy", Age: 15, Sex: sex.Female},        School: "Beijing Primary School"}    fmt.Printf("Age    of %s: %v\n", lucy.Name, lucy.Age)    fmt.Printf("Sex    of %s: %v\n", lucy.Name, lucy.Sex)    fmt.Printf("School of %s: %v\n", lucy.Name, lucy.School)    lucy.SayHi()    lucy.SayHello()    lucy.Person.SayHello()}


输出结果

 

用Python解析Golang源文件