c2rst.py 2.7 KB

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