我目前正在通过buildyourownlisp工作,到目前为止真的很喜欢它,但我目前遇到了一个奇怪的问题。本书使用多精度 C 库为 Lisp 解释器编写语法。因为我在我的 linux 系统上安装了 devtools,所以我还安装了 mpc 和 libmpc 数据包。但是,当我运行书中的代码时,我遇到了语法问题。这个库中似乎没有mpc_parser_t
,我什至找不到在网上使用的这个。我使用的代码是
/* Create Some Parsers */
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Operator = mpc_new("operator");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Lispy = mpc_new("lispy");
/* Define them with the following Language */
mpca_lang(MPCA_LANG_DEFAULT,
" \
number : /-?[0-9]+/ ; \
operator : '+' | '-' | '*' | '/' ; \
expr : <number> | '(' <operator> <expr>+ ')' ; \
lispy : /^/ <operator> <expr>+ /$/ ; \
",
Number, Operator, Expr, Lispy);
每次使用mpc_parser_t
asmpca_lang
和时,编译器都会向我抛出错误MPCA_LANG_DEFAULT
。这是一个例子:
prompt.c:8:2: error: unknown type name ‘mpc_parser_t’; did you mean ‘mp_prec_t’?
8 | mpc_parser_t* Number = mpc_new("number");
| ^~~~~~~~~~~~
| mp_prec_t
我找不到其他人报告这些问题,但我看不出我做错了什么,感谢任何建议。
编辑:以下是我尝试编译的所有代码,因为 Paul Ogilvie 要求我显示包含文件的位置。
#include <mpc.h>
#ifdef _WIN32
static char buffer[2048];
char* readline(char* prompt) {
fputs(prompt, stdout);
fgets(buffer, 2048, stdin);
char* cpy = malloc(strlen(buffer)+1);
strcpy(cpy, buffer);
cpy[strlen(cpy)-1] = '\0';
return cpy;
}
void add_history(char* unused) {}
#else
#include <editline/readline.h>
#endif
int main(int argc, char** argv) {
/* Create Some Parsers */
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Operator = mpc_new("operator");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Lispy = mpc_new("lispy");
/* Define them with the following Language */
mpca_lang(MPCA_LANG_DEFAULT,
" \
number : /-?[0-9]+/ ; \
operator : '+' | '-' | '*' | '/' ; \
expr : <number> | '(' <operator> <expr>+ ')' ; \
lispy : /^/ <operator> <expr>+ /$/ ; \
",
Number, Operator, Expr, Lispy);
puts("Lispy Version 0.0.0.0.2");
puts("Press Ctrl+c to Exit\n");
while (1) {
char* input = readline("lispy> ");
add_history(input);
/* Attempt to parse the user input */
mpc_result_t r;
if (mpc_parse("<stdin>", input, Lispy, &r)) {
/* On success print and delete the AST */
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
/* Otherwise print and delete the Error */
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
free(input);
}
/* Undefine and delete our parsers */
mpc_cleanup(4, Number, Operator, Expr, Lispy);
return 0;
}