什么是评估IF条件的最有效方法?

时间:2014-08-08 13:31:11

标签: c++ if-statement interpreter evaluation evaluate

我正在制作语言翻译,而且我已经达到了我需要评估if语句的程度。起初我认为这很简单,我能够让我的解释器在这样的条件下评估简单,10 == 10但是当我试图让它评估一个更复杂的条件时,10 == 10 and 9 > 2例如,它搞砸了。

我制作了一些代码C ++代码,可以单独评估条件的每个部分,例如。

"Hello World" == "Hello World" or "Test" == "Test"

它目前的工作原理如下,它给出了上面的实际结果和下面的预期结果。结果如下:

TRUE or TRUE           <- Actual
-----------------------
TRUE or TRUE           <- Expected
-----------------------

以下是代码:

#include <iostream>
#include <string>
#include <vector>    
#include "cond.h"

using namespace std;

vector <string> cond_holder;
vector <string> res;
vector <string> expects;

bool eval_cond(string cond) {
    int i;
    int i2;
    bool state = 0;
    bool final_return = false;
    string c = "";

    for (i = 0; i < cond.length();i++) {
        c += cond[i];

        if (cond[i] == '"') {
            if (state == 0)
                state = 1;
            else
                state = 0;
        } else if (cond[i] == ' ' && state == 0) {
            c = c.substr(0,c.length()-1);
            cond_holder.push_back(c);
            c = "";

        }
        if (i == cond.length()-1) {
            cout << c << endl;      
        }

    }
    for (i = 0; i < cond_holder.size();i++) {
        if (cond_holder[i+1] == "eqeq") {
            expects.push_back("TRUE");
            if (cond_holder[i] == cond_holder[i+2]) {
                res.push_back("TRUE");
            } else {
                res.push_back("FALSE");
            }
            i+=3;
        }
        if (cond_holder[i] == "and") {
            res.push_back("and");
            expects.push_back("and");
        } else if (cond_holder[i] == "or") {
            res.push_back("or");
            expects.push_back("or");
        }
    }

    for (i = 0; i < res.size();i++) {
        cout << res[i] << " ";
    }
    cout << endl << "-----------------------" << endl;

    for (i = 0; i < expects.size();i++) {
        cout << expects[i] << " ";
    }
    cout << endl << "-----------------------" << endl;

    return final_return;
}

int main() {
    cout << eval_cond("string:\"Hello World\" eqeq string:\"Hello World\" or string:\"H\" eqeq string:\"H\" ") << endl;
    return 0;
}

老实说,我刚刚开始编写代码,所以如果有人能告诉我一个更好的方法,我会感激不尽。我甚至不确定下一步该如何使用此代码。

1 个答案:

答案 0 :(得分:2)

Variable is an expression
Number is an expression
String is an expression
Expression == Expression is an expression
Expression AND Expression is an expression
Expression ; is a statement
IF Expression { statement } is a statement

用这样的位来构建你的语言,让它们一起崩溃。 Flex和Yacc的旧unix手册是对该主题的一个很好的介绍。

相关问题