# All files / NCalc Expression.ts

92.04% Statements 81/88
83.87% Branches 26/31
90.9% Functions 10/11
91.95% Lines 80/87

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
    208
    209
    210
    211

    282x

    180x

    2x

    141x

    1x

    1x

    141x

    141x

    141x

    155x

    2x

    141x

    141x
    80x

    61x

    141x
    141x

    141x
    141x

    90x

    80x

    80x
    80x
    4x
    4x
    4x
    4x

    76x

    76x
    76x
    76x

    76x
    76x
    76x

    76x

    75x
    75x

    75x

    87x
    87x
    80x

    86x
    2x

    84x

    3x

    141x
    141x

    85x
    1x

    84x

    84x
    84x
    84x
    84x

    84x
    1x
    1x
    1x
    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x

    1x
    1x
    5x
    5x
    5x

    5x
    5x

    1x

    83x
    81x

     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';

    export class ErrorListener {
      private _errors: any = [];
      public get errors() {
        return this._errors;
      }
      public syntaxError(...args: any) {
        this._errors.push(args);
      }
    }

    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: boolean = true;

      private static _compiledExpression: {[key: string]: WeakRef<LogicalExpression>} = {};

      public ParsedExpression: LogicalExpression;

      protected ParameterEnumerators: {[key: string]: any} = {};

      protected ParametersBackup: {[key: string]: object} = {};

      public Parameters: {[key: string]: any} = {};

      public get CacheEnabled() {
        return Expression._cacheEnabled;
      }

      public static get CachedExpressions() {
        return Expression._compiledExpression;
      }

      public set CacheEnabled(value: boolean) {
        Expression._cacheEnabled = value;
        Iif (value === false) {
          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 (Expression._compiledExpression.hasOwnProperty(expression)) {
            const wr = Expression._compiledExpression[expression];
            const stored = wr.deref();
            if (stored && stored !== undefined) {
              return stored;
            }
          }
        }

        if (logicalExpression == null) {
          // Create the lexer
          let inputStream = new antlr4.CharStream(expression);
          let lexer = new NCalcLexer(inputStream);
          lexer.addErrorListener(this.lexerErrors);

          // Create parser
          let tokenStream = new antlr4.CommonTokenStream(lexer);
          let parser = new NCalcParser(tokenStream);
          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 {
        if (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
          );
        }

        var 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 (let key in this.Parameters) {
            this.ParametersBackup[key] = this.Parameters[key];
          }

          this.ParameterEnumerators = {};

          for (let parameter in this.Parameters) {
            const value = this.Parameters[parameter];
            if (Array.isArray(value)) {
              let 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 (let key in this.Parameters) {
            var parameter = this.Parameters[key];
            if (parameter != null) {
              this.ParameterEnumerators[key] = parameter;
            }
          }

          var results = [];
          for (let i = 0; i < size; i++) {
            for (let key in this.ParameterEnumerators) {
              let 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;
      }
    }