c2rst.py 2.3 KB

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