dart_eval
is an extensible interpreter for the dart language, written in dart.
it’s powered under the hood by the dart analyzer,
so it achieves 100% correct and up-to-date parsing (although evaluation isn’t quite there yet.)
the primary goal of dart_eval
is to be interoperable with real dart code.
classes created in ‘real dart’ can be used inside the interpreter with a
wrapper, and classes created in the interpreter can be used outside it by
creating an interface and bridge class.
for now, the project’s current target is to achieve 100% correct evaluation of valid
dart code. correct error handling (beyond parse errors) is out of the scope at this
time.
usage
a simple usage example:
import 'package:dart_eval/dart_eval.dart';
main() {
final parser = parse();
final scope = parser.parse('''
class cat {
cat();
void speak(string name) {
print('meow');
print(name);
}
}
void main() {
final cat = cat();
cat.speak('fluffy');
}
''');
scope('main', []);
}
interop
there are three types of interop:
- value interop
- wrapper interop
- bridge interop
value interop
value interop is the most basic form, and happens automatically whenever the eval
environment is working with an object backed by a real dart value. (therefore, an
int and a string are value interop enabled, but a class created inside eval isn’t.)
to access the backing object of an evalvalue
, use its realvalue
property. you
can also pass a value-interop only enabled object to eval using evalrealobject
with its optional parameters not set, but this is not recommended. instead, you
should use the class pertaining to the value type, such as evalint
or evalstring
.
wrapper interop
using a wrapper enables the eval environment to access the functions and fields on
a class created outside eval. it’s much more powerful than value interop, but much
simpler than bridge interop, making it a great choice for certain use cases. to use
wrapper interop, create an evalrealobject
using its optional parameters to map out
the fields and methods of the wrapped type.
bridge interop
bridge interop enables the most functionality: not only can eval access the fields
of an object, but it can also be extended, allowing you to create subclasses within eval
and use them outside of eval. for example, bridge interop is used by
flightstream to enable the creation of custom flutter widgets within eval.
the downside of bridge interop is that it’s comparatively difficult to use, and
it can’t be used to wrap existing objects created in code you don’t control. (for utmost
flexibility at the expense of simplicity, you can use both bridge and wrapper interop.)
since bridge interop requires a lot of boilerplate code, in the future i will be creating
a solution for code-generation of that boilerplate.
an example featuring bridge interop is available in the example
directory.
Comments are closed.