visitListenExpr method
Implementation
@override
Object? visitListenExpr(Expr.Listen expr) {
Object? object = evaluate(expr.stream);
List<Object?> arguments = [];
Map<Symbol, Object?> namedArguments = {};
for (Expr.Expr argument in expr.arguments) {
var arg = evaluate(argument);
if (argument is Expr.NamedArgs) {
Map args = arg as Map;
namedArguments.addAll({Symbol(args.keys.first): args.values.first});
} else {
arguments.add(arg);
}
}
Stmt.Functional then;
var func = evaluate(expr.arguments.first);
if (func is! LoxFunction) {
throw RuntimeError(
expr.name, "Only func can be used as Mapping function");
} else {
then = func.declaration;
}
Environment previous = environment;
if (object is Stream) {
return object.listen((value) {
if (expr.arguments.first is! Expr.Anonymous) {
previous = environment;
}
LoxFunction thenFun = LoxFunction(then, previous, false);
thenFun.call(this, [value], {});
}, onError: (err) {
var onError = namedArguments[Symbol('onError')];
if (onError != null) {
LoxFunction onErrorFun = onError as LoxFunction;
onErrorFun.call(this, [err], {});
}
}, onDone: () {
var onDone = namedArguments[Symbol('onDone')];
if (onDone != null) {
LoxFunction onDoneFun = onDone as LoxFunction;
onDoneFun.call(this, [], {});
}
});
}
throw RuntimeError(expr.name, "Only stream can be used in listen.");
}