Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions cmake/QuarryVersion.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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}")
Expand Down Expand Up @@ -129,13 +150,21 @@ 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 "
"no packaged fallback exists. Fetch full history with 'git fetch --unshallow' "
"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)
Expand All @@ -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()
3 changes: 2 additions & 1 deletion docs/compiler-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,14 +347,15 @@ 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`)
owns the layout and the optional identity for the whole invocation. Consumers
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`).
Expand Down
19 changes: 11 additions & 8 deletions docs/design/configuration-identity.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -359,18 +358,17 @@ 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
$ 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
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/generated-binding-compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 19 additions & 0 deletions docs/versioning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 9 additions & 0 deletions examples/truck/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions include/quarry/version.hpp.in
Original file line number Diff line number Diff line change
Expand Up @@ -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@
6 changes: 6 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 "$<TARGET_FILE:quarry_schema_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"
Expand Down
7 changes: 7 additions & 0 deletions tests/fixtures/description/alpha.brd
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace: m
record: Alpha
version: 1
type: data
fields:
value:
type: u16
4 changes: 4 additions & 0 deletions tests/fixtures/description/configuration.brd
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
configuration: ordering
imports:
- zeta.brd
- alpha.brd
22 changes: 22 additions & 0 deletions tests/fixtures/description/truck.txt
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions tests/fixtures/description/zeta.brd
Original file line number Diff line number Diff line change
@@ -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
127 changes: 127 additions & 0 deletions tests/tools/schema_description_test.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading