在给ulipad代码编辑器做一个支持Golang的plugin,这个文件是plugin所需的mClassBrowser.py文件的一部分
GolangParse.py
import re def 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 dict if __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 main import "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() }
输出结果
时间: 2024-10-10 15:05:03