首页 > 代码库 > 用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(r‘import\s+(\w*\s*)"(\w+)"‘, line) if match != None: dict[‘import‘].append((match.groups()[-1], linen)) elif re.match(r‘import\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(r‘type\s+(\w+)\s+struct‘, line) if match != None: dict[‘struct‘][match.groups()[-1]] = {‘linen‘:linen, ‘method‘:[]} else: match = re.match(r‘func\s+(\w+)\(.*\)‘, line) if match != None: dict[‘func‘].append((match.groups()[-1], linen)) else: match = re.match(r‘func\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源文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。