| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MoonSharp.Interpreter.Execution;
- using MoonSharp.Interpreter.Execution.VM;
- using MoonSharp.Interpreter.Grammar;
- using MoonSharp.Interpreter.Tree.Expressions;
- namespace MoonSharp.Interpreter.Tree.Statements
- {
- class ForLoopStatement : Statement
- {
- //for' NAME '=' exp ',' exp (',' exp)? 'do' block 'end'
- RuntimeScopeFrame m_StackFrame;
- Statement m_InnerBlock;
- LRef m_VarName;
- Expression m_Start, m_End, m_Step;
- public ForLoopStatement(LuaParser.Stat_forloopContext context, ScriptLoadingContext lcontext)
- : base(context, lcontext)
- {
- var exps = context.exp();
- m_Start = NodeFactory.CreateExpression(exps[0], lcontext);
- m_End = NodeFactory.CreateExpression(exps[1], lcontext);
- if (exps.Length > 2)
- m_Step = NodeFactory.CreateExpression(exps[2], lcontext);
- else
- m_Step = new LiteralExpression(context, lcontext, new RValue(1));
- lcontext.Scope.PushBlock();
- m_VarName = lcontext.Scope.DefineLocal(context.NAME().GetText());
- m_InnerBlock = NodeFactory.CreateStatement(context.block(), lcontext);
- m_StackFrame = lcontext.Scope.Pop();
- }
- public override void Compile(Chunk bc)
- {
- Loop L = new Loop()
- {
- Scope = m_StackFrame
- };
- bc.LoopTracker.Loops.Push(L);
- m_End.Compile(bc);
- bc.ToNum();
- m_Step.Compile(bc);
- bc.ToNum();
- m_Start.Compile(bc);
- bc.ToNum();
- int start = bc.GetJumpPointForNextInstruction();
- var jumpend = bc.Jump(OpCode.JFor, -1);
- bc.Enter(m_StackFrame);
- bc.SymStorN(m_VarName);
- m_InnerBlock.Compile(bc);
- bc.Debug("..end");
- bc.Leave(m_StackFrame);
- bc.Incr(1);
- bc.Jump(OpCode.Jump, start);
- int exitpoint = bc.GetJumpPointForNextInstruction();
- foreach (Instruction i in L.BreakJumps)
- i.NumVal = exitpoint;
- jumpend.NumVal = exitpoint;
- bc.Pop(3);
- }
- }
- }
|