yacc无法解析simpe shell语法

时间:2017-08-15 16:55:20

标签: bison yacc lex bnf

我正在使用yacc / lex为shell编写一个简单的语法。我希望我的语法识别管道,其形式如下: command1 | command2 | ... | commandn。我可以使用the simple_command规则作为下面代码中的起始非终端来重新命名单个命令。但是,当我添加其他规则(simple_command_listpipeline)来解析管道时,事情不起作用。为了测试语法,我从以下字符串中读取yacc: char *input = "command1 | command2 | command3 | command4\n\0",在main函数中定义。当被要求解析这个字符串时,yacc只解析第一个命令,打印"解析错误",并停止,就像这样:

command "command1"
simple command 
1B
parse error

LEX CODE:

%{ 

#include <string.h> 
#include "y.tab.h" 

%} 

%%


\n      { 
                return NEWLINE; 

        } 

[ \t]   { 
                /* Discard spaces and tabs */ 
        } 

">"     { 
                return GREAT; 
        } 

"<"     { 
                return LESS; 
        } 



“|”    { 
                return PIPE; 
        } 

“&”    { 
                return AMPERSAND; 
        } 


[a-zA-Z][a-zA-Z0-9]*  { 
                /* Assume that file names have only alpha chars */ 
                yylval.str = strdup(yytext); 
                return WORD; 
        } 



.       { 
                /* Invalid character in input */ 
                return BAD_TOKEN;
         }

%%
int yywrap(void) {
return 1;
}

YACC代码:

%{
#include <string.h>
#include <stdio.h>
int yylex(void);

void yyerror(char *);


%}

%union
{

    char *str;
    int i;

}

%token <i> AMPERSAND GREAT LESS PIPE NEWLINE BAD_TOKEN
%token <str> WORD
%start pipeline
%expect 1


%%

cmd:
    WORD
    {
        printf("command \"%s\"\n", $1);

    }
;

arg:
    WORD
    {

         printf("argument \"%s\"\n", $1);
    }

;

arg_list:
    arg_list arg
    {

        //printf(" argument list: \n");
    }
    | // empty


;

simple_command:
    cmd arg_list
    {

         printf("simple command \n");
    }

;

simple_command_list:
         simple_command_list PIPE simple_command
        {
            printf("1A\n");
        }
        | simple_command
        {
            printf("1B\n");
        }
;

pipeline:
    simple_command_list NEWLINE
    {

    printf("p-A\n");
    }
    | NEWLINE
    {
        printf("p-B\n");
    }
    ;


%%


void yyerror(char *s) {
    fprintf(stderr, "%s\n", s);
}


int main(void) {
    // read input from a string
    //YY_BUFFER_STATE *bp;
    struct yy_buffer_state *bp;

    char *input = "command1 | command2 | command3 | command4\n\0";

    //  connect input buffer to specified string
    bp = yy_scan_string(input);

    // read from the buffer
    yy_switch_to_buffer(bp);


    // parse 
    yyparse();

    // delete the buffer
    yy_delete_buffer(bp);

    // delete the string (or not)


    return 0;
}

1 个答案:

答案 0 :(得分:0)

你的lex源文件包含unicode字符,如(U-201C LEFT DOUBLE QUOTATION MARK)和(U-201D RIGHT DOUBLE QUOTATION MARK),lex不会重新报告为引号,所以正在寻找包含7字节utf-8序列的输入序列,而不是单个字节|

用Ascii "字符替换它们,它应该有效。

如果您使用--debug选项启用调试bison,您应该会看到它获取的令牌以及它正在转移和减少的规则。在您的情况下,为BAD_TOKEN ...

获取|
相关问题