C语言解释器-12 控制结构之break、continue和return

来源:互联网 发布:mac怎么看群相册 编辑:程序博客网 时间:2024/05/17 04:29

这三种控制结构都必须结合上下文环境共同作用。看起来它们更像是一种标记。因此上,它们的实现也相当简单:

public class Break : ControlFlow    {        public override void Print(int tabs = 0)        {            Debug.WriteLine(new string('\t', tabs) + "break;");                    }    }


 

public class Continue : ControlFlow    {        public override void Print(int tabs = 0)        {            Debug.WriteLine(new string('\t', tabs) + "continue;");        }    }


return多了一个返回值的表达式:

public class Return : ControlFlow    {        public Expression.ExpressionNode Expression;        public override void Print(int tabs = 0)        {            if (Expression == null)                Debug.WriteLine(new string('\t', tabs) + "return ;");            else            {                Debug.WriteLine(new string('\t', tabs) + "return " + Expression.ToString());            }        }    }

 

一切需要回溯到Block,在Block运行时,会检测这三种控制结构:

public override void Run(Context ctx)        {            if (IsFirstRunning)            {                Block parentBlock = this.ParentBlock;                if (parentBlock != null)                {                    this.OnReturn += parentBlock.OnReturn;                    this.OnBreak += parentBlock.OnBreak;                    this.OnContinue += parentBlock.OnContinue;                }                IsFirstRunning = false;            }            foreach (Context stx in Children)            {                if (stx is ControlFlow.ControlFlow)                {                    if (!ExecuteControlFlow(stx))                        break;


再看ExecuteControlFlow():

private bool ExecuteControlFlow(Context stx)        {            if (stx is ControlFlow.Return)            {                if (OnReturn != null)                    OnReturn(this, stx as ControlFlow.Return);                return false;            }            else            {                if (stx is ControlFlow.Break)                {                    if (OnBreak != null)                        OnBreak(this);                    return false;                }                else                    if (stx is ControlFlow.Continue)                    {                        if (OnContinue != null)                            OnContinue(this);                        return false;                    }                    else                        stx.Run(this);            }            return true;        }


通过返回false来立即中止上层Block的运行循环。