【发布时间】:2021-12-15 21:52:14
【问题描述】:
我尝试使用 C# 扩展树编写一些简单的 Brainf*ck 执行器。 但我不能让循环工作。
我有这样的输入:++++++++++++++++++++[>>+<++<-]>.>.
在 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]);
}
看起来应该可以,但问题是变量。
while 循环中的语句是嵌套的ExpressionBlock,任何使用lent 或index 都会导致以下异常:
从范围“”引用的“System.Int32”类型的变量“索引”,但未定义
我构建循环的代码是这样的
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));
变量prebody 包含一个内部语句块。如果我在创建块时添加变量,它会在正文中创建具有相同名称的新变量。如果我不添加它们,我就没有这个变量,也无法访问外部块中的变量。
有没有办法创建一个嵌套的语句块,可以从外部块访问变量?
【问题讨论】:
标签: c# expression-trees