diff options
Diffstat (limited to 'lib/python/qmk/compilation_database.py')
| -rwxr-xr-x | lib/python/qmk/compilation_database.py | 137 |
1 files changed, 137 insertions, 0 deletions
diff --git a/lib/python/qmk/compilation_database.py b/lib/python/qmk/compilation_database.py new file mode 100755 index 0000000000..4c88dadbdd --- /dev/null +++ b/lib/python/qmk/compilation_database.py | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | """Creates a compilation database for the given keyboard build. | ||
| 2 | """ | ||
| 3 | |||
| 4 | import json | ||
| 5 | import os | ||
| 6 | import re | ||
| 7 | import shlex | ||
| 8 | import shutil | ||
| 9 | from functools import lru_cache | ||
| 10 | from pathlib import Path | ||
| 11 | from typing import Dict, Iterator, List | ||
| 12 | |||
| 13 | from milc import cli | ||
| 14 | |||
| 15 | from qmk.commands import find_make | ||
| 16 | from qmk.constants import QMK_FIRMWARE | ||
| 17 | |||
| 18 | |||
| 19 | @lru_cache(maxsize=10) | ||
| 20 | def system_libs(binary: str) -> List[Path]: | ||
| 21 | """Find the system include directory that the given build tool uses. | ||
| 22 | """ | ||
| 23 | cli.log.debug("searching for system library directory for binary: %s", binary) | ||
| 24 | |||
| 25 | # Actually query xxxxxx-gcc to find its include paths. | ||
| 26 | if binary.endswith("gcc") or binary.endswith("g++"): | ||
| 27 | # (TODO): Remove 'stdin' once 'input' no longer causes issues under MSYS | ||
| 28 | result = cli.run([binary, '-E', '-Wp,-v', '-'], capture_output=True, check=True, stdin=None, input='\n') | ||
| 29 | paths = [] | ||
| 30 | for line in result.stderr.splitlines(): | ||
| 31 | if line.startswith(" "): | ||
| 32 | paths.append(Path(line.strip()).resolve()) | ||
| 33 | return paths | ||
| 34 | |||
| 35 | return list(Path(binary).resolve().parent.parent.glob("*/include")) if binary else [] | ||
| 36 | |||
| 37 | |||
| 38 | @lru_cache(maxsize=10) | ||
| 39 | def cpu_defines(binary: str, compiler_args: str) -> List[str]: | ||
| 40 | cli.log.debug("gathering definitions for compilation: %s %s", binary, compiler_args) | ||
| 41 | if binary.endswith("gcc") or binary.endswith("g++"): | ||
| 42 | invocation = [binary, '-dM', '-E'] | ||
| 43 | if binary.endswith("gcc"): | ||
| 44 | invocation.extend(['-x', 'c']) | ||
| 45 | elif binary.endswith("g++"): | ||
| 46 | invocation.extend(['-x', 'c++']) | ||
| 47 | compiler_args = shlex.split(compiler_args) | ||
| 48 | invocation.extend(compiler_args) | ||
| 49 | invocation.append('-') | ||
| 50 | result = cli.run(invocation, capture_output=True, check=True, stdin=None, input='\n') | ||
| 51 | define_args = [] | ||
| 52 | for line in result.stdout.splitlines(): | ||
| 53 | line_args = line.split(' ', 2) | ||
| 54 | if len(line_args) == 3 and line_args[0] == '#define': | ||
| 55 | define_args.append(f'-D{line_args[1]}={line_args[2]}') | ||
| 56 | elif len(line_args) == 2 and line_args[0] == '#define': | ||
| 57 | define_args.append(f'-D{line_args[1]}') | ||
| 58 | return list(sorted(set(define_args))) | ||
| 59 | return [] | ||
| 60 | |||
| 61 | |||
| 62 | file_re = re.compile(r'printf "Compiling: ([^"]+)') | ||
| 63 | cmd_re = re.compile(r'LOG=\$\((.+?)&&') | ||
| 64 | |||
| 65 | |||
| 66 | def parse_make_n(f: Iterator[str]) -> List[Dict[str, str]]: | ||
| 67 | """parse the output of `make -n <target>` | ||
| 68 | |||
| 69 | This function makes many assumptions about the format of your build log. | ||
| 70 | This happens to work right now for qmk. | ||
| 71 | """ | ||
| 72 | |||
| 73 | state = 'start' | ||
| 74 | this_file = None | ||
| 75 | records = [] | ||
| 76 | for line in f: | ||
| 77 | if state == 'start': | ||
| 78 | m = file_re.search(line) | ||
| 79 | if m: | ||
| 80 | this_file = m.group(1) | ||
| 81 | state = 'cmd' | ||
| 82 | |||
| 83 | if state == 'cmd': | ||
| 84 | assert this_file | ||
| 85 | m = cmd_re.search(line) | ||
| 86 | if m: | ||
| 87 | # we have a hit! | ||
| 88 | this_cmd = m.group(1) | ||
| 89 | args = shlex.split(this_cmd) | ||
| 90 | binary = shutil.which(args[0]) | ||
| 91 | compiler_args = set(filter(lambda x: x.startswith('-m') or x.startswith('-f'), args)) | ||
| 92 | for s in system_libs(binary): | ||
| 93 | args += ['-isystem', '%s' % s] | ||
| 94 | args.extend(cpu_defines(binary, ' '.join(shlex.quote(s) for s in compiler_args))) | ||
| 95 | new_cmd = ' '.join(shlex.quote(s) for s in args) | ||
| 96 | records.append({"directory": str(QMK_FIRMWARE.resolve()), "command": new_cmd, "file": this_file}) | ||
| 97 | state = 'start' | ||
| 98 | |||
| 99 | return records | ||
| 100 | |||
| 101 | |||
| 102 | def write_compilation_database(keyboard: str = None, keymap: str = None, output_path: Path = QMK_FIRMWARE / 'compile_commands.json', skip_clean: bool = False, command: List[str] = None, **env_vars) -> bool: | ||
| 103 | # Generate the make command for a specific keyboard/keymap. | ||
| 104 | if not command: | ||
| 105 | from qmk.build_targets import KeyboardKeymapBuildTarget # Lazy load due to circular references | ||
| 106 | target = KeyboardKeymapBuildTarget(keyboard, keymap) | ||
| 107 | command = target.compile_command(dry_run=True, **env_vars) | ||
| 108 | |||
| 109 | if not command: | ||
| 110 | cli.log.error('You must supply both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.') | ||
| 111 | cli.echo('usage: qmk generate-compilation-database [-kb KEYBOARD] [-km KEYMAP]') | ||
| 112 | return False | ||
| 113 | |||
| 114 | # remove any environment variable overrides which could trip us up | ||
| 115 | env = os.environ.copy() | ||
| 116 | env.pop("MAKEFLAGS", None) | ||
| 117 | |||
| 118 | # re-use same executable as the main make invocation (might be gmake) | ||
| 119 | if not skip_clean: | ||
| 120 | clean_command = [find_make(), "clean"] | ||
| 121 | cli.log.info('Making clean with {fg_cyan}%s', ' '.join(clean_command)) | ||
| 122 | cli.run(clean_command, capture_output=False, check=True, env=env) | ||
| 123 | |||
| 124 | cli.log.info('Gathering build instructions from {fg_cyan}%s', ' '.join(command)) | ||
| 125 | |||
| 126 | result = cli.run(command, capture_output=True, check=True, env=env) | ||
| 127 | db = parse_make_n(result.stdout.splitlines()) | ||
| 128 | if not db: | ||
| 129 | cli.log.error("Failed to parse output from make output:\n%s", result.stdout) | ||
| 130 | return False | ||
| 131 | |||
| 132 | cli.log.info("Found %s compile commands", len(db)) | ||
| 133 | |||
| 134 | cli.log.info(f"Writing build database to {output_path}") | ||
| 135 | output_path.write_text(json.dumps(db, indent=4)) | ||
| 136 | |||
| 137 | return True | ||
