评估IF条件的最有效方法是什么?
What's the most efficient way to evaluate an IF condition?
我正在做一个语言解释器,我已经到了需要评估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;
}
老实说,我只是在进行过程中编写了代码,所以如果有人能告诉我更好的方法,我将不胜感激。我什至不确定接下来如何处理这段代码。
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手册很好地介绍了这个主题。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- 将此布尔值传递给此函数的最有效方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?