C#C
C#3y ago
rick_o_max

❔ System.Linq.Expressions custom expression

Hi guys!

I'm parsing a custom language and building an Expression Tree based on it, but I came into an issue:

My language can use Labels, but since I parse the file line by line, I can't reference a label that hasn't been parsed yet when creating a Goto expression.

So parsing something like that would give issues:
IFEQUALS var1, 10;
  GOTO label;
END;
label:
  PRINT "HELLO WORLD";

So, my idea was to inherit the Expression class to create a kind of LazyGotoExpression, where the LabelTarget would be evaluated by the time the expression is compiled, but I have no clue how to do that.

Could you guys give me a hand?

Current parsing code:
  private Expression ParseExpression(List<string> tokens, Func<List<string>> parseNextStatement)
        {
            switch (tokens[0])
            {
                case "LABEL":
                    {
                        var label = tokens[1];
                        var labelTarget = Expression.Label(label);
                        _labels.Add(label, labelTarget);
                        return Expression.Label(labelTarget);
                    }
                case "GOTO":
                    {
                        //I MIGHT NOT HAVE THE LABEL REFERENCE HERE, SO I NEED A WAY TO LAZY EVALUATE IT
                        var label = tokens[1];
                        var expression = Expression.Empty();
                        _goto.Add(expression, label);
                        return expression;
                    }


If there is a way to make a custom Expression return another Expression instance, that would be perfect.
Was this page helpful?