schema.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. #!/usr/bin/env python3
  2. #
  3. # schema.py
  4. #
  5. # Used by signature.py via common-dependencies.py to generate a schema file during the PlatformIO build
  6. # when CONFIG_EXPORT is defined in the configuration.
  7. #
  8. # This script can also be run standalone from within the Marlin repo to generate JSON and YAML schema files.
  9. #
  10. # This script is a companion to abm/js/schema.js in the MarlinFirmware/AutoBuildMarlin project, which has
  11. # been extended to evaluate conditions and can determine what options are actually enabled, not just which
  12. # options are uncommented. That will be migrated to this script for standalone migration.
  13. #
  14. import re,json
  15. from pathlib import Path
  16. def extend_dict(d:dict, k:tuple):
  17. if len(k) >= 1 and k[0] not in d:
  18. d[k[0]] = {}
  19. if len(k) >= 2 and k[1] not in d[k[0]]:
  20. d[k[0]][k[1]] = {}
  21. if len(k) >= 3 and k[2] not in d[k[0]][k[1]]:
  22. d[k[0]][k[1]][k[2]] = {}
  23. grouping_patterns = [
  24. re.compile(r'^([XYZIJKUVW]|[XYZ]2|Z[34]|E[0-7])$'),
  25. re.compile(r'^AXIS\d$'),
  26. re.compile(r'^(MIN|MAX)$'),
  27. re.compile(r'^[0-8]$'),
  28. re.compile(r'^HOTEND[0-7]$'),
  29. re.compile(r'^(HOTENDS|BED|PROBE|COOLER)$'),
  30. re.compile(r'^[XYZIJKUVW]M(IN|AX)$')
  31. ]
  32. # If the indexed part of the option name matches a pattern
  33. # then add it to the dictionary.
  34. def find_grouping(gdict, filekey, sectkey, optkey, pindex):
  35. optparts = optkey.split('_')
  36. if 1 < len(optparts) > pindex:
  37. for patt in grouping_patterns:
  38. if patt.match(optparts[pindex]):
  39. subkey = optparts[pindex]
  40. modkey = '_'.join(optparts)
  41. optparts[pindex] = '*'
  42. wildkey = '_'.join(optparts)
  43. kkey = f'{filekey}|{sectkey}|{wildkey}'
  44. if kkey not in gdict: gdict[kkey] = []
  45. gdict[kkey].append((subkey, modkey))
  46. # Build a list of potential groups. Only those with multiple items will be grouped.
  47. def group_options(schema):
  48. for pindex in range(10, -1, -1):
  49. found_groups = {}
  50. for filekey, f in schema.items():
  51. for sectkey, s in f.items():
  52. for optkey in s:
  53. find_grouping(found_groups, filekey, sectkey, optkey, pindex)
  54. fkeys = [ k for k in found_groups.keys() ]
  55. for kkey in fkeys:
  56. items = found_groups[kkey]
  57. if len(items) > 1:
  58. f, s, w = kkey.split('|')
  59. extend_dict(schema, (f, s, w)) # Add wildcard group to schema
  60. for subkey, optkey in items: # Add all items to wildcard group
  61. schema[f][s][w][subkey] = schema[f][s][optkey] # Move non-wildcard item to wildcard group
  62. del schema[f][s][optkey]
  63. del found_groups[kkey]
  64. # Extract all board names from boards.h
  65. def load_boards():
  66. bpath = Path("Marlin/src/core/boards.h")
  67. if bpath.is_file():
  68. with bpath.open() as bfile:
  69. boards = []
  70. for line in bfile:
  71. if line.startswith("#define BOARD_"):
  72. bname = line.split()[1]
  73. if bname != "BOARD_UNKNOWN": boards.append(bname)
  74. return "['" + "','".join(boards) + "']"
  75. return ''
  76. #
  77. # Extract the specified configuration files in the form of a structured schema.
  78. # Contains the full schema for the configuration files, not just the enabled options,
  79. # Contains the current values of the options, not just data structure, so "schema" is a slight misnomer.
  80. #
  81. # The returned object is a nested dictionary with the following indexing:
  82. #
  83. # - schema[filekey][section][define_name] = define_info
  84. #
  85. # Where the define_info contains the following keyed fields:
  86. # - section = The @section the define is in
  87. # - name = The name of the define
  88. # - enabled = True if the define is enabled (not commented out)
  89. # - line = The line number of the define
  90. # - sid = A serial ID for the define
  91. # - value = The value of the define, if it has one
  92. # - type = The type of the define, if it has one
  93. # - requires = The conditions that must be met for the define to be enabled
  94. # - comment = The comment for the define, if it has one
  95. # - units = The units for the define, if it has one
  96. # - options = The options for the define, if it has any
  97. #
  98. def extract_files(filekey):
  99. # Load board names from boards.h
  100. boards = load_boards()
  101. # Parsing states
  102. class Parse:
  103. NORMAL = 0 # No condition yet
  104. BLOCK_COMMENT = 1 # Looking for the end of the block comment
  105. EOL_COMMENT = 2 # EOL comment started, maybe add the next comment?
  106. SLASH_COMMENT = 3 # Block-like comment, starting with aligned //
  107. GET_SENSORS = 4 # Gathering temperature sensor options
  108. ERROR = 9 # Syntax error
  109. # A JSON object to store the data
  110. sch_out = { key:{} for key in filekey.values() }
  111. # Regex for #define NAME [VALUE] [COMMENT] with sanitized line
  112. defgrep = re.compile(r'^(//)?\s*(#define)\s+([A-Za-z0-9_]+)\s*(.*?)\s*(//.+)?$')
  113. # Pattern to match a float value
  114. flt = r'[-+]?\s*(\d+\.|\d*\.\d+)([eE][-+]?\d+)?[fF]?'
  115. # Defines to ignore
  116. ignore = ('CONFIGURATION_H_VERSION', 'CONFIGURATION_ADV_H_VERSION', 'CONFIG_EXAMPLES_DIR', 'CONFIG_EXPORT')
  117. # Start with unknown state
  118. state = Parse.NORMAL
  119. # Serial ID
  120. sid = 0
  121. # Loop through files and parse them line by line
  122. for fn, fk in filekey.items():
  123. with Path("Marlin", fn).open() as fileobj:
  124. section = 'none' # Current Settings section
  125. line_number = 0 # Counter for the line number of the file
  126. conditions = [] # Create a condition stack for the current file
  127. comment_buff = [] # A temporary buffer for comments
  128. prev_comment = '' # Copy before reset for an EOL comment
  129. options_json = '' # A buffer for the most recent options JSON found
  130. eol_options = False # The options came from end of line, so only apply once
  131. join_line = False # A flag that the line should be joined with the previous one
  132. line = '' # A line buffer to handle \ continuation
  133. last_added_ref = None # Reference to the last added item
  134. # Loop through the lines in the file
  135. for the_line in fileobj.readlines():
  136. line_number += 1
  137. # Clean the line for easier parsing
  138. the_line = the_line.strip()
  139. if join_line: # A previous line is being made longer
  140. line += (' ' if line else '') + the_line
  141. else: # Otherwise, start the line anew
  142. line, line_start = the_line, line_number
  143. # If the resulting line ends with a \, don't process now.
  144. # Strip the end off. The next line will be joined with it.
  145. join_line = line.endswith("\\")
  146. if join_line:
  147. line = line[:-1].strip()
  148. continue
  149. else:
  150. line_end = line_number
  151. defmatch = defgrep.match(line)
  152. # Special handling for EOL comments after a #define.
  153. # At this point the #define is already digested and inserted,
  154. # so we have to extend it
  155. if state == Parse.EOL_COMMENT:
  156. # If the line is not a comment, we're done with the EOL comment
  157. if not defmatch and the_line.startswith('//'):
  158. comment_buff.append(the_line[2:].strip())
  159. else:
  160. state = Parse.NORMAL
  161. cline = ' '.join(comment_buff)
  162. comment_buff = []
  163. if cline != '':
  164. # A (block or slash) comment was already added
  165. cfield = 'notes' if 'comment' in last_added_ref else 'comment'
  166. last_added_ref[cfield] = cline
  167. #
  168. # Add the given comment line to the comment buffer, unless:
  169. # - The line starts with ':' and JSON values to assign to 'opt'.
  170. # - The line starts with '@section' so a new section needs to be returned.
  171. # - The line starts with '======' so just skip it.
  172. #
  173. def use_comment(c, opt, sec, bufref):
  174. if c.startswith(':'): # If the comment starts with : then it has magic JSON
  175. d = c[1:].strip() # Strip the leading :
  176. cbr = c.rindex('}') if d.startswith('{') else c.rindex(']') if d.startswith('[') else 0
  177. if cbr:
  178. opt, cmt = c[1:cbr+1].strip(), c[cbr+1:].strip()
  179. if cmt != '': bufref.append(cmt)
  180. else:
  181. opt = c[1:].strip()
  182. elif c.startswith('@section'): # Start a new section
  183. sec = c[8:].strip()
  184. elif not c.startswith('========'):
  185. bufref.append(c)
  186. return opt, sec
  187. # For slash comments, capture consecutive slash comments.
  188. # The comment will be applied to the next #define.
  189. if state == Parse.SLASH_COMMENT:
  190. if not defmatch and the_line.startswith('//'):
  191. options_json, section = use_comment(the_line[2:].strip(), options_json, section, comment_buff)
  192. continue
  193. else:
  194. state = Parse.NORMAL
  195. # In a block comment, capture lines up to the end of the comment.
  196. # Assume nothing follows the comment closure.
  197. if state in (Parse.BLOCK_COMMENT, Parse.GET_SENSORS):
  198. endpos = line.find('*/')
  199. if endpos < 0:
  200. cline = line
  201. else:
  202. cline, line = line[:endpos].strip(), line[endpos+2:].strip()
  203. # Temperature sensors are done
  204. if state == Parse.GET_SENSORS:
  205. options_json = f'[ {options_json[:-2]} ]'
  206. state = Parse.NORMAL
  207. # Strip the leading '* ' from block comments
  208. cline = re.sub(r'^\* ?', '', cline)
  209. # Collect temperature sensors
  210. if state == Parse.GET_SENSORS:
  211. sens = re.match(r'^(-?\d+)\s*:\s*(.+)$', cline)
  212. if sens:
  213. s2 = sens[2].replace("'","''")
  214. options_json += f"{sens[1]}:'{sens[1]} - {s2}', "
  215. elif state == Parse.BLOCK_COMMENT:
  216. # Look for temperature sensors
  217. if re.match(r'temperature sensors.*:', cline, re.IGNORECASE):
  218. state, cline = Parse.GET_SENSORS, "Temperature Sensors"
  219. options_json, section = use_comment(cline, options_json, section, comment_buff)
  220. # For the normal state we're looking for any non-blank line
  221. elif state == Parse.NORMAL:
  222. # Skip a commented define when evaluating comment opening
  223. st = 2 if re.match(r'^//\s*#define', line) else 0
  224. cpos1 = line.find('/*') # Start a block comment on the line?
  225. cpos2 = line.find('//', st) # Start an end of line comment on the line?
  226. # Only the first comment starter gets evaluated
  227. cpos = -1
  228. if cpos1 != -1 and (cpos1 < cpos2 or cpos2 == -1):
  229. cpos = cpos1
  230. comment_buff = []
  231. state = Parse.BLOCK_COMMENT
  232. eol_options = False
  233. elif cpos2 != -1 and (cpos2 < cpos1 or cpos1 == -1):
  234. cpos = cpos2
  235. # Comment after a define may be continued on the following lines
  236. if defmatch != None and cpos > 10:
  237. state = Parse.EOL_COMMENT
  238. prev_comment = '\n'.join(comment_buff)
  239. comment_buff = []
  240. else:
  241. state = Parse.SLASH_COMMENT
  242. # Process the start of a new comment
  243. if cpos != -1:
  244. comment_buff = []
  245. cline, line = line[cpos+2:].strip(), line[:cpos].strip()
  246. if state == Parse.BLOCK_COMMENT:
  247. # Strip leading '*' from block comments
  248. cline = re.sub(r'^\* ?', '', cline)
  249. else:
  250. # Expire end-of-line options after first use
  251. if cline.startswith(':'): eol_options = True
  252. # Buffer a non-empty comment start
  253. if cline != '':
  254. options_json, section = use_comment(cline, options_json, section, comment_buff)
  255. # If the line has nothing before the comment, go to the next line
  256. if line == '':
  257. options_json = ''
  258. continue
  259. # Parenthesize the given expression if needed
  260. def atomize(s):
  261. if s == '' \
  262. or re.match(r'^[A-Za-z0-9_]*(\([^)]+\))?$', s) \
  263. or re.match(r'^[A-Za-z0-9_]+ == \d+?$', s):
  264. return s
  265. return f'({s})'
  266. #
  267. # The conditions stack is an array containing condition-arrays.
  268. # Each condition-array lists the conditions for the current block.
  269. # IF/N/DEF adds a new condition-array to the stack.
  270. # ELSE/ELIF/ENDIF pop the condition-array.
  271. # ELSE/ELIF negate the last item in the popped condition-array.
  272. # ELIF adds a new condition to the end of the array.
  273. # ELSE/ELIF re-push the condition-array.
  274. #
  275. cparts = line.split()
  276. iselif, iselse = cparts[0] == '#elif', cparts[0] == '#else'
  277. if iselif or iselse or cparts[0] == '#endif':
  278. if len(conditions) == 0:
  279. raise Exception(f'no #if block at line {line_number}')
  280. # Pop the last condition-array from the stack
  281. prev = conditions.pop()
  282. if iselif or iselse:
  283. prev[-1] = '!' + prev[-1] # Invert the last condition
  284. if iselif: prev.append(atomize(line[5:].strip()))
  285. conditions.append(prev)
  286. elif cparts[0] == '#if':
  287. conditions.append([ atomize(line[3:].strip()) ])
  288. elif cparts[0] == '#ifdef':
  289. conditions.append([ f'defined({line[6:].strip()})' ])
  290. elif cparts[0] == '#ifndef':
  291. conditions.append([ f'!defined({line[7:].strip()})' ])
  292. # Handle a complete #define line
  293. elif defmatch != None:
  294. # Get the match groups into vars
  295. enabled, define_name, val = defmatch[1] == None, defmatch[3], defmatch[4]
  296. # Increment the serial ID
  297. sid += 1
  298. # Create a new dictionary for the current #define
  299. define_info = {
  300. 'section': section,
  301. 'name': define_name,
  302. 'enabled': enabled,
  303. 'line': line_start,
  304. 'sid': sid
  305. }
  306. # Type is based on the value
  307. value_type = \
  308. 'switch' if val == '' \
  309. else 'bool' if re.match(r'^(true|false)$', val) \
  310. else 'int' if re.match(r'^[-+]?\s*\d+$', val) \
  311. else 'ints' if re.match(r'^([-+]?\s*\d+)(\s*,\s*[-+]?\s*\d+)+$', val) \
  312. else 'floats' if re.match(rf'({flt}(\s*,\s*{flt})+)', val) \
  313. else 'float' if re.match(f'^({flt})$', val) \
  314. else 'string' if val[0] == '"' \
  315. else 'char' if val[0] == "'" \
  316. else 'state' if re.match(r'^(LOW|HIGH)$', val) \
  317. else 'enum' if re.match(r'^[A-Za-z0-9_]{3,}$', val) \
  318. else 'int[]' if re.match(r'^{\s*[-+]?\s*\d+(\s*,\s*[-+]?\s*\d+)*\s*}$', val) \
  319. else 'float[]' if re.match(r'^{{\s*{flt}(\s*,\s*{flt})*\s*}}$', val) \
  320. else 'array' if val[0] == '{' \
  321. else ''
  322. val = (val == 'true') if value_type == 'bool' \
  323. else int(val) if value_type == 'int' \
  324. else val.replace('f','') if value_type == 'floats' \
  325. else float(val.replace('f','')) if value_type == 'float' \
  326. else val
  327. if val != '': define_info['value'] = val
  328. if value_type != '': define_info['type'] = value_type
  329. # Join up accumulated conditions with &&
  330. if conditions: define_info['requires'] = '(' + ') && ('.join(sum(conditions, [])) + ')'
  331. # If the comment_buff is not empty, add the comment to the info
  332. if comment_buff:
  333. full_comment = '\n'.join(comment_buff)
  334. # An EOL comment will be added later
  335. # The handling could go here instead of above
  336. if state == Parse.EOL_COMMENT:
  337. define_info['comment'] = ''
  338. else:
  339. define_info['comment'] = full_comment
  340. comment_buff = []
  341. # If the comment specifies units, add that to the info
  342. units = re.match(r'^\(([^)]+)\)', full_comment)
  343. if units:
  344. units = units[1]
  345. if units == 's' or units == 'sec': units = 'seconds'
  346. define_info['units'] = units
  347. # Set the options for the current #define
  348. if define_name == "MOTHERBOARD" and boards != '':
  349. define_info['options'] = boards
  350. elif options_json != '':
  351. define_info['options'] = options_json
  352. if eol_options: options_json = ''
  353. # Create section dict if it doesn't exist yet
  354. if section not in sch_out[fk]: sch_out[fk][section] = {}
  355. # If define has already been seen...
  356. if define_name in sch_out[fk][section]:
  357. info = sch_out[fk][section][define_name]
  358. if isinstance(info, dict): info = [ info ] # Convert a single dict into a list
  359. info.append(define_info) # Add to the list
  360. else:
  361. # Add the define dict with name as key
  362. sch_out[fk][section][define_name] = define_info
  363. if state == Parse.EOL_COMMENT:
  364. last_added_ref = define_info
  365. return sch_out
  366. #
  367. # Extract the current configuration files in the form of a structured schema.
  368. #
  369. def extract():
  370. # List of files to process, with shorthand
  371. return extract_files({ 'Configuration.h':'basic', 'Configuration_adv.h':'advanced' })
  372. def dump_json(schema:dict, jpath:Path):
  373. with jpath.open('w') as jfile:
  374. json.dump(schema, jfile, ensure_ascii=False, indent=2)
  375. def dump_yaml(schema:dict, ypath:Path):
  376. import yaml
  377. with ypath.open('w') as yfile:
  378. yaml.dump(schema, yfile, default_flow_style=False, width=120, indent=2)
  379. def main():
  380. try:
  381. schema = extract()
  382. except Exception as exc:
  383. print("Error: " + str(exc))
  384. schema = None
  385. if schema:
  386. # Get the command line arguments after the script name
  387. import sys
  388. args = sys.argv[1:]
  389. if len(args) == 0: args = ['some']
  390. # Does the given array intersect at all with args?
  391. def inargs(c): return len(set(args) & set(c)) > 0
  392. # Help / Unknown option
  393. unk = not inargs(['some','json','jsons','group','yml','yaml'])
  394. if (unk): print(f"Unknown option: '{args[0]}'")
  395. if inargs(['-h', '--help']) or unk:
  396. print("Usage: schema.py [some|json|jsons|group|yml|yaml]...")
  397. print(" some = json + yml")
  398. print(" jsons = json + group")
  399. return
  400. # JSON schema
  401. if inargs(['some', 'json', 'jsons']):
  402. print("Generating JSON ...")
  403. dump_json(schema, Path('schema.json'))
  404. # JSON schema (wildcard names)
  405. if inargs(['group', 'jsons']):
  406. group_options(schema)
  407. dump_json(schema, Path('schema_grouped.json'))
  408. # YAML
  409. if inargs(['some', 'yml', 'yaml']):
  410. try:
  411. import yaml
  412. except ImportError:
  413. print("Installing YAML module ...")
  414. import subprocess
  415. try:
  416. subprocess.run(['python3', '-m', 'pip', 'install', 'pyyaml'])
  417. import yaml
  418. except:
  419. print("Failed to install YAML module")
  420. return
  421. print("Generating YML ...")
  422. dump_yaml(schema, Path('schema.yml'))
  423. if __name__ == '__main__':
  424. main()