【问题标题】:How to implement case insensitive lexical parser in Golang using gocc?如何使用 gocc 在 Golang 中实现不区分大小写的词法解析器?
【发布时间】:2020-08-18 22:02:36
【问题描述】:

我需要使用 Gocc 构建一个词法分析器,但是文档中没有提到忽略大小写的选项,我也找不到任何相关内容。任何人都知道如何做到这一点,或者我应该使用其他工具吗?

/* Lexical part */

_digit : '0'-'9' ;

int64 : '1'-'9' {_digit} ;

switch:  's''w''i''t''c''h';

while:  'w''h''i''l''e';

!whitespace : ' ' | '\t' | '\n' | '\r' ;

/* Syntax part */

<< 
import(
    "github.com/goccmack/gocc/example/calc/token"
    "github.com/goccmack/gocc/example/calc/util"
)
>>

Calc : Expr;

Expr :
        Expr "+" Term   << $0.(int64) + $2.(int64), nil >>
    |   Term            
;

Term :
        Term "*" Factor << $0.(int64) * $2.(int64), nil >>
    |   Factor          
;

Factor :
        "(" Expr ")"    << $1, nil >>
    |   int64           << util.IntValue($0.(*token.Token).Lit) >>
;

例如,对于“switch”,我想识别它是大写还是小写,但不必键入所有组合。在 Bison 中有选项 % option caseless,在 Gocc 中有没有?

【问题讨论】:

    标签: go compiler-construction lexer ignore-case


    【解决方案1】:

    查看该产品的文档,我没有看到任何使字符文字不区分大小写的选项,也没有看到任何编写字符类的方法,就像每个正则表达式引擎和扫描仪生成器一样。但除了乏味、可读性和风格之外,没有什么能阻止你写作

    switch:  ('s'|'S')('w'|'W')('i'|'I')('t'|'T')('c'|'C')('h'|'H');
    while:  ('w'|'W')('h'|'H')('i'|'I')('l'|'L')('e'|'E');
    

    (这源自在 lex 中不区分大小写的旧方法,它使用字符类使其更具可读性:

    [sS][wW][iI][tT][cC][hH]    return T_SWITCH;
    [wW][hH][iI][lL][eE]        return T_WHILE;
    

    您可以通过定义 26 种模式来更接近前者:

    _a: 'a'|'A';
    _b: 'b'|'B';
    _c: 'c'|'C';
    _d: 'd'|'D';
    _e: 'e'|'E';
    _f: 'f'|'F';
    _g: 'g'|'G';
    _h: 'h'|'H';
    _i: 'i'|'I';
    _j: 'j'|'J';
    _k: 'k'|'K';
    _l: 'l'|'L';
    _m: 'm'|'M';
    _n: 'n'|'N';
    _o: 'o'|'O';
    _p: 'p'|'P';
    _q: 'q'|'Q';
    _r: 'r'|'R';
    _s: 's'|'S';
    _t: 't'|'T';
    _u: 'u'|'U';
    _v: 'v'|'V';
    _w: 'w'|'W';
    _x: 'x'|'X';
    _y: 'y'|'Y';
    _z: 'z'|'Z';
    

    然后分解字符串文字:

    switch: _s _w _i _t _c _h;
    while: _w _h _i _l _e;
    

    【讨论】:

    • 可惜没有那个选项。非常感谢您的回答,它非常有用。
    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多