Few interpreters (or compilers) Implement switch control. Without it, it's complicated. SharpC divides the switch into two parts: switch (expression) and case.
First, let's look at the implementation of Case, which consists of the condition value and the execution part:
public class Case : ControlFlow { public Expression.Operand.Value Value; public Block Body { get { return Children.Count > 0 ? Children.First() as Block : null; } } }
To simplify the implementation, Block is used as the execution part of case. The side effects are a little more, slightly affecting efficiency.
Let's look at the switch implementation:
public class Switch : ControlFlow { private Dictionary<int, int> m_caseDict; public Expression.ExpressionNode Condition; public Block Body { get { return Children.Count > 0 ? Children.First() as Block : null; } } public Case Default { get { return Body != null ? Body.Children.Last() as Case : null; } } public List<Context> CaseSet { get { return Body != null ? Body.Children.Count > 1 ? Body.Children.GetRange(0, Body.Children.Count - 1) : null : null; } }
The switch execution is also a block. At the same time, Default is the last Case.
Let's look at the switch Execution Section:
public override void Run(Context ctx) { Debug.WriteLine("Begin Switch."); bool needBreak = false; if (IsFirstRunning) { m_caseDict = new Dictionary<int, int>(); int idx = 0; Body.OnReturn += delegate(Context stx, Return ret) { Debug.WriteLine("Return"); needBreak = true; Block parentBlock = this.ParentBlock; if (parentBlock != null && parentBlock.OnReturn != null) parentBlock.OnReturn(stx, ret); }; Body.OnBreak = delegate(Context stx) { Debug.WriteLine("Break."); needBreak = true; }; foreach (Context item in CaseSet) { Case stxCase = item as Case; m_caseDict.Add(stxCase.Value.AsInt, idx++); stxCase.Body.OnBreak += Body.OnBreak; } IsFirstRunning = false; } Expression.Operand.Value val = Condition.Evaluate(this).GetValue(ctx); Debug.WriteLine(string.Format("Condition: [{0}] = {1}", Condition, val)); if (m_caseDict.ContainsKey(val.AsInt)) { int idx = m_caseDict[val.AsInt]; IEnumerator<Context> caseEnum = CaseSet.GetEnumerator(); int i = 0; while (caseEnum.MoveNext()) { if (i++ < idx) continue; Debug.WriteLine(string.Format("case {0}", (caseEnum.Current as Case).Value.AsInt)); (caseEnum.Current as Case).Body.Run(this); if (needBreak) break; } // while } else { Debug.WriteLine("Default"); Default.Run(this); } }
Create a case dictionary for the first execution, and hope to speed up the next operation. Then, run the case that matches the expression, start from the case, and run the next case in sequence until it runs until it reaches break.