免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
1234
最近访问板块 发新帖
楼主: oldbeginner
打印 上一主题 下一主题

编译器学习笔记02(世界公民antlr)——2014_2_27 [复制链接]

论坛徽章:
0
31 [报告]
发表于 2014-03-10 20:28 |只看该作者
**************************
7.3 Implementing Applications with Visitors

访问
**************************





To use a visitor instead of a listener, we ask ANTLR to generate a visitor
interface, implement that interface, and then create a test rig that calls visit()
on the parse tree. We don’t have to touch the grammar at all.

public class TestPropertyFileVisitor {
    public static class PropertyFileVisitor extends
        PropertyFileBaseVisitor<Void>
    {
        Map<String,String> props = new OrderedHashMap<String, String>();
        public Void visitProp(PropertyFileParser.PropContext ctx) {
            String id = ctx.ID().getText(); // prop : ID '=' STRING '\n' ;
            String value = ctx.STRING().getText();
            props.put(id, value);
            return null; // Java says must return something even when Void
        }
    }

    public static void main(String[] args) throws Exception {
        String inputFile = null;
        if ( args.length>0 ) inputFile = args[0];
        InputStream is = System.in;
        if ( inputFile!=null ) {
            is = new FileInputStream(inputFile);
        }
        ANTLRInputStream input = new ANTLRInputStream(is);
        PropertyFileLexer lexer = new PropertyFileLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        PropertyFileParser parser = new PropertyFileParser(tokens);
        ParseTree tree = parser.file();

        PropertyFileVisitor loader = new PropertyFileVisitor();
        loader.visit(tree);
        System.out.println(loader.props); // print results
    }
}




   

论坛徽章:
0
32 [报告]
发表于 2014-03-11 18:12 |只看该作者
本帖最后由 oldbeginner 于 2014-03-11 18:14 编辑

**********************************
7.4 Labeling Rule Alternatives for Precise Event Methods

大人,你能说清楚点吗?
**********************************





To illustrate the event granularity problem, let’s try to build a simple calculator
with a listener for the following expression grammar:



As it stands, rule e yields a fairly unhelpful listener because all alternatives
of e result in a tree walker triggering the same enterE() and exitE() methods.

看出来了吗,少数 规则e 以权谋私,即 对应 同一个 enterE() 和 exitE() 方法。

public interface ExprListener extends ParseTreeListener {

void enterE(ExprParser.EContext ctx);

void exitE(ExprParser.EContext ctx);
...
}
   

The listener methods would have to test to see which alternative the parser
matched for each e subtree using the op token label and the methods of ctx.

因为少数,剩下的多数就要进行鉴定。

省略是怎样进行鉴定的过程(可以看书)。


然后,作者又提出了一个方法可以改善不清楚表达,从而不用鉴定;看来作者如果在中国当官,一定没有机会爬上去。



To get more precise listener events, ANTLR lets us label the outermost alternatives
of any rule using the # operator.



Now ANTLR generates a separate listener method for each alternative of e.
Consequently, we don’t need the op token label anymore.

作者的方法就是大学老师的土方法,点名。然后没到的学生后面 画个圈圈,然后。。。


For alternative label
X, ANTLR generates enterX() and exitX().

public interface LExprListener extends ParseTreeListener {

void enterMult(LExprParser.MultContext ctx);

void exitMult(LExprParser.MultContext ctx);

void enterAdd(LExprParser.AddContext ctx);

void exitAdd(LExprParser.AddContext ctx);

void enterInt(LExprParser.IntContext ctx);

void exitInt(LExprParser.IntContext ctx);
...
}


Note also that ANTLR generates specific context objects (subclasses of EContext)
for the alternatives, named after the labels.

论坛徽章:
0
33 [报告]
发表于 2014-03-11 19:05 |只看该作者
本帖最后由 oldbeginner 于 2014-03-11 19:46 编辑

******************************
7.5 Sharing Information Among Event Methods

