c - 如何将 GNU readline 与 flex-lexer 一起使用?

标签 c readline flex-lexer lemon

我认为将 GNU Readline 库用于命令行提示很好,我希望我正在使用的 shell 具有该功能。现在 readline 对我有用(我的环境是 CLion、CMake、Ubuntu、BSD、C、flex-lexer 和 lemon-parser),但我还需要 flex 和 yacc 同时工作来扫描和解析输入,但代码似乎“不相容”——真的吗?

    params[0] = NULL;
   printf("> ");

    i=1;
    do {
        lexCode = yylex(scanner);

        /*  snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
         Display prompt and read input (NB: input must be freed after use)...*/



        text = strdup(yyget_text(scanner));
        /*
        input = readline(text);

        if (!input)
            break;

        add_history(input);

        free(input);*/
        printf("lexcode %i Text %s\n", lexCode, text);
        if (lexCode == 4) {
            params[i++] = mystring;
            if (strcmp(text, "\'\0")) {
                params[i++] = mystring;
            }
        } else
        if (lexCode != EOL) {
                params[i++] = text;
                printf("B%s\n", text);
        }
        Parse(shellParser, lexCode, text);
        if (lexCode == EOL) {
            dump_argv("Before exec_arguments", i, params);
            exec_arguments(i, params);
            corpse_collector();
            Parse(shellParser, 0, NULL);
            i=1;
        }
    } while (lexCode > 0);
    if (-1 == lexCode) {
        fprintf(stderr, "The scanner encountered an error.\n");
    }

上面的代码具有解析和扫描功能,并注释掉了如果我同时需要两者将无法使用的 readline 功能。我能让它发挥作用吗?

最佳答案

flex+readline示例

跟随一个可以lsdate 的快速 flex“shell”

%{
  #include <stdlib.h>
  #include <readline/readline.h>
  #include <readline/history.h>
  #define YY_INPUT(buf,result,max_size) result = mygetinput(buf, max_size);

  static int mygetinput(char *buf, int size) {
    char *line;
    if (feof(yyin))  return YY_NULL;
    line = readline("> ");
    if(!line)        return YY_NULL;
    if(strlen(line) > size-2){
       fprintf(stderr,"input line too long\n"); return YY_NULL; }
    sprintf(buf,"%s\n",line);
    add_history(line);
    free(line);
    return strlen(buf);
  }   
%}

%option noyywrap    
%%
ls.*         system(yytext);
date.*       system(yytext);
.+           fprintf(stderr, "Error: unknown comand\n");
[ \t\n]+     {}
%%

构建它:

flex mysh.fl
cc -o mysh lex.yy.c -lreadline -lfl

关于c - 如何将 GNU readline 与 flex-lexer 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706859/

相关文章:

c - 从 C 中的文件加载数据

python : correct use of set_completion_display_matches_hook

c# - C#中通过串口读取整个字符串

c - 我在第二次输入语言时收到错误

c - 我在函数 `yylex' : lex. yy.c :(. text+0x2ac) 中遇到错误: undefined reference

c 二进制文件大于源文件

检查数组中的空白字符串

c - C 中使用 read() 系统调用读取字符串

C# 一遍又一遍地循环一个过程,直到用户按下一个键

c - 我在 flex/bison 中的所有 token 都显示为未声明