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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions examples/09_generic_inheritance.bloch
Original file line number Diff line number Diff line change
@@ -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<bit>.constructor(bit), not constructor(T).

class Sample<T> {
public T value;

public constructor(T value) -> Sample<T> {
this.value = value;
return this;
}
}

class MeasuredReadout extends Sample<bit> {
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);
}
16 changes: 16 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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⟩
Expand Down Expand Up @@ -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<bit>`. 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`
Expand Down
62 changes: 44 additions & 18 deletions src/bloch/compiler/semantics/semantic_analyser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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) + "'");
Expand Down Expand Up @@ -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<T> extends Base<T>.
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<NamedType*>(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) {
Expand All @@ -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");
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -1281,7 +1303,7 @@ namespace bloch::compiler {
if (dynamic_cast<SuperExpression*>(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<CallExpression*>(expr)) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions src/bloch/compiler/semantics/semantic_analyser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ namespace bloch::compiler {
struct ClassInfo {
std::string name;
std::string base;
// The declared base, including specialisation arguments such as Base<int>.
// `base` remains the simple name used for hierarchy traversal.
TypeInfo baseType;
bool isStatic = false;
bool isAbstract = false;
bool hasDestructor = true; // implicit default exists
Expand Down
23 changes: 23 additions & 0 deletions tests/test_integration.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> {
public T value;
public constructor(T value) -> Sample<T> { this.value = value; return this; }
}

class MeasuredReadout extends Sample<bit> {
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);
}
43 changes: 43 additions & 0 deletions tests/test_semantics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,49 @@ TEST(SemanticTest, GenericBoundSatisfiedPasses) {
EXPECT_NO_THROW(analyser.analyse(*program));
}

TEST(SemanticTest, GenericBaseSpecialisationSubstitutesConstructorParameters) {
const char* src =
"class Base<T> { public T value; public constructor(T value) -> Base<T> { "
"this.value = value; return this; } } "
"class Derived extends Base<int> { 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<T> { public constructor() -> Box<T> = 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<T extends Entity> { public constructor(T value) -> Box<T> { return this; } } "
"class Derived extends Box<int> { 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<T> { public constructor() -> Token<T> = default; } "
"class Box<T extends Token<int>> { public constructor() -> Box<T> = default; } "
"class Derived extends Box<Token<float>> { 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<T> { public constructor() -> Box<T> = default; } "
Expand Down
Loading