首页 > 解决方案 > 如何在解析过程中获取光标位置?

问题描述

我为 Packcc 解析器生成器做了一个最小的例子。在这里,解析器必须识别浮点数或整数。我尝试打印检测到的数字的位置。为简单起见,没有行数/列数,只有“ftell”中的数字。

%auxil "FILE*" # The type sent to "pcc_create" for access in "ftell".

test <- line+
        /
        _ EOL+

line <- num _ EOL

num <-  [0-9]+'.'[0-9]+     {printf("Float at %li\n", ftell(auxil));}
        /
        [0-9]+              {printf("Integer at %li\n", ftell(auxil));}

_ <- [ \t]*

EOL <- '\n' / '\r\n' / '\r'

%%

int main()
{
    FILE* file = fopen("test.txt", "r");
    stdin = file;
    if(file == NULL) {
    // try to open.
        puts("File not found");
    }
    else {
    //  parse.
        pcc_context_t *ctx = pcc_create(file);
        while(pcc_parse(ctx, NULL));
        pcc_destroy(ctx);
    }
    return 0;
}

要解析的文件可以是

2.0
42

命令可以是

packcc test.peg && cc test.c && ./a.out

问题是光标值始终位于文件末尾,无论数字位置如何。

标签: cparsingpackcc

解决方案


可以通过特殊变量检索位置。在上面的示例中,“ftell”必须替换为“$0s”或“$0e”。$0s 是匹配模式的开始,$0e 是匹配模式的结束。

https://github.com/arithy/packcc/blob/master/README.md


推荐阅读