cmakeast.py¶
clew/cmakeast.py
The CMake dialect: function and macro definitions for the parse-built front end.
harvest_definitions
dict[str, list[dict[str, Any]]] clew.cmakeast.harvest_definitions(Any tree, bytes src_bytes)
Harvest one CMake file's function and macro definitions.
Source · 22 lines
def harvest_definitions(tree: Any, src_bytes: bytes) -> dict[str, list[dict[str, Any]]]:
"""Positions are 1-based lines and 0-based columns, as doxygen writes them, and the
payload is rowid-free JSON so it caches per file content like every other stage.
`classes` is present and empty: CMake has no class-like construct, and the shape is
shared with the JS/TS payload the same writer consumes.
@brief Harvest CMake definitions.
@return The definitions payload.
"""
out: dict[str, list[dict[str, Any]]] = {"functions": [], "classes": []}
if tree.root_node.type != CMAKE_ROOT:
return out
lines = src_bytes.decode("utf-8", errors="replace").splitlines()
for node in walk_nodes(tree.root_node):
record = _definition_record(node, lines)
if record is not None:
out["functions"].append(record)
out["functions"].sort(key=lambda fn: (fn["line"], fn["name"]))
return out
Activity · 10 steps
Requirements
harvest_generation
dict[str, list[dict[str, Any]]] clew.cmakeast.harvest_generation(Any tree, bytes src_bytes)
Harvest one CMake file's generation rules.
Called by harvest
Tested by 8 tests
test_a_custom_command_is_harvested, test_a_custom_target_is_harvested_as_a_target, test_a_directory_reference_yields_no_filename, test_a_file_with_no_rules_harvests_nothing, test_the_real_mbedtls_cmakelists_yields_all_four_generators, test_the_whole_mbedtls_tree_yields_only_plausible_outputs, test_unlisted_keywords_close_the_section, test_variables_are_recorded_not_resolved
Calls _sections, _variables, walk_nodes
Source · 51 lines
def harvest_generation(tree: Any, src_bytes: bytes) -> dict[str, list[dict[str, Any]]]:
"""WHAT A BUILD FILE SAYS THAT NO OTHER LAYER DOES: which files do not exist until something
produces them, and what produces them. `library/error.c` in mbedtls is generated by
`scripts/generate_errors.pl` from the public headers and `scripts/data_files/error.fmt`, and
an answer that reads `error.c` top to bottom describes a hand-written table and is wrong —
which is exactly what mbedtls Q4's rubric says about it.
`{}` AND NOT `{"generated": []}` for a file with no rules, for the reason
`_ScriptSymbolHarvester` gives about partitions: a row per file recording that a C file
generates nothing is forty thousand rows of nothing on a large target.
FOUR RULES IN THE REAL FILE, not one. Parsed from the frozen checkout: `error.c`,
`version_features.c`, `ssl_debug_helpers_generated.c` and the `psa_crypto_driver_wrappers`
pair, across three generators in two languages. A harvest written for the one graded mark
would have missed three quarters of what that file states.
@brief Harvest CMake generation rules.
@return The generation payload, or {}.
@version 1
"""
if tree.root_node.type != CMAKE_ROOT:
return {}
rules: list[dict[str, Any]] = []
for node in walk_nodes(tree.root_node):
if node.type != _COMMAND:
continue
ident = next((c for c in node.children if c.type == _IDENTIFIER), None)
kind = _GENERATORS.get(node_text(ident).strip().lower()) if ident is not None else None
if kind is None:
continue
arg_list = next((c for c in node.children if c.type == _ARGUMENT_LIST), None)
args = (
[node_text(a) for a in arg_list.children if a.type == _ARGUMENT]
if arg_list is not None
else []
)
sections = _sections(args, first_is_name=(kind == "custom_target"))
rules.append(
{
"kind": kind,
"line": node.start_point[0] + 1,
"outputs": sections.get("OUTPUT", []),
"command": sections.get("COMMAND", []),
"depends": sections.get("DEPENDS", []),
}
)
## 2.1: the file's literal variable assignments ride along, for `resolve_argument` (not
## `variables`, which a payload already uses for typed members).
return {"generated": rules, "cmake_variables": _variables(tree.root_node)} if rules else {}
Activity · 15 steps
Requirements
resolve_argument
str clew.cmakeast.resolve_argument(str literal, str cmake_dir, dict[str, str] variables, bool root_has_cmake)
A generation argument as a repository-relative path, when the build file alone settles it.
Called by _write_generation
Tested by 6 tests
test_a_quoted_argument_resolves_without_its_quotes, test_a_quoted_set_value_expands_without_its_quotes, test_a_variable_set_in_the_file_expands, test_only_an_expanded_variable_resolves, test_the_files_own_directory_and_the_root_expand, test_what_the_build_file_does_not_settle_stays_unresolved
Calls _unquoted
Source · 36 lines
def resolve_argument(
literal: str, cmake_dir: str, variables: dict[str, str], root_has_cmake: bool
) -> str:
"""2.1 (the 2.0.0 grid, mbedtls Q4 −22.7): `${CMAKE_CURRENT_SOURCE_DIR}/../scripts/
generate_errors.pl` was stored only as written, so nothing joined it to the indexed script.
NEVER GUESSED: the binary dir and found programs (`${PERL_EXECUTABLE}`) need a configure step
the index never ran, so anything still holding `${` resolves to "", as does a path that would
leave the repository.
@brief Resolve an argument.
@return Path or "".
"""
import posixpath
## ONLY AN EXPANDED VARIABLE RESOLVES (found measuring mbedtls: command words like `sed` and
## `-i.bak` passed through as "paths"). A literal without one already says all it can.
if "${" not in literal:
return ""
## A QUOTED ARGUMENT'S QUOTES ARE NOT PART OF THE PATH (found measuring mbedtls:
## `"./framework/scripts/generate_test_keys.py"`, sometimes doubled).
text = _unquoted(literal)
for _ in range(4):
for name in _HERE:
text = text.replace(f"${{{name}}}", cmake_dir or ".")
if root_has_cmake:
for name in _ROOT:
text = text.replace(f"${{{name}}}", ".")
for name, value in variables.items():
text = text.replace(f"${{{name}}}", value)
if "${" not in text:
break
text = _unquoted(text)
if "${" in text or not text or text.startswith("/"):
return ""
path = posixpath.normpath(text)
return "" if path == ".." or path.startswith("../") else path1 more lines, not shown