1
0

compilation_database.py 6.8 KB

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