> compile NEMU

221220000 张三
Linux zzy 5.15.146.1-microsoft-standard-WSL2 #1 SMP Thu Jan 11 04:09:03 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux
 18:27:21 up 17:17,  1 user,  load average: 0.29, 0.27, 0.20
This commit is contained in:
tracer-ics2023
2024-08-31 18:27:21 +08:00
committed by zzy
parent 44b8d8ea6d
commit d620e2b679

View File

@ -160,9 +160,21 @@ int check_parentheses(const Token* arr, size_t p, size_t q) {
return !is_surrounded;
}
word_t eval(const Token* arr, size_t p, size_t q, bool* success) {
Assert (p >= 0 && q < nr_token, "invalid range on eval, "\
"p = %"PRIuMAX", q = %"PRIuMAX"\n", p, q);
int get_level(int type) {
switch (type) {
case '+':
case '-': return 1;
case '*':
case '/': return 2;
case TK_NEG: return 8;
case '(': return 9;
default: return 0;
}
}
word_t eval(const Token* arr, int p, int q, bool* success) {
Assert (p >= 0 && q < nr_token && p >= 0 && q >= 0, "invalid range on eval, "\
"p = %d, q = %d\n", p, q);
int parten = check_parentheses(arr, p, q);
if (parten == -1 || p > q) {
@ -185,14 +197,11 @@ word_t eval(const Token* arr, size_t p, size_t q, bool* success) {
return atoi(arr[q].str);
}
/* We should do more things here. */
size_t op = 0;
int op = 0;
int in_parentheses = 0;
int op_type_level = 999;
if (arr[p].type == '-') {
return - eval(arr, p + 1, q, success);
}
for (size_t i = p; i <= q; i ++) {
for (int i = p; i <= q; i ++) {
if (arr[i].type == '(') {
in_parentheses ++;
}
@ -202,30 +211,31 @@ word_t eval(const Token* arr, size_t p, size_t q, bool* success) {
if (in_parentheses != 0) {
continue;
}
if (arr[i].type == '+' || arr[i].type == '-') {
int type = arr[i].type;
int type_level = get_level(type);
if (type_level <= op_type_level) {
op = i;
} else if (arr[i].type == '*' || arr[i].type == '/') {
op = i;
}
if (i + 1 <= q && arr[i + 1].type == '-') {
i++;
op_type_level = type_level;
}
}
word_t val1 = eval(arr, p, op - 1, success);
word_t val2 = eval(arr, op + 1, q, success);
if (success == false) {
return 0;
uint32_t val_l = 0;
uint32_t val_r = 0;
if (op != p) {
val_l = eval(arr, p, op - 1, success);
}
if (op != q) {
val_r = eval(arr, op + 1, q, success);
}
switch (arr[op].type) {
case '+': return val1 + val2;
case '-': return val1 - val2;
case '*': return val1 * val2;
case '/': return val1 / val2;
default:
*success &= false;
return 0;
case TK_NEG: return - val_r;
case '+': return val_l + val_r;
case '-': return val_l - val_r;
case '*': return val_l * val_r;
case '/': return val_l / val_r;
default: *success &= false; return 0;
}
}
@ -238,5 +248,17 @@ word_t expr(char *e, bool *success) {
/* TODO: Insert codes to evaluate the expression. */
// TODO();
*success = true;
for (int i = 0; i < nr_token; i ++) {
int type = tokens[i].type;
if (type == '-' && (i == 0 || \
type == '(' || \
type == '+' || \
type == '-' || \
type == '*' || \
type == '/' || \
type == TK_NEG)) {
tokens[i].type = TK_NEG;
}
}
return eval(tokens, 0, nr_token - 1, success);
}