gen-cpydiff.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # This file is part of the MicroPython project, http://micropython.org/
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) 2016 Rami Ali
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. """ gen-cpydiff generates documentation which outlines operations that differ between MicroPython
  25. and CPython. This script is called by the docs Makefile for html and Latex and may be run
  26. manually using the command make gen-cpydiff. """
  27. import os
  28. import errno
  29. import subprocess
  30. import time
  31. import re
  32. from collections import namedtuple
  33. # MicroPython supports syntax of CPython 3.4 with some features from 3.5, and
  34. # such version should be used to test for differences. If your default python3
  35. # executable is of lower version, you can point MICROPY_CPYTHON3 environment var
  36. # to the correct executable.
  37. if os.name == 'nt':
  38. CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3.exe')
  39. MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/windows/micropython.exe')
  40. else:
  41. CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3')
  42. MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/unix/micropython')
  43. TESTPATH = '../tests/cpydiff/'
  44. DOCPATH = '../docs/genrst/'
  45. INDEXTEMPLATE = '../docs/differences/index_template.txt'
  46. INDEX = 'index.rst'
  47. HEADER = '.. This document was generated by tools/gen-cpydiff.py\n\n'
  48. UIMPORTLIST = {'struct', 'collections', 'json'}
  49. CLASSMAP = {'Core': 'Core Language', 'Types': 'Builtin Types'}
  50. INDEXPRIORITY = ['syntax', 'core_language', 'builtin_types', 'modules']
  51. RSTCHARS = ['=', '-', '~', '`', ':']
  52. SPLIT = '"""\n|categories: |description: |cause: |workaround: '
  53. TAB = ' '
  54. Output = namedtuple('output', ['name', 'class_', 'desc', 'cause', 'workaround', 'code',
  55. 'output_cpy', 'output_upy', 'status'])
  56. def readfiles():
  57. """ Reads test files """
  58. tests = list(filter(lambda x: x.endswith('.py'), os.listdir(TESTPATH)))
  59. tests.sort()
  60. files = []
  61. for test in tests:
  62. text = open(TESTPATH + test, 'r').read()
  63. try:
  64. class_, desc, cause, workaround, code = [x.rstrip() for x in \
  65. list(filter(None, re.split(SPLIT, text)))]
  66. output = Output(test, class_, desc, cause, workaround, code, '', '', '')
  67. files.append(output)
  68. except IndexError:
  69. print('Incorrect format in file ' + TESTPATH + test)
  70. return files
  71. def uimports(code):
  72. """ converts CPython module names into MicroPython equivalents """
  73. for uimport in UIMPORTLIST:
  74. uimport = bytes(uimport, 'utf8')
  75. code = code.replace(uimport, b'u' + uimport)
  76. return code
  77. def run_tests(tests):
  78. """ executes all tests """
  79. results = []
  80. for test in tests:
  81. with open(TESTPATH + test.name, 'rb') as f:
  82. input_cpy = f.read()
  83. input_upy = uimports(input_cpy)
  84. process = subprocess.Popen(CPYTHON3, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  85. output_cpy = [com.decode('utf8') for com in process.communicate(input_cpy)]
  86. process = subprocess.Popen(MICROPYTHON, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  87. output_upy = [com.decode('utf8') for com in process.communicate(input_upy)]
  88. if output_cpy[0] == output_upy[0] and output_cpy[1] == output_upy[1]:
  89. status = 'Supported'
  90. print('Supported operation!\nFile: ' + TESTPATH + test.name)
  91. else:
  92. status = 'Unsupported'
  93. output = Output(test.name, test.class_, test.desc, test.cause,
  94. test.workaround, test.code, output_cpy, output_upy, status)
  95. results.append(output)
  96. results.sort(key=lambda x: x.class_)
  97. return results
  98. def indent(block, spaces):
  99. """ indents paragraphs of text for rst formatting """
  100. new_block = ''
  101. for line in block.split('\n'):
  102. new_block += spaces + line + '\n'
  103. return new_block
  104. def gen_table(contents):
  105. """ creates a table given any set of columns """
  106. xlengths = []
  107. ylengths = []
  108. for column in contents:
  109. col_len = 0
  110. for entry in column:
  111. lines = entry.split('\n')
  112. for line in lines:
  113. col_len = max(len(line) + 2, col_len)
  114. xlengths.append(col_len)
  115. for i in range(len(contents[0])):
  116. ymax = 0
  117. for j in range(len(contents)):
  118. ymax = max(ymax, len(contents[j][i].split('\n')))
  119. ylengths.append(ymax)
  120. table_divider = '+' + ''.join(['-' * i + '+' for i in xlengths]) + '\n'
  121. table = table_divider
  122. for i in range(len(ylengths)):
  123. row = [column[i] for column in contents]
  124. row = [entry + '\n' * (ylengths[i]-len(entry.split('\n'))) for entry in row]
  125. row = [entry.split('\n') for entry in row]
  126. for j in range(ylengths[i]):
  127. k = 0
  128. for entry in row:
  129. width = xlengths[k]
  130. table += ''.join(['| {:{}}'.format(entry[j], width - 1)])
  131. k += 1
  132. table += '|\n'
  133. table += table_divider
  134. return table + '\n'
  135. def gen_rst(results):
  136. """ creates restructured text documents to display tests """
  137. # make sure the destination directory exists
  138. try:
  139. os.mkdir(DOCPATH)
  140. except OSError as e:
  141. if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
  142. raise
  143. toctree = []
  144. class_ = []
  145. for output in results:
  146. section = output.class_.split(',')
  147. for i in range(len(section)):
  148. section[i] = section[i].rstrip()
  149. if section[i] in CLASSMAP:
  150. section[i] = CLASSMAP[section[i]]
  151. if i >= len(class_) or section[i] != class_[i]:
  152. if i == 0:
  153. filename = section[i].replace(' ', '_').lower()
  154. rst = open(DOCPATH + filename + '.rst', 'w')
  155. rst.write(HEADER)
  156. rst.write(section[i] + '\n')
  157. rst.write(RSTCHARS[0] * len(section[i]))
  158. rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
  159. toctree.append(filename)
  160. else:
  161. rst.write(section[i] + '\n')
  162. rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i]))
  163. rst.write('\n\n')
  164. class_ = section
  165. rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0])
  166. rst.write(output.desc + '\n')
  167. rst.write('~' * len(output.desc) + '\n\n')
  168. if output.cause != 'Unknown':
  169. rst.write('**Cause:** ' + output.cause + '\n\n')
  170. if output.workaround != 'Unknown':
  171. rst.write('**Workaround:** ' + output.workaround + '\n\n')
  172. rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n')
  173. output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip()
  174. output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy
  175. output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip()
  176. output_upy = ('::\n\n' if output_upy != '' else '') + output_upy
  177. table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]])
  178. rst.write(table)
  179. template = open(INDEXTEMPLATE, 'r')
  180. index = open(DOCPATH + INDEX, 'w')
  181. index.write(HEADER)
  182. index.write(template.read())
  183. for section in INDEXPRIORITY:
  184. if section in toctree:
  185. index.write(indent(section + '.rst', TAB))
  186. toctree.remove(section)
  187. for section in toctree:
  188. index.write(indent(section + '.rst', TAB))
  189. def main():
  190. """ Main function """
  191. # set search path so that test scripts find the test modules (and no other ones)
  192. os.environ['PYTHONPATH'] = TESTPATH
  193. os.environ['MICROPYPATH'] = TESTPATH
  194. files = readfiles()
  195. results = run_tests(files)
  196. gen_rst(results)
  197. main()