From 4eadd90f9bc0f6b10053192932e08bf28d32a058 Mon Sep 17 00:00:00 2001 From: Akshay Pal Date: Wed, 5 Aug 2026 14:31:50 +0100 Subject: [PATCH 1/4] fix: preserve generic arguments in extends clauses --- .../compiler/semantics/semantic_analyser.cpp | 63 +++++++++++++------ .../compiler/semantics/semantic_analyser.hpp | 3 + tests/test_semantics.cpp | 42 +++++++++++++ 3 files changed, 90 insertions(+), 18 deletions(-) diff --git a/src/bloch/compiler/semantics/semantic_analyser.cpp b/src/bloch/compiler/semantics/semantic_analyser.cpp index b8e2bfe..a0ff119 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.cpp +++ b/src/bloch/compiler/semantics/semantic_analyser.cpp @@ -255,6 +255,8 @@ namespace bloch::compiler { } void SemanticAnalyser::validateTypeApplication(const TypeInfo& t, int line, int column) const { + for (const auto& arg : t.typeArgs) + validateTypeApplication(arg, line, column); if (t.className.empty()) return; const ClassInfo* info = findClass(t.className); @@ -267,17 +269,25 @@ namespace bloch::compiler { } for (size_t i = 0; i < info->typeParams.size() && i < t.typeArgs.size(); ++i) { const auto& bound = info->typeParams[i].bound; - const auto& actual = t.typeArgs[i]; + TypeInfo actual = t.typeArgs[i]; + if (!bound.className.empty() && actual.isTypeParam) { + auto actualBound = getTypeParamBound(actual.className); + if (!actualBound) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type parameter '" + actual.className + + "' does not satisfy bound '" + typeLabel(bound) + "'"); + } + actual = *actualBound; + } if (!bound.className.empty()) { - if (actual.isTypeParam) - continue; if (actual.className.empty()) { throw BlochError(ErrorCategory::Semantic, line, column, "type argument '" + typeLabel(actual) + "' does not satisfy bound '" + typeLabel(bound) + "'"); } - if (actual.className != bound.className && - !isSubclassOf(actual.className, bound.className)) { + if ((actual.className == bound.className && !typeEquals(actual, bound)) || + (actual.className != bound.className && + !isSubclassOf(actual.className, bound.className))) { throw BlochError(ErrorCategory::Semantic, line, column, "type argument '" + typeLabel(actual) + "' does not satisfy bound '" + typeLabel(bound) + "'"); @@ -947,19 +957,33 @@ namespace bloch::compiler { info.column = clsNode->column; info.isStatic = clsNode->isStatic; info.isAbstract = clsNode->isAbstract; + + // A base can refer to this class's type parameters: Child extends Base. + m_currentTypeParams.clear(); + for (auto& tp : clsNode->typeParameters) { + ClassInfo::TypeParamInfo pi; + pi.name = tp->name; + if (tp->bound) + pi.bound = typeFromAst(tp->bound.get()); + m_currentTypeParams.push_back(pi); + info.typeParams.push_back(pi); + } bool hasExplicitBase = false; if (clsNode->baseType) { if (auto named = dynamic_cast(clsNode->baseType.get())) { if (!named->nameParts.empty()) { info.base = named->nameParts.back(); + info.baseType = typeFromAst(clsNode->baseType.get()); hasExplicitBase = true; } } } else if (!clsNode->baseName.empty()) { info.base = clsNode->baseName.back(); + info.baseType = combine(ValueType::Unknown, info.base); hasExplicitBase = true; } else if (!info.isStatic && info.name != "Object") { info.base = "Object"; + info.baseType = combine(ValueType::Unknown, "Object"); } if (info.name == "Object") { if (hasExplicitBase) { @@ -968,16 +992,6 @@ namespace bloch::compiler { } info.base.clear(); } - // Type parameters - m_currentTypeParams.clear(); - for (auto& tp : clsNode->typeParameters) { - ClassInfo::TypeParamInfo pi; - pi.name = tp->name; - if (tp->bound) - pi.bound = typeFromAst(tp->bound.get()); - m_currentTypeParams.push_back(pi); - info.typeParams.push_back(pi); - } if (info.name == "Object" && !info.typeParams.empty()) { throw BlochError(ErrorCategory::Semantic, info.line, info.column, "class 'Object' cannot declare type parameters"); @@ -1093,6 +1107,15 @@ namespace bloch::compiler { } } + // Extends clauses are converted while forward references are permitted. Now that the + // registry is complete, reject raw generic bases and invalid specialisation bounds. + for (auto& [_, info] : m_classes) { + if (info.base.empty()) + continue; + m_currentTypeParams = info.typeParams; + validateTypeApplication(info.baseType, info.line, info.column); + } + // Validate default constructors (parameter-field alignment) for (auto& [name, info] : m_classes) { for (auto* ctor : info.ctorDecls) { @@ -1281,7 +1304,7 @@ namespace bloch::compiler { if (dynamic_cast(expr)) { const ClassInfo* cur = findClass(m_currentClass); if (cur && !cur->base.empty()) - return combine(ValueType::Unknown, cur->base); + return cur->baseType; return combine(ValueType::Unknown, ""); } if (auto call = dynamic_cast(expr)) { @@ -2300,7 +2323,9 @@ namespace bloch::compiler { for (const auto& ctor : base->constructors) { if (!isAccessible(ctor.visibility, base->name, m_currentClass)) continue; - auto cost = paramsConversionCost(ctor.paramTypes, actualTypes); + auto params = substituteMany(ctor.paramTypes, base->typeParams, + cur->baseType.typeArgs); + auto cost = paramsConversionCost(params, actualTypes); if (!cost) continue; if (*cost < bestCost) { @@ -2904,7 +2929,9 @@ namespace bloch::compiler { for (const auto& ctor : base->constructors) { if (!isAccessible(ctor.visibility, base->name, m_currentClass)) continue; - auto cost = paramsConversionCost(ctor.paramTypes, noArgs); + auto params = substituteMany(ctor.paramTypes, base->typeParams, + ctorClassInfo->baseType.typeArgs); + auto cost = paramsConversionCost(params, noArgs); if (!cost) continue; if (*cost < bestCost) { diff --git a/src/bloch/compiler/semantics/semantic_analyser.hpp b/src/bloch/compiler/semantics/semantic_analyser.hpp index 4648fac..48260d4 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.hpp +++ b/src/bloch/compiler/semantics/semantic_analyser.hpp @@ -154,6 +154,9 @@ namespace bloch::compiler { struct ClassInfo { std::string name; std::string base; + // The declared base, including specialisation arguments such as Base. + // `base` remains the simple name used for hierarchy traversal. + TypeInfo baseType; bool isStatic = false; bool isAbstract = false; bool hasDestructor = true; // implicit default exists diff --git a/tests/test_semantics.cpp b/tests/test_semantics.cpp index 6d9165a..93e1f40 100644 --- a/tests/test_semantics.cpp +++ b/tests/test_semantics.cpp @@ -1079,6 +1079,48 @@ TEST(SemanticTest, GenericBoundSatisfiedPasses) { EXPECT_NO_THROW(analyser.analyse(*program)); } +TEST(SemanticTest, GenericBaseSpecialisationSubstitutesConstructorParameters) { + const char* src = + "class Base { public T value; public constructor(T value) -> Base { " + "this.value = value; return this; } } " + "class Derived extends Base { public constructor(int value) -> Derived { " + "super(value); return this; } } " + "function main() -> void { Derived d = new Derived(1); }"; + auto program = parseProgram(src); + SemanticAnalyser analyser; + EXPECT_NO_THROW(analyser.analyse(*program)); +} + +TEST(SemanticTest, RawGenericBaseIsRejected) { + const char* src = + "class Box { public constructor() -> Box = default; } " + "class Derived extends Box { public constructor() -> Derived { super(); return this; } }"; + auto program = parseProgram(src); + SemanticAnalyser analyser; + EXPECT_THROW(analyser.analyse(*program), BlochError); +} + +TEST(SemanticTest, GenericBaseBoundViolationIsRejected) { + const char* src = + "class Entity { public constructor() -> Entity = default; } " + "class Box { public constructor(T value) -> Box { return this; } } " + "class Derived extends Box { public constructor() -> Derived { super(1); return this; } }"; + auto program = parseProgram(src); + SemanticAnalyser analyser; + EXPECT_THROW(analyser.analyse(*program), BlochError); +} + +TEST(SemanticTest, GenericBaseSpecialisedBoundViolationIsRejected) { + const char* src = + "class Token { public constructor() -> Token = default; } " + "class Box> { public constructor() -> Box = default; } " + "class Derived extends Box> { public constructor() -> Derived { " + "super(); return this; } }"; + auto program = parseProgram(src); + SemanticAnalyser analyser; + EXPECT_THROW(analyser.analyse(*program), BlochError); +} + TEST(SemanticTest, GenericDiamondInferenceFromDeclarationType) { const char* src = "class Box { public constructor() -> Box = default; } " From e2a0f9434ec0b1ce160b03a6eadd101ee342083d Mon Sep 17 00:00:00 2001 From: Akshay Pal Date: Wed, 5 Aug 2026 14:36:26 +0100 Subject: [PATCH 2/4] fix: preserve generic arguments in extends clauses --- examples/09_generic_inheritance.bloch | 28 +++++++++++++++++++++++++++ examples/README.md | 16 +++++++++++++++ tests/test_integration.cpp | 23 ++++++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 examples/09_generic_inheritance.bloch diff --git a/examples/09_generic_inheritance.bloch b/examples/09_generic_inheritance.bloch new file mode 100644 index 0000000..ffa634c --- /dev/null +++ b/examples/09_generic_inheritance.bloch @@ -0,0 +1,28 @@ +// A specialised generic base class is useful for typed quantum readouts. +// `MeasuredReadout` fixes Sample's type parameter to bit, so its super call +// must be checked as Sample.constructor(bit), not constructor(T). + +class Sample { + public T value; + + public constructor(T value) -> Sample { + this.value = value; + return this; + } +} + +class MeasuredReadout extends Sample { + public constructor(bit measured) -> MeasuredReadout { + super(measured); + return this; + } +} + +function main() -> void { + qubit q; + x(q); + bit measured = measure q; + + MeasuredReadout readout = new MeasuredReadout(measured); + echo(readout.value); +} diff --git a/examples/README.md b/examples/README.md index 3fd1c9b..618b166 100644 --- a/examples/README.md +++ b/examples/README.md @@ -26,6 +26,8 @@ bloch examples/01_hadamard.bloch --shots=1024 - `04_grover_search.bloch` — Grover search over 2 qubits, marking `11` as the winner - `05_teleport_class.bloch` — class-based single-qubit teleportation (entangle + corrections) - `06_maxcut_c4_class.bloch` — class-based QAOA p=1 for MaxCut on a 4-node cycle +- `08_generics.bloch` — generic classes, bounds, and diamond inference +- `09_generic_inheritance.bloch` — specialised generic base class for a typed quantum readout - `multifile/com/example/QuantumMath.bloch` + `multifile/main.bloch` — multi-file import demo with a static helper ## 01 Hadamard on |0⟩ @@ -167,6 +169,20 @@ bloch examples/08_generics.bloch This demonstrates the usage of generics in user classes. +## 09 Generic inheritance + +**File** `examples/09_generic_inheritance.bloch` + +**Try:** +```bash +bloch examples/09_generic_inheritance.bloch +``` + +`MeasuredReadout` extends `Sample`. Its `super(measured)` call is an +acceptance example for generic inheritance: the compiler must substitute +`T` with `bit` before selecting the `Sample` constructor. The program prints +`1` because it measures a qubit prepared in the `|1⟩` state. + ## Multi-file import: static QuantumMath helper **Files:** `examples/multifile/com/example/QuantumMath.bloch`, `examples/multifile/main.bloch` diff --git a/tests/test_integration.cpp b/tests/test_integration.cpp index ce21a00..8fdf176 100644 --- a/tests/test_integration.cpp +++ b/tests/test_integration.cpp @@ -374,3 +374,26 @@ function main() -> void { std::string output = runBloch(src, "generic_runtime.bloch"); EXPECT_EQ("hi\n", output); } + +TEST(IntegrationTest, GenericInheritanceSpecialisesSuperConstructor) { + std::string src = R"( +class Sample { + public T value; + public constructor(T value) -> Sample { this.value = value; return this; } +} + +class MeasuredReadout extends Sample { + public constructor(bit measured) -> MeasuredReadout { super(measured); return this; } +} + +function main() -> void { + qubit q; + x(q); + bit measured = measure q; + MeasuredReadout readout = new MeasuredReadout(measured); + echo(readout.value); +} +)"; + std::string output = runBloch(src, "generic_inheritance.bloch"); + EXPECT_EQ("1\n", output); +} From b1c5a1c197040ba92569c5cf33c6d6af716571d7 Mon Sep 17 00:00:00 2001 From: Akshay Pal Date: Wed, 5 Aug 2026 14:39:41 +0100 Subject: [PATCH 3/4] fix: preserve generic arguments in extends clauses --- src/bloch/compiler/semantics/semantic_analyser.cpp | 7 +++---- tests/test_semantics.cpp | 3 ++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/bloch/compiler/semantics/semantic_analyser.cpp b/src/bloch/compiler/semantics/semantic_analyser.cpp index a0ff119..16fd9b2 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.cpp +++ b/src/bloch/compiler/semantics/semantic_analyser.cpp @@ -255,8 +255,7 @@ namespace bloch::compiler { } void SemanticAnalyser::validateTypeApplication(const TypeInfo& t, int line, int column) const { - for (const auto& arg : t.typeArgs) - validateTypeApplication(arg, line, column); + for (const auto& arg : t.typeArgs) validateTypeApplication(arg, line, column); if (t.className.empty()) return; const ClassInfo* info = findClass(t.className); @@ -2323,8 +2322,8 @@ namespace bloch::compiler { for (const auto& ctor : base->constructors) { if (!isAccessible(ctor.visibility, base->name, m_currentClass)) continue; - auto params = substituteMany(ctor.paramTypes, base->typeParams, - cur->baseType.typeArgs); + auto params = + substituteMany(ctor.paramTypes, base->typeParams, cur->baseType.typeArgs); auto cost = paramsConversionCost(params, actualTypes); if (!cost) continue; diff --git a/tests/test_semantics.cpp b/tests/test_semantics.cpp index 93e1f40..6ea6f8f 100644 --- a/tests/test_semantics.cpp +++ b/tests/test_semantics.cpp @@ -1104,7 +1104,8 @@ TEST(SemanticTest, GenericBaseBoundViolationIsRejected) { const char* src = "class Entity { public constructor() -> Entity = default; } " "class Box { public constructor(T value) -> Box { return this; } } " - "class Derived extends Box { public constructor() -> Derived { super(1); return this; } }"; + "class Derived extends Box { public constructor() -> Derived { super(1); return this; " + "} }"; auto program = parseProgram(src); SemanticAnalyser analyser; EXPECT_THROW(analyser.analyse(*program), BlochError); From a6a491d1c8e098e68e401b447e1c20456f67a02c Mon Sep 17 00:00:00 2001 From: Akshay Pal Date: Wed, 5 Aug 2026 17:44:05 +0100 Subject: [PATCH 4/4] fix: report errors in custom user destructor logic without crashing --- examples/10_destructor_runtime_error.bloch | 13 ++++++++ ...10_destructor_runtime_error.expected-error | 1 + scripts/run_examples.sh | 21 +++++++++++- src/bloch/runtime/runtime_evaluator.cpp | 33 ++++++++++++++++++- src/bloch/runtime/runtime_evaluator.hpp | 7 ++++ 5 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 examples/10_destructor_runtime_error.bloch create mode 100644 examples/10_destructor_runtime_error.expected-error diff --git a/examples/10_destructor_runtime_error.bloch b/examples/10_destructor_runtime_error.bloch new file mode 100644 index 0000000..8cfdccc --- /dev/null +++ b/examples/10_destructor_runtime_error.bloch @@ -0,0 +1,13 @@ +// Acceptance regression: errors in user destructor code must be reported normally. +class FailingCleanup { + public constructor() -> FailingCleanup { } + + destructor() -> void { + int x = 1 % 0; + } +} + +function main() -> void { + FailingCleanup resource = new FailingCleanup(); + destroy resource; +} diff --git a/examples/10_destructor_runtime_error.expected-error b/examples/10_destructor_runtime_error.expected-error new file mode 100644 index 0000000..4c774bf --- /dev/null +++ b/examples/10_destructor_runtime_error.expected-error @@ -0,0 +1 @@ +Runtime error at Ln 6, Col 19: modulo by zero diff --git a/scripts/run_examples.sh b/scripts/run_examples.sh index dc6a397..359928e 100755 --- a/scripts/run_examples.sh +++ b/scripts/run_examples.sh @@ -84,9 +84,28 @@ failures=0 for example in "${EXAMPLES[@]}"; do relative_path="${example#${TEMP_DIR}/}" output_file="${TEMP_DIR}/example-output.txt" + expected_error_file="${example%.bloch}.expected-error" printf ' RUN %s\n' "${relative_path}" - if run_example "${example}" "${output_file}"; then + if [[ -f "${expected_error_file}" ]]; then + expected_error="$(<"${expected_error_file}")" + if run_example "${example}" "${output_file}"; then + failures=$((failures + 1)) + printf ' %bFAIL%b %s (expected a runtime failure)\n' \ + "${RED}" "${RESET}" "${relative_path}" >&2 + else + status=$? + if [[ ${status} -ne 1 ]] || ! grep -Fq -- "${expected_error}" "${output_file}"; then + failures=$((failures + 1)) + printf ' %bFAIL%b %s (exit %d)\n' \ + "${RED}" "${RESET}" "${relative_path}" "${status}" >&2 + sed 's/^/ /' "${output_file}" >&2 + else + printf ' %bPASS%b %s (expected runtime diagnostic)\n' \ + "${GREEN}" "${RESET}" "${relative_path}" + fi + fi + elif run_example "${example}" "${output_file}"; then printf ' %bPASS%b %s\n' "${GREEN}" "${RESET}" "${relative_path}" else status=$? diff --git a/src/bloch/runtime/runtime_evaluator.cpp b/src/bloch/runtime/runtime_evaluator.cpp index baf5aec..cf6f844 100644 --- a/src/bloch/runtime/runtime_evaluator.cpp +++ b/src/bloch/runtime/runtime_evaluator.cpp @@ -534,6 +534,7 @@ namespace bloch::runtime { m_gcRequested = false; m_gcThreadStarted = false; m_allocSinceGc = 0; + m_deferredRuntimeError = nullptr; m_sim = QasmSimulator{m_collectQasmLog}; bool hasClasses = !program.classes.empty(); if (hasClasses) { @@ -556,6 +557,7 @@ namespace bloch::runtime { m_gcThread.join(); } runCycleCollector(); + throwDeferredRuntimeError(); // Ensure warnings appear before any normal echo output if (m_warnOnExit) warnUnmeasured(); @@ -1355,6 +1357,28 @@ namespace bloch::runtime { obj->fields.clear(); } + void RuntimeEvaluator::deferRuntimeError(std::exception_ptr error) noexcept { + try { + std::lock_guard lock(m_deferredRuntimeErrorMutex); + // Preserve the first failure: it is the one that caused teardown to begin. + if (!m_deferredRuntimeError) + m_deferredRuntimeError = std::move(error); + } catch (...) { + // A deleter cannot propagate any exception. Failure to retain a diagnostic is + // preferable to terminating the host process. + } + } + + void RuntimeEvaluator::throwDeferredRuntimeError() { + std::exception_ptr error; + { + std::lock_guard lock(m_deferredRuntimeErrorMutex); + error = std::move(m_deferredRuntimeError); + } + if (error) + std::rethrow_exception(error); + } + void RuntimeEvaluator::runFieldInitialisers(RuntimeClass* cls, const std::shared_ptr& obj) { if (!cls) @@ -1944,6 +1968,7 @@ namespace bloch::runtime { Value val = eval(assignStmt->value.get()); assign(assignStmt->name, val); } + throwDeferredRuntimeError(); } Value RuntimeEvaluator::eval(Expression* e) { @@ -2253,7 +2278,13 @@ namespace bloch::runtime { "cannot instantiate static or abstract class '" + cls->name + "'"); } auto deleter = [this](Object* obj) { - destroyObject(obj, !obj->skipDestructor); + // This try/catch means that user error in custom destructors is handled internally + // and does not crash the application + try { + destroyObject(obj, !obj->skipDestructor); + } catch (...) { + deferRuntimeError(std::current_exception()); + } delete obj; }; auto obj = std::shared_ptr(new Object{}, deleter); diff --git a/src/bloch/runtime/runtime_evaluator.hpp b/src/bloch/runtime/runtime_evaluator.hpp index 77bbeee..c19f9f2 100644 --- a/src/bloch/runtime/runtime_evaluator.hpp +++ b/src/bloch/runtime/runtime_evaluator.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -260,6 +261,10 @@ namespace bloch::runtime { std::condition_variable m_gcCv; std::mutex m_gcMutex; std::mutex m_heapMutex; + // A shared_ptr destruction path must not allow a user-program exception to escape: + // shared_ptr destruction is noexcept, so escaping would call std::terminate. + std::exception_ptr m_deferredRuntimeError; + std::mutex m_deferredRuntimeErrorMutex; size_t m_allocSinceGc = 0; // Buffer for echo outputs so logs (INFO/WARNING/ERROR) // can be displayed first before normal program output. @@ -321,6 +326,8 @@ namespace bloch::runtime { void markValue(const Value& v); void markObject(const std::shared_ptr& obj); void destroyObject(Object* obj, bool runUserDestructor); + void deferRuntimeError(std::exception_ptr error) noexcept; + void throwDeferredRuntimeError(); Value callMethod(RuntimeMethod* method, RuntimeClass* staticDispatchClass, const std::shared_ptr& receiver, const std::vector& args); void runConstructorChain(RuntimeClass* cls, const std::shared_ptr& obj,