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

标签 c++ if-statement interpreter evaluation evaluate

我正在制作一个语言解释器,我已经到了需要评估 if 语句的地步。起初我认为这很简单,我能够让我的解释器评估简单的 if 条件,10 == 10 但是当我试图让它评估更复杂的条件时, 10 == 10 和 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;
}

但老实说,我只是边做边编代码,所以如果有人能告诉我更好的方法,我将不胜感激。我什至不确定接下来要如何处理这段代码。

最佳答案

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 手册很好地介绍了该主题。

关于c++ - 评估 IF 条件的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25204707/

相关文章:

c++ - 包含来自基于 C 的代码的 C++ header (fstream)?

C++打印从字符串字符派生的整数

java - 在 if 语句中将变量设置为值

scala - 如何通过 Scala REPL 使用第三方库?

jvm - 不要同时启用 JIT 和非 JIT 的解释器最终生成机器代码

c++ - 为Qt添加编译标志以使用mysql

c++ - 带有单元测试的示例 C++ 项目

jquery - SimpleCart JS 根据数量改变购物车的颜色

java - if语句比较java android中的字符串

Python 解释器模式 - 有哪些探索 Python 模块及其用法的方法