acodercc / jcon

A JavaScript parser combinator Library
MIT License
3 stars 3 forks source link

jcon对expr的解析如 1+2*3+4/5 #11

Open acodercc opened 9 years ago

acodercc commented 9 years ago
    var jcon = require('jcon');
    var epsilon = jcon.string('');
    var num = jcon.regex(/\d+/).setAst('num');
    var sum_operator = jcon.regex(/[\+\-]/).setAst('operator');
    var product_operator = jcon.regex(/[\*\/]/).setAst('operator');
    var skips = jcon.regex(/\s*/).skip();
    var product = jcon.lazy(function(){
        return jcon.or(
            num,
            jcon.seq(num, product_rest)
        );
    }).setAst('product');
    var product_rest = jcon.or(epsilon, jcon.seq(skips, product_operator, skips, product));

    var sum = jcon.lazy(function(){
        return jcon.or(product,
            jcon.seq(product, sum_rest)
        );
    }).setAst('sum');
    var sum_rest = jcon.or(epsilon, jcon.seq(skips, sum_operator, skips, sum));

    var s = sum.parse('1+2*3+4/5').ast();
    console.log(JSON.stringify(s, null, '  '));
acodercc commented 9 years ago

sum和product的ast设置错误,应该设置在seq rest的节点上,lazy只是为了在rest定义前使用rest定义sum或product