extract_configs.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2021 Raspberry Pi (Trading) Ltd.
  4. #
  5. # SPDX-License-Identifier: BSD-3-Clause
  6. #
  7. #
  8. # Script to scan the Raspberry Pi Pico SDK tree searching for configuration items
  9. # Outputs a tab separated file of the configuration item:
  10. # name location description type advanced default depends enumvalues group max min
  11. #
  12. # Usage:
  13. #
  14. # ./extract_configs.py <root of source tree> [output file]
  15. #
  16. # If not specified, output file will be `pico_configs.tsv`
  17. import os
  18. import sys
  19. import re
  20. import csv
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. logging.basicConfig(level=logging.INFO)
  24. scandir = sys.argv[1]
  25. outfile = sys.argv[2] if len(sys.argv) > 2 else 'pico_configs.tsv'
  26. CONFIG_RE = re.compile(r'//\s+PICO_CONFIG:\s+(\w+),\s+([^,]+)(?:,\s+(.*))?$')
  27. DEFINE_RE = re.compile(r'#define\s+(\w+)\s+(.+?)(\s*///.*)?$')
  28. all_configs = {}
  29. all_attrs = set()
  30. all_descriptions = {}
  31. all_defines = {}
  32. def ValidateAttrs(config_attrs):
  33. _type = config_attrs.get('type', 'int')
  34. # Validate attrs
  35. if _type == 'int':
  36. assert 'enumvalues' not in config_attrs
  37. _min = _max = _default = None
  38. if config_attrs.get('min', None) is not None:
  39. value = config_attrs['min']
  40. m = re.match(r'^(\d+)e(\d+)$', value.lower())
  41. if m:
  42. _min = int(m.group(1)) * 10**int(m.group(2))
  43. else:
  44. _min = int(value, 0)
  45. if config_attrs.get('max', None) is not None:
  46. value = config_attrs['max']
  47. m = re.match(r'^(\d+)e(\d+)$', value.lower())
  48. if m:
  49. _max = int(m.group(1)) * 10**int(m.group(2))
  50. else:
  51. _max = int(value, 0)
  52. if config_attrs.get('default', None) is not None:
  53. if '/' not in config_attrs['default']:
  54. try:
  55. value = config_attrs['default']
  56. m = re.match(r'^(\d+)e(\d+)$', value.lower())
  57. if m:
  58. _default = int(m.group(1)) * 10**int(m.group(2))
  59. else:
  60. _default = int(value, 0)
  61. except ValueError:
  62. pass
  63. if _min is not None and _max is not None:
  64. if _min > _max:
  65. raise Exception('{} at {}:{} has min {} > max {}'.format(config_name, file_path, linenum, config_attrs['min'], config_attrs['max']))
  66. if _min is not None and _default is not None:
  67. if _min > _default:
  68. raise Exception('{} at {}:{} has min {} > default {}'.format(config_name, file_path, linenum, config_attrs['min'], config_attrs['default']))
  69. if _default is not None and _max is not None:
  70. if _default > _max:
  71. raise Exception('{} at {}:{} has default {} > max {}'.format(config_name, file_path, linenum, config_attrs['default'], config_attrs['max']))
  72. elif _type == 'bool':
  73. assert 'min' not in config_attrs
  74. assert 'max' not in config_attrs
  75. assert 'enumvalues' not in config_attrs
  76. _default = config_attrs.get('default', None)
  77. if _default is not None:
  78. if '/' not in _default:
  79. if (_default.lower() != '0') and (config_attrs['default'].lower() != '1') and ( _default not in all_configs):
  80. logger.info('{} at {}:{} has non-integer default value "{}"'.format(config_name, file_path, linenum, config_attrs['default']))
  81. elif _type == 'enum':
  82. assert 'min' not in config_attrs
  83. assert 'max' not in config_attrs
  84. assert 'enumvalues' in config_attrs
  85. _enumvalues = tuple(config_attrs['enumvalues'].split('|'))
  86. _default = None
  87. if config_attrs.get('default', None) is not None:
  88. _default = config_attrs['default']
  89. if _default is not None:
  90. if _default not in _enumvalues:
  91. raise Exception('{} at {}:{} has default value {} which isn\'t in list of enumvalues {}'.format(config_name, file_path, linenum, config_attrs['default'], config_attrs['enumvalues']))
  92. else:
  93. raise Exception("Found unknown PICO_CONFIG type {} at {}:{}".format(_type, file_path, linenum))
  94. # Scan all .c and .h files in the specific path, recursively.
  95. for dirpath, dirnames, filenames in os.walk(scandir):
  96. for filename in filenames:
  97. file_ext = os.path.splitext(filename)[1]
  98. if file_ext in ('.c', '.h'):
  99. file_path = os.path.join(dirpath, filename)
  100. with open(file_path, encoding="ISO-8859-1") as fh:
  101. linenum = 0
  102. for line in fh.readlines():
  103. linenum += 1
  104. line = line.strip()
  105. m = CONFIG_RE.match(line)
  106. if m:
  107. config_name = m.group(1)
  108. config_description = m.group(2)
  109. _attrs = m.group(3)
  110. # allow commas to appear inside brackets by converting them to and from NULL chars
  111. _attrs = re.sub(r'(\(.+\))', lambda m: m.group(1).replace(',', '\0'), _attrs)
  112. if '=' in config_description:
  113. raise Exception("For {} at {}:{} the description was set to '{}' - has the description field been omitted?".format(config_name, file_path, linenum, config_description))
  114. if config_description in all_descriptions:
  115. raise Exception("Found description {} at {}:{} but it was already used at {}:{}".format(config_description, file_path, linenum, os.path.join(scandir, all_descriptions[config_description]['filename']), all_descriptions[config_description]['line_number']))
  116. else:
  117. all_descriptions[config_description] = {'config_name': config_name, 'filename': os.path.relpath(file_path, scandir), 'line_number': linenum}
  118. config_attrs = {}
  119. prev = None
  120. # Handle case where attr value contains a comma
  121. for item in _attrs.split(','):
  122. if "=" not in item:
  123. assert(prev)
  124. item = prev + "," + item
  125. try:
  126. k, v = (i.strip() for i in item.split('='))
  127. except ValueError:
  128. raise Exception('{} at {}:{} has malformed value {}'.format(config_name, file_path, linenum, item))
  129. config_attrs[k] = v.replace('\0', ',')
  130. all_attrs.add(k)
  131. prev = item
  132. #print(file_path, config_name, config_attrs)
  133. if 'group' not in config_attrs:
  134. raise Exception('{} at {}:{} has no group attribute'.format(config_name, file_path, linenum))
  135. #print(file_path, config_name, config_attrs)
  136. if config_name in all_configs:
  137. raise Exception("Found {} at {}:{} but it was already declared at {}:{}".format(config_name, file_path, linenum, os.path.join(scandir, all_configs[config_name]['filename']), all_configs[config_name]['line_number']))
  138. else:
  139. all_configs[config_name] = {'attrs': config_attrs, 'filename': os.path.relpath(file_path, scandir), 'line_number': linenum, 'description': config_description}
  140. else:
  141. m = DEFINE_RE.match(line)
  142. if m:
  143. name = m.group(1)
  144. value = m.group(2)
  145. # discard any 'u' qualifier
  146. m = re.match(r'^((0x)?\d+)u$', value.lower())
  147. if m:
  148. value = m.group(1)
  149. else:
  150. # discard any '_u(X)' macro
  151. m = re.match(r'^_u\(((0x)?\d+)\)$', value.lower())
  152. if m:
  153. value = m.group(1)
  154. if name not in all_defines:
  155. all_defines[name] = dict()
  156. if value not in all_defines[name]:
  157. all_defines[name][value] = set()
  158. all_defines[name][value] = (file_path, linenum)
  159. # Check for defines with missing PICO_CONFIG entries
  160. resolved_defines = dict()
  161. for d in all_defines:
  162. if d not in all_configs and d.startswith("PICO_"):
  163. logger.warning("Potential unmarked PICO define {}".format(d))
  164. # resolve "nested defines" - this allows e.g. USB_DPRAM_MAX to resolve to USB_DPRAM_SIZE which is set to 4096 (which then matches the relevant PICO_CONFIG entry)
  165. for val in all_defines[d]:
  166. if val in all_defines:
  167. resolved_defines[d] = all_defines[val]
  168. for config_name in all_configs:
  169. ValidateAttrs(all_configs[config_name]['attrs'])
  170. # Check that default values match up
  171. if 'default' in all_configs[config_name]['attrs']:
  172. if config_name in all_defines:
  173. if all_configs[config_name]['attrs']['default'] not in all_defines[config_name] and (config_name not in resolved_defines or all_configs[config_name]['attrs']['default'] not in resolved_defines[config_name]):
  174. if '/' in all_configs[config_name]['attrs']['default'] or ' ' in all_configs[config_name]['attrs']['default']:
  175. continue
  176. # There _may_ be multiple matching defines, but arbitrarily display just one in the error message
  177. first_define_value = list(all_defines[config_name].keys())[0]
  178. raise Exception('Found {} at {}:{} with a default of {}, but #define says {} (at {}:{})'.format(config_name, os.path.join(scandir, all_configs[config_name]['filename']), all_configs[config_name]['line_number'], all_configs[config_name]['attrs']['default'], first_define_value, all_defines[config_name][first_define_value][0], all_defines[config_name][first_define_value][1]))
  179. else:
  180. raise Exception('Found {} at {}:{} with a default of {}, but no matching #define found'.format(config_name, os.path.join(scandir, all_configs[config_name]['filename']), all_configs[config_name]['line_number'], all_configs[config_name]['attrs']['default']))
  181. with open(outfile, 'w', newline='') as csvfile:
  182. fieldnames = ('name', 'location', 'description', 'type') + tuple(sorted(all_attrs - set(['type'])))
  183. writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', dialect='excel-tab')
  184. writer.writeheader()
  185. for config_name in sorted(all_configs):
  186. writer.writerow({'name': config_name, 'location': '{}:{}'.format(all_configs[config_name]['filename'], all_configs[config_name]['line_number']), 'description': all_configs[config_name]['description'], **all_configs[config_name]['attrs']})