All files / NCalc Expression.ts

90.58% Statements 77/85
80.64% Branches 25/31
87.5% Functions 7/8
90.47% Lines 76/84

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207                              186x             2x   2x         186x   186x     186x     234x                     2x               186x       186x 119x   67x     186x 186x     186x 186x       130x       119x   119x 119x 4x 4x 4x 4x         115x   115x 115x 115x     115x 115x   115x   115x   115x 115x       115x               126x 126x 119x           126x 2x       124x   2x       186x 186x     124x       124x             124x 124x 124x 124x     124x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x       1x 1x 5x 5x 5x     5x 5x     1x     123x 121x      
/* eslint-disable @typescript-eslint/no-explicit-any */
import {EvaluationException, EvaluationVisitor, LogicalExpression} from '@/NCalc/Domain/index';
import NCalcParser from '@/Grammar/NCalcParser';
import NCalcLexer from '@/Grammar/NCalcLexer';
import {EvaluateOptions} from './EvaluationOptions';
import {EvaluateFunctionHandler, EvaluateParameterHandler} from './types';
import {default as antlr4} from 'antlr4';
import { ErrorListener } from './ErrorListener';
 
export class Expression {
 
    private lexerErrors: ErrorListener;
 
    private parserErrors: ErrorListener;
 
    public Options: EvaluateOptions = EvaluateOptions.None;
 
    /**
   * Orginal strings representation of the expression
   */
    protected OriginalExpression: string;
 
    private static _cacheEnabled = true;
 
    private static _compiledExpression: {[key: string]: WeakRef<LogicalExpression>} = {};
 
    public ParsedExpression: LogicalExpression;
 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    protected ParameterEnumerators: {[key: string]: any} = {};
 
    protected ParametersBackup: {[key: string]: object} = {};
 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    public Parameters: {[key: string]: any} = {};
 
    public get CacheEnabled() {
        return Expression._cacheEnabled;
    }
 
    public set CacheEnabled(value: boolean) {
        Expression._cacheEnabled = value;
        Iif (value === false) {
            Expression._compiledExpression = {};
        }
    }
 
    public static get CachedExpressions() {
        return Expression._compiledExpression;
    }
 
    public constructor(expression: LogicalExpression);
    public constructor(expression: string);
    public constructor(expression: LogicalExpression, options: EvaluateOptions);
    public constructor(expression: string, options: EvaluateOptions);
    public constructor(expression: any, options: EvaluateOptions = EvaluateOptions.None) {
        Iif (expression == null || expression == '') {
            throw new Error('The expression cannot be null or empty');
        }
 
        if (typeof expression === 'string') {
            this.OriginalExpression = expression;
        } else {
            this.ParsedExpression = expression;
        }
 
        if (options) {
            this.Options = options;
        }
 
        this.lexerErrors = new ErrorListener();
        this.parserErrors = new ErrorListener();
    }
 
    public get errors() {
        return this.lexerErrors.errors.concat(this.parserErrors.errors);
    }
 
    public Compile(expression: string, nocache: boolean): LogicalExpression {
        let logicalExpression: LogicalExpression | null = null;
 
        if (this.CacheEnabled && !nocache) {
            if (Object.prototype.hasOwnProperty.call(Expression._compiledExpression, expression)) {
                const wr = Expression._compiledExpression[expression];
                const stored = wr.deref();
                if (stored && stored !== undefined) {
                    return stored;
                }
            }
        }
 
        if (logicalExpression == null) {
            // Create the lexer
            const inputStream = new antlr4.CharStream(expression);
            const lexer = new NCalcLexer(inputStream);
            lexer.addErrorListener(this.lexerErrors);
 
            // Create parser
            const tokenStream = new antlr4.CommonTokenStream(lexer);
            const parser = new NCalcParser(tokenStream);
            // parser._interp.predictionMode = antlr4.PredictionMode.SLL;
            parser.addErrorListener(this.parserErrors);
 
            logicalExpression = (parser as any).GetExpression();
 
            if (this.CacheEnabled && !nocache) {
                Expression._compiledExpression[expression] = new WeakRef(logicalExpression);
            }
        }
 
        return logicalExpression;
    }
 
    /**
   * Detects whether the expression has errors. This will simply return a boolean value.
   * You can access the error by using the `errors` getter.
   */
    public HasErrors(): boolean {
        try {
            if (this.ParsedExpression == null) {
                this.ParsedExpression = this.Compile(
                    this.OriginalExpression,
                    (this.Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache
                );
            }
 
            if (this.errors.length > 0) {
                throw new Error();
            }
 
            // In case HasErrors() is called multiple times for the same expression
            return this.ParsedExpression === null || this.ParsedExpression === undefined;
        } catch (e) {
            return true;
        }
    }
 
    public EvaluateFunction: {[key: string]: EvaluateFunctionHandler} = {};
    public EvaluateParameter: {[key: string]: EvaluateParameterHandler} = {};
 
    public Evaluate(): any {
        Iif (this.HasErrors()) {
            throw new EvaluationException('Failed evaluating the expression. Refer to errors.');
        }
 
        Iif (this.ParsedExpression == null) {
            this.ParsedExpression = this.Compile(
                this.OriginalExpression,
                (this.Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache
            );
        }
 
        const visitor = new EvaluationVisitor(this.Options);
        visitor.EvaluateFunction = this.EvaluateFunction;
        visitor.EvaluateParameter = this.EvaluateParameter;
        visitor.Parameters = this.Parameters;
 
        // if array evaluation, execute the same expression multiple times
        if ((this.Options & EvaluateOptions.IterateParameters) == EvaluateOptions.IterateParameters) {
            let size = -1;
            this.ParametersBackup = {};
            for (const key in this.Parameters) {
                this.ParametersBackup[key] = this.Parameters[key];
            }
 
            this.ParameterEnumerators = {};
 
            for (const parameter in this.Parameters) {
                const value = this.Parameters[parameter];
                if (Array.isArray(value)) {
                    const localsize = value.length;
                    if (size == -1) {
                        size = localsize;
                    } else IEif (localsize != size) {
                        throw new EvaluationException(
                            'When IterateParameters option is used, IEnumerable parameters must have the same number of items'
                        );
                    }
                }
            }
 
            for (const key in this.Parameters) {
                const parameter = this.Parameters[key];
                if (parameter != null) {
                    this.ParameterEnumerators[key] = parameter;
                }
            }
 
            const results = [];
            for (let i = 0; i < size; i++) {
                for (const key in this.ParameterEnumerators) {
                    const enumerator = this.ParameterEnumerators[key];
                    this.Parameters[key] = enumerator[i];
                }
 
                this.ParsedExpression.Accept(visitor);
                results.push(visitor.Result);
            }
 
            return results;
        }
 
        this.ParsedExpression.Accept(visitor);
        return visitor.Result;
    }
}