c2rst.py 2.6 KB

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