c2rst.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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(len(c)-1,1,-1):
  44. m = re.search("^#ifdef", c[i])
  45. if m:
  46. last = i
  47. break
  48. # skip empty lines at the end
  49. for i in range(last-1,1,-1):
  50. if len(c[i].strip()) > 0:
  51. return i
  52. return 1
  53. if len(sys.argv) < 2:
  54. print("Usage: python c2rst.py input.c/h output.rst")
  55. exit(0)
  56. with open(sys.argv[1]) as f:
  57. c = f.readlines()
  58. with open(sys.argv[2], 'w') as rst:
  59. print(sys.argv[2])
  60. print(last_line(c))
  61. in_doc = False
  62. last = last_line(c)
  63. for i in range(first_line(c), last+1):
  64. line = c[i]
  65. doc_start = False
  66. doc_end = False
  67. if in_doc:
  68. doc_end = comment_end(line)
  69. line = clean_comment(line)
  70. else:
  71. doc_start = comment_start(line)
  72. if doc_start:
  73. doc_end = comment_end(line)
  74. line = clean_comment(line)
  75. if doc_start:
  76. in_doc = True
  77. if not ((doc_start or doc_end) and line == "\n"):
  78. if not in_doc:
  79. line = " " + line
  80. rst.write(clean_line(line))
  81. if doc_end and i < last:
  82. rst.write("\n.. code-block:: c\n\n")
  83. in_doc = False