免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3701 | 回复: 3
打印 上一主题 下一主题

编译器学习笔记03(开始理解 antlr )——2014_3_19 [复制链接]

论坛徽章:
0
1 [报告]
发表于 2014-03-20 15:40 |只看该作者
****************************
开始理解 怎样 写 语法grammar

***************************


在看这里时,突然找到最合适的一副图片 来 描述 这本书的特点。



上面这张图 是 很多语文老师 心目中 的经典。

在初学者看来,作者 说话 东扯西拉,好听点 天马行空,我行我素;难听点 没有主题,更没有中心思想。

****************************

语法 感觉就是 看定义,有点像 从 金字塔 尖 向下 找定义,

作者的例子如下,



然后,就利用上面 的思路,写伪代码,

file : «sequence of rows that are terminated by newlines» ;

row : «sequence of fields separated by commas» ;

field : «number or string» ;



然后,作者又开始东扯,不说了。总之,又挖了一个坑,就像美剧一样。

我现在联想事情 都开始往 美剧 上扯了,因为



CSV 文件 语法 就讲成 这样了? 是的。
   

论坛徽章:
0
2 [报告]
发表于 2014-03-21 13:35 |只看该作者
*************************
追逐 CSV

*************************


作者在第五章 只是 随口 CSV,然后不完整。然后,



作者在第六章又开始 讲 CSV,这次不能放过,

要解析的文件
Details,Month,Amount
Mid Bonus,June,"$2,000"
,January,"""zippo"""
Total Bonuses,"","$5,000"

语法如下,



这里面就要开始理解了,

Note that we’ve introduced an extra rule called hdr for clarity. Grammatically it’s just a row, but we’ve made its role clearer by separating it out.

Compare this to using just row+ or row row* on the right-side rule file.

file 本来可以定义为 file : row row+; 但是 作者 定义 为 file: hdr row+; 然后再 定义 hdr: row;

不清楚,可能要实际操作一把,看看效果。

'\r'? '\n'  可以看做 固定格式,表示 新的一行,
下面的用法非常多,
NEWLINE:'\r'? '\n' ; // return newlines to parser (is end-statement signal)

语法规矩 就是 file hdr row filed

剩下两个 TEXT STRING 是词法规则。

TEXT tokens are a sequence of characters until we hit the next comma field separator or the end of the line.   

TEXT : ~[,\n\r"]+ ; 这个词法规则基本可以认定不变

Strings are any characters in between double quotes.

STRING : '"' ('""'|~'"')* '"' ; // quote-quote is an escaped quote

格式比较麻烦,作者是这样解释的,To get a double quote inside a double-quoted string, the CSV format generally
uses two double quotes in a row. That’s what the ('""'|~'"')* subrule does in rule STRING.

***************************************

把语法文件修改如下,



运行结果 和 用 hdr 的一样,感觉比用hdr还简单易懂,不理解这里用hdr,作者到底想说明什么?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP