eval<T> function

  1. @experimental
Future<T> eval<T>(
  1. String expression, {
  2. T decoder(
    1. String raw
    )?,
})

evaluates a dart expression.

IMPORTANT

This is just for fun; if the language doesn't support this, there is no point in trying to use this hack!

I just wanted to how this works and experiment with the Dart VM

Implementation

@experimental
Future<T> eval<T>(String expression, {T Function(String raw)? decoder}) async {
  final dec = decoder ?? extendedJsonDecode;
  final uri = Uri.dataFromString(
    '''
    import "dart:isolate";
    import 'dart:async';
    import 'dart:convert';
    import "package:lean_extensions/collection_extensions.dart";
    import "package:lean_extensions/dart_essentials.dart";
    import "package:lean_extensions/lean_extensions.dart";

    Future<void> main(_, SendPort port) async {
      port.send(extendedJsonEncode(await $expression));
    }
    ''',
    mimeType: 'application/dart',
  );

  final port = ReceivePort();
  final isolate = await Isolate.spawnUri(
    uri,
    [],
    port.sendPort,
  );
  final response = (await port.first).toString();

  port.close();
  isolate.kill();

  return dec(response) as T;
}