c2rst.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import sys
  2. import os
  3. import binascii
  4. import re
  5. remove_keyword = [" UA_EXPORT", " UA_FUNC_ATTR_WARN_UNUSED_RESULT",
  6. " UA_FUNC_ATTR_MALLOC"]
  7. def clean_comment(line):
  8. m = re.search("^( \* |/\*\* )(.*?)( \*/)?$", line)
  9. if not m:
  10. return "\n"
  11. return m.group(2) + "\n"
  12. def clean_line(line):
  13. for keyword in remove_keyword:
  14. line = line.replace(keyword, "")
  15. return line
  16. def comment_start(line):
  17. m = re.search("^/\*\*[ \n]", line)
  18. if not m:
  19. return False
  20. return True
  21. def comment_end(line):
  22. m = re.search(" \*/$", line)
  23. if not m:
  24. return False
  25. return True
  26. def first_line(c):
  27. "Searches for the first comment"
  28. for i in range(len(c)):
  29. if comment_start(c[i]):
  30. return i
  31. return -1
  32. def last_line(c):
  33. "Searches for the latest ifdef (closing the include guard)"
  34. last = 1
  35. for i in range(1, len(c)):
  36. m = re.search("^#ifdef", c[i])
  37. if m:
  38. last = i
  39. return last
  40. if len(sys.argv) < 2:
  41. print("Usage: python c2rst.py input.c/h output.rst")
  42. exit(0)
  43. with open(sys.argv[1]) as f:
  44. c = f.readlines()
  45. with open(sys.argv[2], 'w') as rst:
  46. in_doc = False
  47. for i in range(first_line(c), last_line(c)):
  48. line = c[i]
  49. doc_start = False
  50. doc_end = False
  51. if in_doc:
  52. doc_end = comment_end(line)
  53. line = clean_comment(line)
  54. else:
  55. doc_start = comment_start(line)
  56. if doc_start:
  57. doc_end = comment_end(line)
  58. line = clean_comment(line)
  59. if doc_start:
  60. in_doc = True
  61. if not ((doc_start or doc_end) and line == "\n"):
  62. if not in_doc:
  63. line = " " + line
  64. rst.write(clean_line(line))
  65. if doc_end:
  66. rst.write("\n.. code-block:: c\n\n")
  67. in_doc = False
  68. rst.write("\n")