diff --git a/nemu/src/monitor/debug/expr.cc b/nemu/src/monitor/debug/expr.cc index 4a09ceb6ac04315eba7dff07c79ed71bfa328c1c..9d428270e2643f7f1c9f01c56f9156da22d5ea33 100644 --- a/nemu/src/monitor/debug/expr.cc +++ b/nemu/src/monitor/debug/expr.cc @@ -105,7 +105,6 @@ uint32_t expr(char *e, bool *success) { return 0; } - /* TODO: Insert codes to evaluate the expression. */ try { auto res = parse_one(std::string(e)); *success = true; diff --git a/nemu/tools/gen-expr/Makefile b/nemu/tools/gen-expr/Makefile index 2da6083c60527fb21ab4474f212818be20c5ed59..28955a617e48bf6e276f83388df769edff58cf0b 100644 --- a/nemu/tools/gen-expr/Makefile +++ b/nemu/tools/gen-expr/Makefile @@ -1,7 +1,7 @@ APP=gen-expr -$(APP): gen-expr.c - gcc -O2 -Wall -Werror -o $@ $< +$(APP): gen-expr.cc + g++ -O2 -Wall -o $@ $< -g .PHONY: clean clean: diff --git a/nemu/tools/gen-expr/gen-expr.cc b/nemu/tools/gen-expr/gen-expr.cc index 1ac1592e0061dd1e3be0b8794021d28fd3999b0d..d72f3d27143c68e4e8a2278040dd787bf5091ca6 100644 --- a/nemu/tools/gen-expr/gen-expr.cc +++ b/nemu/tools/gen-expr/gen-expr.cc @@ -5,14 +5,45 @@ #include <assert.h> #include <string.h> +#include <string> +#include <array> +#include <random> +#include <chrono> + +static std::mt19937 rand_generator(std::chrono::system_clock::now().time_since_epoch().count()); + +#define RANDFLOAT ((float)(rand_generator() % (1<<30)) / (float)(1<<30)) +static std::string do_gen_rand_expr(int depth) { + if(depth > 64) { + return std::to_string(rand() % 100); + } + if(RANDFLOAT < 0.4) { + auto op = std::array<std::string, 16> {"+", "-", "*", "==", "!=", "&&"} [rand() % 6]; + return do_gen_rand_expr(depth+1) + op + do_gen_rand_expr(depth+1); + } + if(RANDFLOAT < 0.4) { + return "(" + do_gen_rand_expr(depth+1) + ")"; + } + if(RANDFLOAT < 0.2) { + auto tmp = do_gen_rand_expr(depth+1); + if(tmp[0] != '-') tmp = '-' + tmp; + return tmp; + } + return std::to_string(rand() % 10000); +} +#undef RANDFLOAT + // this should be enough static char buf[65536]; static inline void gen_rand_expr() { - buf[0] = '\0'; + auto res = do_gen_rand_expr(0); + while(res.size() > 512 || res.size() < 16) + res = do_gen_rand_expr(0); + strcpy(buf, res.c_str()); } static char code_buf[65536]; -static char *code_format = +static const char *code_format = "#include <stdio.h>\n" "int main() { " " unsigned result = %s; " @@ -21,8 +52,6 @@ static char *code_format = "}"; int main(int argc, char *argv[]) { - int seed = time(0); - srand(seed); int loop = 1; if (argc > 1) { sscanf(argv[1], "%d", &loop); @@ -38,6 +67,7 @@ int main(int argc, char *argv[]) { fputs(code_buf, fp); fclose(fp); + // One test one compile: extremely slow, unusable. int ret = system("gcc .code.c -o .expr"); if (ret != 0) continue;