Home > Software engineering >  How to get access to variables from outer Block in nested one?
How to get access to variables from outer Block in nested one?

Time:12-16

I trying to code some simple brainf*ck executor with C# extension trees. But I can't make loops work.

I have something like this as imput: [>> < <-]>.>. And after the building from CST:

() => {
    int index;
    LazyDictionary<int, char> lent;
    index = 0;
    lent = #LazyDictionary<int, char>;
    lent[index] = (char)(lent[index]   20);
    while (true) {
        if (lent[index] == '') {
            break;
        } else {
            index  = (int)2;
            lent[index] = (char)(lent[index]   1);
            index -= (int)1;
            lent[index] = (char)(lent[index]   2);
            index -= (int)1;
            lent[index] = (char)(lent[index] - 1);
        }
    };
    index  = (int)1;
    Console.Write(lent[index]);
    index  = (int)1;
    Console.Write(lent[index]);
}

It looks like thit should work, but the problem is variables.

Statements in the while loop is a nested ExpressionBlock and any using of lent or index lead to exception like:

Variable 'index' of type 'System.Int32' referenced from scope '', but it is not defined

My code for building loop is something like this

cstLoopNode.Inner.Visit(this);

var prebody = Buffer.Pop();
var breakLabel = Expression.Label();
var condition = Expression.Equal(CurrentLentValueExpression, Expression.Constant('\0'));
var loopStopper = Expression.IfThenElse(condition, Expression.Break(breakLabel), prebody);

Buffer.Push(Expression.Loop(loopStopper, breakLabel));

The variable prebody contains a Block of inner statements. If I add variables when create the Block, it creates new variables into the body with same names. If I don't add them, I don't have this variables and it can't get access to ones form outer Block.

Is there a way for create a nested block of statements which can get access to variables from the outside block?

CodePudding user response:

When you create a block using Expression.Block you give a collection of local variables. Those should be visible within the block and any sub-blocks. You will have to bubble up the needed variables to the declaration of the Block if you don't know them until you traverse.

See BlockExpression.Variables

  • Related