不好意思,我们率先进入了 人工智能 信息时代
******************************




In this section, we’re going to explore mechanisms that let event methods
pass data around without altering the event method signatures.



******************************
Traversing Parse Trees with Visitors
******************************


To build a visitor-based calculator, the easiest approach is to have the event
methods associated with rule expr return subexpression values.





然后,





*********************************
Simulating Return Values with a Stack
*********************************
  

ANTLR generates listener event methods that return no values (void return
types). To return values to listener methods executing on nodes higher in the
parse tree, we can store partial results in a field of our listener.

The idea is to push the result of computing
a subexpression onto the stack. Methods for subexpressions further up the
parse tree pop operands off the stack.





Using a stack field is a bit awkward but works fine. We have to make sure
that the event methods push and pop things in the correct order across listener
events.



******************************
Annotating Parse Trees
*****************************


Instead of using temporary storage to share data between event methods, we
can store those values in the parse tree itself.

The easiest way to annotate parse-tree nodes is to use a Map that associates
arbitrary values with nodes.

得到节点数据的讲解比较多,这里省略。




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

选哪个?

All three are completely decoupled from the grammar itself and nicely
encapsulated in specialized objects. Beyond that, there are advantages and
disadvantages to each.



Visitor methods read nicely because they directly call other visitor methods
to get partial results and can return values like any other method.

The stack-based solution can simulate arguments and return values with a
stack, but there’s a chance of a disconnect when manually managing the
stack.

The annotator is my default solution because it allows me to arbitrarily provide
information to event methods operating on nodes above and below in the
parse tree.

恭喜 annotator 嘉宾,祝贺你 有机会和另一嘉宾 一起在 宝马车里  哭泣,而不是 凯越 福克斯 之流。


112.jpg (14.06 KB, 下载次数: 42)

112.jpg

论坛徽章:
0
34 [报告]
发表于 2014-03-12 20:48 |只看该作者
本帖最后由 oldbeginner 于 2014-03-12 20:51 编辑

********************************
CHAPTER 8
Building Some Real Language Applications

当下,学点实用技能吧

眼看他起高楼,眼看他宴宾客,眼看他楼塌了
********************************








深受崩溃论影响,
中国的僵尸企业正在指数级增长,失控是一瞬间的事情。

深受 成功学大师 Rick 影响,Walter就算了(在中国会被枪毙5分钟的)。


每年3月12日 学习Rick,先从从简单的开始,

************************
8.1 Loading CSV Data

CSV 是非常厉害 爆头 装备,一定要配上
************************




Our goal is to build a listener that loads comma-separated-value (CSV) data
into a nice “list of maps” data structure.




CSV的成分

To get precise methods within our listener, let’s label each of the alternatives
in rule field from the CSV grammar.



需要自己写一个执行文件,LoadCSV.java
作者分成了几个部分来介绍 怎样 写 这个java文件。

感觉,作者 讲解 java 的水平 和 head first java 相比 就是 小学生。

然后,




   

论坛徽章:
0
35 [报告]
发表于 2014-03-12 21:34 |只看该作者
本帖最后由 oldbeginner 于 2014-03-12 21:42 编辑

*************************
8.2 Translating JSON to XML

聊斋之,易容术
*************************



我感觉,易容术 比 windows 还要高级,对社会贡献应该 不相伯仲。

Lots of web services return JSON data, and we might run into a situation
where we want to feed some JSON data into existing code that accepts only
XML.

比方,原来长这样


整整之后,
and emit XML in an equivalent form, like this:



整容过程很简单,不知道要价为什么那么贵?

grammar JSON;

json:   object
    |   array
    ;

object
    :   '{' pair (',' pair)* '}'    # AnObject
    |   '{' '}'                     # EmptyObject
    ;
       
array
    :   '[' value (',' value)* ']'  # ArrayOfValues
    |   '[' ']'                     # EmptyArray
    ;

pair:   STRING ':' value ;

