| 1 | #!/usr/bin/env python3 |
| 2 | # |
| 3 | # SPDX-FileCopyrightText: Copyright 2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 4 | # |
| 5 | # SPDX-License-Identifier: Apache-2.0 |
| 6 | # |
| 7 | """ |
| 8 | Verifies that every header file under kai/ can be included on its own. |
| 9 | |
| 10 | This script does this by collecting all headers under the kai/ directory and |
| 11 | for each header, generates a temporary .c/.cpp file that includes the header |
| 12 | and compiles the source file with the flag -fsyntax-only. It does this with |
| 13 | -std=c99 and -std=c++17. |
| 14 | |
| 15 | If any headers fail, the script prints the failing headers, language mode, |
| 16 | compiler command and compiler stderr. The script then exits by returning 1. |
| 17 | |
| 18 | If all headers pass, the script prints the number of checked headers and exits |
| 19 | by returning 0. |
| 20 | """ |
| 21 | from __future__ import annotations |
| 22 | |
| 23 | import argparse |
| 24 | import os |
| 25 | import shutil |
| 26 | import subprocess |
| 27 | import sys |
| 28 | import tempfile |
| 29 | from dataclasses import dataclass |
| 30 | from enum import Enum |
| 31 | from typing import Optional |
| 32 | from typing import Sequence |
| 33 | |
| 34 | import utils.git as git_utils |
| 35 | |
| 36 | HEADER_EXTS = {".h"} |
| 37 | |
| 38 | |
| 39 | class Language(Enum): |
| 40 | C = "c" |
| 41 | CPP = "c++" |
| 42 | |
| 43 | def suffix(self) -> str: |
| 44 | return {Language.C: ".c", Language.CPP: ".cpp"}[self] |
| 45 | |
| 46 | def standard(self) -> str: |
| 47 | return {Language.C: "c99", Language.CPP: "c++17"}[self] |
| 48 | |
| 49 | |
| 50 | LANGUAGES = [Language.C, Language.CPP] |
| 51 | |
| 52 | |
| 53 | @dataclass(frozen=True) |
| 54 | class CheckFailure: |
| 55 | header: str |
| 56 | language: str |
| 57 | command: Sequence[str] |
| 58 | stderr: str |
| 59 | |
| 60 | |
| 61 | def default_target() -> str: |
| 62 | if sys.platform == "darwin": |
| 63 | return "arm64-apple-darwin" |
| 64 | return "aarch64-linux-gnu" |
| 65 | |
| 66 | |
| 67 | def resolve_compiler(name: Optional[str]) -> str: |
| 68 | """Returns the full path of the compiler binary. If no compiler is |
| 69 | specified as argument to this function, it attempts to read the |
| 70 | environment variable CC. If that also fails, the function falls |
| 71 | back to assuming clang.""" |
| 72 | compiler = name or os.environ.get("CC") or "clang" |
| 73 | path = shutil.which(compiler) |
| 74 | assert path, f"Compiler not found: {compiler}" |
| 75 | return path |
| 76 | |
| 77 | |
| 78 | def iter_headers(kai_dir: str) -> list[str]: |
| 79 | headers: list[str] = [] |
| 80 | for dirpath, _, filenames in os.walk(kai_dir): |
| 81 | for filename in filenames: |
| 82 | _, ext = os.path.splitext(filename) |
| 83 | if ext in HEADER_EXTS: |
| 84 | headers.append(os.path.join(dirpath, filename)) |
| 85 | return sorted(headers) |
| 86 | |
| 87 | |
| 88 | def check_header( |
| 89 | compiler: str, |
| 90 | repo_dir: str, |
| 91 | header: str, |
| 92 | language: Language, |
| 93 | target: Optional[str], |
| 94 | verbose: bool, |
| 95 | ) -> Optional[CheckFailure]: |
| 96 | """Verifies that header can be included standalone by a c/cpp file. |
| 97 | This is done by creating a temporary c/cpp file that just includes |
| 98 | the header file and then compiled by the specified compiler using |
| 99 | the -fsyntax-only flag.""" |
| 100 | rel_header = os.path.relpath(header, repo_dir).replace(os.sep, "/") |
| 101 | suffix = language.suffix() |
| 102 | standard = language.standard() |
| 103 | |
| 104 | with tempfile.TemporaryDirectory() as tmp_dir: |
| 105 | source = os.path.join(tmp_dir, f"include_check{suffix}") |
| 106 | with open(source, "w", encoding="utf-8") as source_file: |
| 107 | source_file.write(f'#include "{rel_header}"\n') |
| 108 | |
| 109 | command = [compiler, "-fsyntax-only", f"-std={standard}", "-I", repo_dir] |
| 110 | if target: |
| 111 | command.extend(["-target", target]) |
| 112 | command.append(source) |
| 113 | |
| 114 | if verbose: |
| 115 | print(f"{command}") |
| 116 | |
| 117 | result = subprocess.run( |
| 118 | command, |
| 119 | check=False, |
| 120 | stdout=subprocess.PIPE, |
| 121 | stderr=subprocess.PIPE, |
| 122 | text=True, |
| 123 | ) |
| 124 | |
| 125 | if result.returncode == 0: |
| 126 | return None |
| 127 | |
| 128 | return CheckFailure( |
| 129 | header=rel_header, |
| 130 | language=language.value, |
| 131 | command=command, |
| 132 | stderr=result.stderr.strip(), |
| 133 | ) |
| 134 | |
| 135 | |
| 136 | def main(argv: Optional[Sequence[str]] = None) -> int: |
| 137 | parser = argparse.ArgumentParser(description=__doc__) |
| 138 | parser.add_argument( |
| 139 | "--compiler", help="Compiler to use for syntax checks (default: CC or clang)" |
| 140 | ) |
| 141 | parser.add_argument( |
| 142 | "--target", |
| 143 | default=default_target(), |
| 144 | help=( |
| 145 | "Compiler target triple. Pass an empty string to use the compiler " |
| 146 | "default (default: %(default)s)" |
| 147 | ), |
| 148 | ) |
| 149 | parser.add_argument( |
| 150 | "--verbose", |
| 151 | action="store_true", |
| 152 | help="Print each compiler invocation before running it", |
| 153 | ) |
| 154 | args = parser.parse_args(argv) |
| 155 | |
| 156 | repo_dir = git_utils.repo_root() |
| 157 | kai_dir = os.path.abspath(os.path.join(repo_dir, "kai")) |
| 158 | |
| 159 | if not os.path.isdir(kai_dir): |
| 160 | raise SystemExit(f"Micro-kernel directory not found: {kai_dir}") |
| 161 | |
| 162 | compiler = resolve_compiler(args.compiler) |
| 163 | target = args.target or None |
| 164 | headers = iter_headers(kai_dir) |
| 165 | |
| 166 | failures: list[CheckFailure] = [] |
| 167 | for header in headers: |
| 168 | for language in LANGUAGES: |
| 169 | failure = check_header( |
| 170 | compiler, repo_dir, header, language, target, args.verbose |
| 171 | ) |
| 172 | if failure is not None: |
| 173 | failures.append(failure) |
| 174 | |
| 175 | if failures: |
| 176 | print("Headers that failed standalone include checks:") |
| 177 | for failure in failures: |
| 178 | print(f"\n{failure.header} ({failure.language})") |
| 179 | print("Command:") |
| 180 | print(f" {failure.command}") |
| 181 | if failure.stderr: |
| 182 | print("Compiler output:") |
| 183 | print(failure.stderr) |
| 184 | return 1 |
| 185 | |
| 186 | print( |
| 187 | f"Checked {len(headers)} header(s) under {os.path.relpath(kai_dir, repo_dir)} " |
| 188 | f"as {', '.join([lang.value for lang in LANGUAGES])}." |
| 189 | ) |
| 190 | return 0 |
| 191 | |
| 192 | |
| 193 | if __name__ == "__main__": |
| 194 | sys.exit(main()) |