0

Imagine a scenario where you want to allow users to supply an application with logical binary expressions as strings, using a set of well-defined parameters. For example:

"isSuperAdmin || userLevel > 5 && isAdmin"

The system is using NReco's Lambda Parser to validate the expression by trying to Parse it:

Expression exp = lambdaParser.Parse("isSuperAdmin || userLevel > 5 && isAdmin");

The above returns an expression if the structure of the expression is valid, throws otherwise. But it cannot apply any type-checking on the parameters E.g. isAdmin must be a boolean value but what if the user has constructed the following:

    "isSuperAdmin || userLevel > 5 && isAdmin > 33"

This expression is syntactically correct and can be parsed, but it will not be evaluated properly because isAdmin is a boolean, not an integer. Is there a way, not necessarily using NReco.LambdaParser, to infer the expected type of each parameter in an expression and validate it?

mihalios
  • 828
  • 1
  • 6
  • 12
  • No!!! There is no way of inferring that a variable like "userLevel" is an integer or string. It is valid in any algebra that a comparison of string could be : "A" > "B". You first have to define the algebra and the operations that are allowed before you can infer. – jdweng May 05 '21 at 10:43
  • NReco.LambdaParser was specially designed to allow 'weak-type' parameters, without strong types that are needed for .NET Expression trees. To validate an expression you may use LambdaParser.Parse method and analyze generated Expression-tree, however it might be non-trivial to detect what parameter type _should be_ because LambdaParser tries to align types in run-time. – Vitaliy Fedorchenko May 05 '21 at 11:08
  • @VitaliyFedorchenko exactly, I tried to determine the types from the expression tree but it didn't turn out to be possible. An alternative approach to my problem would be to perform type-checking when an expression string is constructed, instead of whenever it's evaluated. – mihalios May 05 '21 at 11:12
  • Don't know anything about this NReco.LambdaParser, but `true` is usually 1 and `false` is usually 0, so the expression `true > false` is usually true, and there is no error in it. – Dialecticus May 05 '21 at 11:30

0 Answers0