2

我正在继续学习 PEG.js,但停留在下一个问题上。

PEG.js 生成的解析器无法匹配包含下划线的字符串:

CONFIG += stl_off

但在没有它们的情况下成功解析了字符串:

CONFIG += static

(这是一个内置变量CONFIG“附加赋值”语句,rvalue是一组有限字符串的列表)

我究竟做错了什么?


语法:

Start =
    Statement* {return env; }

Statement
    = Comment
    / GenericAssignmentStatementT

GenericAssignmentStatementT = Whitespace* GenericAssignmentStatement Whitespace*
GenericAssignmentStatement
    // TEMPLATE
    = TemplateAssignmentStatement
    // CONFIG
    / ConfigAssignmentStatement
    / ConfigAppendingAssignmentStatement

// -------------------------------------------------------------------------------------------------

// # Single-line comment
Comment "Comment string" = Whitespace* "#" rvalue:$(!LineBreak .)* LineBreak+ {
    return "#" + rvalue;
}

// -------------------------------------------------------------------------------------------------

// TEMPLATE = app|lib|subdirs|aux|vcapp|vclib
SystemTemplateVariable = "TEMPLATE"
SystemTemplateVariableValue = "app" / "lib" / "subdirs" / "aux" / "vcapp" / "vclib"
TemplateAssignmentStatement = lvalue:SystemTemplateVariable AssignmentOperator rvalue:SystemTemplateVariableValue Whitespace* LineBreak* {
    if (!env.qmakeVars)
        env.qmakeVars = {};
    env.qmakeVars[lvalue] = rvalue;
    return {name:"TEMPLATE", op:"=", value:rvalue};
}

// -------------------------------------------------------------------------------------------------

// CONFIG = release|debug|debug_and_release|debug_and_release_target
SystemConfigVariable = "CONFIG"
SystemConfigVariableValue = "release" / "debug" / "debug_and_release" / "debug_and_release_target"

ConfigAssignmentStatement = lvalue:SystemConfigVariable AssignmentOperator rvalue:SystemConfigVariableValue? Whitespace* LineBreak* {
    if (!env.qmakeVars)
        env.qmakeVars = {};
    env.qmakeVars[lvalue] = [rvalue];
    return {name:"CONFIG", op:"=", value:rvalue};
 }

 ConfigAppendingAssignmentStatement = lvalue:SystemConfigVariable 
 AppendingAssignmentOperator rvalue:SystemConfigVariableValue Whitespace* LineBreak* {
    if (!env.qmakeVars)
        env.qmakeVars = {};
    if (!env.qmakeVars[lvalue])
        env.qmakeVars[lvalue] = [];
    env.qmakeVars[lvalue].push(rvalue);
    return {name:"CONFIG", op:"+=", value:rvalue};
}

// Assignment operators
AssignmentOperator = Whitespace* "=" Whitespace*
AppendingAssignmentOperator = Whitespace* "+=" Whitespace*

// Delimeters
LineBreak = [\r\n] {
    return "LB";
}

Whitespace = [ \t] {
    return "WS";
}

测试输入:

TEMPLATE = app
CONFIG += debug_and_release

测试 PEG.js 输出:

Line 2, column 16: Expected "CONFIG", "TEMPLATE", Comment string, [ \t], [\r\n], or end of input but "_" found.
4

1 回答 1

1

PEGSystemConfigVariableValue从左到右进行计算,因此debug_and_release实际上会与release文字匹配(之后解析器会感到困惑)。

如果您首先声明更具体的文字,它将起作用:

SystemConfigVariableValue = "debug_and_release_target" / "debug_and_release" / "release" / "debug"
于 2017-05-28T19:28:25.600 回答