1
0

go-inline 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. # Simple and indolent text processor to do inline go function calling
  3. import sys, re
  4. files = sys.argv
  5. class inline(object):
  6. def __init__(self, name):
  7. self.name = name
  8. self.receiver = ""
  9. self.args = []
  10. self.contents = []
  11. self.file = ""
  12. self.original = ""
  13. inlines = {}
  14. for file in sorted(files, reverse=True):
  15. contents = open(file).read().splitlines()
  16. i = 0
  17. name = ""
  18. while i < len(contents):
  19. line = contents[i]
  20. m = re.match(".*\/\/ \+inline-start", line)
  21. if m:
  22. m2 = re.match("^func\s*(\([\*\s\w]+\))?\s*(\w+)\(([^\)]*)\)", line)
  23. name = m2.group(2)
  24. tinline = inline(name)
  25. tinline.original = line.split("//")[0].strip().rstrip("{")
  26. tinline.file = file
  27. if m2.group(1):
  28. tinline.receiver = m2.group(1).split("(")[1].split(" ")[0]
  29. tinline.args = [arg.strip().split(" ")[0] for arg in m2.group(3).split(",")]
  30. inlines[name] = tinline
  31. else:
  32. if re.match(".*\/\/\s*\+inline-end", line):
  33. inlines[name].contents = "\n".join(inlines[name].contents)
  34. name = ""
  35. elif len(name) > 0:
  36. inlines[name].contents.append(line)
  37. i += 1
  38. def do_inlining(text):
  39. contents = text.splitlines()
  40. buf = []
  41. i = 0
  42. while i < len(contents):
  43. line = contents[i]
  44. m = re.match("\s*\/\/\s*\+inline-call\s+([\w\.]+)\s+(.*)", line)
  45. if m:
  46. inlinet = inlines[m.group(1).split(".")[-1]]
  47. buf.append("// this section is inlined by go-inline")
  48. buf.append("// source function is '{}' in '{}'".format(inlinet.original, inlinet.file))
  49. buf.append("{")
  50. if len(inlinet.receiver) > 0 and inlinet.receiver != m.group(1).split(".")[0]:
  51. buf.append("{} := {}".format(inlinet.receiver, ".".join(m.group(1).split(".")[0:-1])))
  52. callargs = [arg.strip() for arg in m.group(2).split(" ")]
  53. for j in range(len(callargs)):
  54. if inlinet.args[j] != callargs[j]:
  55. buf.append("{} := {}".format(inlinet.args[j], callargs[j]))
  56. buf.append(do_inlining(inlinet.contents))
  57. buf.append("}")
  58. else:
  59. buf.append(line)
  60. i += 1
  61. return "\n".join(buf)
  62. for file in files:
  63. if not file.startswith("_"):
  64. continue
  65. contents = open(file).read()
  66. with open(file.lstrip("_"), "w") as io:
  67. inlined = do_inlining(contents).split("\n")
  68. for i in range(len(inlined)):
  69. if i == 1:
  70. io.write("////////////////////////////////////////////////////////\n")
  71. io.write("// This file was generated by go-inline. DO NOT EDIT. //\n")
  72. io.write("////////////////////////////////////////////////////////\n")
  73. io.write(inlined[i])
  74. io.write("\n")
  75. io.write("\n")