public override int Compile(FunctionContext context) { context.Line(FileName, Line); var stack = 0; var start = context.MakeLabel("forStart"); var increment = context.MakeLabel("forContinue"); var end = context.MakeLabel("forEnd"); context.PushScope(); if (Initializer != null) { stack += Initializer.Compile(context); } context.Bind(start); if (Condition != null) { stack += Condition.Compile(context); stack += context.JumpFalse(end); } context.PushLoop(increment, end); stack += Block.Compile(context); context.PopLoop(); stack += context.Bind(increment); if (Increment != null) { stack += Increment.Compile(context); } stack += context.Jump(start); stack += context.Bind(end); context.PopScope(); CheckStack(stack, 0); return(stack); }
public override int Compile(FunctionContext context) { context.Position(Token); var stack = 0; var start = context.MakeLabel("forStart"); var increment = context.MakeLabel("forContinue"); var brk = context.MakeLabel("forBreak"); var end = context.MakeLabel("forEnd"); var containsFunction = new LoopContainsFunctionVisitor(); Block.Accept(containsFunction); context.PushScope(); if (Initializer != null) { var hasCode = true; if (Initializer.Statements.Count > 0) { if (Initializer.Statements[0] is VarExpression initializerVar && initializerVar.Declarations.All(d => d.Initializer == null)) { hasCode = false; } } if (hasCode) { context.Statement(Initializer); } stack += Initializer.Compile(context); } // loop body context.Bind(start); if (Condition != null) { context.Statement(Condition); stack += Condition.Compile(context); stack += context.JumpFalse(end); } var loopContext = containsFunction.Value ? new LoopContext(context) : context; loopContext.PushLoop(increment, containsFunction.Value ? brk : end); if (containsFunction.Value) { stack += loopContext.Enter(); } stack += Block.Compile(loopContext); stack += context.Bind(increment); // continue if (containsFunction.Value) { stack += loopContext.Leave(); } loopContext.PopLoop(); if (Increment != null) { context.Statement(Increment); stack += Increment.Compile(context); } stack += context.Jump(start); if (containsFunction.Value) { stack += context.Bind(brk); // break (with function) stack += context.Leave(); } stack += context.Bind(end); // break (without function) context.PopScope(); CheckStack(stack, 0); return(stack); }