Definition of constants and operators in Irony

I'm new to Irony and the whole shebang implementation language, so I played with the ExpressionEvaluator , which comes with a source of irony that seems to (almost) match my needs for the project I'm working on.

However, I would like it to support booleans as well, so I added comparison operators to the list of binary operators:

BinOp.Rule = ToTerm("+") | "-" | "*" | "/" | "**" | "==" | "<=" | ">=" | "<" | ">" | "!=" | "<>"; // added comparison operators 

Here is an example of what I'm trying to achieve:

 x = 1 y = 2 eval = x < 2 eval2 = y < x bool = true bool2 = (eval == eval2) 

Due to the added binary operators, he manages to parse the above. However, when compiling and running the code, it does not work in the last two lines.

  • The string bool = true fails with the message: Error: the variable true is not defined. On (5: 8). How to define true and false as constants?
  • Line error bool2 = (eval == eval2) with the message: Error: Operator '==' is not defined for the types System.Boolean and System.Boolean. In (6:15).

Edit: resolved both problems, see answer below.

+4
source share
1 answer

Well, solved both problems. Hope this can help others.

Problem 1

As far as I understand from this discussion thread of irony , true and false constants should be considered as predefined global variables, and not be implemented directly as part of the language. As such, I define them as global when creating the ScriptInterpreter .

It should be remembered that by doing this in this way they can be changed using a script, since they are not constants, but simply global variables. This may be the best way to do this, but it will do now:

 var interpreter = new Irony.Interpreter.ScriptInterpreter( new ExpressionEvaluatorGrammar()); interpreter.Globals["true"] = true; interpreter.Globals["false"] = false; interpreter.Evaluate(parsedSample); 

Problem 2

First, the <> operator must appear before the < and > operators in the binary operator rule:

 BinOp.Rule = ToTerm("+") | "-" | "*" | "/" | "**" | "<>" | "==" | "<=" | ">=" | "<" | ">" | "!="; // added comparison operators 

Then I created a custom implementation of the LanguageRuntime class, which implements the necessary operators.

 public class CustomLanguageRuntime : LanguageRuntime { public CustomLanguageRuntime(LanguageData data) : base(data) { } public override void InitOperatorImplementations() { base.InitOperatorImplementations(); AddImplementation("<>", typeof(bool), (x, y) => (bool)x != (bool)y); AddImplementation("!=", typeof(bool), (x, y) => (bool)x != (bool)y); AddImplementation("==", typeof(bool), (x, y) => (bool)x == (bool)y); } } 

In ExpressionEvaluatorGrammar, override the CreateRuntime method to return an instance of CustomLanguageRuntime :

 public override LanguageRuntime CreateRuntime(LanguageData data) { return new CustomLanguageRuntime(data); } 
+9
source

All Articles