value
    :   STRING                # String
    |   NUMBER                # Atom
    |   object          # ObjectValue
    |   array                  # ArrayValue
    |   'true'                # Atom
    |   'false'                # Atom
    |   'null'                # Atom
    ;

LCURLY : '{' ;
LBRACK : '[' ;
STRING :  '"' (ESC | ~["\\])* '"' ;

fragment ESC :   '\\' (["\\/bfnrt] | UNICODE) ;
fragment UNICODE : 'u' HEX HEX HEX HEX ;
fragment HEX : [0-9a-fA-F] ;

NUMBER
    :   '-'? INT '.' INT EXP?   // 1.35, 1.35E-9, 0.3, -4.5
    |   '-'? INT EXP            // 1e10 -3e4
    |   '-'? INT                // -3, 45
    ;
fragment INT :   '0' | '1'..'9' '0'..'9'* ; // no leading zeros
fragment EXP :   [Ee] [+\-]? INT ; // \- since - means "range" inside [...]

WS  :   [ \t\n\r]+ -> skip ;




同样,要编写
一个JSON2XML.java 文件

语法和这个java 文件,作者在书上介绍了。

然后,



这是 我志愿 为 antlr 第5版 做得 推广 海报 (给antlr 做个广告,希望不会被删),

论坛徽章:
0
36 [报告]
发表于 2014-03-13 10:50 |只看该作者
****************************

小回顾,再次理解 decouple 其实 真地 非常 重要

分离 分离 再分离
***************************


我曾经觉得应该把 软件专业 转到 中文系, 现在 想想 觉得有点 不科学,

应该 一半 转到 中文系,另一半 转到 金融 系。

原因就是 软件 很看重 decouple,尤其看设计模式 也是非常注重decouple。现在 中国的金融 政策 已经基本 动弹不得,原因 是已经完全 被 很多行业 couple 了。

例如,钢材价格 下跌 就能 让 银行也 产生 上千亿的坏账(上千亿,计量单位是 100,000,000,000 元)


铁矿石 下跌,银行 也 中招,


一个煤老板也能让 银行 损失 上百亿


铜价下跌,银行 一样 损失惨重。


等等,钢啊、铜啊、煤啊、房啊等 每一个 都能 把 银行 拉下 水, 银行 就是 因为 decouple 做得不好,才被 coupled。

目前,这些损失 正在 被隐藏 ,并 被 希望 能够 慢慢 消化 , 就像 程序员 隐藏 bug 一样,最后 整个系统 崩溃。


再回顾,


一个 接 一个 行业 崩溃, 可能 只 崩溃 了一两个,随后 就全 蹦了,就是 因为 decouple 没做好。


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

也许 崩溃 结束 后,

在废墟 上 新成立 的银行 ,第一条 章程 就是  decouple,

这是 血 的教训。






   

论坛徽章:
0
37 [报告]
发表于 2014-03-14 10:40 |只看该作者
****************************
8.3 Generating a Call Graph

我们除了他谁都不认 / 우리는 당신밖에 모른다
****************************


Software is hard to write and maintain, which is why we try to build tools to
increase our productivity and effectiveness

他 这里 指 图片。

作者应该是有很多生活经验的人,即使 放在 中国,



要不是 有 图片,


陈金奉一边招呼我们喝茶,一边将他的复仇故事娓娓道来。“我这样一个聪明人”常出现在他的言语之间,比如他一开始做纺织生意,用两个月搞懂技术,比如中学时下象棋,鲜遇敌手。提起仇家,他面露鄙夷之情,带着胜利者的骄傲。

      “这个赵明华的生活规律已经被我摸透了,他好色,作为法官,他好这一口儿,我就知道他死定了。他用法律整我,我就用党的纪律整他。抓住他的把柄只是时间问题。有的有暗房,进不去,我就先不暴露自己,慢慢跟踪。”

画外音,真可惜,其它几个法官 躺枪。

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

In this section, we’re going to build a call graph generator using the Cymbol
grammar.



语法文件 已经 介绍过了,同时要去除 不确定,然后编写 java 文件,

然后,


Naturally, to view the call graph, cut and paste just the output starting with
digraph G {.



With very little code, we were able to build a call graph generator in this section.

论坛徽章:
0
38 [报告]
发表于 2014-03-15 11:11 |只看该作者
*******************************
8.4 Validating Program Symbol Usage

李香兰全局变量是日本人,所以不用死;而川岛芳子全局变量是中国人,所以必须死
*******************************


1994年,周星驰主演的香港电影《国产凌凌漆》在剧情中提及李香兰。片中女主角袁咏仪饰虚构角色李香琴,其母为李香兰,据剧情有影射文革中被打为“卖国贼”,导致其女香琴因此不得翻身,而不得不受金枪人的要挟。

李香兰最受听众欢迎的三首歌是《何日君再来》、《苏州夜曲》和《夜来香》。


1945年日本战败,李香兰以汉奸罪名被逮捕,后因其日本公民身份被无罪释放。1946年遣送回日本,1947年改回原名山口淑子继续其演艺事业。

楼主你到底什么意图?在敏感时期,在影射什么吗?

日本公民 是 全局 变量, 李香兰 是 局部变量。

其实我觉得花絮最有意思,
她曾收到了日本外交大臣松岗洋右的长子松岗谦一郎的来信。信上说:

“人的价值不能用有无名气来衡量。人的价值并不表现在人的表面,你应该珍重自己。现在是个人价值被愚弄的时代,你必须更加尊重自己,否则只能被国家时局摆布。希望你永远自尊自爱。”

这些话是耐人寻味的。在日本历史最黑暗的一个时期,战后被定为战犯的松岗外相之子,给一个冒充中国人(或“满洲人”),为日本的远东政策效力的女明星写这样的信。


我觉得上面的这些话现在也可以使用,改成: 在 一个虚假 繁荣的 时代,你必须更加尊重自己,否则只能被房价、职务、炫耀摆布。希望你永远自尊自爱。
http://baike.baidu.com/subview/2 ... 45&from=rdtself

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

Language implementers typically call the data structure that holds symbols
a symbol table.

The language being implemented dictates a symbol table’s
structure and complexity.



The scopes form a tree.



To begin building our validator, let’s think about the big picture and form an
overall strategy.

We can break this problem down according to the key operations:
define and resolve.



To learn more about symbol table management, I shamelessly
suggest you purchase and dig through Language Implementation Patterns

If you’ve been following along pretty well so far in this section of the book,
you’re in great shape!

论坛徽章:
0
39 [报告]
发表于 2014-03-17 13:12 |只看该作者
*******************************
CHAPTER 15
Grammar Reference

跳到 最后一章 类似复习
*******************************


作者可能 编译器水平非常高,但是 写作水平 实在 无法恭维。

感觉这本书,重点不突出,很像流水账。

This chapter is a reference and
summarizes grammar syntax and the key semantics of ANTLR grammars.

其实这章应该放在 前面,而且再细致些。




******************************
15.1 Grammar Lexicon

又 词法
*****************************



我为什么说个 又 ?

The lexicon of ANTLR is familiar to most programmers because it follows the
syntax of C and its derivatives with some extensions for grammatical
descriptions.

Comments
There are single-line, multiline, and Javadoc-style comments.




Identifiers

Token names always start with a capital letter and so do lexer rules as defined
by Java’s Character.isUpperCase() method.

Parser rule names always start with a
lowercase letter (those that fail Character.isUpperCase()).

   
Literals


All literal strings that are one or more characters in length are
enclosed in single quotes such as ';', 'if', '>=', and '\''


Actions

Actions are code blocks written in the target language.


Keywords

Here’s a list of the reserved words in ANTLR grammars: import, fragment, lexer,
parser, grammar, returns, locals, throws, catch, finally, mode, options, tokens.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP