1

寻找使用 PegJS 之类的解决方案(对其他建议开放)以递归方式查找和扩展变量。

程序可以将变量设置为其他变量或数字

给定这样的结构:
{$a: '1', $b: '$a + 2', $c: '$b + 10'}

$a 
// looks up $a, expands to 1
$b 
// looks up $b, finds $a + 2, looks up $a and expands to 1 + 2
$c 
// looks up $c, finds $b + 10, looks up $b and finds $a + 2, looks up $a and expands to 1 + 2

完成此任务的最佳方法(工具或其他方式)是什么?

4

1 回答 1

1

这是一个简单的解决方案,可以帮助您入门。在初始化程序中定义obj = {},因为您希望在解析时使对象可用,以便在找到键时缓存它们。

{
    var obj = {};
}

obj =
    "{" _* keyPair* "}"
    {
        return obj;
    }

keyPair =
    key:key ":" _* val:singleQuoted _*
    {
        obj[key] = val;
    }

key =
    $("$" word)

expression =
    key:key _* "+" _* num:num
    {
        return obj[key] + num;
    }

singleQuoted =
    "'" exp:(expression / num) "'" ","?
    {
        return exp;
    }

num =
    num:$([0-9]+)
    {
        return parseInt(num);
    }

word =
    $([A-Za-z]+)

_ =
    " "
于 2018-03-08T15:10:46.703 回答