mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 20:50:13 +01:00
Relates to https://github.com/carbon-language/carbon-lang/issues/1881 - Add support for `.base` field in structs for [parent class initialization](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/classes.md#constructors) - Disabling base class initialization without `.base` - Support class constructors (`Create() -> Self`) for base classes - Direct access to base class(es) attributes with `object.var` remains unaffected Changes: - Add `TypeChecker::FieldTypesWithBase` to help assessing if a struct with `base` fields can be converted to a class - Add a new `base_type()` attribute+getter to `NominalClassDeclaration` to as a first step to allow resolving parametrized classes - Add a new `base` attribute+getter to `NominalClassValue` that contains the base class `NominalClassValue`. It is currently used mainly to get and set members of a class object. - Add `Interpreter::ConvertClassWithBase` to build `NominalClassValue` from a init struct, that contains `.base` fields with either `NominalClassValue` or `StructValue` - Add `FindClassField` to find a field in a class or its base classes - Remove superfluous `ClassDeclaration::base()` in favor of `ClassDeclaration::base_type()` Limitations; - Though some work is done in that direction, parametrized base class where time is not know at the declaration site are not supported. Namely the example below does not compile ``` base class A(T:! Type) {} class B(T:! Type) extends A(T) {} ``` But this one is functional already ``` base class A(T:! Type) {} class B extends A(i32) {} ``` Co-authored-by: Richard Smith <richard@metafoo.co.uk>
41 lines
860 B
Plaintext
41 lines
860 B
Plaintext
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
|
// Exceptions. See /LICENSE for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
//
|
|
// AUTOUPDATE
|
|
// RUN: %{explorer-run}
|
|
// RUN: %{explorer-run-trace}
|
|
// CHECK:STDOUT: Class D
|
|
// CHECK:STDOUT: d.value = 2
|
|
// CHECK:STDOUT: d.GetValue() = 2
|
|
// CHECK:STDOUT: result: 0
|
|
|
|
package ExplorerTest api;
|
|
|
|
base class C {
|
|
fn Method1() {
|
|
Print("Class C");
|
|
}
|
|
fn GetValue[me: Self]() -> i32 {
|
|
return me.value;
|
|
}
|
|
var value: i32;
|
|
}
|
|
|
|
class D extends C {
|
|
fn Method1() {
|
|
Print("Class D");
|
|
}
|
|
var value: i32;
|
|
}
|
|
|
|
fn Main() -> i32 {
|
|
// Initialize derived value first, base value second
|
|
var d: D = {.value = 2, .base={.value = 1}};
|
|
d.Method1();
|
|
|
|
Print("d.value = {0}", d.value);
|
|
Print("d.GetValue() = {0}", d.GetValue());
|
|
return 0;
|
|
}
|