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>
40 lines
826 B
Plaintext
40 lines
826 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: Read var_c=1
|
|
// CHECK:STDOUT: Read var_d=2
|
|
// CHECK:STDOUT: Assign var_c=3
|
|
// CHECK:STDOUT: Assign var_d=4
|
|
// CHECK:STDOUT: result: 0
|
|
|
|
package ExplorerTest api;
|
|
|
|
base class C {
|
|
var var_c: i32;
|
|
}
|
|
|
|
class D extends C {
|
|
var var_d: i32;
|
|
}
|
|
|
|
fn Main() -> i32 {
|
|
// Initialization
|
|
var d: D = {.base = {.var_c= 1}, .var_d= 2};
|
|
|
|
// Read
|
|
Print("Read var_c={0}", d.var_c);
|
|
Print("Read var_d={0}", d.var_d);
|
|
|
|
// Assignment
|
|
d.var_c = 3;
|
|
d.var_d = 4;
|
|
Print("Assign var_c={0}", d.var_c);
|
|
Print("Assign var_d={0}", d.var_d);
|
|
|
|
return 0;
|
|
}
|