gen_scalars.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //go:build codegen
  2. // +build codegen
  3. package ptr
  4. import "strings"
  5. func GetScalars() Scalars {
  6. return Scalars{
  7. {Type: "bool"},
  8. {Type: "byte"},
  9. {Type: "string"},
  10. {Type: "int"},
  11. {Type: "int8"},
  12. {Type: "int16"},
  13. {Type: "int32"},
  14. {Type: "int64"},
  15. {Type: "uint"},
  16. {Type: "uint8"},
  17. {Type: "uint16"},
  18. {Type: "uint32"},
  19. {Type: "uint64"},
  20. {Type: "float32"},
  21. {Type: "float64"},
  22. {Type: "Time", Import: &Import{Path: "time"}},
  23. {Type: "Duration", Import: &Import{Path: "time"}},
  24. }
  25. }
  26. // Import provides the import path and optional alias
  27. type Import struct {
  28. Path string
  29. Alias string
  30. }
  31. // Package returns the Go package name for the import. Returns alias if set.
  32. func (i Import) Package() string {
  33. if v := i.Alias; len(v) != 0 {
  34. return v
  35. }
  36. if v := i.Path; len(v) != 0 {
  37. parts := strings.Split(v, "/")
  38. pkg := parts[len(parts)-1]
  39. return pkg
  40. }
  41. return ""
  42. }
  43. // Scalar provides the definition of a type to generate pointer utilities for.
  44. type Scalar struct {
  45. Type string
  46. Import *Import
  47. }
  48. // Name returns the exported function name for the type.
  49. func (t Scalar) Name() string {
  50. return strings.Title(t.Type)
  51. }
  52. // Symbol returns the scalar's Go symbol with path if needed.
  53. func (t Scalar) Symbol() string {
  54. if t.Import != nil {
  55. return t.Import.Package() + "." + t.Type
  56. }
  57. return t.Type
  58. }
  59. // Scalars is a list of scalars.
  60. type Scalars []Scalar
  61. // Imports returns all imports for the scalars.
  62. func (ts Scalars) Imports() []*Import {
  63. imports := []*Import{}
  64. for _, t := range ts {
  65. if v := t.Import; v != nil {
  66. imports = append(imports, v)
  67. }
  68. }
  69. return imports
  70. }