compilation_database.py 5.2 KB

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