mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 22:02:23 +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>
34 lines
679 B
Plaintext
34 lines
679 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: 1
|
|
// CHECK:STDOUT: 2
|
|
// CHECK:STDOUT: result: 0
|
|
|
|
package ExplorerTest api;
|
|
|
|
base class A {
|
|
fn Create() -> Self {
|
|
return {.value_a = 1};
|
|
}
|
|
var value_a: i32;
|
|
}
|
|
|
|
class B extends A {
|
|
fn Create() -> Self {
|
|
return {.base = A.Create(), .value_b = 2};
|
|
}
|
|
var value_b: i32;
|
|
}
|
|
|
|
fn Main() -> i32 {
|
|
var b: B = B.Create();
|
|
Print("{0}", b.value_a);
|
|
Print("{0}", b.value_b);
|
|
return 0;
|
|
}
|