[dart2wasm]: Add compile-time define identifying tool

Knowing whether Dart code is running in a WebAssembly context is useful
to potentially select different code paths exploiting differences in
JavaScript and WASM behavior or simply to report the information to
users (e.g. for crash reports).

Without such a constant, one has to rely on implementation differences
such as `identical(0, 0.0)` or check the available `dart:` libraries.
Both are error-prone, so having a reliable constant as an alternative
makes this easier.

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

Change-Id: Ia969641e4b78223c394cbf251805cf77a30cb0fa
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/365822
Reviewed-by: Ömer Ağacan <omersa@google.com>
Commit-Queue: Martin Kustermann <kustermann@google.com>
Commit-Queue: Ömer Ağacan <omersa@google.com>
Reviewed-by: Martin Kustermann <kustermann@google.com>
This commit is contained in:
Simon Binder 2024-05-23 10:51:50 +00:00 committed by Commit Queue
parent 1eaa749e0e
commit 6b71aa1f3e
3 changed files with 19 additions and 1 deletions

View file

@ -82,3 +82,8 @@ In the signatures of imported and exported functions, use the following types:
- For numbers, use `double`.
- For JS objects, use a JS interop type, e.g. `JSAny`, which translates to the Wasm `externref` type. These can be passed around and stored as opaque values on the Dart side.
- For Dart objects, use the corresponding Dart type. This will be emitted as `anyref` and automatically converted to and from the Dart type at the boundary.
## Detecting whether code is running as WebAssembly
`dart2wasm` defines `dart.tool.dart2wasm` as `true`, meaning that `bool.fromEnvironment('dart.tool.dart2wasm')` can be used in a constant context to determine whether it was
compiled to WebAssembly.

View file

@ -92,7 +92,10 @@ Future<CompilerOutput?> compileToModule(compiler.WasmCompilerOptions options,
..sdkRoot = Uri.file('.')
..librariesSpecificationUri = options.librariesSpecPath
..packagesFileUri = options.packagesPath
..environmentDefines = options.environment
..environmentDefines = {
'dart.tool.dart2wasm': 'true',
...options.environment,
}
..explicitExperimentalFlags = options.feExperimentalFlags
..verbose = false
..onDiagnostic = diagnosticMessageHandler

View file

@ -0,0 +1,10 @@
// 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';
void main() async {
const bool isDart2Wasm = bool.fromEnvironment('dart.tool.dart2wasm');
Expect.isTrue(isDart2Wasm);
}