private static EvalValue CalcWhile(IEnvironment env, AstWhile ast) { // 返回值为最后一条语句或表达式的值 var ret = new EvalValue(); while (true) { var cond = ast.condition.Eval(env); if (cond.type == EvalValueType.INT && cond.intVal > 0) { // 当条件满足时执行代码块中的每一条子语句 foreach (var item in ast) { ret = item.Eval(env); } } else if (cond.type == EvalValueType.STRING) { throw new RunTimeException("条件表达式不能为字符串", ast.condition); } else { break; } } return(ret); }
static AstNode RemoveUnreachableCode(AstWhile whileStatement) { if (TypeConverter.ToBoolean(whileStatement.Condition.ConstValue() ?? AstTrue.Instance)) { return(whileStatement); } var declarations = GetDeclarations(whileStatement.Body); return(declarations ?? Remove); }
/// <summary> /// 解析语句state /// </summary> /// <returns></returns> private AstStatement DoStatement() { // state ::== <while><expr><do>{<expr>|<state>}<end>';' // | <if><expr><do>{<expr>|<state>}<end>';' // | <return><expr>';' if (Is("while", TokenType.KEYWORD)) { // while语句 Pass("while", TokenType.KEYWORD); AstExpression condition = DoExpression(); Pass("do", TokenType.KEYWORD); List <AstNode> list = DoBlock(); Pass("end", TokenType.KEYWORD); Pass(";", TokenType.SEPERATOR); var ret = new AstWhile(list, condition); Utils.LogDebug("[P] while语句: {0}", ret.ToString()); return(ret); } if (Is("if", TokenType.KEYWORD)) { // if语句 Pass("if", TokenType.KEYWORD); AstExpression condition = DoExpression(); Pass("do", TokenType.KEYWORD); List <AstNode> list = DoBlock(); List <AstNode> elseList = null; if (Is("else", TokenType.KEYWORD)) { // 有else块 Pass("else", TokenType.KEYWORD); elseList = DoBlock(); } Pass("end", TokenType.KEYWORD); Pass(";", TokenType.SEPERATOR); var ret = new AstIf(list, condition, elseList); Utils.LogDebug("[P] if语句: {0}", ret.ToString()); return(ret); } if (Is("return", TokenType.KEYWORD)) { // return语句 Pass("return", TokenType.KEYWORD); AstExpression expr = DoExpression(); var ret = new AstReturn(new List <AstNode>(), expr); Utils.LogDebug("[P] return语句: {0}", ret.ToString()); return(ret); } throw new ParseException(m_scanner.Peek(0), "未知语句"); }
private void CompileWhile(AstWhile node, Syt syt, StringBuilder sb) { var lblWhile = Id("WHILE"); var lblTrue = Id("WHILE_TRUE"); var lblEnd = Id("WHILE_END"); sb.AppendLine("label " + lblWhile); CompileRecursive(node.exprCond, syt, sb); sb.AppendLine("if-goto " + lblTrue); sb.AppendLine("goto " + lblEnd); sb.AppendLine("label " + lblTrue); CompileRecursive(node.rgstm, syt, sb); sb.AppendLine("goto " + lblWhile); sb.AppendLine("label " + lblEnd); }