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/src/bloch/compiler/semantics/semantic_analyser.cpp b/src/bloch/compiler/semantics/semantic_analyser.cpp index b8e2bfe..16fd9b2 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.cpp +++ b/src/bloch/compiler/semantics/semantic_analyser.cpp @@ -255,6 +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); if (t.className.empty()) return; const ClassInfo* info = findClass(t.className); @@ -267,17 +268,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 +956,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 +991,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 +1106,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 +1303,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 +2322,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 +2928,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_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); +} diff --git a/tests/test_semantics.cpp b/tests/test_semantics.cpp index 6d9165a..6ea6f8f 100644 --- a/tests/test_semantics.cpp +++ b/tests/test_semantics.cpp @@ -1079,6 +1079,49 @@ 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; } "