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

Nik*_*ntz 3 c readline lemon flex-lexer

我认为使用 GNU Readline 库作为命令行提示符很好,我希望我正在开发的 shell 也能使用该功能。现在 readline 对我有用(我的环境是 CLion、CMake、Ubuntu、BSD、C、flex-lexer 和柠檬解析器),但我还需要 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");
    }
Run Code Online (Sandbox Code Playgroud)

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

JJo*_*oao 5

flex+readline 示例

遵循快速弯曲的“外壳”,可以ls并且date

%{
  #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]+     {}
%%
Run Code Online (Sandbox Code Playgroud)

构建它:

flex mysh.fl
cc -o mysh lex.yy.c -lreadline -lfl
Run Code Online (Sandbox Code Playgroud)