From 3d971a844088da5920a204e51f787bc0d0db3fab Mon Sep 17 00:00:00 2001 From: Igor Prilepov Date: Fri, 20 Nov 2026 19:09:18 -0800 Subject: [PATCH] Add deterministic schema description and explicit release metadata --- cmake/QuarryVersion.cmake | 32 +++++ docs/compiler-architecture.md | 3 +- docs/design/configuration-identity.md | 19 +-- docs/generated-binding-compatibility.md | 3 +- docs/versioning.md | 19 +++ examples/truck/README.md | 9 ++ include/quarry/version.hpp.in | 1 + tests/CMakeLists.txt | 6 + tests/fixtures/description/alpha.brd | 7 + tests/fixtures/description/configuration.brd | 4 + tests/fixtures/description/truck.txt | 22 +++ tests/fixtures/description/zeta.brd | 14 ++ tests/tools/schema_description_test.py | 127 ++++++++++++++++ tests/version/version_resolution_test.py | 62 +++++++- tools/CMakeLists.txt | 16 +++ tools/README.md | 27 ++++ tools/schema_compiler/main.cpp | 143 ++++++++++++++++++- 17 files changed, 498 insertions(+), 16 deletions(-) create mode 100644 tests/fixtures/description/alpha.brd create mode 100644 tests/fixtures/description/configuration.brd create mode 100644 tests/fixtures/description/truck.txt create mode 100644 tests/fixtures/description/zeta.brd create mode 100644 tests/tools/schema_description_test.py diff --git a/cmake/QuarryVersion.cmake b/cmake/QuarryVersion.cmake index a8f3214..bf10b56 100644 --- a/cmake/QuarryVersion.cmake +++ b/cmake/QuarryVersion.cmake @@ -30,6 +30,7 @@ function(quarry_resolve_version) set(_source "") set(_sha "") set(_dirty FALSE) + set(_release_tag "untagged") find_package(Git QUIET) if(Git_FOUND AND EXISTS "${CMAKE_SOURCE_DIR}/.git") execute_process( @@ -83,6 +84,24 @@ function(quarry_resolve_version) if(NOT _sha_result EQUAL 0) set(_sha "") endif() + # An ancestor tag is not release metadata for HEAD. Include both + # annotated and lightweight tags, as the archive exporter does. + execute_process( + COMMAND "${GIT_EXECUTABLE}" -C "${CMAKE_SOURCE_DIR}" + describe --tags --exact-match --match "v*" + RESULT_VARIABLE _tag_result + OUTPUT_VARIABLE _tag + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if(_tag_result EQUAL 0 AND + _tag MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)(-rc\\.[0-9]+)?$") + # Only recognize release labels for this development line. + # Numeric Git versioning and dirty-tree detection stay independent. + if(CMAKE_MATCH_1 STREQUAL _major AND CMAKE_MATCH_2 STREQUAL _minor) + set(_release_tag "${_tag}") + endif() + endif() execute_process( COMMAND "${GIT_EXECUTABLE}" -C "${CMAKE_SOURCE_DIR}" status --porcelain --untracked-files=no RESULT_VARIABLE _dirty_result @@ -97,6 +116,8 @@ function(quarry_resolve_version) endif() if(NOT _resolved AND EXISTS "${CMAKE_SOURCE_DIR}/cmake/QuarryResolvedVersion.cmake") + # A tag must come from the fallback file, not caller/cache state. + set(QUARRY_ARCHIVE_TAG "") include("${CMAKE_SOURCE_DIR}/cmake/QuarryResolvedVersion.cmake") if(DEFINED QUARRY_VERSION AND QUARRY_VERSION MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+$") string(REPLACE "." ";" _resolved_parts "${QUARRY_VERSION}") @@ -129,6 +150,13 @@ function(quarry_resolve_version) endif() endif() + if(_resolved AND _source MATCHES "^packaged-" AND + QUARRY_ARCHIVE_TAG MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)(-rc\\.[0-9]+)?$") + if(CMAKE_MATCH_1 STREQUAL _major AND CMAKE_MATCH_2 STREQUAL _minor) + set(_release_tag "${QUARRY_ARCHIVE_TAG}") + endif() + endif() + if(NOT _resolved) message(FATAL_ERROR "Unable to resolve Quarry version: Git history is unavailable or shallow and " @@ -136,6 +164,7 @@ function(quarry_resolve_version) "or provide a packaged cmake/QuarryResolvedVersion.cmake fallback.") endif() + set(QUARRY_RELEASE_TAG "${_release_tag}" PARENT_SCOPE) set(QUARRY_VERSION_MAJOR "${_major}" PARENT_SCOPE) set(QUARRY_VERSION_MINOR "${_minor}" PARENT_SCOPE) set(QUARRY_VERSION_REVISION "${_revision}" PARENT_SCOPE) @@ -156,4 +185,7 @@ function(quarry_write_resolved_version_fallback output_file) "# Generated release fallback; do not edit.\n" "set(QUARRY_VERSION \"${QUARRY_VERSION}\")\n" "set(QUARRY_GIT_SHA \"${QUARRY_GIT_SHA}\")\n") + if(NOT QUARRY_RELEASE_TAG STREQUAL "untagged") + file(APPEND "${output_file}" "set(QUARRY_ARCHIVE_TAG \"${QUARRY_RELEASE_TAG}\")\n") + endif() endfunction() diff --git a/docs/compiler-architecture.md b/docs/compiler-architecture.md index 4b8b5b2..6b23a7a 100644 --- a/docs/compiler-architecture.md +++ b/docs/compiler-architecture.md @@ -347,6 +347,7 @@ Schema IR (complete resolved configuration) -> consumers, all borrowing the same layout: backend plan()/generate() C++, C, C++/C storage, Python, Go QbsModelBuilder::build() --emit-qbs + description formatter --describe (assigned Schema IR IDs and prepared identity) ``` * `PreparedConfiguration` (`tools/schema_compiler/configuration_preparation.hpp`) @@ -354,7 +355,7 @@ Schema IR (complete resolved configuration) receive `const` references, use them only during the call, and keep no copy. * The layout always covers the complete configuration, never a `--generate` subset, so identity and record IDs do not depend on selection. -* Identity is hashed for ordinary generation and `--print-schema-id`. With +* Identity is hashed for ordinary generation, `--describe` and `--print-schema-id`. With `--emit-qbs` the QBS builder hashes the same input once instead. With `--list-outputs` nothing is hashed, including `--emit-qbs --list-outputs`, which still builds and validates the QBS model (`QbsBuildOptions::compute_configuration_identity = false`). diff --git a/docs/design/configuration-identity.md b/docs/design/configuration-identity.md index 96fe8e6..a2e1cb6 100644 --- a/docs/design/configuration-identity.md +++ b/docs/design/configuration-identity.md @@ -1,7 +1,6 @@ # Configuration Identity in Generated Code (A4) -Status: **approved; A4.1–A4.3 and #111 G1–G5 implemented**. A4.4 (`--describe`) -and A4.5 (`--name-prefix`) remain proposals, +Status: **approved; A4.1–A4.4 and #111 G1–G5 implemented**. A4.5 (`--name-prefix`) remains a proposal, not supported CLI/runtime features. A4 builds on hierarchical record IDs (#84) and configuration roots / `--generate` (#86); §15 records its historical review and §16 specifies the implemented generated-code identity. @@ -359,10 +358,9 @@ quarry_generic_status_t quarry_qbs_schema_id(const quarry_qbs_view_t* qbs, quarr and parser errors retain their existing behavior; no identity cache is added. - **Go:** has no QBS runtime, so only the generated constants exist. -## 7. Proposed A4.4 `--describe`; implemented `--print-schema-id` +## 7. Implemented `--describe` and `--print-schema-id` -`--describe` is not implemented. The proposed output below is not a runnable -current CLI example. In the proposal it prints human-readable, deterministic, line-oriented text. It ignores `--generate`, +`--describe` prints human-readable, deterministic, line-oriented text. It ignores `--generate`, writes nothing, and doesn't affect any output. ```text @@ -370,7 +368,7 @@ $ quarry-schema-compiler --describe examples/truck/schemas/configuration.brd configuration: class8_truck root: examples/truck/schemas/configuration.brd schema_id: 9200ca494f010801b830d0857cf66dde (algorithm 1: sha256-128) -compiler: quarry-schema-compiler 0.1.31-rc.1 (2507998, release tag v0.1.31-rc.1) +compiler: quarry-schema-compiler 0.1.288 (2507998, release tag v0.1.31-rc.1) formats: brf 2, qbs 1, schema-ir 1 generated-code epochs: cpp 3, c 7, python 1, go 1 domains: 6 @@ -394,11 +392,16 @@ records: 8 - **`--print-schema-id`** prints only the 32 hex digits, for scripts and CMake, alongside the existing `--print-generated-code-api-version`. - **Record roots** omit the `configuration:` line. -- **The compiler version line** needs a new version field. `QuarryVersion.cmake` would derive a - release tag from `git describe --exact-match --match 'v*'` (or the packaged archive tag), giving +- **The compiler version line** includes separate release metadata. `QuarryVersion.cmake` derives a + release tag from `git describe --tags --exact-match --match 'v*'` (or the packaged archive tag), giving `QUARRY_RELEASE_TAG`. Untagged builds print `untagged`. - **Version metadata never enters the identity input.** A4.1 leaves generated files unchanged; future bindings expose informational version metadata without mandatory runtime storage. +Mappings use assigned ID order as approved in #101. Numeric Git versions keep +the existing commit counter; release tags are separate informational metadata. +See [CLI behavior](../../tools/README.md#schema-description) and +[version resolution](../versioning.md#informational-release-metadata). + ## 8. Measured overhead These are historical A4 measurements, before generated-code identity. Current diff --git a/docs/generated-binding-compatibility.md b/docs/generated-binding-compatibility.md index 6b94a47..d8c1b0a 100644 --- a/docs/generated-binding-compatibility.md +++ b/docs/generated-binding-compatibility.md @@ -195,7 +195,8 @@ implementation. See the [C example](../examples/c/basic_encode_decode/README.md) [owning CMake integration](../examples/cpp/schema_compiler_cmake/README.md). The installed `quarry_generate_cpp()` helper is for C++ owning. This guide adds -no C-storage helper or `--name-prefix` / `--describe` feature. A4.3 +no C-storage helper or `--name-prefix` feature. A4.4 adds the optional +[`--describe` query](../tools/README.md#schema-description). A4.3 provides optional [stored QBS identity accessors](../runtime_c/README.md#stored-qbs-configuration-identity) in the existing C, C++ parser and Python APIs; these do not change generated bindings. Do not treat proposed design examples as current CLI. diff --git a/docs/versioning.md b/docs/versioning.md index 4f02f8c..432a67a 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -68,3 +68,22 @@ compiler, so an old build directory cannot silently retain version metadata from an earlier checkout. Directly invoking an existing binary does not reconfigure CMake; use the wrapper after changing Git state or switching commits. + +## Informational release metadata + +`QUARRY_RELEASE_TAG` and the compiler's `--version` / `--describe` report a +separate release tag. In Git this is an exact HEAD tag, annotated or lightweight, +matching `vX.Y.Z` or `vX.Y.Z-rc.N` and the current `git_version` major/minor. +Ancestor tags, unrelated tags and tags for another development line report +`untagged`. The numeric commit counter and tracked-file `-dirty` semantics above +are unchanged: an exact `v0.1.31-rc.1` tag can accompany numeric version +`0.1.288`. A dirty checkout retains its HEAD tag as informational metadata; +release creation still requires a clean commit. + +Archives use explicit `QUARRY_ARCHIVE_TAG` metadata alongside their existing +numeric fallback. A valid numeric fallback without a tag reports `untagged`; +package version strings never imply a release tag. The generated build fallback +preserves both fields when a tag exists. Missing or invalid numeric fallback +metadata remains an error without Git. When archive Git SHA metadata is absent, +the CLI explicitly reports `Git SHA unavailable`. None of these fields enters +schema identity, generated-code identity or generated bindings. diff --git a/examples/truck/README.md b/examples/truck/README.md index d534589..daf8ad6 100644 --- a/examples/truck/README.md +++ b/examples/truck/README.md @@ -38,6 +38,15 @@ local IDs number each namespace's records by name. Two files contribute to `truck.engine` and two to `truck.brakes`. Each namespace is generated as one unit containing all of its records. +Inspect the complete configuration without generating files (from this directory): + +```sh +quarry-schema-compiler --describe schemas/configuration.brd +``` + +The report includes the full schema identity, assigned IDs and compiler metadata; +`--generate` selections do not change it. + ## Generating the bindings The ECU needs only its own namespace and the shared timestamp: diff --git a/include/quarry/version.hpp.in b/include/quarry/version.hpp.in index 8d12f9b..bfc6f51 100644 --- a/include/quarry/version.hpp.in +++ b/include/quarry/version.hpp.in @@ -5,5 +5,6 @@ #define QUARRY_VERSION_REVISION @QUARRY_VERSION_REVISION@ #define QUARRY_VERSION_STRING "@QUARRY_VERSION@" #define QUARRY_VERSION_DISPLAY "@QUARRY_VERSION_DISPLAY@" +#define QUARRY_RELEASE_TAG "@QUARRY_RELEASE_TAG@" #define QUARRY_GIT_SHA "@QUARRY_GIT_SHA@" #define QUARRY_VERSION_DIRTY @QUARRY_VERSION_DIRTY@ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a3b1878..bb50bde 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,12 @@ target_link_libraries(backend_python_test PRIVATE quarry_schema_ir_warning_tweak find_program(QUARRY_PYTHON3_EXECUTABLE python3) if(QUARRY_PYTHON3_EXECUTABLE) + add_test(NAME schema_description_test + COMMAND ${QUARRY_PYTHON3_EXECUTABLE} + "${CMAKE_CURRENT_SOURCE_DIR}/tools/schema_description_test.py" + --source "${CMAKE_SOURCE_DIR}" + --compiler "$" + --generated-include "${QUARRY_GENERATED_INCLUDE_DIR}") add_test(NAME consumer_documentation_test COMMAND ${QUARRY_PYTHON3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/tools/consumer_documentation_test.py" diff --git a/tests/fixtures/description/alpha.brd b/tests/fixtures/description/alpha.brd new file mode 100644 index 0000000..8664f0d --- /dev/null +++ b/tests/fixtures/description/alpha.brd @@ -0,0 +1,7 @@ +namespace: m +record: Alpha +version: 1 +type: data +fields: + value: + type: u16 diff --git a/tests/fixtures/description/configuration.brd b/tests/fixtures/description/configuration.brd new file mode 100644 index 0000000..c7b8881 --- /dev/null +++ b/tests/fixtures/description/configuration.brd @@ -0,0 +1,4 @@ +configuration: ordering +imports: + - zeta.brd + - alpha.brd diff --git a/tests/fixtures/description/truck.txt b/tests/fixtures/description/truck.txt new file mode 100644 index 0000000..d333980 --- /dev/null +++ b/tests/fixtures/description/truck.txt @@ -0,0 +1,22 @@ +configuration: class8_truck +root: examples/truck/schemas/configuration.brd +schema_id: 9200ca494f010801b830d0857cf66dde (algorithm 1: sha256-128) +compiler: @COMPILER@ +formats: brf 2, qbs 1, schema-ir 1 +generated-code epochs: cpp 3, c 7, python 1, go 1 +domains: 6 + 0x0001 truck + 0x0002 truck.brakes + 0x0003 truck.cms + 0x0004 truck.common + 0x0005 truck.engine + 0x0006 truck.transmission +records: 8 + 0x00010001 truck.VehicleSnapshot + 0x00020001 truck.brakes.AbsEvent + 0x00020002 truck.brakes.BrakeStatus + 0x00030001 truck.cms.CameraHealth + 0x00040001 truck.common.Timestamp + 0x00050001 truck.engine.EngineStatus + 0x00050002 truck.engine.FaultCode + 0x00060001 truck.transmission.GearState diff --git a/tests/fixtures/description/zeta.brd b/tests/fixtures/description/zeta.brd new file mode 100644 index 0000000..b962a90 --- /dev/null +++ b/tests/fixtures/description/zeta.brd @@ -0,0 +1,14 @@ +namespace: m +record: Zeta +version: 1 +type: data +enums: + UnusedA: + values: + first: 1 + UnusedB: + values: + second: 2 +fields: + value: + type: u16 diff --git a/tests/tools/schema_description_test.py b/tests/tools/schema_description_test.py new file mode 100644 index 0000000..6c902aa --- /dev/null +++ b/tests/tools/schema_description_test.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Exercise the actual --describe CLI, wire identity and read-only behavior.""" +import argparse +import ast +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('source', 'compiler', 'generated-include'): + parser.add_argument('--' + name, required=True) + args = parser.parse_args() + source = Path(args.source).resolve() + generated = Path(args.generated_include) + fixtures = source / 'tests/fixtures/description' + with tempfile.TemporaryDirectory(prefix='quarry-description-') as temporary: + root = Path(temporary) + shutil.copytree(source / 'examples/truck/schemas', root / 'examples/truck/schemas') + shutil.copytree(fixtures, root / 'small') + + def call(*flags, status=0, locale=None): + environment = os.environ.copy() + if locale: + environment['LC_ALL'] = locale + result = subprocess.run([args.compiler, *map(str, flags)], cwd=root, + text=True, capture_output=True, env=environment, check=False) + assert result.returncode == status, (flags, result.returncode, result.stderr) + if status == 0: + assert not result.stderr, result.stderr + else: + assert not result.stdout, result.stdout + assert re.search(r'error(?::| [A-Z]+[0-9]+:)', result.stderr), result.stderr + return result.stdout + + schema = 'examples/truck/schemas/configuration.brd' + version = call('--version').strip() + expected = (fixtures / 'truck.txt').read_text().replace('@COMPILER@', version) + before = set(root.rglob('*')) + assert call('--describe', schema) == expected + for _ in range(3): + assert call('--describe', schema) == expected + assert call('--describe', schema, locale='C') == expected + assert call('--describe', schema, locale='tr_TR.UTF-8') == expected + for selection in ('truck.engine', 'truck.common,truck.engine', 'unknown.namespace'): + assert call('--describe', '--generate', selection, schema) == expected + for language in ('cpp', 'c', 'python', 'go'): + assert call('--describe', '--language', language, '-o', root / 'not-created', + '--root-file-stem', 'renamed', '--file-extension', '.custom', schema) == expected + assert call('--describe', '--language', 'go', '--cpp-storage', 'c', + '--c-optimize-size=unknown', '--go-import-prefix', 'unused', schema) == expected + absolute = call('--describe', root / schema) + assert absolute == expected.replace('root: ' + schema, 'root: configuration.brd') + assert str(root) not in absolute + assert set(root.rglob('*')) == before, '--describe wrote files' + + epochs = re.search(r'generated-code epochs: cpp (\d+), c (\d+), python (\d+), go (\d+)', expected).groups() + cpp_header = (generated / 'quarry/runtime/version.hpp').read_text() + c_header = (generated / 'quarry/runtime_c/version.h').read_text() + assert epochs[0] == re.search(r'kGeneratedCodeApiVersion\s*=\s*(\d+)U', cpp_header).group(1) + assert epochs[0] == call('--print-generated-code-api-version').strip() + assert epochs[1] == re.search(r'QUARRY_C_GENERATED_CODE_API_VERSION\s+(\d+)U', c_header).group(1) + python_tree = ast.parse((source / 'runtime/python/src/quarry/runtime/python/__init__.py').read_text()) + python_epoch = next(ast.literal_eval(node.value) for node in python_tree.body + if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and + t.id == 'QUARRY_GENERATED_CODE_API_VERSION_PYTHON' for t in node.targets)) + assert epochs[2] == str(python_epoch) + go = (source / 'runtime/go/brf/brf.go').read_text() + assert epochs[3] == re.search(r'const GeneratedCodeAPIVersion = (\d+)', go).group(1) + identity = call('--print-schema-id', schema).strip() + assert 'schema_id: ' + identity + ' (algorithm 1: sha256-128)' in expected + for reflective in (False, True): + image = root / ('reflective.qbs' if reflective else 'minimal.qbs') + call('--emit-qbs', image, *(['--qbs-reflective'] if reflective else []), schema) + raw = image.read_bytes() + assert raw[8] == 1 and raw[12:28].hex() == identity + + # Import order, declaration/file order, top-level YAML key order and + # unused enum declaration order do not change the reported mappings. + small = root / 'small' + baseline = call('--describe', 'small/configuration.brd') + assert 'domains: 1\n 0x0001 m\nrecords: 2\n' in baseline + assert '0x00010001 m.Alpha\n 0x00010002 m.Zeta\n' in baseline + alpha, zeta = (small / 'alpha.brd').read_text(), (small / 'zeta.brd').read_text() + (small / 'alpha.brd').write_text(zeta.replace('namespace: m\nrecord: Zeta', 'record: Zeta\nnamespace: m')) + (small / 'zeta.brd').write_text(alpha) + config = small / 'configuration.brd' + config.write_text(config.read_text().replace(' - zeta.brd\n - alpha.brd', ' - alpha.brd\n - zeta.brd')) + assert call('--describe', 'small/configuration.brd') == baseline + config.write_text(config.read_text().replace('ordering', 'renamed')) + assert call('--describe', 'small/configuration.brd') == baseline.replace('configuration: ordering', 'configuration: renamed') + body = (small / 'alpha.brd').read_text() + first = ' UnusedA:\n values:\n first: 1\n' + second = ' UnusedB:\n values:\n second: 2\n' + (small / 'alpha.brd').write_text(body.replace(first + second, second + first)) + assert call('--describe', 'small/configuration.brd') == baseline.replace('configuration: ordering', 'configuration: renamed') + standalone = call('--describe', 'small/zeta.brd') + assert 'configuration:' not in standalone + assert 'records: 1\n 0x00010001 m.Alpha\n' in standalone + assert call('--print-schema-id', 'small/zeta.brd').strip() in standalone + if os.name != 'nt': + unusual = small / 'line\nbreak.brd' + unusual.write_text(alpha) + assert 'root: line\\x0abreak.brd\n' in call('--describe', unusual) + + for conflicting in (['--list-outputs'], ['--list-inputs'], ['--print-schema-id'], + ['--print-generated-code-api-version'], ['--version'], + ['--emit-qbs', 'forbidden.qbs'], ['--qbs-reflective'], ['--describe']): + call('--describe', *conflicting, schema, status=2) + assert not (root / 'forbidden.qbs').exists() + call('--describe', status=2) + call('--describe', schema, schema, status=2) + call('--describe', '--generate', '', schema, status=2) + call('--describe', '--language', 'invalid', schema, status=2) + call('--describe', 'does-not-exist.brd', status=1) + (root / 'invalid.brd').write_text('unknown: invalid\n') + call('--describe', 'invalid.brd', status=1) + assert '--describe' in call('--help', '--describe') + print('Description golden, identity/epochs, ordering, options, errors and read-only invariants passed.') + + +if __name__ == '__main__': + main() diff --git a/tests/version/version_resolution_test.py b/tests/version/version_resolution_test.py index 026c941..9d96f65 100644 --- a/tests/version/version_resolution_test.py +++ b/tests/version/version_resolution_test.py @@ -66,7 +66,8 @@ def write_project(root: Path, resolver: Path) -> None: f"include(\"{resolver}\")\n" "quarry_resolve_version()\n" "file(WRITE \"${CMAKE_BINARY_DIR}/result.txt\"\n" - " \"${QUARRY_VERSION}|${QUARRY_VERSION_DISPLAY}|${QUARRY_VERSION_DIRTY}|${QUARRY_VERSION_SOURCE}\")\n", + " \"${QUARRY_VERSION}|${QUARRY_VERSION_DISPLAY}|${QUARRY_VERSION_DIRTY}|${QUARRY_VERSION_SOURCE}|${QUARRY_RELEASE_TAG}\")\n" + "quarry_write_resolved_version_fallback(\"${CMAKE_BINARY_DIR}/QuarryResolvedVersion.cmake\")\n", encoding="utf-8") @@ -118,6 +119,64 @@ def archive_fallback_scenario(cmake: str, resolver: Path) -> None: assert result.startswith("0.3.8|packaged-archive|"), result +def release_metadata_scenarios(cmake: str, resolver: Path) -> None: + with tempfile.TemporaryDirectory(prefix="quarry-release-metadata-") as temporary: + root = Path(temporary) / "git" + root.mkdir() + run(["git", "init", "-q"], cwd=root) + run(["git", "config", "user.name", "Quarry version fixture"], cwd=root) + run(["git", "config", "user.email", "fixture@example.invalid"], cwd=root) + (root / "git_version").write_text("0.1\n") + (root / ".gitignore").write_text("build/\n") + write_project(root, resolver) + commit(root, "initial") + assert configure(root, cmake).endswith("|untagged") + run(["git", "tag", "v0.1.31-rc.1"], cwd=root) + tagged = configure(root, cmake) + assert tagged == "0.1.0|0.1.0|FALSE|git|v0.1.31-rc.1", tagged + assert configure(root, cmake) == tagged + # A build fallback retains the tag without replacing the Git-derived number. + archive = Path(temporary) / "fallback" + archive.mkdir() + (archive / "git_version").write_text("0.1\n") + (archive / "cmake").mkdir() + (archive / "cmake/QuarryResolvedVersion.cmake").write_bytes( + (root / "build/QuarryResolvedVersion.cmake").read_bytes()) + write_project(archive, resolver) + assert configure(archive, cmake) == "0.1.0|0.1.0|FALSE|packaged-fallback|v0.1.31-rc.1" + (root / "marker").write_text("tracked\n") + commit(root, "after release") + assert configure(root, cmake) == "0.1.1|0.1.1|FALSE|git|untagged" + run(["git", "tag", "-a", "v0.1.32-rc.2", "-m", "test release"], cwd=root) + assert configure(root, cmake).endswith("|v0.1.32-rc.2") + (root / "marker").write_text("dirty\n") + assert configure(root, cmake) == "0.1.1|0.1.1-dirty|TRUE|git|v0.1.32-rc.2" + run(["git", "checkout", "--", "marker"], cwd=root) + run(["git", "tag", "-d", "v0.1.32-rc.2"], cwd=root) + run(["git", "tag", "v9.9.9"], cwd=root) + assert configure(root, cmake).endswith("|untagged") + + cases = { + "numeric": ('set(QUARRY_VERSION "0.1.31")\n', "0.1.31|0.1.31|FALSE|packaged-fallback|untagged"), + "release": ('set(QUARRY_VERSION "0.1.31")\nset(QUARRY_ARCHIVE_TAG "v0.1.31-rc.1")\n', + "0.1.31|0.1.31|FALSE|packaged-fallback|v0.1.31-rc.1"), + "missing": (None, None), + "invalid": ('set(QUARRY_VERSION "invalid")\n', None), + "ancestor": ('set(QUARRY_ARCHIVE_TAG "v0.1.31-1-gabcdef")\n', None), + } + for name, (fallback, expected) in cases.items(): + source = Path(temporary) / name + source.mkdir() + (source / "git_version").write_text("0.1\n") + write_project(source, resolver) + if fallback is not None: + (source / "cmake").mkdir() + (source / "cmake/QuarryResolvedVersion.cmake").write_text(fallback) + result = configure(source, cmake, expect_success=expected is not None) + if expected is not None: + assert result == expected, (name, result) + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--cmake", required=True) @@ -183,6 +242,7 @@ def main() -> None: assert "Major.Minor" in configure(malformed_root, args.cmake, expect_success=False) archive_fallback_scenario(args.cmake, args.resolver) + release_metadata_scenarios(args.cmake, args.resolver) if __name__ == "__main__": diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index a5f6322..e0d27dc 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -40,6 +40,22 @@ target_link_libraries(quarry_schema_compiler quarry_schema_compiler_preparation quarry_schema_ir_warning_tweaks ) +# Python's runtime epoch is maintained outside CMake. Read its public literal +# at configure time so --describe needs neither Python at runtime nor a second +# hard-coded epoch. Watch the source when an incremental build updates it. +set(_python_epoch_source "${CMAKE_SOURCE_DIR}/runtime/python/src/quarry/runtime/python/__init__.py") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_python_epoch_source}") +file(STRINGS "${_python_epoch_source}" _python_epoch_line + REGEX "^QUARRY_GENERATED_CODE_API_VERSION_PYTHON = [0-9]+$") +list(LENGTH _python_epoch_line _python_epoch_count) +if(NOT _python_epoch_count EQUAL 1) + message(FATAL_ERROR "Cannot read the Python runtime's generated-code API epoch") +endif() +string(REGEX REPLACE "^QUARRY_GENERATED_CODE_API_VERSION_PYTHON = ([0-9]+)$" "\\1" + _python_epoch "${_python_epoch_line}") +target_compile_definitions(quarry_schema_compiler PRIVATE + QUARRY_SCHEMA_COMPILER_PYTHON_API_EPOCH=${_python_epoch}) + target_include_directories(quarry_schema_compiler PRIVATE ${QUARRY_GENERATED_INCLUDE_DIR} diff --git a/tools/README.md b/tools/README.md index 3dfd110..487df15 100644 --- a/tools/README.md +++ b/tools/README.md @@ -53,6 +53,7 @@ Options: --list-outputs Print generated output paths without writing files --print-generated-code-api-version Print the generated-code API compatibility version and exit + --describe Describe the full configuration without writing files --print-schema-id Print the resolved configuration's 128-bit schema_id --version Show version information -h, --help Show help @@ -642,3 +643,29 @@ Encoding validates fields as it writes them. On any encode error, discard or clear the affected output span; `bytes_written` reports its extent even on failure, including partial nested writes. It is not a valid record length on error. The codec does not roll back failed writes. `encoded_size()` remains available for a separate validating size calculation. + +### Schema description + +Run `quarry-schema-compiler --describe examples/truck/schemas/configuration.brd` +from the repository root. The deterministic text includes the configuration name +(for configuration roots), root label, full schema identity and algorithm, +compiler and release metadata, format versions, API epochs, and assigned domain +and record mappings. Standalone record roots omit the configuration line. +Domains and records appear in assigned ID order, using four and eight lowercase +hexadecimal digits respectively. Only namespaces containing records have domains. +The IDs and canonical names come from the resolved Schema IR; identity comes from +the same configuration preparation as `--print-schema-id`. + +`--describe` ignores `--generate` (including unknown namespace selections), +backend, storage, output-directory and naming options. Their basic argument syntax +is still checked. It describes the complete configuration and creates no files. +Combining it with `--list-inputs`, `--list-outputs`, `--print-schema-id`, +`--print-generated-code-api-version`, `--version`, `--emit-qbs` or +`--qbs-reflective` is a usage error (exit 2); `--help` remains terminal. +A missing root is exit 2; unreadable or invalid schemas are exit 1. + +Relative root labels are lexically normalized with forward slashes; absolute +inputs display only their basename. Backslashes and control bytes in labels are +escaped. Output contains no timestamps or host-specific absolute paths and uses +locale-independent number formatting. Compiler metadata may differ between +compiler builds; it never contributes to schema identity. diff --git a/tools/schema_compiler/main.cpp b/tools/schema_compiler/main.cpp index 54bee92..9641b1a 100644 --- a/tools/schema_compiler/main.cpp +++ b/tools/schema_compiler/main.cpp @@ -1,6 +1,7 @@ #include "compiler/backend/backend.hpp" #include "compiler/backend/generated_code_api_version.hpp" #include "compiler/backend_c/backend_c.hpp" +#include "compiler/backend_c/generated_code_api_version_c.hpp" #include "compiler/backend_go/backend_go.hpp" #include "compiler/backend_python/backend_python.hpp" #include "compiler/context/compiler_context.hpp" @@ -14,13 +15,18 @@ #include "tools/schema_compiler/configuration_preparation.hpp" #include +#include #include #include #include +#include #include +#include +#include #include #include #include +#include #include #include #include @@ -56,6 +62,7 @@ struct CommandLine { bool show_version = false; bool show_generated_code_api_version = false; bool print_schema_id = false; + bool describe = false; bool list_outputs = false; bool list_inputs = false; bool c_optimize_size = false; @@ -98,6 +105,7 @@ struct CommandLine { " Print the generated-code API compatibility version and " "exit\n" " --print-schema-id Print the resolved configuration's 128-bit schema_id\n" + " --describe Describe the full configuration without writing files\n" " --version Show version information\n" " -h, --help Show this help text\n"; } @@ -105,8 +113,15 @@ struct CommandLine { void print_usage(std::ostream& output) { output << usage_text(); } void print_version(std::ostream& output) { - output << "quarry-schema-compiler " << QUARRY_VERSION_DISPLAY - << " (" << QUARRY_GIT_SHA << ")\n"; + output << "quarry-schema-compiler " << QUARRY_VERSION_DISPLAY << " (" + << (std::string_view(QUARRY_GIT_SHA).empty() ? "Git SHA unavailable" : QUARRY_GIT_SHA) + << ", "; + if (std::string_view(QUARRY_RELEASE_TAG) == "untagged") { + output << "untagged"; + } else { + output << "release tag " << QUARRY_RELEASE_TAG; + } + output << ")\n"; } void print_generated_code_api_version(std::ostream& output) { @@ -118,6 +133,88 @@ void print_schema_id(std::ostream& output, output << quarry::compiler::support::schema_id_hex(identity) << '\n'; } +// Metadata only: paths are display labels, never host-specific canonical paths. +[[nodiscard]] std::string description_label(std::string_view value) { + constexpr char digits[] = "0123456789abcdef"; + std::string text; + for (const unsigned char byte : value) { + if (byte == '\\') { + text += "\\\\"; + } else if (byte < 32U || byte == 127U) { + text += "\\x"; + text += digits[byte >> 4U]; + text += digits[byte & 15U]; + } else { + text += static_cast(byte); + } + } + return text; +} + +void print_description(const CommandLine& command_line, + const context::CompilerContext& compiler_context, + const quarry::compiler::schema_ir::SchemaIrModel& ir, + const PreparedConfiguration& prepared, std::ostream& output) { + struct Record { + std::uint32_t id; + std::string_view fqn; + }; + std::map domains; + std::vector records; + std::vector pending{&ir.root_namespace()}; + while (!pending.empty()) { + const auto* ns = pending.back(); + pending.pop_back(); + if (!ns->records().empty()) { + // Extract the existing domain component; do not allocate/reassign IDs. + domains.emplace(ns->records(0).record_id() >> 16U, ns->fqn()); + } + for (const auto& record : ns->records()) { + records.push_back({record.record_id(), record.fqn()}); + } + for (const auto& child : ns->namespaces()) { + pending.push_back(&child); + } + } + std::sort(records.begin(), records.end(), [](const Record& left, const Record& right) { + return std::tie(left.id, left.fqn) < std::tie(right.id, right.fqn); + }); + std::ostringstream text; + text.imbue(std::locale::classic()); + for (const auto& unit : compiler_context.source_units()) { + if (unit.is_root && unit.is_configuration) { + text << "configuration: " << description_label(unit.configuration_name) << '\n'; + } + } + auto root = std::filesystem::path(command_line.input_path).lexically_normal(); + if (root.is_absolute()) { + root = root.filename(); + } + text << "root: " << description_label(root.generic_string()) << '\n'; + const auto& identity = *prepared.identity; + text << "schema_id: " << quarry::compiler::support::schema_id_hex(identity) + << " (algorithm " << static_cast(identity.algorithm) << ": sha256-128)\n"; + text << "compiler: "; + print_version(text); + text << "formats: brf " << static_cast(quarry::compiler::qbs::kBrfFormatVersion) + << ", qbs " << static_cast(quarry::compiler::qbs::kQbsFormatVersion) + << ", schema-ir " << ir.schema_ir_version() << '\n'; + text << "generated-code epochs: cpp " << backend::kGeneratedCodeApiVersion + << ", c " << backend_c::kGeneratedCodeApiVersionC + << ", python " << QUARRY_SCHEMA_COMPILER_PYTHON_API_EPOCH + << ", go " << backend_go::kGeneratedCodeApiVersionGo << '\n'; + text << "domains: " << domains.size() << '\n'; + for (const auto& [id, fqn] : domains) { + text << " 0x" << std::hex << std::setfill('0') << std::setw(4) << id << ' ' + << (fqn.empty() ? "" : fqn) << '\n'; + } + text << std::dec << "records: " << records.size() << '\n'; + for (const auto& record : records) { + text << " 0x" << std::hex << std::setw(8) << record.id << ' ' << record.fqn << '\n'; + } + output << text.str(); +} + [[nodiscard]] bool option_requires_value(std::string_view option) { return option == "-o" || option == "--output-directory" || option == "--root-file-stem" || option == "--file-extension" || option == "--language" || option == "--emit-qbs" || @@ -154,6 +251,14 @@ void print_schema_id(std::ostream& output, command_line.show_generated_code_api_version = true; continue; } + if (argument == "--describe") { + if (command_line.describe) { + errors << "error: duplicate --describe option\n"; + return std::nullopt; + } + command_line.describe = true; + continue; + } if (argument == "--print-schema-id") { if (command_line.print_schema_id) { errors << "error: duplicate --print-schema-id option\n"; @@ -321,6 +426,23 @@ void print_schema_id(std::ostream& output, command_line.input_path = std::string(argument); } + if (command_line.describe) { + if (!command_line.show_help && + (command_line.show_version || command_line.show_generated_code_api_version || + command_line.print_schema_id || command_line.list_inputs || command_line.list_outputs || + saw_qbs_output || saw_qbs_reflective)) { + errors << "error: --describe cannot be combined with other query or QBS operations\n"; + return std::nullopt; + } + if (!command_line.show_help && command_line.input_path.empty()) { + errors << "error: expected exactly one input file\n"; + return std::nullopt; + } + // Syntax was checked above. Backend/output options have no meaning in + // a full-configuration metadata query, including --generate selection. + return command_line; + } + if (command_line.show_generated_code_api_version) { const bool has_generation_arguments = command_line.list_inputs || command_line.list_outputs || @@ -577,7 +699,8 @@ template const frontend::YamlCompilationResult compilation_result = compiler.compile(source_file_id, compiler_context, diagnostic_engine, quarry::compiler::output_planning::GenerationSelection{ - .namespaces = command_line.generate_namespaces}); + .namespaces = command_line.describe ? std::vector{} + : command_line.generate_namespaces}); if (!diagnostic_engine.empty()) { errors << diagnostics::DiagnosticFormatter::format_all( @@ -632,7 +755,7 @@ template return exit_success; } - if (command_line.c_optimize_size) { + if (!command_line.describe && command_line.c_optimize_size) { backend_c::CodegenOptions storage_options; storage_options.optimize_size_namespaces = command_line.c_optimize_size_namespaces; if (const auto error = backend_c::validate_storage_options(*compilation_result.schema_ir, @@ -645,7 +768,7 @@ template // Prepare the resolved configuration once: its authoritative BRF layout, // and its identity only where an output depends on it. --emit-qbs hashes // inside the QBS builder; --list-outputs needs no identity at all. - const bool identity_required = command_line.print_schema_id || + const bool identity_required = command_line.describe || command_line.print_schema_id || (!command_line.list_outputs && command_line.qbs_output.empty()); diagnostics::DiagnosticEngine layout_diagnostics; const std::optional prepared = @@ -655,6 +778,16 @@ template compiler_context.source_manager()); }; + if (command_line.describe) { + if (!prepared.has_value()) { + print_layout_diagnostics(); + return exit_failure; + } + print_description(command_line, compiler_context, *compilation_result.schema_ir, *prepared, + output); + return exit_success; + } + if (command_line.print_schema_id) { if (!prepared.has_value()) { print_layout_diagnostics();