From 692b83189a8e6f1f53360d87b7b6c2de8fb5a699 Mon Sep 17 00:00:00 2001 From: Igor Prilepov Date: Fri, 20 Nov 2026 21:08:39 -0800 Subject: [PATCH] Add explicit naming isolation for generated configurations --- .github/workflows/ci.yml | 27 ++ cmake/QuarryGenerate.cmake | 44 +- compiler/backend/README.md | 10 + compiler/backend/backend.cpp | 419 +++++++++--------- compiler/backend/backend.hpp | 2 + compiler/backend_c/README.md | 18 + compiler/backend_c/backend_c.cpp | 331 +++++++------- compiler/backend_c/backend_c.hpp | 2 + compiler/backend_go/backend_go.cpp | 10 +- compiler/backend_go/backend_go.hpp | 2 + compiler/backend_python/README.md | 10 + compiler/backend_python/backend_python.cpp | 330 +++++++------- compiler/backend_python/backend_python.hpp | 2 + compiler/support/generated_names.hpp | 191 ++++++++ compiler/support/namespace_macro.hpp | 4 +- cortex_m/CMakeLists.txt | 17 +- cortex_m/README.md | 15 + cortex_m/smoke/name_prefix_adapter.h | 34 ++ cortex_m/smoke/workload_smoke.c | 4 + docs/design/configuration-identity.md | 67 +-- docs/design/go-backend.md | 10 + docs/generated-binding-compatibility.md | 14 +- docs/schema-compiler-tool-distribution.md | 27 ++ examples/README.md | 2 + examples/truck/README.md | 7 + .../truck/multi_configuration/CMakeLists.txt | 66 +++ examples/truck/multi_configuration/README.md | 64 +++ .../truck/multi_configuration/c_storage.cpp | 51 +++ examples/truck/multi_configuration/main.go.in | 59 +++ examples/truck/multi_configuration/owning.cpp | 50 +++ examples/truck/multi_configuration/plain.c | 59 +++ examples/truck/multi_configuration/python.py | 23 + .../rev_b/configuration.brd | 8 + .../multi_configuration/rev_b/mirror_fold.brd | 7 + examples/truck/multi_configuration/run.py | 78 ++++ tests/CMakeLists.txt | 12 + tests/examples/example_validation.py | 10 + .../name_prefix/unprefixed_sha256.json | 91 ++++ tests/tools/name_prefix_cmake_test.py | 101 +++++ tests/tools/name_prefix_test.py | 223 ++++++++++ tools/README.md | 43 ++ tools/schema_compiler/main.cpp | 39 +- 42 files changed, 2031 insertions(+), 552 deletions(-) create mode 100644 compiler/support/generated_names.hpp create mode 100644 cortex_m/smoke/name_prefix_adapter.h create mode 100644 examples/truck/multi_configuration/CMakeLists.txt create mode 100644 examples/truck/multi_configuration/README.md create mode 100644 examples/truck/multi_configuration/c_storage.cpp create mode 100644 examples/truck/multi_configuration/main.go.in create mode 100644 examples/truck/multi_configuration/owning.cpp create mode 100644 examples/truck/multi_configuration/plain.c create mode 100644 examples/truck/multi_configuration/python.py create mode 100644 examples/truck/multi_configuration/rev_b/configuration.brd create mode 100644 examples/truck/multi_configuration/rev_b/mirror_fold.brd create mode 100644 examples/truck/multi_configuration/run.py create mode 100644 tests/fixtures/name_prefix/unprefixed_sha256.json create mode 100644 tests/tools/name_prefix_cmake_test.py create mode 100644 tests/tools/name_prefix_test.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 028ddf1..3958262 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -239,6 +239,31 @@ jobs: | tee storage-policy-report.md >> "$GITHUB_STEP_SUMMARY"; cat storage-policy-report.md + - name: Compare explicit naming prefix + shell: bash + run: >- + set -o pipefail; + docker compose run --rm dev sh -ec ' + for config in Default MinSizeRel Debug; do + for side in plain prefixed; do + prefix=OFF; if [ "$side" = prefixed ]; then prefix=ON; fi; + build_type=""; if [ "$config" != Default ]; then build_type="-DCMAKE_BUILD_TYPE=$config"; fi; + cmake -S cortex_m -B "build/name-prefix/$side-$config" $build_type + -DCMAKE_TOOLCHAIN_FILE="$(pwd)/cmake/toolchains/arm-cortex-m4.cmake" + -DQUARRY_HOST_SCHEMA_COMPILER="$(pwd)/build/docker-debug/tools/quarry-schema-compiler" + -DQUARRY_RUNTIME_C_INCLUDE_DIR="$(pwd)/include" + -DQUARRY_RUNTIME_C_VERSION_HEADER_DIR="$(pwd)/build/docker-debug/generated" + -DQUARRY_SMOKE_PREFIXED=$prefix > /dev/null; + cmake --build "build/name-prefix/$side-$config" --parallel > /dev/null; + arm-none-eabi-nm -S --defined-only "build/name-prefix/$side-$config/quarry_cortex_m_smoke.elf" + > "build/name-prefix/$side-$config-symbols.txt"; + done; + python3 cortex_m/scripts/compare_machine_code.py + --base "build/name-prefix/plain-$config" --candidate "build/name-prefix/prefixed-$config" + --label "$config" --base-label "unprefixed" --candidate-label "name-prefix rev_a"; + done' | tee name-prefix-report.md >> "$GITHUB_STEP_SUMMARY"; + cat name-prefix-report.md + - name: Upload footprint report uses: actions/upload-artifact@v4 with: @@ -247,6 +272,8 @@ jobs: cortex_m/build/footprint*.json machine-code-report.md storage-policy-report.md + name-prefix-report.md + build/name-prefix/*-symbols.txt coverage: name: Coverage baseline diff --git a/cmake/QuarryGenerate.cmake b/cmake/QuarryGenerate.cmake index 9567df6..523a298 100644 --- a/cmake/QuarryGenerate.cmake +++ b/cmake/QuarryGenerate.cmake @@ -226,7 +226,7 @@ endfunction() function(_quarry_generate_parse_arguments) set(_keywords SCHEMA OUTPUT_DIR OUT_FILES ROOT_FILE_STEM FILE_EXTENSION SCHEMA_COMPILER - GENERATE) + GENERATE NAME_PREFIX SCHEMA_ID_VARIABLE) set(_pending_keyword) foreach(_arg IN LISTS ARGN) @@ -294,10 +294,13 @@ function(_quarry_generate_validate_outputs output_dir schema outputs) endfunction() function(_quarry_generate_query_outputs compiler output_dir schema root_file_stem file_extension - generate output_variable) + generate name_prefix output_variable) set(_quarry_list_args --list-outputs --output-directory "${output_dir}") + if(NOT "${name_prefix}" STREQUAL "") + list(APPEND _quarry_list_args --name-prefix "${name_prefix}") + endif() if(NOT "${generate}" STREQUAL "") list(APPEND _quarry_list_args --generate "${generate}") endif() @@ -349,6 +352,21 @@ endfunction() # Query the compiler's authoritative resolved import graph, rather than parsing # schema syntax in CMake. This includes configuration roots and unused imports. +function(_quarry_generate_query_schema_id compiler schema output_variable) + execute_process(COMMAND "${compiler}" --print-schema-id "${schema}" + RESULT_VARIABLE _result OUTPUT_VARIABLE _stdout ERROR_VARIABLE _stderr) + if(NOT _result EQUAL 0) + _quarry_generate_fail("failed to query schema_id for schema '${schema}' with compiler " + "'${compiler}' (exit ${_result}):\n${_stdout}${_stderr}") + endif() + string(REGEX REPLACE "\r?\n$" "" _schema_id "${_stdout}") + string(LENGTH "${_schema_id}" _length) + if(NOT _length EQUAL 32 OR NOT "${_schema_id}" MATCHES "^[0-9a-f]+$") + _quarry_generate_fail("compiler returned malformed schema_id for '${schema}': ${_stdout}") + endif() + set(${output_variable} "${_schema_id}" PARENT_SCOPE) +endfunction() + function(_quarry_generate_query_inputs compiler schema output_variable) execute_process( COMMAND "${compiler}" --list-inputs "${schema}" @@ -463,6 +481,7 @@ function(_quarry_generate_verify_output_inventory) if(DEFINED QUARRY_VERIFY_FILE_EXTENSION) set(_file_extension "${QUARRY_VERIFY_FILE_EXTENSION}") endif() + set(_name_prefix "${QUARRY_VERIFY_NAME_PREFIX}") set(_generate) if(DEFINED QUARRY_VERIFY_GENERATE) set(_generate "${QUARRY_VERIFY_GENERATE}") @@ -482,6 +501,7 @@ function(_quarry_generate_verify_output_inventory) "${_root_file_stem}" "${_file_extension}" "${_generate}" + "${_name_prefix}" _current_outputs) set(_expected_outputs ${QUARRY_VERIFY_EXPECTED_OUTPUTS}) @@ -602,10 +622,24 @@ function(quarry_generate_cpp) list(APPEND _quarry_generate_args --generate "${QUARRY_GENERATE_GENERATE}") endif() + set(_quarry_name_prefix) + if(DEFINED QUARRY_GENERATE_NAME_PREFIX) + _quarry_generate_reject_unsafe("${QUARRY_GENERATE_NAME_PREFIX}" "NAME_PREFIX") + _quarry_generate_reject_genex("${QUARRY_GENERATE_NAME_PREFIX}" "NAME_PREFIX") + set(_quarry_name_prefix "${QUARRY_GENERATE_NAME_PREFIX}") + list(APPEND _quarry_generate_args --name-prefix "${_quarry_name_prefix}") + endif() + if(DEFINED QUARRY_GENERATE_SCHEMA_ID_VARIABLE) + _quarry_generate_reject_unsafe("${QUARRY_GENERATE_SCHEMA_ID_VARIABLE}" "SCHEMA_ID_VARIABLE") + _quarry_generate_reject_genex("${QUARRY_GENERATE_SCHEMA_ID_VARIABLE}" "SCHEMA_ID_VARIABLE") + # Deliberately do not pass prefix or --generate: query the complete root. + _quarry_generate_query_schema_id("${_quarry_compiler}" "${_quarry_schema}" _quarry_schema_id) + endif() + _quarry_generate_query_outputs("${_quarry_compiler}" "${_quarry_output_dir}" "${_quarry_schema}" "${_quarry_root_file_stem}" "${_quarry_file_extension}" - "${_quarry_generate_selection}" _quarry_outputs) + "${_quarry_generate_selection}" "${_quarry_name_prefix}" _quarry_outputs) _quarry_generate_register_outputs("${_quarry_schema}" "${_quarry_outputs}") _quarry_generate_query_inputs("${_quarry_compiler}" "${_quarry_schema}" _quarry_inputs) @@ -627,6 +661,7 @@ function(quarry_generate_cpp) "-DQUARRY_VERIFY_ROOT_FILE_STEM=${_quarry_root_file_stem}" "-DQUARRY_VERIFY_FILE_EXTENSION=${_quarry_file_extension}" "-DQUARRY_VERIFY_GENERATE=${_quarry_generate_selection}" + "-DQUARRY_VERIFY_NAME_PREFIX=${_quarry_name_prefix}" -P "${_quarry_module}" COMMAND "${CMAKE_COMMAND}" -E make_directory "${_quarry_output_dir}" COMMAND "${_quarry_compiler}" ${_quarry_generate_args} @@ -640,6 +675,9 @@ function(quarry_generate_cpp) VERBATIM) set_source_files_properties(${_quarry_outputs} PROPERTIES GENERATED TRUE) + if(DEFINED QUARRY_GENERATE_SCHEMA_ID_VARIABLE) + set("${QUARRY_GENERATE_SCHEMA_ID_VARIABLE}" "${_quarry_schema_id}" PARENT_SCOPE) + endif() set(${QUARRY_GENERATE_OUT_FILES} "${_quarry_outputs}" PARENT_SCOPE) endfunction() diff --git a/compiler/backend/README.md b/compiler/backend/README.md index e3f4c39..0be67bb 100644 --- a/compiler/backend/README.md +++ b/compiler/backend/README.md @@ -306,3 +306,13 @@ without a layout compute it themselves. This layer must not parse source, resolve names, perform semantic analysis, compute layout, or assign compiler-managed identifiers. + +## Explicit naming prefix + +`CodegenOptions::name_prefix` (CLI `--name-prefix`) is optional and empty by +default. It projects generated source names and output paths without modifying +Schema IR, canonical FQNs, record IDs or configuration identity. Selection and +storage-policy options still use canonical namespace names. Unprefixed output +is pinned byte for byte in `tests/fixtures/name_prefix/unprefixed_sha256.json`. +See the [source naming contract](../../tools/README.md#deliberate-source-naming-isolation) +and [multi-configuration example](../../examples/truck/multi_configuration/README.md). diff --git a/compiler/backend/backend.cpp b/compiler/backend/backend.cpp index f37e630..46ae949 100644 --- a/compiler/backend/backend.cpp +++ b/compiler/backend/backend.cpp @@ -4,6 +4,7 @@ #include "compiler/diagnostics/diagnostic.hpp" #include "compiler/layout/layout.hpp" #include "compiler/support/generated_code_identity.hpp" +#include "compiler/support/generated_names.hpp" #include "compiler/support/namespace_macro.hpp" #include @@ -39,6 +40,7 @@ struct NamedTypeInfo { }; struct TypeCatalog { + std::string name_prefix; std::map named_types; // Include path of every namespace that declares a record or enum, to the // namespace FQN, so a header can name the identity of each generated @@ -140,6 +142,7 @@ struct DeclarationPlan { struct NamespacePlan { const ::quarry::schema_ir::NamespaceIR* namespace_ir = nullptr; std::string fqn; + std::string name_prefix; std::string file_path; std::string include_path; bool emits_file = false; @@ -201,9 +204,11 @@ struct OutputSelection { [[nodiscard]] std::string file_stem_for_namespace(const CodegenOptions& options, std::string_view namespace_fqn) { if (namespace_fqn.empty()) { - return options.root_file_stem + options.file_extension; + return support::named_path(options.name_prefix, + options.root_file_stem + options.file_extension); } - return join_path(namespace_parts(namespace_fqn)) + options.file_extension; + return support::named_path(options.name_prefix, + join_path(namespace_parts(namespace_fqn)) + options.file_extension); } [[nodiscard]] std::string file_path_for_namespace(const CodegenOptions& options, @@ -220,9 +225,11 @@ struct OutputSelection { return file_stem_for_namespace(options, namespace_fqn); } -[[nodiscard]] std::string cpp_qualified_name(std::string_view namespace_fqn, - std::string_view name) { +[[nodiscard]] std::string cpp_qualified_name(std::string_view namespace_fqn, std::string_view name, + std::string_view name_prefix = {}) { std::string cpp_name = "::"; + if (!name_prefix.empty()) + cpp_name += std::string(name_prefix) + "::"; if (namespace_fqn.empty()) { cpp_name.append(name); return cpp_name; @@ -237,8 +244,11 @@ struct OutputSelection { return cpp_name; } -[[nodiscard]] std::string cpp_namespace_prefix(std::string_view namespace_fqn) { +[[nodiscard]] std::string cpp_namespace_prefix(std::string_view namespace_fqn, + std::string_view name_prefix = {}) { std::string prefix = "::"; + if (!name_prefix.empty()) + prefix += std::string(name_prefix) + "::"; if (namespace_fqn.empty()) { return prefix; } @@ -266,9 +276,9 @@ struct OutputSelection { // Encoded namespace body (#117). Empty when the name is not a namespace FQN; // plan validation rejects that before a header is written. -[[nodiscard]] std::string namespace_macro_body(std::string_view namespace_fqn) { - const std::optional encoded = support::encode_namespace_macro(namespace_fqn); - return encoded.has_value() ? *encoded : std::string(); +[[nodiscard]] std::string namespace_macro_body(std::string_view namespace_fqn, + std::string_view name_prefix = {}) { + return support::named_macro_body(name_prefix, namespace_fqn); } // Prefix of the configuration-identity and generated-code identity macros of @@ -276,9 +286,10 @@ struct OutputSelection { // from the namespace FQN by support::encode_namespace_macro, never from the // output path, so --root-file-stem and --file-extension do not change it. // The root namespace uses the same prefix with the root body. -[[nodiscard]] std::string generated_code_identity_macro_prefix(std::string_view namespace_fqn) { +[[nodiscard]] std::string generated_code_identity_macro_prefix(std::string_view namespace_fqn, + std::string_view name_prefix = {}) { return std::string(support::kCppOwningNamespaceMacroPrefix) + - namespace_macro_body(namespace_fqn); + namespace_macro_body(namespace_fqn, name_prefix); } [[nodiscard]] std::string namespace_display_name(std::string_view namespace_fqn) { @@ -376,9 +387,8 @@ constexpr std::string_view kReservedGeneratedNamespacePrefix = "quarry_gen_"; } [[nodiscard]] bool emits_records(const NamespacePlan& plan) { - return std::any_of(plan.declarations.begin(), plan.declarations.end(), [](const auto& decl) { - return decl.kind == DeclarationPlan::Kind::Record; - }); + return std::any_of(plan.declarations.begin(), plan.declarations.end(), + [](const auto& decl) { return decl.kind == DeclarationPlan::Kind::Record; }); } [[nodiscard]] std::string field_member_name(std::string_view field_name) { @@ -547,12 +557,10 @@ void merge_type_requirements(TypeLoweringResult& target, const TypeLoweringResul [[nodiscard]] const NamedTypeInfo* lookup_named_type(const TypeCatalog& catalog, std::uint64_t ir_id, std::string& error_message); -[[nodiscard]] TypeLoweringResult -lower_field_type(const ::quarry::schema_ir::FieldType& field_type, - const std::string& current_namespace_fqn, - const std::map& local_declaration_ids, - const TypeCatalog& catalog, const OutputSelection* output_selection, - std::string& error_message) { +[[nodiscard]] TypeLoweringResult lower_field_type( + const ::quarry::schema_ir::FieldType& field_type, const std::string& current_namespace_fqn, + const std::map& local_declaration_ids, const TypeCatalog& catalog, + const OutputSelection* output_selection, std::string& error_message) { TypeLoweringResult result; switch (field_type.kind_case()) { @@ -697,7 +705,8 @@ lower_runtime_field_encoding(const ::quarry::schema_ir::FieldType& field_type, type_it->second.record_ir == nullptr) { return encoding; } - const std::string namespace_prefix = cpp_namespace_prefix(type_it->second.namespace_fqn); + const std::string namespace_prefix = + cpp_namespace_prefix(type_it->second.namespace_fqn, catalog.name_prefix); encoding.record_encoding = RuntimeRecordEncoding{ .encode_function = namespace_prefix + "encode_result", .decode_function = @@ -749,7 +758,8 @@ lower_runtime_field_encoding(const ::quarry::schema_ir::FieldType& field_type, type_it->second.record_ir == nullptr) { return encoding; } - const std::string namespace_prefix = cpp_namespace_prefix(type_it->second.namespace_fqn); + const std::string namespace_prefix = + cpp_namespace_prefix(type_it->second.namespace_fqn, catalog.name_prefix); array_encoding.record_encoding = RuntimeRecordEncoding{ .encode_function = namespace_prefix + "encode_result", .decode_function = @@ -926,37 +936,39 @@ lookup_named_type(const TypeCatalog& catalog, std::uint64_t ir_id, std::string& return true; } -void collect_named_types(const ::quarry::schema_ir::NamespaceIR& ns, - const CodegenOptions& options, TypeCatalog& catalog) { +void collect_named_types(const ::quarry::schema_ir::NamespaceIR& ns, const CodegenOptions& options, + TypeCatalog& catalog) { const std::string file_path = file_path_for_namespace(options, ns.fqn()); const std::string include_path = include_path_for_namespace(options, ns.fqn()); for (int index = 0; index < ns.records_size(); ++index) { const ::quarry::schema_ir::RecordIR& record = ns.records(index); - catalog.named_types.emplace(record.ir_id(), - NamedTypeInfo{ - .kind = NamedTypeInfo::Kind::Record, - .namespace_fqn = ns.fqn(), - .file_path = file_path, - .include_path = include_path, - .cpp_name = cpp_qualified_name(ns.fqn(), record.name()), - .record_ir = &record, - .enum_ir = nullptr, - }); + catalog.named_types.emplace( + record.ir_id(), + NamedTypeInfo{ + .kind = NamedTypeInfo::Kind::Record, + .namespace_fqn = ns.fqn(), + .file_path = file_path, + .include_path = include_path, + .cpp_name = cpp_qualified_name(ns.fqn(), record.name(), options.name_prefix), + .record_ir = &record, + .enum_ir = nullptr, + }); } for (int index = 0; index < ns.enums_size(); ++index) { const ::quarry::schema_ir::EnumIR& enum_ir = ns.enums(index); - catalog.named_types.emplace(enum_ir.ir_id(), - NamedTypeInfo{ - .kind = NamedTypeInfo::Kind::Enum, - .namespace_fqn = ns.fqn(), - .file_path = file_path, - .include_path = include_path, - .cpp_name = cpp_qualified_name(ns.fqn(), enum_ir.name()), - .record_ir = nullptr, - .enum_ir = &enum_ir, - }); + catalog.named_types.emplace( + enum_ir.ir_id(), + NamedTypeInfo{ + .kind = NamedTypeInfo::Kind::Enum, + .namespace_fqn = ns.fqn(), + .file_path = file_path, + .include_path = include_path, + .cpp_name = cpp_qualified_name(ns.fqn(), enum_ir.name(), options.name_prefix), + .record_ir = nullptr, + .enum_ir = &enum_ir, + }); } if (ns.records_size() > 0 || ns.enums_size() > 0) { @@ -973,8 +985,16 @@ void collect_named_types(const ::quarry::schema_ir::NamespaceIR& ns, const ::quarry::compiler::layout::LayoutModel& layout_model, const OutputSelection* output_selection, NamespacePlan& plan, std::string& error_message) { + if (!support::valid_prefix_for_namespace(options.name_prefix, ns.fqn())) { + error_message = + "invalid or conflicting --name-prefix '" + options.name_prefix + + "': use an unreserved identifier distinct from every namespace's first segment"; + return false; + } + plan.namespace_ir = &ns; plan.fqn = ns.fqn(); + plan.name_prefix = options.name_prefix; plan.file_path = file_path_for_namespace(options, ns.fqn()); plan.include_path = file_stem_for_namespace(options, ns.fqn()); plan.emits_file = ns.records_size() > 0 || ns.enums_size() > 0; @@ -1042,29 +1062,28 @@ void collect_named_types(const ::quarry::schema_ir::NamespaceIR& ns, record_plan.brf_layout->fields.size() != static_cast(record_plan.record->fields_size())) { error_message = "backend codegen could not find canonical BRF v2 layout for '" + - record_plan.record->fqn() + "'"; + record_plan.record->fqn() + "'"; return false; } record_plan.fields.reserve(static_cast(record_plan.record->fields_size())); for (int field_index = 0; field_index < record_plan.record->fields_size(); ++field_index) { - const ::quarry::schema_ir::FieldIR& field = - record_plan.record->fields(field_index); - const TypeLoweringResult lowered = lower_field_type( - field.type(), ns.fqn(), local_declaration_ids, catalog, output_selection, - error_message); + const ::quarry::schema_ir::FieldIR& field = record_plan.record->fields(field_index); + const TypeLoweringResult lowered = + lower_field_type(field.type(), ns.fqn(), local_declaration_ids, catalog, + output_selection, error_message); if (!error_message.empty()) { return false; } const RuntimeFieldEncoding runtime_encoding = lower_runtime_field_encoding(field.type(), catalog); - record_plan.fields.push_back( - FieldPlan{.field = &field, - .brf_layout = &record_plan.brf_layout->fields[ - static_cast(field_index)], - .name = field.name(), - .cpp_type = lowered.cpp_type, - .runtime_encoding = runtime_encoding}); + record_plan.fields.push_back(FieldPlan{ + .field = &field, + .brf_layout = + &record_plan.brf_layout->fields[static_cast(field_index)], + .name = field.name(), + .cpp_type = lowered.cpp_type, + .runtime_encoding = runtime_encoding}); plan.standard_includes.insert(lowered.standard_includes.begin(), lowered.standard_includes.end()); plan.includes.insert(lowered.generated_includes.begin(), @@ -1092,8 +1111,7 @@ void collect_named_types(const ::quarry::schema_ir::NamespaceIR& ns, for (int index = 0; index < ns.namespaces_size(); ++index) { NamespacePlan child_plan; if (!analyze_namespace(ns.namespaces(index), options, catalog, layout_model, - output_selection, - child_plan, error_message)) { + output_selection, child_plan, error_message)) { return false; } plan.children.push_back(std::move(child_plan)); @@ -1150,9 +1168,10 @@ void collect_planned_files(const NamespacePlan& plan, RenderGenerationPlan& gene file.namespace_plan->include_path + ")"; return false; } - const std::string identity_prefix = - generated_code_identity_macro_prefix(file.namespace_plan->fqn); - if (namespace_macro_body(file.namespace_plan->fqn).empty() || + const std::string identity_prefix = generated_code_identity_macro_prefix( + file.namespace_plan->fqn, file.namespace_plan->name_prefix); + if (namespace_macro_body(file.namespace_plan->fqn, file.namespace_plan->name_prefix) + .empty() || !support::is_unreserved_macro_identifier(identity_prefix + "_CODE_ID_FORMAT") || !support::is_unreserved_macro_identifier(identity_prefix + "_SCHEMA_ID_ALGORITHM")) { error_message = "backend codegen: namespace '" + @@ -1191,12 +1210,10 @@ void collect_planned_files(const NamespacePlan& plan, RenderGenerationPlan& gene const std::size_t dependency_index = it->second; if (state[dependency_index] == VisitState::Visiting) { - error_message = "backend codegen detected a namespace cycle between '" + - generation_plan.files[index].file.generated_include_path + - "' and '" + - generation_plan.files[dependency_index].file - .generated_include_path + - "'"; + error_message = + "backend codegen detected a namespace cycle between '" + + generation_plan.files[index].file.generated_include_path + "' and '" + + generation_plan.files[dependency_index].file.generated_include_path + "'"; return false; } if (state[dependency_index] == VisitState::Unvisited) { @@ -1220,8 +1237,8 @@ void collect_planned_files(const NamespacePlan& plan, RenderGenerationPlan& gene return true; } -[[nodiscard]] GenerationPlan to_public_generation_plan( - const RenderGenerationPlan& render_generation_plan) { +[[nodiscard]] GenerationPlan +to_public_generation_plan(const RenderGenerationPlan& render_generation_plan) { GenerationPlan generation_plan; generation_plan.files.reserve(render_generation_plan.files.size()); for (const PlannedRenderFile& file : render_generation_plan.files) { @@ -1236,6 +1253,7 @@ void collect_planned_files(const NamespacePlan& plan, RenderGenerationPlan& gene const output_planning::OutputPlan* output_plan, NamespacePlan& root_plan, RenderGenerationPlan& generation_plan, std::string& error_message) { TypeCatalog catalog; + catalog.name_prefix = options.name_prefix; collect_named_types(schema_ir.root_namespace(), options, catalog); OutputSelection selection; @@ -1499,8 +1517,8 @@ void render_unsupported_present_field_encoding(const FieldPlan& field, std::size const unsigned int field_index = static_cast(field.field->field_index()); stream << indent(indent_level) << "if (value.has_" << field.name << "()) {\n"; render_encode_failure_return(stream, indent_level + 1, - "::quarry::runtime::EncodeError::unsupported_field_type", field_index, - "std::nullopt"); + "::quarry::runtime::EncodeError::unsupported_field_type", + field_index, "std::nullopt"); stream << indent(indent_level) << "}\n"; } @@ -1512,12 +1530,13 @@ void render_scalar_field_encoding(const FieldPlan& field, std::size_t indent_lev stream << indent(indent_level + 1) << "std::vector field_bytes;\n"; stream << indent(indent_level + 1) << "if (!::quarry::runtime::" << append_function << "(field_bytes, *value." << field.name << "())) {\n"; - render_encode_failure_return(stream, indent_level + 2, "::quarry::runtime::EncodeError::overflow", - field_index, "std::nullopt"); + render_encode_failure_return(stream, indent_level + 2, + "::quarry::runtime::EncodeError::overflow", field_index, + "std::nullopt"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(field_bytes),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; @@ -1529,8 +1548,9 @@ void render_enum_field_encoding(const FieldPlan& field, const RuntimeEnumEncodin const std::string unsigned_type = enum_unsigned_type(enum_encoding.width_bytes); const unsigned int field_index = static_cast(field.field->field_index()); stream << indent(indent_level) << "if (value.has_" << field.name << "()) {\n"; - stream << indent(indent_level + 1) << "const auto enum_numeric = static_cast(*value." - << field.name << "());\n"; + stream << indent(indent_level + 1) + << "const auto enum_numeric = static_cast(*value." << field.name + << "());\n"; stream << indent(indent_level + 1) << "if (!("; for (std::size_t index = 0; index < enum_encoding.valid_values.size(); ++index) { if (index > 0) { @@ -1550,8 +1570,8 @@ void render_enum_field_encoding(const FieldPlan& field, const RuntimeEnumEncodin stream << indent(indent_level + 1) << "::quarry::runtime::" << append_function << "(field_bytes, static_cast<" << unsigned_type << ">(enum_numeric));\n"; stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(field_bytes),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; @@ -1560,7 +1580,8 @@ void render_enum_field_encoding(const FieldPlan& field, const RuntimeEnumEncodin void render_string_field_encoding(const FieldPlan& field, std::size_t indent_level, std::ostringstream& stream) { const unsigned int field_index = static_cast(field.field->field_index()); - stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." << field.name << "()->empty()) {\n"; + stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." + << field.name << "()->empty()) {\n"; stream << indent(indent_level + 1) << "if (value." << field.name << "()->size() > " << field.runtime_encoding.max_bytes << "U) {\n"; render_encode_failure_return(stream, indent_level + 2, @@ -1569,15 +1590,15 @@ void render_string_field_encoding(const FieldPlan& field, std::size_t indent_lev stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "std::vector field_bytes;\n"; stream << indent(indent_level + 1) - << "if (!::quarry::runtime::append_string_utf8(field_bytes, *value." - << field.name << "())) {\n"; + << "if (!::quarry::runtime::append_string_utf8(field_bytes, *value." << field.name + << "())) {\n"; render_encode_failure_return(stream, indent_level + 2, "::quarry::runtime::EncodeError::invalid_utf8", field_index, "std::nullopt"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(field_bytes),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; @@ -1586,7 +1607,8 @@ void render_string_field_encoding(const FieldPlan& field, std::size_t indent_lev void render_bytes_field_encoding(const FieldPlan& field, std::size_t indent_level, std::ostringstream& stream) { const unsigned int field_index = static_cast(field.field->field_index()); - stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." << field.name << "()->empty()) {\n"; + stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." + << field.name << "()->empty()) {\n"; stream << indent(indent_level + 1) << "if (value." << field.name << "()->size() > " << field.runtime_encoding.max_bytes << "U) {\n"; render_encode_failure_return(stream, indent_level + 2, @@ -1598,14 +1620,15 @@ void render_bytes_field_encoding(const FieldPlan& field, std::size_t indent_leve << "std::span(value." << field.name << "()->data(), value." << field.name << "()->size()));\n"; stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(field_bytes),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; } -void render_record_field_encoding(const FieldPlan& field, const RuntimeRecordEncoding& record_encoding, +void render_record_field_encoding(const FieldPlan& field, + const RuntimeRecordEncoding& record_encoding, std::size_t indent_level, std::ostringstream& stream) { const unsigned int field_index = static_cast(field.field->field_index()); stream << indent(indent_level) << "if (value.has_" << field.name << "()) {\n"; @@ -1622,8 +1645,8 @@ void render_record_field_encoding(const FieldPlan& field, const RuntimeRecordEnc << "field_bytes.error, std::move(nested_path));\n"; stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(*field_bytes.value),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; @@ -1632,7 +1655,8 @@ void render_record_field_encoding(const FieldPlan& field, const RuntimeRecordEnc void render_array_field_encoding(const FieldPlan& field, const RuntimeArrayEncoding& array_encoding, std::size_t indent_level, std::ostringstream& stream) { const unsigned int field_index = static_cast(field.field->field_index()); - stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." << field.name << "()->empty()) {\n"; + stream << indent(indent_level) << "if (value.has_" << field.name << "() && !value." + << field.name << "()->empty()) {\n"; stream << indent(indent_level + 1) << "if (value." << field.name << "()->size() > " << array_encoding.max_elements << "U) {\n"; render_encode_failure_return(stream, indent_level + 2, @@ -1650,8 +1674,8 @@ void render_array_field_encoding(const FieldPlan& field, const RuntimeArrayEncod field.brf_layout->type.element_type->classification == ::quarry::compiler::layout::RecordClassification::FixedSize; render_array_encode_loop_open(stream, indent_level + 1, field.name); - stream << indent(indent_level + 2) << "auto element_bytes = " - << record_encoding.encode_function << "(element);\n"; + stream << indent(indent_level + 2) + << "auto element_bytes = " << record_encoding.encode_function << "(element);\n"; stream << indent(indent_level + 2) << "if (!element_bytes.has_value()) {\n"; stream << indent(indent_level + 3) << "auto nested_path = std::move(element_bytes.path);\n"; stream << indent(indent_level + 3) @@ -1665,12 +1689,10 @@ void render_array_field_encoding(const FieldPlan& field, const RuntimeArrayEncod << "element_bytes.error, std::move(nested_path));\n"; stream << indent(indent_level + 2) << "}\n"; if (!fixed_record_elements) { - stream << indent(indent_level + 2) - << "::quarry::runtime::append_varuint(field_bytes, " + stream << indent(indent_level + 2) << "::quarry::runtime::append_varuint(field_bytes, " << "element_bytes.value->size());\n"; } - stream << indent(indent_level + 2) - << "::quarry::runtime::append_bytes(field_bytes, " + stream << indent(indent_level + 2) << "::quarry::runtime::append_bytes(field_bytes, " << "std::span(element_bytes.value->data(), " << "element_bytes.value->size()));\n"; stream << indent(indent_level + 1) << "}\n"; @@ -1723,8 +1745,8 @@ void render_array_field_encoding(const FieldPlan& field, const RuntimeArrayEncod } stream << ")) {\n"; render_encode_failure_return(stream, indent_level + 3, - "::quarry::runtime::EncodeError::unknown_enum_value", field_index, - "static_cast(element_index)"); + "::quarry::runtime::EncodeError::unknown_enum_value", + field_index, "static_cast(element_index)"); stream << indent(indent_level + 2) << "}\n"; stream << indent(indent_level + 2) << "::quarry::runtime::" << append_function << "(field_bytes, static_cast<" << unsigned_type << ">(enum_numeric));\n"; @@ -1742,8 +1764,8 @@ void render_array_field_encoding(const FieldPlan& field, const RuntimeArrayEncod } stream << indent(indent_level + 1) << "fields.push_back(::quarry::runtime::FieldBytes{\n"; - stream << indent(indent_level + 2) << ".field_index = " - << static_cast(field.field->field_index()) << "U,\n"; + stream << indent(indent_level + 2) + << ".field_index = " << static_cast(field.field->field_index()) << "U,\n"; stream << indent(indent_level + 2) << ".bytes = std::move(field_bytes),\n"; stream << indent(indent_level + 1) << "});\n"; stream << indent(indent_level) << "}\n"; @@ -1797,8 +1819,7 @@ void render_record_encoder_definition(const RecordPlan& record_plan, std::size_t } else { stream << indent(indent_level + 1) << "(void)value;\n"; } - stream << indent(indent_level + 1) - << "return ::quarry::runtime::encode_brf_v2_record_result(" + stream << indent(indent_level + 1) << "return ::quarry::runtime::encode_brf_v2_record_result(" << "brf_v2_layout_" << record_name << "(), fields);\n"; stream << indent(indent_level) << "}\n"; stream << "\n\n"; @@ -1833,7 +1854,8 @@ void render_decode_failure_return(std::ostringstream& stream, std::size_t indent } void render_unsupported_present_field_decoding(const FieldPlan& field, std::string_view record_name, - std::size_t indent_level, std::ostringstream& stream) { + std::size_t indent_level, + std::ostringstream& stream) { const unsigned int field_index = static_cast(field.field->field_index()); stream << indent(indent_level) << "if (const auto* field = " << "::quarry::runtime::find_field(*parsed.record, " << field_index @@ -1851,11 +1873,11 @@ void render_scalar_field_decoding(const FieldPlan& field, std::string_view recor stream << indent(indent_level) << "if (const auto* field = " << "::quarry::runtime::find_field(*parsed.record, " << field_index << "U); field != nullptr) {\n"; - stream << indent(indent_level + 1) << "const auto decoded = ::quarry::runtime::" - << read_function << "(field->bytes);\n"; + stream << indent(indent_level + 1) + << "const auto decoded = ::quarry::runtime::" << read_function << "(field->bytes);\n"; stream << indent(indent_level + 1) << "if (!decoded.value.has_value()) {\n"; - render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", field_index, - "std::nullopt", "field->field_offset"); + render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", + field_index, "std::nullopt", "field->field_offset"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "if (!builder.set_" << field.name << "(*decoded.value)) {\n"; @@ -1874,11 +1896,11 @@ void render_enum_field_decoding(const FieldPlan& field, const RuntimeEnumEncodin stream << indent(indent_level) << "if (const auto* field = " << "::quarry::runtime::find_field(*parsed.record, " << field_index << "U); field != nullptr) {\n"; - stream << indent(indent_level + 1) << "const auto decoded = ::quarry::runtime::" - << read_function << "(field->bytes);\n"; + stream << indent(indent_level + 1) + << "const auto decoded = ::quarry::runtime::" << read_function << "(field->bytes);\n"; stream << indent(indent_level + 1) << "if (!decoded.value.has_value()) {\n"; - render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", field_index, - "std::nullopt", "field->field_offset"); + render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", + field_index, "std::nullopt", "field->field_offset"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "const auto enum_numeric = static_cast(*decoded.value);\n"; @@ -1897,8 +1919,8 @@ void render_enum_field_decoding(const FieldPlan& field, const RuntimeEnumEncodin "::quarry::runtime::DecodeError::unknown_enum_value", field_index, "std::nullopt", "field->field_offset"); stream << indent(indent_level + 1) << "}\n"; - stream << indent(indent_level + 1) << "if (!builder.set_" << field.name - << "(static_cast<" << enum_encoding.cpp_type << ">(enum_numeric))) {\n"; + stream << indent(indent_level + 1) << "if (!builder.set_" << field.name << "(static_cast<" + << enum_encoding.cpp_type << ">(enum_numeric))) {\n"; render_decode_failure_return(stream, indent_level + 2, record_name, "::quarry::runtime::DecodeError::bounds_exceeded", field_index, "std::nullopt", "field->field_offset"); @@ -1921,8 +1943,8 @@ void render_string_field_decoding(const FieldPlan& field, std::string_view recor stream << indent(indent_level + 1) << "const auto decoded = ::quarry::runtime::read_string_utf8(field->bytes);\n"; stream << indent(indent_level + 1) << "if (!decoded.value.has_value()) {\n"; - render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", field_index, - "std::nullopt", "field->field_offset"); + render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", + field_index, "std::nullopt", "field->field_offset"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "if (!builder.set_" << field.name << "(*decoded.value)) {\n"; @@ -1948,8 +1970,8 @@ void render_bytes_field_decoding(const FieldPlan& field, std::string_view record stream << indent(indent_level + 1) << "const auto decoded = ::quarry::runtime::read_bytes(field->bytes);\n"; stream << indent(indent_level + 1) << "if (!decoded.value.has_value()) {\n"; - render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", field_index, - "std::nullopt", "field->field_offset"); + render_decode_failure_return(stream, indent_level + 2, record_name, "decoded.error", + field_index, "std::nullopt", "field->field_offset"); stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "if (!builder.set_" << field.name << "(*decoded.value)) {\n"; @@ -1968,21 +1990,21 @@ void render_record_field_decoding(const FieldPlan& field, stream << indent(indent_level) << "if (const auto* field = " << "::quarry::runtime::find_field(*parsed.record, " << field_index << "U); field != nullptr) {\n"; - stream << indent(indent_level + 1) << "auto decoded = " - << record_encoding.decode_function << "(field->bytes);\n"; + stream << indent(indent_level + 1) << "auto decoded = " << record_encoding.decode_function + << "(field->bytes);\n"; stream << indent(indent_level + 1) << "if (!decoded.value.has_value()) {\n"; stream << indent(indent_level + 2) << "auto nested_path = std::move(decoded.path);\n"; stream << indent(indent_level + 2) << "nested_path.push_back(::quarry::runtime::PathElement{\n"; stream << indent(indent_level + 3) << ".field_index = " << field_index << "U,\n"; stream << indent(indent_level + 3) << ".array_index = std::nullopt,\n"; stream << indent(indent_level + 2) << "});\n"; - stream << indent(indent_level + 2) - << "const std::optional nested_offset = decoded.byte_offset.has_value()\n"; + stream + << indent(indent_level + 2) + << "const std::optional nested_offset = decoded.byte_offset.has_value()\n"; stream << indent(indent_level + 3) << "? std::optional(field->field_offset + *decoded.byte_offset)\n"; stream << indent(indent_level + 3) << ": std::nullopt;\n"; - stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" - << record_name + stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" << record_name << ">(decoded.error, std::move(nested_path), nested_offset);\n"; stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "if (!builder.set_" << field.name @@ -2012,9 +2034,9 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod const std::string read_function = is_enum_array ? enum_read_function(array_encoding.enum_encoding->width_bytes) : runtime_read_function(array_encoding.scalar); - const std::uint8_t element_width = - is_enum_array ? array_encoding.enum_encoding->width_bytes - : runtime_scalar_width_bytes(array_encoding.scalar); + const std::uint8_t element_width = is_enum_array + ? array_encoding.enum_encoding->width_bytes + : runtime_scalar_width_bytes(array_encoding.scalar); stream << indent(indent_level) << "if (const auto* field = " << "::quarry::runtime::find_field(*parsed.record, " << field_index << "U); field != nullptr) {\n"; @@ -2042,10 +2064,9 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod stream << indent(indent_level + 1) << "for (std::size_t index = 0U; index < element_count; ++index) {\n"; if (fixed_record_elements) { - stream << indent(indent_level + 2) << "const std::size_t element_length = " - << fixed_record_element_size << "U;\n"; stream << indent(indent_level + 2) - << "if (element_offset > field->bytes.size() || " + << "const std::size_t element_length = " << fixed_record_element_size << "U;\n"; + stream << indent(indent_level + 2) << "if (element_offset > field->bytes.size() || " << "element_length > field->bytes.size() - element_offset) {\n"; render_decode_failure_return(stream, indent_level + 3, record_name, "::quarry::runtime::DecodeError::invalid_field_length", @@ -2053,49 +2074,46 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod "field->field_offset + element_offset"); stream << indent(indent_level + 2) << "}\n"; } else { - stream << indent(indent_level + 2) << "const std::size_t element_length_start = " - << "element_offset;\n"; - stream << indent(indent_level + 2) - << "const auto decoded_length = ::quarry::runtime::read_varuint(" - << "field->bytes, element_offset);\n"; - stream << indent(indent_level + 2) - << "if (!decoded_length.value.has_value()) {\n"; - render_decode_failure_return(stream, indent_level + 3, record_name, "decoded_length.error", - field_index, "static_cast(index)", - "field->field_offset + element_length_start"); - stream << indent(indent_level + 2) << "}\n"; - stream << indent(indent_level + 2) - << "if (*decoded_length.value > field->bytes.size() - element_offset) {\n"; - render_decode_failure_return(stream, indent_level + 3, record_name, - "::quarry::runtime::DecodeError::invalid_field_length", - field_index, "static_cast(index)", - "field->field_offset + element_offset"); - stream << indent(indent_level + 2) << "}\n"; - stream << indent(indent_level + 2) - << "const auto element_length = static_cast(*decoded_length.value);\n"; + stream << indent(indent_level + 2) << "const std::size_t element_length_start = " + << "element_offset;\n"; + stream << indent(indent_level + 2) + << "const auto decoded_length = ::quarry::runtime::read_varuint(" + << "field->bytes, element_offset);\n"; + stream << indent(indent_level + 2) << "if (!decoded_length.value.has_value()) {\n"; + render_decode_failure_return( + stream, indent_level + 3, record_name, "decoded_length.error", field_index, + "static_cast(index)", "field->field_offset + element_length_start"); + stream << indent(indent_level + 2) << "}\n"; + stream << indent(indent_level + 2) + << "if (*decoded_length.value > field->bytes.size() - element_offset) {\n"; + render_decode_failure_return(stream, indent_level + 3, record_name, + "::quarry::runtime::DecodeError::invalid_field_length", + field_index, "static_cast(index)", + "field->field_offset + element_offset"); + stream << indent(indent_level + 2) << "}\n"; + stream + << indent(indent_level + 2) + << "const auto element_length = static_cast(*decoded_length.value);\n"; } stream << indent(indent_level + 2) << "const auto element_bytes = " << "field->bytes.subspan(element_offset, element_length);\n"; - stream << indent(indent_level + 2) << "auto decoded = " - << record_encoding.decode_function << "(element_bytes);\n"; + stream << indent(indent_level + 2) << "auto decoded = " << record_encoding.decode_function + << "(element_bytes);\n"; stream << indent(indent_level + 2) << "if (!decoded.value.has_value()) {\n"; stream << indent(indent_level + 3) << "auto nested_path = std::move(decoded.path);\n"; stream << indent(indent_level + 3) << "nested_path.push_back(::quarry::runtime::PathElement{\n"; stream << indent(indent_level + 4) << ".field_index = " << field_index << "U,\n"; - stream << indent(indent_level + 4) - << ".array_index = static_cast(index),\n"; + stream << indent(indent_level + 4) << ".array_index = static_cast(index),\n"; stream << indent(indent_level + 3) << "});\n"; - stream << indent(indent_level + 3) - << "const std::optional nested_offset = " + stream << indent(indent_level + 3) << "const std::optional nested_offset = " << "decoded.byte_offset.has_value()\n"; stream << indent(indent_level + 4) << "? std::optional(field->field_offset + element_offset + " << "*decoded.byte_offset)\n"; stream << indent(indent_level + 4) << ": std::nullopt;\n"; stream << indent(indent_level + 3) << "return ::quarry::runtime::decode_failure<" - << record_name - << ">(decoded.error, std::move(nested_path), nested_offset);\n"; + << record_name << ">(decoded.error, std::move(nested_path), nested_offset);\n"; stream << indent(indent_level + 2) << "}\n"; stream << indent(indent_level + 2) << "elements.push_back(*decoded.value);\n"; stream << indent(indent_level + 2) << "element_offset += element_length;\n"; @@ -2103,7 +2121,8 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod stream << indent(indent_level + 1) << "if (element_offset != field->bytes.size()) {\n"; render_decode_failure_return(stream, indent_level + 2, record_name, "::quarry::runtime::DecodeError::invalid_field_length", - field_index, "std::nullopt", "field->field_offset + element_offset"); + field_index, "std::nullopt", + "field->field_offset + element_offset"); stream << indent(indent_level + 1) << "}\n"; } else if (is_string_array || is_bytes_array) { stream << indent(indent_level + 1) @@ -2156,11 +2175,13 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod stream << indent(indent_level + 1) << "if (element_offset != field->bytes.size()) {\n"; render_decode_failure_return(stream, indent_level + 2, record_name, "::quarry::runtime::DecodeError::invalid_field_length", - field_index, "std::nullopt", "field->field_offset + element_offset"); + field_index, "std::nullopt", + "field->field_offset + element_offset"); stream << indent(indent_level + 1) << "}\n"; } else { - stream << indent(indent_level + 1) << "const std::size_t element_width = " - << static_cast(element_width) << "U;\n"; + stream << indent(indent_level + 1) + << "const std::size_t element_width = " << static_cast(element_width) + << "U;\n"; stream << indent(indent_level + 1) << "const std::size_t remaining_bytes = field->bytes.size() - element_offset;\n"; stream << indent(indent_level + 1) @@ -2172,8 +2193,9 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << "for (std::size_t index = 0U; index < element_count; ++index) {\n"; - stream << indent(indent_level + 2) << "const auto decoded = ::quarry::runtime::" - << read_function << "(field->bytes.subspan(element_offset, element_width));\n"; + stream << indent(indent_level + 2) + << "const auto decoded = ::quarry::runtime::" << read_function + << "(field->bytes.subspan(element_offset, element_width));\n"; stream << indent(indent_level + 2) << "if (!decoded.value.has_value()) {\n"; render_decode_failure_return(stream, indent_level + 3, record_name, "decoded.error", field_index, "static_cast(index)", @@ -2217,12 +2239,10 @@ void render_array_field_decoding(const FieldPlan& field, const RuntimeArrayEncod } void render_field_decoding(const FieldPlan& field, std::string_view record_name, - std::size_t indent_level, - std::ostringstream& stream) { + std::size_t indent_level, std::ostringstream& stream) { if (field.runtime_encoding.enum_encoding.has_value()) { render_enum_field_decoding(field, *field.runtime_encoding.enum_encoding, record_name, - indent_level, - stream); + indent_level, stream); return; } if (field.runtime_encoding.variable == RuntimeVariableEncoding::String) { @@ -2240,8 +2260,7 @@ void render_field_decoding(const FieldPlan& field, std::string_view record_name, } if (field.runtime_encoding.array_encoding.has_value()) { render_array_field_decoding(field, *field.runtime_encoding.array_encoding, record_name, - indent_level, - stream); + indent_level, stream); return; } if (field.runtime_encoding.scalar != RuntimeScalarEncoder::Unsupported) { @@ -2272,12 +2291,13 @@ void render_brf_v2_layout_definition(const RecordPlan& record_plan, std::size_t stream << indent(indent_level + 1) << "static const ::quarry::runtime::BrfV2RecordLayout layout{\n"; stream << indent(indent_level + 2) << ".record_id = " << layout.record_id << "U,\n"; - stream << indent(indent_level + 2) << ".presence_bitmap_size = " - << layout.presence_bitmap_size << "U,\n"; + stream << indent(indent_level + 2) << ".presence_bitmap_size = " << layout.presence_bitmap_size + << "U,\n"; stream << indent(indent_level + 2) << ".fixed_region_size = " << layout.fixed_region_size << "U,\n"; if (layout.complete_fixed_record_size.has_value()) { - stream << indent(indent_level + 2) << ".complete_fixed_record_size = std::optional{" + stream << indent(indent_level + 2) + << ".complete_fixed_record_size = std::optional{" << *layout.complete_fixed_record_size << "U},\n"; } else { stream << indent(indent_level + 2) << ".complete_fixed_record_size = std::nullopt,\n"; @@ -2289,8 +2309,8 @@ void render_brf_v2_layout_definition(const RecordPlan& record_plan, std::size_t << field.location.byte_offset << "U, " << static_cast(field.location.bit_offset) << "U, " << field.location.bit_width << "U, " << field.slot_size << "U, " - << "::quarry::runtime::BrfV2FieldStorage::" - << brf_v2_storage_name(field.storage) << ", {}},\n"; + << "::quarry::runtime::BrfV2FieldStorage::" << brf_v2_storage_name(field.storage) + << ", {}},\n"; } stream << indent(indent_level + 2) << "},\n"; stream << indent(indent_level + 1) << "};\n"; @@ -2307,21 +2327,21 @@ void render_record_decoder_definition(const RecordPlan& record_plan, std::size_t << "const auto parsed = ::quarry::runtime::parse_brf_v2_record(" << "input, brf_v2_layout_" << record_name << "());\n"; stream << indent(indent_level + 1) << "if (!parsed.record.has_value()) {\n"; - stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" - << record_name << ">(::quarry::runtime::brf_v2_decode_error(parsed.error), {}, " + stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" << record_name + << ">(::quarry::runtime::brf_v2_decode_error(parsed.error), {}, " << "parsed.offset);\n"; stream << indent(indent_level + 1) << "}\n"; - stream << indent(indent_level + 1) << "if (parsed.record->record_id != " - << record_plan.record->record_id() << "U) {\n"; - stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" - << record_name << ">(::quarry::runtime::DecodeError::unexpected_record_id, {}, 0U);\n"; + stream << indent(indent_level + 1) + << "if (parsed.record->record_id != " << record_plan.record->record_id() << "U) {\n"; + stream << indent(indent_level + 2) << "return ::quarry::runtime::decode_failure<" << record_name + << ">(::quarry::runtime::DecodeError::unexpected_record_id, {}, 0U);\n"; stream << indent(indent_level + 1) << "}\n"; stream << indent(indent_level + 1) << record_name << "Builder builder;\n"; for (const FieldPlan& field : record_plan.fields) { render_field_decoding(field, record_name, indent_level + 1, stream); } - stream << indent(indent_level + 1) << "return ::quarry::runtime::decoded_value<" - << record_name << ">(builder.build());\n"; + stream << indent(indent_level + 1) << "return ::quarry::runtime::decoded_value<" << record_name + << ">(builder.build());\n"; stream << indent(indent_level) << "}\n"; stream << "\n\n"; stream << indent(indent_level) << "inline std::optional<" << record_name << "> decode_" @@ -2406,8 +2426,9 @@ void render_identity_macros(std::ostringstream& stream, std::string_view namespa // Generated-code identity metadata (#111): this header's own identity, which // is not known until the header is hashed, so every form is a placeholder. void render_generated_code_identity_macros(std::ostringstream& stream, - std::string_view namespace_fqn) { - const std::string prefix = generated_code_identity_macro_prefix(namespace_fqn); + std::string_view namespace_fqn, + std::string_view name_prefix) { + const std::string prefix = generated_code_identity_macro_prefix(namespace_fqn, name_prefix); stream << "// Generated-code identity of this header: SHA-256 (truncated to 128 bits) of its\n"; stream << "// normalized generated definitions, its configuration and the identities of the\n"; stream << "// generated headers it includes (format " @@ -2427,9 +2448,9 @@ void render_generated_code_identity_macros(std::ostringstream& stream, // different definitions is not skipped. Reaching this point with the // namespace's identity macros already defined means a different definition of // the namespace was included first. -void render_same_translation_unit_check(std::ostringstream& stream, - std::string_view namespace_fqn) { - const std::string prefix = generated_code_identity_macro_prefix(namespace_fqn); +void render_same_translation_unit_check(std::ostringstream& stream, std::string_view namespace_fqn, + std::string_view name_prefix) { + const std::string prefix = generated_code_identity_macro_prefix(namespace_fqn, name_prefix); stream << "#if defined(" << prefix << "_CODE_ID_FORMAT) || \\\n defined(" << support::placeholder::macro_stem(namespace_fqn) << "_SCHEMA_ID_ALGORITHM)\n"; stream << "#error \"" << support::placeholder::include_path(namespace_fqn) @@ -2464,7 +2485,7 @@ void render_dependency_identity_checks( "compilation root as " << self_path << ".\"\n"; stream << "#endif\n"; - const std::string prefix = cpp_namespace_prefix(namespace_fqn); + const std::string prefix = cpp_namespace_prefix(namespace_fqn, plan.name_prefix); stream << "static_assert(" << prefix << kReservedIdentityAlgorithmConstant << " == " << static_cast(identity.algorithm) << "U &&\n"; stream << " " << prefix << kReservedIdentityConstant << " ==\n"; @@ -2479,7 +2500,8 @@ void render_dependency_identity_checks( stream << "// definitions this header was generated against (generated-code identity).\n"; for (const auto& [include_path, namespace_fqn] : plan.generated_dependencies) { const support::GeneratedCodeIdentity& expected = dependency_ids.find(namespace_fqn)->second; - const std::string macro = generated_code_identity_macro_prefix(namespace_fqn); + const std::string macro = + generated_code_identity_macro_prefix(namespace_fqn, plan.name_prefix); const std::string path = support::placeholder::include_path(namespace_fqn); stream << "#if !defined(" << macro << "_CODE_ID_FORMAT)"; for (std::size_t word = 0; word < 4U; ++word) { @@ -2535,14 +2557,14 @@ void render_dependency_identity_checks( // when a generated header is compiled on its own. // The guard carries the full generated-code identity, so two different // definitions of a namespace never share a guard, and identical ones do. - const std::string guard = generated_code_identity_macro_prefix(plan.fqn) + "_" + - support::placeholder::self_identity('H') + "_"; + const std::string guard = generated_code_identity_macro_prefix(plan.fqn, options.name_prefix) + + "_" + support::placeholder::self_identity('H') + "_"; stream << "#ifndef " << guard << "\n"; stream << "#define " << guard << "\n"; stream << '\n'; - render_same_translation_unit_check(stream, plan.fqn); + render_same_translation_unit_check(stream, plan.fqn, options.name_prefix); render_identity_macros(stream, plan.fqn, identity); - render_generated_code_identity_macros(stream, plan.fqn); + render_generated_code_identity_macros(stream, plan.fqn, options.name_prefix); std::set standard_includes = plan.standard_includes; standard_includes.insert(""); @@ -2572,7 +2594,8 @@ void render_dependency_identity_checks( } render_dependency_identity_checks(stream, plan, identity, dependency_ids); - const std::vector parts = namespace_parts(plan.fqn); + const std::vector parts = + namespace_parts(support::named_namespace(options.name_prefix, plan.fqn)); append_namespace_open(stream, parts); // Every declaration of the namespace lives in an inline namespace keyed by // its full generated-code identity: user code keeps writing @@ -2740,7 +2763,8 @@ identify_namespaces(const RenderGenerationPlan& complete_plan, const CodegenOpti const NamespacePlan& plan = *file.namespace_plan; ids.emplace(plan.fqn, identified.at(plan.fqn).identity); values.include_paths.emplace(plan.fqn, plan.include_path); - values.macro_stems.emplace(plan.fqn, generated_code_identity_macro_prefix(plan.fqn)); + values.macro_stems.emplace( + plan.fqn, generated_code_identity_macro_prefix(plan.fqn, options.name_prefix)); } files.reserve(generation_plan.files.size()); @@ -2810,8 +2834,7 @@ compute_layout(const schema_ir::SchemaIrModel& schema_ir, std::string& error_mes } // namespace -PlanResult Backend::plan(const schema_ir::SchemaIrModel& schema_ir, - const CodegenOptions& options, +PlanResult Backend::plan(const schema_ir::SchemaIrModel& schema_ir, const CodegenOptions& options, const output_planning::OutputPlan* output_plan) const { std::string error_message; const auto layout_model = compute_layout(schema_ir, error_message); diff --git a/compiler/backend/backend.hpp b/compiler/backend/backend.hpp index e1e0550..d519468 100644 --- a/compiler/backend/backend.hpp +++ b/compiler/backend/backend.hpp @@ -19,6 +19,8 @@ struct CodegenOptions { // Required for generate(), ignored by plan(). The schema compiler computes it // once from the resolved configuration; see missing_configuration_identity_message. std::optional configuration_identity; + // Explicit source naming only; canonical Schema IR and schema_id are unchanged. + std::string name_prefix = ""; }; struct GeneratedFile { diff --git a/compiler/backend_c/README.md b/compiler/backend_c/README.md index becd9ba..e22159f 100644 --- a/compiler/backend_c/README.md +++ b/compiler/backend_c/README.md @@ -287,3 +287,21 @@ The [consumer compatibility and migration guide](../../docs/generated-binding-co defines the shared plain-C/C++ contract, mixed-TU native boundaries, older-binding migration and working per-namespace storage commands. Equal wire identity or API epoch is not a prebuilt-library ABI guarantee. + +## Explicit naming prefix + +`CodegenOptions::name_prefix` (CLI `--name-prefix`) is optional and empty by +default. It projects generated source names and output paths without modifying +Schema IR, canonical FQNs, record IDs or configuration identity. Selection and +storage-policy options still use canonical namespace names. Unprefixed output +is pinned byte for byte in `tests/fixtures/name_prefix/unprefixed_sha256.json`. +See the [source naming contract](../../tools/README.md#deliberate-source-naming-isolation) +and [multi-configuration example](../../examples/truck/multi_configuration/README.md). + +Prefixed C symbols use the case-preserving #117 encoding of the prefix followed +by every canonical namespace segment. Enum constants preserve that encoded +namespace's case, then retain the existing uppercase enum/member suffix. +C++/C-storage wrappers use the same encoded stem; callback language linkage and +identity-bearing external names retain their established rules. Unprefixed +legacy C spellings and #119's general migration remain unchanged. The existing +format-1 generated-code identity hashes the changed definitions normally. diff --git a/compiler/backend_c/backend_c.cpp b/compiler/backend_c/backend_c.cpp index 97cae95..55a8509 100644 --- a/compiler/backend_c/backend_c.cpp +++ b/compiler/backend_c/backend_c.cpp @@ -4,6 +4,7 @@ #include "compiler/diagnostics/diagnostic.hpp" #include "compiler/layout/layout.hpp" #include "compiler/support/generated_code_identity.hpp" +#include "compiler/support/generated_names.hpp" #include "compiler/support/namespace_macro.hpp" #include @@ -25,15 +26,15 @@ namespace quarry::compiler::backend_c { namespace { +using ::quarry::compiler::layout::FieldStorage; +using ::quarry::compiler::layout::LayoutModel; +using ::quarry::compiler::layout::RecordLayout; using ::quarry::schema_ir::EnumIR; using ::quarry::schema_ir::EnumValueIR; using ::quarry::schema_ir::FieldIR; using ::quarry::schema_ir::FieldType; using ::quarry::schema_ir::NamespaceIR; using ::quarry::schema_ir::RecordIR; -using ::quarry::compiler::layout::FieldStorage; -using ::quarry::compiler::layout::LayoutModel; -using ::quarry::compiler::layout::RecordLayout; // --- Namespace/symbol naming ------------------------------------------------- // @@ -75,7 +76,10 @@ using ::quarry::compiler::layout::RecordLayout; // Namespace FQN -> C symbol prefix, e.g. "quarry.telemetry" -> "quarry_telemetry_". // The root (synthetic, unnamed) namespace contributes no prefix segment. -[[nodiscard]] std::string symbol_prefix_for_namespace(std::string_view fqn) { +[[nodiscard]] std::string symbol_prefix_for_namespace(std::string_view fqn, + std::string_view name_prefix) { + if (!name_prefix.empty()) + return support::named_macro_body(name_prefix, fqn) + "_"; const std::vector parts = namespace_parts(fqn); if (parts.empty()) { return ""; @@ -89,9 +93,9 @@ using ::quarry::compiler::layout::RecordLayout; std::string_view fqn) { const std::vector parts = namespace_parts(fqn); if (parts.empty()) { - return options.root_file_stem; + return support::named_path(options.name_prefix, options.root_file_stem); } - return join_with(parts, '/'); + return support::named_path(options.name_prefix, join_with(parts, '/')); } [[nodiscard]] std::string uppercase_alnum_or_underscore(std::string_view text) { @@ -112,15 +116,12 @@ using ::quarry::compiler::layout::RecordLayout; // the same source spelling differently. [[nodiscard]] bool is_c_keyword(std::string_view identifier) { static constexpr std::string_view keywords[] = { - "auto", "break", "case", "char", "const", "continue", - "default", "do", "double", "else", "enum", "extern", - "float", "for", "goto", "if", "inline", "int", - "long", "register", "restrict", "return", "short", "signed", - "sizeof", "static", "struct", "switch", "typedef", "union", - "unsigned", "void", "volatile", "while", "_Bool", "_Complex", - "_Imaginary"}; - return std::find(std::begin(keywords), std::end(keywords), identifier) != - std::end(keywords); + "auto", "break", "case", "char", "const", "continue", "default", "do", + "double", "else", "enum", "extern", "float", "for", "goto", "if", + "inline", "int", "long", "register", "restrict", "return", "short", "signed", + "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", + "volatile", "while", "_Bool", "_Complex", "_Imaginary"}; + return std::find(std::begin(keywords), std::end(keywords), identifier) != std::end(keywords); } constexpr std::string_view cpp_keywords[] = {"alignas", @@ -230,7 +231,7 @@ constexpr std::string_view cpp_keywords[] = {"alignas", } class CIdentifierAllocator { - public: +public: [[nodiscard]] std::string allocate(std::string_view candidate) { const std::string base = safe_c_identifier(candidate); if (used_.insert(base).second) { @@ -252,7 +253,7 @@ class CIdentifierAllocator { return used_.find(std::string(identifier)) != used_.end(); } - private: +private: std::set used_; }; @@ -265,27 +266,29 @@ struct FieldEncoding; // Encoded namespace body (#117). Empty when the name is not a namespace FQN; // the file plan rejects that before a header is written. -[[nodiscard]] std::string namespace_macro_body(std::string_view namespace_fqn) { - const std::optional encoded = support::encode_namespace_macro(namespace_fqn); - return encoded.has_value() ? *encoded : std::string(); +[[nodiscard]] std::string namespace_macro_body(std::string_view namespace_fqn, + std::string_view name_prefix) { + return support::named_macro_body(name_prefix, namespace_fqn); } // Configuration-identity macros, for example QUARRY_NS_truck_engine_SCHEMA_ID_W0. // The root namespace uses the same prefix with the root body. The spelling is // the shared namespace encoding, not the C symbol prefix, so dep.engine and // dep_engine do not share a macro. -[[nodiscard]] std::string identity_macro_prefix(std::string_view namespace_fqn) { - return std::string(support::kCNamespaceMacroPrefix) + namespace_macro_body(namespace_fqn) + - "_SCHEMA_ID"; +[[nodiscard]] std::string identity_macro_prefix(std::string_view namespace_fqn, + std::string_view name_prefix) { + return std::string(support::kCNamespaceMacroPrefix) + + namespace_macro_body(namespace_fqn, name_prefix) + "_SCHEMA_ID"; } // Optional runtime accessor. It uses the same encoding as the macros: the old // symbol-prefix spelling collided for the same namespace pairs, and a second // definition of that static function would reject the translation unit before // the macros could coexist. -[[nodiscard]] std::string identity_accessor_name(std::string_view namespace_fqn) { - return std::string(support::kCNamespaceAccessorPrefix) + namespace_macro_body(namespace_fqn) + - "_schema_id"; +[[nodiscard]] std::string identity_accessor_name(std::string_view namespace_fqn, + std::string_view name_prefix) { + return std::string(support::kCNamespaceAccessorPrefix) + + namespace_macro_body(namespace_fqn, name_prefix) + "_schema_id"; } // Prefix of the generated-code identity macros and guard of a namespace's @@ -294,10 +297,11 @@ struct FieldEncoding; // namespace encoding (#117), never from the output path; reserved per // namespace in the file-scope identifier registry. [[nodiscard]] std::string code_identity_macro_prefix(std::string_view namespace_fqn, - bool cpp_wrapper) { + bool cpp_wrapper, + std::string_view name_prefix) { return std::string(cpp_wrapper ? support::kCppCStorageNamespaceMacroPrefix : support::kCNamespaceCodeIdMacroPrefix) + - namespace_macro_body(namespace_fqn); + namespace_macro_body(namespace_fqn, name_prefix); } // The generated-code identity variant of a C backend invocation. @@ -334,10 +338,10 @@ struct FieldEncoding; // though the shared codec no longer needs per-field scratch variables. struct FieldEncoding { - std::string c_type; // e.g. "int32_t", "float", "bool", or an enum's own typedef name - // -- for an array field, describes the *element* type - std::string runtime_verb; // e.g. "i32" -> quarry_c_write_i32 / quarry_c_read_i32 - // -- for an array field, the *element* verb + std::string c_type; // e.g. "int32_t", "float", "bool", or an enum's own typedef name + // -- for an array field, describes the *element* type + std::string runtime_verb; // e.g. "i32" -> quarry_c_write_i32 / quarry_c_read_i32 + // -- for an array field, the *element* verb std::uint8_t width_bytes = 0U; // for an array field, the *element* width bool is_enum = false; // for an array field, whether the *element* type is an enum std::vector enum_valid_values; // only meaningful when is_enum @@ -351,21 +355,21 @@ struct FieldEncoding { // this value (no "+1" -- see "Bytes fields" above), so // unlike string_max_bytes this never needs widening bool is_array = false; - std::uint32_t array_max_elements = 0U; // only meaningful when is_array + std::uint32_t array_max_elements = 0U; // only meaningful when is_array std::uint64_t array_scratch_capacity = 0U; // only meaningful when is_array; widened to // std::uint64_t for the same overflow-avoidance // reason as string_max_bytes (max_elements * // width_bytes, plus the worst-case varuint count // prefix, could overflow uint32_t) - bool array_element_is_record = false; // only meaningful when is_array; true when the - // array's element type is a same-namespace record - // reference rather than a scalar/enum. Reuses (does - // not duplicate) record_target_ir_id/ - // record_symbol_name/record_max_encoded_size below -- - // a field is never simultaneously is_record and - // is_array, so field reuse is unambiguous, mirroring - // how is_enum already double-duties for both plain-enum - // and array-of-enum fields. + bool array_element_is_record = false; // only meaningful when is_array; true when the + // array's element type is a same-namespace record + // reference rather than a scalar/enum. Reuses (does + // not duplicate) record_target_ir_id/ + // record_symbol_name/record_max_encoded_size below -- + // a field is never simultaneously is_record and + // is_array, so field reuse is unambiguous, mirroring + // how is_enum already double-duties for both plain-enum + // and array-of-enum fields. bool array_element_is_fixed_record = false; std::uint32_t array_element_fixed_record_size = 0U; bool is_record = false; @@ -392,8 +396,7 @@ struct FieldEncoding { }; [[nodiscard]] bool is_field_scratch_required(const FieldEncoding& encoding) { - return encoding.is_array || encoding.is_record || - (!encoding.is_string && !encoding.is_bytes); + return encoding.is_array || encoding.is_record || (!encoding.is_string && !encoding.is_bytes); } // A field name participates in more than the struct-member namespace. Its @@ -406,9 +409,8 @@ struct FieldEncoding { bool cpp_wrapper = false) { const std::string base = safe_c_identifier(source_name); for (std::uint32_t suffix = 0U;; ++suffix) { - const std::string candidate = suffix == 0U - ? base - : base + "_" + std::to_string(suffix + 1U); + const std::string candidate = + suffix == 0U ? base : base + "_" + std::to_string(suffix + 1U); std::vector generated_names; generated_names.push_back(candidate); generated_names.push_back("has_" + candidate); @@ -432,10 +434,9 @@ struct FieldEncoding { generated_names.push_back(candidate + "_size"); } - if (std::all_of(generated_names.begin(), generated_names.end(), - [&allocator](const std::string& name) { - return !allocator.contains(name); - })) { + if (std::all_of( + generated_names.begin(), generated_names.end(), + [&allocator](const std::string& name) { return !allocator.contains(name); })) { for (const std::string& name : generated_names) { (void)allocator.reserve(name); } @@ -548,13 +549,15 @@ struct EnumCatalogEntry { using EnumCatalog = std::unordered_map; -[[nodiscard]] bool collect_enum_catalog(const NamespaceIR& ns, EnumCatalog& catalog, - std::string& error_message) { - const std::string symbol_prefix = symbol_prefix_for_namespace(ns.fqn()); +[[nodiscard]] bool collect_enum_catalog(const NamespaceIR& ns, const CodegenOptions& options, + EnumCatalog& catalog, std::string& error_message) { + const std::string symbol_prefix = symbol_prefix_for_namespace(ns.fqn(), options.name_prefix); for (const EnumIR& enum_ir : ns.enums()) { EnumCatalogEntry entry; entry.type_name = safe_c_identifier(symbol_prefix + enum_ir.name()) + "_t"; - entry.value_prefix = uppercase_alnum_or_underscore(symbol_prefix + enum_ir.name()); + entry.value_prefix = options.name_prefix.empty() + ? uppercase_alnum_or_underscore(symbol_prefix + enum_ir.name()) + : symbol_prefix + uppercase_alnum_or_underscore(enum_ir.name()); entry.owning_namespace_fqn = ns.fqn(); entry.all_non_negative = true; @@ -584,7 +587,7 @@ using EnumCatalog = std::unordered_map; } for (const NamespaceIR& child : ns.namespaces()) { - if (!collect_enum_catalog(child, catalog, error_message)) { + if (!collect_enum_catalog(child, options, catalog, error_message)) { return false; } } @@ -736,7 +739,7 @@ lower_enum_reference(std::uint64_t target_enum_ir_id, std::string_view current_n // every record's catalog entry is first created. struct RecordCatalogEntry { - std::string symbol_name; // e.g. "quarry_telemetry_Child" (no _t/_encode/_decode suffix) + std::string symbol_name; // e.g. "quarry_telemetry_Child" (no _t/_encode/_decode suffix) std::string owning_namespace_fqn; std::uint64_t max_encoded_size = 0U; // resolved later; see collect_namespace_files std::uint32_t record_id = 0U; @@ -744,8 +747,9 @@ struct RecordCatalogEntry { using RecordCatalog = std::unordered_map; -void collect_record_catalog(const NamespaceIR& ns, RecordCatalog& catalog) { - const std::string symbol_prefix = symbol_prefix_for_namespace(ns.fqn()); +void collect_record_catalog(const NamespaceIR& ns, const CodegenOptions& options, + RecordCatalog& catalog) { + const std::string symbol_prefix = symbol_prefix_for_namespace(ns.fqn(), options.name_prefix); for (const RecordIR& record_ir : ns.records()) { RecordCatalogEntry entry; entry.symbol_name = safe_c_identifier(symbol_prefix + record_ir.name()); @@ -754,7 +758,7 @@ void collect_record_catalog(const NamespaceIR& ns, RecordCatalog& catalog) { catalog.emplace(record_ir.ir_id(), std::move(entry)); } for (const NamespaceIR& child : ns.namespaces()) { - collect_record_catalog(child, catalog); + collect_record_catalog(child, options, catalog); } } @@ -873,8 +877,8 @@ compute_record_max_encoded_size(const std::vector& fields) { for (std::size_t index = 0; index < records.size(); ++index) { if (indegree[index] == 0U) { ready.emplace(index, index); // (source_order, index): original index is the - // declaration order here, matching the C++ - // backend's identical tie-break + // declaration order here, matching the C++ + // backend's identical tie-break } } @@ -941,9 +945,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return encoding; } else if (type.kind_case() == FieldType::kEnumType) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "'"; - std::optional encoding = lower_enum_reference( - type.enum_type().target_enum_ir_id(), current_namespace_fqn, catalog, context, - error_message); + std::optional encoding = + lower_enum_reference(type.enum_type().target_enum_ir_id(), current_namespace_fqn, + catalog, context, error_message); if (encoding.has_value()) { return encoding; } @@ -962,9 +966,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else if (element_type.kind_case() == FieldType::kEnumType) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "' array element type"; - element_encoding = lower_enum_reference(element_type.enum_type().target_enum_ir_id(), - current_namespace_fqn, catalog, context, - error_message); + element_encoding = + lower_enum_reference(element_type.enum_type().target_enum_ir_id(), + current_namespace_fqn, catalog, context, error_message); } else if (element_type.kind_case() == FieldType::kString) { element_encoding = FieldEncoding{}; element_encoding->is_string = true; @@ -976,10 +980,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else if (element_type.kind_case() == FieldType::kRecord) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "' array element type"; - element_encoding = - lower_record_reference(element_type.record().target_record_ir_id(), - current_namespace_fqn, record_catalog, context, - error_message); + element_encoding = lower_record_reference(element_type.record().target_record_ir_id(), + current_namespace_fqn, record_catalog, + context, error_message); if (element_encoding.has_value()) { element_encoding->array_element_is_record = true; } @@ -1020,7 +1023,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, static_cast(array_type.max_elements()) * (static_cast(kMaxVaruintBytesForUint32) + (encoding.is_string ? encoding.string_max_bytes - : static_cast(encoding.bytes_max_bytes))); + : static_cast(encoding.bytes_max_bytes))); } else { encoding.array_scratch_capacity = static_cast(kMaxVaruintBytesForUint32) + @@ -1030,9 +1033,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return encoding; } else if (type.kind_case() == FieldType::kRecord) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "'"; - std::optional encoding = lower_record_reference( - type.record().target_record_ir_id(), current_namespace_fqn, record_catalog, context, - error_message); + std::optional encoding = + lower_record_reference(type.record().target_record_ir_id(), current_namespace_fqn, + record_catalog, context, error_message); if (encoding.has_value()) { encoding->is_record = true; return encoding; @@ -1065,13 +1068,18 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // the same "emit files only for namespaces that directly own records or // enums" rule compiler/backend/backend.cpp already follows for C++ -- an // independently reached, not shared, implementation of the same policy. -[[nodiscard]] bool collect_namespace_files(const NamespaceIR& ns, const CodegenOptions& options, - const EnumCatalog& catalog, - RecordCatalog& record_catalog, - const LayoutModel& layout_model, - const OutputSelection* output_selection, - std::vector& files, - std::string& error_message) { +[[nodiscard]] bool +collect_namespace_files(const NamespaceIR& ns, const CodegenOptions& options, + const EnumCatalog& catalog, RecordCatalog& record_catalog, + const LayoutModel& layout_model, const OutputSelection* output_selection, + std::vector& files, std::string& error_message) { + if (!support::valid_prefix_for_namespace(options.name_prefix, ns.fqn())) { + error_message = + "invalid or conflicting --name-prefix '" + options.name_prefix + + "': use an unreserved identifier distinct from every namespace's first segment"; + return false; + } + if (namespace_emits_file(ns)) { PlannedNamespaceFile file; file.namespace_fqn = ns.fqn(); @@ -1084,8 +1092,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } if (output_selection != nullptr && !output_selection->planned_namespaces.contains(ns.fqn())) { - error_message = "backend_c: namespace '" + ns.fqn() + - "' is missing from the compiler output plan"; + error_message = + "backend_c: namespace '" + ns.fqn() + "' is missing from the compiler output plan"; return false; } CIdentifierAllocator enum_constants; @@ -1111,22 +1119,22 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, const std::string normalized_name = uppercase_alnum_or_underscore(value_ir.name()); planned_enum.values.push_back(PlannedEnumValue{ .name = normalized_name, - .c_name = enum_constants.allocate(planned_enum.symbol_name + "_" + - normalized_name), + .c_name = + enum_constants.allocate(planned_enum.symbol_name + "_" + normalized_name), .value = value_ir.value()}); } file.enums.push_back(std::move(planned_enum)); } - const std::string symbol_prefix = symbol_prefix_for_namespace(ns.fqn()); + const std::string symbol_prefix = + symbol_prefix_for_namespace(ns.fqn(), options.name_prefix); CIdentifierAllocator type_names; for (const PlannedEnum& planned_enum : file.enums) { (void)type_names.reserve(planned_enum.type_name); } for (const RecordIR& record_ir : ns.records()) { - (void)type_names.reserve( - safe_c_identifier(symbol_prefix + record_ir.name()) + "_t"); + (void)type_names.reserve(safe_c_identifier(symbol_prefix + record_ir.name()) + "_t"); } // Phase 1: lower every field of every record in this namespace, in @@ -1146,7 +1154,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, for (const RecordIR& record_ir : ns.records()) { const RecordLayout* canonical_layout = layout_model.find_record(record_ir.fqn()); if (canonical_layout == nullptr || - canonical_layout->fields.size() != static_cast(record_ir.fields_size())) { + canonical_layout->fields.size() != + static_cast(record_ir.fields_size())) { error_message = "backend_c: canonical BRF v2 layout is missing record '" + record_ir.fqn() + "' or has an inconsistent field count"; return false; @@ -1213,7 +1222,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, unsigned_runtime_verb_for_width(planned_field.encoding.width_bytes); } if (!planned_field.encoding.is_string && !planned_field.encoding.is_bytes && - !planned_field.encoding.is_record && !planned_field.encoding.array_element_is_record && + !planned_field.encoding.is_record && + !planned_field.encoding.array_element_is_record && canonical_type->encoded_width != 0U) { planned_field.encoding.width_bytes = static_cast(canonical_type->encoded_width); @@ -1232,21 +1242,22 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, canonical_field.type.element_type->encoded_width; } ++field_position; - const bool references_record = - planned_field.encoding.is_record || - planned_field.encoding.array_element_is_record; + const bool references_record = planned_field.encoding.is_record || + planned_field.encoding.array_element_is_record; const bool references_enum = planned_field.encoding.is_enum; if (references_record || references_enum) { const std::uint64_t target_id = - references_record - ? planned_field.encoding.record_target_ir_id - : (field_ir.type().kind_case() == FieldType::kArray - ? field_ir.type().array().element_type().enum_type() - .target_enum_ir_id() - : field_ir.type().enum_type().target_enum_ir_id()); - const std::string& owner = references_record - ? record_catalog.at(target_id).owning_namespace_fqn - : catalog.at(target_id).owning_namespace_fqn; + references_record ? planned_field.encoding.record_target_ir_id + : (field_ir.type().kind_case() == FieldType::kArray + ? field_ir.type() + .array() + .element_type() + .enum_type() + .target_enum_ir_id() + : field_ir.type().enum_type().target_enum_ir_id()); + const std::string& owner = + references_record ? record_catalog.at(target_id).owning_namespace_fqn + : catalog.at(target_id).owning_namespace_fqn; if (owner != ns.fqn()) { if (output_selection != nullptr && !output_selection->planned_namespaces.contains(owner)) { @@ -1306,7 +1317,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, record_catalog.at(planned_field.encoding.record_target_ir_id) .max_encoded_size; } else if (planned_field.encoding.is_array && - planned_field.encoding.array_element_is_record) { + planned_field.encoding.array_element_is_record) { // Only array_scratch_capacity is set here, not // record_max_encoded_size: every read site of // record_max_encoded_size (compute_record_max_encoded_size, @@ -1335,9 +1346,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, for (const NamespaceIR& child : ns.namespaces()) { if (!collect_namespace_files(child, options, catalog, record_catalog, layout_model, - output_selection, - files, - error_message)) { + output_selection, files, error_message)) { return false; } } @@ -1350,14 +1359,15 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // collected later, so use the already compiler-resolved record ids and a // small deterministic DFS over the generated record plans. This is sizing // metadata only; declaration and codec lowering remain unchanged. -[[nodiscard]] bool resolve_record_sizes( - std::uint64_t record_id, const std::map& records, - RecordCatalog& record_catalog, std::map& state, - std::string& error_message) { +[[nodiscard]] bool resolve_record_sizes(std::uint64_t record_id, + const std::map& records, + RecordCatalog& record_catalog, + std::map& state, + std::string& error_message) { const auto record_it = records.find(record_id); if (record_it == records.end()) { - error_message = "backend_c: could not resolve record sizing dependency " + - std::to_string(record_id); + error_message = + "backend_c: could not resolve record sizing dependency " + std::to_string(record_id); return false; } const unsigned char current_state = state[record_id]; @@ -1373,8 +1383,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, state[record_id] = 1U; PlannedRecord& record = *record_it->second; for (PlannedField& field : record.fields) { - const bool nested_record = field.encoding.is_record || - field.encoding.array_element_is_record; + const bool nested_record = + field.encoding.is_record || field.encoding.array_element_is_record; if (!nested_record) { continue; } @@ -1392,8 +1402,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, (kMaxVaruintBytesForUint64 + target_size); } } - record_catalog.at(record_id).max_encoded_size = - compute_record_max_encoded_size(record.fields); + record_catalog.at(record_id).max_encoded_size = compute_record_max_encoded_size(record.fields); state[record_id] = 2U; return true; } @@ -1422,13 +1431,14 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } } } - const OutputSelection* output_selection_ptr = output_plan == nullptr ? nullptr : &output_selection; + const OutputSelection* output_selection_ptr = + output_plan == nullptr ? nullptr : &output_selection; EnumCatalog catalog; - if (!collect_enum_catalog(schema_ir.root_namespace(), catalog, error_message)) { + if (!collect_enum_catalog(schema_ir.root_namespace(), options, catalog, error_message)) { return false; } RecordCatalog record_catalog; - collect_record_catalog(schema_ir.root_namespace(), record_catalog); + collect_record_catalog(schema_ir.root_namespace(), options, record_catalog); std::optional computed_layout; ::quarry::compiler::diagnostics::DiagnosticEngine layout_diagnostics; if (precomputed_layout == nullptr) { @@ -1460,12 +1470,13 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, FieldType::kEnumType) { enum_type = &field_ir.type().array().element_type(); } - if (enum_type == nullptr) continue; - const auto enum_it = catalog.find( - enum_type->enum_type().target_enum_ir_id()); + if (enum_type == nullptr) + continue; + const auto enum_it = catalog.find(enum_type->enum_type().target_enum_ir_id()); if (enum_it != catalog.end() && !enum_it->second.all_non_negative) { error_message = "backend_c: field '" + record_ir.fqn() + "." + - field_ir.name() + "' references an enum with a negative " + field_ir.name() + + "' references an enum with a negative " "declared value; enum fields are only supported when " "every declared value is non-negative"; if (field_ir.type().kind_case() == FieldType::kArray) { @@ -1475,15 +1486,15 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } } } - for (const NamespaceIR& child : current->namespaces()) namespaces.push_back(&child); + for (const NamespaceIR& child : current->namespaces()) + namespaces.push_back(&child); } return false; } const LayoutModel& layout_model = precomputed_layout != nullptr ? *precomputed_layout : *computed_layout; if (!collect_namespace_files(schema_ir.root_namespace(), options, catalog, record_catalog, - layout_model, - output_selection_ptr, files, error_message)) { + layout_model, output_selection_ptr, files, error_message)) { return false; } @@ -1508,8 +1519,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, const auto reserve_file_scope_identifier = [&](const std::string& identifier, std::string_view category) { if (!seen_file_scope_identifiers.insert(identifier).second) { - error_message = "backend_c: generated " + std::string(category) + " '" + - identifier + "' collides with another generated C identifier"; + error_message = "backend_c: generated " + std::string(category) + " '" + identifier + + "' collides with another generated C identifier"; return false; } // In C++, C-storage headers, and plain C headers compiled as C++ (G2), @@ -1551,13 +1562,13 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, }; for (const PlannedNamespaceFile& file : files) { if (!seen_paths.insert(file.relative_header_path).second) { - error_message = "backend_c: duplicate generated header path: " + - file.relative_header_path; + error_message = + "backend_c: duplicate generated header path: " + file.relative_header_path; return false; } if (!seen_paths.insert(file.relative_source_path).second) { - error_message = "backend_c: duplicate generated source path: " + - file.relative_source_path; + error_message = + "backend_c: duplicate generated source path: " + file.relative_source_path; return false; } const std::string guard = header_guard_macro(file.relative_header_path); @@ -1567,9 +1578,11 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return false; } // Configuration identity names of this namespace (render_header). - const std::string macro_prefix = identity_macro_prefix(file.namespace_fqn); - const std::string accessor = identity_accessor_name(file.namespace_fqn); - if (namespace_macro_body(file.namespace_fqn).empty() || + const std::string macro_prefix = + identity_macro_prefix(file.namespace_fqn, options.name_prefix); + const std::string accessor = + identity_accessor_name(file.namespace_fqn, options.name_prefix); + if (namespace_macro_body(file.namespace_fqn, options.name_prefix).empty() || !support::is_unreserved_macro_identifier(macro_prefix + "_ALGORITHM") || !support::is_unreserved_macro_identifier(accessor)) { error_message = @@ -1579,7 +1592,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return false; } if (!support::is_unreserved_macro_identifier( - code_identity_macro_prefix(file.namespace_fqn, options.cpp_wrapper) + + code_identity_macro_prefix(file.namespace_fqn, options.cpp_wrapper, + options.name_prefix) + "_CODE_ID_FORMAT")) { error_message = "backend_c: namespace '" + file.namespace_fqn + "' has no standards-compliant generated-code identity macro spelling"; @@ -1596,10 +1610,11 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } for (const std::string_view suffix : {"_CODE_ID_FORMAT", "_CODE_ID_W0", "_CODE_ID_W1", "_CODE_ID_W2", "_CODE_ID_W3"}) { - if (!reserve_file_scope_identifier( - code_identity_macro_prefix(file.namespace_fqn, options.cpp_wrapper) + - std::string(suffix), - "generated-code identity macro")) { + if (!reserve_file_scope_identifier(code_identity_macro_prefix(file.namespace_fqn, + options.cpp_wrapper, + options.name_prefix) + + std::string(suffix), + "generated-code identity macro")) { return false; } } @@ -1617,8 +1632,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, const std::string type_name = record.symbol_name + "_t"; if (!reserve_file_scope_identifier(type_name, "record type") || !reserve_file_scope_identifier(record.symbol_name + "_init", "function") || - !reserve_file_scope_identifier(record.symbol_name + "_encoded_size", - "function") || + !reserve_file_scope_identifier(record.symbol_name + "_encoded_size", "function") || !reserve_file_scope_identifier(record.symbol_name + "_encode_result_t", "encode result type") || !reserve_file_scope_identifier(record.symbol_name + "_encode", "function") || @@ -1628,8 +1642,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return false; } for (const std::string_view suffix : - {"_encoded_size_result_t", "_type", "_members", "_brf_v2_fields", "_brf_v2_layout", "_encode_with_record_id", - "_decode_with_record_id"}) { + {"_encoded_size_result_t", "_type", "_members", "_brf_v2_fields", "_brf_v2_layout", + "_encode_with_record_id", "_decode_with_record_id"}) { if (!reserve_file_scope_identifier(record.symbol_name + std::string(suffix), "binding symbol")) { return false; @@ -1909,7 +1923,8 @@ void render_binding(std::ostringstream& stream, const PlannedRecord& record, boo << " " << n << "_encoded_size_result_t result;\n" << " result.status = (quarry_c_status_t)measured.status; result.size = measured.size;\n" << " return result;\n}\n"; - stream << "typedef struct { quarry_c_status_t status; size_t bytes_written; } " << n << "_encode_result_t;\n"; + stream << "typedef struct { quarry_c_status_t status; size_t bytes_written; } " << n + << "_encode_result_t;\n"; stream << linkage.function << n << "_encode_result_t " << n << "_encode_with_record_id(const " << n << "_t* record, uint32_t record_id, uint8_t* output, size_t output_capacity) {\n" << " quarry_c_typed_encode_result_t encoded = quarry_c_typed_encode(&" << n @@ -2040,6 +2055,7 @@ void render_cpp_wrapper(::std::ostringstream& stream, const PlannedRecord& recor // generated-code identity (#111; plain C since G2), and `dependency_ids` holds // the identity of every generated namespace they include. struct CRenderContext { + std::string_view name_prefix; bool optimize_size = false; bool cpp_wrapper = false; const std::map& namespace_by_include; @@ -2076,7 +2092,7 @@ void render_dependency_identity_checks(std::ostringstream& stream, const Planned " * configuration (compilation root). */\n"; wrote_comment = true; } - const std::string macro = identity_macro_prefix(it->second); + const std::string macro = identity_macro_prefix(it->second, context.name_prefix); stream << "#if !defined(" << macro << "_ALGORITHM)"; for (std::size_t word = 0; word < 4U; ++word) { stream << " || \\\n !defined(" << macro << "_W" << word << ")"; @@ -2110,7 +2126,8 @@ void render_dependency_identity_checks(std::ostringstream& stream, const Planned wrote_identity_comment = true; } const support::GeneratedCodeIdentity& expected = context.dependency_ids.at(it->second); - const std::string macro = code_identity_macro_prefix(it->second, context.cpp_wrapper); + const std::string macro = + code_identity_macro_prefix(it->second, context.cpp_wrapper, context.name_prefix); const std::string path = context.path(it->second, include_path); stream << "#if !defined(" << macro << "_CODE_ID_FORMAT)"; for (std::size_t word = 0; word < 4U; ++word) { @@ -2147,9 +2164,11 @@ void render_dependency_identity_checks(std::ostringstream& stream, const Planned // Guards are keyed by the generated-code identity (C++/C storage since G1, // plain C since G2), so two different definitions of a namespace never // share a guard and identical ones do, whatever their output paths. - const std::string code_id_prefix = code_identity_macro_prefix(file.namespace_fqn, cpp_wrapper); + const std::string code_id_prefix = + code_identity_macro_prefix(file.namespace_fqn, cpp_wrapper, context.name_prefix); const std::string guard = code_id_prefix + "_" + support::placeholder::self_identity('H') + "_"; - const std::string identity_macro = identity_macro_prefix(file.namespace_fqn); + const std::string identity_macro = + identity_macro_prefix(file.namespace_fqn, context.name_prefix); // C++ (C-storage) headers put every declaration in an inline namespace // keyed by the full generated-code identity. Source code keeps writing // ::truck_engine_EngineStatus_t, but the C++ entities those declarations @@ -2291,7 +2310,8 @@ void render_dependency_identity_checks(std::ostringstream& stream, const Planned if (optimize_size) { std::size_t bits = 0U; for (const auto& field : record.fields) - if (!field.encoding.is_array && !field.encoding.is_string && !field.encoding.is_bytes) + if (!field.encoding.is_array && !field.encoding.is_string && + !field.encoding.is_bytes) ++bits; if (bits != 0U) stream << " uint8_t quarry_presence_bits[" << (bits + 7U) / 8U << "];\n"; @@ -2365,8 +2385,8 @@ void render_dependency_identity_checks(std::ostringstream& stream, const Planned stream << "\n"; stream << "/* Optional runtime access to the configuration identity; emitted into object\n"; stream << " * code only when called. */\n"; - stream << linkage.function << "const uint8_t* " << identity_accessor_name(file.namespace_fqn) - << "(void) {\n"; + stream << linkage.function << "const uint8_t* " + << identity_accessor_name(file.namespace_fqn, context.name_prefix) << "(void) {\n"; stream << " static const uint8_t id[16] = {"; for (std::size_t index = 0; index < identity.schema_id.size(); ++index) { stream << (index == 0U ? "" : ", ") << hex_byte_literal(identity.schema_id[index]); @@ -2521,7 +2541,8 @@ identify_file(const PlannedNamespaceFile& file, .variant = code_identity_variant(options.cpp_wrapper), .identity = dependency->second}); } - const CRenderContext context{.optimize_size = file.optimize_size, + const CRenderContext context{.name_prefix = options.name_prefix, + .optimize_size = file.optimize_size, .cpp_wrapper = options.cpp_wrapper, .namespace_by_include = namespace_by_include, .header_extension = options.header_extension, diff --git a/compiler/backend_c/backend_c.hpp b/compiler/backend_c/backend_c.hpp index 3bb4c22..7aeecff 100644 --- a/compiler/backend_c/backend_c.hpp +++ b/compiler/backend_c/backend_c.hpp @@ -23,6 +23,8 @@ struct CodegenOptions { // Required for generate(), ignored by plan(). The schema compiler computes it // once from the resolved configuration; see missing_configuration_identity_message. std::optional configuration_identity; + // Explicit source naming only; canonical Schema IR and schema_id are unchanged. + std::string name_prefix = ""; }; // Checks policy selections against the complete configuration, without layout or identity work. diff --git a/compiler/backend_go/backend_go.cpp b/compiler/backend_go/backend_go.cpp index db0df6d..a127798 100644 --- a/compiler/backend_go/backend_go.cpp +++ b/compiler/backend_go/backend_go.cpp @@ -1,6 +1,7 @@ #include "compiler/backend_go/backend_go.hpp" #include "compiler/diagnostics/diagnostic.hpp" #include "compiler/layout/layout.hpp" +#include "compiler/support/generated_names.hpp" #include #include @@ -449,10 +450,17 @@ lower_field(const RecordIR& record_ir, const FieldIR& field_ir, const EnumCatalo const LayoutModel& layout_model, std::vector& files, std::string& error_message) { + if (!support::valid_prefix_for_namespace(options.name_prefix, ns.fqn())) { + error_message = + "invalid or conflicting --name-prefix '" + options.name_prefix + + "': use an unreserved identifier distinct from every namespace's first segment"; + return false; + } + if (ns.records_size() > 0 || ns.enums_size() > 0) { PlannedPackageFile file; file.namespace_fqn = ns.fqn(); - file.directories = namespace_parts(ns.fqn()); + file.directories = namespace_parts(support::named_namespace(options.name_prefix, ns.fqn())); for (const std::string& segment : file.directories) { if (!is_safe_path_segment(segment)) { error_message = "backend_go: namespace segment '" + segment + "' of '" + ns.fqn() + diff --git a/compiler/backend_go/backend_go.hpp b/compiler/backend_go/backend_go.hpp index cc7a343..fbeb153 100644 --- a/compiler/backend_go/backend_go.hpp +++ b/compiler/backend_go/backend_go.hpp @@ -34,6 +34,8 @@ struct CodegenOptions { // Required for generate(), ignored by plan(). The schema compiler computes it // once from the resolved configuration; see missing_configuration_identity_message. std::optional configuration_identity; + // Explicit source naming only; canonical Schema IR and schema_id are unchanged. + std::string name_prefix = ""; }; struct GeneratedFile { diff --git a/compiler/backend_python/README.md b/compiler/backend_python/README.md index 15c4ae4..1018f28 100644 --- a/compiler/backend_python/README.md +++ b/compiler/backend_python/README.md @@ -45,3 +45,13 @@ caller's `layout::LayoutModel`, computed once from the same Schema IR. `quarry-schema-compiler` uses those overloads so one compilation computes its BRF layout once (see `docs/compiler-architecture.md`, "Configuration Preparation"); the overloads without a layout compute it themselves. + +## Explicit naming prefix + +`CodegenOptions::name_prefix` (CLI `--name-prefix`) is optional and empty by +default. It projects generated source names and output paths without modifying +Schema IR, canonical FQNs, record IDs or configuration identity. Selection and +storage-policy options still use canonical namespace names. Unprefixed output +is pinned byte for byte in `tests/fixtures/name_prefix/unprefixed_sha256.json`. +See the [source naming contract](../../tools/README.md#deliberate-source-naming-isolation) +and [multi-configuration example](../../examples/truck/multi_configuration/README.md). diff --git a/compiler/backend_python/backend_python.cpp b/compiler/backend_python/backend_python.cpp index 259866e..f270ebf 100644 --- a/compiler/backend_python/backend_python.cpp +++ b/compiler/backend_python/backend_python.cpp @@ -1,6 +1,7 @@ #include "compiler/backend_python/backend_python.hpp" -#include "compiler/layout/layout.hpp" #include "compiler/diagnostics/diagnostic.hpp" +#include "compiler/layout/layout.hpp" +#include "compiler/support/generated_names.hpp" #include #include @@ -20,6 +21,9 @@ namespace quarry::compiler::backend_python { namespace { +using ::quarry::compiler::layout::FieldStorage; +using ::quarry::compiler::layout::LayoutModel; +using ::quarry::compiler::layout::RecordClassification; using ::quarry::schema_ir::ArrayType; using ::quarry::schema_ir::EnumIR; using ::quarry::schema_ir::EnumValueIR; @@ -28,9 +32,6 @@ using ::quarry::schema_ir::FieldType; using ::quarry::schema_ir::NamespaceIR; using ::quarry::schema_ir::PrimitiveType; using ::quarry::schema_ir::RecordIR; -using ::quarry::compiler::layout::FieldStorage; -using ::quarry::compiler::layout::LayoutModel; -using ::quarry::compiler::layout::RecordClassification; // Compatibility epoch embedded in every generated module's import-time check // (see render_module below). Independent from @@ -82,10 +83,11 @@ using PythonNameSet = std::set; [[nodiscard]] bool is_python_keyword(std::string_view name) { static constexpr std::string_view keywords[] = { - "False", "None", "True", "and", "as", "assert", "async", "await", "break", - "case", "class", "continue", "def", "del", "elif", "else", "except", "finally", - "for", "from", "global", "if", "import", "in", "is", "lambda", "match", "nonlocal", - "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", + "False", "None", "True", "and", "as", "assert", "async", "await", + "break", "case", "class", "continue", "def", "del", "elif", "else", + "except", "finally", "for", "from", "global", "if", "import", "in", + "is", "lambda", "match", "nonlocal", "not", "or", "pass", "raise", + "return", "try", "while", "with", "yield", }; for (const std::string_view keyword : keywords) { if (keyword == name) { @@ -99,8 +101,8 @@ using PythonNameSet = std::set; if (name.size() >= 4U && name.starts_with("__") && name.ends_with("__")) { return true; } - return name.size() >= 3U && name.front() == '_' && name.back() == '_' && - name[1] != '_' && name[name.size() - 2U] != '_'; + return name.size() >= 3U && name.front() == '_' && name.back() == '_' && name[1] != '_' && + name[name.size() - 2U] != '_'; } [[nodiscard]] std::string sanitize_python_identifier(std::string_view original) { @@ -130,9 +132,10 @@ using PythonNameSet = std::set; return result; } -[[nodiscard]] std::optional python_name_for( - std::string_view original, std::string_view context, const PythonNameSet& reserved, - std::string& error_message) { +[[nodiscard]] std::optional python_name_for(std::string_view original, + std::string_view context, + const PythonNameSet& reserved, + std::string& error_message) { std::string generated = sanitize_python_identifier(original); if (generated.starts_with("_quarry_")) { error_message = "backend_python: " + std::string(context) + " '" + std::string(original) + @@ -156,9 +159,9 @@ using PythonNameSet = std::set; if (names.insert(std::string(generated)).second) { return true; } - error_message = "backend_python: " + std::string(context) + " names '" + - std::string(original) + "' and another schema identifier both normalize to '" + - std::string(generated) + "'; generation is ambiguous"; + error_message = "backend_python: " + std::string(context) + " names '" + std::string(original) + + "' and another schema identifier both normalize to '" + std::string(generated) + + "'; generation is ambiguous"; return false; } @@ -178,10 +181,27 @@ using PythonNameSet = std::set; [[nodiscard]] const PythonNameSet& field_reserved_names() { static const PythonNameSet names = { - "IntEnum", "Optional", "_brf", "QUARRY_GENERATED_CODE_API_VERSION_PYTHON", "dataclass", - "encode", "decode", "encoded_size", "fields", - "_array_data", "_count", "_offset", "_index", "_length_offset", "_element_length", - "_error", "_element_end", "_items", "_array_payload", "_item", "_encoded_item", + "IntEnum", + "Optional", + "_brf", + "QUARRY_GENERATED_CODE_API_VERSION_PYTHON", + "dataclass", + "encode", + "decode", + "encoded_size", + "fields", + "_array_data", + "_count", + "_offset", + "_index", + "_length_offset", + "_element_length", + "_error", + "_element_end", + "_items", + "_array_payload", + "_item", + "_encoded_item", }; return names; } @@ -196,12 +216,12 @@ using PythonNameSet = std::set; return names; } -[[nodiscard]] std::optional> sanitize_namespace_parts( - std::string_view fqn, std::string& error_message) { +[[nodiscard]] std::optional> +sanitize_namespace_parts(std::string_view fqn, std::string& error_message) { std::vector result; for (const std::string& original : namespace_parts(fqn)) { - const std::optional generated = - python_name_for(original, "namespace segment", namespace_reserved_names(), error_message); + const std::optional generated = python_name_for( + original, "namespace segment", namespace_reserved_names(), error_message); if (!generated.has_value()) { return std::nullopt; } @@ -226,8 +246,9 @@ using PythonNameSet = std::set; // module lives directly under the output directory with no wrapping // package, mirroring the root-namespace precedent already established by // both existing backends' file_stem_for_namespace equivalents. -[[nodiscard]] std::optional module_path_for_namespace( - const CodegenOptions& options, const std::vector& parts, std::string& error_message) { +[[nodiscard]] std::optional +module_path_for_namespace(const CodegenOptions& options, const std::vector& parts, + std::string& error_message) { static const PythonNameSet no_reserved_names; const std::optional stem = python_name_for( options.root_module_stem, "root module stem", no_reserved_names, error_message); @@ -375,7 +396,7 @@ struct EnumCatalogEntry { // pack_enum()/unpack_enum() as their // `type_name` argument std::vector> values; // (name, value), - // in declaration order + // in declaration order }; using EnumCatalog = std::unordered_map; @@ -455,8 +476,7 @@ using RecordCatalog = std::unordered_map; if (!python_name.has_value()) { return false; } - catalog.emplace(record_ir.ir_id(), - RecordCatalogEntry{*python_name, ns.fqn()}); + catalog.emplace(record_ir.ir_id(), RecordCatalogEntry{*python_name, ns.fqn()}); } for (const NamespaceIR& child : ns.namespaces()) { if (!collect_record_catalog(child, catalog, error_message)) { @@ -471,10 +491,10 @@ struct RecordFieldEncoding { std::string owning_namespace_fqn; }; -[[nodiscard]] std::optional lower_record_reference( - std::uint64_t target_record_ir_id, std::string_view current_namespace_fqn, - const RecordCatalog& catalog, std::string_view context_description, - std::string& error_message) { +[[nodiscard]] std::optional +lower_record_reference(std::uint64_t target_record_ir_id, std::string_view current_namespace_fqn, + const RecordCatalog& catalog, std::string_view context_description, + std::string& error_message) { const auto catalog_it = catalog.find(target_record_ir_id); if (catalog_it == catalog.end()) { return std::nullopt; @@ -497,8 +517,8 @@ struct RecordFieldEncoding { // user-facing diagnostic path. [[nodiscard]] std::optional lower_enum_reference(std::uint64_t target_enum_ir_id, std::string_view current_namespace_fqn, - const EnumCatalog& catalog, std::string_view context_description, - std::string& error_message) { + const EnumCatalog& catalog, std::string_view context_description, + std::string& error_message) { const auto catalog_it = catalog.find(target_enum_ir_id); if (catalog_it == catalog.end()) { return std::nullopt; @@ -514,8 +534,7 @@ lower_enum_reference(std::uint64_t target_enum_ir_id, std::string_view current_n error_message = stream.str(); return std::nullopt; } - return EnumFieldEncoding{entry.class_name, entry.width_type_name, - entry.owning_namespace_fqn}; + return EnumFieldEncoding{entry.class_name, entry.width_type_name, entry.owning_namespace_fqn}; } // --- Planning ------------------------------------------------------------- @@ -607,16 +626,14 @@ struct PlannedNamespaceFile { } // Resolves one field's type: a scalar primitive, a non-negative-valued enum -// reference, a bounded string/bytes field, a nested record reference, or a bounded array of one of the -// supported non-record element kinds. -// Returns std::nullopt (with error_message set) for every unsupported -// case: a non-scalar/non-enum/non-string/non-bytes type; an enum declared -// with a negative declared value. +// reference, a bounded string/bytes field, a nested record reference, or a bounded array of one of +// the supported non-record element kinds. Returns std::nullopt (with error_message set) for every +// unsupported case: a non-scalar/non-enum/non-string/non-bytes type; an enum declared with a +// negative declared value. [[nodiscard]] std::optional lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, - std::string_view current_namespace_fqn, const EnumCatalog& enum_catalog, - const RecordCatalog& record_catalog, - std::string& error_message) { + std::string_view current_namespace_fqn, const EnumCatalog& enum_catalog, + const RecordCatalog& record_catalog, std::string& error_message) { const FieldType& type = field_ir.type(); // Plain sequential member assignment (not a brace-enclosed designated @@ -632,9 +649,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // toolchain, not reproduced locally under Clang. if (type.kind_case() == FieldType::kEnumType) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "'"; - std::optional encoding = lower_enum_reference( - type.enum_type().target_enum_ir_id(), current_namespace_fqn, enum_catalog, context, - error_message); + std::optional encoding = + lower_enum_reference(type.enum_type().target_enum_ir_id(), current_namespace_fqn, + enum_catalog, context, error_message); if (encoding.has_value()) { PlannedField field; field.name = field_ir.name(); @@ -674,9 +691,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return field; } else if (type.kind_case() == FieldType::kRecord) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "'"; - const std::optional record_encoding = lower_record_reference( - type.record().target_record_ir_id(), current_namespace_fqn, record_catalog, context, - error_message); + const std::optional record_encoding = + lower_record_reference(type.record().target_record_ir_id(), current_namespace_fqn, + record_catalog, context, error_message); if (record_encoding.has_value()) { PlannedField field; field.name = field_ir.name(); @@ -708,9 +725,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else if (element_type.kind_case() == FieldType::kEnumType) { const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "' array element type"; - enum_encoding = lower_enum_reference(element_type.enum_type().target_enum_ir_id(), - current_namespace_fqn, enum_catalog, context, - error_message); + enum_encoding = + lower_enum_reference(element_type.enum_type().target_enum_ir_id(), + current_namespace_fqn, enum_catalog, context, error_message); element_is_enum = enum_encoding.has_value(); } if (scalar_encoding.has_value()) { @@ -764,8 +781,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, const std::string context = "field '" + record_ir.fqn() + "." + field_ir.name() + "' array element type"; const std::optional record_encoding = lower_record_reference( - element_type.record().target_record_ir_id(), current_namespace_fqn, - record_catalog, context, error_message); + element_type.record().target_record_ir_id(), current_namespace_fqn, record_catalog, + context, error_message); if (record_encoding.has_value()) { PlannedField field; field.name = field_ir.name(); @@ -868,7 +885,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, if (ordered.size() != records.size()) { error_message = "backend_python: detected a cycle in nested record " - "declaration dependencies in namespace '" + std::string(namespace_fqn) + + "declaration dependencies in namespace '" + + std::string(namespace_fqn) + "' -- a record cannot embed itself, directly or transitively, by value"; return false; } @@ -890,10 +908,11 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, for (std::size_t index = 0; index < planned_record.fields.size(); ++index) { const auto& canonical = layout->fields[index]; PlannedField& field = planned_record.fields[index]; - if (canonical.field_index != field.field_index || canonical.name != record_ir.fields( - static_cast(index)).name()) { + if (canonical.field_index != field.field_index || + canonical.name != record_ir.fields(static_cast(index)).name()) { error_message = "backend_python: canonical BRF v2 layout field order disagrees with " - "Schema IR for record '" + record_ir.fqn() + "'"; + "Schema IR for record '" + + record_ir.fqn() + "'"; return false; } field.byte_offset = canonical.location.byte_offset; @@ -929,17 +948,22 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // record and field for any field whose type is not one of the eleven // supported scalar primitives or a same-namespace non-negative-valued // enum reference. -[[nodiscard]] bool collect_namespace_files(const NamespaceIR& ns, const CodegenOptions& options, - const EnumCatalog& enum_catalog, - const RecordCatalog& record_catalog, - const LayoutModel& layout_model, - std::vector& files, - std::set& ancestor_init_paths, - std::string& error_message) { +[[nodiscard]] bool +collect_namespace_files(const NamespaceIR& ns, const CodegenOptions& options, + const EnumCatalog& enum_catalog, const RecordCatalog& record_catalog, + const LayoutModel& layout_model, std::vector& files, + std::set& ancestor_init_paths, std::string& error_message) { + if (!support::valid_prefix_for_namespace(options.name_prefix, ns.fqn())) { + error_message = + "invalid or conflicting --name-prefix '" + options.name_prefix + + "': use an unreserved identifier distinct from every namespace's first segment"; + return false; + } + if (namespace_emits_file(ns)) { PlannedNamespaceFile file; - const std::optional> safe_namespace = - sanitize_namespace_parts(ns.fqn(), error_message); + const std::optional> safe_namespace = sanitize_namespace_parts( + support::named_namespace(options.name_prefix, ns.fqn()), error_message); if (!safe_namespace.has_value()) { return false; } @@ -967,16 +991,15 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, planned_enum.class_name = entry.class_name; PythonNameSet enum_members; for (const auto& [value_name, value] : entry.values) { - const std::optional python_member = - python_name_for(value_name, "enum member", enum_member_reserved_names(), - error_message); + const std::optional python_member = python_name_for( + value_name, "enum member", enum_member_reserved_names(), error_message); if (!python_member.has_value() || !insert_python_name(enum_members, *python_member, value_name, "enum member", error_message)) { return false; } - planned_enum.values.push_back(PlannedEnumValue{.name = *python_member, - .value = value}); + planned_enum.values.push_back( + PlannedEnumValue{.name = *python_member, .value = value}); } file.enums.push_back(std::move(planned_enum)); } @@ -1001,15 +1024,14 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, std::vector dependencies; planned_fields.reserve(static_cast(record_ir.fields_size())); for (const FieldIR& field_ir : record_ir.fields()) { - std::optional planned_field = - lower_field_encoding(record_ir, field_ir, ns.fqn(), enum_catalog, - record_catalog, error_message); + std::optional planned_field = lower_field_encoding( + record_ir, field_ir, ns.fqn(), enum_catalog, record_catalog, error_message); if (!planned_field.has_value()) { return false; } - const std::optional python_field_name = python_name_for( - field_ir.name(), "field '" + record_ir.fqn() + "'", field_reserved_names(), - error_message); + const std::optional python_field_name = + python_name_for(field_ir.name(), "field '" + record_ir.fqn() + "'", + field_reserved_names(), error_message); if (!python_field_name.has_value() || !insert_python_name(field_names, *python_field_name, field_ir.name(), "field in record '" + record_ir.fqn() + "'", @@ -1017,8 +1039,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, return false; } planned_field->name = *python_field_name; - if (planned_field->is_record && - planned_field->target_namespace_fqn == ns.fqn()) { + if (planned_field->is_record && planned_field->target_namespace_fqn == ns.fqn()) { dependencies.push_back(planned_field->record_target_ir_id); } planned_fields.push_back(std::move(*planned_field)); @@ -1044,8 +1065,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, for (const NamespaceIR& child : ns.namespaces()) { if (!collect_namespace_files(child, options, enum_catalog, record_catalog, layout_model, - files, - ancestor_init_paths, error_message)) { + files, ancestor_init_paths, error_message)) { return false; } } @@ -1056,13 +1076,11 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // so the two modes cannot diverge -- the same discipline // compiler/backend/backend.cpp and compiler/backend_c/backend_c.cpp already // document for C++ and C respectively. -[[nodiscard]] bool build_generation_plan(const schema_ir::SchemaIrModel& schema_ir, - const CodegenOptions& options, - const output_planning::OutputPlan* output_plan, - const LayoutModel& layout_model, - std::vector& init_file_paths, - std::vector& module_files, - std::string& error_message) { +[[nodiscard]] bool +build_generation_plan(const schema_ir::SchemaIrModel& schema_ir, const CodegenOptions& options, + const output_planning::OutputPlan* output_plan, + const LayoutModel& layout_model, std::vector& init_file_paths, + std::vector& module_files, std::string& error_message) { EnumCatalog enum_catalog; if (!collect_enum_catalog(schema_ir.root_namespace(), enum_catalog, error_message)) { return false; @@ -1075,8 +1093,7 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, std::set ancestor_init_paths; if (!collect_namespace_files(schema_ir.root_namespace(), options, enum_catalog, record_catalog, - layout_model, - module_files, ancestor_init_paths, error_message)) { + layout_model, module_files, ancestor_init_paths, error_message)) { return false; } @@ -1124,8 +1141,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, if (module_it == module_name_by_namespace.end() || (output_plan != nullptr && !planned_namespaces.contains(field.target_namespace_fqn))) { - error_message = "backend_python: field '" + file.source_namespace_fqn + - "." + record.name + "." + field.name + + error_message = "backend_python: field '" + file.source_namespace_fqn + "." + + record.name + "." + field.name + " references external namespace '" + field.target_namespace_fqn + "' whose generated module is not in the compiler output plan"; @@ -1136,10 +1153,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, if (alias.empty()) { alias = "_quarry_dep_"; for (const char ch : module_it->second) { - alias.push_back((std::isalnum(static_cast(ch)) != 0 || - ch == '_') - ? ch - : '_'); + alias.push_back( + (std::isalnum(static_cast(ch)) != 0 || ch == '_') ? ch + : '_'); } } const std::string type_expression = alias + "." + field.python_type_hint; @@ -1164,16 +1180,18 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // remain available through the same output tree. Direct backend use // (without an OutputPlan) retains its historical all-modules behavior. if (output_plan != nullptr) { - module_files.erase( - std::remove_if(module_files.begin(), module_files.end(), - [&emitting_namespaces](const PlannedNamespaceFile& file) { - return !emitting_namespaces.contains(file.source_namespace_fqn); - }), - module_files.end()); + module_files.erase(std::remove_if(module_files.begin(), module_files.end(), + [&emitting_namespaces](const PlannedNamespaceFile& file) { + return !emitting_namespaces.contains( + file.source_namespace_fqn); + }), + module_files.end()); ancestor_init_paths.clear(); for (const PlannedNamespaceFile& file : module_files) { std::string safe_error; - const auto safe_namespace = sanitize_namespace_parts(file.source_namespace_fqn, safe_error); + const auto safe_namespace = sanitize_namespace_parts( + support::named_namespace(options.name_prefix, file.source_namespace_fqn), + safe_error); if (!safe_namespace.has_value()) { error_message = std::move(safe_error); return false; @@ -1218,9 +1236,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, stream << ", "; } const PlannedField& field = record.fields[index]; - stream << "(" << field.field_index << ", " << field.byte_offset << ", " - << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ")"; + stream << "(" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size + << ", " << field.storage_kind << ", " << field.presence_bit_index << ")"; } stream << "]"; return stream.str(); @@ -1251,10 +1268,9 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, // Bare PEP 585 list[...] subscription -- no new import needed // beyond the already-emitted `from typing import Optional`. const std::string type_expression = field.python_type_expression.empty() - ? field.python_type_hint - : field.python_type_expression; - const std::string hint = - field.is_array ? "list[" + type_expression + "]" : type_expression; + ? field.python_type_hint + : field.python_type_expression; + const std::string hint = field.is_array ? "list[" + type_expression + "]" : type_expression; stream << " " << field.name << ": Optional[" << hint << "] = None\n"; } stream << "\n"; @@ -1277,7 +1293,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, if (field.is_array && field.is_record) { stream << " _items = value." << field.name << "\n"; stream << " if len(_items) > " << field.array_max_elements << ":\n"; - stream << " raise _brf.EncodeError(\"array length \" + str(len(_items)) + \" exceeds max_elements=" + stream << " raise _brf.EncodeError(\"array length \" + str(len(_items)) + " + "\" exceeds max_elements=" << field.array_max_elements << "\")\n"; stream << " _array_payload = bytearray()\n"; stream << " _brf.append_varuint(_array_payload, len(_items))\n"; @@ -1294,37 +1311,36 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else if (field.is_array && field.is_string) { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_array_of_string(value." << field.name << ", " - << field.array_max_elements << ", " << field.string_max_bytes << ")))\n"; + << field.presence_bit_index << ", _brf.pack_array_of_string(value." << field.name + << ", " << field.array_max_elements << ", " << field.string_max_bytes << ")))\n"; } else if (field.is_array && field.is_bytes) { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_array_of_bytes(value." << field.name << ", " - << field.array_max_elements << ", " << field.bytes_max_bytes << ")))\n"; + << field.presence_bit_index << ", _brf.pack_array_of_bytes(value." << field.name + << ", " << field.array_max_elements << ", " << field.bytes_max_bytes << ")))\n"; } else if (field.is_array && field.is_enum) { const std::string type_expression = field.python_type_expression.empty() - ? field.python_type_hint - : field.python_type_expression; + ? field.python_type_hint + : field.python_type_expression; stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_array_of_enum(" << type_expression << ", \"" - << field.runtime_type_name << "\", value." << field.name << ", " + << field.presence_bit_index << ", _brf.pack_array_of_enum(" << type_expression + << ", \"" << field.runtime_type_name << "\", value." << field.name << ", " << field.array_max_elements << ")))\n"; } else if (field.is_array) { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_array_of_scalar(\"" << field.runtime_type_name - << "\", value." << field.name << ", " << field.array_max_elements - << ")))\n"; + << field.presence_bit_index << ", _brf.pack_array_of_scalar(\"" + << field.runtime_type_name << "\", value." << field.name << ", " + << field.array_max_elements << ")))\n"; } else if (field.is_enum) { const std::string type_expression = field.python_type_expression.empty() - ? field.python_type_hint - : field.python_type_expression; + ? field.python_type_hint + : field.python_type_expression; stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_enum(" - << type_expression << ", value." << field.name << ", \"" - << field.runtime_type_name << "\")))\n"; + << field.presence_bit_index << ", _brf.pack_enum(" << type_expression + << ", value." << field.name << ", \"" << field.runtime_type_name << "\")))\n"; } else if (field.is_string) { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " @@ -1338,13 +1354,13 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else if (field.is_record) { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", " << field.record_encode_expression << "(value." - << field.name << ")))\n"; + << field.presence_bit_index << ", " << field.record_encode_expression + << "(value." << field.name << ")))\n"; } else { stream << " fields.append((" << field.field_index << ", " << field.byte_offset << ", " << field.slot_size << ", " << field.storage_kind << ", " - << field.presence_bit_index << ", _brf.pack_scalar(\"" - << field.runtime_type_name << "\", value." << field.name << ")))\n"; + << field.presence_bit_index << ", _brf.pack_scalar(\"" << field.runtime_type_name + << "\", value." << field.name << ")))\n"; } if (field.is_array || field.is_string || field.is_bytes) { // Pack first so empty values cannot bypass type/bounds validation. @@ -1370,9 +1386,10 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, stream << " _count, _offset = _brf.read_varuint(_array_data, 0)\n"; stream << " except _brf.DecodeError as _error:\n"; stream << " raise _brf.DecodeError(\"malformed array count varuint at byte " - "offset 0: \" + str(_error)) from _error\n"; + "offset 0: \" + str(_error)) from _error\n"; stream << " if _count > " << field.array_max_elements << ":\n"; - stream << " raise _brf.DecodeError(\"array count \" + str(_count) + \" exceeds max_elements=" + stream << " raise _brf.DecodeError(\"array count \" + str(_count) + \" " + "exceeds max_elements=" << field.array_max_elements << "\")\n"; stream << " " << field.name << " = []\n"; stream << " for _index in range(_count):\n"; @@ -1382,22 +1399,27 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, } else { stream << " _length_offset = _offset\n"; stream << " try:\n"; - stream << " _element_length, _offset = _brf.read_varuint(_array_data, _offset)\n"; + stream << " _element_length, _offset = " + "_brf.read_varuint(_array_data, _offset)\n"; stream << " except _brf.DecodeError as _error:\n"; - stream << " raise _brf.DecodeError('malformed element length varuint for ' + str(_index) + ' at byte offset ' + str(_length_offset) + ': ' + str(_error)) from _error\n"; + stream << " raise _brf.DecodeError('malformed element length " + "varuint for ' + str(_index) + ' at byte offset ' + str(_length_offset) " + "+ ': ' + str(_error)) from _error\n"; } stream << " if _element_length > len(_array_data) - _offset:\n"; - stream << " raise _brf.DecodeError('truncated array element ' + str(_index) + ' payload at byte offset ' + str(_offset))\n"; + stream << " raise _brf.DecodeError('truncated array element ' + " + "str(_index) + ' payload at byte offset ' + str(_offset))\n"; stream << " _element_end = _offset + _element_length\n"; stream << " try:\n"; stream << " " << field.name << ".append(" - << field.record_decode_expression - << "(_array_data[_offset:_element_end]))\n"; + << field.record_decode_expression << "(_array_data[_offset:_element_end]))\n"; stream << " except _brf.DecodeError as _error:\n"; - stream << " raise _brf.DecodeError('array element ' + str(_index) + ' at byte offset ' + str(_offset) + ': ' + str(_error)) from _error\n"; + stream << " raise _brf.DecodeError('array element ' + str(_index) + ' " + "at byte offset ' + str(_offset) + ': ' + str(_error)) from _error\n"; stream << " _offset = _element_end\n"; stream << " if _offset != len(_array_data):\n"; - stream << " raise _brf.DecodeError(\"trailing bytes in record array payload at " + stream + << " raise _brf.DecodeError(\"trailing bytes in record array payload at " "byte offset \" + str(_offset))\n"; } else if (field.is_array && field.is_string) { stream << " " << field.name << " = _brf.unpack_array_of_string(fields[" @@ -1409,20 +1431,19 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, << field.bytes_max_bytes << ")\n"; } else if (field.is_array && field.is_enum) { const std::string type_expression = field.python_type_expression.empty() - ? field.python_type_hint - : field.python_type_expression; - stream << " " << field.name << " = _brf.unpack_array_of_enum(" - << type_expression << ", \"" << field.runtime_type_name - << "\", fields[" << field.field_index << "], " << field.array_max_elements - << ")\n"; + ? field.python_type_hint + : field.python_type_expression; + stream << " " << field.name << " = _brf.unpack_array_of_enum(" << type_expression + << ", \"" << field.runtime_type_name << "\", fields[" << field.field_index + << "], " << field.array_max_elements << ")\n"; } else if (field.is_array) { stream << " " << field.name << " = _brf.unpack_array_of_scalar(\"" << field.runtime_type_name << "\", fields[" << field.field_index << "], " << field.array_max_elements << ")\n"; } else if (field.is_enum) { const std::string type_expression = field.python_type_expression.empty() - ? field.python_type_hint - : field.python_type_expression; + ? field.python_type_hint + : field.python_type_expression; stream << " " << field.name << " = _brf.unpack_enum(" << type_expression << ", \"" << field.runtime_type_name << "\", fields[" << field.field_index << "])\n"; @@ -1433,9 +1454,8 @@ lower_field_encoding(const RecordIR& record_ir, const FieldIR& field_ir, stream << " " << field.name << " = _brf.unpack_bytes(fields[" << field.field_index << "], " << field.bytes_max_bytes << ")\n"; } else if (field.is_record) { - stream << " " << field.name << " = " - << field.record_decode_expression << "(fields[" - << field.field_index << "])\n"; + stream << " " << field.name << " = " << field.record_decode_expression + << "(fields[" << field.field_index << "])\n"; } else { stream << " " << field.name << " = _brf.unpack_scalar(\"" << field.runtime_type_name << "\", fields[" << field.field_index << "])\n"; @@ -1578,7 +1598,7 @@ void render_identity_and_dependency_imports(std::ostringstream& stream, } // namespace std::string output_path_for_planned_file(const CodegenOptions& options, - std::string_view relative_path) { + std::string_view relative_path) { if (options.output_directory.empty()) { return std::string(relative_path); } diff --git a/compiler/backend_python/backend_python.hpp b/compiler/backend_python/backend_python.hpp index b652764..3482cd8 100644 --- a/compiler/backend_python/backend_python.hpp +++ b/compiler/backend_python/backend_python.hpp @@ -18,6 +18,8 @@ struct CodegenOptions { // Required for generate(), ignored by plan(). The schema compiler computes it // once from the resolved configuration; see missing_configuration_identity_message. std::optional configuration_identity; + // Explicit source naming only; canonical Schema IR and schema_id are unchanged. + std::string name_prefix = ""; }; struct GeneratedFile { diff --git a/compiler/support/generated_names.hpp b/compiler/support/generated_names.hpp new file mode 100644 index 0000000..c292919 --- /dev/null +++ b/compiler/support/generated_names.hpp @@ -0,0 +1,191 @@ +#pragma once + +#include "compiler/support/namespace_macro.hpp" + +#include +#include +#include +#include +#include + +// Source naming only. Canonical Schema IR FQNs and identity-input keys never +// pass through this projection. Empty prefixes preserve every old spelling. +namespace quarry::compiler::support { + +[[nodiscard]] inline bool valid_name_prefix(std::string_view prefix) { + if (!is_unreserved_macro_identifier(prefix) || prefix == "quarry" || prefix == "std" || + prefix == "kQuarrySchemaId" || prefix == "kQuarrySchemaIdAlgorithm" || + prefix == "kQuarryGeneratedCodeId" || prefix == "kQuarryGeneratedCodeIdFormat" || + prefix.starts_with("quarry_gen_") || prefix.starts_with("quarry_cfg_")) { + return false; + } + // A prefix is used literally in C++ namespaces and Python packages. Use + // one portable spelling for all backends, rather than silently renaming it. + static constexpr std::string_view keywords[] = {"alignas", + "alignof", + "and", + "and_eq", + "asm", + "auto", + "bitand", + "bitor", + "bool", + "break", + "case", + "catch", + "char", + "char8_t", + "char16_t", + "char32_t", + "class", + "compl", + "concept", + "const", + "consteval", + "constexpr", + "constinit", + "const_cast", + "continue", + "co_await", + "co_return", + "co_yield", + "decltype", + "default", + "delete", + "do", + "double", + "dynamic_cast", + "else", + "enum", + "explicit", + "export", + "extern", + "false", + "float", + "for", + "friend", + "goto", + "if", + "inline", + "int", + "long", + "mutable", + "namespace", + "new", + "noexcept", + "not", + "not_eq", + "nullptr", + "operator", + "or", + "or_eq", + "private", + "protected", + "public", + "register", + "reinterpret_cast", + "requires", + "restrict", + "return", + "short", + "signed", + "sizeof", + "static", + "static_assert", + "static_cast", + "struct", + "switch", + "template", + "this", + "thread_local", + "throw", + "true", + "try", + "typedef", + "typeid", + "typename", + "union", + "unsigned", + "using", + "virtual", + "void", + "volatile", + "wchar_t", + "while", + "xor", + "xor_eq", + "False", + "None", + "True", + "as", + "assert", + "async", + "await", + "def", + "del", + "elif", + "except", + "finally", + "from", + "global", + "import", + "in", + "is", + "lambda", + "nonlocal", + "pass", + "raise", + "with", + "yield", + "chan", + "defer", + "fallthrough", + "func", + "go", + "interface", + "map", + "match", + "package", + "range", + "select", + "type", + "var"}; + return std::find(std::begin(keywords), std::end(keywords), prefix) == std::end(keywords); +} + +[[nodiscard]] inline bool valid_prefix_for_namespace(std::string_view prefix, + std::string_view fqn) { + return prefix.empty() || (valid_name_prefix(prefix) && fqn.substr(0, fqn.find('.')) != prefix); +} + +[[nodiscard]] inline std::string named_namespace(std::string_view prefix, std::string_view fqn) { + if (prefix.empty()) { + return std::string(fqn); + } + return std::string(prefix) + (fqn.empty() ? "" : "." + std::string(fqn)); +} + +[[nodiscard]] inline std::string named_path(std::string_view prefix, std::string_view path) { + return prefix.empty() ? std::string(path) : std::string(prefix) + "/" + std::string(path); +} + +[[nodiscard]] inline std::string named_macro_body(std::string_view prefix, std::string_view fqn) { + if (prefix.empty()) { + return encode_namespace_macro(fqn).value_or(""); + } + std::vector segments{prefix}; + while (!fqn.empty()) { + const auto end = fqn.find('.'); + segments.push_back(fqn.substr(0, end)); + if (end == std::string_view::npos) { + break; + } + fqn.remove_prefix(end + 1U); + if (fqn.empty()) { + return ""; // A trailing separator is not a canonical namespace. + } + } + return encode_namespace_macro_segments(segments).value_or(""); +} + +} // namespace quarry::compiler::support diff --git a/compiler/support/namespace_macro.hpp b/compiler/support/namespace_macro.hpp index e9d5c40..b90365d 100644 --- a/compiler/support/namespace_macro.hpp +++ b/compiler/support/namespace_macro.hpp @@ -13,7 +13,7 @@ // never contains a reserved identifier spelling. Output paths, file extensions, // root file stems and --generate do not enter the encoding. // -// A future --name-prefix (A4.5, #102) is a leading segment of this encoding, +// --name-prefix (A4.5, #102) is a leading segment of this encoding, // not text concatenated onto it. Call encode_namespace_macro_segments with the // prefix segment first. This header does not implement the flag. // @@ -74,7 +74,7 @@ inline constexpr std::string_view kCNamespaceAccessorPrefix = "quarry_ns_"; // identifier or a separator is empty, leading or trailing. [[nodiscard]] std::optional encode_namespace_macro(std::string_view namespace_fqn); -// Body of `segments` in order. An empty span is the root body "0". A future +// Body of `segments` in order. An empty span is the root body "0". An explicit // --name-prefix passes its identifier as the first segment, ahead of the // namespace segments. nullopt when any segment is not an identifier. [[nodiscard]] std::optional diff --git a/cortex_m/CMakeLists.txt b/cortex_m/CMakeLists.txt index 1ae69e3..5922b32 100644 --- a/cortex_m/CMakeLists.txt +++ b/cortex_m/CMakeLists.txt @@ -87,14 +87,19 @@ set(QUARRY_SHARED_SCHEMA "${QUARRY_SCHEMAS_DIR}/workload_shared.brd") set(QUARRY_WORKLOAD_SCHEMA "${QUARRY_SCHEMAS_DIR}/workload.brd") set(QUARRY_GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated") +option(QUARRY_SMOKE_PREFIXED "Use the fixed rev_a source naming experiment" OFF) +set(QUARRY_GENERATED_BINDING_ROOT "${QUARRY_GENERATED_DIR}") +if(QUARRY_SMOKE_PREFIXED) + string(APPEND QUARRY_GENERATED_BINDING_ROOT "/rev_a") +endif() set(QUARRY_GENERATED_SHARED_HEADER - "${QUARRY_GENERATED_DIR}/benchmark/workload/shared.generated.h") + "${QUARRY_GENERATED_BINDING_ROOT}/benchmark/workload/shared.generated.h") set(QUARRY_GENERATED_SHARED_SOURCE - "${QUARRY_GENERATED_DIR}/benchmark/workload/shared.generated.c") + "${QUARRY_GENERATED_BINDING_ROOT}/benchmark/workload/shared.generated.c") set(QUARRY_GENERATED_WORKLOAD_HEADER - "${QUARRY_GENERATED_DIR}/benchmark/workload.generated.h") + "${QUARRY_GENERATED_BINDING_ROOT}/benchmark/workload.generated.h") set(QUARRY_GENERATED_WORKLOAD_SOURCE - "${QUARRY_GENERATED_DIR}/benchmark/workload.generated.c") + "${QUARRY_GENERATED_BINDING_ROOT}/benchmark/workload.generated.c") # Both namespaces are generated from one compilation root, workload.brd # (which imports workload_shared.brd), so they share one configuration @@ -118,6 +123,10 @@ elseif(NOT QUARRY_C_OPTIMIZE_SIZE STREQUAL "") list(APPEND QUARRY_C_STORAGE_DEFINITIONS QUARRY_SMOKE_COMPACT_SHARED) endif() endif() +if(QUARRY_SMOKE_PREFIXED) + list(APPEND QUARRY_C_STORAGE_ARGUMENTS --name-prefix rev_a) + list(APPEND QUARRY_C_STORAGE_DEFINITIONS QUARRY_SMOKE_PREFIXED=1) +endif() add_custom_command( OUTPUT "${QUARRY_GENERATED_SHARED_HEADER}" "${QUARRY_GENERATED_SHARED_SOURCE}" "${QUARRY_GENERATED_WORKLOAD_HEADER}" "${QUARRY_GENERATED_WORKLOAD_SOURCE}" diff --git a/cortex_m/README.md b/cortex_m/README.md index 7b9e473..db93c87 100644 --- a/cortex_m/README.md +++ b/cortex_m/README.md @@ -144,3 +144,18 @@ policy of each namespace. Compare equivalent policies to detect implementation overhead. Comparing default and compact policies instead measures expected native layout and codec changes; those differences are not overhead introduced by namespace selection. + +## Explicit source-prefix comparison + +`-DQUARRY_SMOKE_PREFIXED=ON` runs the same smoke workload against bindings +created with the fixed test prefix `rev_a`. A validation-only adapter maps the +smoke consumer to the approved encoded C names; generated files are untouched. +The option defaults to OFF and changes no runtime API or schema identity. + +CI compares plain and prefixed builds under identical toolchain/linker settings +in Default, MinSizeRel and Debug. `name-prefix-report.md` reports actual +allocatable bytes, relocations and defined symbols, and the artifact includes +raw symbol dumps. Renamed symbols, function-section names and debug paths may +differ, so a naming-only change is not described as an identical object file. +Inspect linked flash/RAM and section contents separately from those names. +Stack/heap high-water marks and execution on physical hardware are not measured. diff --git a/cortex_m/smoke/name_prefix_adapter.h b/cortex_m/smoke/name_prefix_adapter.h new file mode 100644 index 0000000..a55130a --- /dev/null +++ b/cortex_m/smoke/name_prefix_adapter.h @@ -0,0 +1,34 @@ +/* Validation-only adapter for the fixed --name-prefix rev_a experiment. + * Both builds execute the same workload. No aliases enter generated bindings. */ +#ifndef QUARRY_CORTEX_M_NAME_PREFIX_ADAPTER_H +#define QUARRY_CORTEX_M_NAME_PREFIX_ADAPTER_H +#include "rev_a/benchmark/workload.generated.h" +#define benchmark_workload_Workload_t revq0a_benchmark_workload_Workload_t +#define benchmark_workload_Workload_init revq0a_benchmark_workload_Workload_init +#define benchmark_workload_Workload_encode_result_t \ + revq0a_benchmark_workload_Workload_encode_result_t +#define benchmark_workload_Workload_encode revq0a_benchmark_workload_Workload_encode +#define benchmark_workload_Workload_decode_result_t \ + revq0a_benchmark_workload_Workload_decode_result_t +#define benchmark_workload_Workload_decode revq0a_benchmark_workload_Workload_decode +#define benchmark_workload_shared_Child_t revq0a_benchmark_workload_shared_Child_t +#define benchmark_workload_shared_Child_init revq0a_benchmark_workload_shared_Child_init +#define BENCHMARK_WORKLOAD_STATUS_ACTIVE revq0a_benchmark_workload_STATUS_ACTIVE +#define quarry_ns_benchmark_workload_schema_id quarry_ns_revq0a_benchmark_workload_schema_id +#define benchmark_workload_Workload_set_sequence_present \ + revq0a_benchmark_workload_Workload_set_sequence_present +#define benchmark_workload_Workload_set_timestamp_present \ + revq0a_benchmark_workload_Workload_set_timestamp_present +#define benchmark_workload_Workload_set_counter_present \ + revq0a_benchmark_workload_Workload_set_counter_present +#define benchmark_workload_Workload_set_ratio_present \ + revq0a_benchmark_workload_Workload_set_ratio_present +#define benchmark_workload_Workload_set_enabled_present \ + revq0a_benchmark_workload_Workload_set_enabled_present +#define benchmark_workload_Workload_set_status_present \ + revq0a_benchmark_workload_Workload_set_status_present +#define benchmark_workload_Workload_set_child_present \ + revq0a_benchmark_workload_Workload_set_child_present +#define benchmark_workload_shared_Child_set_id_present \ + revq0a_benchmark_workload_shared_Child_set_id_present +#endif diff --git a/cortex_m/smoke/workload_smoke.c b/cortex_m/smoke/workload_smoke.c index bd975f8..eb178f4 100644 --- a/cortex_m/smoke/workload_smoke.c +++ b/cortex_m/smoke/workload_smoke.c @@ -10,7 +10,11 @@ * hosted I/O facility, and so the calls cannot be optimized away as unused. */ +#if defined(QUARRY_SMOKE_PREFIXED) +#include "name_prefix_adapter.h" +#else #include "benchmark/workload.generated.h" +#endif #ifdef QUARRY_SMOKE_COMPACT_WORKLOAD #define WORKLOAD_PRESENT(record, field) benchmark_workload_Workload_set_##field##_present(record, true) diff --git a/docs/design/configuration-identity.md b/docs/design/configuration-identity.md index a2e1cb6..dcc58c1 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.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) +Status: **approved; A4.1–A4.5 and #111 G1–G5 implemented**. 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. @@ -101,8 +100,7 @@ but the actual declarations are inside Guards are keyed by namespace and `gid`; dependencies check both identities. Different generated definitions can coexist in separate TUs; incompatible -versions of one namespace in the same TU are rejected. No `--name-prefix` -workaround exists today. User-defined inline functions and prebuilt native +versions of one namespace in the same TU are rejected. Use explicit, distinct `--name-prefix` values for deliberate same-TU coexistence (§5). User-defined inline functions and prebuilt native interfaces remain the consumer's responsibility, even when their signatures hide use of generated types. @@ -191,11 +189,11 @@ The composed macro is a prefix that ends in one `_`, the body, and a suffix that the whole identifier matches `[A-Za-z][A-Za-z0-9_]*`. It is a C and C++ macro name and not a reserved identifier. -A future `--name-prefix` (#102) is a leading segment of this encoding, not text concatenated onto +`--name-prefix` (#102) is a leading segment of this encoding, not text concatenated onto it. `encode_namespace_macro_segments` takes the prefix identifier first. A prefix `rev_a` on `truck.engine` encodes as `revq0a_truck_engine`. A prefix `rev_` on `a_b` encodes as `revq0_aq0b`. Concatenating the prefix onto an already encoded body would not be injective. -The flag is not implemented. +The flag is opt-in and does not change canonical namespace FQNs. The canonical generated-code identity format stays 1. Renderers still write the `M` placeholder; only the substituted stem is this encoding. The `CODE_ID` prefix and the identity guard are @@ -209,33 +207,48 @@ configuration-identity check reports that it predates generated configuration id ## 5. Deliberate multiple configurations -### 5.1 Proposed A4.5: `--name-prefix ` (not implemented) +### 5.1 Implemented A4.5: `--name-prefix ` -The following describes the proposed option, which the current CLI rejects. -In that proposal `--name-prefix` is optional and off by default. Bindings are generated as if every namespace were +`--name-prefix` is optional and off by default. Bindings are generated as if every namespace were nested under ``, which changes names and paths only: | Backend | Without prefix | With `--name-prefix rev_a` | |---|---|---| -| C types, functions | `truck_engine_EngineStatus_t` | `rev_a_truck_engine_EngineStatus_t` | +| C types, functions | `truck_engine_EngineStatus_t` | `revq0a_truck_engine_EngineStatus_t` | | C macros | `QUARRY_NS_truck_engine_SCHEMA_ID_W0` | `QUARRY_NS_revq0a_truck_engine_SCHEMA_ID_W0` | | C/C++ files, includes | `truck/engine.generated.h` | `rev_a/truck/engine.generated.h` | -| Header guards | `QUARRY_GENERATED_C_TRUCK_ENGINE_…` | `QUARRY_GENERATED_C_REV_A_TRUCK_ENGINE_…` | -| C++ namespace | `truck::engine` (+ inline cfg namespace) | `rev_a::truck::engine` (+ inline cfg namespace) | -| C++/C-storage wrappers | `quarry::cxx::truck_engine_EngineStatus` | `quarry::cxx::rev_a_truck_engine_EngineStatus` | +| Header guards | `QUARRY_GENERATED_C_NS_truck_engine__` | `QUARRY_GENERATED_C_NS_revq0a_truck_engine__` | +| C++ namespace | `truck::engine` (+ inline `quarry_gen_` namespace) | `rev_a::truck::engine` (+ inline `quarry_gen_` namespace) | +| C++/C-storage wrappers | `quarry::cxx::truck_engine_EngineStatus` | `quarry::cxx::revq0a_truck_engine_EngineStatus` | | Python modules | `truck.engine.schema` | `rev_a.truck.engine.schema` (with `rev_a/__init__.py`) | | Go packages | `/truck/engine`, package `engine` | `/rev_a/truck/engine`, package `engine` | - **Unaffected:** record IDs, Schema IR, QBS (FQNs stay `truck.engine.EngineStatus`) and `schema_id`. - **Byte-identity baseline (#102).** Output without `--name-prefix` is the output after #117. It is not the A4.2 spelling: #117 renamed the C and C++ identity macros. Python and Go output - without the flag stays byte-identical to their current output. The prefix, when implemented, + without the flag stays byte-identical to their current output. The prefix uses §4.6 with the prefix as the leading segment. - **Validation:** the prefix must be a valid identifier and must not equal a namespace's first segment. - **Mismatched prefixes:** when dependencies are generated with different prefixes, the dependency include or import path doesn't exist, so the build fails visibly. +**Approved prefixed-only C correction (#102 / #119).** Prefixes and canonical +namespace segments use §4.6's injective encoding for C symbols as well as macros. +Thus `rev_a` + `dep.engine` and `rev` + `a_dep.engine` produce different stems, +`revq0a_dep_engine_` and `rev_aq0dep_engine_`. Prefixed enum constants preserve the +encoded namespace's case, so case-only prefixes do not merge C enumerators. +C-storage wrappers use the same stem. This optional naming rule was approved +separately; it does not migrate unprefixed symbols or close #119. Existing +backend rules for record/enum/member identifiers still apply. + +Prefixes use portable, unreserved identifiers and are checked against the entire +resolved namespace tree, including unselected namespaces. The +[CLI contract](../../tools/README.md#deliberate-source-naming-isolation) specifies +validation and query behavior. The existing format-1 algorithm hashes changed +emitted definitions normally; it need not retain the same `gid` under a prefix. +Canonical identity-input namespace keys, `schema_id` and wire bytes stay unchanged. + **When a prefix is needed:** | Language | Two configurations in one program, separate translation units/files | In one translation unit or module | @@ -252,21 +265,21 @@ Alternatives considered: 2. **Relative imports in Python.** These would make the package tree relocatable without an option, but would change the backend's deliberate absolute-import design. I don't recommend it for A4. -### 5.2 Proposed A4.5 truck cloud application with two vehicle configurations +### 5.2 Truck cloud application with two vehicle configurations The fleet runs revision A (`class8_truck`, `9200ca494f010801b830d0857cf66dde`) and revision B, which -adds `truck.cms.MirrorFold` (`class8_truck_rev_b`, `acf1443058daea59db96ff373869a4be`). In both, +adds `truck.cms.MirrorFold` with one `folded: bool` field (`class8_truck_rev_b`, `806e9a4e11d0df71c4e5b51045f85010`). In both, `EngineStatus` is `0x00050001`; `MirrorFold` is `0x00030002` and exists only in B. ```sh -# Go service: separate import paths, no prefix needed. -quarry-schema-compiler --language go --go-import-prefix example.com/fleet/gen/rev_a \ - -o gen/rev_a rev_a/configuration.brd -quarry-schema-compiler --language go --go-import-prefix example.com/fleet/gen/rev_b \ - -o gen/rev_b rev_b/configuration.brd +# Go service: explicit names below a caller-selected import root. +quarry-schema-compiler --language go --name-prefix rev_a --go-import-prefix example.com/fleet/gen \ + -o gen examples/truck/schemas/configuration.brd +quarry-schema-compiler --language go --name-prefix rev_b --go-import-prefix example.com/fleet/gen \ + -o gen examples/truck/multi_configuration/rev_b/configuration.brd # Python analytics: one package tree, prefixed. -quarry-schema-compiler --language python --name-prefix rev_a -o py rev_a/configuration.brd -quarry-schema-compiler --language python --name-prefix rev_b -o py rev_b/configuration.brd +quarry-schema-compiler --language python --name-prefix rev_a -o py examples/truck/schemas/configuration.brd +quarry-schema-compiler --language python --name-prefix rev_b -o py examples/truck/multi_configuration/rev_b/configuration.brd ``` ```go @@ -430,7 +443,7 @@ confirm the numbers with GCC as part of A4.2. ## 9. Test requirements -This is the original A4 test plan, including future A4.4–A4.5 features. A4.3 +This is the original A4 test plan, now including implemented A4.4–A4.5 features. A4.3 now has parser, C99, installed-package and three-language identity tests; the remaining proposed tests are not a statement that future features exist. Use the [G4 validation guide](../generated-code-identity-validation.md) for current measured coverage. @@ -480,8 +493,8 @@ The [consumer guide](../generated-binding-compatibility.md#per-namespace-storage contains executable separate-invocation examples. The [CLI contract](../../tools/README.md) and [CMake integration](../schema-compiler-tool-distribution.md) define supported -options. `NAME_PREFIX`, `SCHEMA_ID_VARIABLE` and `--name-prefix` are A4.5 -proposals, not current helper/CLI options. Build systems must regenerate the +options. `NAME_PREFIX`, `SCHEMA_ID_VARIABLE` and `--name-prefix` are implemented A4.5 +helper/CLI options. Build systems must regenerate the complete affected closure; a wholly stale but internally consistent set can compile successfully. Identity checks do not replace dependency tracking. @@ -557,7 +570,7 @@ A4.3 and A4.4 are independent of A4.2. The A5 cross-language matrix follows A4.5 3. **Fixtures.** Revision B fixtures live under `tests/fixtures/configuration_identity/`: one with a different `schema_id` and unchanged numeric record IDs (`rev_b_same_ids`), one with a different `schema_id`, renumbered records and changed layouts (`rev_b_renumbered`). The public - multi-configuration example remains A4.5 work. + multi-configuration example is implemented in `examples/truck/multi_configuration`. 4. **Footprint.** The byte-identical object-code requirement is replaced by a zero mandatory runtime footprint: linked `.text`, `.rodata`, `.data` and `.bss` are compared under identical GCC build settings; no mandatory identity-related storage, startup code, allocation or hashing. Symbol diff --git a/docs/design/go-backend.md b/docs/design/go-backend.md index 8d5e65b..5c61f3a 100644 --- a/docs/design/go-backend.md +++ b/docs/design/go-backend.md @@ -161,3 +161,13 @@ toolchain): to the root input. * Generated encode/decode methods are plain code per field; there is no reflection-based or zero-copy decode API. + +## Optional source naming prefix + +`--name-prefix` inserts one literal directory segment below the output directory +and below the caller-selected `--go-import-prefix`. Cross-namespace imports use +those prefixed paths; the backend never supplies an application module path. +Canonical namespace metadata, record IDs, schema identity and runtime API epoch +are unchanged. Without the flag, generated bytes are unchanged. The +[truck example](../../examples/truck/multi_configuration/README.md) imports both +prefixed configurations in one binary and checks actual BRF round trips. diff --git a/docs/generated-binding-compatibility.md b/docs/generated-binding-compatibility.md index d8c1b0a..f738b47 100644 --- a/docs/generated-binding-compatibility.md +++ b/docs/generated-binding-compatibility.md @@ -195,7 +195,7 @@ 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` feature. A4.4 adds the optional +no C-storage helper. A4.5 provides explicit `--name-prefix` isolation. 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 @@ -274,10 +274,14 @@ Changing this exclusion requires a separately approved naming/API decision. The issue remains open for later scheduling; this disposition does not authorize implementation or expand the API contract. -Future A4.5 naming isolation must encode a prefix as an injective leading segment -for C symbols as well as identity macros. Simply concatenating underscore-joined -text can still collide. `--name-prefix` is not available today and is not a -current workaround. #119 and its milestone remain unchanged by this guide. +A4.5 `--name-prefix` implements a separately approved, prefixed-only correction: +the prefix and canonical namespace segments use the injective #117 encoding for +C symbols and identity macros. Prefixed enum constants preserve namespace case; +C-storage wrappers use the same stem. This allows deliberate isolation with +distinct prefixes, including the adversarial prefix/namespace joins described +in #119. Unprefixed C spelling and the general #119 migration remain deferred. +Existing backend restrictions on declaration/member names still apply. See the +[naming contract](../tools/README.md#deliberate-source-naming-isolation). ## Evidence boundary diff --git a/docs/schema-compiler-tool-distribution.md b/docs/schema-compiler-tool-distribution.md index 62a8a16..215c61b 100644 --- a/docs/schema-compiler-tool-distribution.md +++ b/docs/schema-compiler-tool-distribution.md @@ -900,3 +900,30 @@ A future PR should define and test: 4. Decide whether imported target overrides, host-tools packages, multi-config-specific output directories, package components, or stale-output cleanup are justified. + +## Explicit names and configure-time configuration identity + +The installed `quarry_generate_cpp()` helper accepts `NAME_PREFIX ` +and `SCHEMA_ID_VARIABLE ` in addition to its existing keywords: + +```cmake +quarry_generate_cpp(SCHEMA "${CMAKE_CURRENT_SOURCE_DIR}/configuration.brd" + OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated" NAME_PREFIX rev_a + GENERATE truck.engine,truck.common OUT_FILES generated_a + SCHEMA_ID_VARIABLE schema_a) +``` + +`NAME_PREFIX` is passed to generation and both output-inventory queries, including +the build-time `cmake -P` verifier. The existing absolute `--list-inputs` inventory +still covers the complete root and drives reconfiguration. The output claim +registry still rejects collisions. Different prefixes permit multiple roots to +share an output directory; the helper does not remove stale output files. + +`SCHEMA_ID_VARIABLE` returns 32 lowercase hexadecimal digits to the caller's scope +by running `--print-schema-id` at configure time. Neither `NAME_PREFIX` nor +`GENERATE` enters that query. Query failures and malformed responses produce +configure-time errors with the compiler/root context. Applications may compare +identities for roots without a dependency edge; these checks stay optional. +The installed module retains its `3.20...3.31` policy pin. Both configure mode and +the inventory/query script path are tested with CMake 3.x; the public generation +function itself requires configure mode because it creates build rules. diff --git a/examples/README.md b/examples/README.md index 782a896..2071141 100644 --- a/examples/README.md +++ b/examples/README.md @@ -18,6 +18,8 @@ Current examples: * `truck`: a Class 8 truck configuration root. Embedded C bindings for the engine ECU and cloud-side Python bindings are generated separately from the same root and agree on every record ID. +* `truck/multi_configuration`: rev A and rev B coexist in C++ owning, C99, + C++/C storage, Python and Go using explicit prefixes and real round trips. * `protobuf/descriptor_to_brd`: descriptor-set protobuf translation into bounded `.brd` units, followed by separate Quarry compiler invocations. diff --git a/examples/truck/README.md b/examples/truck/README.md index daf8ad6..0703493 100644 --- a/examples/truck/README.md +++ b/examples/truck/README.md @@ -107,3 +107,10 @@ Generated dependencies check configuration identity and generated-code identity at compile time. Preserve consistent effective per-namespace storage policies across separate invocations, including unselected dependencies. See the [consumer compatibility and migration guide](../../docs/generated-binding-compatibility.md). + +## Two revisions in one application + +The [multi-configuration example](multi_configuration/README.md) uses the same +revision A root and a revision B root adding `truck.cms.MirrorFold`. It runs all +five binding variants with explicit prefixes, checks record IDs and complete +schema identities, and compares real encoded bytes. diff --git a/examples/truck/multi_configuration/CMakeLists.txt b/examples/truck/multi_configuration/CMakeLists.txt new file mode 100644 index 0000000..5ccb3b2 --- /dev/null +++ b/examples/truck/multi_configuration/CMakeLists.txt @@ -0,0 +1,66 @@ +cmake_minimum_required(VERSION 3.20) +project(quarry_truck_multi_configuration LANGUAGES C CXX) +find_package(Quarry CONFIG REQUIRED) +set(rev_a "${CMAKE_CURRENT_SOURCE_DIR}/../schemas/configuration.brd") +set(rev_b "${CMAKE_CURRENT_SOURCE_DIR}/rev_b/configuration.brd") +set(cpp_dir "${CMAKE_CURRENT_BINARY_DIR}/generated/cpp") +quarry_generate_cpp(SCHEMA "${rev_a}" OUTPUT_DIR "${cpp_dir}" NAME_PREFIX rev_a + SCHEMA_ID_VARIABLE id_a OUT_FILES cpp_a) +quarry_generate_cpp(SCHEMA "${rev_b}" OUTPUT_DIR "${cpp_dir}" NAME_PREFIX rev_b + SCHEMA_ID_VARIABLE id_b OUT_FILES cpp_b) +if(NOT id_a STREQUAL "9200ca494f010801b830d0857cf66dde" OR id_a STREQUAL id_b) + message(FATAL_ERROR "unexpected complete truck configuration identities") +endif() +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/schema_ids.txt" "${id_a}\n${id_b}\n") +add_executable(truck_multi_cpp owning.cpp ${cpp_a} ${cpp_b}) +target_include_directories(truck_multi_cpp PRIVATE "${cpp_dir}") +target_link_libraries(truck_multi_cpp PRIVATE Quarry::runtime) +target_compile_features(truck_multi_cpp PRIVATE cxx_std_20) + +# There is no installed C/C-storage generation helper. Follow the explicit +# custom-command pattern used by the other public C examples. +file(GLOB schemas CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/../schemas/*.brd" + "${CMAKE_CURRENT_SOURCE_DIR}/rev_b/*.brd") +function(fixed_bindings variable directory root prefix storage) + if(storage) + set(flags --language cpp --cpp-storage c) + set(header hpp) + set(source cpp) + else() + set(flags --language c) + set(header h) + set(source c) + endif() + set(outputs) + foreach(ns truck truck/engine truck/common truck/cms truck/brakes truck/transmission) + list(APPEND outputs "${directory}/${prefix}/${ns}.generated.${header}" + "${directory}/${prefix}/${ns}.generated.${source}") + endforeach() + add_custom_command(OUTPUT ${outputs} + COMMAND "$" ${flags} --name-prefix "${prefix}" + --output-directory "${directory}" "${root}" + DEPENDS ${schemas} Quarry::schema_compiler VERBATIM) + set(${variable} "${outputs}" PARENT_SCOPE) +endfunction() +foreach(kind c c_storage) + set(directory "${CMAKE_CURRENT_BINARY_DIR}/generated/${kind}") + if(kind STREQUAL c_storage) + set(storage TRUE) + set(main c_storage.cpp) + else() + set(storage FALSE) + set(main plain.c) + endif() + fixed_bindings(files_a "${directory}" "${rev_a}" rev_a ${storage}) + fixed_bindings(files_b "${directory}" "${rev_b}" rev_b ${storage}) + add_executable(truck_multi_${kind} ${main} ${files_a} ${files_b}) + target_include_directories(truck_multi_${kind} PRIVATE "${directory}") + target_link_libraries(truck_multi_${kind} PRIVATE Quarry::runtime_c) + set_target_properties(truck_multi_${kind} PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED ON + C_EXTENSIONS OFF CXX_STANDARD 20 CXX_STANDARD_REQUIRED ON CXX_EXTENSIONS OFF) +endforeach() +foreach(target truck_multi_cpp truck_multi_c truck_multi_c_storage) + if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror) + endif() +endforeach() diff --git a/examples/truck/multi_configuration/README.md b/examples/truck/multi_configuration/README.md new file mode 100644 index 0000000..9717f0e --- /dev/null +++ b/examples/truck/multi_configuration/README.md @@ -0,0 +1,64 @@ +# Two truck revisions in one application + +This example uses the authoritative revision A root at +`../schemas/configuration.brd` and revision B at `rev_b/configuration.brd`. +Revision B imports the same records and adds `truck.cms.MirrorFold` with a +`folded: bool` field. No configuration name implicitly supplies a prefix. + +| Configuration | Complete schema_id | EngineStatus ID | MirrorFold ID | +|---|---|---|---| +| Revision A | `9200ca494f010801b830d0857cf66dde` | `0x00050001` | absent | +| Revision B | `806e9a4e11d0df71c4e5b51045f85010` | `0x00050001` | `0x00030002` | + +Install Quarry and its Python runtime wheel first. From this directory, run: + +```sh +python3 run.py --prefix /path/to/installed/quarry \ + --python /path/to/runtime-venv/bin/python \ + --go-runtime ../../../runtime/go --go-module example.com/fleet +``` + +`--go-runtime` points to the Go runtime module's source tree; it is not an +installed CMake target. `--go-module` is the caller-selected example application +module path, passed through `--go-import-prefix`. Go 1.22+ is required. The runner +uses a temporary build directory and local Go caches; it publishes nothing. +Use `--work /tmp/truck-multi` to retain generated files and logs for inspection. +Source-tree developers may replace the installed wheel with +`--python-runtime ../../../runtime/python/src`. `--skip-go` explicitly limits +execution to the native and Python examples when Go is unavailable. + +The runner builds and executes: + +- C++ owning revision A and B in one translation unit, using + `rev_a::truck::engine` and `rev_b::truck::engine`. +- Plain C99 revision A and B in one translation unit. The approved prefixed-only + C naming rule gives stems `revq0a_truck_engine_` and `revq0b_truck_engine_`. +- C++/C-storage wrappers in one translation unit, using the same encoded stems + beneath `quarry::cxx`. +- Both absolute Python package trees in one process, plus unprefixed revision A + as a wire-byte control. +- Both Go import trees in one binary, plus the unprefixed wire-byte control. + +Every variant encodes and decodes EngineStatus and revision B's MirrorFold, +checks the actual record IDs, and verifies revision A/B EngineStatus bytes agree. +The shared timestamp exercises a generated cross-namespace dependency. The native +CMake project demonstrates `NAME_PREFIX`, `SCHEMA_ID_VARIABLE`, multiple helper +calls sharing an output directory, and explicit C/C-storage custom commands. +Python imports and Go imports stay absolute. Existing dependency identity checks +remain enabled. Selection of a vehicle revision remains out of band; there is +no runtime negotiation, new wire metadata or native ABI interchangeability claim. + +Run only the native examples with: + +```sh +cmake -S . -B /tmp/truck-native -DCMAKE_PREFIX_PATH=/path/to/installed/quarry +cmake --build /tmp/truck-native --parallel +/tmp/truck-native/truck_multi_cpp +/tmp/truck-native/truck_multi_c +/tmp/truck-native/truck_multi_c_storage +``` + +The public-example validation runs this workflow through an installed package +and Python wheel. Go execution is explicitly skipped only on developer machines +without Go; CI and the A4.5 validation run all five variants. Unprefixed source +names remain unchanged, and #119's general C naming migration remains deferred. diff --git a/examples/truck/multi_configuration/c_storage.cpp b/examples/truck/multi_configuration/c_storage.cpp new file mode 100644 index 0000000..9be83f9 --- /dev/null +++ b/examples/truck/multi_configuration/c_storage.cpp @@ -0,0 +1,51 @@ +#include "rev_a/truck.generated.hpp" +#include "rev_a/truck/engine.generated.hpp" +#include "rev_b/truck.generated.hpp" +#include "rev_b/truck/cms.generated.hpp" +#include "rev_b/truck/engine.generated.hpp" + +#include +#include +#include +#include +#include + +int main() { + using A = quarry::cxx::revq0a_truck_engine_EngineStatus; + using B = quarry::cxx::revq0b_truck_engine_EngineStatus; + static_assert(!std::is_same_v); + A a; + B b; + a.set_rpm(1450); + b.set_rpm(1450); + a.native().has_time = b.native().has_time = true; + a.native().time.has_unix_ms = b.native().time.has_unix_ms = true; + a.native().time.unix_ms = b.native().time.unix_ms = 42; + std::array wa{}, wb{}; + const auto ea = a.encode(wa); + const auto eb = b.encode(wb); + if (ea.status != QUARRY_C_STATUS_OK || eb.status != QUARRY_C_STATUS_OK || + ea.bytes_written != eb.bytes_written || + std::memcmp(wa.data(), wb.data(), ea.bytes_written) != 0 || wa[4] != std::byte{0} || + wa[5] != std::byte{5} || wa[6] != std::byte{0} || wa[7] != std::byte{1}) + return 1; + A da; + B db; + if (da.decode(std::span(wa.data(), ea.bytes_written)).status != + QUARRY_C_STATUS_OK || + db.decode(std::span(wb.data(), eb.bytes_written)).status != + QUARRY_C_STATUS_OK || + da.native().rpm != 1450 || db.native().rpm != 1450 || da.native().time.unix_ms != 42) + return 2; + quarry::cxx::revq0b_truck_cms_MirrorFold mirror; + mirror.set_folded(true); + const auto em = mirror.encode(wb); + if (em.status != QUARRY_C_STATUS_OK || wb[5] != std::byte{3} || wb[7] != std::byte{2}) + return 3; + decltype(mirror) dm; + if (dm.decode(std::span(wb.data(), em.bytes_written)).status != + QUARRY_C_STATUS_OK || + !dm.native().has_folded || !dm.native().folded) + return 4; + std::cout << "C++/C storage: both prefixed revisions round-trip\n"; +} diff --git a/examples/truck/multi_configuration/main.go.in b/examples/truck/multi_configuration/main.go.in new file mode 100644 index 0000000..0d7dd61 --- /dev/null +++ b/examples/truck/multi_configuration/main.go.in @@ -0,0 +1,59 @@ +package main + +import ( + ca "@MODULE@/gen/rev_a/truck/common" + a "@MODULE@/gen/rev_a/truck/engine" + cms "@MODULE@/gen/rev_b/truck/cms" + cb "@MODULE@/gen/rev_b/truck/common" + b "@MODULE@/gen/rev_b/truck/engine" + originalcommon "@MODULE@/gen/truck/common" + original "@MODULE@/gen/truck/engine" + "bytes" + "fmt" + "github.com/ip332/quarry/runtime/go/brf" +) + +func main() { + if a.QuarrySchemaID() == b.QuarrySchemaID() { + panic("configuration identity collision") + } + av := a.EngineStatus{Rpm: brf.Ptr(uint16(1450)), Time: &ca.Timestamp{UnixMs: brf.Ptr(uint64(42))}} + bv := b.EngineStatus{Rpm: brf.Ptr(uint16(1450)), Time: &cb.Timestamp{UnixMs: brf.Ptr(uint64(42))}} + wa, err := av.MarshalBRF() + if err != nil { + panic(err) + } + wb, err := bv.MarshalBRF() + if err != nil { + panic(err) + } + ov := original.EngineStatus{Rpm: brf.Ptr(uint16(1450)), Time: &originalcommon.Timestamp{UnixMs: brf.Ptr(uint64(42))}} + wo, err := ov.MarshalBRF() + if err != nil || !bytes.Equal(wa, wo) { + panic("prefix changed wire bytes") + } + id, err := brf.PeekRecordID(wa) + if err != nil || id != 0x00050001 || !bytes.Equal(wa, wb) { + panic("engine wire mismatch") + } + var da a.EngineStatus + var db b.EngineStatus + if da.UnmarshalBRF(wa) != nil || db.UnmarshalBRF(wb) != nil || da.Rpm == nil || db.Rpm == nil || + *da.Rpm != 1450 || *db.Rpm != 1450 || da.Time == nil || da.Time.UnixMs == nil || *da.Time.UnixMs != 42 { + panic("engine round trip") + } + m := cms.MirrorFold{Folded: brf.Ptr(true)} + wm, err := m.MarshalBRF() + if err != nil { + panic(err) + } + id, err = brf.PeekRecordID(wm) + if err != nil || id != 0x00030002 { + panic("mirror record ID") + } + var dm cms.MirrorFold + if dm.UnmarshalBRF(wm) != nil || dm.Folded == nil || !*dm.Folded { + panic("mirror round trip") + } + fmt.Println("Go: both import paths round-trip; EngineStatus bytes agree") +} diff --git a/examples/truck/multi_configuration/owning.cpp b/examples/truck/multi_configuration/owning.cpp new file mode 100644 index 0000000..f1c92dc --- /dev/null +++ b/examples/truck/multi_configuration/owning.cpp @@ -0,0 +1,50 @@ +#include "rev_a/truck.generated.hpp" +#include "rev_a/truck/engine.generated.hpp" +#include "rev_b/truck.generated.hpp" +#include "rev_b/truck/cms.generated.hpp" +#include "rev_b/truck/engine.generated.hpp" + +#include +#include +#include + +int main() { + static_assert( + !std::is_same_v); + static_assert(rev_a::truck::engine::kQuarrySchemaId != rev_b::truck::engine::kQuarrySchemaId); + rev_a::truck::common::TimestampBuilder time_a; + rev_b::truck::common::TimestampBuilder time_b; + rev_a::truck::engine::EngineStatusBuilder a; + rev_b::truck::engine::EngineStatusBuilder b; + if (!time_a.set_unix_ms(42) || !time_b.set_unix_ms(42) || !a.set_time(time_a.build()) || + !b.set_time(time_b.build()) || !a.set_rpm(1450) || !b.set_rpm(1450)) + return 1; + const auto encoded_a = rev_a::truck::engine::encode_result(a.build()); + const auto encoded_b = rev_b::truck::engine::encode_result(b.build()); + if (!encoded_a || !encoded_b || *encoded_a.value != *encoded_b.value) + return 2; + const auto decoded_a = rev_a::truck::engine::decode_EngineStatus_result(*encoded_a.value); + const auto decoded_b = rev_b::truck::engine::decode_EngineStatus_result(*encoded_b.value); + if (!decoded_a || !decoded_b || !decoded_a.value->rpm() || !decoded_b.value->rpm() || + *decoded_a.value->rpm() != 1450 || *decoded_b.value->rpm() != 1450 || + !decoded_a.value->time() || *decoded_a.value->time()->unix_ms() != 42) + return 3; + rev_b::truck::cms::MirrorFoldBuilder mirror; + if (!mirror.set_folded(true)) + return 4; + const auto bytes = rev_b::truck::cms::encode_result(mirror.build()); + if (!bytes) + return 5; + const auto& wire = *bytes.value; + if (wire.size() < 8 || wire[4] != std::byte{0} || wire[5] != std::byte{3} || + wire[6] != std::byte{0} || wire[7] != std::byte{2}) + return 6; + const auto decoded = rev_b::truck::cms::decode_MirrorFold_result(wire); + if (!decoded || !decoded.value->folded() || !*decoded.value->folded()) + return 7; + const auto& engine = *encoded_a.value; + if (engine.size() < 8 || engine[4] != std::byte{0} || engine[5] != std::byte{5} || + engine[6] != std::byte{0} || engine[7] != std::byte{1}) + return 8; + std::cout << "C++: two revisions, EngineStatus 0x00050001, MirrorFold 0x00030002\n"; +} diff --git a/examples/truck/multi_configuration/plain.c b/examples/truck/multi_configuration/plain.c new file mode 100644 index 0000000..a490923 --- /dev/null +++ b/examples/truck/multi_configuration/plain.c @@ -0,0 +1,59 @@ +#include "rev_a/truck.generated.h" +#include "rev_a/truck/engine.generated.h" +#include "rev_b/truck.generated.h" +#include "rev_b/truck/cms.generated.h" +#include "rev_b/truck/engine.generated.h" + +#include +#include + +static uint32_t record_id(const uint8_t* data) { + return ((uint32_t)data[4] << 24) | ((uint32_t)data[5] << 16) | ((uint32_t)data[6] << 8) | + data[7]; +} + +int main(void) { + revq0a_truck_engine_EngineStatus_t a; + revq0b_truck_engine_EngineStatus_t b; + revq0a_truck_engine_EngineStatus_init(&a); + revq0b_truck_engine_EngineStatus_init(&b); + a.has_rpm = b.has_rpm = true; + a.rpm = b.rpm = 1450; + a.has_time = b.has_time = true; + a.time.has_unix_ms = b.time.has_unix_ms = true; + a.time.unix_ms = b.time.unix_ms = 42; + uint8_t bytes_a[256], bytes_b[256]; + const revq0a_truck_engine_EngineStatus_encode_result_t ea = + revq0a_truck_engine_EngineStatus_encode(&a, bytes_a, sizeof(bytes_a)); + const revq0b_truck_engine_EngineStatus_encode_result_t eb = + revq0b_truck_engine_EngineStatus_encode(&b, bytes_b, sizeof(bytes_b)); + if (ea.status != QUARRY_C_STATUS_OK || eb.status != QUARRY_C_STATUS_OK || + ea.bytes_written != eb.bytes_written || memcmp(bytes_a, bytes_b, ea.bytes_written) != 0 || + record_id(bytes_a) != 0x00050001U) + return 1; + const revq0a_truck_engine_EngineStatus_decode_result_t da = + revq0a_truck_engine_EngineStatus_decode(bytes_a, ea.bytes_written); + const revq0b_truck_engine_EngineStatus_decode_result_t db = + revq0b_truck_engine_EngineStatus_decode(bytes_b, eb.bytes_written); + if (da.status != QUARRY_C_STATUS_OK || db.status != QUARRY_C_STATUS_OK || !da.value.has_rpm || + !db.value.has_rpm || da.value.rpm != 1450 || db.value.rpm != 1450 || + !da.value.time.has_unix_ms || da.value.time.unix_ms != 42) + return 2; + if (memcmp(quarry_ns_revq0a_truck_engine_schema_id(), quarry_ns_revq0b_truck_engine_schema_id(), + 16) == 0) + return 3; + revq0b_truck_cms_MirrorFold_t mirror; + revq0b_truck_cms_MirrorFold_init(&mirror); + mirror.has_folded = true; + mirror.folded = true; + const revq0b_truck_cms_MirrorFold_encode_result_t em = + revq0b_truck_cms_MirrorFold_encode(&mirror, bytes_b, sizeof(bytes_b)); + if (em.status != QUARRY_C_STATUS_OK || record_id(bytes_b) != 0x00030002U) + return 4; + const revq0b_truck_cms_MirrorFold_decode_result_t dm = + revq0b_truck_cms_MirrorFold_decode(bytes_b, em.bytes_written); + if (dm.status != QUARRY_C_STATUS_OK || !dm.value.has_folded || !dm.value.folded) + return 5; + puts("C99: two revisions, EngineStatus 0x00050001, MirrorFold 0x00030002"); + return 0; +} diff --git a/examples/truck/multi_configuration/python.py b/examples/truck/multi_configuration/python.py new file mode 100644 index 0000000..e55b2f5 --- /dev/null +++ b/examples/truck/multi_configuration/python.py @@ -0,0 +1,23 @@ +"""Both prefixed Python packages coexist in one process; selection is out of band.""" +from truck.common.schema import Timestamp as Time0 +from truck.engine.schema import EngineStatus as Engine0 +from rev_a.truck.schema import VehicleSnapshot as SnapshotA +from rev_b.truck.schema import VehicleSnapshot as SnapshotB +from rev_a.truck.common.schema import Timestamp as TimeA +from rev_b.truck.common.schema import Timestamp as TimeB +from rev_a.truck.engine.schema import EngineStatus as EngineA, QUARRY_SCHEMA_ID as ID_A +from rev_b.truck.engine.schema import EngineStatus as EngineB, QUARRY_SCHEMA_ID as ID_B +from rev_b.truck.cms.schema import MirrorFold + +assert SnapshotA.__module__ != SnapshotB.__module__ +assert ID_A.hex() == '9200ca494f010801b830d0857cf66dde' and ID_A != ID_B +a = EngineA(time=TimeA(unix_ms=42), rpm=1450) +b = EngineB(time=TimeB(unix_ms=42), rpm=1450) +wa, wb = a.encode(), b.encode() +assert wa == wb == Engine0(time=Time0(unix_ms=42), rpm=1450).encode() and int.from_bytes(wa[4:8], 'big') == 0x00050001 +assert EngineA.decode(wa).rpm == EngineB.decode(wb).rpm == 1450 +assert EngineA.decode(wa).time.unix_ms == EngineB.decode(wb).time.unix_ms == 42 +mirror = MirrorFold(folded=True).encode() +assert int.from_bytes(mirror[4:8], 'big') == 0x00030002 +assert MirrorFold.decode(mirror).folded is True +print('Python: both packages round-trip; schema identities differ, EngineStatus bytes agree') diff --git a/examples/truck/multi_configuration/rev_b/configuration.brd b/examples/truck/multi_configuration/rev_b/configuration.brd new file mode 100644 index 0000000..5b64f1b --- /dev/null +++ b/examples/truck/multi_configuration/rev_b/configuration.brd @@ -0,0 +1,8 @@ +configuration: class8_truck_rev_b +imports: + - ../../schemas/vehicle.brd + - ../../schemas/engine.brd + - ../../schemas/transmission.brd + - ../../schemas/brakes.brd + - ../../schemas/cms.brd + - mirror_fold.brd diff --git a/examples/truck/multi_configuration/rev_b/mirror_fold.brd b/examples/truck/multi_configuration/rev_b/mirror_fold.brd new file mode 100644 index 0000000..069074e --- /dev/null +++ b/examples/truck/multi_configuration/rev_b/mirror_fold.brd @@ -0,0 +1,7 @@ +namespace: truck.cms +record: MirrorFold +version: 1 +type: data +fields: + folded: + type: bool diff --git a/examples/truck/multi_configuration/run.py b/examples/truck/multi_configuration/run.py new file mode 100644 index 0000000..e29f8cc --- /dev/null +++ b/examples/truck/multi_configuration/run.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Build and run all five truck naming-isolation examples using installed Quarry.""" +import argparse +import contextlib +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prefix', required=True, type=Path, help='installed Quarry prefix') + parser.add_argument('--cmake', default='cmake') + parser.add_argument('--python', default=sys.executable) + parser.add_argument('--python-runtime', type=Path, help='source Python runtime; omit for installed wheel') + parser.add_argument('--go', default='go') + parser.add_argument('--skip-go', action='store_true', help='run native and Python checks without a Go toolchain') + parser.add_argument('--go-runtime', type=Path) + parser.add_argument('--go-module', default='example.com/fleet') + parser.add_argument('--work', type=Path) + args = parser.parse_args() + example = Path(__file__).resolve().parent + source = example.parents[2] + go_runtime = (args.go_runtime or source / 'runtime/go').resolve() + context = contextlib.nullcontext(str(args.work.resolve())) if args.work else tempfile.TemporaryDirectory(prefix='quarry-truck-multi-') + with context as temporary: + work = Path(temporary) + work.mkdir(parents=True, exist_ok=True) + + def run(command, **options): + subprocess.run(list(map(str, command)), cwd=work, check=True, **options) + + native = work / 'native' + run([args.cmake, '-S', example, '-B', native, '-DCMAKE_PREFIX_PATH=' + str(args.prefix.resolve())]) + run([args.cmake, '--build', native, '--parallel', '4']) + for name in ('truck_multi_cpp', 'truck_multi_c', 'truck_multi_c_storage'): + run([native / name]) + ids = (native / 'schema_ids.txt').read_text().splitlines() + print('Complete configuration identities:', *ids, flush=True) + compiler = args.prefix.resolve() / 'bin/quarry-schema-compiler' + roots = [example.parent / 'schemas/configuration.brd', example / 'rev_b/configuration.brd'] + python_output = work / 'python' + go_output = work / 'go' + go_output.mkdir(exist_ok=True) + # The original source names also remain usable and emit the same wire bytes. + run([compiler, '--language', 'python', '-o', python_output, roots[0]]) + run([compiler, '--language', 'go', '--go-import-prefix', args.go_module + '/gen', + '-o', go_output / 'gen', roots[0]]) + for revision, root in zip(('rev_a', 'rev_b'), roots): + run([compiler, '--language', 'python', '--name-prefix', revision, '-o', python_output, root]) + run([compiler, '--language', 'go', '--name-prefix', revision, + '--go-import-prefix', args.go_module + '/gen', '-o', go_output / 'gen', root]) + environment = os.environ.copy() + environment['PYTHONDONTWRITEBYTECODE'] = '1' + environment['PYTHONPATH'] = str(python_output) + (os.pathsep + str(args.python_runtime.resolve()) if args.python_runtime else '') + run([args.python, example / 'python.py'], env=environment) + if args.skip_go: + print('Native and Python coexistence passed; Go execution explicitly skipped.') + return + if not shutil.which(args.go): + raise SystemExit('Go 1.22+ is required for the dual-import example') + module = ('module ' + args.go_module + '\n\ngo 1.22\n\n' + 'require github.com/ip332/quarry/runtime/go v0.0.0\n' + 'replace github.com/ip332/quarry/runtime/go => "' + go_runtime.as_posix() + '"\n') + (go_output / 'go.mod').write_text(module) + (go_output / 'main.go').write_text((example / 'main.go.in').read_text().replace('@MODULE@', args.go_module)) + environment.update(GOWORK='off', GOPROXY='off', GOSUMDB='off', GOTOOLCHAIN='local', + GOCACHE=str(work / 'go-cache'), GOPATH=str(work / 'go-path')) + subprocess.run([args.go, 'build', './...'], cwd=go_output, env=environment, check=True) + subprocess.run([args.go, 'run', '.'], cwd=go_output, env=environment, check=True) + print('All five truck variants coexist and execute successfully.') + + +if __name__ == '__main__': + main() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index bb50bde..688d18c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,18 @@ 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 name_prefix_test + COMMAND ${QUARRY_PYTHON3_EXECUTABLE} + "${CMAKE_CURRENT_SOURCE_DIR}/tools/name_prefix_test.py" + --source "${CMAKE_SOURCE_DIR}" --compiler "$" + --generated-include "${QUARRY_GENERATED_INCLUDE_DIR}" + --cc "${CMAKE_C_COMPILER}" --cxx "${CMAKE_CXX_COMPILER}" + --runtime-c "$" --coverage "$") + add_test(NAME name_prefix_cmake_test + COMMAND ${QUARRY_PYTHON3_EXECUTABLE} + "${CMAKE_CURRENT_SOURCE_DIR}/tools/name_prefix_cmake_test.py" + --source "${CMAKE_SOURCE_DIR}" --build-dir "${CMAKE_BINARY_DIR}" + --cmake "${CMAKE_COMMAND}") add_test(NAME schema_description_test COMMAND ${QUARRY_PYTHON3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/tools/schema_description_test.py" diff --git a/tests/examples/example_validation.py b/tests/examples/example_validation.py index f56eab0..960b92c 100644 --- a/tests/examples/example_validation.py +++ b/tests/examples/example_validation.py @@ -4,6 +4,7 @@ import argparse import os +import shutil from pathlib import Path import subprocess import tempfile @@ -99,6 +100,15 @@ def main() -> None: run([str(python), str(truck / "cloud/decode.py"), str(report)], cwd=truck, env=environment) + multi = truck / "multi_configuration/run.py" + command = [str(args.python), str(multi), "--prefix", str(prefix), + "--cmake", str(args.cmake), "--python", str(python), + "--go-runtime", str(args.source_dir / "runtime/go"), + "--work", str(root / "truck-multi")] + if not shutil.which("go"): + command.append("--skip-go") + run(command, cwd=root) + if __name__ == "__main__": main() diff --git a/tests/fixtures/name_prefix/unprefixed_sha256.json b/tests/fixtures/name_prefix/unprefixed_sha256.json new file mode 100644 index 0000000..e67a74d --- /dev/null +++ b/tests/fixtures/name_prefix/unprefixed_sha256.json @@ -0,0 +1,91 @@ +{ + "baseline": "85fd8123ac88e9b337ba3b18c57a30736dbf6452", + "variants": { + "cpp": { + "truck/brakes.generated.hpp": "00769adeb014b125badc94653af6cc4b1937745ec31b7b238bd1a732869fcbd2", + "truck/cms.generated.hpp": "dc75f846f456e1e46f0877e12b3a3bafb0123e910ee1d1dac1906ab0ea434ad5", + "truck/common.generated.hpp": "7805a679fb8d3a6ce2da9c9b99cfd59063ab1a88c0d8a3122f0d6794b9342b4a", + "truck/engine.generated.hpp": "3d66e44dab37e744c52ec737c6a9ba1e22ae98502bd1356f339a4dae5f8293bf", + "truck/transmission.generated.hpp": "85ee9f3d3c4f57608b89d83ef372ef1a3cb1a08b8628daafcac357544744d792", + "truck.generated.hpp": "c2e9e2de1454aaf52093996254e05c7f24cc000d01ff3b9720d8f1227fc91b5b" + }, + "c": { + "truck/brakes.generated.c": "1a3a162665e2ec48eb6cad1fa12bad7efbfc3898ee4df732efbd912be3116f8e", + "truck/brakes.generated.h": "368ff7fe5b9dab60779fbeecc76588fae4f19ee7338074593cc1ea5773de3965", + "truck/cms.generated.c": "ff904c8e4d147215c83b52d2996964616f31d4351389efa18c637d1c4f257b7f", + "truck/cms.generated.h": "fe88b6fb857b4dc56ea2bcc9ded3a262d4f25846876fb3e2e399565b6992c53d", + "truck/common.generated.c": "c31a57de6bf3e553244aade587c58044c4086dec4982cade10c92666cceeff53", + "truck/common.generated.h": "36cf51f29ddc246937e58988c6b66a1d670eaf2a0d4de03ab13920a05960439e", + "truck/engine.generated.c": "d874c04f00fe81d1f35afbfeb0d30b16e12bae346a71a5504630672c587a75a5", + "truck/engine.generated.h": "0484ba353142765980327720f868546ec66cbd1c669f09c728375f385983bc8e", + "truck/transmission.generated.c": "be10915e96c89b3a679d56908e7eb148830b1289cb20eaadd333b1a77f1ddc03", + "truck/transmission.generated.h": "44aad0b48b2f1dda4c62df4b5cfa4adcf8976cf8934bc419660ff03a4249d53d", + "truck.generated.c": "a94bc1fd4edffaac39da44787659212a1164b9401aea136db40fce5d7841fe00", + "truck.generated.h": "732f2e20803f6ea7d2cadfab9911d629a0dbac5d1c020f9d0ae71a26c742cffb" + }, + "c-compact": { + "truck/brakes.generated.c": "1a3a162665e2ec48eb6cad1fa12bad7efbfc3898ee4df732efbd912be3116f8e", + "truck/brakes.generated.h": "b77ef6380fec1e004981f3a451658863be357ac97494284c070b3e12f8d9b4b6", + "truck/cms.generated.c": "ff904c8e4d147215c83b52d2996964616f31d4351389efa18c637d1c4f257b7f", + "truck/cms.generated.h": "34faab2e098a8f15479c43fe392ef6c0bb878db92045e9882318876515727066", + "truck/common.generated.c": "c31a57de6bf3e553244aade587c58044c4086dec4982cade10c92666cceeff53", + "truck/common.generated.h": "93050355a555f05148c7feb58e4192fa05d88172d44196a1692f6f040e41b2c1", + "truck/engine.generated.c": "d874c04f00fe81d1f35afbfeb0d30b16e12bae346a71a5504630672c587a75a5", + "truck/engine.generated.h": "05e9da8c6b3fe6c59580059c299227aaba2646b9821bd7e5aac8d985798f9ece", + "truck/transmission.generated.c": "be10915e96c89b3a679d56908e7eb148830b1289cb20eaadd333b1a77f1ddc03", + "truck/transmission.generated.h": "77324385b969398377173add34a0fda0e4c94fb509e415a17956b5f2dda46f51", + "truck.generated.c": "a94bc1fd4edffaac39da44787659212a1164b9401aea136db40fce5d7841fe00", + "truck.generated.h": "0d0b1fcc92ab1e29e115d66b910c72c4b18763d841c6af578d5235eb79de0bc4" + }, + "cpp-c": { + "truck/brakes.generated.cpp": "7e7d23b580151789a8d28fa8bcf22c84184ef21147e72801cf9c3ed0f67f80f2", + "truck/brakes.generated.hpp": "4344d07636d3187ee4fbce4598ea4e77bc1a7ea66533f98a676df5bf7a9ccb74", + "truck/cms.generated.cpp": "8d812606be1fce3c51fc3cf2b10b3141528c1a2f16343dfd7f6bd4363e6a53e5", + "truck/cms.generated.hpp": "2229f180b56154443d3664f9ec5eaf2741954a6d3ef8c25e5d46207bbc090036", + "truck/common.generated.cpp": "946b2e6223b5b471c90d86fda310392b517bf08da0947224c32cebf15c221c04", + "truck/common.generated.hpp": "f689b7a75227fc72d48b4df74eb171dbbf61d9e91512af70daa2db025a35760f", + "truck/engine.generated.cpp": "1eb732d23743351fa916161e81d6b533b263b13a9d97674bfef0b8ca308c2b71", + "truck/engine.generated.hpp": "86053413e3abfc1945d6e2ab2b03b5f91fd8b9a3b6aa009d62c0e63b27b6f0a6", + "truck/transmission.generated.cpp": "2f9184c568108186ee20d334792db7d9694af314c39bc3d45bf4a9159c925fd9", + "truck/transmission.generated.hpp": "99ff55d3a69af9348433dcf656442056099f0c87c8fa06a0fcc85cb6c6f566f5", + "truck.generated.cpp": "bf88e32a5ee1138d37e0f1241bd3f40e2ade1a5c1e61a5e269c6dc0e7255cbfc", + "truck.generated.hpp": "ce36b516a8558f9a06e788808a7f15f5806a881b8f2fa5a5a58ad100f167d9fd" + }, + "cpp-c-compact": { + "truck/brakes.generated.cpp": "7e7d23b580151789a8d28fa8bcf22c84184ef21147e72801cf9c3ed0f67f80f2", + "truck/brakes.generated.hpp": "8daceccf0485966aadca8e02f904177bd1b4a3bea3e8d8d5aa5775d84b594fba", + "truck/cms.generated.cpp": "8d812606be1fce3c51fc3cf2b10b3141528c1a2f16343dfd7f6bd4363e6a53e5", + "truck/cms.generated.hpp": "b34825af24494568eaba3301cfb2b4c962db67b7b1ea0be01abd1b81030612d7", + "truck/common.generated.cpp": "946b2e6223b5b471c90d86fda310392b517bf08da0947224c32cebf15c221c04", + "truck/common.generated.hpp": "3adb7dbbd759c4c360fa22c175516c5945819cfa2669ac7e3f3ce18dc57e0d07", + "truck/engine.generated.cpp": "1eb732d23743351fa916161e81d6b533b263b13a9d97674bfef0b8ca308c2b71", + "truck/engine.generated.hpp": "5881bb473d5e9ca872069dd4cc2e235d8210eac3a5105b8ccea2234bd1acf085", + "truck/transmission.generated.cpp": "2f9184c568108186ee20d334792db7d9694af314c39bc3d45bf4a9159c925fd9", + "truck/transmission.generated.hpp": "d104630147223dc04b677cba93e824129eb4744a8db1f817735bd35592ce7404", + "truck.generated.cpp": "bf88e32a5ee1138d37e0f1241bd3f40e2ade1a5c1e61a5e269c6dc0e7255cbfc", + "truck.generated.hpp": "19361eebf6395698cace638a2e3f154d0cec38cb397fa9bf50b7ad51bd959573" + }, + "python": { + "truck/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/brakes/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/brakes/schema.py": "c2bae9a61d329e6e3c0c4900982bb6188b3702a9f2a89634eb37f843fed347d3", + "truck/cms/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/cms/schema.py": "f6e42fc541bfd383c6e5b2ed8b1890093859fe7f6e23ecce7b798cced1c0d4f3", + "truck/common/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/common/schema.py": "31b4def1ae723e011a781dc0ce80b96a2a5962604538fe87462c7556b7c9faa6", + "truck/engine/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/engine/schema.py": "d64bdb81f2ade11bc77a9c09aadef4446cbb654ee2c960ac42306baca63d98b5", + "truck/schema.py": "e7de38050ac2d5267a7aa3383fb11b878f878b02bf59453141d58ae828a754ee", + "truck/transmission/__init__.py": "371dd0f17d1e6a6855c6b06f159fc30b70e7c6c304b3171280311ff3e1496170", + "truck/transmission/schema.py": "b8d53b50f78e1af5896a5b5e99687e9fa448e5155559cf50df652665574c95bf" + }, + "go": { + "truck/brakes/schema.quarry.go": "312db809ff82efab04819ea337fd2adde3f410f07c9d1b858c825be14f7a00bd", + "truck/cms/schema.quarry.go": "f8d343af3a7a7ded74ea1d76f9502b740ef4904665aca35d554afdb92f25a3ff", + "truck/common/schema.quarry.go": "afe5846bb6d5e6f6e7afc696d951777ba25c3792b3c0d22eda3a0d499d413f83", + "truck/engine/schema.quarry.go": "5adedeb609f0463f7f0c6774c94e0e8ee683d670e12469d47d77c80b3793b898", + "truck/schema.quarry.go": "46f9c2209b9d29ac5614735dccaad6d511102fe2aa9a0ea9f1b9a218a4be3669", + "truck/transmission/schema.quarry.go": "64ebb6f88448bea8eb13a82af04ccae2945f1d104669b427278281b17608281a" + } + } +} diff --git a/tests/tools/name_prefix_cmake_test.py b/tests/tools/name_prefix_cmake_test.py new file mode 100644 index 0000000..b0bfc14 --- /dev/null +++ b/tests/tools/name_prefix_cmake_test.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Installed NAME_PREFIX/SCHEMA_ID_VARIABLE and cmake -P policy regression.""" +import argparse +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for option in ('source', 'build-dir', 'cmake'): + parser.add_argument('--' + option, required=True) + args = parser.parse_args() + source = Path(args.source).resolve() + with tempfile.TemporaryDirectory(prefix='quarry-name-prefix-cmake-') as temporary: + work = Path(temporary) + prefix = work / 'install' + + def run(command, success=True): + result = subprocess.run(list(map(str, command)), cwd=work, text=True, + capture_output=True, check=False) + assert (result.returncode == 0) == success, result.stdout + result.stderr + return result.stdout + result.stderr + + run([args.cmake, '--install', args.build_dir, '--prefix', prefix]) + compiler = prefix / 'bin/quarry-schema-compiler' + module = prefix / 'lib/cmake/Quarry/QuarryGenerate.cmake' + roots = [source / 'examples/truck/schemas/configuration.brd', + source / 'examples/truck/multi_configuration/rev_b/configuration.brd'] + project = work / 'consumer' + project.mkdir() + cmakelists = '''cmake_minimum_required(VERSION 3.20) +project(prefix_helper LANGUAGES CXX) +find_package(Quarry CONFIG REQUIRED) +set(other rev_b) +if(COLLIDE) + set(other rev_a) +endif() +set(compiler_option) +if(FAKE_COMPILER) + list(APPEND compiler_option SCHEMA_COMPILER "${FAKE_COMPILER}") +endif() +quarry_generate_cpp(SCHEMA "@A@" OUTPUT_DIR "${CMAKE_BINARY_DIR}/gen" NAME_PREFIX rev_a + SCHEMA_ID_VARIABLE id_a GENERATE truck.engine OUT_FILES files_a ${compiler_option}) +quarry_generate_cpp(SCHEMA "@B@" OUTPUT_DIR "${CMAKE_BINARY_DIR}/gen" NAME_PREFIX ${other} + SCHEMA_ID_VARIABLE id_b GENERATE truck.engine OUT_FILES files_b ${compiler_option}) +quarry_generate_cpp(SCHEMA "@A@" OUTPUT_DIR "${CMAKE_BINARY_DIR}/gen" NAME_PREFIX rev_c + SCHEMA_ID_VARIABLE id_c OUT_FILES files_c ${compiler_option}) +if(NOT id_a STREQUAL "9200ca494f010801b830d0857cf66dde" OR NOT id_c STREQUAL id_a OR id_b STREQUAL id_a) + message(FATAL_ERROR "configuration identity depends on prefix/selection or was not exported") +endif() +file(WRITE "${CMAKE_BINARY_DIR}/results.txt" "${id_a}\\n${id_b}\\n${id_c}\\n${files_a}\\n") +add_custom_target(generate ALL DEPENDS ${files_a} ${files_b} ${files_c}) +'''.replace('@A@', roots[0].as_posix()).replace('@B@', roots[1].as_posix()) + (project / 'CMakeLists.txt').write_text(cmakelists) + build = work / 'build' + configure = [args.cmake, '-Werror=dev', '-S', project, '-B', build, + '-DCMAKE_PREFIX_PATH=' + str(prefix)] + run(configure) + run([args.cmake, '--build', build, '--parallel', '4']) + lines = (build / 'results.txt').read_text().splitlines() + assert lines[:3] == ['9200ca494f010801b830d0857cf66dde', + '806e9a4e11d0df71c4e5b51045f85010', + '9200ca494f010801b830d0857cf66dde'], lines + assert '/rev_a/truck/engine.generated.hpp' in lines[3], lines + assert (build / 'gen/rev_b/truck/engine.generated.hpp').is_file() + + # Exactly the build-time inventory path, under cmake -P with no + # cmake_minimum_required in the caller. #87's policy capture must hold. + script = work / 'verify.cmake' + script.write_text('set(QUARRY_VERIFY_OUTPUT_INVENTORY TRUE)\n' + f'set(QUARRY_VERIFY_COMPILER "{compiler.as_posix()}")\n' + f'set(QUARRY_VERIFY_SCHEMA "{roots[0].as_posix()}")\n' + f'set(QUARRY_VERIFY_OUTPUT_DIR "{(build / "gen").as_posix()}")\n' + 'set(QUARRY_VERIFY_GENERATE "truck.engine")\n' + 'set(QUARRY_VERIFY_NAME_PREFIX "rev_a")\n' + f'set(QUARRY_VERIFY_EXPECTED_OUTPUTS "{lines[3]}")\n' + f'include("{module.as_posix()}")\n' + f'_quarry_generate_query_schema_id("{compiler.as_posix()}" "{roots[0].as_posix()}" id)\n' + 'if(NOT id STREQUAL "9200ca494f010801b830d0857cf66dde")\n' + ' message(FATAL_ERROR "script schema identity mismatch")\nendif()\n') + run([args.cmake, '-Werror=dev', '-P', script]) + # The same installed registry must reject real output collisions. + collision = run([*configure, '-B', work / 'collision', '-DCOLLIDE=ON'], success=False) + assert 'output' in collision.lower() and ('claim' in collision.lower() or 'multiple' in collision.lower()), collision + (project / 'CMakeLists.txt').write_text(cmakelists.replace('NAME_PREFIX rev_a', 'NAME_PREFIX rev_a NAME_PREFIX rev_b', 1)) + duplicate = run([*configure, '-B', work / 'duplicate'], success=False) + assert 'duplicate NAME_PREFIX' in duplicate, duplicate + (project / 'CMakeLists.txt').write_text(cmakelists) + fake = work / 'bad-identity-compiler' + fake.write_text('#!/usr/bin/env python3\nimport os, sys\n' + 'if "--print-schema-id" in sys.argv:\n print("not-a-schema-id")\n sys.exit(0)\n' + f'os.execv({str(compiler)!r}, [{str(compiler)!r}, *sys.argv[1:]])\n') + fake.chmod(0o755) + malformed = run([*configure, '-B', work / 'malformed', '-DFAKE_COMPILER=' + str(fake)], success=False) + assert 'malformed schema_id' in malformed, malformed + print('Installed helper: prefix paths, complete identities, multiple calls, collisions, malformed query and cmake -P passed.') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/name_prefix_test.py b/tests/tools/name_prefix_test.py new file mode 100644 index 0000000..35a8c41 --- /dev/null +++ b/tests/tools/name_prefix_test.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Black-box naming isolation, baseline bytes, identity and strict native consumers.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +VARIANTS = { + 'cpp': ['--language', 'cpp'], + 'c': ['--language', 'c'], + 'c-compact': ['--language', 'c', '--c-optimize-size=truck.common'], + 'cpp-c': ['--language', 'cpp', '--cpp-storage', 'c'], + 'cpp-c-compact': ['--language', 'cpp', '--cpp-storage', 'c', '--c-optimize-size=truck.common'], + 'python': ['--language', 'python'], + 'go': ['--language', 'go', '--go-import-prefix', 'example.com/quarry/naming'], +} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('source', 'compiler', 'generated-include', 'cc', 'cxx', 'runtime-c'): + parser.add_argument('--' + name, required=True) + parser.add_argument("--coverage", default="OFF") + args = parser.parse_args() + source = Path(args.source).resolve() + compiler = str(Path(args.compiler).resolve()) + manifest = json.loads((source / 'tests/fixtures/name_prefix/unprefixed_sha256.json').read_text()) + truck = source / 'examples/truck/schemas/configuration.brd' + with tempfile.TemporaryDirectory(prefix='quarry-name-prefix-') as temporary: + work = Path(temporary) + + def call(*flags, status=0): + result = subprocess.run([compiler, *map(str, flags)], cwd=work, + text=True, capture_output=True, check=False) + assert result.returncode == status, (flags, result.returncode, result.stderr) + if status == 0: + assert not result.stderr, result.stderr + else: + assert result.stderr and not result.stdout, result + return result.stdout + + def files(directory): + return {p.relative_to(directory).as_posix(): p.read_bytes() + for p in directory.rglob('*') if p.is_file()} + + def gid(header): + return re.search(r'^#ifndef .*_([A-F0-9]{32})_$', header.read_text(), re.M).group(1) + + def compile_run(text, name, includes, *, cpp=False, succeeds=True): + path = work / (name + ('.cpp' if cpp else '.c')) + path.write_text(text) + executable = work / name + command = [args.cxx if cpp else args.cc, '-std=c++20' if cpp else '-std=c99', + '-Wall', '-Wextra', '-Wpedantic', '-Werror', '-I' + str(source / 'include'), + '-I' + args.generated_include] + if args.coverage.lower() in ('on', 'true', '1', 'yes'): + command.append('--coverage') + command += ['-I' + str(p) for p in includes] + command += [str(path), args.runtime_c, '-o', str(executable)] + result = subprocess.run(command, text=True, capture_output=True, check=False) + assert (result.returncode == 0) == succeeds, (name, result.stderr) + if succeeds: + subprocess.run([str(executable)], check=True) + return result.stderr + + for variant, flags in VARIANTS.items(): + base, prefixed, selected = [work / (variant + '-' + label) + for label in ('base', 'prefix', 'selection')] + call(*flags, '-o', base, truck) + actual = {name: hashlib.sha256(data).hexdigest() for name, data in files(base).items()} + assert actual == manifest['variants'][variant], variant + call(*flags, '--name-prefix', 'rev_a', '-o', prefixed, truck) + planned = call(*flags, '--name-prefix', 'rev_a', '--list-outputs', '-o', prefixed, truck) + assert set(planned.splitlines()) == {str(prefixed / p) for p in files(prefixed)}, variant + call(*flags, '--name-prefix', 'rev_a', '--generate', 'truck.engine,truck.common', + '-o', selected, truck) + for name, data in files(selected).items(): + assert data == files(prefixed)[name], (variant, name) + assert not list(prefixed.glob('truck')), variant + if variant == 'python': + assert (prefixed / 'rev_a/__init__.py').is_file() + assert 'import rev_a.truck.common.schema' in (prefixed / 'rev_a/truck/engine/schema.py').read_text() + if variant == 'go': + assert 'example.com/quarry/naming/rev_a/truck/common' in (prefixed / 'rev_a/truck/engine/schema.quarry.go').read_text() + if variant in ('cpp', 'c', 'cpp-c'): + extension = '.generated.h' if variant == 'c' else '.generated.hpp' + assert gid(base / ('truck/engine' + extension)) != gid(prefixed / ('rev_a/truck/engine' + extension)) + if variant == 'cpp': + renamed = work / 'cpp-renamed' + call(*flags, '--name-prefix', 'rev_a', '--root-file-stem', 'renamed', + '--file-extension', '.other.hpp', '-o', renamed, truck) + assert gid(renamed / 'rev_a/truck/engine.other.hpp') == gid(prefixed / 'rev_a/truck/engine.generated.hpp') + # A renamed dependency with the wrong gid must still fail even + # after its source-level prefix is made to look correct. + other = work / (variant + '-other') + call(*flags, '--name-prefix', 'rev_b', '-o', other, truck) + common = prefixed / ('rev_a/truck/common' + extension) + original = common.read_bytes() + other_text = (other / ('rev_b/truck/common' + extension)).read_text() + common.write_text(other_text.replace('revq0b', 'revq0a').replace('rev_b', 'rev_a')) + error = compile_run('#include "rev_a/truck/engine' + extension + '"\nint main(void) { return 0; }\n', + variant + '-wrong-gid', [prefixed], cpp=variant != 'c', succeeds=False) + assert 'generated definitions' in error or 'generated-code identity' in error, error + common.write_bytes(original) + # A dependency generated under another prefix is not silently + # resolved through an unprefixed include path. + missing = work / (variant + '-missing') + call(*flags, '--name-prefix', 'rev_a', '--generate', 'truck.engine', '-o', missing, truck) + compile_run('#include "rev_a/truck/engine' + extension + '"\nint main(void) { return 0; }\n', + variant + '-wrong-prefix', [missing, other], cpp=variant != 'c', succeeds=False) + + # Naming must not change actual BRF bytes, including packed dependency storage. + for variant in ('cpp', 'c', 'c-compact', 'cpp-c', 'cpp-c-compact'): + base, named = work / (variant + '-base'), work / (variant + '-prefix') + extension = '.generated.h' if variant.startswith('c') and not variant.startswith('cpp') else '.generated.hpp' + text = '#include "truck/engine' + extension + '"\n#include "rev_a/truck/engine' + extension + '"\n' + if variant == 'cpp': + text += r'''int main() { + truck::engine::EngineStatusBuilder a; + rev_a::truck::engine::EngineStatusBuilder b; + if (!a.set_rpm(1450) || !b.set_rpm(1450)) return 1; + auto wa = truck::engine::encode_result(a.build()); + auto wb = rev_a::truck::engine::encode_result(b.build()); + if (!wa || !wb || *wa.value != *wb.value) return 2; + auto da = truck::engine::decode_EngineStatus_result(*wa.value); + auto db = rev_a::truck::engine::decode_EngineStatus_result(*wb.value); + return da && db && da.value->rpm() && db.value->rpm() && *da.value->rpm() == 1450 && *db.value->rpm() == 1450 ? 0 : 3; +} +''' + else: + text += '#include \nint main(void) {\n unsigned char a[256], b[256];\n' + for name, prefix, output in [('a', 'truck', 'a'), ('b', 'revq0a_truck', 'b')]: + stem = prefix + '_engine_EngineStatus' + timestamp = prefix + '_common_Timestamp' + text += f' {stem}_t v{name}; {stem}_init(&v{name});\n' + text += f' v{name}.has_rpm = true; v{name}.rpm = 1450; v{name}.has_time = true;\n' + text += f' {timestamp}_t t{name}; {timestamp}_init(&t{name}); t{name}.unix_ms = 42;\n' + if variant.endswith('compact'): + text += f' {timestamp}_set_unix_ms_present(&t{name}, true);\n' + else: + text += f' t{name}.has_unix_ms = true;\n' + text += f' v{name}.time = t{name};\n {stem}_encode_result_t e{name} = {stem}_encode(&v{name}, {output}, sizeof({output}));\n' + text += f' if (e{name}.status != QUARRY_C_STATUS_OK) return 1;\n' + text += f' {stem}_decode_result_t d{name} = {stem}_decode({output}, e{name}.bytes_written);\n' + text += f' if (d{name}.status != QUARRY_C_STATUS_OK || d{name}.value.rpm != 1450 || d{name}.value.time.unix_ms != 42) return 2;\n' + text += ' return ea.bytes_written == eb.bytes_written && memcmp(a, b, ea.bytes_written) == 0 ? 0 : 3;\n}\n' + compile_run(text, variant + '-wire', [base, named], cpp=variant.startswith('cpp')) + + identity = call('--print-schema-id', truck) + description = call('--describe', truck) + for prefix in ('rev_a', 'q', 'Rev_A', 'revision_'): + assert call('--print-schema-id', '--name-prefix', prefix, '--generate', 'truck.engine', truck) == identity + assert call('--describe', '--name-prefix', prefix, truck) == description + for reflective in (False, True): + plain, named = work / 'plain.qbs', work / 'named.qbs' + options = ['--qbs-reflective'] if reflective else [] + call('--emit-qbs', plain, *options, truck) + call('--emit-qbs', named, *options, '--name-prefix', prefix, truck) + assert plain.read_bytes() == named.read_bytes() + assert named.read_bytes()[12:28].hex() == identity.strip() + for prefix in ('', '9bad', '_reserved', 'double__underscore', 'not.valid', 'dash-name', + 'class', 'def', 'func', 'match', 'std', 'quarry', 'kQuarrySchemaId', 'quarry_gen_example'): + call('--name-prefix', prefix, '--list-outputs', truck, status=2) + call('--name-prefix', 'rev_a', '--name-prefix', 'rev_b', truck, status=2) + call('--name-prefix', status=2) + call('--name-prefix', 'truck', '--generate', 'truck.engine', truck, status=2) + + # No source namespace is selected, but the complete configuration must + # still reject a conflicting leading namespace segment. + schema = work / 'a.brd' + schema.write_text('namespace: omitted.child\nrecord: Status\nversion: 1\ntype: data\nfields:\n value:\n type: u16\n') + root = work / 'configuration.brd' + (work / 'selected.brd').write_text('namespace: selected\nrecord: Other\nversion: 1\ntype: data\nfields:\n value:\n type: u16\n') + root.write_text('configuration: names\nimports:\n - a.brd\n - selected.brd\n') + call('--name-prefix', 'omitted', '--generate', 'selected', '--list-outputs', root, status=2) + + # C namespace joins and case-only prefixes previously collided (#119). + # Opt-in encoding must distinguish them without changing legacy output. + cases = [('rev_a', 'dep.engine', 'revq0a_dep_engine'), + ('rev', 'a_dep.engine', 'rev_aq0dep_engine'), + ('lower', 'model', 'lower_model'), ('Lower', 'model', 'Lower_model'), + ('q', 'model', 'qq_model')] + for variant, flags, extension, cpp in [ + ('c', ['--language', 'c'], '.h', False), + ('c-cpp', ['--language', 'c'], '.h', True), + ('cpp-c', ['--language', 'cpp', '--cpp-storage', 'c'], '.hpp', True)]: + headers = [] + stems = [] + for number, (prefix, namespace, stem) in enumerate(cases): + schema = work / f'enum-{number}.brd' + schema.write_text('namespace: ' + namespace + '\nrecord: Status\nversion: 1\ntype: data\n' + 'enums:\n Mode:\n values:\n off: 0\n on: 1\n' + 'fields:\n value:\n type: u16\n mode:\n type: Mode\n') + out = work / f'{variant}-adversarial-{number}' + call(*flags, '--name-prefix', prefix, '-o', out, schema) + headers.append(next(out.rglob('*generated' + extension))) + stems.append(stem) + text = ''.join('#include "' + p.as_posix() + '"\n' for p in headers) + text += 'int main(void) {\n unsigned char bytes[256];\n' + for number, stem in enumerate(stems): + text += f''' {stem}_Status_t v{number}; + {stem}_Status_init(&v{number}); + v{number}.has_value = true; v{number}.value = 42; + v{number}.has_mode = true; v{number}.mode = {stem}_MODE_ON; + {stem}_Status_encode_result_t e{number} = {stem}_Status_encode(&v{number}, bytes, sizeof(bytes)); + if (e{number}.status != QUARRY_C_STATUS_OK) return 1; + {stem}_Status_decode_result_t d{number} = {stem}_Status_decode(bytes, e{number}.bytes_written); + if (d{number}.status != QUARRY_C_STATUS_OK || d{number}.value.value != 42 || + d{number}.value.mode != {stem}_MODE_ON) return 2; +''' + text += ' return 0;\n}\n' + compile_run(text, variant + '-adversarial', [], cpp=cpp) + print('72 baseline hashes, seven variants, QBS/identity, selections, negative dependencies and C/C++ enum coexistence passed.') + + +if __name__ == '__main__': + main() diff --git a/tools/README.md b/tools/README.md index 487df15..b48ec2a 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 + --name-prefix NAME Nest generated source names and paths beneath NAME --describe Describe the full configuration without writing files --print-schema-id Print the resolved configuration's 128-bit schema_id --version Show version information @@ -669,3 +670,45 @@ 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. + +### Deliberate source naming isolation + +`--name-prefix rev_a` explicitly nests generated source names beneath `rev_a`. +The configuration name never supplies a prefix automatically. The prefix must +be an ASCII identifier starting with a letter, with no double underscores, +language keyword, reserved `std` / `quarry` name, identity constant, or `quarry_gen_` / `quarry_cfg_` +spelling. Empty, repeated or invalid options are usage errors (exit 2). A prefix +matching any canonical namespace's first segment is also exit 2, even when that +namespace is outside `--generate`. Comparisons preserve case. On case-insensitive +filesystems, choose prefixes differing beyond case when sharing an output tree. + +The prefix is a source naming operation. Schema IR, canonical FQNs, hierarchical +record IDs, BRF/QBS bytes and `schema_id` remain unchanged. `--generate` and +`--c-optimize-size=NS` continue to take canonical, unprefixed namespace names. +`--describe`, `--print-schema-id`, `--list-inputs` and `--emit-qbs` do not include +prefixes in their data. Ordinary query/QBS conflicts keep their existing rules. +`--list-outputs` reports the prefixed output paths. Generation errors remain exit 1. + +| Variant | Naming with `--name-prefix rev_a` | +|---|---| +| C++ owning | `rev_a::truck::engine`, with the existing `quarry_gen_` inline namespace | +| C | `revq0a_truck_engine_EngineStatus_t`, functions and descriptors with the same stem | +| C++ with C storage | The C names above and `quarry::cxx::revq0a_truck_engine_EngineStatus` | +| Python | `rev_a.truck.engine.schema`, absolute dependency imports and `rev_a/__init__.py` | +| Go | `/rev_a/truck/engine`; the namespace's leaf package name is retained | + +Every output path gains a literal `/` directory. C/C++ include paths, +identity macro names and guards use the same prefix consistently. For C symbols +and identity metadata, encode the prefix as the first namespace segment using +[#117's encoding](../docs/design/configuration-identity.md#46-namespace-to-macro-encoding-117): +`q` becomes `qq`, `_` becomes `q0`, and `_` separates encoded segments. Prefixed +C enum constants retain this encoded namespace's case, followed by the existing +uppercase enum/member spelling. Unprefixed C symbols retain their legacy names; +#119's general unprefixed migration remains deferred. + +The format-1 generated-code identity still hashes normalized emitted definitions +under canonical namespace keys. Prefixes can change those definitions and their +`gid`; the algorithm and format do not change. Prefixes do not make prebuilt +native objects ABI-interchangeable. See the +[truck multi-configuration example](../examples/truck/multi_configuration/README.md) +for working C, C++, C-storage, Python and Go consumers. diff --git a/tools/schema_compiler/main.cpp b/tools/schema_compiler/main.cpp index 9641b1a..96bf08b 100644 --- a/tools/schema_compiler/main.cpp +++ b/tools/schema_compiler/main.cpp @@ -1,4 +1,5 @@ #include "compiler/backend/backend.hpp" +#include "compiler/support/generated_names.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" @@ -105,6 +106,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" + " --name-prefix NAME Nest generated source names and paths beneath NAME\n" " --describe Describe the full configuration without writing files\n" " --version Show version information\n" " -h, --help Show this help text\n"; @@ -218,12 +220,14 @@ void print_description(const CommandLine& command_line, [[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" || - option == "--cpp-storage" || option == "--go-import-prefix" || option == "--generate"; + option == "--cpp-storage" || option == "--go-import-prefix" || option == "--generate" || + option == "--name-prefix"; } [[nodiscard]] std::optional parse_command_line(int argc, char** argv, std::ostream& errors) { CommandLine command_line; + bool saw_name_prefix = false; bool saw_output_directory = false; bool saw_root_file_stem = false; bool saw_file_extension = false; @@ -352,7 +356,16 @@ void print_description(const CommandLine& command_line, return std::nullopt; } - if (argument == "-o" || argument == "--output-directory") { + if (argument == "--name-prefix") { + if (saw_name_prefix || !quarry::compiler::support::valid_name_prefix(value)) { + errors << "error: --name-prefix must be specified once as an unreserved " + "portable identifier (letters, digits and underscores; no leading " + "underscore, double underscore, keyword or reserved library/generator name)\n"; + return std::nullopt; + } + saw_name_prefix = true; + command_line.codegen_options.name_prefix = value; + } else if (argument == "-o" || argument == "--output-directory") { if (saw_output_directory) { errors << "error: duplicate output-directory option\n"; return std::nullopt; @@ -445,6 +458,7 @@ void print_description(const CommandLine& command_line, if (command_line.show_generated_code_api_version) { const bool has_generation_arguments = + !command_line.codegen_options.name_prefix.empty() || command_line.list_inputs || command_line.list_outputs || !command_line.input_path.empty() || command_line.codegen_options.output_directory != "generated" || @@ -712,6 +726,24 @@ template return exit_failure; } + if (!command_line.codegen_options.name_prefix.empty()) { + std::vector pending{ + &compilation_result.schema_ir->root_namespace()}; + while (!pending.empty()) { + const auto* ns = pending.back(); + pending.pop_back(); + const auto first = ns->fqn().substr(0, ns->fqn().find('.')); + if (first == command_line.codegen_options.name_prefix) { + errors << "error: --name-prefix '" << first + << "' conflicts with a namespace's first segment in the complete configuration\n"; + return exit_usage; + } + for (const auto& child : ns->namespaces()) { + pending.push_back(&child); + } + } + } + if (command_line.list_inputs) { // Every unit is listed at its canonical path, which changes when its // content does. The root and each import are also listed at the path @@ -868,6 +900,7 @@ template c_options.optimize_size = command_line.c_optimize_size && command_line.c_optimize_size_namespaces.empty(); c_options.optimize_size_namespaces = command_line.c_optimize_size_namespaces; + c_options.name_prefix = command_line.codegen_options.name_prefix; c_options.output_directory = command_line.codegen_options.output_directory; c_options.root_file_stem = command_line.codegen_options.root_file_stem; @@ -905,6 +938,7 @@ template if (command_line.language == Language::Go) { backend_go::CodegenOptions go_options; + go_options.name_prefix = command_line.codegen_options.name_prefix; go_options.output_directory = command_line.codegen_options.output_directory; go_options.root_file_stem = command_line.codegen_options.root_file_stem; go_options.go_import_prefix = command_line.go_import_prefix; @@ -938,6 +972,7 @@ template if (command_line.language == Language::Python) { backend_python::CodegenOptions python_options; + python_options.name_prefix = command_line.codegen_options.name_prefix; python_options.output_directory = command_line.codegen_options.output_directory; python_options.root_module_stem = command_line.codegen_options.root_file_stem;