qmk-keychron-q3-colemak-dh/lib/python/qmk/c_parse.py

305 lines
10 KiB
Python
Raw Normal View History

"""Functions for working with config.h files.
"""
2022-05-15 23:39:29 +02:00
from pygments.lexers.c_cpp import CLexer
from pygments.token import Token
from pygments import lex
from itertools import islice
from pathlib import Path
2020-12-02 01:04:22 +01:00
import re
from milc import cli
from qmk.comment_remover import comment_remover
default_key_entry = {'x': -1, 'y': 0, 'w': 1}
2021 May 29 Breaking Changes Update (#13034) * Add Per Key functionality for AutoShift (#11536) * LED Matrix: Reactive effect buffers & advanced indicators (#12588) * [Keyboard] kint36: switch to sym_eager_pk debouncing (#12626) * [Keyboard] kint2pp: reduce input latency by ≈10ms (#12625) * LED Matrix: Split (#12633) * [CI] Format code according to conventions (#12650) * feat: infinite timeout for leader key (#6580) * feat: implement leader_no_timeout logic * docs(leader_key): infinite leader timeout docs * Format code according to conventions (#12680) * Update ADC driver for STM32F1xx, STM32F3xx, STM32F4xx (#12403) * Fix default ADC_RESOLUTION for ADCv3 (and ADCv4) Recent ChibiOS update removed ADC_CFGR1_RES_10BIT from the ADCv3 headers (that macro should not have been there, because ADCv3 has CFGR instead of CFGR1). Fix the default value for ADC_RESOLUTION to use ADC_CFGR_RES_10BITS if it is defined (that name is used for ADCv3 and ADCv4). * Update ADC docs to match the actually used resolution ADC driver for ChibiOS actually uses the 10-bit resolution by default (probably to match AVR); fix the documentation accordingly. Also add both ADC_CFGR_RES_10BITS and ADC_CFGR1_RES_10BIT constants (these names differ according to the ADC implementation in the particular MCU). * Fix pinToMux() for B12 and B13 on STM32F3xx Testing on STM32F303CCT6 revealed that the ADC mux values for B12 and B13 pins were wrong. * Add support for all possible analog pins on STM32F1xx Added ADC mux values for pins A0...A7, B0, B1, C0...C5 on STM32F1xx (they are the same at least for STM32F103x8 and larger F103 devices, and also F102, F105, F107 families). Actually tested on STM32F103C8T6 (therefore pins C0...C5 were not tested). Pins F6...F10, which are present on STM32F103x[C-G] in 144-pin packages, cannot be supported at the moment, because those pins are connected only to ADC3, but the ChibiOS ADC driver for STM32F1xx supports only ADC1. * Add support for all possible analog pins on STM32F4xx Added ADC mux values for pins A0...A7, B0, B1, C0...C5 and optionally F3...F10 (if STM32_ADC_USE_ADC3 is enabled). These mux values are apparently the same for all F4xx devices, except some smaller devices may not have ADC3. Actually tested on STM32F401CCU6, STM32F401CEU6, STM32F411CEU6 (using various WeAct “Blackpill” boards); only pins A0...A7, B0, B1 were tested. Pins F3...F10 are inside `#if STM32_ADC_USE_ADC3` because some devices which don't have ADC3 also don't have the GPIOF port, therefore the code which refers to Fx pins does not compile. * Fix STM32F3xx ADC mux table in documentation The ADC driver documentation had some errors in the mux table for STM32F3xx. Fix this table to match the datasheet and the actual code (mux settings for B12 and B13 were also tested on a real STM32F303CCT6 chip). * Add STM32F1xx ADC pins to the documentation * Add STM32F4xx ADC pins to the documentation * Add initial support for tinyuf2 bootloader (when hosted on F411 blackpill) (#12600) * Add support for jumping to tinyuf2 bootloader. Adds blackpill UF2 example. * Update flashing.md * Update chconf.h * Update config.h * Update halconf.h * Update mcuconf.h * eeprom driver: Refactor where eeprom driver initialisation (and EEPROM emulation initialisation) occurs to make it non-target-specific. (#12671) * Add support for MCU = STM32F446 (#12619) * Add support for MCU = STM32F446 * Update platforms/chibios/GENERIC_STM32_F446XE/configs/config.h * Restore mcuconf.h to the one used by RT-STM32F446RE-NUCLEO64 * stm32f446: update mcuconf.h and board.h for 16MHz operation, with USB enabled, and other peripherals disabled. * Format code according to conventions (#12682) * Format code according to conventions (#12687) * Add STM32L433 and L443 support (#12063) * initial L433 commit * change to XC * fix L433 * disable all peripherals * update system and peripheral clocks * 433 change * use its own board files * revert its own board files * l433 specific change * fix stm32l432xx define * remove duplicate #define * fix bootloader jump * move to L443xx and add i2c2, spi2, usart3 to mcuconf.h * move to L443 * move to L443 * fix sdmmc in mcuconf.h * include STM32L443 * add L443 * Include L443 in compatible microcontrollers * Include L443 in compatible microcontrollers * Update config bootloader jump description * Update ChibiOS define reasoning * Update quantum/mcu_selection.mk * fix git conflict * Updated Function96 with V2 files and removed chconf.h and halconf.h (#12613) * Fix bad PR merge for #6580. (#12721) * Change RGB/LED Matrix to use a simple define for USB suspend (#12697) * [CI] Format code according to conventions (#12731) * Fixing transport's led/rgb matrix suspend state logic (#12770) * [CI] Format code according to conventions (#12772) * Fix comment parsing (#12750) * Added OLED fade out support (#12086) * fix some references to bin/qmk that slipped in (#12832) * Resolve a number of warnings in `qmk generate-api` (#12833) * New command: qmk console (#12828) * stash poc * stash * tidy up implementation * Tidy up slightly for review * Tidy up slightly for review * Bodge environment to make tests pass * Refactor away from asyncio due to windows issues * Filter devices * align vid/pid printing * Add hidapi to the installers * start preparing for multiple hid_listeners * udev rules for hid_listen * refactor to move closer to end state * very basic implementation of the threaded model * refactor how vid/pid/index are supplied and parsed * windows improvements * read the report directly when usage page isn't available * add per-device colors, the choice to show names or numbers, and refactor * add timestamps * Add support for showing bootloaders * tweak the color for bootloaders * Align bootloader disconnect with connect color * add support for showing all bootloaders * fix the pyusb check * tweaks * fix exception * hide a stack trace behind -v * add --no-bootloaders option * add documentation for qmk console * Apply suggestions from code review * pyformat * clean up and flesh out KNOWN_BOOTLOADERS * Remove pointless SERIAL_LINK_ENABLE rules (#12846) * Make Swap Hands use PROGMEM (#12284) This converts the array that the Swap Hands feature uses to use PROGMEM, and to read from that array, as such. Since this array never changes at runtime, there is no reason to keep it in memory. Especially for AVR boards, as memory is a precious resource. * Fix another bin/qmk reference (#12856) * [Keymap] Turn OLED off on suspend in soundmonster keymap (#10419) * Fixup build errors on `develop` branch. (#12723) * LED Matrix: Effects! (#12651) * Fix syntax error when compiling for ARM (#12866) * Remove KEYMAP and LAYOUT_kc (#12160) * alias KEYMAP to LAYOUT * remove KEYMAP and LAYOUT_kc * Add setup, clone, and env to the list of commands we allow even with broken modules (#12868) * Rename `point_t` -> `led_point_t` (#12864) * [Keyboard] updated a vendor name / fixed minor keymap issues (#12881) * Add missing LED Matrix suspend code to suspend.c (#12878) * LED Matrix: Documentation (#12685) * Deprecate `send_unicode_hex_string()` (#12602) * Fix spelling mistake regarding LED Matrix in split_common. (#12888) * [Keymap] Fix QWERTY/DVORAK status output for kzar keymap (#12895) * Use milc.subcommand.config instead of qmk.cli.config (#12915) * Use milc.subcommand.config instead * pyformat * remove the config test * Add function to allow repeated blinking of one layer (#12237) * Implement function rgblight_blink_layer_repeat to allow repeated blinking of one layer at a time * Update doc * Rework rgblight blinking according to requested change * optimize storage * Fixup housekeeping from being invoked twice per loop. (#12933) * matrix: wait for row signal to go HIGH for every row (#12945) I noticed this discrepancy (last row of the matrix treated differently than the others) when optimizing the input latency of my keyboard controller, see also https://michael.stapelberg.ch/posts/2021-05-08-keyboard-input-latency-qmk-kinesis/ Before this commit, when tuning the delays I noticed ghost key presses when pressing the F2 key, which is on the last row of the keyboard matrix: the dead_grave key, which is on the first row of the keyboard matrix, would be incorrectly detected as pressed. After this commit, all keyboard matrix rows are interpreted correctly. I suspect that my setup is more susceptible to this nuance than others because I use GPIO_INPUT_PIN_DELAY=0 and hence don’t have another delay that might mask the problem. * ensure we do not conflict with existing keymap aliases (#12976) * Add support for up to 4 IS31FL3733 drivers (#12342) * Convert Encoder callbacks to be boolean functions (#12805) * [Keyboard] Fix Terrazzo build failure (#12977) * Do not hard set config in CPTC files (#11864) * [Keyboard] Corne - Remove legacy revision support (#12226) * [Keymap] Update to Drashna keymap and user code (based on develop) (#12936) * Add Full-duplex serial driver for ARM boards (#9842) * Document LED_MATRIX_FRAMEBUFFER_EFFECTS (#12987) * Backlight: add defines for default level and breathing state (#12560) * Add dire message about LUFA mass storage bootloader (#13014) * [Keyboard] Remove redundant legacy and common headers for crkbd (#13023) Was causing compiler errors on some systems. * Fix keyboards/keymaps for boolean encoder callback changes (#12985) * `backlight.c`: include `eeprom.h` (#13024) * Add changelog for 2021-05-29 Breaking Changes merge (#12939) * Add ChangeLog for 2021-05-29 Breaking Changes Merge: initial version * Add recent develop changes * Sort recent develop changes * Remove sections for ChibiOS changes per tzarc No ChibiOS changes this round. * Add and sort recent develop changes * add notes about keyboard moves/deletions * import changelog for PR 12172 Documents the change to BOOTMAGIC_ENABLE. * update section headings * re-sort changelog * add additional note regarding Bootmagic changes * remove changelog timestamp * update dates in main Breaking Changes docs * fix broken section anchors in previous changelogs * add link to backlight/eeprom patch to changelog * highlight some more changes * link PRs from section headers * Restore standard readme * run: qmk cformat --core-only
2021-05-29 23:38:50 +02:00
single_comment_regex = re.compile(r'\s+/[/*].*$')
2021-01-08 09:00:15 +01:00
multi_comment_regex = re.compile(r'/\*(.|\n)*?\*/', re.MULTILINE)
layout_macro_define_regex = re.compile(r'^#\s*define')
2020-12-02 01:04:22 +01:00
2022-05-15 23:39:29 +02:00
def _get_chunks(it, size):
"""Break down a collection into smaller parts
"""
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
def _preprocess_c_file(file):
"""Load file and strip comments
"""
file_contents = file.read_text(encoding='utf-8')
file_contents = comment_remover(file_contents)
return file_contents.replace('\\\n', '')
2020-12-02 01:04:22 +01:00
def strip_line_comment(string):
"""Removes comments from a single line string.
"""
return single_comment_regex.sub('', string)
def strip_multiline_comment(string):
"""Removes comments from a single line string.
"""
return multi_comment_regex.sub('', string)
def c_source_files(dir_names):
"""Returns a list of all *.c, *.h, and *.cpp files for a given list of directories
Args:
dir_names
List of directories relative to `qmk_firmware`.
"""
files = []
for dir in dir_names:
files.extend(file for file in Path(dir).glob('**/*') if file.suffix in ['.c', '.h', '.cpp'])
return files
def find_layouts(file):
"""Returns list of parsed LAYOUT preprocessor macros found in the supplied include file.
"""
file = Path(file)
aliases = {} # Populated with all `#define`s that aren't functions
parsed_layouts = {}
# Search the file for LAYOUT macros and aliases
file_contents = _preprocess_c_file(file)
for line in file_contents.split('\n'):
if layout_macro_define_regex.match(line.lstrip()) and '(' in line and 'LAYOUT' in line:
# We've found a LAYOUT macro
macro_name, layout, matrix = _parse_layout_macro(line.strip())
# Reject bad macro names
if macro_name.startswith('LAYOUT_kc') or not macro_name.startswith('LAYOUT'):
continue
# Parse the matrix data
matrix_locations = _parse_matrix_locations(matrix, file, macro_name)
# Parse the layout entries into a basic structure
default_key_entry['x'] = -1 # Set to -1 so _default_key(key) will increment it to 0
layout = layout.strip()
parsed_layout = [_default_key(key) for key in layout.split(',')]
2021-02-24 19:35:08 +01:00
for i, key in enumerate(parsed_layout):
if 'label' not in key:
cli.log.error('Invalid LAYOUT macro in %s: Empty parameter name in macro %s at pos %s.', file, macro_name, i)
elif key['label'] in matrix_locations:
2020-12-02 01:04:22 +01:00
key['matrix'] = matrix_locations[key['label']]
parsed_layouts[macro_name] = {
'layout': parsed_layout,
'filename': str(file),
}
elif '#define' in line:
# Attempt to extract a new layout alias
try:
_, pp_macro_name, pp_macro_text = line.strip().split(' ', 2)
aliases[pp_macro_name] = pp_macro_text
except ValueError:
continue
return parsed_layouts, aliases
def parse_config_h_file(config_h_file, config_h=None):
"""Extract defines from a config.h file.
"""
if not config_h:
config_h = {}
config_h_file = Path(config_h_file)
if config_h_file.exists():
config_h_text = config_h_file.read_text(encoding='utf-8')
2021-01-08 09:21:51 +01:00
config_h_text = config_h_text.replace('\\\n', '')
2020-12-02 01:04:22 +01:00
config_h_text = strip_multiline_comment(config_h_text)
for linenum, line in enumerate(config_h_text.split('\n')):
2020-12-02 01:04:22 +01:00
line = strip_line_comment(line).strip()
if not line:
continue
line = line.split()
if line[0] == '#define':
if len(line) == 1:
cli.log.error('%s: Incomplete #define! On or around line %s' % (config_h_file, linenum))
elif len(line) == 2:
config_h[line[1]] = True
else:
config_h[line[1]] = ' '.join(line[2:])
elif line[0] == '#undef':
if len(line) == 2:
if line[1] in config_h:
if config_h[line[1]] is True:
del config_h[line[1]]
else:
config_h[line[1]] = False
else:
cli.log.error('%s: Incomplete #undef! On or around line %s' % (config_h_file, linenum))
return config_h
def _default_key(label=None):
"""Increment x and return a copy of the default_key_entry.
"""
default_key_entry['x'] += 1
new_key = default_key_entry.copy()
if label:
new_key['label'] = label
return new_key
def _parse_layout_macro(layout_macro):
"""Split the LAYOUT macro into its constituent parts
"""
layout_macro = layout_macro.replace('\\', '').replace(' ', '').replace('\t', '').replace('#define', '')
macro_name, layout = layout_macro.split('(', 1)
layout, matrix = layout.split(')', 1)
return macro_name, layout, matrix
def _parse_matrix_locations(matrix, file, macro_name):
"""Parse raw matrix data into a dictionary keyed by the LAYOUT identifier.
"""
matrix_locations = {}
for row_num, row in enumerate(matrix.split('},{')):
if row.startswith('LAYOUT'):
cli.log.error('%s: %s: Nested layout macro detected. Matrix data not available!', file, macro_name)
break
row = row.replace('{', '').replace('}', '')
for col_num, identifier in enumerate(row.split(',')):
if identifier != 'KC_NO':
2020-12-02 01:04:22 +01:00
matrix_locations[identifier] = [row_num, col_num]
return matrix_locations
2022-05-15 23:39:29 +02:00
def _coerce_led_token(_type, value):
""" Convert token to valid info.json content
"""
value_map = {
'NO_LED': None,
'LED_FLAG_ALL': 0xFF,
'LED_FLAG_NONE': 0x00,
'LED_FLAG_MODIFIER': 0x01,
'LED_FLAG_UNDERGLOW': 0x02,
'LED_FLAG_KEYLIGHT': 0x04,
'LED_FLAG_INDICATOR': 0x08,
}
if _type is Token.Literal.Number.Integer:
return int(value)
if _type is Token.Literal.Number.Float:
return float(value)
if _type is Token.Literal.Number.Hex:
return int(value, 0)
if _type is Token.Name and value in value_map.keys():
return value_map[value]
def _validate_led_config(matrix, matrix_rows, matrix_indexes, position, position_raw, flags):
# TODO: Improve crude parsing/validation
if len(matrix) != matrix_rows and len(matrix) != (matrix_rows / 2):
raise ValueError("Unable to parse g_led_config matrix data")
if len(position) != len(flags):
raise ValueError(f"Number of g_led_config physical positions ({len(position)}) does not match number of flags ({len(flags)})")
if len(matrix_indexes) and (max(matrix_indexes) >= len(flags)):
raise ValueError(f"LED index {max(matrix_indexes)} is OOB in g_led_config - should be < {len(flags)}")
if not all(isinstance(n, int) for n in matrix_indexes):
raise ValueError("matrix indexes are not all ints")
if (len(position_raw) % 2) != 0:
raise ValueError("Malformed g_led_config position data")
2022-05-15 23:39:29 +02:00
def _parse_led_config(file, matrix_cols, matrix_rows):
"""Return any 'raw' led/rgb matrix config
"""
matrix_raw = []
position_raw = []
flags = []
found_led_config = False
bracket_count = 0
section = 0
for _type, value in lex(_preprocess_c_file(file), CLexer()):
2022-05-15 23:39:29 +02:00
# Assume g_led_config..stuff..;
if value == 'g_led_config':
found_led_config = True
elif value == ';':
found_led_config = False
elif found_led_config:
# Assume bracket count hints to section of config we are within
if value == '{':
bracket_count += 1
if bracket_count == 2:
section += 1
elif value == '}':
bracket_count -= 1
else:
# Assume any non whitespace value here is important enough to stash
if _type in [Token.Literal.Number.Integer, Token.Literal.Number.Float, Token.Literal.Number.Hex, Token.Name]:
if section == 1 and bracket_count == 3:
matrix_raw.append(_coerce_led_token(_type, value))
if section == 2 and bracket_count == 3:
position_raw.append(_coerce_led_token(_type, value))
if section == 3 and bracket_count == 2:
flags.append(_coerce_led_token(_type, value))
elif _type in [Token.Comment.Preproc]:
# TODO: Promote to error
return None
2022-05-15 23:39:29 +02:00
# Slightly better intrim format
matrix = list(_get_chunks(matrix_raw, matrix_cols))
position = list(_get_chunks(position_raw, 2))
matrix_indexes = list(filter(lambda x: x is not None, matrix_raw))
# If we have not found anything - bail with no error
2022-05-15 23:39:29 +02:00
if not section:
return None
# Throw any validation errors
_validate_led_config(matrix, matrix_rows, matrix_indexes, position, position_raw, flags)
2022-05-15 23:39:29 +02:00
return (matrix, position, flags)
def find_led_config(file, matrix_cols, matrix_rows):
"""Search file for led/rgb matrix config
"""
found = _parse_led_config(file, matrix_cols, matrix_rows)
if not found:
return None
# Expand collected content
(matrix, position, flags) = found
# Align to output format
led_config = []
for index, item in enumerate(position, start=0):
led_config.append({
'x': item[0],
'y': item[1],
'flags': flags[index],
})
for r in range(len(matrix)):
for c in range(len(matrix[r])):
index = matrix[r][c]
if index is not None:
led_config[index]['matrix'] = [r, c]
return led_config