logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

compilation_database.py (5661B)


  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', '-std=gnu11'])
  36. elif binary.endswith("g++"):
  37. invocation.extend(['-x', 'c++', '-std=gnu++14'])
  38. invocation.extend(shlex.split(compiler_args))
  39. invocation.append('-')
  40. result = cli.run(invocation, capture_output=True, check=True, stdin=None, input='\n')
  41. define_args = []
  42. for line in result.stdout.splitlines():
  43. line_args = line.split(' ', 2)
  44. if len(line_args) == 3 and line_args[0] == '#define':
  45. define_args.append(f'-D{line_args[1]}={line_args[2]}')
  46. elif len(line_args) == 2 and line_args[0] == '#define':
  47. define_args.append(f'-D{line_args[1]}')
  48. type_filter = re.compile(
  49. r'^-D__(SIZE|INT|UINT|WINT|WCHAR|BYTE|SHRT|SIG|FLOAT|LONG|CHAR|SCHAR|DBL|FLT|LDBL|PTRDIFF|QQ|DQ|DA|HA|HQ|SA|SQ|TA|TQ|UDA|UDQ|UHA|UHQ|USQ|USA|UTQ|UTA|UQQ|UQA|ACCUM|FRACT|UACCUM|UFRACT|LACCUM|LFRACT|ULACCUM|ULFRACT|LLACCUM|LLFRACT|ULLACCUM|ULLFRACT|SACCUM|SFRACT|USACCUM|USFRACT)'
  50. )
  51. return list(sorted(set(filter(lambda x: not type_filter.match(x), define_args))))
  52. return []
  53. file_re = re.compile(r'printf "Compiling: ([^"]+)')
  54. cmd_re = re.compile(r'LOG=\$\((.+?)&&')
  55. def parse_make_n(f: Iterator[str]) -> List[Dict[str, str]]:
  56. """parse the output of `make -n <target>`
  57. This function makes many assumptions about the format of your build log.
  58. This happens to work right now for qmk.
  59. """
  60. state = 'start'
  61. this_file = None
  62. records = []
  63. for line in f:
  64. if state == 'start':
  65. m = file_re.search(line)
  66. if m:
  67. this_file = m.group(1)
  68. state = 'cmd'
  69. if state == 'cmd':
  70. assert this_file
  71. m = cmd_re.search(line)
  72. if m:
  73. # we have a hit!
  74. this_cmd = m.group(1)
  75. args = shlex.split(this_cmd)
  76. binary = shutil.which(args[0])
  77. compiler_args = set(filter(lambda x: x.startswith('-m') or x.startswith('-f'), args))
  78. for s in system_libs(binary):
  79. args += ['-isystem', '%s' % s]
  80. args.extend(cpu_defines(binary, ' '.join(shlex.quote(s) for s in compiler_args)))
  81. args[0] = binary
  82. records.append({"arguments": args, "directory": str(QMK_FIRMWARE.resolve()), "file": this_file})
  83. state = 'start'
  84. return records
  85. 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:
  86. # Generate the make command for a specific keyboard/keymap.
  87. if not command:
  88. from qmk.build_targets import KeyboardKeymapBuildTarget # Lazy load due to circular references
  89. target = KeyboardKeymapBuildTarget(keyboard, keymap)
  90. command = target.compile_command(dry_run=True, **env_vars)
  91. if not command:
  92. cli.log.error('You must supply both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
  93. cli.echo('usage: qmk generate-compilation-database [-kb KEYBOARD] [-km KEYMAP]')
  94. return False
  95. # remove any environment variable overrides which could trip us up
  96. env = os.environ.copy()
  97. env.pop("MAKEFLAGS", None)
  98. # re-use same executable as the main make invocation (might be gmake)
  99. if not skip_clean:
  100. clean_command = [find_make(), "clean"]
  101. cli.log.info('Making clean with {fg_cyan}%s', ' '.join(clean_command))
  102. cli.run(clean_command, capture_output=False, check=True, env=env)
  103. cli.log.info('Gathering build instructions from {fg_cyan}%s', ' '.join(command))
  104. result = cli.run(command, capture_output=True, check=True, env=env)
  105. db = parse_make_n(result.stdout.splitlines())
  106. if not db:
  107. cli.log.error("Failed to parse output from make output:\n%s", result.stdout)
  108. return False
  109. cli.log.info("Found %s compile commands", len(db))
  110. cli.log.info(f"Writing build database to {output_path}")
  111. output_path.write_text(json.dumps(db, indent=4))
  112. return True