github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgGoSource/kmgGoParser/Package.go (about)

     1  package kmgGoParser
     2  
     3  import (
     4  	"fmt"
     5  	"path"
     6  )
     7  
     8  // 表示一个package,注意: 一个目录下最多会有2个package.暂时忽略xxx_test 这种package
     9  type Package struct {
    10  	Program       *Program
    11  	PkgPath       string
    12  	ImportMap     map[string]bool //这个package第一层import
    13  	FuncList      []*FuncOrMethodDeclaration
    14  	MethodList    []*FuncOrMethodDeclaration
    15  	NamedTypeList []*NamedType
    16  }
    17  
    18  func (pkg *Package) GetImportList() []string {
    19  	output := make([]string, 0, len(pkg.ImportMap))
    20  	for imp := range pkg.ImportMap {
    21  		output = append(output, imp)
    22  	}
    23  	return output
    24  }
    25  
    26  func (pkg *Package) AddImport(pkgPath string) {
    27  	if pkgPath != "" {
    28  		pkg.ImportMap[pkgPath] = true
    29  	}
    30  }
    31  
    32  func (pkg *Package) GetNamedTypeMethodSet(typ *NamedType) (output []*FuncOrMethodDeclaration) {
    33  	if typ.PackagePath != pkg.PkgPath {
    34  		panic(fmt.Errorf("can not get MethodSet on diff pacakge typ[%s] pkg[%s]", typ.PackagePath, pkg.PkgPath))
    35  	}
    36  	for _, decl := range pkg.MethodList {
    37  		recvier := decl.ReceiverType
    38  		if recvier.GetKind() == Ptr {
    39  			recvier = recvier.(PointerType).Elem
    40  		}
    41  		if recvier.GetKind() != Named {
    42  			panic(fmt.Errorf("[GetNamedTypeMethodSet] reciver is not a named type %T %s", recvier, recvier.GetKind()))
    43  		}
    44  		if recvier.(*NamedType).Name == typ.Name {
    45  			output = append(output, decl)
    46  		}
    47  	}
    48  	return output
    49  }
    50  
    51  // 表示一个go的file
    52  type File struct {
    53  	PackageName    string //最开头的package上面写的东西.
    54  	PackagePath    string
    55  	ImportMap      map[string]bool //这个文件的导入表
    56  	AliasImportMap map[string]string
    57  	FuncList       []*FuncOrMethodDeclaration
    58  	MethodList     []*FuncOrMethodDeclaration
    59  	NamedTypeList  []*NamedType
    60  	Pkg            *Package
    61  }
    62  
    63  func (pkg *File) AddImport(pkgPath string, aliasPath string) {
    64  	if pkgPath == "" {
    65  		return
    66  	}
    67  	pkg.ImportMap[pkgPath] = true
    68  	if aliasPath == "" {
    69  		aliasPath = path.Base(pkgPath)
    70  	}
    71  	pkg.AliasImportMap[aliasPath] = pkgPath
    72  }
    73  
    74  func (gofile *File) LookupFullPackagePath(pkgAliasPath string) (string, error) {
    75  	pkgPath := gofile.AliasImportMap[pkgAliasPath]
    76  	if pkgPath == "" {
    77  		return pkgAliasPath, fmt.Errorf("unable to find import alias %s", pkgAliasPath)
    78  	}
    79  	return pkgPath, nil
    80  }