想成为一名优秀的计算机专业本科生,应该对程序编译有所了解。通过这节课学习编译器的构造,理解程序编译的实现过程,实现一个编译器,提升自己的能力。
课程源地址
Week 1: Introduction & the Cool Programming Language
The difference between Compilers and Interpreters
The economy of programming languages
Why are there s many programming languages?
应用域具有独特或冲突的需要。
Application domains have distinctive/conflicting needs.
Why are there new programming languages?
声明:程序员培训是编程语言的主要成本。
Claim: Programmer training is the dominant cost for a programming language.
What is a good programming language?
语言设计没有普遍接受的度量标准。
There is no universally accepted metric for language design.
cool的VM安装方式(推荐使用这个)
cool的linux安装方式
class Main{
main():Int { 1 };
};
(*需要返回值*)
class Main {
i : IO <- new IO;
main():IO { i.out_string("Hello World!\n") };
}
(*返回类型需要相等*)
class Main {
i : IO <- new IO;
main():Object { i.out_string("Hello World!\n") };
}
(*Object类型也可以*)
class Main {
main():Object { (new IO).out_string("Hello World!\n") };
}
class Main inherits IO{
main():Object { self.out_string("Hello World!\n") };
}
(*继承写法*)
class Main {
main():Object {
(new IO).out_string((new IO).in_string().concat("\n\n"))
};
};
(*从键盘输入字符串,输出该字符串*)
class Main inherits A2I{
main():Object {
(new IO).out_string(i2a(a2i((new IO).in_string())+1).concat("\n\n"))
};
};
(*
*将输入的字符串转换为数字串,输出数字串+1的字符串
*注:编译的时候需要将atoi.cl一同编译,Main类继承
*)
class Main inherits A2I{
main():Object {
(new IO).out_string(i2a(fact(a2i((new IO).in_string()))).concat("\n\n"))
};
fact(i: Int): Int {
if (i = 0) then 1 else i * fact(i-1) fi
};
};
(*求阶乘递归写法*)
class Main inherits A2I{
main():Object {
(new IO).out_string(i2a(fact(a2i((new IO).in_string()))).concat("\n\n"))
};
fact(i: Int): Int {
let fact: Int <- 1 in { (*fact 初始化为1*)
while (not (i = 0)) loop
{
fact <- fact * i; (*<-为赋值,=为比较*)
i <- i - 1;
}
pool;
fact;
}
};
};
(*求阶乘无递归写法*)
class List inherits A2I {
item: Object;
next: List;
init(i: Object, n: List): List {
{
item <- i;
next <- n;
self;
}
};
flatten(): String {
let string: String <-
case item of
i: Int => i2a(i);
s: String => s;
o: Object => { abort(); ""; };
esac
in
if (isvoid next) then
string
else
string.concat(next.flatten())
fi
};
};
class Main inherits IO {
main():Object {
let hello: String <- "Hello ",
world: String <- "World!",
newline: String <- "\n",
nil: List,
list: List <-
(new List).init(hello,
(new List).init(world,
(new List).init(newline, nil)))
in
out_string(list.flatten())
};
};
(*该样例程序比较难,跟着视频能收获更多*)
注:个人英文水平有限,如有错误请指正,谢谢!