Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Expression Parser in C#

I am working on a calculator program for a finance application. I need to parse and evaluate complex financial expressions like mentioned below.

The expression is a mix of custom functions and arithmetic expressions. I am using NCalc to resolve the Arithmetic expressions. However, I am having trouble in resolving the Custom Functions.

IF((COALESCE(X1,X2)-X3+IF(X4<=0,0,X5))>0, CUSTOM_FUNCTION(X6), X7)

Any suggestion on best approach?

I am currently working on a complex logic Involving Recursive calls and Stack Push/Pop. But it is not working.

like image 932
user5256439 Avatar asked Mar 15 '23 00:03

user5256439


1 Answers

This is an old problem that was solved a long time ago. The solution is to use a parser generator, not to write your own parser from scratch. There are many options available, one of the more popular ones being ANTLR.

Using a parser generator like ANTLR you can describe your problem using easy-to-understand EBNF-like production rules. The parser generator will generate the complicated logic it seems you are now trying to write by hand, in the language of your choosing, in your case C#. Probably the grammar of your language is already available in this format or you have used this format to describe the language to your users and in your development team.

like image 191
Mishax Avatar answered Mar 28 '23 07:03

Mishax