[dart2wasm] Only perform compile-time lookup in constant list if index is in-bounds

We have an optimization that will do list lookups at compile time when
the receiver is a constant list and the index is a constant integer.

=> We should only perform this optimization if index is in-bounds.
=> If it's out-of-bounds it should be a [RangeError] thrown at runtime
   (if that code is ever executed)

Closes https://github.com/dart-lang/sdk/issues/55817

Change-Id: I3e99cdd96c79e7ff3f490babb2d52131cbd83a88
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/368302
Commit-Queue: Martin Kustermann <kustermann@google.com>
Reviewed-by: Ömer Ağacan <omersa@google.com>
This commit is contained in:
Martin Kustermann 2024-05-27 11:52:48 +00:00 committed by Commit Queue
parent 85ab16ff67
commit 827a7c4e95
2 changed files with 19 additions and 3 deletions

View file

@ -313,9 +313,11 @@ class Intrinsifier {
}
}
if (constIndex != null) {
ListConstant list = receiver.constant as ListConstant;
Expression element = ConstantExpression(list.entries[constIndex]);
return codeGen.wrap(element, typeOfExp(element));
final entries = (receiver.constant as ListConstant).entries;
if (0 <= constIndex && constIndex < entries.length) {
Expression element = ConstantExpression(entries[constIndex]);
return codeGen.wrap(element, typeOfExp(element));
}
}
return null;

View file

@ -0,0 +1,14 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";
int foo(bool returnA0, List<int> a, [List<int> b = const []]) {
return returnA0 ? a[0] : b[0];
}
main() {
Expect.equals(42, foo(true, const [42]));
Expect.throws(() => foo(false, const [42]), (e) => e is RangeError);
}