idents.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package generator
  2. import (
  3. "github.com/jcla1/gisp/parser"
  4. "bytes"
  5. "go/ast"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. )
  10. func makeIdentSlice(nodes []*parser.IdentNode) []*ast.Ident {
  11. out := make([]*ast.Ident, len(nodes))
  12. for i, node := range nodes {
  13. out[i] = ast.NewIdent(node.Ident)
  14. }
  15. return out
  16. }
  17. func makeSelectorExpr(x ast.Expr, sel *ast.Ident) *ast.SelectorExpr {
  18. return &ast.SelectorExpr{
  19. X: x,
  20. Sel: sel,
  21. }
  22. }
  23. func makeIdomaticSelector(src string) ast.Expr {
  24. strs := strings.Split(src, "/")
  25. var expr ast.Expr = makeIdomaticIdent(strs[0])
  26. for i := 1; i < len(strs); i++ {
  27. ido := CamelCase(strs[i], true)
  28. expr = makeSelectorExpr(expr, ast.NewIdent(ido))
  29. }
  30. return expr
  31. }
  32. func makeIdomaticIdent(src string) *ast.Ident {
  33. if src == "_" { return ast.NewIdent(src) }
  34. return ast.NewIdent(CamelCase(src, false))
  35. }
  36. var camelingRegex = regexp.MustCompile("[0-9A-Za-z]+")
  37. func CamelCase(src string, capit bool) string {
  38. byteSrc := []byte(src)
  39. chunks := camelingRegex.FindAll(byteSrc, -1)
  40. for idx, val := range chunks {
  41. if idx > 0 || capit {
  42. chunks[idx] = bytes.Title(val)
  43. }
  44. }
  45. return string(bytes.Join(chunks, nil))
  46. }
  47. var gensyms = func() <-chan string {
  48. syms := make(chan string)
  49. go func() {
  50. i := 0
  51. for {
  52. syms <- "GEN" + strconv.Itoa(i)
  53. i++
  54. }
  55. }()
  56. return syms
  57. }()
  58. func generateIdent() *ast.Ident {
  59. return ast.NewIdent(<-gensyms)
  60. }