Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if the script is running in the dart vm or dart2js?

Tags:

dart

dart2js

Is there a way to check if the script is running in the dart vm or dart2js? Maybe using mirrors API?

like image 362
Tiago Avatar asked Feb 01 '13 21:02

Tiago


People also ask

Does dart use a VM?

Native platform: For apps targeting mobile and desktop devices, Dart includes both a Dart VM with just-in-time (JIT) compilation and an ahead-of-time (AOT) compiler for producing machine code.

Does dart Transpile to JavaScript?

No. Dart is designed to compile to JavaScript to run across the modern web.

What is VM in dart?

Dart VM is a virtual machine in a sense that it provides an execution environment for a high-level programming language, however it does not imply that Dart is always interpreted or JIT-compiled, when executing on Dart VM.

How do I run a script in flutter?

dart in the file extension as well. Then call flutter pub run script. dart from the projects root directory via terminal/cli and it'll look inside the bin directory for script. dart calling just script won't find the script unless the extension is missing.


2 Answers

There is no official way, as far as I know. The intent is that for all practical purposes, you shouldn't have to know if you are running native or compiled to JavaScript.

That said, there are few hacks you can use. The easiest one is probably to exploit the fact that Dart has two numeric types, int and double, while JavaScript has only one, which is equivalent to Dart's double, and dart2js doesn't have a special implementation of int just yet. Therefore, identical(1, 1.0) is false in Dart, and the VM implements that correctly, but when compiled to JS, it is true.

Note that you should think pretty hard before using a hack like this. In most cases, you don't have to do that, just write Dart and don't try to recognize if you are running JS or not. Also, noone can guarantee that it will work forever.

like image 140
Ladicek Avatar answered Sep 29 '22 05:09

Ladicek


Based on a code fragment found in path library (Dart v0.7.2) :

import 'dart:mirrors';

/// Value indicating that the VM is Dart on server-side.
const int DART_SERVER=1;

/// Value indicating that the VM is Dart on client-side.
const int DART_CLIENT=2;

/// Value indicating that the VM is JavaScript on client-side (e.g. dart2js).
const int JS_CLIENT=3;

/// Returns the type of the current virtual machine.
int vmType() {
  Map<Uri, LibraryMirror> libraries=currentMirrorSystem().libraries;
  if(libraries[Uri.parse('dart:io')]!=null) return DART_SERVER;
  if(libraries[Uri.parse('dart:html')]!=null) return DART_CLIENT;
  return JS_CLIENT;
}

/// Application entry point.
void main() {
  print(vmType());
}
like image 32
CedX Avatar answered Sep 29 '22 05:09

CedX