c - 如何在解析过程中获取光标位置?
问题描述
我为 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
问题是光标值始终位于文件末尾,无论数字位置如何。
解决方案
可以通过特殊变量检索位置。在上面的示例中,“ftell”必须替换为“$0s”或“$0e”。$0s 是匹配模式的开始,$0e 是匹配模式的结束。
推荐阅读
- java - 如何从图的广度优先搜索中获取路径中的所有节点
- java - 从 InputStream 读取 NullPointerException
- android - SimpleDateFormat 解析日期正确模式
- java - CrudRepository - 按日期删除
- android - 从相机捕获流并在 Android 上使用 Ionic 将其放在画布上
- scala - scala:用结构归纳证明两个函数
- javascript - 将包含十进制代码的字符串转换为纯字符串
- tsql - T-SQL 两个计数与不同的 where 子句
- android - 什么对battery_changed 更好?广播接收器,或服务,或意图服务?
- docker - lagom 配置覆盖