From a722358a0944e788c8aef15dac0af19e811d4761 Mon Sep 17 00:00:00 2001 From: EnzeXing Date: Tue, 20 Aug 2024 12:52:07 -0400 Subject: [PATCH 1/2] Fix uninitializing fields when evaluating a cached constructor call --- .../src/dotty/tools/dotc/transform/init/Objects.scala | 1 - tests/init-global/pos/cache-constructor.scala | 9 +++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/init-global/pos/cache-constructor.scala diff --git a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala index 1ceb8d4472a3..892cd3ce8b06 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala @@ -950,7 +950,6 @@ class Objects(using Context @constructorOnly): val instance = OfClass(klass, outerWidened, ctor, args.map(_.value), envWidened) callConstructor(instance, ctor, args) - instance case ValueSet(values) => values.map(ref => instantiate(ref, klass, ctor, args)).join diff --git a/tests/init-global/pos/cache-constructor.scala b/tests/init-global/pos/cache-constructor.scala new file mode 100644 index 000000000000..f7af30f32516 --- /dev/null +++ b/tests/init-global/pos/cache-constructor.scala @@ -0,0 +1,9 @@ +class Bar: + var f: Int = 0 + +object A: + val b1 = new Bar() + val b2 = new Bar() + val b3 = new Bar() + b3.f = 1 + \ No newline at end of file From 36b49497186b50febf865a556d338d109f9027a6 Mon Sep 17 00:00:00 2001 From: EnzeXing Date: Tue, 20 Aug 2024 14:23:36 -0400 Subject: [PATCH 2/2] Address comment --- compiler/src/dotty/tools/dotc/transform/init/Objects.scala | 5 ++++- tests/init-global/pos/cache-constructor.scala | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala index 892cd3ce8b06..1050fbe85ef2 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Objects.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Objects.scala @@ -908,7 +908,10 @@ class Objects(using Context @constructorOnly): Bottom } - /** Handle new expression `new p.C(args)`. + /** + * Handle new expression `new p.C(args)`. + * The actual instance might be cached without running the constructor. + * See tests/init-global/pos/cache-constructor.scala * * @param outer The value for `p`. * @param klass The symbol of the class `C`. diff --git a/tests/init-global/pos/cache-constructor.scala b/tests/init-global/pos/cache-constructor.scala index f7af30f32516..87769fd5d78a 100644 --- a/tests/init-global/pos/cache-constructor.scala +++ b/tests/init-global/pos/cache-constructor.scala @@ -6,4 +6,3 @@ object A: val b2 = new Bar() val b3 = new Bar() b3.f = 1 - \ No newline at end of file