注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
previously:
第五个unit http://www.1point3acres.com/bbs/thread-37444-1-1.html
第四个unit http://www.1point3acres.com/bbs/thread-37362-1-1.html
第三个unit http://www.1point3acres.com/bbs/thread-37239-1-1.html
第二个unit http://www.1point3acres.com/bbs/thread-37174-1-1.html
第一个unit http://www.1point3acres.com/bbs/thread-37089-1-1.html
其实这门课重点的前几章都已经cover了: 编译任何语言需要的几个主要步骤:lexing, parsing和interpreting。复习一下:
Lexing was based on regular expressions. They specify sets of strings, and they can be implemented under the hood with finite state machines.
Parsing uses context-free grammars, which can capture behavior like balanced parentheses that regular expressions can't. And we saw how to implement those with dynamic programming, that is, writing ourselves little memos in a chart, and parse states.
interpreting refers to walking the abstract syntax tree recursively and computing the final value.
而这节课讲了以下一些知识点
1. Put them together to build a Web Browser
对于浏览器,输入是一个网页源代码文件,首先通过Lexical Analysis把那些plain text转化成一些列tokens.接着通过比照该语言的grammar生成一个AST树(parse tree)。html interpreter遍历这棵树,(同时调用graphics library在终端上渲染该网页),对于这棵AST树中javascript的部分,则要通过js interpreter去执行它。
2. function call
重新强调了每一次函数调用都应该新建一个frame同时父指针指向当前环境。 而frame里的环境变量就是该function里声明的变量,其他变量则需要依循父指针向上层的frame里查询。最上层的frame是global environment。有个非常好的例子就是javascript里面的闭包,闭包里的可以访问外层环境的变量就是因为最临近的上层frame是外层函数。
3. Optimization
举了一些js interpreter优化的例子,比如 A * 0 直接得到0, A+0得到A。虽然这些优化规则很简单,但是能减少AST树中Node的数量总是好的,可以让interpreter处理更快一点。
4. the Living and the Dead
考虑如下代码
- function myfun(a,b,c,d) {
- # a = 1;
- b = 2;
- c = 3;
- # d = 4;
- a = 5;
- d = c + b;
- return (a + d);
- }
复制代码 有两行可以去掉是因为他们根本没对结果产生任何影响,We say that a variable is LIVE if the value it holds may be needed in the future. More formally, a variable is LIVE if its value may be read before the next time it is overwritten. 从下往上分析,每一行我们都可以计算出当前哪些变量是live的,这样没有在live列表里面的变量就是不对结果产生影响的也即可以去掉的。 这个思想可用在任何语言的IDE(比如eclipse)中作为检测dead code/ unused variable的方法。
编程作业题:
JavaScript's Big Bang
给interpreter中处理javascript的部分增加逻辑,使之可以处理javascript代码块中的html代码。
# In this assignment you will extend our web browser so that the string
# produced by JavaScript is not merely passed to the graphics library as a
# word, but is instead lexed, parsed and interpreted as HTML. (For the
# purposes of this assignment, if JavaScript creates HTML, it must created
# only well-balanced tags.)
举例:
# In practice, however, JavaScript output may include HTML tags and should
# be lexed, parsed and interpreted again. For example, on modern web
# browsers the following webpage ...
#
# <html>
# <script type="text/javascript">
# document.write("Tags in <i>my</i> output should be processed.");
# </script>
# </html>
#
# Does not output the literal string "Tags in <i>my</i> output should be
# processed." Instead, the <i> tags are lexed, parsed and interpreted
# again, and the web page contains "Tags in my output should be processed."
# with the word "my" drawn in italics.
|