Skip to content

对标准bnf-file的parse #2

Description

@acodercc

要把bnf解析为jsbison能使用的json格式的上下文无关文法。。

如:

%start expr
%%
expr
    : expr '+' term
        {
            this.$$ = $1 + $2;
        }
    | term
        {
            this.$$ = $1;
        }
    ;

term
    : term '*' factoy
        {
            this.$$ = $1 * $2;
        }
    | factoy
        {
            this.$$ = $1;
        }
    ;

factoy
    : NUMBER
        {
            this.$$ = parseInt($1, 10);
        }
    |   '(' expr ')'
        {
            this.$$ = $2;
        }
    ;

转换为:

{
        tokens: '+ * ( ) NUMBER',
        start: 'expr',
        bnf: {
            'expr': {
                'expr + term': 'this.$$ = $1 + $3',
                'term': 'this.$$ = $1'
            },
            'term': {
                'term * factor': 'this.$$ = $1 * $3',
                'factor': 'this.$$ = $1'
            },
            'factor': {
                'NUMBER': 'this.$$ = parseInt($1, 10)',
                '( expr )': 'this.$$ = $2'
            }
        }
}

jsbison的bnf2cfg,所能解析的bnf文件中支持的功能:

功能 完成度
声明token: %token ok
声明结合性与优先级 %left %right %nonassoc ok
声明开始符号: %start ok
未声明开始符号时,自动使用首个定义的产生式的lhs为开始符号 不支持,必须定义%start
应用产生式归约为非终结符时的语义动作 ok
语义动作中引用各符号值 $1 $2 $n ok
语义动作中定义归约后的非终结符的值 this.$$ ok

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions