github.com/junaozun/protoc-gen-go-clone@v0.0.0-20231229025521-89199567f720/plugin/clone/parse_fd.go (about)

     1  package clone
     2  
     3  import (
     4  	"strings"
     5  	"unicode"
     6  
     7  	"github.com/junaozun/protoc-gen-go-clone/generator"
     8  
     9  	"github.com/golang/protobuf/protoc-gen-go/descriptor"
    10  )
    11  
    12  type IFieldDesc interface {
    13  	clone(funcName string) ([]byte, error)
    14  	isValueBase() bool
    15  	getValueType() string
    16  	getValuePrefix() string
    17  	addFuncWay(temp *genTemp, funcWay map[string]IFieldDesc) (string, string)
    18  	getFinalVal() string
    19  }
    20  
    21  type parseFd struct {
    22  	gen           *generator.Generator
    23  	sourceFileMap map[string]*filesAllMsg // fileName:fileMsg
    24  	annObject     map[string][]string     // pkgName:有注释对象
    25  }
    26  
    27  // all files message
    28  type filesAllMsg struct {
    29  	isSourceFile bool // 是否传入的源文件
    30  	isProto3     bool
    31  	packageName  string                  // 文件所属包
    32  	allObjects   map[string][]IFieldDesc // 对象名:fieldsDesc
    33  }
    34  
    35  type mapEntry struct {
    36  	fieldName   string // 字段名
    37  	keyType     string // key 类型 string
    38  	valueType   string // value 类型 string,Apple
    39  	valuePrefix string // value 的包名
    40  	isBaseType  bool   // value 是否基础类型
    41  	needPrefix  bool
    42  	finalValue  string
    43  }
    44  
    45  type array struct {
    46  	fieldName   string
    47  	valueType   string
    48  	valuePrefix string
    49  	isBaseType  bool
    50  	needPrefix  bool
    51  	finalValue  string
    52  }
    53  
    54  type enum struct {
    55  	isProto3    bool
    56  	fieldName   string
    57  	valueType   string
    58  	valuePrefix string
    59  	needPrefix  bool
    60  	finalValue  string
    61  }
    62  
    63  type message struct {
    64  	fieldName   string
    65  	valueType   string
    66  	valuePrefix string
    67  	needPrefix  bool
    68  	finalValue  string
    69  }
    70  
    71  type base struct {
    72  	isProto3  bool
    73  	fieldName string
    74  	valueType string
    75  }
    76  
    77  func NewParseFd(gen *generator.Generator) *parseFd {
    78  	return &parseFd{
    79  		gen:           gen,
    80  		sourceFileMap: make(map[string]*filesAllMsg),
    81  		annObject:     make(map[string][]string),
    82  	}
    83  }
    84  
    85  func (p *parseFd) ParseFileDesc(file *generator.FileDescriptor, cb func(announce []*descriptor.SourceCodeInfo_Location) []string) bool {
    86  	fsGen := &filesAllMsg{
    87  		isSourceFile: p.isSourceFile(file.GetName()),
    88  		isProto3:     fileIsProto3(file.FileDescriptorProto),
    89  		packageName:  file.GetPackage(),
    90  		allObjects:   make(map[string][]IFieldDesc),
    91  	}
    92  	p.sourceFileMap[file.GetName()] = fsGen
    93  	for _, m := range file.FileDescriptorProto.MessageType {
    94  		middleMap := make(map[string]IFieldDesc)
    95  		p.parseAllFields(m, fsGen, file.GetName(), file.GetPackage(), middleMap, "")
    96  	}
    97  	// get annotation object
    98  	p.annObject[file.GetPackage()] = append(p.annObject[file.GetPackage()], cb(file.GetSourceCodeInfo().GetLocation())...)
    99  
   100  	if len(p.sourceFileMap) != len(p.gen.Request.ProtoFile) {
   101  		return false
   102  	}
   103  	return true
   104  }
   105  
   106  func convertFieldDesc(valueTypes string) (valueType string, valuePrefix string, isBaseType bool) {
   107  	if strings.Contains(valueTypes, ".") {
   108  		res := strings.Split(valueTypes, ".")
   109  		if len(res) != 2 {
   110  			panic("convertFieldDesc err")
   111  		}
   112  		return res[1], res[0], false
   113  	}
   114  	return valueTypes, "", true
   115  }
   116  
   117  func isLowerFirstChar(name string) bool {
   118  	return unicode.IsLower(rune(name[0]))
   119  }
   120  
   121  // Given a type name defined in a .proto, return its name as we will print it.
   122  func (p *parseFd) typeName(str string) string {
   123  	return p.gen.TypeName(p.objectNamed(str))
   124  }
   125  
   126  // Given a type name defined in a .proto, return its object.
   127  // Also record that we're using it, to guarantee the associated import.
   128  func (g *parseFd) objectNamed(name string) generator.Object {
   129  	g.gen.RecordTypeUse(name)
   130  	return g.gen.ObjectNamed(name)
   131  }
   132  
   133  func (p *parseFd) parseAllFields(m *descriptor.DescriptorProto, fsGen *filesAllMsg, fileName, filePkgName string, middle map[string]IFieldDesc, parent string) {
   134  	mName := generator.CamelCase(m.GetName())
   135  	// 是内嵌类型的情况下,判断一下内嵌message首字母是大写还是小写
   136  	if parent != "" {
   137  		if isLowerFirstChar(m.GetName()) {
   138  			mName = parent + mName
   139  		} else {
   140  			mName = parent + "_" + mName
   141  		}
   142  	}
   143  
   144  	fsGen.allObjects[mName] = nil
   145  
   146  	// enum 和 message都可能以嵌套形式存在
   147  	for _, l := range m.NestedType {
   148  		if !l.GetOptions().GetMapEntry() {
   149  			p.parseAllFields(l, fsGen, fileName, filePkgName, middle, mName)
   150  			continue
   151  		}
   152  		_, keyType := getValueTypeAndValue(l.GetField()[0])
   153  		_, valueTypes := getValueTypeAndValue(l.GetField()[1]) // 带有前缀
   154  		if valueTypes == "" {
   155  			continue
   156  		}
   157  		valueType, valuePrefix, isBaseType := convertFieldDesc(valueTypes)
   158  		var finalValue string
   159  		aa := l.GetField()[1].GetTypeName()
   160  		if aa != "" {
   161  			finalValue = p.typeName(aa)
   162  		}
   163  		middle[l.GetName()] = &mapEntry{
   164  			fieldName:   convertFieldName(l.GetName()[:len(l.GetName())-5]), // map类型尾部都拼接了Entry,所以这里要删掉,
   165  			keyType:     keyType,
   166  			valueType:   valueType,
   167  			valuePrefix: valuePrefix,
   168  			isBaseType:  isBaseType,
   169  			finalValue:  finalValue,
   170  		}
   171  	}
   172  
   173  	for _, f := range m.Field {
   174  		iFieldDesc, valueTypes := getValueTypeAndValue(f)
   175  		valueType, valuePrefix, isBaseType := convertFieldDesc(valueTypes)
   176  		aa := f.GetTypeName()
   177  		var finalValue string
   178  		if aa != "" {
   179  			finalValue = p.typeName(aa)
   180  		}
   181  		var (
   182  			fd IFieldDesc
   183  		)
   184  		switch iFieldDesc.(type) {
   185  		case *mapEntry:
   186  			fd = middle[strings.Title(f.GetName())+"Entry"]
   187  		case *array:
   188  			fd = &array{
   189  				fieldName:   convertFieldName(f.GetName()),
   190  				valueType:   valueType,
   191  				valuePrefix: valuePrefix,
   192  				isBaseType:  isBaseType,
   193  				finalValue:  finalValue,
   194  			}
   195  		case *enum:
   196  			newStr := f.GetTypeName()[1:]
   197  			ls := strings.Split(newStr, ".")
   198  			var eName string
   199  			if len(ls) == 2 {
   200  				eName = strings.Title(ls[1])
   201  			} else {
   202  				// 对内嵌enum的处理
   203  				eName = strings.Title(strings.Split(spiltValueType(newStr), ".")[1])
   204  			}
   205  			fd = &enum{
   206  				isProto3:    fsGen.isProto3,
   207  				fieldName:   convertFieldName(f.GetName()),
   208  				valueType:   eName,
   209  				valuePrefix: ls[0],
   210  				finalValue:  finalValue,
   211  			}
   212  			fsGen.allObjects[eName] = append(fsGen.allObjects[eName], fd)
   213  		case *message:
   214  			fd = &message{
   215  				fieldName:   convertFieldName(f.GetName()),
   216  				valueType:   valueType,
   217  				valuePrefix: valuePrefix,
   218  				finalValue:  finalValue,
   219  			}
   220  		case *base:
   221  			fd = &base{
   222  				isProto3:  fsGen.isProto3,
   223  				fieldName: convertFieldName(f.GetName()),
   224  				valueType: valueType,
   225  			}
   226  		default:
   227  			continue
   228  		}
   229  		fsGen.allObjects[mName] = append(fsGen.allObjects[mName], fd)
   230  	}
   231  }
   232  
   233  func convertFieldName(fieldName string) string {
   234  	var newString string
   235  	var nextBig bool
   236  	for _, v := range fieldName {
   237  		if string(v) == "_" {
   238  			nextBig = true
   239  			continue
   240  		}
   241  		if nextBig {
   242  			newString += strings.Title(string(v))
   243  			nextBig = false
   244  			continue
   245  		}
   246  		newString += string(v)
   247  	}
   248  	return newString
   249  }
   250  
   251  func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
   252  	return file.GetSyntax() == "proto3"
   253  }
   254  
   255  func getValueTypeAndValue(fl *descriptor.FieldDescriptorProto) (IFieldDesc, string) {
   256  	if fl.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED {
   257  		switch fl.GetType() {
   258  		case descriptor.FieldDescriptorProto_TYPE_STRING:
   259  			return &array{}, "string"
   260  		case descriptor.FieldDescriptorProto_TYPE_INT32:
   261  			return &array{}, "int32"
   262  		case descriptor.FieldDescriptorProto_TYPE_INT64:
   263  			return &array{}, "int64"
   264  		case descriptor.FieldDescriptorProto_TYPE_BYTES:
   265  			return &array{}, "byte"
   266  		case descriptor.FieldDescriptorProto_TYPE_UINT32:
   267  			return &array{}, "uint32"
   268  		case descriptor.FieldDescriptorProto_TYPE_UINT64:
   269  			return &array{}, "uint64"
   270  		case descriptor.FieldDescriptorProto_TYPE_BOOL:
   271  			return &array{}, "bool"
   272  		case descriptor.FieldDescriptorProto_TYPE_FLOAT:
   273  			return &array{}, "float32"
   274  		case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
   275  			return &array{}, "float64"
   276  		case descriptor.FieldDescriptorProto_TYPE_ENUM:
   277  			return &array{}, "enum"
   278  		case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
   279  			// 可能是数组对象类型,也可能是map类型
   280  			str := fl.GetTypeName()
   281  			if len(str) == 0 {
   282  				panic("message_type not found typeName")
   283  			}
   284  			newStr := str[1:]
   285  			res := strings.Split(newStr, ".")
   286  			if len(res) < 2 {
   287  				panic("message_type split error")
   288  			}
   289  			if res[len(res)-1] == strings.Title(fl.GetName())+"Entry" {
   290  				return &mapEntry{}, ""
   291  			}
   292  			if len(res) != 2 {
   293  				newStr = spiltValueType(newStr)
   294  			}
   295  			return &array{}, newStr
   296  		default:
   297  			panic("label LABEL_REPEATED ,type_err")
   298  		}
   299  	} else if fl.GetLabel() == descriptor.FieldDescriptorProto_LABEL_OPTIONAL || fl.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REQUIRED {
   300  		switch fl.GetType() {
   301  		case descriptor.FieldDescriptorProto_TYPE_STRING:
   302  			return &base{}, "string"
   303  		case descriptor.FieldDescriptorProto_TYPE_INT32:
   304  			return &base{}, "int32"
   305  		case descriptor.FieldDescriptorProto_TYPE_INT64:
   306  			return &base{}, "int64"
   307  		case descriptor.FieldDescriptorProto_TYPE_BYTES:
   308  			return &base{}, "byte"
   309  		case descriptor.FieldDescriptorProto_TYPE_UINT32:
   310  			return &base{}, "uint32"
   311  		case descriptor.FieldDescriptorProto_TYPE_UINT64:
   312  			return &base{}, "uint64"
   313  		case descriptor.FieldDescriptorProto_TYPE_BOOL:
   314  			return &base{}, "bool"
   315  		case descriptor.FieldDescriptorProto_TYPE_ENUM:
   316  			return &enum{}, "enum"
   317  		case descriptor.FieldDescriptorProto_TYPE_FLOAT:
   318  			return &base{}, "float32"
   319  		case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
   320  			return &base{}, "float64"
   321  		case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
   322  			str := fl.GetTypeName()
   323  			if len(str) == 0 {
   324  				panic("message_type not found typeName")
   325  			}
   326  			newStr := str[1:]
   327  			res := strings.Split(newStr, ".")
   328  			if len(res) < 2 {
   329  				panic("message_type split error")
   330  			}
   331  			if len(res) != 2 {
   332  				newStr = spiltValueType(newStr)
   333  			}
   334  			return &message{}, newStr
   335  		default:
   336  			panic("label LABEL_OPTIONAL ,type_err")
   337  		}
   338  	} else {
   339  		panic("getLabelType label type error")
   340  	}
   341  }
   342  
   343  // 先忽略第一个分隔符. 从遇到第二个分隔符开始,遇到大写下划线拼接,遇到小写转成大写再拼接
   344  func spiltValueType(valueType string) string {
   345  	var (
   346  		newStr string
   347  	)
   348  	str := strings.Split(valueType, ".")
   349  	for i, v := range str {
   350  		if i == 1 {
   351  			v = "." + strings.Title(v)
   352  		} else if i > 1 {
   353  			if !isLowerFirstChar(v) {
   354  				v = "_" + strings.Title(v)
   355  			} else {
   356  				v = strings.Title(v)
   357  			}
   358  		}
   359  		newStr += v
   360  	}
   361  	return newStr
   362  }
   363  
   364  func (p *parseFd) isSourceFile(file string) bool {
   365  	for _, sourceFile := range p.gen.Request.GetFileToGenerate() {
   366  		if file == sourceFile {
   367  			return true
   368  		}
   369  	}
   370  	return false
   371  }
   372  
   373  func (m *mapEntry) isValueBase() bool {
   374  	return m.isBaseType
   375  }
   376  
   377  func (a *array) isValueBase() bool {
   378  	return a.isBaseType
   379  }
   380  
   381  func (e *enum) isValueBase() bool {
   382  	return true
   383  }
   384  
   385  func (m *message) isValueBase() bool {
   386  	return false
   387  }
   388  
   389  func (b *base) isValueBase() bool {
   390  	return true
   391  }
   392  
   393  func (m *mapEntry) getValueType() string {
   394  	return m.valueType
   395  }
   396  
   397  func (a *array) getValueType() string {
   398  	return a.valueType
   399  }
   400  
   401  func (e *enum) getValueType() string {
   402  	return e.valueType
   403  }
   404  
   405  func (m *message) getValueType() string {
   406  	return m.valueType
   407  }
   408  
   409  func (b *base) getValueType() string {
   410  	return b.valueType
   411  }
   412  
   413  func (m *mapEntry) getValuePrefix() string {
   414  	return m.valuePrefix
   415  }
   416  
   417  func (a *array) getValuePrefix() string {
   418  	return a.valuePrefix
   419  }
   420  
   421  func (e *enum) getValuePrefix() string {
   422  	return ""
   423  }
   424  
   425  func (m *message) getValuePrefix() string {
   426  	return m.valuePrefix
   427  }
   428  
   429  func (b *base) getValuePrefix() string {
   430  	return ""
   431  }
   432  
   433  func (m *mapEntry) getFinalVal() string {
   434  	return m.finalValue
   435  }
   436  
   437  func (a *array) getFinalVal() string {
   438  	return a.finalValue
   439  }
   440  
   441  func (e *enum) getFinalVal() string {
   442  	return e.finalValue
   443  }
   444  
   445  func (m *message) getFinalVal() string {
   446  	return m.finalValue
   447  }
   448  
   449  func (b *base) getFinalVal() string {
   450  	return b.fieldName
   451  }