@akala/core
Version:
67 lines • 2.65 kB
JavaScript
import { isPromiseLike } from '../promiseHelpers.js';
import { ExpressionVisitor } from '../parser/expressions/visitors/expression-visitor.js';
import { Injector } from './shared.js';
/**
* Evaluates expressions by resolving dependencies through an injector.
* This class extends ExpressionVisitor to traverse and resolve expressions recursively.
*/
export class InjectorEvaluator extends ExpressionVisitor {
injector;
/**
* Initializes the evaluator with a dependency injector.
* @param injector - The injector instance used to resolve dependencies during expression evaluation.
*/
constructor(injector) {
super();
this.injector = injector;
}
result;
/**
* Evaluates the provided expression and returns the computed result.
* @template T - The expected return type of the expression evaluation.
* @param expression - The expression tree to evaluate.
* @returns The resolved value after traversing and computing the expression.
*/
eval(expression) {
// console.log(expression);
this.result = this.injector;
this.visit(expression);
// console.log(this.result);
return this.result;
}
/**
* Handles constant expressions by setting the result to their fixed value.
* @param expression - The constant expression containing the static value.
* @returns The same constant expression after processing.
*/
visitConstant(expression) {
this.result = expression.value;
return expression;
}
/**
* Resolves member access expressions (e.g., object.property).
* Evaluates the source expression and retrieves the member value via dependency injection if applicable.
* @template T - The type of the source object.
* @template TMember - The key type of the member being accessed.
* @param expression - The member expression representing property access.
* @returns The processed member expression with updated resolution context.
*/
visitMember(expression) {
if (expression.source)
this.visit(expression.source);
let source = this.result;
this.visit(expression.member);
const key = this.result;
if (source instanceof Injector) {
this.result = source.resolve(key);
return expression;
}
if (isPromiseLike(source)) {
this.result = source.then((result) => { return result[key]; });
return expression;
}
this.result = source && source[key];
return expression;
}
}
//# sourceMappingURL=expression-injector.js.map