├── .gitignore ├── README.md ├── assignments ├── PA1 │ ├── Lex1.l │ ├── Lex2.l │ ├── Lex3.l │ ├── Lex4.l │ ├── Makefile │ ├── README.SKEL │ ├── ans │ │ ├── LexSamp4.l │ │ ├── f1.lex │ │ ├── f2.1.lex │ │ ├── f2.2.lex │ │ ├── f2.3.lex │ │ ├── f2.lex │ │ ├── f3.lex │ │ ├── f4.lex │ │ ├── f5.lex │ │ ├── f6.lex │ │ ├── lex.yy │ │ ├── lex.yy.c │ │ ├── makefile │ │ ├── makefile (copy) │ │ ├── makefile-unknow │ │ ├── test.cl │ │ ├── test3 │ │ ├── text │ │ ├── text1 │ │ └── text2 │ ├── demo.cl │ ├── fib.cl │ ├── stack.cl │ ├── task2.cl │ └── test.cl ├── PA2 │ ├── Makefile │ ├── README │ ├── README.SKEL │ ├── cool.flex │ ├── cool.flex.SKEL │ ├── mycoolc │ ├── reference-lexer │ ├── test.cl │ └── test.cl.SKEL ├── PA3 │ ├── Makefile │ ├── README │ ├── README.SKEL │ ├── bad.cl │ ├── bad.cl.SKEL │ ├── cool-tree.aps │ ├── cool-tree.handcode.h │ ├── cool-tree.handcode.h.SKEL │ ├── cool.ans.y │ ├── cool.output │ ├── cool.y │ ├── cool.y.SKEL │ ├── good.cl │ ├── good.cl.SKEL │ ├── myparser │ ├── task1.l │ ├── task1.y │ ├── task1p.l │ ├── task1p.y │ ├── task2.l │ ├── task2.y │ ├── task3.y │ ├── task4 │ ├── task4.y │ └── task5.y ├── PA4 │ ├── Makefile │ ├── README │ ├── bad.cl │ ├── checkpoint │ ├── cool-tree.h │ ├── cool-tree.handcode.h │ ├── good.cl │ ├── semant.cc │ └── semant.h └── PA5 │ ├── Makefile │ ├── README │ ├── cgen.cc │ ├── cgen.h │ ├── cgen_supp.cc │ ├── checkpoint │ ├── cool-tree.h │ ├── cool-tree.handcode.h │ ├── emit.h │ ├── example.cl │ └── hello_world.cl ├── bin ├── aps2c++ ├── aps2java ├── coolc ├── dispatch.SKEL ├── java_cup ├── jlex ├── reference-cgen ├── reference-lexer ├── reference-parser ├── reference-semant ├── spim ├── test.cl~ └── xspim ├── doc ├── UnixProgrammingTools.pdf ├── bison.ps.gz ├── cool-manual.pdf ├── cool-manual.tex ├── cool-program-language.pdf ├── cool-runtime.pdf ├── cool-tour.pdf ├── cool-tour.tex ├── flex.ps.gz ├── instructors-guide.pdf ├── instructors-guide.tex ├── make.ps.gz └── spim.ps.gz ├── etc ├── copy ├── copy-skel ├── copy-skel.SKEL ├── copy~ ├── link-object ├── link-object.SKEL ├── link-object.SKEL~ ├── link-shared └── link-shared.SKEL ├── examples ├── LexSamp1.l ├── README ├── arith.cl ├── assign.cl ├── atoi.cl ├── atoi_test.cl ├── book_list.cl ├── cells.cl ├── complex.cl ├── cool.cl ├── demo.cl ├── ex1.c ├── exp2 ├── graph.cl ├── hairyscary.cl ├── hello_world.cl ├── io.cl ├── lam.cl ├── lex.yy.c ├── life.cl ├── list.cl ├── new_complex.cl ├── null_string.cl ├── palindrome.cl ├── primes.cl ├── sort_list.cl └── test.cl ├── guide_file.doc ├── handouts ├── Makefile ├── asn1.pdf ├── asn1.tex ├── asn2.pdf ├── asn2.tex ├── asn3.pdf ├── asn3.tex ├── asn4.pdf ├── asn4.tex ├── asn5.pdf ├── asn5.tex ├── macros.tex └── mymargins.tex ├── include ├── PA2 │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-io.h~ │ ├── cool-parse.h │ ├── cool-parse.h~ │ ├── cool.h │ ├── cool.h~ │ ├── copyright.h │ ├── list.h │ ├── list.h~ │ ├── stringtab.h │ ├── stringtab.h~ │ ├── stringtab_functions.h │ ├── tree.h │ ├── tree.h~ │ ├── utilities.h │ └── utilities.h~ ├── PA3 │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-parse.h │ ├── cool-parse.h~ │ ├── cool-tree.h │ ├── cool-tree.handcode.h │ ├── cool-tree.handcode.h~ │ ├── cool-tree.h~ │ ├── cool.h │ ├── cool.h~ │ ├── copyright.h │ ├── list.h │ ├── list.h~ │ ├── stringtab.h │ ├── stringtab.h~ │ ├── stringtab_functions.h │ ├── tree.h │ ├── tree.h~ │ ├── utilities.h │ └── utilities.h~ ├── PA4 │ ├── ast-parse.h │ ├── ast-parse.h~ │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-parse.h │ ├── cool-parse.h~ │ ├── cool.h │ ├── cool.h~ │ ├── copyright.h │ ├── list.h │ ├── list.h~ │ ├── stringtab.h │ ├── stringtab.h~ │ ├── stringtab_functions.h │ ├── symtab.h │ ├── symtab.h~ │ ├── tree.h │ ├── tree.h~ │ ├── utilities.h │ └── utilities.h~ └── PA5 │ ├── ast-parse.h │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-parse.h │ ├── cool-tree.h │ ├── cool.h │ ├── copyright.h │ ├── list.h │ ├── stringtab.h │ ├── stringtab_functions.h │ ├── symtab.h │ ├── tree.h │ ├── tree.h~ │ └── utilities.h ├── lib └── trap.handler └── src ├── PA2 ├── handle_flags.cc ├── lextest.cc ├── mycoolc ├── stringtab.cc └── utilities.cc ├── PA3 ├── cool-tree.aps ├── cool-tree.cc ├── cool-tree.cc~ ├── dumptype.cc ├── handle_flags.cc ├── mycoolc ├── myparser ├── parser-phase.cc ├── parser-phase.cc~ ├── ref-parser ├── stringtab.cc ├── tokens-lex.cc ├── tree.cc ├── tree.cc~ ├── utilities.cc └── utilities.cc~ ├── PA4 ├── ast-lex.cc ├── ast-parse.cc ├── ast-parse.cc~ ├── cool-tree.aps ├── cool-tree.cc ├── cool-tree.cc~ ├── dumptype.cc ├── dumptype.cc~ ├── handle_flags.cc ├── handle_flags.cc~ ├── mycoolc ├── mysemant ├── ref-semant ├── semant-phase.cc ├── semant-phase.cc~ ├── stringtab.cc ├── symtab_example.cc ├── tree.cc ├── utilities.cc └── utilities.cc~ └── PA5 ├── ast-lex.cc ├── ast-parse.cc ├── cgen-phase.cc ├── cool-tree.cc ├── dumptype.cc ├── handle_flags.cc ├── mycoolc ├── stringtab.cc ├── tree.cc ├── utilities.cc └── utilities.cc~ /.gitignore: -------------------------------------------------------------------------------- 1 | *.s 2 | *.out 3 | tmp* 4 | temp* 5 | 6 | # PA2 7 | 8 | /assignments/PA2/test.output 9 | /assignments/PA2/*.s 10 | /assignments/PA2/*.o 11 | /assignments/PA2/*.d 12 | /assignments/PA2/*.cc 13 | /assignments/PA2/*~ 14 | /assignments/PA2/lexer 15 | 16 | # PA3 17 | 18 | /assignments/PA3/*.yy.c 19 | /assignments/PA3/*.tab.h 20 | /assignments/PA3/*.tab.c 21 | /assignments/PA3/*.out 22 | /assignments/PA3/*.o 23 | /assignments/PA3/*.cc 24 | /assignments/PA3/*.c 25 | /assignments/PA3/*.d 26 | /assignments/PA3/lexer 27 | /assignments/PA3/semant 28 | /assignments/PA3/ref-parser 29 | /assignments/PA3/parser 30 | /assignments/PA3/*.output 31 | 32 | 33 | # PA4 34 | 35 | /assignments/PA4/ast-lex.* 36 | /assignments/PA4/ast-parse.* 37 | 38 | /assignments/PA4/cool-tree.* 39 | !/assignments/PA4/cool-tree.h 40 | !/assignments/PA4/cool-tree.handcode.h 41 | 42 | /assignments/PA4/dumptype.* 43 | /assignments/PA4/handle_flags.* 44 | 45 | /assignments/PA4/semant.* 46 | !/assignments/PA4/semant.cc 47 | !/assignments/PA4/semant.h 48 | 49 | /assignments/PA4/semant-phase.* 50 | /assignments/PA4/stringtab.* 51 | /assignments/PA4/symtab_example.* 52 | /assignments/PA4/tree.* 53 | /assignments/PA4/utilities.* 54 | /assignments/PA4/lexer 55 | /assignments/PA4/cgen 56 | /assignments/PA4/parser 57 | /assignments/PA4/ref-semant 58 | /assignments/PA4/semant 59 | /assignments/PA4/symtab_example 60 | /assignments/PA4/mycoolc 61 | /assignments/PA4/mysemant 62 | 63 | # PA5 64 | 65 | /assignments/PA5/*.o 66 | /assignments/PA5/*.d 67 | /assignments/PA5/*.cc 68 | /assignments/PA5/mycoolc 69 | /assignments/PA5/parser 70 | /assignments/PA5/semant 71 | /assignments/PA5/cgen 72 | /assignments/PA5/lexer 73 | !/assignments/PA5/cgen.cc 74 | !/assignments/PA5/cgen_supp.cc 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wsl+vscode cool 配置指南 2 | 3 | > requirements: win10,电脑得装得下wsl 4 | 5 | ### 需要安装的软件 6 | 7 | - 微软商店中的任意Linux子系统(Ubuntu,debian,centos均可,需要开启wsl子系统功能) 8 | 9 | - vscode,官网自寻 10 | 11 | ## 步骤 12 | 13 | - 步骤3、4、5次序可以交换 14 | 15 | 1. 下载完成wsl后启动,配置用户名密码等。并更换apt源 (清华 阿里) 16 | 17 | 2. 打开vscode 安装汉化插件 安装remote-wsl 18 | 19 | 3. https://github.com/Microsoft/WSL/issues/2468 配置wsl 支持32bit程序。 20 | 21 | 每次使用需要开启binfmt-support服务 22 | ```bash 23 | sudo start binfmt-support start 24 | ``` 25 | 26 | 4. 安装flex bison 27 | 28 | 5. 将cool文件夹放入~目录 29 | 30 | - 可以在wsl中使用mv、cp等指令 31 | - 可以查询wsl所在文件在系统中的位置直接移动 32 | - 亦可以将cool文件夹放在任意位置,但是注意CLASSDIR应该设置为/mnt/(盘符)/... 33 | 34 | 6. 在vscode中打开wsl子系统。ctrl+`打开控制台。之后使用和指导书一致。 35 | 36 | 37 | # 编译器实验 coolc 38 | 39 | 西安交通大学 编译原理 实验 40 | 41 | 由于老师给的文件中有过多干扰,故建立此repo 42 | 43 | 修改中难免有错误,请以各个PA中的readme为准 44 | 45 | ## 第一次实验 46 | 47 | 配置环境(见上) 48 | 49 | ## 第二次实验 50 | 51 | PA1 52 | 53 | 编写编译运行coolc程序 54 | 55 | ## 第三次实验 56 | 57 | PA1 58 | 59 | |目标|文件| 60 | |-|-| 61 | |统计行数,列数和字数|Lex1.l| 62 | |记录行数,列数和字数|Lex2.l| 63 | |magic多入口|Lex3.l| 64 | |统计if个数|Lex4.l| 65 | 66 | - 编译命令 67 | 68 | ```bash 69 | # flex 识别 70 | flex ${file}.l 71 | # gcc 生成.out可执行文件 72 | gcc -o ${file}.out lex.yy.c -lfl 73 | ``` 74 | 75 | ## 第四次实验 76 | 77 | PA2 78 | 79 | |目标|文件| 80 | |-|-| 81 | |coolc的词法分析器编写|cool.flex| 82 | 83 | 84 | ## 第五次实验 85 | 86 | PA3 87 | 88 | |目标|文件| 89 | |-|-| 90 | |多位计算(加减乘除括号)|task1.l task1.y联合编译| 91 | |double计算(加减乘除括号)|task1p.l task1p.y联合编译| 92 | |布尔运算(与或非括号)|task2.l task2.y联合编译| 93 | |一位数计算器(减法、乘法、赋值)|task3.y 单文件编译| 94 | |一位数计算器(加减乘除括号赋值)|task4.y 单文件编译| 95 | |多位数计算器(加减乘除括号赋值)|task5.y 单文件编译| 96 | 97 | 98 | - 联合编译命令 99 | 100 | ```bash 101 | # flex 识别token 102 | flex -o ${file}.yy.c ${file}.l 103 | # bison生成.tab.h 定义token 104 | bison -d ${file}.y 105 | # bison生成.tab.c 106 | bison -o ${file}.tab.c ${file}.y 107 | # 生成可执行文件 108 | gcc -o ${file}.out ${file}.yy.c ${file}.tab.c 109 | ``` 110 | 111 | - 单文件编译命令 112 | 113 | ```bash 114 | # bison生成.c 115 | bison -o ${file}.c ${file}.y 116 | # 生成可执行文件 117 | gcc -o ${file}.out ${file}.c 118 | ``` 119 | 120 | 121 | ## 第六次实验 122 | 123 | PA3 124 | 125 | cool.y为原语法分析器 126 | cool.ans.y即为语法分析器,可替换cool.y编译使用,增加了对let的支持 127 | 128 | ## 第七次实验 129 | 130 | ## 第八次实验 131 | 132 | ## Attention 133 | 134 | 请务必仔细阅读相应的readme 135 | 如有必要,请学习编写修改Makefile文件 136 | -------------------------------------------------------------------------------- /assignments/PA1/Lex1.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 统计行数,列数和字数 4 | */ 5 | #include 6 | int nline,ncolumn,nnword,column; /* 分别记录行数,列数和字数 */ 7 | %} 8 | 9 | %% 10 | 11 | [ \t] {column++;} 12 | [^ \t\n]+ { 13 | nnword++; 14 | column+=yyleng; 15 | } 16 | \n { 17 | ncolumn=(ncolumn>column)?ncolumn:column; 18 | ++nline; 19 | column=0; 20 | } 21 | 22 | %% 23 | 24 | int main(){ 25 | printf("Press CTRL+d to quit.\nInput any text:\n"); 26 | yylex(); /* 调用词法分析器,直到输入结束 */ 27 | printf("nline=%d, ncolumn=%d, nnword=%d\n", nline, ncolumn, nnword); 28 | return 0; 29 | } -------------------------------------------------------------------------------- /assignments/PA1/Lex2.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 统计行数,列数和字数 文件/直接输入 4 | * 5 | */ 6 | #include 7 | int nline,ncolumn,nnword,column; /* 分别记录行数,列数和字数 */ 8 | %} 9 | 10 | %% 11 | 12 | [ \t] {column++;} 13 | [^ \t\n]+ { 14 | nnword++; 15 | column+=yyleng; 16 | } 17 | \n { 18 | ncolumn=(ncolumn>column)?ncolumn:column; 19 | ++nline; 20 | column=0; 21 | } 22 | 23 | %% 24 | 25 | int main(int argc, char **argv){ 26 | if(argc > 1) { 27 | if(!(yyin=fopen(argv[1],"r"))) { 28 | perror(argv[1]); 29 | return 1; 30 | } 31 | } 32 | yylex(); /* 调用词法分析器,直到输入结束 */ 33 | printf("nline=%d, ncolumn=%d, nnword=%d\n", nline, ncolumn, nnword); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /assignments/PA1/Lex3.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 功能: 3 | * 将输入复制到输出,同时对输入文本中的字符序列“magic”做变换: 4 | * (1) 若行首以字母a开始,则将紧跟其后的第1个序列"magic"变化为"first"输出; 5 | * (2) 若行首以字母b开始,则将紧跟其后的第1个序列"magic"变化为"second"输出; 6 | * (3) 若行首以字母c开始,则将紧跟其后的第1个序列"magic"变化为"third"输出; 7 | * (4) 其他地方出现的序列"magic"变化为"zero"输出; 8 | * (5) 其他行和非magic单词不变,直接输出。 9 | */ 10 | 11 | #include 12 | %} 13 | %start AA BB CC 14 | %% 15 | ^a { ECHO; BEGIN AA; } 16 | ^b { ECHO; BEGIN BB; } 17 | ^c { ECHO; BEGIN CC; } 18 | 19 | magic { printf ("first"); } 20 | magic { printf ("second");} 21 | magic { printf ("third");} 22 | \n|(\t)+|" "+ { ECHO; BEGIN 0; } 23 | magic { printf ("zero");} 24 | 25 | %% 26 | 27 | int main() 28 | { 29 | int a; 30 | a = yylex(); 31 | return 0; 32 | } 33 | 34 | int yywrap() { return 1; } -------------------------------------------------------------------------------- /assignments/PA1/Lex4.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 统计if个数 4 | */ 5 | #include 6 | int nif=0; 7 | %} 8 | 9 | %% 10 | 11 | [ \t\n]*if[ \t\n]+ {nif++;} 12 | [^ \t\n]+[ \t\n]+ {} 13 | 14 | %% 15 | 16 | int main(int argc, char **argv){ 17 | if(argc > 1) { 18 | if(!(yyin=fopen(argv[1],"r"))) { 19 | perror(argv[1]); 20 | return 1; 21 | } 22 | } 23 | printf("Press CTRL+d to quit.\nInput any text:\n"); 24 | yylex(); /* 调用词法分析器,直到输入结束 */ 25 | printf("nif=%d\n", nif); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /assignments/PA1/Makefile: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # 编辑这里 3 | # 把CLASSDIR设置成cool文件的位置 4 | # 以便让Makefile通过 ${CLASSDIR}/bin 可以找到coolc 5 | # 下面是我的电脑上cool文件夹的位置 6 | CLASSDIR= ~/cool 7 | ####################################### 8 | 9 | ASSN = 1 10 | CLASS= cs-compiler 11 | SRC= demo.cl README.SKEL 12 | LSRC= Makefile 13 | 14 | CC=gcc 15 | CFLAGS=-g 16 | 17 | default: source compile test 18 | 19 | .c.o: 20 | ${CC} ${CFLAGS} -c $< 21 | 22 | source : lsource 23 | ${CLASSDIR}/etc/copy-skel ${ASSN} ${SRC} 24 | 25 | lsource: 26 | ${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 27 | 28 | compile: demo 29 | 30 | demo: demo.cl 31 | @echo create demo.s 32 | ${CLASSDIR}/bin/coolc demo.cl 33 | 34 | test: compile 35 | @echo test demo.s 36 | ${CLASSDIR}/bin/spim -trap_file ${CLASSDIR}/lib/trap.handler -file demo.s 37 | 38 | run: compile 39 | @echo run demo.s 40 | ${CLASSDIR}/bin/spim -trap_file ${CLASSDIR}/lib/trap.handler -file demo.s 41 | 42 | clean : 43 | rm -f *.s core *~ 44 | 45 | main: 46 | @echo compile and run $(file).cl 47 | ${CLASSDIR}/bin/coolc $(file).cl 48 | ${CLASSDIR}/bin/spim -trap_file ${CLASSDIR}/lib/trap.handler -file $(file).s 49 | 50 | # lex 51 | lex: 52 | @echo run flex $(file).l 53 | flex $(file).l 54 | cc -o $(file).out lex.yy.c -lfl 55 | rm lex.yy.c -------------------------------------------------------------------------------- /assignments/PA1/README.SKEL: -------------------------------------------------------------------------------- 1 | 2 | README file for Programming Assignment 1 3 | ======================================== 4 | 5 | Your directory should now contain the following files: 6 | 7 | Makefile -> [course dir]/assignments/PA1/Makefile 8 | README 9 | atoi.cl -> [course dir]/assignments/PA1/atoi.cl 10 | stack.cl 11 | stack.test -> [course dir]/assignments/PA1/stack.test 12 | 13 | The Makefile contains targets for compiling and running your 14 | program, as well as handing it in. 15 | 16 | The README contains this info. Part of the assignment is to 17 | answer the questions at the end of this README file. 18 | Just edit this file. 19 | 20 | atoi.cl is an implementation in Cool of the string to integer 21 | conversion function known from the C language. 22 | 23 | stack.cl is the skeleton file which you should fill in with 24 | your program. 25 | 26 | stack.test is a short test input to the stack machine. It is 27 | run through your program when you hand it in, and the output 28 | is also handed in. 29 | 30 | 31 | The symlinked files (see "man ln") are that way to emphasize 32 | that they are read-only -- when we test your program, we already 33 | have our own versions. 34 | 35 | Questions on PA1 36 | ---------------- 37 | 38 | 1. Describe your implementation of the stack machine in a single short 39 | paragraph. 40 | 41 | 42 | 2. List 3 things that you like about the Cool programming language. 43 | 44 | 45 | 3. List 3 things you DON'T like about Cool. 46 | 47 | 48 | If you used Harmonia-mode for all or part of your project, please answer 49 | the following questions: 50 | 51 | H1. Rate Harmonia-mode's usefulness on a scale of 0 to 6, where 0 means 52 | that it kept you from doing any work, 3 means that it neither helped 53 | nor hindered you, and 6 means that you'll never again dare to edit a 54 | Cool program without it. 55 | 56 | H2. What aspects of Harmonia-mode particularly helped you? 57 | 58 | H3. What aspects were particularly detrimental? 59 | 60 | H4. Is there anything else about Harmonia-mode that you would like 61 | to mention? 62 | -------------------------------------------------------------------------------- /assignments/PA1/ans/LexSamp4.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 功能: 3 | * 将输入复制到输出,同时对输入文本中的字符序列“magic”做变换: 4 | * (1) 若行首以字母a开始,则将紧跟其后的第1个序列"magic"变化为"first"输出; 5 | * (2) 若行首以字母b开始,则将紧跟其后的第1个序列"magic"变化为"second"输出; 6 | * (3) 若行首以字母c开始,则将紧跟其后的第1个序列"magic"变化为"third"输出; 7 | * (4) 其他地方出现的序列"magic"变化为"zero"输出; 8 | * (5) 其他行和非magic单词不变,直接输出。 9 | * 10 | *----------- 11 | * 若将非互斥入口该为互斥入口,即 %start 该为 %x,则 12 | * 一旦进入某入口,总是用对应正规式识别 后续任意的 magic。 13 | * 14 | * 用gcc生成可执行程序: 15 | flex -o lexsamp4.c lexsamp4.l 16 | gcc -o lexsamp4 lexsamp4.c 17 | 之后输入./lexsamp4即可运行 18 | */ 19 | 20 | #include 21 | %} 22 | %start AA BB CC 23 | %% 24 | ^a { ECHO; BEGIN AA; } 25 | ^b { ECHO; BEGIN BB; } 26 | ^c { ECHO; BEGIN CC; } 27 | /*注释不能顶头 */ 28 | \n|(\t)+|" "+ { ECHO; BEGIN 0; } 29 | /**/ 30 | /* 如果这个规则位于所有magic之前,则 31 | * magic规则永远无法起作用 32 | * 33 | magic { printf ("zero");} 34 | */ 35 | magic { /*adding your code*/ } 36 | magic { /*adding your code*/} 37 | magic { /*adding your code*/} 38 | /* 该规则必须放到上三条之后,原因见上 */ 39 | magic { printf ("zero");} 40 | /* */ 41 | %% 42 | 43 | /*以上语义动作没有return语句,所以yylex()仅遇到 44 | * 输入结束才返回。 45 | */ 46 | int main() 47 | { 48 | yyin=fopen("text1","r"); 49 | yylex(); 50 | 51 | return 0; 52 | } 53 | 54 | int yywrap() { return 1; } 55 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f1.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | %} 3 | %option noyywrap 4 | %% 5 | %% 6 | int main() 7 | { 8 | yyin=fopen("text","r"); 9 | yylex(); 10 | } 11 | 12 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f2.1.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int nchar,nwords,nline,nwordif; 4 | %} 5 | 6 | %% 7 | 8 | [ \t] /* 匹配到一个空格或Tab键就“吃”掉它们 */ 9 | \n {++nline; } /* 匹配到一个换行符,行数加1 */ 10 | [^ \t\n]+ { 11 | ++nwords;nchar += yyleng; 12 | } 13 | [a-z|A-Z]*|[1-9]*(if)[a-z|A-Z]*|[1-9]* {++nwordif;} 14 | 15 | %% 16 | int main() 17 | { 18 | yyin=fopen("text1","r"); 19 | yylex(); 20 | printf("nchar=%d,nwords=%d,nline=%d \n",nchar,nwords,nline); 21 | printf("nwordif=%d \n",nwordif); 22 | } 23 | 24 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f2.2.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int nchar,nwords,nline,nwordif; 4 | %} 5 | 6 | %% 7 | 8 | integer {++nchar; } /* 匹配到一个空格或Tab键就“吃”掉它们 */ 9 | [a-z]+ {++nline; } /* 匹配到一个换行符,行数加1 */ 10 | 11 | 12 | %% 13 | int main() 14 | { 15 | 16 | yylex(); 17 | printf("nchar=%d,nwords=%d,nline=%d \n",nchar,nwords,nline); 18 | 19 | } 20 | 21 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f2.3.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int flag=0; 4 | %} 5 | %% 6 | . ECHO; 7 | \n ECHO; 8 | %% 9 | 10 | int yywrap(void) { 11 | return 1; 12 | } 13 | int main(void) { 14 | yylex(); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f2.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int nchar,nwords,nline; 4 | %} 5 | 6 | %% 7 | [ \t] /* 匹配到一个空格或Tab键就“吃”掉它们 */ 8 | \n {++nline; } /* 匹配到一个换行符,行数加1 */ 9 | [^ \t\n]+ { 10 | ++nwords;nchar += yyleng; 11 | } 12 | %% 13 | int main() 14 | { 15 | yyin=fopen("text","r"); 16 | yylex(); 17 | printf("nchar=%d,nwords=%d,nline=%d \n",nchar,nwords,nline); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f3.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int flag=0; 4 | %} 5 | %% 6 | ^a {ECHO;flag='a';} 7 | ^b {ECHO;flag='b';} 8 | ^c {ECHO;flag='c';} 9 | ^l {ECHO;flag='c';} 10 | ^w {ECHO;flag='c';} 11 | magic {switch(flag) { 12 | case 'a':printf("first");break; 13 | case 'b':printf("second");break; 14 | case 'c':printf("third");break; 15 | case 'l':printf("ll");break; 16 | case 'w':printf("ww");break; 17 | default:printf("zero");break; 18 | } 19 | } 20 | \n|(\t)+|" "+ {ECHO;flag=0;} 21 | %% 22 | int main() 23 | { 24 | yyin=fopen("text1","r"); 25 | yylex(); 26 | /*printf("nchar=%d,nwords=%d,nline=%d \n",nchar,nwords,nline);*/ 27 | } 28 | 29 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f4.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int flag=0; 4 | %} 5 | %start AA BB CC 6 | %option noyywrap 7 | %%; 8 | ^a {ECHO;BEGIN AA;} 9 | ^b {ECHO;BEGIN BB;} 10 | ^c {ECHO;BEGIN CC;} 11 | magic {printf("first");} 12 | magic {printf("second");} 13 | magic {printf("third");} 14 | magic {printf("zero");} 15 | \n|(\t)+|" "+ {ECHO;BEGIN 0;} 16 | %% 17 | int main() 18 | { 19 | yyin=fopen("text1","r"); 20 | yylex(); 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f5.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int LineNo=0,num=0; 4 | %} 5 | %x comment c_comment 6 | %option noyywrap 7 | %% 8 | "//" {BEGIN comment;num++;} 9 | . ; 10 | \n {BEGIN 0;LineNo ++;} 11 | "/*" {BEGIN c_comment;} 12 | "*/" {BEGIN 0;num++;} 13 | . ; 14 | \n {LineNo++;} 15 | %% 16 | int main() 17 | { 18 | yyin=fopen("text2","r"); 19 | yylex(); 20 | printf("lineno=%d,num=%d",LineNo,num); 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /assignments/PA1/ans/f6.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | int uniqueIndex =1; 3 | 4 | %} 5 | TYPEID [A-Z]+[_A-Za-z0-9]* 6 | OBJECTID [a-z]+[_a-zA-Z0-9]* 7 | STR_CONST \".*\" 8 | INT_CONST [0-9]+ 9 | WHITE [ \t]+ 10 | LINE \n 11 | 12 | %s MutiCom 13 | %% 14 | "program"+[A-Z]+[_A-Za-z0-9]* {printf("\n");printf("\n");} 15 | 16 | "program" {printf("\n");} 17 | "var" {printf("\n");} 18 | "type" {printf("\n");} 19 | "integer" {printf("\n");} 20 | "char" {printf("\n");} 21 | "begin" {printf("\n");} 22 | "end" {printf("\n");} 23 | 24 | "{" {return '{';} 25 | "}" {return '}';} 26 | "(" {return '(';} 27 | ")" {return ')';} 28 | ":" {return ':';} 29 | ";" {return ';';} 30 | "+" {return '+';} 31 | "-" {return '-';} 32 | "*" {return '*';} 33 | "/" {return '/';} 34 | "=" {return '=';} 35 | "<" {return '<';} 36 | "." {return '.';} 37 | "~" {return '~';} 38 | "," {return ',';} 39 | "@" {return '@';} 40 | ":=" {printf("\n");} 41 | ".." {printf("\n");} 42 | %% 43 | int main(){ 44 | yyin=fopen("test3","r"); 45 | yylex(); 46 | //printf("fie"); 47 | 48 | return 0; 49 | } 50 | 51 | int yywrap() 52 | { 53 | return 1; 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /assignments/PA1/ans/lex.yy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/assignments/PA1/ans/lex.yy -------------------------------------------------------------------------------- /assignments/PA1/ans/makefile: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # from the simplist start 3 | # 以便Makefile可以找到cool/bin所在的位置 4 | CLASSDIR= /home/os/Public/cool/cool 5 | ####################################### 6 | ASSN = 2 7 | LIB= /home/os/Public/cool/cool/lib 8 | SRC= f1.flex test.cl README 9 | #make需要的源文件列表 10 | CSRC= lextest.cc utilities.cc stringtab.cc handle_flags.cc 11 | #一个shell脚本程序 12 | TSRC= mycoolc 13 | HSRC= 14 | #需要生成的文件 15 | CGEN= cool-lex.cc 16 | #一个完整的编译过程 17 | LIBS= parser semant cgen 18 | CFIL= ${CSRC} ${CGEN} 19 | LSRC= Makefile 20 | #OBJS表示所有的.o目标 21 | OBJS= ${CFIL:.cc=.o} 22 | #执行make test.output命令的时候,会将记号输出到test.out文件中 23 | OUTPUT= test.output 24 | LSRC= Makefile 25 | CC=gcc 26 | CFLAGS=-g 27 | #default: source compile test 28 | default: 29 | flex ${CLASSDIR}/assignments/PA2.1/f6.lex 30 | gcc -o lex.yy ${CLASSDIR}/assignments/PA2.1/lex.yy.c -ll 31 | 32 | 33 | 34 | clean: 35 | rm *.o *.d *.~ lex.yy.c 36 | 37 | 38 | -------------------------------------------------------------------------------- /assignments/PA1/ans/makefile (copy): -------------------------------------------------------------------------------- 1 | ####################################### 2 | # from the simplist start 3 | # 以便Makefile可以找到cool/bin所在的位置 4 | CLASSDIR= /home/os/Public/cool/cool 5 | ####################################### 6 | ASSN = 2 7 | LIB= /home/os/Public/cool/cool/lib 8 | SRC= f1.flex test.cl README 9 | #make需要的源文件列表 10 | CSRC= lextest.cc utilities.cc stringtab.cc handle_flags.cc 11 | #一个shell脚本程序 12 | TSRC= mycoolc 13 | HSRC= 14 | #需要生成的文件 15 | CGEN= cool-lex.cc 16 | #一个完整的编译过程 17 | LIBS= parser semant cgen 18 | CFIL= ${CSRC} ${CGEN} 19 | LSRC= Makefile 20 | #OBJS表示所有的.o目标 21 | OBJS= ${CFIL:.cc=.o} 22 | #执行make test.output命令的时候,会将记号输出到test.out文件中 23 | OUTPUT= test.output 24 | LSRC= Makefile 25 | CC=gcc 26 | CFLAGS=-g 27 | default: source compile test 28 | rr: 29 | flex ${CLASSDIR}/assignments/PA2.1/LexSamp4.l 30 | gcc -o lex.yy ${CLASSDIR}/assignments/PA2.1/lex.yy.c -ll 31 | 32 | 33 | 34 | clean: 35 | rm *.o *.d *.~ lex.yy.c 36 | 37 | 38 | -------------------------------------------------------------------------------- /assignments/PA1/ans/makefile-unknow: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # 将这里的CLASSDIR改成你机子上cool所在的目录 3 | # 以便Makefile可以找到cool/bin所在的位置 4 | CLASSDIR= /home/os/Public/cool/cool 5 | ####################################### 6 | #作业号,用来判断需要链接的头文件和源文件的目录 7 | ASSN = 2 8 | #没有用,表示这个作业是用来干嘛的 9 | CLASS= xjtucomplier 10 | #表示lib的位置,这里不用lib,暂时没有用 11 | LIB= -L/usr/sww/lib 12 | 13 | #make依赖的文件列表 14 | SRC= cool.flex test.cl README 15 | #make需要的源文件列表 16 | CSRC= lextest.cc utilities.cc stringtab.cc handle_flags.cc 17 | #一个shell脚本程序 18 | TSRC= mycoolc 19 | HSRC= 20 | #需要生成的文件 21 | CGEN= cool-lex.cc 22 | HGEN= 23 | #一个完整的编译过程 24 | LIBS= parser semant cgen 25 | CFIL= ${CSRC} ${CGEN} 26 | LSRC= Makefile 27 | #OBJS表示所有的.o目标 28 | OBJS= ${CFIL:.cc=.o} 29 | #执行make test.output命令的时候,会将记号输出到test.out文件中 30 | OUTPUT= test.output 31 | 32 | #指定头文件和源文件的目录 33 | CPPINCLUDE= -I. -I${CLASSDIR}/include/PA${ASSN} -I${CLASSDIR}/src/PA${ASSN} 34 | 35 | #设置flex的编译选项,-d表示允许debug,-o表示允许output 36 | FFLAGS= -d -ocool-lex.cc 37 | #使用flex 38 | FLEX=flex ${FFLAGS} 39 | 40 | #设置编译器g++ 41 | CC=g++ 42 | #设置g++的编译选项,-g表示添加调试信息,-Wall表示输出警告 43 | CFLAGS= -g -Wall -Wno-unused ${CPPINCLUDE} 44 | #-MM表示自动生成.o文件和.h文件的关系,且不输出这个关系 45 | DEPEND = ${CC} -MM ${CPPINCLUDE} 46 | 47 | #缺省目标 48 | default: source lexer dotest 49 | 50 | #调用shell脚本检查文件是否齐全 51 | source : ${SRC} ${TSRC} ${LSRC} ${LIBS} lsource 52 | 53 | lsource: ${LSRC} 54 | 55 | #将记号输出到output.test文件中去 56 | ${OUTPUT}: lexer test.cl 57 | @rm -f test.output 58 | -./lexer test.cl >test.output 2>&1 59 | 60 | #生成lexer,这里的OBJS都是.o,makefile会自动根据依赖项生成.o文件 61 | lexer: ${OBJS} 62 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o lexer 63 | 64 | #双缀规则,表示所有的.cc文件都必须编译成.o文件 65 | .cc.o: 66 | ${CC} ${CFLAGS} -c $< 67 | 68 | #处理cool-flex,生成词法分析程序的.cc文件 69 | cool-lex.cc: cool.flex 70 | ${FLEX} cool.flex 71 | 72 | #测试lexer 73 | dotest: lexer test.cl 74 | ./lexer test1.cl 75 | 76 | ${LIBS}: 77 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 78 | 79 | # 以下的部分用来检查和copy本次实验需要的文件 80 | # 如果目录下有这些文件的话,不会被覆盖 81 | 82 | ${SRC} : 83 | ${CLASSDIR}/etc/copy-skel ${ASSN} ${SRC} 84 | 85 | ${LSRC} : 86 | ${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 87 | 88 | ${TSRC} ${CSRC}: 89 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 90 | 91 | ${HSRC}: 92 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 93 | 94 | #以下的部分执行清理,使用:例如,make clean 95 | 96 | submit-clean: ${OUTPUT} 97 | -rm -f *.s core ${OBJS} lexer cool-lex.cc *~ parser cgen semant 98 | 99 | clean : 100 | -rm -f ${OUTPUT} *.s core ${OBJS} lexer cool-lex.cc *~ parser cgen semant *.d *.cc 101 | 102 | clean-compile: 103 | @-rm -f core ${OBJS} cool-lex.cc ${LSRC} 104 | 105 | %.d: %.cc ${SRC} ${LSRC} 106 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 107 | 108 | -include ${CFIL:.cc=.d} 109 | 110 | 111 | -------------------------------------------------------------------------------- /assignments/PA1/ans/test.cl: -------------------------------------------------------------------------------- 1 | class CellularAutomaton inherits IO { 2 | population_map : String; 3 | init(map : String) : SELF_TYPE { 4 | { 5 | population_map <- map; 6 | self; 7 | } 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /assignments/PA1/ans/test3: -------------------------------------------------------------------------------- 1 | program p 2 | type t = integer; 3 | var v1:t; 4 | v2:char; 5 | begin 6 | read(v1); 7 | v1:=v1*10; 8 | v1:="d"; 9 | v2:='a'; 10 | write(v1); { 这里是 11 | 注释 12 | } 13 | end. 14 | 15 | -------------------------------------------------------------------------------- /assignments/PA1/ans/text: -------------------------------------------------------------------------------- 1 | tomorrow is sunday 2 | 3 | -------------------------------------------------------------------------------- /assignments/PA1/ans/text1: -------------------------------------------------------------------------------- 1 | tomorrow is sunday 2 | ifif 3 | 4 | amagic bmagic 5 | bmagic 6 | magic 7 | lmagic is with 8 | if 9 | wmagic 10 | there isifele 11 | -------------------------------------------------------------------------------- /assignments/PA1/ans/text2: -------------------------------------------------------------------------------- 1 | tomorrow is sunday 2 | //ifif 3 | 4 | amagic bmagic 5 | bmagic 6 | magic 7 | lmagic is with 8 | if 9 | /* wmagic */ 10 | there isifele 11 | // 12 | 13 | -------------------------------------------------------------------------------- /assignments/PA1/fib.cl: -------------------------------------------------------------------------------- 1 | -- 斐波那契数列 2 | class Main inherits IO { 3 | s:Int; 4 | f(n:Int):Int{ 5 | { 6 | let a:Int <- 1,t:Int <- 1,sum:Int <- 1 in { 7 | if n<3 then 8 | 1 9 | else { 10 | while 2test.output 2>&1 59 | 60 | #生成lexer,这里的OBJS都是.o,makefile会自动根据依赖项生成.o文件 61 | lexer: ${OBJS} 62 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o lexer 63 | 64 | #双缀规则,表示所有的.cc文件都必须编译成.o文件 65 | .cc.o: 66 | ${CC} ${CFLAGS} -c $< 67 | 68 | #处理cool-flex,生成词法分析程序的.cc文件 69 | cool-lex.cc: cool.flex 70 | ${FLEX} cool.flex 71 | 72 | #测试lexer 73 | dotest: lexer test.cl 74 | ./lexer test.cl 75 | 76 | ${LIBS}: 77 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 78 | 79 | # 以下的部分用来检查和copy本次实验需要的文件 80 | # 如果目录下有这些文件的话,不会被覆盖 81 | 82 | ${SRC} : 83 | ${CLASSDIR}/etc/copy-skel ${ASSN} ${SRC} 84 | 85 | ${LSRC} : 86 | ${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 87 | 88 | ${TSRC} ${CSRC}: 89 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 90 | 91 | ${HSRC}: 92 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 93 | 94 | #以下的部分执行清理,使用:例如,make clean 95 | 96 | submit-clean: ${OUTPUT} 97 | -rm -f *.s core ${OBJS} lexer cool-lex.cc *~ parser cgen semant 98 | 99 | clean : 100 | -rm -f ${OUTPUT} *.s core ${OBJS} lexer cool-lex.cc *~ parser cgen semant *.d *.cc 101 | 102 | clean-compile: 103 | @-rm -f core ${OBJS} cool-lex.cc ${LSRC} 104 | 105 | %.d: %.cc ${SRC} ${LSRC} 106 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 107 | 108 | -include ${CFIL:.cc=.d} 109 | 110 | 111 | -------------------------------------------------------------------------------- /assignments/PA2/cool.flex.SKEL: -------------------------------------------------------------------------------- 1 | /* 2 | * The scanner definition for COOL. 3 | */ 4 | 5 | /* 6 | * Stuff enclosed in %{ %} in the first section is copied verbatim to the 7 | * output, so headers and global definitions are placed here to be visible 8 | * to the code in the file. Don't remove anything that was here initially 9 | */ 10 | %{ 11 | #include 12 | #include 13 | #include 14 | 15 | /* The compiler assumes these identifiers. */ 16 | #define yylval cool_yylval 17 | #define yylex cool_yylex 18 | 19 | /* Max size of string constants */ 20 | #define MAX_STR_CONST 1025 21 | #define YY_NO_UNPUT /* keep g++ happy */ 22 | 23 | extern FILE *fin; /* we read from this file */ 24 | 25 | /* define YY_INPUT so we read from the FILE fin: 26 | * This change makes it possible to use this scanner in 27 | * the Cool compiler. 28 | */ 29 | #undef YY_INPUT 30 | #define YY_INPUT(buf,result,max_size) \ 31 | if ( (result = fread( (char*)buf, sizeof(char), max_size, fin)) < 0) \ 32 | YY_FATAL_ERROR( "read() in flex scanner failed"); 33 | 34 | char string_buf[MAX_STR_CONST]; /* to assemble string constants */ 35 | char *string_buf_ptr; 36 | 37 | extern int curr_lineno; 38 | extern int verbose_flag; 39 | 40 | extern YYSTYPE cool_yylval; 41 | 42 | /* 43 | * Add Your own definitions here 44 | */ 45 | 46 | %} 47 | 48 | /* 49 | * Define names for regular expressions here. 50 | */ 51 | 52 | /* For example, here is a simple regular expression that matches the 53 | * double-arrow '=>' used in case statements. */ 54 | DARROW => 55 | CLASS class 56 | 57 | 58 | %% 59 | 60 | /* 61 | * Nested comments 62 | */ 63 | 64 | 65 | /* 66 | * The multiple-character operators. 67 | */ 68 | 69 | /* Here is a rule that generates DARROW tokens. */ 70 | "=>" { return (DARROW); } 71 | /* This would do the same thing. It uses the regexp defined above: 72 | * {DARROW} { return (DARROW); } 73 | */ 74 | 75 | 76 | /* 77 | * Keywords are case-insensitive except for the values true and false, 78 | * which must begin with a lower-case letter. 79 | */ 80 | "class" {return (CLASS);} 81 | 82 | 83 | /* 84 | * String constants (C syntax) 85 | * Escape sequence \c is accepted for all characters c. Except for 86 | * \n \t \b \f, the result is c. 87 | * 88 | */ 89 | 90 | 91 | %% 92 | 93 | int yywrap() 94 | { return 1; } 95 | -------------------------------------------------------------------------------- /assignments/PA2/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /assignments/PA2/reference-lexer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/assignments/PA2/reference-lexer -------------------------------------------------------------------------------- /assignments/PA2/test.cl: -------------------------------------------------------------------------------- 1 | (* models one-dimensional cellular automaton on a circle of finite radius 2 | arrays are faked as Strings, 3 | X's respresent live cells, dots represent dead cells, 4 | no error checking is done *) 5 | class CellularAutomaton inherits IO { 6 | population_map : String; 7 | 8 | init(map : String) : SELF_TYPE { 9 | { 10 | population_map <- map; 11 | self; 12 | } 13 | }; 14 | 15 | print() : SELF_TYPE { 16 | { 17 | out_string(population_map.concat("\n")); 18 | self; 19 | } 20 | }; 21 | 22 | num_cells() : Int { 23 | population_map.length() 24 | }; 25 | 26 | cell(position : Int) : String { 27 | population_map.substr(position, 1) 28 | }; 29 | 30 | cell_left_neighbor(position : Int) : String { 31 | if position = 0 then 32 | cell(num_cells() - 1) 33 | else 34 | cell(position - 1) 35 | fi 36 | }; 37 | 38 | cell_right_neighbor(position : Int) : String { 39 | if position = num_cells() - 1 then 40 | cell(0) 41 | else 42 | cell(position + 1) 43 | fi 44 | }; 45 | 46 | (* a cell will live if exactly 1 of itself and it's immediate 47 | neighbors are alive *) 48 | cell_at_next_evolution(position : Int) : String { 49 | if (if cell(position) = "X" then 1 else 0 fi 50 | + if cell_left_neighbor(position) = "X" then 1 else 0 fi 51 | + if cell_right_neighbor(position) = "X" then 1 else 0 fi 52 | = 1) 53 | then 54 | "X" 55 | else 56 | '.' 57 | fi 58 | }; 59 | 60 | evolve() : SELF_TYPE { 61 | (let position : Int in 62 | (let num : Int <- num_cells[] in 63 | (let temp : String in 64 | { 65 | while position < num loop 66 | { 67 | temp <- temp.concat(cell_at_next_evolution(position)); 68 | position <- position + 1; 69 | } 70 | pool; 71 | population_map <- temp; 72 | self; 73 | } 74 | ) ) ) 75 | }; 76 | }; 77 | 78 | class Main { 79 | cells : CellularAutomaton; 80 | 81 | main() : SELF_TYPE { 82 | { 83 | cells <- (new CellularAutomaton).init(" X "); 84 | cells.print(); 85 | (let countdown : Int <- 20 in 86 | while countdown > 0 loop 87 | { 88 | cells.evolve(); 89 | cells.print(); 90 | countdown <- countdown - 1; 91 | 92 | pool 93 | ); (* end let countdown 94 | self; 95 | } 96 | }; 97 | }; 98 | -------------------------------------------------------------------------------- /assignments/PA2/test.cl.SKEL: -------------------------------------------------------------------------------- 1 | (* models one-dimensional cellular automaton on a circle of finite radius 2 | arrays are faked as Strings, 3 | X's respresent live cells, dots represent dead cells, 4 | no error checking is done *) 5 | class CellularAutomaton inherits IO { 6 | population_map : String; 7 | 8 | init(map : String) : SELF_TYPE { 9 | { 10 | population_map <- map; 11 | self; 12 | } 13 | }; 14 | 15 | print() : SELF_TYPE { 16 | { 17 | out_string(population_map.concat("\n")); 18 | self; 19 | } 20 | }; 21 | 22 | num_cells() : Int { 23 | population_map.length() 24 | }; 25 | 26 | cell(position : Int) : String { 27 | population_map.substr(position, 1) 28 | }; 29 | 30 | cell_left_neighbor(position : Int) : String { 31 | if position = 0 then 32 | cell(num_cells() - 1) 33 | else 34 | cell(position - 1) 35 | fi 36 | }; 37 | 38 | cell_right_neighbor(position : Int) : String { 39 | if position = num_cells() - 1 then 40 | cell(0) 41 | else 42 | cell(position + 1) 43 | fi 44 | }; 45 | 46 | (* a cell will live if exactly 1 of itself and it's immediate 47 | neighbors are alive *) 48 | cell_at_next_evolution(position : Int) : String { 49 | if (if cell(position) = "X" then 1 else 0 fi 50 | + if cell_left_neighbor(position) = "X" then 1 else 0 fi 51 | + if cell_right_neighbor(position) = "X" then 1 else 0 fi 52 | = 1) 53 | then 54 | "X" 55 | else 56 | '.' 57 | fi 58 | }; 59 | 60 | evolve() : SELF_TYPE { 61 | (let position : Int in 62 | (let num : Int <- num_cells[] in 63 | (let temp : String in 64 | { 65 | while position < num loop 66 | { 67 | temp <- temp.concat(cell_at_next_evolution(position)); 68 | position <- position + 1; 69 | } 70 | pool; 71 | population_map <- temp; 72 | self; 73 | } 74 | ) ) ) 75 | }; 76 | }; 77 | 78 | class Main { 79 | cells : CellularAutomaton; 80 | 81 | main() : SELF_TYPE { 82 | { 83 | cells <- (new CellularAutomaton).init(" X "); 84 | cells.print(); 85 | (let countdown : Int <- 20 in 86 | while countdown > 0 loop 87 | { 88 | cells.evolve(); 89 | cells.print(); 90 | countdown <- countdown - 1; 91 | 92 | pool 93 | ); (* end let countdown 94 | self; 95 | } 96 | }; 97 | }; 98 | -------------------------------------------------------------------------------- /assignments/PA3/Makefile: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # 编辑这里 3 | # 将CLASSDIR设置成你电脑上cool项目所在的位置 4 | CLASSDIR= ~/cool 5 | ####################################### 6 | 7 | #作业序号,第三次作业 8 | ASSN = 3 9 | #没有用 10 | CLASS= xjtucompiler 11 | #链接库,暂时不用管 12 | LIB= -L/usr/sww/lib 13 | 14 | #Makefile依赖的文件列表 15 | SRC= cool.y cool-tree.handcode.h good.cl bad.cl README 16 | #生成parser依赖的源文件列表 17 | CSRC= parser-phase.cc utilities.cc stringtab.cc dumptype.cc \ 18 | tree.cc cool-tree.cc tokens-lex.cc handle_flags.cc 19 | #需要链接到当前目录的文件 20 | # TSRC= myparser mycoolc cool-tree.aps ref-parser 21 | TSRC= myparser cool-tree.aps ref-parser 22 | 23 | #bison要生成的源文件和头文件 24 | CGEN= cool-parse.cc 25 | HGEN= cool-parse.h 26 | # LIBS= lexer semant cgen 27 | 28 | #将所有源文件都连接起来 29 | LIBS= lexer semant 30 | CFIL= ${CSRC} ${CGEN} 31 | 32 | #依赖的头文件 33 | HFIL= cool-tree.h cool-tree.handcode.h 34 | LSRC= Makefile 35 | 36 | #将.cc全部替换成.o后缀 37 | OBJS= ${CFIL:.cc=.o} 38 | #将结果输出到文档中去 39 | OUTPUT= good.output bad.output 40 | 41 | #依赖的头文件和部分源文件分别存放在include和src目录下 42 | CPPINCLUDE= -I. -I ${CLASSDIR}/include/PA${ASSN} -I ${CLASSDIR}/src/PA${ASSN} 43 | 44 | #bison的编译选项 45 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 46 | 47 | CC=g++ 48 | CFLAGS=-g -Wall ${CPPINCLUDE} 49 | FLEX=flex ${FFLAGS} 50 | BISON= bison ${BFLAGS} 51 | DEPEND = ${CC} -MM ${CPPINCLUDE} 52 | 53 | default: source parser 54 | 55 | source: ${SRC} ${TSRC} ${LSRC} ${LIBS} lsource 56 | 57 | lsource: ${LSRC} 58 | 59 | ${OUTPUT}: parser good.cl bad.cl 60 | @rm -f ${OUTPUT} 61 | ./myparser good.cl >good.output 2>&1 62 | -./myparser bad.cl >bad.output 2>&1 63 | 64 | parser: ${OBJS} 65 | echo "start parser" 66 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o parser 67 | 68 | .cc.o: 69 | ${CC} ${CFLAGS} -c $< 70 | 71 | cool-parse.cc cool-parse.h: cool.y 72 | ${BISON} cool.y 73 | mv -f cool.tab.c cool-parse.cc 74 | 75 | dotest: myparser good.cl 76 | @echo "\nRunning parser on good.cl\n" 77 | @echo "\nRunning parser on bad.cl\n" 78 | 79 | ${LIBS}: 80 | ln -s ${CLASSDIR}/bin/reference-$@ $@ 81 | #sg: just symlink to the architecture independant refernce-* shell scripts 82 | # ${CLASSDIR}/etc/link-object ${ASSN} $@ 83 | 84 | # These dependencies allow you to get the starting files for 85 | # the assignment. They will not overwrite a file you already have. 86 | 87 | ${SRC} : 88 | -${CLASSDIR}/etc/copy-skel ${ASSN} ${SRC} 89 | 90 | ${LSRC} : 91 | -${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 92 | 93 | ${TSRC} ${CSRC}: 94 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 95 | 96 | ${HSRC}: 97 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 98 | 99 | submit-clean: ${OUTPUT} 100 | -rm -f *.s core ${OBJS} ${CGEN} ${HGEN} *~ parser 101 | 102 | clean : 103 | -rm -f ${OUTPUT} *.s core ${OBJS} ${CGEN} ${HGEN} parser *~ *.a *.o *.cc *.d 104 | 105 | clean-compile: 106 | @-rm -f core ${OBJS} ${CGEN} ${HGEN} ${LSRC} 107 | 108 | %.d: %.cc ${LSRC} 109 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 110 | 111 | -include ${CFIL:.cc=.d} 112 | 113 | task5: 114 | # e.g. make task5 file=tmp 115 | # ATTENTION: 116 | # 在${file}.l 中,请勿忘记添加"${file}.tab.h"头文件 117 | 118 | # flex 识别token 119 | flex -o ${file}.yy.c ${file}.l 120 | # bison生成.tab.h 定义token 121 | bison -d ${file}.y 122 | # bison生成.tab.c 123 | bison -o ${file}.tab.c ${file}.y 124 | # 生成可执行文件 125 | gcc -o ${file}.out ${file}.yy.c ${file}.tab.c 126 | -------------------------------------------------------------------------------- /assignments/PA3/bad.cl: -------------------------------------------------------------------------------- 1 | 2 | (* 3 | * execute "coolc bad.cl" to see the error messages that the coolc parser 4 | * generates 5 | * 6 | * execute "myparser bad.cl" to see the error messages that your parser 7 | * generates 8 | *) 9 | 10 | (* no error *) 11 | class A { 12 | }; 13 | 14 | (* error: b is not a type identifier *) 15 | Class b inherits A { 16 | }; 17 | 18 | (* error: a is not a type identifier *) 19 | Class C inherits a { 20 | }; 21 | 22 | (* error: keyword inherits is misspelled *) 23 | Class D inherts A { 24 | }; 25 | 26 | (* error: closing brace is missing *) 27 | Class E inherits A { 28 | ; 29 | 30 | class Main inherits IO { 31 | main():Int { 32 | }; 33 | }; 34 | -------------------------------------------------------------------------------- /assignments/PA3/bad.cl.SKEL: -------------------------------------------------------------------------------- 1 | 2 | (* 3 | * execute "coolc bad.cl" to see the error messages that the coolc parser 4 | * generates 5 | * 6 | * execute "myparser bad.cl" to see the error messages that your parser 7 | * generates 8 | *) 9 | 10 | (* no error *) 11 | class A { 12 | }; 13 | 14 | (* error: b is not a type identifier *) 15 | Class b inherits A { 16 | }; 17 | 18 | (* error: a is not a type identifier *) 19 | Class C inherits a { 20 | }; 21 | 22 | (* error: keyword inherits is misspelled *) 23 | Class D inherts A { 24 | }; 25 | 26 | (* error: closing brace is missing *) 27 | Class E inherits A { 28 | ; 29 | 30 | -------------------------------------------------------------------------------- /assignments/PA3/cool-tree.aps: -------------------------------------------------------------------------------- 1 | /home/wangyang/cool/src/PA3/cool-tree.aps -------------------------------------------------------------------------------- /assignments/PA3/cool-tree.handcode.h: -------------------------------------------------------------------------------- 1 | // 2 | // The following include files must come first. 3 | 4 | #ifndef COOL_TREE_HANDCODE_H 5 | #define COOL_TREE_HANDCODE_H 6 | 7 | #include 8 | #include "tree.h" 9 | #include "cool.h" 10 | #include "stringtab.h" 11 | 12 | #define yylineno curr_lineno; 13 | extern int yylineno; 14 | 15 | inline Boolean copy_Boolean(Boolean b) {return b; } 16 | inline void assert_Boolean(Boolean) {} 17 | inline void dump_Boolean(std::ostream& stream, int padding, Boolean b) 18 | { stream << pad(padding) << (int) b << "\n"; } 19 | 20 | void dump_Symbol(std::ostream& stream, int padding, Symbol b); 21 | void assert_Symbol(Symbol b); 22 | Symbol copy_Symbol(Symbol b); 23 | 24 | class Program_class; 25 | typedef Program_class *Program; 26 | class Class__class; 27 | typedef Class__class *Class_; 28 | class Feature_class; 29 | typedef Feature_class *Feature; 30 | class Formal_class; 31 | typedef Formal_class *Formal; 32 | class Expression_class; 33 | typedef Expression_class *Expression; 34 | class Case_class; 35 | typedef Case_class *Case; 36 | 37 | typedef list_node Classes_class; 38 | typedef Classes_class *Classes; 39 | typedef list_node Features_class; 40 | typedef Features_class *Features; 41 | typedef list_node Formals_class; 42 | typedef Formals_class *Formals; 43 | typedef list_node Expressions_class; 44 | typedef Expressions_class *Expressions; 45 | typedef list_node Cases_class; 46 | typedef Cases_class *Cases; 47 | 48 | #define Program_EXTRAS \ 49 | virtual void dump_with_types(std::ostream&, int) = 0; 50 | 51 | 52 | 53 | #define program_EXTRAS \ 54 | void dump_with_types(std::ostream&, int); 55 | 56 | #define Class__EXTRAS \ 57 | virtual Symbol get_filename() = 0; \ 58 | virtual void dump_with_types(std::ostream&,int) = 0; 59 | 60 | 61 | #define class__EXTRAS \ 62 | Symbol get_filename() { return filename; } \ 63 | void dump_with_types(std::ostream&,int); 64 | 65 | 66 | #define Feature_EXTRAS \ 67 | virtual void dump_with_types(std::ostream&,int) = 0; 68 | 69 | 70 | #define Feature_SHARED_EXTRAS \ 71 | void dump_with_types(std::ostream&,int); 72 | 73 | 74 | 75 | 76 | 77 | #define Formal_EXTRAS \ 78 | virtual void dump_with_types(std::ostream&,int) = 0; 79 | 80 | 81 | #define formal_EXTRAS \ 82 | void dump_with_types(std::ostream&,int); 83 | 84 | 85 | #define Case_EXTRAS \ 86 | virtual void dump_with_types(std::ostream& ,int) = 0; 87 | 88 | 89 | #define branch_EXTRAS \ 90 | void dump_with_types(std::ostream& ,int); 91 | 92 | 93 | #define Expression_EXTRAS \ 94 | Symbol type; \ 95 | Symbol get_type() { return type; } \ 96 | Expression set_type(Symbol s) { type = s; return this; } \ 97 | virtual void dump_with_types(std::ostream&,int) = 0; \ 98 | void dump_type(std::ostream&, int); \ 99 | Expression_class() { type = (Symbol) NULL; } 100 | 101 | 102 | 103 | #define Expression_SHARED_EXTRAS \ 104 | void dump_with_types(std::ostream&,int); 105 | 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /assignments/PA3/cool-tree.handcode.h.SKEL: -------------------------------------------------------------------------------- 1 | // 2 | // The following include files must come first. 3 | 4 | #ifndef COOL_TREE_HANDCODE_H 5 | #define COOL_TREE_HANDCODE_H 6 | 7 | #include 8 | #include "tree.h" 9 | #include "cool.h" 10 | #include "stringtab.h" 11 | #define yylineno curr_lineno; 12 | extern int yylineno; 13 | 14 | inline Boolean copy_Boolean(Boolean b) {return b; } 15 | inline void assert_Boolean(Boolean) {} 16 | inline void dump_Boolean(ostream& stream, int padding, Boolean b) 17 | { stream << pad(padding) << (int) b << "\n"; } 18 | 19 | void dump_Symbol(ostream& stream, int padding, Symbol b); 20 | void assert_Symbol(Symbol b); 21 | Symbol copy_Symbol(Symbol b); 22 | 23 | class Program_class; 24 | typedef Program_class *Program; 25 | class Class__class; 26 | typedef Class__class *Class_; 27 | class Feature_class; 28 | typedef Feature_class *Feature; 29 | class Formal_class; 30 | typedef Formal_class *Formal; 31 | class Expression_class; 32 | typedef Expression_class *Expression; 33 | class Case_class; 34 | typedef Case_class *Case; 35 | 36 | typedef list_node Classes_class; 37 | typedef Classes_class *Classes; 38 | typedef list_node Features_class; 39 | typedef Features_class *Features; 40 | typedef list_node Formals_class; 41 | typedef Formals_class *Formals; 42 | typedef list_node Expressions_class; 43 | typedef Expressions_class *Expressions; 44 | typedef list_node Cases_class; 45 | typedef Cases_class *Cases; 46 | 47 | #define Program_EXTRAS \ 48 | virtual void dump_with_types(ostream&, int) = 0; 49 | 50 | 51 | 52 | #define program_EXTRAS \ 53 | void dump_with_types(ostream&, int); 54 | 55 | #define Class__EXTRAS \ 56 | virtual Symbol get_filename() = 0; \ 57 | virtual void dump_with_types(ostream&,int) = 0; 58 | 59 | 60 | #define class__EXTRAS \ 61 | Symbol get_filename() { return filename; } \ 62 | void dump_with_types(ostream&,int); 63 | 64 | 65 | #define Feature_EXTRAS \ 66 | virtual void dump_with_types(ostream&,int) = 0; 67 | 68 | 69 | #define Feature_SHARED_EXTRAS \ 70 | void dump_with_types(ostream&,int); 71 | 72 | 73 | 74 | 75 | 76 | #define Formal_EXTRAS \ 77 | virtual void dump_with_types(ostream&,int) = 0; 78 | 79 | 80 | #define formal_EXTRAS \ 81 | void dump_with_types(ostream&,int); 82 | 83 | 84 | #define Case_EXTRAS \ 85 | virtual void dump_with_types(ostream& ,int) = 0; 86 | 87 | 88 | #define branch_EXTRAS \ 89 | void dump_with_types(ostream& ,int); 90 | 91 | 92 | #define Expression_EXTRAS \ 93 | Symbol type; \ 94 | Symbol get_type() { return type; } \ 95 | Expression set_type(Symbol s) { type = s; return this; } \ 96 | virtual void dump_with_types(ostream&,int) = 0; \ 97 | void dump_type(ostream&, int); \ 98 | Expression_class() { type = (Symbol) NULL; } 99 | 100 | 101 | 102 | #define Expression_SHARED_EXTRAS \ 103 | void dump_with_types(ostream&,int); 104 | 105 | 106 | #endif 107 | -------------------------------------------------------------------------------- /assignments/PA3/good.cl: -------------------------------------------------------------------------------- 1 | class A { 2 | }; 3 | 4 | Class BB__ inherits A { 5 | }; 6 | -------------------------------------------------------------------------------- /assignments/PA3/good.cl.SKEL: -------------------------------------------------------------------------------- 1 | class A { 2 | }; 3 | 4 | Class BB__ inherits A { 5 | }; 6 | -------------------------------------------------------------------------------- /assignments/PA3/myparser: -------------------------------------------------------------------------------- 1 | ./lexer $* | ./parser 2 | -------------------------------------------------------------------------------- /assignments/PA3/task1.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 识别整数 加减乘除 括号 4 | */ 5 | #include "task1.tab.h" 6 | %} 7 | 8 | %% 9 | 10 | [0-9]+ { yylval = atoi(yytext); return T_NUM; } 11 | [-/+*()\n] { return yytext[0]; } 12 | . { return 0; /* end when meet everything else */ } 13 | 14 | %% 15 | 16 | int yywrap(){ 17 | return 1; 18 | } -------------------------------------------------------------------------------- /assignments/PA3/task1.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | void yyerror(const char* str){}; 4 | %} 5 | 6 | %token T_NUM 7 | 8 | %left '+' '-' 9 | %left '*' '/' 10 | %right uminus 11 | 12 | %% 13 | S : S E '\n' { printf("ans = %d\n", $2); } 14 | | /* empty */ { /* empty */ } 15 | ; 16 | 17 | E : E '+' E { $$ = $1 + $3; } 18 | | E '-' E { $$ = $1 - $3; } 19 | | E '*' E { $$ = $1 * $3; } 20 | | E '/' E { $$ = $1 / $3; } 21 | | '-' E %prec uminus { $$ = -$2; } 22 | | T_NUM { $$ = $1; } 23 | | '(' E ')' { $$ = $2; } 24 | ; 25 | 26 | %% 27 | int main() { 28 | return yyparse(); 29 | } 30 | -------------------------------------------------------------------------------- /assignments/PA3/task1p.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 识别double 加减乘除 括号 4 | */ 5 | #define YYSTYPE double 6 | #include "task1p.tab.h" 7 | %} 8 | 9 | %% 10 | 11 | [0-9]+[.][0-9]+ {yylval = atof(yytext); return T_NUM; } 12 | [0-9]+ {yylval = atof(yytext); return T_NUM; } 13 | [-/+*()\n] { return yytext[0]; } 14 | 15 | %% 16 | 17 | int yywrap(){ 18 | return 1; 19 | } -------------------------------------------------------------------------------- /assignments/PA3/task1p.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #define YYSTYPE double 3 | #include 4 | #include 5 | #include 6 | void yyerror(const char* str){}; 7 | %} 8 | %token T_NUM 9 | 10 | %left '+' '-' 11 | %left '*' '/' 12 | %right uminus 13 | 14 | %% 15 | S : S E '\n' { printf ("ans = %f\n", $2); } 16 | | /* empty */ { /* empty */ } 17 | ; 18 | 19 | E : E '+' E { $$ = $1 + $3;} 20 | | E '-' E { $$ = $1 - $3; } 21 | | E '*' E { $$ = $1 * $3; } 22 | | E '/' E { $$ = $1 / $3; } 23 | | '-' E %prec uminus { $$ = -$2; } 24 | | T_NUM { $$ = $1;} 25 | | '(' E ')' { $$ = $2; } 26 | ; 27 | 28 | %% 29 | int main() { 30 | return yyparse(); 31 | } 32 | -------------------------------------------------------------------------------- /assignments/PA3/task2.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 识别布尔识别 4 | */ 5 | #include "task2.tab.h" 6 | %} 7 | 8 | %% 9 | 10 | true { return T_TRUE; } 11 | false {return T_FALSE; } 12 | "||" { return T_OR; } 13 | "&&" { return T_AND; } 14 | "!" {return T_NOT;} 15 | [()\n] { return yytext[0]; } 16 | [ ] {/* 忽略空格 */} 17 | %% 18 | 19 | int yywrap(){ 20 | return 1; 21 | } -------------------------------------------------------------------------------- /assignments/PA3/task2.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | void yyerror(const char* str){ 4 | }; 5 | %} 6 | %token T_FALSE T_TRUE T_AND T_OR T_NOT 7 | 8 | %right uminus 9 | 10 | %% 11 | S : S E '\n' { if($2==1){printf("ans = true\n");}else{printf("ans = false\n");}} 12 | | /* empty */ { /* empty */ } 13 | ; 14 | 15 | E : E T_AND E { $$ = $1 * $3;} 16 | | E T_OR E { $$ = ($1 + $3>0)?1:0; } 17 | | T_NOT E %prec uminus { $$ = $2 ^ 1; } 18 | | T_FALSE { $$ = 0;} 19 | | T_TRUE { $$ = 1;} 20 | | '(' E ')' { $$ = $2; } 21 | ; 22 | 23 | %% 24 | int main() { 25 | return yyparse(); 26 | } 27 | -------------------------------------------------------------------------------- /assignments/PA3/task3.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | int regs[26]; 4 | void yyerror(char *s); 5 | int yylex(); 6 | %} 7 | 8 | %token LETTER DIGIT 9 | 10 | %right '=' 11 | %left '-' 12 | %left '*' 13 | 14 | %% 15 | S : S E '\n' { printf("ans = %d\n", $2); } 16 | | /* empty */ { /* empty */ } 17 | ; 18 | 19 | E : E '-' E { $$ = $1 - $3; } 20 | | E '*' E { $$ = $1 * $3; } 21 | | DIGIT { $$ = $1; } 22 | | LETTER { $$ = regs[$1]; } 23 | | '(' E ')' { $$ = $2; } 24 | | LETTER '=' E { regs[$1] = $3; $$ = $3; } 25 | ; 26 | 27 | %% 28 | 29 | 30 | int yylex() { /* lexical analysis routine */ 31 | int c; 32 | do{ 33 | c = getchar(); 34 | }while(c==' '); 35 | 36 | if(c>='a'&&c<='z'){ 37 | yylval=c-'a';return LETTER; 38 | }else if(c>='A'&&c<='Z'){ 39 | yylval=c-'A';return LETTER; 40 | }else if(c>='0'&&c<='9'){ 41 | yylval=c-'0';return DIGIT; 42 | } 43 | 44 | return c; 45 | } 46 | 47 | void yyerror(char *s) 48 | { 49 | fprintf(stderr,"%s\n",s); 50 | } 51 | 52 | int main() { 53 | yyparse(); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /assignments/PA3/task4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/assignments/PA3/task4 -------------------------------------------------------------------------------- /assignments/PA3/task4.y: -------------------------------------------------------------------------------- 1 | %{ 2 | // 加减乘除括号 一位数 a-z符号 3 | #include 4 | int regs[26]; 5 | void yyerror(char *s); 6 | int yylex(); 7 | %} 8 | 9 | %token LETTER DIGIT 10 | 11 | %right '=' 12 | %left '-' '+' 13 | %left '*' '/' 14 | %right uminus 15 | 16 | %% 17 | S : S E '\n' { printf("ans = %d\n", $2); } 18 | | /* empty */ { /* empty */ } 19 | ; 20 | 21 | E : E '+' E { $$ = $1 + $3;} 22 | | E '-' E { $$ = $1 - $3; } 23 | | E '*' E { $$ = $1 * $3; } 24 | | E '/' E { $$ = $1 / $3; } 25 | | LETTER { $$ = regs[$1]; } 26 | | '-' E %prec uminus { $$ = -$2; } 27 | | DIGIT { $$ = $1;} 28 | | '(' E ')' { $$ = $2; } 29 | | LETTER '=' E { regs[$1] = $3; $$ = $3; } 30 | ; 31 | 32 | 33 | %% 34 | 35 | 36 | int yylex() { /* lexical analysis routine */ 37 | int c; 38 | do{ 39 | c = getchar(); 40 | }while(c==' '); 41 | 42 | if(c>='a'&&c<='z'){ 43 | yylval=c-'a';return LETTER; 44 | }else if(c>='A'&&c<='Z'){ 45 | yylval=c-'A';return LETTER; 46 | }else if(c>='0'&&c<='9'){ 47 | yylval=c-'0';return DIGIT; 48 | } 49 | return c; 50 | } 51 | 52 | void yyerror(char *s) 53 | { 54 | fprintf(stderr,"%s\n",s); 55 | } 56 | 57 | int main() { 58 | yyparse(); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /assignments/PA3/task5.y: -------------------------------------------------------------------------------- 1 | %{ 2 | // 加减乘除括号 多位数 a-z符号 存在空格问题 需要使用lex解决 3 | #include 4 | int regs[26]; 5 | void yyerror(char *s); 6 | int yylex(); 7 | %} 8 | 9 | %token DIGIT ID 10 | 11 | %left '+' '-' 12 | %left '*' '/' 13 | %right uminus 14 | 15 | %% 16 | S : S STAT '\n' { printf("ans = %d\n", $2); } 17 | | /* empty */ { /* empty */ } 18 | ; 19 | 20 | STAT: ID '=' E { regs[$1] = $3; $$ = $3; } 21 | | E { $$ = $1;} 22 | ; 23 | 24 | E : E '+' E { $$ = $1 + $3;} 25 | | E '-' E { $$ = $1 - $3; } 26 | | E '*' E { $$ = $1 * $3; } 27 | | E '/' E { $$ = $1 / $3; } 28 | | ID { $$ = regs[$1]; } 29 | | '-' E %prec uminus { $$ = -$2; } 30 | | number { $$ = $1;} 31 | | '(' E ')' { $$ = $2; } 32 | | error { yyerror("expr: error"); } 33 | ; 34 | 35 | number 36 | : DIGIT { $$ = $1; } 37 | | number DIGIT { $$ = $1*10 + $2;} 38 | 39 | %% 40 | 41 | int yylex() { /* lexical analysis routine */ 42 | int c; 43 | int t; 44 | do{ 45 | c = getchar(); 46 | }while(c==' '); 47 | 48 | if(c>='a'&&c<='z'){ 49 | yylval = c - 'a';return ID; 50 | }else if(c>='A'&&c<='Z'){ 51 | yylval = c -'A';return ID; 52 | }else if(c>='0'&&c<='9'){ 53 | yylval = c-'0'; 54 | return DIGIT; 55 | } 56 | // 必须加 57 | return c; 58 | } 59 | 60 | void yyerror(char *s) 61 | { 62 | fprintf(stderr,"%s\n",s); 63 | } 64 | 65 | int main() { 66 | yyparse(); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /assignments/PA4/Makefile: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Edit this! 3 | # Set CLASSDIR to the location of the cool package. 4 | # e.g. the makefile needs to access ${CLASSDIR}/bin 5 | CLASSDIR= ~/cool 6 | ####################################### 7 | 8 | ASSN = 4 9 | CLASS= cs164 10 | AR= gar 11 | ARCHIVE_NEW= -cr 12 | LIB= -L/usr/sww/lib -lfl 13 | RANLIB= gar -qs 14 | 15 | SRC= semant.cc semant.h cool-tree.h cool-tree.handcode.h good.cl bad.cl README checkpoint 16 | CSRC= semant-phase.cc symtab_example.cc handle_flags.cc ast-lex.cc ast-parse.cc utilities.cc stringtab.cc dumptype.cc tree.cc cool-tree.cc 17 | TSRC= mycoolc mysemant cool-tree.aps ref-semant 18 | CGEN= 19 | HGEN= 20 | LIBS= lexer parser cgen 21 | CFIL= semant.cc ${CSRC} ${CGEN} 22 | LSRC= Makefile 23 | OBJS= ${CFIL:.cc=.o} 24 | OUTPUT= good.output bad.output 25 | 26 | 27 | CPPINCLUDE= -I. -I ${CLASSDIR}/include/PA${ASSN} -I ${CLASSDIR}/src/PA${ASSN} 28 | 29 | FFLAGS = -d8 -ocool-lex.cc 30 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 31 | ASTBFLAGS = -d -v -y -b ast --debug -p ast_yy 32 | 33 | CC=g++ 34 | CFLAGS=-g -Wall -Wno-unused ${CPPINCLUDE} -DDEBUG -Wno-deprecated 35 | FLEX=flex ${FFLAGS} 36 | BISON= bison ${BFLAGS} 37 | DEPEND = ${CC} -MM ${CPPINCLUDE} 38 | 39 | default: source semant 40 | 41 | source: ${SRC} ${TSRC} ${LIBS} lsource 42 | 43 | lsource: ${LSRC} 44 | 45 | ${OUTPUT}: semant 46 | @rm -f ${OUTPUT} 47 | ./mysemant good.cl >good.output 2>&1 48 | -./mysemant bad.cl >bad.output 2>&1 49 | 50 | compile: semant change-prot 51 | 52 | change-prot: 53 | @-chmod 660 ${SRC} ${OUTPUT} 54 | 55 | SEMANT_OBJS := ${filter-out symtab_example.o,${OBJS}} 56 | 57 | semant: ${SEMANT_OBJS} lexer parser cgen 58 | ${CC} ${CFLAGS} ${SEMANT_OBJS} ${LIB} -o semant 59 | 60 | symtab_example: symtab_example.cc 61 | ${CC} ${CFLAGS} symtab_example.cc ${LIB} -o symtab_example 62 | 63 | .cc.o: 64 | ${CC} ${CFLAGS} -c $< 65 | 66 | dotest: semant good.cl bad.cl 67 | @echo "\nRunning semantic checker on good.cl\n" 68 | -./mysemant good.cl 69 | @echo "\nRunning semantic checker on bad.cl\n" 70 | -./mysemant bad.cl 71 | 72 | ${LIBS}: 73 | ln -s ${CLASSDIR}/bin/reference-$@ $@ 74 | # ${CLASSDIR}/etc/link-object ${ASSN} $@ 75 | 76 | # These dependencies allow you to get the starting files for 77 | # the assignment. They will not overwrite a file you already have. 78 | 79 | ${SRC} : 80 | -${CLASSDIR}/etc/copy ${ASSN} ${SRC} 81 | 82 | ${LSRC} : 83 | -${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 84 | 85 | ${TSRC} ${CSRC}: 86 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 87 | 88 | ${HSRC}: 89 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 90 | 91 | submit-clean: ${OUTPUT} 92 | -rm -f *.s core ${OBJS} ${CGEN} ${HGEN} *~ semant symtab_example 93 | 94 | clean : 95 | -rm -f ${OUTPUT} *.s core ${OBJS} semant symtab_example *~ *.a *.o 96 | 97 | clean-compile: 98 | @-rm -f core ${OBJS} ${LSRC} 99 | 100 | %.d: %.cc ${SRC} 101 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 102 | 103 | -include ${CFIL:.cc=.d} 104 | 105 | -------------------------------------------------------------------------------- /assignments/PA4/bad.cl: -------------------------------------------------------------------------------- 1 | class C { 2 | a : Int; 3 | b : Bool; 4 | init(x : Int, y : Bool) : C { 5 | { 6 | a <- x; 7 | b <- y; 8 | self; 9 | } 10 | }; 11 | }; 12 | 13 | Class Main { 14 | main():C { 15 | { 16 | (new C).init(1,1); 17 | (new C).init(1,true,3); 18 | (new C).iinit(1,true); 19 | (new C); 20 | } 21 | }; 22 | }; 23 | -------------------------------------------------------------------------------- /assignments/PA4/checkpoint: -------------------------------------------------------------------------------- 1 | Put your answers to the checkpoint questions in this file. 2 | 3 | Submit it by running "submit PA4-checkpoint". 4 | 5 | -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 6 | -------------------------------------------------------------------------------- /assignments/PA4/good.cl: -------------------------------------------------------------------------------- 1 | class C { 2 | a : Int; 3 | b : Bool; 4 | init(x : Int, y : Bool) : C { 5 | { 6 | a <- x; 7 | b <- y; 8 | self; 9 | } 10 | }; 11 | }; 12 | 13 | Class Main { 14 | main():C { 15 | (new C).init(1,true) 16 | }; 17 | }; 18 | -------------------------------------------------------------------------------- /assignments/PA4/semant.h: -------------------------------------------------------------------------------- 1 | #ifndef SEMANT_H_ 2 | #define SEMANT_H_ 3 | 4 | #include 5 | #include 6 | #include "cool-tree.h" 7 | #include "stringtab.h" 8 | #include "symtab.h" 9 | #include "list.h" 10 | 11 | #define TRUE 1 12 | #define FALSE 0 13 | 14 | class ClassTable; 15 | typedef ClassTable *ClassTableP; 16 | 17 | // This is a structure that may be used to contain the semantic 18 | // information such as the inheritance graph. You may use it or not as 19 | // you like: it is only here to provide a container for the supplied 20 | // methods. 21 | 22 | class ClassTable { 23 | private: 24 | int semant_errors; 25 | void install_basic_classes(); 26 | std::ostream& error_stream; 27 | 28 | public: 29 | ClassTable(Classes); 30 | int errors() { return semant_errors; } 31 | std::ostream& semant_error(); 32 | std::ostream& semant_error(Class_ c); 33 | std::ostream& semant_error(Symbol filename, tree_node *t); 34 | }; 35 | 36 | 37 | #endif 38 | 39 | -------------------------------------------------------------------------------- /assignments/PA5/Makefile: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Edit this! 3 | # Set CLASSDIR to the location of the cool package. 4 | # e.g. the makefile needs to access ${CLASSDIR}/bin 5 | CLASSDIR= ~/cool 6 | ####################################### 7 | 8 | 9 | ASSN = 5 10 | CLASS= cs164 11 | LIB= -L/usr/sww/lib -lfl 12 | AR= gar 13 | ARCHIVE_NEW= -cr 14 | RANLIB= gar -qs 15 | 16 | SRC= cgen.cc cgen.h cgen_supp.cc cool-tree.h cool-tree.handcode.h emit.h example.cl README checkpoint 17 | CSRC= cgen-phase.cc utilities.cc stringtab.cc dumptype.cc tree.cc cool-tree.cc ast-lex.cc ast-parse.cc handle_flags.cc 18 | TSRC= mycoolc 19 | CGEN= 20 | HGEN= 21 | LIBS= lexer parser semant 22 | CFIL= cgen.cc cgen_supp.cc ${CSRC} ${CGEN} 23 | LSRC= Makefile 24 | OBJS= ${CFIL:.cc=.o} 25 | OUTPUT= good.output bad.output 26 | 27 | 28 | CPPINCLUDE= -I. -I ${CLASSDIR}/include/PA${ASSN} -I ${CLASSDIR}/src/PA${ASSN} 29 | 30 | 31 | FFLAGS = -d8 -ocool-lex.cc 32 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 33 | 34 | CC=g++ 35 | CFLAGS=-g -Wall -Wno-unused ${CPPINCLUDE} -DDEBUG 36 | FLEX=flex ${FFLAGS} 37 | BISON= bison ${BFLAGS} 38 | DEPEND = ${CC} -MM ${CPPINCLUDE} 39 | 40 | default: source cgen 41 | 42 | source: ${SRC} ${TSRC} ${LIBS} lsource 43 | 44 | lsource: ${LSRC} 45 | 46 | # 47 | # if make turnin says "turnin is up to date.", and you want to turnin 48 | # anyway, you can delete the file 'turnin', and do make turnin again. 49 | # 50 | turnin : ${SRC} ${OUTPUT} turnin-clean 51 | cd ..; ${CLASSDIR}/bin/turnin ${CLASS} PA${ASSN} 52 | 53 | turnin-clean: 54 | @rm -f cgen ${OBJS} *.a *.o *~ *.d 55 | 56 | ${OUTPUT}: cgen 57 | @rm -f ${OUTPUT} 58 | ./mycoolc example.cl >example.output 2>&1 59 | 60 | compile: cgen change-prot 61 | 62 | change-prot: 63 | @-chmod 660 ${SRC} ${OUTPUT} 64 | 65 | cgen: ${OBJS} parser semant 66 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o cgen 67 | 68 | .cc.o: 69 | ${CC} ${CFLAGS} -c $< 70 | 71 | dotest: cgen example.cl 72 | @echo "\nRunning code generator on example.cl\n" 73 | -./mycoolc example.cl 74 | 75 | ${LIBS}: 76 | ln -s ${CLASSDIR}/bin/reference-$@ $@ 77 | 78 | 79 | # These dependencies allow you to get the starting files for 80 | # the assignment. They will not overwrite a file you already have. 81 | 82 | ${SRC} : 83 | -${CLASSDIR}/etc/copy ${ASSN} ${SRC} 84 | 85 | ${LSRC} : 86 | -${CLASSDIR}/etc/link-shared ${ASSN} ${LSRC} 87 | 88 | ${TSRC} ${CSRC}: 89 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 90 | 91 | ${HSRC}: 92 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 93 | 94 | clean : 95 | -rm -f ${OUTPUT} *.s core ${OBJS} cgen *~ *.a *.o 96 | 97 | clean-compile: 98 | @-rm -f core ${OBJS} ${LSRC} 99 | 100 | %.d: %.cc ${SRC} 101 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 102 | 103 | -include ${CFIL:.cc=.d} 104 | 105 | 106 | -------------------------------------------------------------------------------- /assignments/PA5/cgen.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "emit.h" 4 | #include "cool-tree.h" 5 | #include "symtab.h" 6 | 7 | enum Basicness {Basic, NotBasic}; 8 | #define TRUE 1 9 | #define FALSE 0 10 | 11 | class CgenClassTable; 12 | typedef CgenClassTable *CgenClassTableP; 13 | 14 | class CgenNode; 15 | typedef CgenNode *CgenNodeP; 16 | 17 | class CgenClassTable : public SymbolTable { 18 | private: 19 | List *nds; 20 | ostream& str; 21 | int stringclasstag; 22 | int intclasstag; 23 | int boolclasstag; 24 | 25 | 26 | // The following methods emit code for 27 | // constants and global declarations. 28 | 29 | void code_global_data(); 30 | void code_global_text(); 31 | void code_bools(int); 32 | void code_select_gc(); 33 | void code_constants(); 34 | 35 | // The following creates an inheritance graph from 36 | // a list of classes. The graph is implemented as 37 | // a tree of `CgenNode', and class names are placed 38 | // in the base class symbol table. 39 | 40 | void install_basic_classes(); 41 | void install_class(CgenNodeP nd); 42 | void install_classes(Classes cs); 43 | void build_inheritance_tree(); 44 | void set_relations(CgenNodeP nd); 45 | public: 46 | CgenClassTable(Classes, ostream& str); 47 | void code(); 48 | CgenNodeP root(); 49 | }; 50 | 51 | 52 | class CgenNode : public class__class { 53 | private: 54 | CgenNodeP parentnd; // Parent of class 55 | List *children; // Children of class 56 | Basicness basic_status; // `Basic' if class is basic 57 | // `NotBasic' otherwise 58 | 59 | public: 60 | CgenNode(Class_ c, 61 | Basicness bstatus, 62 | CgenClassTableP class_table); 63 | 64 | void add_child(CgenNodeP child); 65 | List *get_children() { return children; } 66 | void set_parentnd(CgenNodeP p); 67 | CgenNodeP get_parentnd() { return parentnd; } 68 | int basic() { return (basic_status == Basic); } 69 | }; 70 | 71 | class BoolConst 72 | { 73 | private: 74 | int val; 75 | public: 76 | BoolConst(int); 77 | void code_def(ostream&, int boolclasstag); 78 | void code_ref(ostream&) const; 79 | }; 80 | 81 | -------------------------------------------------------------------------------- /assignments/PA5/cgen_supp.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "stringtab.h" 5 | 6 | static int ascii = 0; 7 | 8 | void ascii_mode(ostream& str) 9 | { 10 | if (!ascii) 11 | { 12 | str << "\t.ascii\t\""; 13 | ascii = 1; 14 | } 15 | } 16 | 17 | void byte_mode(ostream& str) 18 | { 19 | if (ascii) 20 | { 21 | str << "\"\n"; 22 | ascii = 0; 23 | } 24 | } 25 | 26 | void emit_string_constant(ostream& str, char* s) 27 | { 28 | ascii = 0; 29 | 30 | while (*s) { 31 | switch (*s) { 32 | case '\n': 33 | ascii_mode(str); 34 | str << "\\n"; 35 | break; 36 | case '\t': 37 | ascii_mode(str); 38 | str << "\\t"; 39 | break; 40 | case '\\': 41 | byte_mode(str); 42 | str << "\t.byte\t" << (int) ((unsigned char) '\\') << endl; 43 | break; 44 | case '"' : 45 | ascii_mode(str); 46 | str << "\\\""; 47 | break; 48 | default: 49 | if (*s >= ' ' && ((unsigned char) *s) < 128) 50 | { 51 | ascii_mode(str); 52 | str << *s; 53 | } 54 | else 55 | { 56 | byte_mode(str); 57 | str << "\t.byte\t" << (int) ((unsigned char) *s) << endl; 58 | } 59 | break; 60 | } 61 | s++; 62 | } 63 | byte_mode(str); 64 | str << "\t.byte\t0\t" << endl; 65 | } 66 | 67 | 68 | -------------------------------------------------------------------------------- /assignments/PA5/checkpoint: -------------------------------------------------------------------------------- 1 | PA5 Checkpoint Questions 2 | ------------------------ 3 | 4 | The following are several questions which should help you to 5 | understand features of the project, and suggestions on how to better 6 | implement the project. Answer them and submit by running 7 | 'submit PA5-checkpoint' 8 | 9 | 10 | Much of this project involves outputting code which properly interacts 11 | with the library code, which is documented both in the tour of the cool 12 | support files and as comments to the library code itself: 13 | ~cs164/lib/trap.handler. 14 | 15 | 16 | 1) Which library functions will your generated code call directly? 17 | (Other functions in trap.handler, such as most garbage collector 18 | routines, are only called by other library functions.) What is the 19 | calling convention for these library functions? 20 | 21 | 22 | 23 | 24 | 2) How is your code supposed to interact with the garbage collector? 25 | What is the root set in the registers (i.e., what registers does it 26 | examine)? How do you select which garbage collector is used? 27 | 28 | 29 | 30 | 31 | (Initially, you may choose to test your code generator without using a 32 | garbage collector. After we discuss garbage collection in class, you 33 | should revisit these issues. For instance, you should think about 34 | what kinds of values can be stored on the stack and in attributes.) 35 | 36 | 37 | 3) How does your program start up? 38 | 39 | 40 | 41 | 42 | 4) How does Cool perform arithmetic operations? 43 | 44 | 45 | 46 | 47 | 5) How do you turn a string reference into the appropriate string 48 | constant? Same for an integer? 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /assignments/PA5/example.cl: -------------------------------------------------------------------------------- 1 | 2 | (* Example cool program testing as many aspects of the code generator 3 | as possible. 4 | *) 5 | 6 | class Main { 7 | main():Int { 0 }; 8 | }; 9 | 10 | -------------------------------------------------------------------------------- /assignments/PA5/hello_world.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main(): SELF_TYPE { 3 | out_string("Hello, World.\n") 4 | }; 5 | }; 6 | -------------------------------------------------------------------------------- /bin/aps2c++: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/aps2c++ -------------------------------------------------------------------------------- /bin/aps2java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/aps2java -------------------------------------------------------------------------------- /bin/coolc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/coolc -------------------------------------------------------------------------------- /bin/dispatch.SKEL: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch=`ARCH` 3 | 4 | PRG=$0 5 | progname=`/bin/basename $0` 6 | 7 | # Resolve symlinks, so that the pathname computations below find the 8 | # directory structure they expect. 9 | while [ -h "$PRG" ]; do 10 | # Get the target of the symlink. N.B.: We assume that neither the 11 | # link's value nor the pathname leading to it contains "-> ". 12 | ls=`/bin/ls -ld "$PRG"` 13 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 14 | # If the link is absolute, use it as is; otherwise, substitute it 15 | # into the leafname part of $PRG. 16 | case $link in 17 | /*) PRG="$link";; 18 | *) PRG="`/usr/bin/dirname $PRG`/$link" 19 | esac 20 | done 21 | 22 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 23 | 24 | # set environment for spim/xspim 25 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 26 | export DEFAULT_TRAP_HANDLER 27 | 28 | xname=$COOL_INST/bin/.$arch/PROGRAM 29 | 30 | if [ -x $xname ]; then 31 | exec $xname $* 32 | else 33 | echo PROGRAM is not compiled for $arch 34 | fi 35 | -------------------------------------------------------------------------------- /bin/java_cup: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | exec java -classpath `dirname $0`/../lib java_cup.Main $* 4 | -------------------------------------------------------------------------------- /bin/jlex: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | exec java -classpath `dirname $0`/../lib JLex.Main $* 4 | -------------------------------------------------------------------------------- /bin/reference-cgen: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/reference-cgen -------------------------------------------------------------------------------- /bin/reference-lexer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/reference-lexer -------------------------------------------------------------------------------- /bin/reference-parser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/reference-parser -------------------------------------------------------------------------------- /bin/reference-semant: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/reference-semant -------------------------------------------------------------------------------- /bin/spim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/spim -------------------------------------------------------------------------------- /bin/test.cl~: -------------------------------------------------------------------------------- 1 | -- 这是注释 2 | 3 | class Main inherits IO 4 | { 5 | main():SELF_TYPE { 6 | out_string("Hello,Cool!\n") 7 | }; 8 | }; 9 | -------------------------------------------------------------------------------- /bin/xspim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/bin/xspim -------------------------------------------------------------------------------- /doc/UnixProgrammingTools.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/UnixProgrammingTools.pdf -------------------------------------------------------------------------------- /doc/bison.ps.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/bison.ps.gz -------------------------------------------------------------------------------- /doc/cool-manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/cool-manual.pdf -------------------------------------------------------------------------------- /doc/cool-program-language.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/cool-program-language.pdf -------------------------------------------------------------------------------- /doc/cool-runtime.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/cool-runtime.pdf -------------------------------------------------------------------------------- /doc/cool-tour.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/cool-tour.pdf -------------------------------------------------------------------------------- /doc/flex.ps.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/flex.ps.gz -------------------------------------------------------------------------------- /doc/instructors-guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/instructors-guide.pdf -------------------------------------------------------------------------------- /doc/make.ps.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/make.ps.gz -------------------------------------------------------------------------------- /doc/spim.ps.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/doc/spim.ps.gz -------------------------------------------------------------------------------- /etc/copy: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #/home/ff/cs164ECT, IN/home/ff/cs164ECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | #like copy-skel, put doesn't expect to see a .SKEL on the end of the source file. 27 | 28 | 29 | # Resolve symlinks, so that the pathname computations below find the 30 | # directory structure they expect. 31 | while [ -h "$PRG" ]; do 32 | # Get the target of the symlink. N.B.: We assume that neither the 33 | # link's value nor the pathname leading to it contains "-> ". 34 | ls=`/bin/ls -ld "$PRG"` 35 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 36 | # If the link is absolute, use it as is; otherwise, substitute it 37 | # into the leafname part of $PRG. 38 | case $link in 39 | /*) PRG="$link";; 40 | *) PRG="`/usr/bin/dirname $PRG`/$link" 41 | esac 42 | done 43 | 44 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 45 | 46 | num=$1 47 | shift 48 | for f 49 | do 50 | if test -r "$f" 51 | then 52 | echo "$f" already exists. Skipping $f. 53 | else 54 | cp ${COOL_INST}/assignments/PA$num/$f $f 55 | chmod u+w $f 56 | fi 57 | done 58 | -------------------------------------------------------------------------------- /etc/copy-skel: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #/tmp/coolECT, IN/tmp/coolECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | shift 45 | for f 46 | do 47 | if test -r "$f" 48 | then 49 | echo "$f" already exists. Skipping $f. 50 | else 51 | cp ${COOL_INST}/assignments/PA$num/$f.SKEL $f 52 | chmod u+w $f 53 | fi 54 | done 55 | -------------------------------------------------------------------------------- /etc/copy-skel.SKEL: -------------------------------------------------------------------------------- 1 | #!SHELL 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | shift 45 | for f 46 | do 47 | if test -r "$f" 48 | then 49 | echo "$f" already exists. Skipping $f. 50 | else 51 | cp ${COOL_INST}/assignments/PA$num/$f.SKEL $f 52 | chmod u+w $f 53 | fi 54 | done 55 | -------------------------------------------------------------------------------- /etc/copy~: -------------------------------------------------------------------------------- 1 | #!/usr/sww/bin/bash 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #/home/ff/cs164ECT, IN/home/ff/cs164ECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | #like copy-skel, put doesn't expect to see a .SKEL on the end of the source file. 27 | 28 | 29 | # Resolve symlinks, so that the pathname computations below find the 30 | # directory structure they expect. 31 | while [ -h "$PRG" ]; do 32 | # Get the target of the symlink. N.B.: We assume that neither the 33 | # link's value nor the pathname leading to it contains "-> ". 34 | ls=`/bin/ls -ld "$PRG"` 35 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 36 | # If the link is absolute, use it as is; otherwise, substitute it 37 | # into the leafname part of $PRG. 38 | case $link in 39 | /*) PRG="$link";; 40 | *) PRG="`/usr/bin/dirname $PRG`/$link" 41 | esac 42 | done 43 | 44 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 45 | 46 | num=$1 47 | shift 48 | for f 49 | do 50 | if test -r "$f" 51 | then 52 | echo "$f" already exists. Skipping $f. 53 | else 54 | cp ${COOL_INST}/assignments/PA$num/$f $f 55 | chmod u+w $f 56 | fi 57 | done 58 | -------------------------------------------------------------------------------- /etc/link-object: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #/tmp/coolECT, IN/tmp/coolECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | arch=`arch` 45 | shift 46 | for f 47 | do 48 | echo "linking $f" 49 | xname=${COOL_INST}/lib/.${arch}/PA$num/$f 50 | if [ -f $xname ]; then 51 | ln -s $xname $f 52 | else 53 | echo $f is not compiled for $arch 54 | fi 55 | done 56 | 57 | -------------------------------------------------------------------------------- /etc/link-object.SKEL: -------------------------------------------------------------------------------- 1 | #!SHELL 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | arch=`uname -m` 45 | shift 46 | for f 47 | do 48 | echo "linking $f" 49 | xname=${COOL_INST}/lib/.${arch}/PA$num/$f 50 | if [ -f $xname ]; then 51 | ln -s $xname $f 52 | else 53 | echo $f is not compiled for $arch 54 | fi 55 | done 56 | 57 | -------------------------------------------------------------------------------- /etc/link-object.SKEL~: -------------------------------------------------------------------------------- 1 | #!SHELL 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | arch=`uname -m` 45 | shift 46 | for f 47 | do 48 | echo "linking $f" 49 | xname=${COOL_INST}/lib/.${arch}/PA$num/$f 50 | if [ -f $xname ]; then 51 | ln -s $xname $f 52 | else 53 | echo $f is not compiled for $arch 54 | fi 55 | done 56 | 57 | -------------------------------------------------------------------------------- /etc/link-shared: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #/tmp/coolECT, IN/tmp/coolECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | shift 45 | for f 46 | do 47 | if test -f "$f" 48 | then 49 | echo "$f" already exists. Skipping $f. 50 | else 51 | ln -s ${COOL_INST}/assignments/PA$num/$f $f 52 | fi 53 | done 54 | -------------------------------------------------------------------------------- /etc/link-shared.SKEL: -------------------------------------------------------------------------------- 1 | #!SHELL 2 | # 3 | # 4 | #Copyright (c) 1995,1996 The Regents of the University of California. 5 | #All rights reserved. 6 | # 7 | #Permission to use, copy, modify, and distribute this software 8 | #for any purpose, without fee, and without written agreement is 9 | #hereby granted, provided that the above copyright notice and the following 10 | #two paragraphs appear in all copies of this software. 11 | # 12 | #IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 13 | #DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 14 | #OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 15 | #CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 16 | # 17 | #THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 18 | #INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 19 | #AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 20 | #ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 21 | #PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 22 | # 23 | 24 | PRG=$0 25 | 26 | # Resolve symlinks, so that the pathname computations below find the 27 | # directory structure they expect. 28 | while [ -h "$PRG" ]; do 29 | # Get the target of the symlink. N.B.: We assume that neither the 30 | # link's value nor the pathname leading to it contains "-> ". 31 | ls=`/bin/ls -ld "$PRG"` 32 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 33 | # If the link is absolute, use it as is; otherwise, substitute it 34 | # into the leafname part of $PRG. 35 | case $link in 36 | /*) PRG="$link";; 37 | *) PRG="`/usr/bin/dirname $PRG`/$link" 38 | esac 39 | done 40 | 41 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 42 | 43 | num=$1 44 | shift 45 | for f 46 | do 47 | if test -f "$f" 48 | then 49 | echo "$f" already exists. Skipping $f. 50 | else 51 | ln -s ${COOL_INST}/assignments/PA$num/$f $f 52 | fi 53 | done 54 | -------------------------------------------------------------------------------- /examples/LexSamp1.l: -------------------------------------------------------------------------------- 1 | %{ 2 | /* 3 | * 统计单词数、行数、字符数 4 | * 用gcc生成可执行程序: 5 | * flex -o ex1.c lexsamp1.l 6 | * gcc -o ex1 ex1.c 7 | 之后运行./ex1 即可运行 8 | */ 9 | #include 10 | int nchar, nword, nline; /* 分别记录字符个数、字数和行数 */ 11 | %} 12 | %option yylineno 13 | %% 14 | [ \t] /* 匹配到一个空格或Tab键就“吃”掉它们 */ 15 | \n {/*adding your code*/; 16 | nline++; 17 | } /* 匹配到一个换行符,行数加1 */ 18 | [^ \t\n]+ { 19 | /* 匹配到一个不包括空格、Tab键和换行符的字, 20 | 字数加1,字符数加yyleng(字符长度) */ 21 | /*adding your code*/; 22 | ++nword; nchar+=yyleng; 23 | } 24 | 25 | %% 26 | int main() 27 | { 28 | printf("Press CTRL+d to quit.\nInput any text:\n"); 29 | yylex(); /* 调用词法分析器,直到输入结束 */ 30 | printf("nchar=%d, nword=%d, nline=%d\n", nchar, nword, nline); 31 | return 0; 32 | } 33 | 34 | /* 函数yywrap是LEX提供的一个库函数 35 | * 若生成可执行程序时没有链接LEX库,则必须手工定义 36 | * 反之,生成可执行程序时必须如此: 37 | * cc -o a.out lex.yy.c -ll # for LEX 38 | * cc -o a.out lex.yy.c -lfl # for FLEX 39 | * 其中-ll表示连接函数库libl.a(in UNIX) 40 | */ 41 | // int yywrap(){ return 1; } 42 | -------------------------------------------------------------------------------- /examples/README: -------------------------------------------------------------------------------- 1 | 2 | The examples directory contains a few small and not so small 3 | example programs which illustrate various aspects of the Cool 4 | programming language. 5 | 6 | arith.cl Tests various aspects of arithmetic in Cool. 7 | 8 | atoi.cl An implementation of the C function by the 9 | same name. It converts a String into an Int. 10 | 11 | atoi_test.cl An example program using atoi.cl. Since you 12 | will most likely use atoi.cl in the first 13 | assignment, you should study this example. 14 | 15 | list.cl A very simple program showing how to create a 16 | list data type for integers. It illustrates 17 | inheritance and dynamic dispatch. 18 | 19 | book_list.cl Illustrates inheritance and in particular the 20 | mechanism of STATIC DISPATCH and the CASE 21 | statement. 22 | 23 | cells.cl Models a one-dimensional cellular automaton. 24 | 25 | cool.cl An short and obscure program. 26 | 27 | io.cl Shows how to use the IO class. (input/output) 28 | 29 | hairyscary.cl Exercises many of the obscure features of the 30 | language in obscure ways. 31 | 32 | hello_world.cl The classic first program. 33 | 34 | primes.cl An unusual prime number generator. 35 | 36 | graph.cl A program reading descriptions of weighted- 37 | directed graphs from stdin in text format. 38 | 39 | g1.graph A sample input to graph.cl 40 | 41 | palindrome.cl Recognizes palindromes. 42 | 43 | complex.cl Checks the = operator and cummulative effects of 44 | method calls via a complex number object. 45 | 46 | life.cl The classic Game of Life 47 | 48 | sort_list.cl A more complex example sorting lists of integers. 49 | 50 | null_string.cl Not a valid Cool program: contains a string with 51 | an embedded NULL character. 52 | -------------------------------------------------------------------------------- /examples/assign.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO{ 2 | x:Int; 3 | main () : Object { 4 | while x<9000 loop out_int (x<-x+1) pool 5 | }; 6 | }; 7 | -------------------------------------------------------------------------------- /examples/atoi.cl: -------------------------------------------------------------------------------- 1 | (* 2 | The class A2I provides integer-to-string and string-to-integer 3 | conversion routines. To use these routines, either inherit them 4 | in the class where needed, have a dummy variable bound to 5 | something of type A2I, or simpl write (new A2I).method(argument). 6 | *) 7 | 8 | 9 | (* 10 | c2i Converts a 1-character string to an integer. Aborts 11 | if the string is not "0" through "9" 12 | *) 13 | class A2I { 14 | 15 | c2i(char : String) : Int { 16 | if char = "0" then 0 else 17 | if char = "1" then 1 else 18 | if char = "2" then 2 else 19 | if char = "3" then 3 else 20 | if char = "4" then 4 else 21 | if char = "5" then 5 else 22 | if char = "6" then 6 else 23 | if char = "7" then 7 else 24 | if char = "8" then 8 else 25 | if char = "9" then 9 else 26 | { abort(); 0; } -- the 0 is needed to satisfy the typchecker 27 | fi fi fi fi fi fi fi fi fi fi 28 | }; 29 | 30 | (* 31 | i2c is the inverse of c2i. 32 | *) 33 | i2c(i : Int) : String { 34 | if i = 0 then "0" else 35 | if i = 1 then "1" else 36 | if i = 2 then "2" else 37 | if i = 3 then "3" else 38 | if i = 4 then "4" else 39 | if i = 5 then "5" else 40 | if i = 6 then "6" else 41 | if i = 7 then "7" else 42 | if i = 8 then "8" else 43 | if i = 9 then "9" else 44 | { abort(); ""; } -- the "" is needed to satisfy the typchecker 45 | fi fi fi fi fi fi fi fi fi fi 46 | }; 47 | 48 | (* 49 | a2i converts an ASCII string into an integer. The empty string 50 | is converted to 0. Signed and unsigned strings are handled. The 51 | method aborts if the string does not represent an integer. Very 52 | long strings of digits produce strange answers because of arithmetic 53 | overflow. 54 | 55 | *) 56 | a2i(s : String) : Int { 57 | if s.length() = 0 then 0 else 58 | if s.substr(0,1) = "-" then ~a2i_aux(s.substr(1,s.length()-1)) else 59 | if s.substr(0,1) = "+" then a2i_aux(s.substr(1,s.length()-1)) else 60 | a2i_aux(s) 61 | fi fi fi 62 | }; 63 | 64 | (* 65 | a2i_aux converts the usigned portion of the string. As a programming 66 | example, this method is written iteratively. 67 | *) 68 | a2i_aux(s : String) : Int { 69 | (let int : Int <- 0 in 70 | { 71 | (let j : Int <- s.length() in 72 | (let i : Int <- 0 in 73 | while i < j loop 74 | { 75 | int <- int * 10 + c2i(s.substr(i,1)); 76 | i <- i + 1; 77 | } 78 | pool 79 | ) 80 | ); 81 | int; 82 | } 83 | ) 84 | }; 85 | 86 | (* 87 | i2a converts an integer to a string. Positive and negative 88 | numbers are handled correctly. 89 | *) 90 | i2a(i : Int) : String { 91 | if i = 0 then "0" else 92 | if 0 < i then i2a_aux(i) else 93 | "-".concat(i2a_aux(i * ~1)) 94 | fi fi 95 | }; 96 | 97 | (* 98 | i2a_aux is an example using recursion. 99 | *) 100 | i2a_aux(i : Int) : String { 101 | if i = 0 then "" else 102 | (let next : Int <- i / 10 in 103 | i2a_aux(next).concat(i2c(i - next * 10)) 104 | ) 105 | fi 106 | }; 107 | 108 | }; 109 | -------------------------------------------------------------------------------- /examples/atoi_test.cl: -------------------------------------------------------------------------------- 1 | (* 2 | This method implements a driver for testing the ATOI class. 3 | The program repeatedly asks the user to enter a number, which 4 | is then coverted from its string form to an integer and back 5 | again to a string. The results of both conversions are printed 6 | on the screen. Typing "stop" at the prompt exits the program. 7 | *) 8 | 9 | class Main inherits IO { 10 | newline() : Object { 11 | out_string("\n") 12 | }; 13 | 14 | prompt() : String { 15 | { 16 | out_string("Enter a number>"); 17 | in_string(); 18 | } 19 | }; 20 | 21 | main() : Object { 22 | (* Since we didn't bother to inherit from the A2I class, we have 23 | to have an object of type A2I in order to access the 24 | methods of that class. *) 25 | (let z : A2I <- new A2I in 26 | while true loop 27 | (let s : String <- prompt() in 28 | if s = "stop" then 29 | abort() -- we don't bother to terminate gracefully 30 | else 31 | (let i : Int <- z.a2i(s) in 32 | (let news : String <- z.i2a(i) in 33 | { 34 | out_int(i); 35 | newline(); 36 | out_string(news); 37 | newline(); 38 | } 39 | ) 40 | ) 41 | fi 42 | ) 43 | pool 44 | ) 45 | }; 46 | }; 47 | -------------------------------------------------------------------------------- /examples/cells.cl: -------------------------------------------------------------------------------- 1 | (* models one-dimensional cellular automaton on a circle of finite radius 2 | arrays are faked as Strings, 3 | X's respresent live cells, dots represent dead cells, 4 | no error checking is done *) 5 | class CellularAutomaton inherits IO { 6 | population_map : String; 7 | 8 | init(map : String) : SELF_TYPE { 9 | { 10 | population_map <- map; 11 | self; 12 | } 13 | }; 14 | 15 | print() : SELF_TYPE { 16 | { 17 | out_string(population_map.concat("\n")); 18 | self; 19 | } 20 | }; 21 | 22 | num_cells() : Int { 23 | population_map.length() 24 | }; 25 | 26 | cell(position : Int) : String { 27 | population_map.substr(position, 1) 28 | }; 29 | 30 | cell_left_neighbor(position : Int) : String { 31 | if position = 0 then 32 | cell(num_cells() - 1) 33 | else 34 | cell(position - 1) 35 | fi 36 | }; 37 | 38 | cell_right_neighbor(position : Int) : String { 39 | if position = num_cells() - 1 then 40 | cell(0) 41 | else 42 | cell(position + 1) 43 | fi 44 | }; 45 | 46 | (* a cell will live if exactly 1 of itself and it's immediate 47 | neighbors are alive *) 48 | cell_at_next_evolution(position : Int) : String { 49 | if (if cell(position) = "X" then 1 else 0 fi 50 | + if cell_left_neighbor(position) = "X" then 1 else 0 fi 51 | + if cell_right_neighbor(position) = "X" then 1 else 0 fi 52 | = 1) 53 | then 54 | "X" 55 | else 56 | "." 57 | fi 58 | }; 59 | 60 | evolve() : SELF_TYPE { 61 | (let position : Int in 62 | (let num : Int <- num_cells() in 63 | (let temp : String in 64 | { 65 | while position < num loop 66 | { 67 | temp <- temp.concat(cell_at_next_evolution(position)); 68 | position <- position + 1; 69 | } 70 | pool; 71 | population_map <- temp; 72 | self; 73 | } 74 | ) ) ) 75 | }; 76 | }; 77 | 78 | class Main { 79 | cells : CellularAutomaton; 80 | 81 | main() : SELF_TYPE { 82 | { 83 | cells <- (new CellularAutomaton).init(" X "); 84 | cells.print(); 85 | (let countdown : Int <- 20 in 86 | while 0 < countdown loop 87 | { 88 | cells.evolve(); 89 | cells.print(); 90 | countdown <- countdown - 1; 91 | } 92 | pool 93 | ); 94 | self; 95 | } 96 | }; 97 | }; 98 | -------------------------------------------------------------------------------- /examples/complex.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main() : SELF_TYPE { 3 | (let c : Complex <- (new Complex).init(1, 1) in 4 | if c.reflect_X().reflect_Y() = c.reflect_0() 5 | then out_string("=)\n") 6 | else out_string("=(\n") 7 | fi 8 | ) 9 | }; 10 | }; 11 | 12 | class Complex inherits IO { 13 | x : Int; 14 | y : Int; 15 | 16 | init(a : Int, b : Int) : Complex { 17 | { 18 | x = a; 19 | y = b; 20 | self; 21 | } 22 | }; 23 | 24 | print() : Object { 25 | if y = 0 26 | then out_int(x) 27 | else out_int(x).out_string("+").out_int(y).out_string("I") 28 | fi 29 | }; 30 | 31 | reflect_0() : Complex { 32 | { 33 | x = ~x; 34 | y = ~y; 35 | self; 36 | } 37 | }; 38 | 39 | reflect_X() : Complex { 40 | { 41 | y = ~y; 42 | self; 43 | } 44 | }; 45 | 46 | reflect_Y() : Complex { 47 | { 48 | x = ~x; 49 | self; 50 | } 51 | }; 52 | }; 53 | -------------------------------------------------------------------------------- /examples/cool.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main() : SELF_TYPE { 3 | { 4 | out_string((new Object).type_name().substr(4,1)). 5 | out_string((isvoid self).type_name().substr(1,3)); 6 | out_string("\n"); 7 | } 8 | }; 9 | }; 10 | -------------------------------------------------------------------------------- /examples/exp2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/examples/exp2 -------------------------------------------------------------------------------- /examples/hairyscary.cl: -------------------------------------------------------------------------------- 1 | (* hairy . . .*) 2 | 3 | class Foo inherits Bazz { 4 | a : Razz <- case self of 5 | n : Razz => (new Bar); 6 | n : Foo => (new Razz); 7 | n : Bar => n; 8 | esac; 9 | 10 | b : Int <- a.doh() + g.doh() + doh() + printh(); 11 | 12 | doh() : Int { (let i : Int <- h in { h <- h + 2; i; } ) }; 13 | 14 | }; 15 | 16 | class Bar inherits Razz { 17 | 18 | c : Int <- doh(); 19 | 20 | d : Object <- printh(); 21 | }; 22 | 23 | 24 | class Razz inherits Foo { 25 | 26 | e : Bar <- case self of 27 | n : Razz => (new Bar); 28 | n : Bar => n; 29 | esac; 30 | 31 | f : Int <- a@Bazz.doh() + g.doh() + e.doh() + doh() + printh(); 32 | 33 | }; 34 | 35 | class Bazz inherits IO { 36 | 37 | h : Int <- 1; 38 | 39 | g : Foo <- case self of 40 | n : Bazz => (new Foo); 41 | n : Razz => (new Bar); 42 | n : Foo => (new Razz); 43 | n : Bar => n; 44 | esac; 45 | 46 | i : Object <- printh(); 47 | 48 | printh() : Int { { out_int(h); 0; } }; 49 | 50 | doh() : Int { (let i: Int <- h in { h <- h + 1; i; } ) }; 51 | }; 52 | 53 | (* scary . . . *) 54 | class Main { 55 | a : Bazz <- new Bazz; 56 | b : Foo <- new Foo; 57 | c : Razz <- new Razz; 58 | d : Bar <- new Bar; 59 | 60 | main(): String { "do nothing" }; 61 | 62 | }; 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /examples/hello_world.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main(): SELF_TYPE { 3 | out_string("Hello, World.\n") 4 | }; 5 | }; 6 | -------------------------------------------------------------------------------- /examples/io.cl: -------------------------------------------------------------------------------- 1 | (* 2 | * The IO class is predefined and has 4 methods: 3 | * 4 | * out_string(s : String) : SELF_TYPE 5 | * out_int(i : Int) : SELF_TYPE 6 | * in_string() : String 7 | * in_int() : Int 8 | * 9 | * The out operations print their argument to the terminal. The 10 | * in_string method reads an entire line from the terminal and returns a 11 | * string not containing the new line. The in_int method also reads 12 | * an entire line from the terminal and returns the integer 13 | * corresponding to the first non blank word on the line. If that 14 | * word is not an integer, it returns 0. 15 | * 16 | * 17 | * Because our language is object oriented, we need an object of type 18 | * IO in order to call any of these methods. 19 | * 20 | * There are basically two ways of getting access to IO in a class C. 21 | * 22 | * 1) Define C to Inherit from IO. This way the IO methods become 23 | * methods of C, and they can be called using the abbreviated 24 | * dispatch, i.e. 25 | * 26 | * class C inherits IO is 27 | * ... 28 | * out_string("Hello world\n") 29 | * ... 30 | * end; 31 | * 32 | * 2) If your class C does not directly or indirectly inherit from 33 | * IO, the best way to access IO is through an initialized 34 | * attribute of type IO. 35 | * 36 | * class C inherits Foo is 37 | * io : IO <- new IO; 38 | * ... 39 | * io.out_string("Hello world\n"); 40 | * ... 41 | * end; 42 | * 43 | * Approach 1) is most often used, in particular when you need IO 44 | * functions in the Main class. 45 | * 46 | *) 47 | 48 | 49 | class A { 50 | 51 | -- Let's assume that we don't want A to not inherit from IO. 52 | 53 | io : IO <- new IO; 54 | 55 | out_a() : Object { io.out_string("A: Hello world\n") }; 56 | 57 | }; 58 | 59 | 60 | class B inherits A { 61 | 62 | -- B does not have to an extra attribute, since it inherits io from A. 63 | 64 | out_b() : Object { io.out_string("B: Hello world\n") }; 65 | 66 | }; 67 | 68 | 69 | class C inherits IO { 70 | 71 | -- Now the IO methods are part of C. 72 | 73 | out_c() : Object { out_string("C: Hello world\n") }; 74 | 75 | -- Note that out_string(...) is just a shorthand for self.out_string(...) 76 | 77 | }; 78 | 79 | 80 | class D inherits C { 81 | 82 | -- Inherits IO methods from C. 83 | 84 | out_d() : Object { out_string("D: Hello world\n") }; 85 | 86 | }; 87 | 88 | 89 | class Main inherits IO { 90 | 91 | -- Same case as class C. 92 | 93 | main() : Object { 94 | { 95 | (new A).out_a(); 96 | (new B).out_b(); 97 | (new C).out_c(); 98 | (new D).out_d(); 99 | out_string("Done.\n"); 100 | } 101 | }; 102 | 103 | }; 104 | -------------------------------------------------------------------------------- /examples/new_complex.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main() : SELF_TYPE { 3 | (let c : Complex <- (new Complex).init(1, 1) in 4 | { 5 | -- trivially equal (see CoolAid) 6 | if c.reflect_X() = c.reflect_0() 7 | then out_string("=)\n") 8 | else out_string("=(\n") 9 | fi; 10 | -- equal 11 | if c.reflect_X().reflect_Y().equal(c.reflect_0()) 12 | then out_string("=)\n") 13 | else out_string("=(\n") 14 | fi; 15 | } 16 | ) 17 | }; 18 | }; 19 | 20 | class Complex inherits IO { 21 | x : Int; 22 | y : Int; 23 | 24 | init(a : Int, b : Int) : Complex { 25 | { 26 | x = a; 27 | y = b; 28 | self; 29 | } 30 | }; 31 | 32 | print() : Object { 33 | if y = 0 34 | then out_int(x) 35 | else out_int(x).out_string("+").out_int(y).out_string("I") 36 | fi 37 | }; 38 | 39 | reflect_0() : Complex { 40 | { 41 | x = ~x; 42 | y = ~y; 43 | self; 44 | } 45 | }; 46 | 47 | reflect_X() : Complex { 48 | { 49 | y = ~y; 50 | self; 51 | } 52 | }; 53 | 54 | reflect_Y() : Complex { 55 | { 56 | x = ~x; 57 | self; 58 | } 59 | }; 60 | 61 | equal(d : Complex) : Bool { 62 | if x = d.x_value() 63 | then 64 | if y = d.y_value() 65 | then true 66 | else false 67 | fi 68 | else false 69 | fi 70 | }; 71 | 72 | x_value() : Int { 73 | x 74 | }; 75 | 76 | y_value() : Int { 77 | y 78 | }; 79 | }; 80 | -------------------------------------------------------------------------------- /examples/null_string.cl: -------------------------------------------------------------------------------- 1 | (* this file tests strings with embedded NULLs. It is meant as a lexer 2 | * test file: it is not a complete cool program *) 3 | "This is a string with null [] character." yada 4 | "This is a string with null [] character and an escaped quote \" here." yida 5 | (* Note that your parser should not return a token for the word "here" at all. 6 | * Your parser should skip past it. *) 7 | 8 | (* This test file is provided because not everyone can get their text editor 9 | * to produce a raw NULL and the assignment is not meant to demonstrate 10 | * arcane vi or emacs knowledge. [Weimer Spring '01] *) 11 | -------------------------------------------------------------------------------- /examples/palindrome.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | pal(s : String) : Bool { 3 | if s.length() = 0 4 | then true 5 | else if s.length() = 1 6 | then true 7 | else if s.substr(0, 1) = s.substr(s.length() - 1, 1) 8 | then pal(s.substr(1, s.length() -2)) 9 | else false 10 | fi fi fi 11 | }; 12 | 13 | i : Int; 14 | 15 | main() : SELF_TYPE { 16 | { 17 | i <- ~1; 18 | out_string("enter a string\n"); 19 | if pal(in_string()) 20 | then out_string("that was a palindrome\n") 21 | else out_string("that was not a palindrome\n") 22 | fi; 23 | } 24 | }; 25 | }; 26 | -------------------------------------------------------------------------------- /examples/primes.cl: -------------------------------------------------------------------------------- 1 | 2 | (* 3 | * methodless-primes.cl 4 | * 5 | * Designed by Jesse H. Willett, jhw@cory, 11103234, with 6 | * Istvan Siposs, isiposs@cory, 12342921. 7 | * 8 | * This program generates primes in order without using any methods. 9 | * Actually, it does use three methods: those of IO to print out each prime, and 10 | * abort() to halt the program. These methods are incidental, however, 11 | * to the information-processing functionality of the program. We 12 | * could regard the attribute 'out's sequential values as our output, 13 | * and the string "halt" as our terminate signal. 14 | * 15 | * Naturally, using Cool this way is a real waste, basically reducing it 16 | * to assembly without the benefit of compilation. 17 | * 18 | * There could even be a subroutine-like construction, in that different 19 | * code could be in the assign fields of attributes of other classes, 20 | * and it could be executed by calling 'new Sub', but no parameters 21 | * could be passed to the subroutine, and it could only return itself. 22 | * but returning itself would be useless since we couldn't call methods 23 | * and the only operators we have are for Int and Bool, which do nothing 24 | * interesting when we initialize them! 25 | *) 26 | 27 | class Main inherits IO { 28 | 29 | main() : Int { -- main() is an atrophied method so we can parse. 30 | 0 31 | }; 32 | 33 | out : Int <- -- out is our 'output'. It's values are the primes. 34 | { 35 | out_string("2 is trivially prime.\n"); 36 | 2; 37 | }; 38 | 39 | testee : Int <- out; -- testee is a number to be tested for primeness. 40 | 41 | divisor : Int; -- divisor is a number which may factor testee. 42 | 43 | stop : Int <- 500; -- stop is an arbitrary value limiting testee. 44 | 45 | m : Object <- -- m supplants the main method. 46 | while true loop 47 | { 48 | 49 | testee <- testee + 1; 50 | divisor <- 2; 51 | 52 | while 53 | if testee < divisor * divisor 54 | then false -- can stop if divisor > sqrt(testee). 55 | else if testee - divisor*(testee/divisor) = 0 56 | then false -- can stop if divisor divides testee. 57 | else true 58 | fi fi 59 | loop 60 | divisor <- divisor + 1 61 | pool; 62 | 63 | if testee < divisor * divisor -- which reason did we stop for? 64 | then -- testee has no factors less than sqrt(testee). 65 | { 66 | out <- testee; -- we could think of out itself as the output. 67 | out_int(out); 68 | out_string(" is prime.\n"); 69 | } 70 | else -- the loop halted on testee/divisor = 0, testee isn't prime. 71 | 0 -- testee isn't prime, do nothing. 72 | fi; 73 | 74 | if stop <= testee then 75 | "halt".abort() -- we could think of "halt" as SIGTERM. 76 | else 77 | "continue" 78 | fi; 79 | 80 | } 81 | pool; 82 | 83 | }; (* end of Main *) 84 | 85 | -------------------------------------------------------------------------------- /examples/test.cl: -------------------------------------------------------------------------------- 1 | -- 这是注释 2 | 3 | class Main iO 4 | { 5 | main():SELF_TYPE { 6 | out_string("Hello,World!") 7 | }; 8 | }; 9 | -------------------------------------------------------------------------------- /guide_file.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/guide_file.doc -------------------------------------------------------------------------------- /handouts/Makefile: -------------------------------------------------------------------------------- 1 | .IGNORE: 2 | 3 | TEXSOURCES = asn1 asn2 asn3 asn4 asn5 cool-manual cool-tour instructors-guide 4 | INCLUDES = mymargins.tex macros.tex handout.sty 5 | 6 | PS = $(foreach f, ${TEXSOURCES}, ${f}.ps) 7 | 8 | all: ${PS} 9 | 10 | %.dvi : %.tex ${INCLUDES} 11 | latex $< 12 | latex $< 13 | 14 | %.ps : %.dvi 15 | rm -f $@ 16 | dvips $< -o $@ 17 | 18 | clean: 19 | rm -f *.txt *.dvi *.log *.aux *~ 20 | 21 | really-clean: clean 22 | rm -f *.ps 23 | -------------------------------------------------------------------------------- /handouts/asn1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/handouts/asn1.pdf -------------------------------------------------------------------------------- /handouts/asn2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/handouts/asn2.pdf -------------------------------------------------------------------------------- /handouts/asn3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/handouts/asn3.pdf -------------------------------------------------------------------------------- /handouts/asn4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/handouts/asn4.pdf -------------------------------------------------------------------------------- /handouts/asn5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhq1065/coolc-compiler/4acb0710a577532d799c1bc355a5919b34c92d6b/handouts/asn5.pdf -------------------------------------------------------------------------------- /handouts/mymargins.tex: -------------------------------------------------------------------------------- 1 | % Side margins: 2 | % Actual margin is 1 in + this number 3 | \oddsidemargin -0.25in 4 | \evensidemargin -0.25in 5 | 6 | % Text width: 7 | \textwidth 6.9in 8 | 9 | % Top margin: 10 | % Actual margin is 1.5 in + this number 11 | \topmargin -.3in 12 | 13 | % Text height: 14 | \textheight 8.7in 15 | -------------------------------------------------------------------------------- /include/PA2/cgen_gc.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | // 8 | // Garbage collection options 9 | // 10 | 11 | extern enum Memmgr { GC_NOGC, GC_GENGC, GC_SNCGC } cgen_Memmgr; 12 | 13 | extern enum Memmgr_Test { GC_NORMAL, GC_TEST } cgen_Memmgr_Test; 14 | 15 | extern enum Memmgr_Debug { GC_QUICK, GC_DEBUG } cgen_Memmgr_Debug; 16 | -------------------------------------------------------------------------------- /include/PA2/cool-io.h: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件包含了cool编译器的输入输出所需要的所有头文件和名字空间 3 | // 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef COOL_IO_H 8 | #define COOL_IO_H 9 | 10 | // 11 | // include该文件的所有函数都可以使用c++的标准输入输出代码 12 | // 13 | 14 | //缺省使用标准的iostream 15 | #ifndef COOL_USE_OLD_HEADERS 16 | 17 | # include 18 | 19 | using std::ostream; 20 | using std::cout; 21 | using std::cerr; 22 | using std::endl; 23 | 24 | # include 25 | 26 | using std::ofstream; 27 | 28 | # include 29 | 30 | using std::oct; 31 | using std::dec; 32 | using std::setw; 33 | using std::setfill; 34 | 35 | //如果只包含std的名字空间,那么std:plus和plus AST中的节点类型产生冲突 36 | //using namespace std; 37 | 38 | #else 39 | // include老版本的头文件 40 | 41 | // 这里没有测试,但是应该是可以使用的 42 | # include 43 | # include 44 | # include 45 | 46 | #endif // COOL_USE_OLD_HEADERS 47 | 48 | 49 | #endif //COOL_IO_H 50 | -------------------------------------------------------------------------------- /include/PA2/cool-io.h~: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件包含了cool编译器的输入输出所需要的所有头文件和名字空间 3 | // 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef COOL_IO_H 8 | #define COOL_IO_H 9 | 10 | // 11 | // include该文件的所有函数都可以使用c++的标准输入输出代码 12 | // 13 | 14 | //缺省使用标准的iostream 15 | #ifndef COOL_USE_OLD_HEADERS 16 | 17 | # include 18 | 19 | using std::ostream; 20 | using std::cout; 21 | using std::cerr; 22 | using std::endl; 23 | 24 | # include 25 | 26 | using std::ofstream; 27 | 28 | # include 29 | 30 | using std::oct; 31 | using std::dec; 32 | using std::setw; 33 | using std::setfill; 34 | 35 | //如果只包含std的名字空间,那么std:plus和plus AST中的节点类型产生冲突 36 | //using namespace std; 37 | 38 | #else 39 | // include老版本的头文件 40 | 41 | // 这里没有测试,但是应该是可以使用的 42 | # include 43 | # include 44 | # include 45 | 46 | #endif // COOL_USE_OLD_HEADERS 47 | 48 | 49 | #endif //COOL_IO_H 50 | -------------------------------------------------------------------------------- /include/PA2/cool-parse.h: -------------------------------------------------------------------------------- 1 | #ifndef _COOL_PARSE_H 2 | #define _COOL_PARSE_H 3 | // 4 | // 该文件定义了词法过程中的记号和语法树中的节点结构 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _COOL_H_ 9 | #define _COOL_H_ 10 | 11 | #include 12 | 13 | //给类型起个新名字 14 | typedef int Boolean; 15 | class Entry; //Entry定义在stringtab.h文件中,表示语法树中的节点的类型(Int,String,id) 16 | typedef Entry *Symbol; //用Symbol表示Entry类型的指针 17 | 18 | //下面这些函数的实现在cool-tree.handcode.h文件当中,词法分析用不到 19 | Boolean copy_Boolean(Boolean); 20 | void assert_Boolean(Boolean); 21 | void dump_Boolean(std::ostream &,int,Boolean); 22 | 23 | //下面这些函数的实现在stringtab.cc文件当中,词法分析也用不到 24 | Symbol copy_Symbol(Symbol); 25 | void assert_Symbol(Symbol); 26 | void dump_Symbol(std::ostream &,int,Symbol); 27 | 28 | #endif 29 | 30 | //给节点类型都取一个别名 31 | #include "tree.h" 32 | typedef class Program_class *Program; 33 | typedef class Class__class *Class_; 34 | typedef class Feature_class *Feature; 35 | typedef class Formal_class *Formal; 36 | typedef class Expression_class *Expression; 37 | typedef class Case_class *Case; 38 | typedef list_node Classes_class; 39 | typedef Classes_class *Classes; 40 | typedef list_node Features_class; 41 | typedef Features_class *Features; 42 | typedef list_node Formals_class; 43 | typedef Formals_class *Formals; 44 | typedef list_node Expressions_class; 45 | typedef Expressions_class *Expressions; 46 | typedef list_node Cases_class; 47 | typedef Cases_class *Cases; 48 | 49 | //定义语法树的节点类型 50 | typedef union { 51 | Boolean boolean; 52 | Symbol symbol; 53 | Program program; 54 | Class_ class_; 55 | Classes classes; 56 | Feature feature; 57 | Features features; 58 | Formal formal; 59 | Formals formals; 60 | Case case_; 61 | Cases cases; 62 | Expression expression; 63 | Expressions expressions; 64 | char *error_msg; 65 | } YYSTYPE; 66 | 67 | //定义记号 68 | #define CLASS 258 69 | #define ELSE 259 70 | #define FI 260 71 | #define IF 261 72 | #define IN 262 73 | #define INHERITS 263 74 | #define LET 264 75 | #define LOOP 265 76 | #define POOL 266 77 | #define THEN 267 78 | #define WHILE 268 79 | #define CASE 269 80 | #define ESAC 270 81 | #define OF 271 82 | #define DARROW 272 83 | #define NEW 273 84 | #define ISVOID 274 85 | #define STR_CONST 275 86 | #define INT_CONST 276 87 | #define BOOL_CONST 277 88 | #define TYPEID 278 89 | #define OBJECTID 279 90 | #define ASSIGN 280 91 | #define NOT 281 92 | #define LE 282 93 | #define ERROR 283 94 | #define LET_STMT 284 95 | 96 | 97 | extern YYSTYPE cool_yylval; 98 | #endif 99 | -------------------------------------------------------------------------------- /include/PA2/cool-parse.h~: -------------------------------------------------------------------------------- 1 | #ifndef _COOL_PARSE_H 2 | #define _COOL_PARSE_H 3 | // 4 | // 该文件定义了词法过程中的记号和语法树中的节点结构 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _COOL_H_ 9 | #define _COOL_H_ 10 | 11 | #include 12 | 13 | //给类型起个新名字 14 | typedef int Boolean; 15 | class Entry; //Entry定义在stringtab.h文件中,表示语法树中的节点的类型(Int,String,id) 16 | typedef Entry *Symbol; //用Symbol表示Entry类型的指针 17 | 18 | //下面这些函数的实现在cool-tree.handcode.h文件当中,词法分析用不到 19 | Boolean copy_Boolean(Boolean); 20 | void assert_Boolean(Boolean); 21 | void dump_Boolean(std::ostream &,int,Boolean); 22 | 23 | //下面这些函数的实现在stringtab.cc文件当中,词法分析也用不到 24 | Symbol copy_Symbol(Symbol); 25 | void assert_Symbol(Symbol); 26 | void dump_Symbol(std::ostream &,int,Symbol); 27 | 28 | #endif 29 | 30 | //给节点类型都取一个别名 31 | #include "tree.h" 32 | typedef class Program_class *Program; 33 | typedef class Class__class *Class_; 34 | typedef class Feature_class *Feature; 35 | typedef class Formal_class *Formal; 36 | typedef class Expression_class *Expression; 37 | typedef class Case_class *Case; 38 | typedef list_node Classes_class; 39 | typedef Classes_class *Classes; 40 | typedef list_node Features_class; 41 | typedef Features_class *Features; 42 | typedef list_node Formals_class; 43 | typedef Formals_class *Formals; 44 | typedef list_node Expressions_class; 45 | typedef Expressions_class *Expressions; 46 | typedef list_node Cases_class; 47 | typedef Cases_class *Cases; 48 | 49 | //定义语法树的节点类型 50 | typedef union { 51 | Boolean boolean; 52 | Symbol symbol; 53 | Program program; 54 | Class_ class_; 55 | Classes classes; 56 | Feature feature; 57 | Features features; 58 | Formal formal; 59 | Formals formals; 60 | Case case_; 61 | Cases cases; 62 | Expression expression; 63 | Expressions expressions; 64 | char *error_msg; 65 | } YYSTYPE; 66 | 67 | //定义记号 68 | #define CLASS 258 69 | #define ELSE 259 70 | #define FI 260 71 | #define IF 261 72 | #define IN 262 73 | #define INHERITS 263 74 | #define LET 264 75 | #define LOOP 265 76 | #define POOL 266 77 | #define THEN 267 78 | #define WHILE 268 79 | #define CASE 269 80 | #define ESAC 270 81 | #define OF 271 82 | #define DARROW 272 83 | #define NEW 273 84 | #define ISVOID 274 85 | #define STR_CONST 275 86 | #define INT_CONST 276 87 | #define BOOL_CONST 277 88 | #define TYPEID 278 89 | #define OBJECTID 279 90 | #define ASSIGN 280 91 | #define NOT 281 92 | #define LE 282 93 | #define ERROR 283 94 | #define LET_STMT 284 95 | 96 | 97 | extern YYSTYPE cool_yylval; 98 | #endif 99 | -------------------------------------------------------------------------------- /include/PA2/cool.h: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件定义了cool当中常用的一些函数 3 | // 4 | #include "copyright.h" 5 | 6 | #ifndef _COOL_H_ 7 | #define _COOL_H_ 8 | 9 | #include "cool-io.h" 10 | 11 | typedef int Boolean; 12 | class Entry; 13 | typedef Entry *Symbol; 14 | 15 | Boolean copy_Boolean(Boolean); 16 | void assert_Boolean(Boolean); 17 | void dump_Boolean(ostream &,int,Boolean); 18 | 19 | Symbol copy_Symbol(Symbol); 20 | void assert_Symbol(Symbol); 21 | void dump_Symbol(ostream &,int,Symbol); 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /include/PA2/cool.h~: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件定义了cool当中常用的一些函数 3 | // 4 | #include "copyright.h" 5 | 6 | #ifndef _COOL_H_ 7 | #define _COOL_H_ 8 | 9 | #include "cool-io.h" 10 | 11 | typedef int Boolean; 12 | class Entry; 13 | typedef Entry *Symbol; 14 | 15 | Boolean copy_Boolean(Boolean); 16 | void assert_Boolean(Boolean); 17 | void dump_Boolean(ostream &,int,Boolean); 18 | 19 | Symbol copy_Symbol(Symbol); 20 | void assert_Symbol(Symbol); 21 | void dump_Symbol(ostream &,int,Symbol); 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /include/PA2/copyright.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 1995,1996 The Regents of the University of California. 3 | All rights reserved. 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose, without fee, and without written agreement is hereby granted, 7 | provided that the above copyright notice and the following two 8 | paragraphs appear in all copies of this software. 9 | 10 | IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 11 | DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 12 | OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 13 | CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 14 | 15 | THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 16 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 17 | AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 18 | ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 19 | PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 20 | */ 21 | -------------------------------------------------------------------------------- /include/PA2/list.h: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件定义了一个list的模版以及和list相关的操作函数 3 | // 4 | #include "copyright.h" 5 | 6 | #ifndef _LIST_H_ 7 | #define _LIST_H_ 8 | 9 | #include "cool-io.h" 10 | #include 11 | 12 | template 13 | class List { 14 | private: 15 | T *head; 16 | List* tail; 17 | public: 18 | List(T *h,List* t = NULL): head(h), tail(t) { } 19 | 20 | T *hd() const { return head; } 21 | List* tl() const { return tail; } 22 | }; 23 | 24 | ///////////////////////////////////////////////////////////////////////// 25 | // 26 | // 和list相关的函数模版 27 | // 28 | // 为了方便定义多个list的情况,这里将函数定义为模版函数,而不是list类的成员函数 29 | // 30 | ///////////////////////////////////////////////////////////////////////// 31 | 32 | // 33 | // Map a function for its side effect over a list. 34 | // 35 | template 36 | void list_map(void f(T*), List *l) 37 | { 38 | for (l; l != NULL; l = l->tl()) 39 | f(l->hd()); 40 | } 41 | 42 | // 43 | // 将已知的list打印出来 44 | // 这里需要求"<<" 对该S类型定义过. 45 | // 46 | template 47 | void list_print(S &str, List *l) 48 | { 49 | str << "[\n"; 50 | for(; l != NULL; l = l->tl()) 51 | str << *(l->hd()) << " "; 52 | str << "]\n"; 53 | } 54 | 55 | // 56 | // 计算一个list的长度 57 | // 58 | template 59 | int list_length(List *l) 60 | { 61 | int i = 0; 62 | for (; l != NULL; l = l->tl()) 63 | i++; 64 | return i; 65 | } 66 | 67 | #endif 68 | 69 | -------------------------------------------------------------------------------- /include/PA2/list.h~: -------------------------------------------------------------------------------- 1 | // 2 | // 该文件定义了一个list的模版以及和list相关的操作函数 3 | // 4 | #include "copyright.h" 5 | 6 | #ifndef _LIST_H_ 7 | #define _LIST_H_ 8 | 9 | #include "cool-io.h" 10 | #include 11 | 12 | template 13 | class List { 14 | private: 15 | T *head; 16 | List* tail; 17 | public: 18 | List(T *h,List* t = NULL): head(h), tail(t) { } 19 | 20 | T *hd() const { return head; } 21 | List* tl() const { return tail; } 22 | }; 23 | 24 | ///////////////////////////////////////////////////////////////////////// 25 | // 26 | // 和list相关的函数模版 27 | // 28 | // 为了方便定义多个list的情况,这里将函数定义为模版函数,而不是list类的成员函数 29 | // 30 | ///////////////////////////////////////////////////////////////////////// 31 | 32 | // 33 | // Map a function for its side effect over a list. 34 | // 35 | template 36 | void list_map(void f(T*), List *l) 37 | { 38 | for (l; l != NULL; l = l->tl()) 39 | f(l->hd()); 40 | } 41 | 42 | // 43 | // 将已知的list打印出来 44 | // 这里需要求"<<" 对该S类型定义过. 45 | // 46 | template 47 | void list_print(S &str, List *l) 48 | { 49 | str << "[\n"; 50 | for(; l != NULL; l = l->tl()) 51 | str << *(l->hd()) << " "; 52 | str << "]\n"; 53 | } 54 | 55 | // 56 | // 计算一个list的长度 57 | // 58 | template 59 | int list_length(List *l) 60 | { 61 | int i = 0; 62 | for (; l != NULL; l = l->tl()) 63 | i++; 64 | return i; 65 | } 66 | 67 | #endif 68 | 69 | -------------------------------------------------------------------------------- /include/PA2/stringtab_functions.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include "cool-io.h" 8 | #define MAXSIZE 1000000 9 | #define min(a,b) (a > b ? b : a) 10 | 11 | #include "stringtab.h" 12 | #include 13 | 14 | // 15 | // A string table is implemented a linked list of Entrys. Each Entry 16 | // in the list has a unique string. 17 | // 18 | 19 | template 20 | Elem *StringTable::add_string(char *s) 21 | { 22 | return add_string(s,MAXSIZE); 23 | } 24 | 25 | // 26 | // Add a string requires two steps. First, the list is searched; if the 27 | // string is found, a pointer to the existing Entry for that string is 28 | // returned. If the string is not found, a new Entry is created and added 29 | // to the list. 30 | // 31 | template 32 | Elem *StringTable::add_string(char *s, int maxchars) 33 | { 34 | int len = min((int) strlen(s),maxchars); 35 | for(List *l = tbl; l; l = l->tl()) 36 | if (l->hd()->equal_string(s,len)) 37 | return l->hd(); 38 | 39 | Elem *e = new Elem(s,len,index++); 40 | tbl = new List(e, tbl); 41 | return e; 42 | } 43 | 44 | // 45 | // To look up a string, the list is scanned until a matching Entry is located. 46 | // If no such entry is found, an assertion failure occurs. Thus, this function 47 | // is used only for strings that one expects to find in the table. 48 | // 49 | template 50 | Elem *StringTable::lookup_string(char *s) 51 | { 52 | int len = strlen(s); 53 | for(List *l = tbl; l; l = l->tl()) 54 | if (l->hd()->equal_string(s,len)) 55 | return l->hd(); 56 | assert(0); // fail if string is not found 57 | return NULL; // to avoid compiler warning 58 | } 59 | 60 | // 61 | // lookup is similar to lookup_string, but uses the index of the string 62 | // as the key. 63 | // 64 | template 65 | Elem *StringTable::lookup(int ind) 66 | { 67 | for(List *l = tbl; l; l = l->tl()) 68 | if (l->hd()->equal_index(ind)) 69 | return l->hd(); 70 | assert(0); // fail if string is not found 71 | return NULL; // to avoid compiler warning 72 | } 73 | 74 | // 75 | // add_int adds the string representation of an integer to the list. 76 | // 77 | template 78 | Elem *StringTable::add_int(int i) 79 | { 80 | static char *buf = new char[20]; 81 | snprintf(buf, 20, "%d", i); 82 | return add_string(buf); 83 | } 84 | template 85 | int StringTable::first() 86 | { 87 | return 0; 88 | } 89 | 90 | template 91 | int StringTable::more(int i) 92 | { 93 | return i < index; 94 | } 95 | 96 | template 97 | int StringTable::next(int i) 98 | { 99 | assert(i < index); 100 | return i+1; 101 | } 102 | 103 | template 104 | void StringTable::print() 105 | { 106 | list_print(cerr,tbl); 107 | } 108 | -------------------------------------------------------------------------------- /include/PA2/utilities.h: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | #include "cool-io.h" 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA2/utilities.h~: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | #include "cool-io.h" 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA3/cgen_gc.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | // 8 | // Garbage collection options 9 | // 10 | 11 | extern enum Memmgr { GC_NOGC, GC_GENGC, GC_SNCGC } cgen_Memmgr; 12 | 13 | extern enum Memmgr_Test { GC_NORMAL, GC_TEST } cgen_Memmgr_Test; 14 | 15 | extern enum Memmgr_Debug { GC_QUICK, GC_DEBUG } cgen_Memmgr_Debug; 16 | -------------------------------------------------------------------------------- /include/PA3/cool-io.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef COOL_IO_H 8 | #define COOL_IO_H 9 | 10 | // 11 | // Cool files include this header to use the standard library's 12 | // IO streams. 13 | // 14 | 15 | //By default use the ANSI standard iostream, etc. 16 | #ifndef COOL_USE_OLD_HEADERS 17 | 18 | # include 19 | 20 | using std::ostream; 21 | using std::cout; 22 | using std::cerr; 23 | using std::endl; 24 | 25 | # include 26 | 27 | using std::ofstream; 28 | 29 | # include 30 | 31 | using std::oct; 32 | using std::dec; 33 | using std::setw; 34 | using std::setfill; 35 | 36 | //Including the entire std namespace doesn't work well because of conflicts 37 | //between e.g. std::plus and the plus AST node. 38 | //using namespace std; 39 | 40 | #else 41 | // COOL_USE_OLD_HEADERS is defined 42 | 43 | // I haven't actually tested this, but it ought to work 44 | # include 45 | # include 46 | # include 47 | 48 | #endif // COOL_USE_OLD_HEADERS 49 | 50 | 51 | #endif //COOL_IO_H 52 | -------------------------------------------------------------------------------- /include/PA3/cool-tree.handcode.h: -------------------------------------------------------------------------------- 1 | // 2 | // 改文件定义了一些类型的别名,并实现了一些打印和拷贝基础类型的函数 3 | 4 | #ifndef COOL_TREE_HANDCODE_H 5 | #define COOL_TREE_HANDCODE_H 6 | 7 | #include 8 | #include "tree.h" 9 | #include "cool.h" 10 | #include "stringtab.h" 11 | 12 | #define yylineno curr_lineno; 13 | extern int yylineno; 14 | 15 | inline Boolean copy_Boolean(Boolean b) {return b; } 16 | inline void assert_Boolean(Boolean) {} 17 | inline void dump_Boolean(std::ostream& stream, int padding, Boolean b) 18 | { stream << pad(padding) << (int) b << "\n"; } 19 | 20 | void dump_Symbol(std::ostream& stream, int padding, Symbol b); 21 | void assert_Symbol(Symbol b); 22 | Symbol copy_Symbol(Symbol b); 23 | 24 | class Program_class; 25 | typedef Program_class *Program; 26 | class Class__class; 27 | typedef Class__class *Class_; 28 | class Feature_class; 29 | typedef Feature_class *Feature; 30 | class Formal_class; 31 | typedef Formal_class *Formal; 32 | class Expression_class; 33 | typedef Expression_class *Expression; 34 | class Case_class; 35 | typedef Case_class *Case; 36 | 37 | typedef list_node Classes_class; 38 | typedef Classes_class *Classes; 39 | typedef list_node Features_class; 40 | typedef Features_class *Features; 41 | typedef list_node Formals_class; 42 | typedef Formals_class *Formals; 43 | typedef list_node Expressions_class; 44 | typedef Expressions_class *Expressions; 45 | typedef list_node Cases_class; 46 | typedef Cases_class *Cases; 47 | 48 | #define Program_EXTRAS \ 49 | virtual void dump_with_types(std::ostream&, int) = 0; 50 | 51 | 52 | 53 | #define program_EXTRAS \ 54 | void dump_with_types(std::ostream&, int); 55 | 56 | #define Class__EXTRAS \ 57 | virtual Symbol get_filename() = 0; \ 58 | virtual void dump_with_types(std::ostream&,int) = 0; 59 | 60 | 61 | #define class__EXTRAS \ 62 | Symbol get_filename() { return filename; } \ 63 | void dump_with_types(std::ostream&,int); 64 | 65 | 66 | #define Feature_EXTRAS \ 67 | virtual void dump_with_types(std::ostream&,int) = 0; 68 | 69 | 70 | #define Feature_SHARED_EXTRAS \ 71 | void dump_with_types(std::ostream&,int); 72 | 73 | 74 | 75 | 76 | 77 | #define Formal_EXTRAS \ 78 | virtual void dump_with_types(std::ostream&,int) = 0; 79 | 80 | 81 | #define formal_EXTRAS \ 82 | void dump_with_types(std::ostream&,int); 83 | 84 | 85 | #define Case_EXTRAS \ 86 | virtual void dump_with_types(std::ostream& ,int) = 0; 87 | 88 | 89 | #define branch_EXTRAS \ 90 | void dump_with_types(std::ostream& ,int); 91 | 92 | 93 | #define Expression_EXTRAS \ 94 | Symbol type; \ 95 | Symbol get_type() { return type; } \ 96 | Expression set_type(Symbol s) { type = s; return this; } \ 97 | virtual void dump_with_types(std::ostream&,int) = 0; \ 98 | void dump_type(std::ostream&, int); \ 99 | Expression_class() { type = (Symbol) NULL; } 100 | 101 | 102 | 103 | #define Expression_SHARED_EXTRAS \ 104 | void dump_with_types(std::ostream&,int); 105 | 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /include/PA3/cool-tree.handcode.h~: -------------------------------------------------------------------------------- 1 | // 2 | // 改文件定义了一些类型的别名,并实现了一些打印和拷贝基础类型的函数 3 | 4 | #ifndef COOL_TREE_HANDCODE_H 5 | #define COOL_TREE_HANDCODE_H 6 | 7 | #include 8 | #include "tree.h" 9 | #include "cool.h" 10 | #include "stringtab.h" 11 | 12 | #define yylineno curr_lineno; 13 | extern int yylineno; 14 | 15 | inline Boolean copy_Boolean(Boolean b) {return b; } 16 | inline void assert_Boolean(Boolean) {} 17 | inline void dump_Boolean(std::ostream& stream, int padding, Boolean b) 18 | { stream << pad(padding) << (int) b << "\n"; } 19 | 20 | void dump_Symbol(std::ostream& stream, int padding, Symbol b); 21 | void assert_Symbol(Symbol b); 22 | Symbol copy_Symbol(Symbol b); 23 | 24 | class Program_class; 25 | typedef Program_class *Program; 26 | class Class__class; 27 | typedef Class__class *Class_; 28 | class Feature_class; 29 | typedef Feature_class *Feature; 30 | class Formal_class; 31 | typedef Formal_class *Formal; 32 | class Expression_class; 33 | typedef Expression_class *Expression; 34 | class Case_class; 35 | typedef Case_class *Case; 36 | 37 | typedef list_node Classes_class; 38 | typedef Classes_class *Classes; 39 | typedef list_node Features_class; 40 | typedef Features_class *Features; 41 | typedef list_node Formals_class; 42 | typedef Formals_class *Formals; 43 | typedef list_node Expressions_class; 44 | typedef Expressions_class *Expressions; 45 | typedef list_node Cases_class; 46 | typedef Cases_class *Cases; 47 | 48 | #define Program_EXTRAS \ 49 | virtual void dump_with_types(std::ostream&, int) = 0; 50 | 51 | 52 | 53 | #define program_EXTRAS \ 54 | void dump_with_types(std::ostream&, int); 55 | 56 | #define Class__EXTRAS \ 57 | virtual Symbol get_filename() = 0; \ 58 | virtual void dump_with_types(std::ostream&,int) = 0; 59 | 60 | 61 | #define class__EXTRAS \ 62 | Symbol get_filename() { return filename; } \ 63 | void dump_with_types(std::ostream&,int); 64 | 65 | 66 | #define Feature_EXTRAS \ 67 | virtual void dump_with_types(std::ostream&,int) = 0; 68 | 69 | 70 | #define Feature_SHARED_EXTRAS \ 71 | void dump_with_types(std::ostream&,int); 72 | 73 | 74 | 75 | 76 | 77 | #define Formal_EXTRAS \ 78 | virtual void dump_with_types(std::ostream&,int) = 0; 79 | 80 | 81 | #define formal_EXTRAS \ 82 | void dump_with_types(std::ostream&,int); 83 | 84 | 85 | #define Case_EXTRAS \ 86 | virtual void dump_with_types(std::ostream& ,int) = 0; 87 | 88 | 89 | #define branch_EXTRAS \ 90 | void dump_with_types(std::ostream& ,int); 91 | 92 | 93 | #define Expression_EXTRAS \ 94 | Symbol type; \ 95 | Symbol get_type() { return type; } \ 96 | Expression set_type(Symbol s) { type = s; return this; } \ 97 | virtual void dump_with_types(std::ostream&,int) = 0; \ 98 | void dump_type(std::ostream&, int); \ 99 | Expression_class() { type = (Symbol) NULL; } 100 | 101 | 102 | 103 | #define Expression_SHARED_EXTRAS \ 104 | void dump_with_types(std::ostream&,int); 105 | 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /include/PA3/cool.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef _COOL_H_ 8 | #define _COOL_H_ 9 | 10 | #include 11 | 12 | /* a type renaming */ 13 | typedef int Boolean; 14 | class Entry; 15 | typedef Entry *Symbol; 16 | 17 | Boolean copy_Boolean(Boolean); 18 | void assert_Boolean(Boolean); 19 | void dump_Boolean(std::ostream &,int,Boolean); 20 | 21 | Symbol copy_Symbol(Symbol); 22 | void assert_Symbol(Symbol); 23 | void dump_Symbol(std::ostream &,int,Symbol); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /include/PA3/cool.h~: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef _COOL_H_ 8 | #define _COOL_H_ 9 | 10 | #include 11 | 12 | /* a type renaming */ 13 | typedef int Boolean; 14 | class Entry; 15 | typedef Entry *Symbol; 16 | 17 | Boolean copy_Boolean(Boolean); 18 | void assert_Boolean(Boolean); 19 | void dump_Boolean(std::ostream &,int,Boolean); 20 | 21 | Symbol copy_Symbol(Symbol); 22 | void assert_Symbol(Symbol); 23 | void dump_Symbol(std::ostream &,int,Symbol); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /include/PA3/copyright.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 1995,1996 The Regents of the University of California. 3 | All rights reserved. 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose, without fee, and without written agreement is hereby granted, 7 | provided that the above copyright notice and the following two 8 | paragraphs appear in all copies of this software. 9 | 10 | IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 11 | DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 12 | OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 13 | CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 14 | 15 | THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 16 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 17 | AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 18 | ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 19 | PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 20 | */ 21 | -------------------------------------------------------------------------------- /include/PA3/list.h: -------------------------------------------------------------------------------- 1 | /* -*-Mode: C++;-*- */ 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | ////////////////////////////////////////////////////////////////////// 10 | // 11 | // list.h 12 | // 13 | // This file implements a list template. 14 | // Adapted from similar templates written by Kathy Yelick and 15 | // Paul Hilfinger. 16 | // 17 | ////////////////////////////////////////////////////////////////////// 18 | 19 | #ifndef _LIST_H_ 20 | #define _LIST_H_ 21 | 22 | #include 23 | #include 24 | 25 | 26 | template 27 | class List { 28 | private: 29 | T *head; 30 | List* tail; 31 | public: 32 | List(T *h,List* t = NULL): head(h), tail(t) { } 33 | 34 | T *hd() const { return head; } 35 | List* tl() const { return tail; } 36 | }; 37 | 38 | ///////////////////////////////////////////////////////////////////////// 39 | // 40 | // list function templates 41 | // 42 | // To avoid potential problems with mutliple definitions of 43 | // the List<> class members, the list functions are not members of the 44 | // list class. 45 | // 46 | ///////////////////////////////////////////////////////////////////////// 47 | 48 | // 49 | // Map a function for its side effect over a list. 50 | // 51 | template 52 | void list_map(void f(T*), List *l) 53 | { 54 | for (l; l != NULL; l = l->tl()) 55 | f(l->hd()); 56 | } 57 | 58 | // 59 | // Print the given list on the standard output. 60 | // Requires that "<<" be defined for the element type. 61 | // 62 | template 63 | void list_print(S &str, List *l) 64 | { 65 | str << "[\n"; 66 | for(; l != NULL; l = l->tl()) 67 | str << *(l->hd()) << " "; 68 | str << "]\n"; 69 | } 70 | 71 | // 72 | // Compute the length of a list. 73 | // 74 | template 75 | int list_length(List *l) 76 | { 77 | int i = 0; 78 | for (; l != NULL; l = l->tl()) 79 | i++; 80 | return i; 81 | } 82 | 83 | #endif 84 | 85 | -------------------------------------------------------------------------------- /include/PA3/list.h~: -------------------------------------------------------------------------------- 1 | /* -*-Mode: C++;-*- */ 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | ////////////////////////////////////////////////////////////////////// 10 | // 11 | // list.h 12 | // 13 | // This file implements a list template. 14 | // Adapted from similar templates written by Kathy Yelick and 15 | // Paul Hilfinger. 16 | // 17 | ////////////////////////////////////////////////////////////////////// 18 | 19 | #ifndef _LIST_H_ 20 | #define _LIST_H_ 21 | 22 | #include 23 | #include 24 | 25 | 26 | template 27 | class List { 28 | private: 29 | T *head; 30 | List* tail; 31 | public: 32 | List(T *h,List* t = NULL): head(h), tail(t) { } 33 | 34 | T *hd() const { return head; } 35 | List* tl() const { return tail; } 36 | }; 37 | 38 | ///////////////////////////////////////////////////////////////////////// 39 | // 40 | // list function templates 41 | // 42 | // To avoid potential problems with mutliple definitions of 43 | // the List<> class members, the list functions are not members of the 44 | // list class. 45 | // 46 | ///////////////////////////////////////////////////////////////////////// 47 | 48 | // 49 | // Map a function for its side effect over a list. 50 | // 51 | template 52 | void list_map(void f(T*), List *l) 53 | { 54 | for (l; l != NULL; l = l->tl()) 55 | f(l->hd()); 56 | } 57 | 58 | // 59 | // Print the given list on the standard output. 60 | // Requires that "<<" be defined for the element type. 61 | // 62 | template 63 | void list_print(S &str, List *l) 64 | { 65 | str << "[\n"; 66 | for(; l != NULL; l = l->tl()) 67 | str << *(l->hd()) << " "; 68 | str << "]\n"; 69 | } 70 | 71 | // 72 | // Compute the length of a list. 73 | // 74 | template 75 | int list_length(List *l) 76 | { 77 | int i = 0; 78 | for (; l != NULL; l = l->tl()) 79 | i++; 80 | return i; 81 | } 82 | 83 | #endif 84 | 85 | -------------------------------------------------------------------------------- /include/PA3/stringtab.h: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | #ifndef _STRINGTAB_H_ 10 | #define _STRINGTAB_H_ 11 | 12 | #include 13 | #include 14 | #include "list.h" // list template 15 | 16 | class Entry; 17 | typedef Entry* Symbol; 18 | 19 | extern std::ostream& operator<<(std::ostream& s, const Entry& sym); 20 | extern std::ostream& operator<<(std::ostream& s, Symbol sym); 21 | 22 | ///////////////////////////////////////////////////////////////////////// 23 | // 24 | // Entry是符号表的基础类型 25 | // 26 | ///////////////////////////////////////////////////////////////////////// 27 | 28 | class Entry { 29 | protected: 30 | char *str; // 存一个字符串 31 | int len; // 长度 32 | int index; // 唯一的索引值 33 | public: 34 | Entry(char *s, int l, int i); 35 | 36 | int equal_string(char *s, int len) const; 37 | 38 | bool equal_index(int ind) const { return ind == index; } 39 | 40 | std::ostream& print(std::ostream& s) const; 41 | 42 | char *get_string() const; 43 | int get_len() const; 44 | }; 45 | 46 | class StringEntry : public Entry { 47 | public: 48 | void code_def(std::ostream& str, int stringclasstag); 49 | void code_ref(std::ostream& str); 50 | StringEntry(char *s, int l, int i); 51 | }; 52 | 53 | class IdEntry : public Entry { 54 | public: 55 | IdEntry(char *s, int l, int i); 56 | }; 57 | 58 | class IntEntry: public Entry { 59 | public: 60 | void code_def(std::ostream& str, int intclasstag); 61 | void code_ref(std::ostream& str); 62 | IntEntry(char *s, int l, int i); 63 | }; 64 | 65 | typedef StringEntry *StringEntryP; 66 | typedef IdEntry *IdEntryP; 67 | typedef IntEntry *IntEntryP; 68 | 69 | ////////////////////////////////////////////////////////////////////////// 70 | // 71 | // 符号表的模版,模版中方法的实现见stringtab_functions.h 72 | // 73 | ////////////////////////////////////////////////////////////////////////// 74 | 75 | template 76 | class StringTable 77 | { 78 | protected: 79 | List *tbl; // 符号表是个list 80 | int index; // 当前的索引 81 | public: 82 | StringTable(): tbl((List *) NULL), index(0) { } // 初始化一个空的符号表 83 | 84 | Elem *add_string(char *s, int maxchars); 85 | 86 | Elem *add_string(char *s); 87 | 88 | Elem *add_int(int i); 89 | 90 | 91 | // 迭代. 92 | int first(); 93 | int more(int i); 94 | int next(int i); 95 | 96 | Elem *lookup(int index); // 根据索引查找 97 | Elem *lookup_string(char *s); // 根据字符内容查找 98 | 99 | void print(); // 打印整个符号表,调试时使用 100 | 101 | }; 102 | 103 | class IdTable : public StringTable { }; 104 | 105 | class StrTable : public StringTable 106 | { 107 | public: 108 | void code_string_table(std::ostream&, int classtag); 109 | }; 110 | 111 | class IntTable : public StringTable 112 | { 113 | public: 114 | void code_string_table(std::ostream&, int classtag); 115 | }; 116 | 117 | extern IdTable idtable; 118 | extern IntTable inttable; 119 | extern StrTable stringtable; 120 | #endif 121 | -------------------------------------------------------------------------------- /include/PA3/stringtab.h~: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | #ifndef _STRINGTAB_H_ 10 | #define _STRINGTAB_H_ 11 | 12 | #include 13 | #include 14 | #include "list.h" // list template 15 | 16 | class Entry; 17 | typedef Entry* Symbol; 18 | 19 | extern std::ostream& operator<<(std::ostream& s, const Entry& sym); 20 | extern std::ostream& operator<<(std::ostream& s, Symbol sym); 21 | 22 | ///////////////////////////////////////////////////////////////////////// 23 | // 24 | // Entry是符号表的基础类型 25 | // 26 | ///////////////////////////////////////////////////////////////////////// 27 | 28 | class Entry { 29 | protected: 30 | char *str; // 存一个字符串 31 | int len; // 长度 32 | int index; // 唯一的索引值 33 | public: 34 | Entry(char *s, int l, int i); 35 | 36 | int equal_string(char *s, int len) const; 37 | 38 | bool equal_index(int ind) const { return ind == index; } 39 | 40 | std::ostream& print(std::ostream& s) const; 41 | 42 | char *get_string() const; 43 | int get_len() const; 44 | }; 45 | 46 | class StringEntry : public Entry { 47 | public: 48 | void code_def(std::ostream& str, int stringclasstag); 49 | void code_ref(std::ostream& str); 50 | StringEntry(char *s, int l, int i); 51 | }; 52 | 53 | class IdEntry : public Entry { 54 | public: 55 | IdEntry(char *s, int l, int i); 56 | }; 57 | 58 | class IntEntry: public Entry { 59 | public: 60 | void code_def(std::ostream& str, int intclasstag); 61 | void code_ref(std::ostream& str); 62 | IntEntry(char *s, int l, int i); 63 | }; 64 | 65 | typedef StringEntry *StringEntryP; 66 | typedef IdEntry *IdEntryP; 67 | typedef IntEntry *IntEntryP; 68 | 69 | ////////////////////////////////////////////////////////////////////////// 70 | // 71 | // 符号表的模版,模版中方法的实现见stringtab_functions.h 72 | // 73 | ////////////////////////////////////////////////////////////////////////// 74 | 75 | template 76 | class StringTable 77 | { 78 | protected: 79 | List *tbl; // 符号表是个list 80 | int index; // 当前的索引 81 | public: 82 | StringTable(): tbl((List *) NULL), index(0) { } // 初始化一个空的符号表 83 | 84 | Elem *add_string(char *s, int maxchars); 85 | 86 | Elem *add_string(char *s); 87 | 88 | Elem *add_int(int i); 89 | 90 | 91 | // 迭代. 92 | int first(); 93 | int more(int i); 94 | int next(int i); 95 | 96 | Elem *lookup(int index); // 根据索引查找 97 | Elem *lookup_string(char *s); // 根据字符内容查找 98 | 99 | void print(); // 打印整个符号表,调试时使用 100 | 101 | }; 102 | 103 | class IdTable : public StringTable { }; 104 | 105 | class StrTable : public StringTable 106 | { 107 | public: 108 | void code_string_table(std::ostream&, int classtag); 109 | }; 110 | 111 | class IntTable : public StringTable 112 | { 113 | public: 114 | void code_string_table(std::ostream&, int classtag); 115 | }; 116 | 117 | extern IdTable idtable; 118 | extern IntTable inttable; 119 | extern StrTable stringtable; 120 | #endif 121 | -------------------------------------------------------------------------------- /include/PA3/stringtab_functions.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include "cool-io.h" 8 | #define MAXSIZE 1000000 9 | #define min(a,b) (a > b ? b : a) 10 | 11 | #include "stringtab.h" 12 | #include 13 | 14 | // 15 | // A string table is implemented a linked list of Entrys. Each Entry 16 | // in the list has a unique string. 17 | // 18 | 19 | template 20 | Elem *StringTable::add_string(char *s) 21 | { 22 | return add_string(s,MAXSIZE); 23 | } 24 | 25 | // 26 | // Add a string requires two steps. First, the list is searched; if the 27 | // string is found, a pointer to the existing Entry for that string is 28 | // returned. If the string is not found, a new Entry is created and added 29 | // to the list. 30 | // 31 | template 32 | Elem *StringTable::add_string(char *s, int maxchars) 33 | { 34 | int len = min((int) strlen(s),maxchars); 35 | for(List *l = tbl; l; l = l->tl()) 36 | if (l->hd()->equal_string(s,len)) 37 | return l->hd(); 38 | 39 | Elem *e = new Elem(s,len,index++); 40 | tbl = new List(e, tbl); 41 | return e; 42 | } 43 | 44 | // 45 | // To look up a string, the list is scanned until a matching Entry is located. 46 | // If no such entry is found, an assertion failure occurs. Thus, this function 47 | // is used only for strings that one expects to find in the table. 48 | // 49 | template 50 | Elem *StringTable::lookup_string(char *s) 51 | { 52 | int len = strlen(s); 53 | for(List *l = tbl; l; l = l->tl()) 54 | if (l->hd()->equal_string(s,len)) 55 | return l->hd(); 56 | assert(0); // fail if string is not found 57 | return NULL; // to avoid compiler warning 58 | } 59 | 60 | // 61 | // lookup is similar to lookup_string, but uses the index of the string 62 | // as the key. 63 | // 64 | template 65 | Elem *StringTable::lookup(int ind) 66 | { 67 | for(List *l = tbl; l; l = l->tl()) 68 | if (l->hd()->equal_index(ind)) 69 | return l->hd(); 70 | assert(0); // fail if string is not found 71 | return NULL; // to avoid compiler warning 72 | } 73 | 74 | // 75 | // add_int adds the string representation of an integer to the list. 76 | // 77 | template 78 | Elem *StringTable::add_int(int i) 79 | { 80 | static char *buf = new char[20]; 81 | snprintf(buf, 20, "%d", i); 82 | return add_string(buf); 83 | } 84 | template 85 | int StringTable::first() 86 | { 87 | return 0; 88 | } 89 | 90 | template 91 | int StringTable::more(int i) 92 | { 93 | return i < index; 94 | } 95 | 96 | template 97 | int StringTable::next(int i) 98 | { 99 | assert(i < index); 100 | return i+1; 101 | } 102 | 103 | template 104 | void StringTable::print() 105 | { 106 | list_print(cerr,tbl); 107 | } 108 | -------------------------------------------------------------------------------- /include/PA3/utilities.h: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | #include "cool-io.h" 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA3/utilities.h~: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | #include "cool-io.h" 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA4/cgen_gc.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | // 8 | // Garbage collection options 9 | // 10 | 11 | extern enum Memmgr { GC_NOGC, GC_GENGC, GC_SNCGC } cgen_Memmgr; 12 | 13 | extern enum Memmgr_Test { GC_NORMAL, GC_TEST } cgen_Memmgr_Test; 14 | 15 | extern enum Memmgr_Debug { GC_QUICK, GC_DEBUG } cgen_Memmgr_Debug; 16 | -------------------------------------------------------------------------------- /include/PA4/cool-io.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef COOL_IO_H 8 | #define COOL_IO_H 9 | 10 | // 11 | // Cool files include this header to use the standard library's 12 | // IO streams. 13 | // 14 | 15 | //By default use the ANSI standard iostream, etc. 16 | #ifndef COOL_USE_OLD_HEADERS 17 | 18 | # include 19 | 20 | using std::ostream; 21 | using std::cout; 22 | using std::cerr; 23 | using std::endl; 24 | 25 | # include 26 | 27 | using std::ofstream; 28 | 29 | # include 30 | 31 | using std::oct; 32 | using std::dec; 33 | using std::setw; 34 | using std::setfill; 35 | 36 | //Including the entire std namespace doesn't work well because of conflicts 37 | //between e.g. std::plus and the plus AST node. 38 | //using namespace std; 39 | 40 | #else 41 | // COOL_USE_OLD_HEADERS is defined 42 | 43 | // I haven't actually tested this, but it ought to work 44 | # include 45 | # include 46 | # include 47 | 48 | #endif // COOL_USE_OLD_HEADERS 49 | 50 | 51 | #endif //COOL_IO_H 52 | -------------------------------------------------------------------------------- /include/PA4/cool.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef _COOL_H_ 8 | #define _COOL_H_ 9 | 10 | #include 11 | 12 | /* a type renaming */ 13 | typedef int Boolean; 14 | class Entry; 15 | typedef Entry *Symbol; 16 | 17 | Boolean copy_Boolean(Boolean); 18 | void assert_Boolean(Boolean); 19 | void dump_Boolean(std::ostream &,int,Boolean); 20 | 21 | Symbol copy_Symbol(Symbol); 22 | void assert_Symbol(Symbol); 23 | void dump_Symbol(std::ostream &,int,Symbol); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /include/PA4/cool.h~: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef _COOL_H_ 8 | #define _COOL_H_ 9 | 10 | #include 11 | 12 | /* a type renaming */ 13 | typedef int Boolean; 14 | class Entry; 15 | typedef Entry *Symbol; 16 | 17 | Boolean copy_Boolean(Boolean); 18 | void assert_Boolean(Boolean); 19 | void dump_Boolean(std::ostream &,int,Boolean); 20 | 21 | Symbol copy_Symbol(Symbol); 22 | void assert_Symbol(Symbol); 23 | void dump_Symbol(std::ostream &,int,Symbol); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /include/PA4/copyright.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 1995,1996 The Regents of the University of California. 3 | All rights reserved. 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose, without fee, and without written agreement is hereby granted, 7 | provided that the above copyright notice and the following two 8 | paragraphs appear in all copies of this software. 9 | 10 | IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 11 | DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 12 | OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 13 | CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 14 | 15 | THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 16 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 17 | AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 18 | ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 19 | PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 20 | */ 21 | -------------------------------------------------------------------------------- /include/PA4/list.h: -------------------------------------------------------------------------------- 1 | /* -*-Mode: C++;-*- */ 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | ////////////////////////////////////////////////////////////////////// 10 | // 11 | // list.h 12 | // 13 | // This file implements a list template. 14 | // Adapted from similar templates written by Kathy Yelick and 15 | // Paul Hilfinger. 16 | // 17 | ////////////////////////////////////////////////////////////////////// 18 | 19 | #ifndef _LIST_H_ 20 | #define _LIST_H_ 21 | 22 | #include 23 | #include 24 | 25 | template 26 | class List { 27 | private: 28 | T *head; 29 | List* tail; 30 | public: 31 | List(T *h,List* t = NULL): head(h), tail(t) { } 32 | 33 | T *hd() const { return head; } 34 | List* tl() const { return tail; } 35 | }; 36 | 37 | ///////////////////////////////////////////////////////////////////////// 38 | // 39 | // list function templates 40 | // 41 | // To avoid potential problems with mutliple definitions of 42 | // the List<> class members, the list functions are not members of the 43 | // list class. 44 | // 45 | ///////////////////////////////////////////////////////////////////////// 46 | 47 | // 48 | // Map a function for its side effect over a list. 49 | // 50 | template 51 | void list_map(void f(T*), List *l) 52 | { 53 | for (l; l != NULL; l = l->tl()) 54 | f(l->hd()); 55 | } 56 | 57 | // 58 | // Print the given list on the standard output. 59 | // Requires that "<<" be defined for the element type. 60 | // 61 | template 62 | void list_print(S &str, List *l) 63 | { 64 | str << "[\n"; 65 | for(; l != NULL; l = l->tl()) 66 | str << *(l->hd()) << " "; 67 | str << "]\n"; 68 | } 69 | 70 | // 71 | // Compute the length of a list. 72 | // 73 | template 74 | int list_length(List *l) 75 | { 76 | int i = 0; 77 | for (; l != NULL; l = l->tl()) 78 | i++; 79 | return i; 80 | } 81 | 82 | #endif 83 | 84 | -------------------------------------------------------------------------------- /include/PA4/list.h~: -------------------------------------------------------------------------------- 1 | /* -*-Mode: C++;-*- */ 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | ////////////////////////////////////////////////////////////////////// 10 | // 11 | // list.h 12 | // 13 | // This file implements a list template. 14 | // Adapted from similar templates written by Kathy Yelick and 15 | // Paul Hilfinger. 16 | // 17 | ////////////////////////////////////////////////////////////////////// 18 | 19 | #ifndef _LIST_H_ 20 | #define _LIST_H_ 21 | 22 | #include 23 | #include 24 | 25 | template 26 | class List { 27 | private: 28 | T *head; 29 | List* tail; 30 | public: 31 | List(T *h,List* t = NULL): head(h), tail(t) { } 32 | 33 | T *hd() const { return head; } 34 | List* tl() const { return tail; } 35 | }; 36 | 37 | ///////////////////////////////////////////////////////////////////////// 38 | // 39 | // list function templates 40 | // 41 | // To avoid potential problems with mutliple definitions of 42 | // the List<> class members, the list functions are not members of the 43 | // list class. 44 | // 45 | ///////////////////////////////////////////////////////////////////////// 46 | 47 | // 48 | // Map a function for its side effect over a list. 49 | // 50 | template 51 | void list_map(void f(T*), List *l) 52 | { 53 | for (l; l != NULL; l = l->tl()) 54 | f(l->hd()); 55 | } 56 | 57 | // 58 | // Print the given list on the standard output. 59 | // Requires that "<<" be defined for the element type. 60 | // 61 | template 62 | void list_print(S &str, List *l) 63 | { 64 | str << "[\n"; 65 | for(; l != NULL; l = l->tl()) 66 | str << *(l->hd()) << " "; 67 | str << "]\n"; 68 | } 69 | 70 | // 71 | // Compute the length of a list. 72 | // 73 | template 74 | int list_length(List *l) 75 | { 76 | int i = 0; 77 | for (; l != NULL; l = l->tl()) 78 | i++; 79 | return i; 80 | } 81 | 82 | #endif 83 | 84 | -------------------------------------------------------------------------------- /include/PA4/stringtab_functions.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include "cool-io.h" 8 | #define MAXSIZE 1000000 9 | #define min(a,b) (a > b ? b : a) 10 | 11 | #include "stringtab.h" 12 | #include 13 | 14 | // 15 | // A string table is implemented a linked list of Entrys. Each Entry 16 | // in the list has a unique string. 17 | // 18 | 19 | template 20 | Elem *StringTable::add_string(char *s) 21 | { 22 | return add_string(s,MAXSIZE); 23 | } 24 | 25 | // 26 | // Add a string requires two steps. First, the list is searched; if the 27 | // string is found, a pointer to the existing Entry for that string is 28 | // returned. If the string is not found, a new Entry is created and added 29 | // to the list. 30 | // 31 | template 32 | Elem *StringTable::add_string(char *s, int maxchars) 33 | { 34 | int len = min((int) strlen(s),maxchars); 35 | for(List *l = tbl; l; l = l->tl()) 36 | if (l->hd()->equal_string(s,len)) 37 | return l->hd(); 38 | 39 | Elem *e = new Elem(s,len,index++); 40 | tbl = new List(e, tbl); 41 | return e; 42 | } 43 | 44 | // 45 | // To look up a string, the list is scanned until a matching Entry is located. 46 | // If no such entry is found, an assertion failure occurs. Thus, this function 47 | // is used only for strings that one expects to find in the table. 48 | // 49 | template 50 | Elem *StringTable::lookup_string(char *s) 51 | { 52 | int len = strlen(s); 53 | for(List *l = tbl; l; l = l->tl()) 54 | if (l->hd()->equal_string(s,len)) 55 | return l->hd(); 56 | assert(0); // fail if string is not found 57 | return NULL; // to avoid compiler warning 58 | } 59 | 60 | // 61 | // lookup is similar to lookup_string, but uses the index of the string 62 | // as the key. 63 | // 64 | template 65 | Elem *StringTable::lookup(int ind) 66 | { 67 | for(List *l = tbl; l; l = l->tl()) 68 | if (l->hd()->equal_index(ind)) 69 | return l->hd(); 70 | assert(0); // fail if string is not found 71 | return NULL; // to avoid compiler warning 72 | } 73 | 74 | // 75 | // add_int adds the string representation of an integer to the list. 76 | // 77 | template 78 | Elem *StringTable::add_int(int i) 79 | { 80 | static char *buf = new char[20]; 81 | snprintf(buf, 20, "%d", i); 82 | return add_string(buf); 83 | } 84 | template 85 | int StringTable::first() 86 | { 87 | return 0; 88 | } 89 | 90 | template 91 | int StringTable::more(int i) 92 | { 93 | return i < index; 94 | } 95 | 96 | template 97 | int StringTable::next(int i) 98 | { 99 | assert(i < index); 100 | return i+1; 101 | } 102 | 103 | template 104 | void StringTable::print() 105 | { 106 | list_print(cerr,tbl); 107 | } 108 | -------------------------------------------------------------------------------- /include/PA4/utilities.h: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | //class std::ostream; 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(std::ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA4/utilities.h~: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | //class std::ostream; 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(std::ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | //char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /include/PA5/cgen_gc.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | // 8 | // Garbage collection options 9 | // 10 | 11 | extern enum Memmgr { GC_NOGC, GC_GENGC, GC_SNCGC } cgen_Memmgr; 12 | 13 | extern enum Memmgr_Test { GC_NORMAL, GC_TEST } cgen_Memmgr_Test; 14 | 15 | extern enum Memmgr_Debug { GC_QUICK, GC_DEBUG } cgen_Memmgr_Debug; 16 | -------------------------------------------------------------------------------- /include/PA5/cool-io.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef COOL_IO_H 8 | #define COOL_IO_H 9 | 10 | // 11 | // Cool files include this header to use the standard library's 12 | // IO streams. 13 | // 14 | 15 | //By default use the ANSI standard iostream, etc. 16 | #ifndef COOL_USE_OLD_HEADERS 17 | 18 | # include 19 | 20 | using std::ostream; 21 | using std::cout; 22 | using std::cerr; 23 | using std::endl; 24 | 25 | # include 26 | 27 | using std::ofstream; 28 | 29 | # include 30 | 31 | using std::oct; 32 | using std::dec; 33 | using std::setw; 34 | using std::setfill; 35 | 36 | //Including the entire std namespace doesn't work well because of conflicts 37 | //between e.g. std::plus and the plus AST node. 38 | //using namespace std; 39 | 40 | #else 41 | // COOL_USE_OLD_HEADERS is defined 42 | 43 | // I haven't actually tested this, but it ought to work 44 | # include 45 | # include 46 | # include 47 | 48 | #endif // COOL_USE_OLD_HEADERS 49 | 50 | 51 | #endif //COOL_IO_H 52 | -------------------------------------------------------------------------------- /include/PA5/cool.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #ifndef _COOL_H_ 8 | #define _COOL_H_ 9 | 10 | #include "cool-io.h" 11 | 12 | /* a type renaming */ 13 | typedef int Boolean; 14 | class Entry; 15 | typedef Entry *Symbol; 16 | 17 | Boolean copy_Boolean(Boolean); 18 | void assert_Boolean(Boolean); 19 | void dump_Boolean(ostream &,int,Boolean); 20 | 21 | Symbol copy_Symbol(Symbol); 22 | void assert_Symbol(Symbol); 23 | void dump_Symbol(ostream &,int,Symbol); 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /include/PA5/copyright.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 1995,1996 The Regents of the University of California. 3 | All rights reserved. 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose, without fee, and without written agreement is hereby granted, 7 | provided that the above copyright notice and the following two 8 | paragraphs appear in all copies of this software. 9 | 10 | IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR 11 | DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT 12 | OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF 13 | CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 14 | 15 | THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, 16 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 17 | AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 18 | ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO 19 | PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 20 | */ 21 | -------------------------------------------------------------------------------- /include/PA5/list.h: -------------------------------------------------------------------------------- 1 | /* -*-Mode: C++;-*- */ 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | 9 | ////////////////////////////////////////////////////////////////////// 10 | // 11 | // list.h 12 | // 13 | // This file implements a list template. 14 | // Adapted from similar templates written by Kathy Yelick and 15 | // Paul Hilfinger. 16 | // 17 | ////////////////////////////////////////////////////////////////////// 18 | 19 | #ifndef _LIST_H_ 20 | #define _LIST_H_ 21 | 22 | #include "cool-io.h" //includes iostream 23 | #include 24 | 25 | template 26 | class List { 27 | private: 28 | T *head; 29 | List* tail; 30 | public: 31 | List(T *h,List* t = NULL): head(h), tail(t) { } 32 | 33 | T *hd() const { return head; } 34 | List* tl() const { return tail; } 35 | }; 36 | 37 | ///////////////////////////////////////////////////////////////////////// 38 | // 39 | // list function templates 40 | // 41 | // To avoid potential problems with mutliple definitions of 42 | // the List<> class members, the list functions are not members of the 43 | // list class. 44 | // 45 | ///////////////////////////////////////////////////////////////////////// 46 | 47 | // 48 | // Map a function for its side effect over a list. 49 | // 50 | template 51 | void list_map(void f(T*), List *l) 52 | { 53 | for (l; l != NULL; l = l->tl()) 54 | f(l->hd()); 55 | } 56 | 57 | // 58 | // Print the given list on the standard output. 59 | // Requires that "<<" be defined for the element type. 60 | // 61 | template 62 | void list_print(S &str, List *l) 63 | { 64 | str << "[\n"; 65 | for(; l != NULL; l = l->tl()) 66 | str << *(l->hd()) << " "; 67 | str << "]\n"; 68 | } 69 | 70 | // 71 | // Compute the length of a list. 72 | // 73 | template 74 | int list_length(List *l) 75 | { 76 | int i = 0; 77 | for (; l != NULL; l = l->tl()) 78 | i++; 79 | return i; 80 | } 81 | 82 | #endif 83 | 84 | -------------------------------------------------------------------------------- /include/PA5/stringtab_functions.h: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include "cool-io.h" 8 | #define MAXSIZE 1000000 9 | #define min(a,b) (a > b ? b : a) 10 | 11 | #include "stringtab.h" 12 | #include 13 | 14 | // 15 | // A string table is implemented a linked list of Entrys. Each Entry 16 | // in the list has a unique string. 17 | // 18 | 19 | template 20 | Elem *StringTable::add_string(char *s) 21 | { 22 | return add_string(s,MAXSIZE); 23 | } 24 | 25 | // 26 | // Add a string requires two steps. First, the list is searched; if the 27 | // string is found, a pointer to the existing Entry for that string is 28 | // returned. If the string is not found, a new Entry is created and added 29 | // to the list. 30 | // 31 | template 32 | Elem *StringTable::add_string(char *s, int maxchars) 33 | { 34 | int len = min((int) strlen(s),maxchars); 35 | for(List *l = tbl; l; l = l->tl()) 36 | if (l->hd()->equal_string(s,len)) 37 | return l->hd(); 38 | 39 | Elem *e = new Elem(s,len,index++); 40 | tbl = new List(e, tbl); 41 | return e; 42 | } 43 | 44 | // 45 | // To look up a string, the list is scanned until a matching Entry is located. 46 | // If no such entry is found, an assertion failure occurs. Thus, this function 47 | // is used only for strings that one expects to find in the table. 48 | // 49 | template 50 | Elem *StringTable::lookup_string(char *s) 51 | { 52 | int len = strlen(s); 53 | for(List *l = tbl; l; l = l->tl()) 54 | if (l->hd()->equal_string(s,len)) 55 | return l->hd(); 56 | assert(0); // fail if string is not found 57 | return NULL; // to avoid compiler warning 58 | } 59 | 60 | // 61 | // lookup is similar to lookup_string, but uses the index of the string 62 | // as the key. 63 | // 64 | template 65 | Elem *StringTable::lookup(int ind) 66 | { 67 | for(List *l = tbl; l; l = l->tl()) 68 | if (l->hd()->equal_index(ind)) 69 | return l->hd(); 70 | assert(0); // fail if string is not found 71 | return NULL; // to avoid compiler warning 72 | } 73 | 74 | // 75 | // add_int adds the string representation of an integer to the list. 76 | // 77 | template 78 | Elem *StringTable::add_int(int i) 79 | { 80 | static char *buf = new char[20]; 81 | snprintf(buf, 20, "%d", i); 82 | return add_string(buf); 83 | } 84 | template 85 | int StringTable::first() 86 | { 87 | return 0; 88 | } 89 | 90 | template 91 | int StringTable::more(int i) 92 | { 93 | return i < index; 94 | } 95 | 96 | template 97 | int StringTable::next(int i) 98 | { 99 | assert(i < index); 100 | return i+1; 101 | } 102 | 103 | template 104 | void StringTable::print() 105 | { 106 | list_print(cerr,tbl); 107 | } 108 | -------------------------------------------------------------------------------- /include/PA5/utilities.h: -------------------------------------------------------------------------------- 1 | // -*-Mode: C++;-*- 2 | // 3 | // See copyright.h for copyright notice and limitation of liability 4 | // and disclaimer of warranty provisions. 5 | // 6 | #include "copyright.h" 7 | 8 | #ifndef _UTILITIES_H_ 9 | #define _UTILITIES_H_ 10 | 11 | #include "cool-io.h" 12 | 13 | extern char *cool_token_to_string(int tok); 14 | extern void print_cool_token(int tok); 15 | extern void fatal_error(char *); 16 | extern void print_escaped_string(ostream& str, const char *s); 17 | extern char *pad(int); 18 | /* On some machines strdup is not in the standard library. */ 19 | char *strdup(const char *s); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /src/PA2/lextest.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | ////////////////////////////////////////////////////////////////////////////// 8 | // 9 | // lextest.cc 10 | // 11 | // Reads input from file argument. 12 | // 13 | // Option -l prints summary of flex actions. 14 | // 15 | ////////////////////////////////////////////////////////////////////////////// 16 | 17 | #include // needed on Linux system 18 | #include 19 | #include // for getopt 20 | #include "cool-parse.h" // bison-generated file; defines tokens 21 | #include "utilities.h" 22 | 23 | // 24 | // The lexer keeps this global variable up to date with the line number 25 | // of the current line read from the input. 26 | // 27 | int curr_lineno = 1; 28 | char *curr_filename = ""; // this name is arbitrary 29 | FILE *fin; // This is the file pointer from which the lexer reads its input. 30 | 31 | // 32 | // cool_yylex() is the function produced by flex. It returns the next 33 | // token each time it is called. 34 | // 35 | extern int cool_yylex(); 36 | YYSTYPE cool_yylval; // Not compiled with parser, so must define this. 37 | 38 | extern int optind; // used for option processing (man 3 getopt for more info) 39 | 40 | // 41 | // Option -v sets the lex_verbose flag. The main() function prints out tokens 42 | // if the program is invoked with option -v. Option -l sets yy_flex_debug. 43 | // 44 | extern int yy_flex_debug; // Flex debugging; see flex documentation. 45 | extern int lex_verbose; // Controls printing of tokens. 46 | void handle_flags(int argc, char *argv[]); 47 | 48 | // 49 | // The full Cool compiler contains several debugging flags, all of which 50 | // are handled and set by the routine handle_flags. Here we declare 51 | // cool_yydebug, which is not used by the lexer but is needed to link 52 | // with handle_flags. 53 | // 54 | int cool_yydebug; 55 | 56 | // defined in utilities.cc 57 | extern void dump_cool_token(ostream& out, int lineno, 58 | int token, YYSTYPE yylval); 59 | 60 | 61 | int main(int argc, char** argv) { 62 | int token; 63 | 64 | handle_flags(argc,argv); 65 | 66 | while (optind < argc) { 67 | fin = fopen(argv[optind], "r"); 68 | if (fin == NULL) { 69 | cerr << "Could not open input file " << argv[optind] << endl; 70 | exit(1); 71 | } 72 | 73 | // sm: the 'coolc' compiler's file-handling loop resets 74 | // this counter, so let's make the stand-alone lexer 75 | // do the same thing 76 | curr_lineno = 1; 77 | 78 | // 79 | // Scan and print all tokens. 80 | // 81 | cout << "#name \"" << argv[optind] << "\"" << endl; 82 | while ((token = cool_yylex()) != 0) { 83 | dump_cool_token(cout, curr_lineno, token, cool_yylval); 84 | } 85 | fclose(fin); 86 | optind++; 87 | } 88 | exit(0); 89 | } 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /src/PA2/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /src/PA2/stringtab.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include 8 | #include "stringtab_functions.h" 9 | #include "stringtab.h" 10 | 11 | extern char *pad(int n); 12 | 13 | // 14 | // Explicit template instantiations. 15 | // Comment out for versions of g++ prior to 2.7 16 | // 17 | template class StringTable; 18 | template class StringTable; 19 | template class StringTable; 20 | 21 | Entry::Entry(char *s, int l, int i) : len(l), index(i) { 22 | str = new char [len+1]; 23 | strncpy(str, s, len); 24 | str[len] = '\0'; 25 | } 26 | 27 | int Entry::equal_string(char *string, int length) const 28 | { 29 | return (len == length) && (strncmp(str,string,len) == 0); 30 | } 31 | 32 | ostream& Entry::print(ostream& s) const 33 | { 34 | return s << "{" << str << ", " << len << ", " << index << "}\n"; 35 | } 36 | 37 | ostream& operator<<(ostream& s, const Entry& sym) 38 | { 39 | return s << sym.get_string(); 40 | } 41 | 42 | 43 | ostream& operator<<(ostream& s, Symbol sym) 44 | { 45 | return s << *sym; 46 | } 47 | 48 | char *Entry::get_string() const 49 | { 50 | return str; 51 | } 52 | 53 | int Entry::get_len() const 54 | { 55 | return len; 56 | } 57 | 58 | // A Symbol is a pointer to an Entry. Symbols are stored directly 59 | // as nodes of the abstract syntax tree defined by the cool-tree.aps. 60 | // The APS package requires that copy and print (called dump) functions 61 | // be defined for components of the abstract syntax tree. 62 | // 63 | Symbol copy_Symbol(const Symbol s) 64 | { 65 | return s; 66 | } 67 | 68 | void dump_Symbol(ostream& s, int n, Symbol sym) 69 | { 70 | s << pad(n) << sym << endl; 71 | } 72 | 73 | StringEntry::StringEntry(char *s, int l, int i) : Entry(s,l,i) { } 74 | IdEntry::IdEntry(char *s, int l, int i) : Entry(s,l,i) { } 75 | IntEntry::IntEntry(char *s, int l, int i) : Entry(s,l,i) { } 76 | 77 | IdTable idtable; 78 | IntTable inttable; 79 | StrTable stringtable; 80 | -------------------------------------------------------------------------------- /src/PA3/cool-tree.aps: -------------------------------------------------------------------------------- 1 | -- A (typed) tree language for Cool abstract syntax trees 2 | 3 | module COOL[] begin 4 | type Symbol; 5 | type Boolean; 6 | 7 | phylum Program; 8 | 9 | phylum Class_; 10 | phylum Classes = LIST[Class_]; 11 | 12 | phylum Feature; 13 | phylum Features = LIST[Feature]; 14 | 15 | phylum Formal; 16 | phylum Formals = LIST[Formal]; 17 | 18 | phylum Expression; 19 | phylum Expressions = LIST[Expression]; 20 | 21 | phylum Case; 22 | phylum Cases = LIST[Case]; 23 | 24 | constructor program(classes : Classes) : Program; 25 | constructor class_(name : Symbol; parent: Symbol; 26 | features : Features; filename : Symbol): Class_; 27 | 28 | -- Features: 29 | constructor method(name : Symbol; 30 | formals : Formals; 31 | return_type : Symbol; 32 | expr: Expression) : Feature; 33 | constructor attr(name, type_decl : Symbol; 34 | init : Expression) : Feature; 35 | 36 | -- Formals 37 | constructor formal(name, type_decl: Symbol) : Formal; 38 | 39 | -- Case 40 | constructor branch(name, type_decl: Symbol; expr: Expression): Case; 41 | 42 | -- Expressions 43 | constructor assign(name : Symbol; expr : Expression) : Expression; 44 | constructor static_dispatch(expr: Expression; 45 | type_name : Symbol; 46 | name : Symbol; 47 | actual : Expressions) : Expression; 48 | constructor dispatch(expr : Expression; 49 | name : Symbol; 50 | actual : Expressions) : Expression; 51 | constructor cond(pred, then_exp, else_exp : Expression): Expression; 52 | constructor loop(pred, body: Expression) : Expression; 53 | constructor typcase(expr: Expression; cases: Cases): Expression; 54 | constructor block(body: Expressions) : Expression; 55 | constructor let(identifier, type_decl: Symbol; 56 | init, body: Expression): Expression; 57 | constructor plus(e1, e2: Expression) : Expression; 58 | constructor sub(e1, e2: Expression) : Expression; 59 | constructor mul(e1, e2: Expression) : Expression; 60 | constructor divide(e1, e2: Expression) : Expression; 61 | constructor neg(e1: Expression) : Expression; 62 | constructor lt(e1, e2: Expression) : Expression; 63 | constructor eq(e1, e2: Expression) : Expression; 64 | constructor leq(e1, e2: Expression) : Expression; 65 | constructor comp(e1: Expression) : Expression; 66 | constructor int_const(token: Symbol) : Expression; 67 | constructor bool_const(val: Boolean) : Expression; 68 | constructor string_const(token: Symbol) : Expression; 69 | constructor new_(type_name: Symbol): Expression; 70 | constructor isvoid(e1: Expression): Expression; 71 | constructor no_expr(): Expression; 72 | constructor object(name: Symbol): Expression; 73 | end; 74 | -------------------------------------------------------------------------------- /src/PA3/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /src/PA3/myparser: -------------------------------------------------------------------------------- 1 | ./lexer $* | ./parser 2 | -------------------------------------------------------------------------------- /src/PA3/parser-phase.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | ////////////////////////////////////////////////////////////////////////////// 8 | // 9 | // parser-phase.cc 10 | // 11 | // Reads a COOL token stream from a file and builds the abstract syntax tree. 12 | // 13 | ////////////////////////////////////////////////////////////////////////////// 14 | 15 | #include // for Linux system 16 | #include 17 | #include // for getopt 18 | #include "cool-tree.h" 19 | #include "utilities.h" // for fatal_error 20 | #include "cool-parse.h" 21 | 22 | 23 | // 24 | // These globals keep everything working. 25 | // 26 | FILE *token_file = stdin; // we read from this file 27 | extern Classes parse_results; // list of classes; used for multiple files 28 | extern Program ast_root; // the AST produced by the parse 29 | 30 | int curr_lineno; // needed for lexical analyzer 31 | char *curr_filename = ""; 32 | 33 | extern int omerrs; // a count of lex and parse errors 34 | 35 | extern int cool_yyparse(); 36 | void handle_flags(int argc, char *argv[]); 37 | 38 | int main(int argc, char *argv[]) { 39 | handle_flags(argc, argv); 40 | cool_yyparse(); 41 | if (omerrs != 0) { 42 | std::cerr << "Compilation halted due to lex and parse errors\n"; 43 | exit(1); 44 | } 45 | ast_root->dump_with_types(cout,0); 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /src/PA3/parser-phase.cc~: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | ////////////////////////////////////////////////////////////////////////////// 8 | // 9 | // parser-phase.cc 10 | // 11 | // Reads a COOL token stream from a file and builds the abstract syntax tree. 12 | // 13 | ////////////////////////////////////////////////////////////////////////////// 14 | 15 | #include // for Linux system 16 | #include 17 | #include // for getopt 18 | #include "cool-tree.h" 19 | #include "utilities.h" // for fatal_error 20 | #include "cool-parse.h" 21 | 22 | 23 | // 24 | // These globals keep everything working. 25 | // 26 | FILE *token_file = stdin; // we read from this file 27 | extern Classes parse_results; // list of classes; used for multiple files 28 | extern Program ast_root; // the AST produced by the parse 29 | 30 | int curr_lineno; // needed for lexical analyzer 31 | char *curr_filename = ""; 32 | 33 | extern int omerrs; // a count of lex and parse errors 34 | 35 | extern int cool_yyparse(); 36 | void handle_flags(int argc, char *argv[]); 37 | 38 | int main(int argc, char *argv[]) { 39 | handle_flags(argc, argv); 40 | cool_yyparse(); 41 | if (omerrs != 0) { 42 | std::cerr << "Compilation halted due to lex and parse errors\n"; 43 | exit(1); 44 | } 45 | ast_root->dump_with_types(cout,0); 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /src/PA3/ref-parser: -------------------------------------------------------------------------------- 1 | ./lexer $* | ../../bin/reference-parser 2 | -------------------------------------------------------------------------------- /src/PA3/stringtab.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include 8 | #include "stringtab_functions.h" 9 | #include "stringtab.h" 10 | 11 | extern char *pad(int n); 12 | 13 | // 14 | // Explicit template instantiations. 15 | // Comment out for versions of g++ prior to 2.7 16 | // 17 | template class StringTable; 18 | template class StringTable; 19 | template class StringTable; 20 | 21 | Entry::Entry(char *s, int l, int i) : len(l), index(i) { 22 | str = new char [len+1]; 23 | strncpy(str, s, len); 24 | str[len] = '\0'; 25 | } 26 | 27 | int Entry::equal_string(char *string, int length) const 28 | { 29 | return (len == length) && (strncmp(str,string,len) == 0); 30 | } 31 | 32 | ostream& Entry::print(ostream& s) const 33 | { 34 | return s << "{" << str << ", " << len << ", " << index << "}\n"; 35 | } 36 | 37 | ostream& operator<<(ostream& s, const Entry& sym) 38 | { 39 | return s << sym.get_string(); 40 | } 41 | 42 | 43 | ostream& operator<<(ostream& s, Symbol sym) 44 | { 45 | return s << *sym; 46 | } 47 | 48 | char *Entry::get_string() const 49 | { 50 | return str; 51 | } 52 | 53 | int Entry::get_len() const 54 | { 55 | return len; 56 | } 57 | 58 | // A Symbol is a pointer to an Entry. Symbols are stored directly 59 | // as nodes of the abstract syntax tree defined by the cool-tree.aps. 60 | // The APS package requires that copy and print (called dump) functions 61 | // be defined for components of the abstract syntax tree. 62 | // 63 | Symbol copy_Symbol(const Symbol s) 64 | { 65 | return s; 66 | } 67 | 68 | void dump_Symbol(ostream& s, int n, Symbol sym) 69 | { 70 | s << pad(n) << sym << endl; 71 | } 72 | 73 | StringEntry::StringEntry(char *s, int l, int i) : Entry(s,l,i) { } 74 | IdEntry::IdEntry(char *s, int l, int i) : Entry(s,l,i) { } 75 | IntEntry::IntEntry(char *s, int l, int i) : Entry(s,l,i) { } 76 | 77 | IdTable idtable; 78 | IntTable inttable; 79 | StrTable stringtable; 80 | -------------------------------------------------------------------------------- /src/PA3/tree.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | 8 | /////////////////////////////////////////////////////////////////////////// 9 | // 10 | // file: tree.cc 11 | // 12 | // This file defines the basic class of tree node 13 | // 14 | /////////////////////////////////////////////////////////////////////////// 15 | 16 | #include "tree.h" 17 | 18 | #define yylineno curr_lineno; 19 | 20 | extern int yylineno; 21 | 22 | /////////////////////////////////////////////////////////////////////////// 23 | // 24 | // tree_node::tree_node 25 | // 26 | // constructor of tree node 27 | // 28 | /////////////////////////////////////////////////////////////////////////// 29 | tree_node::tree_node() 30 | { 31 | line_number = yylineno; 32 | } 33 | 34 | /////////////////////////////////////////////////////////////////////////// 35 | // 36 | // tree_node::get_line_number 37 | // 38 | /////////////////////////////////////////////////////////////////////////// 39 | int tree_node::get_line_number() 40 | { 41 | return line_number; 42 | } 43 | 44 | // 45 | // Set up common area from existing node 46 | // 47 | tree_node *tree_node::set(tree_node *t) { 48 | line_number = t->line_number; 49 | return this; 50 | } 51 | -------------------------------------------------------------------------------- /src/PA3/tree.cc~: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | 8 | /////////////////////////////////////////////////////////////////////////// 9 | // 10 | // file: tree.cc 11 | // 12 | // This file defines the basic class of tree node 13 | // 14 | /////////////////////////////////////////////////////////////////////////// 15 | 16 | #include "tree.h" 17 | 18 | #define yylineno curr_lineno; 19 | 20 | extern int yylineno; 21 | 22 | /////////////////////////////////////////////////////////////////////////// 23 | // 24 | // tree_node::tree_node 25 | // 26 | // constructor of tree node 27 | // 28 | /////////////////////////////////////////////////////////////////////////// 29 | tree_node::tree_node() 30 | { 31 | line_number = yylineno; 32 | } 33 | 34 | /////////////////////////////////////////////////////////////////////////// 35 | // 36 | // tree_node::get_line_number 37 | // 38 | /////////////////////////////////////////////////////////////////////////// 39 | int tree_node::get_line_number() 40 | { 41 | return line_number; 42 | } 43 | 44 | // 45 | // Set up common area from existing node 46 | // 47 | tree_node *tree_node::set(tree_node *t) { 48 | line_number = t->line_number; 49 | return this; 50 | } 51 | -------------------------------------------------------------------------------- /src/PA4/cool-tree.aps: -------------------------------------------------------------------------------- 1 | -- A (typed) tree language for Cool abstract syntax trees 2 | 3 | module COOL[] begin 4 | type Symbol; 5 | type Boolean; 6 | 7 | phylum Program; 8 | 9 | phylum Class_; 10 | phylum Classes = LIST[Class_]; 11 | 12 | phylum Feature; 13 | phylum Features = LIST[Feature]; 14 | 15 | phylum Formal; 16 | phylum Formals = LIST[Formal]; 17 | 18 | phylum Expression; 19 | phylum Expressions = LIST[Expression]; 20 | 21 | phylum Case; 22 | phylum Cases = LIST[Case]; 23 | 24 | constructor program(classes : Classes) : Program; 25 | constructor class_(name : Symbol; parent: Symbol; 26 | features : Features; filename : Symbol): Class_; 27 | 28 | -- Features: 29 | constructor method(name : Symbol; 30 | formals : Formals; 31 | return_type : Symbol; 32 | expr: Expression) : Feature; 33 | constructor attr(name, type_decl : Symbol; 34 | init : Expression) : Feature; 35 | 36 | -- Formals 37 | constructor formal(name, type_decl: Symbol) : Formal; 38 | 39 | -- Case 40 | constructor branch(name, type_decl: Symbol; expr: Expression): Case; 41 | 42 | -- Expressions 43 | constructor assign(name : Symbol; expr : Expression) : Expression; 44 | constructor static_dispatch(expr: Expression; 45 | type_name : Symbol; 46 | name : Symbol; 47 | actual : Expressions) : Expression; 48 | constructor dispatch(expr : Expression; 49 | name : Symbol; 50 | actual : Expressions) : Expression; 51 | constructor cond(pred, then_exp, else_exp : Expression): Expression; 52 | constructor loop(pred, body: Expression) : Expression; 53 | constructor typcase(expr: Expression; cases: Cases): Expression; 54 | constructor block(body: Expressions) : Expression; 55 | constructor let(identifier, type_decl: Symbol; 56 | init, body: Expression): Expression; 57 | constructor plus(e1, e2: Expression) : Expression; 58 | constructor sub(e1, e2: Expression) : Expression; 59 | constructor mul(e1, e2: Expression) : Expression; 60 | constructor divide(e1, e2: Expression) : Expression; 61 | constructor neg(e1: Expression) : Expression; 62 | constructor lt(e1, e2: Expression) : Expression; 63 | constructor eq(e1, e2: Expression) : Expression; 64 | constructor leq(e1, e2: Expression) : Expression; 65 | constructor comp(e1: Expression) : Expression; 66 | constructor int_const(token: Symbol) : Expression; 67 | constructor bool_const(val: Boolean) : Expression; 68 | constructor string_const(token: Symbol) : Expression; 69 | constructor new_(type_name: Symbol): Expression; 70 | constructor isvoid(e1: Expression): Expression; 71 | constructor no_expr(): Expression; 72 | constructor object(name: Symbol): Expression; 73 | end; 74 | -------------------------------------------------------------------------------- /src/PA4/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /src/PA4/mysemant: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* 3 | -------------------------------------------------------------------------------- /src/PA4/ref-semant: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | reference-semant $* 3 | -------------------------------------------------------------------------------- /src/PA4/semant-phase.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "cool-tree.h" 3 | 4 | extern Program ast_root; // root of the abstract syntax tree 5 | FILE *ast_file = stdin; // we read the AST from standard input 6 | extern int ast_yyparse(void); // entry point to the AST parser 7 | 8 | int cool_yydebug; // not used, but needed to link with handle_flags 9 | int curr_lineno; 10 | char *curr_filename; 11 | 12 | void handle_flags(int argc, char *argv[]); 13 | 14 | int main(int argc, char *argv[]) { 15 | handle_flags(argc,argv); 16 | ast_yyparse(); 17 | ast_root->semant(); 18 | ast_root->dump_with_types(std::cout,0); 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/PA4/semant-phase.cc~: -------------------------------------------------------------------------------- 1 | #include 2 | #include "cool-tree.h" 3 | 4 | extern Program ast_root; // root of the abstract syntax tree 5 | FILE *ast_file = stdin; // we read the AST from standard input 6 | extern int ast_yyparse(void); // entry point to the AST parser 7 | 8 | int cool_yydebug; // not used, but needed to link with handle_flags 9 | int curr_lineno; 10 | char *curr_filename; 11 | 12 | void handle_flags(int argc, char *argv[]); 13 | 14 | int main(int argc, char *argv[]) { 15 | handle_flags(argc,argv); 16 | ast_yyparse(); 17 | ast_root->semant(); 18 | ast_root->dump_with_types(std::cout,0); 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/PA4/stringtab.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include 8 | #include "stringtab_functions.h" 9 | #include "stringtab.h" 10 | 11 | extern char *pad(int n); 12 | 13 | // 14 | // Explicit template instantiations. 15 | // Comment out for versions of g++ prior to 2.7 16 | // 17 | template class StringTable; 18 | template class StringTable; 19 | template class StringTable; 20 | 21 | Entry::Entry(char *s, int l, int i) : len(l), index(i) { 22 | str = new char [len+1]; 23 | strncpy(str, s, len); 24 | str[len] = '\0'; 25 | } 26 | 27 | int Entry::equal_string(char *string, int length) const 28 | { 29 | return (len == length) && (strncmp(str,string,len) == 0); 30 | } 31 | 32 | ostream& Entry::print(ostream& s) const 33 | { 34 | return s << "{" << str << ", " << len << ", " << index << "}\n"; 35 | } 36 | 37 | ostream& operator<<(ostream& s, const Entry& sym) 38 | { 39 | return s << sym.get_string(); 40 | } 41 | 42 | 43 | ostream& operator<<(ostream& s, Symbol sym) 44 | { 45 | return s << *sym; 46 | } 47 | 48 | char *Entry::get_string() const 49 | { 50 | return str; 51 | } 52 | 53 | int Entry::get_len() const 54 | { 55 | return len; 56 | } 57 | 58 | // A Symbol is a pointer to an Entry. Symbols are stored directly 59 | // as nodes of the abstract syntax tree defined by the cool-tree.aps. 60 | // The APS package requires that copy and print (called dump) functions 61 | // be defined for components of the abstract syntax tree. 62 | // 63 | Symbol copy_Symbol(const Symbol s) 64 | { 65 | return s; 66 | } 67 | 68 | void dump_Symbol(ostream& s, int n, Symbol sym) 69 | { 70 | s << pad(n) << sym << endl; 71 | } 72 | 73 | StringEntry::StringEntry(char *s, int l, int i) : Entry(s,l,i) { } 74 | IdEntry::IdEntry(char *s, int l, int i) : Entry(s,l,i) { } 75 | IntEntry::IntEntry(char *s, int l, int i) : Entry(s,l,i) { } 76 | 77 | IdTable idtable; 78 | IntTable inttable; 79 | StrTable stringtable; 80 | -------------------------------------------------------------------------------- /src/PA4/symtab_example.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | // 7 | // Create a mapping from strings to ints 8 | // 9 | 10 | SymbolTable *map = new SymbolTable(); 11 | char *Fred = "Fred"; 12 | char *Mary = "Mary"; 13 | char *Miguel = "Miguel"; 14 | 15 | // enter a scope; required before any symbols can be added 16 | map->enterscope(); 17 | 18 | // add a couple of entries mapping name to age. 19 | // note the second argument must be a pointer to an integer 20 | map->addid(Fred, new int(22)); 21 | map->addid(Mary, new int(25)); 22 | 23 | // add a scope, add more names: 24 | map->enterscope(); 25 | map->addid(Miguel, new int(35)); 26 | map->addid(Mary, new int(23)); 27 | 28 | // check whether Fred is in the current scope; predicate is false 29 | std::cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 30 | 31 | // check whether Mary is in any scope; predicate is true 32 | std::cout << ((map->lookup(Mary) != NULL) ? "Yes\n" : "No\n"); 33 | 34 | // print age of most-closely-nested Mary; note the 35 | // lookup returns a pointer to an integer. 36 | std::cout << *(map->lookup(Mary)) << "\n"; 37 | 38 | // check whether Miguel is in the current scope; predicate is true 39 | std::cout << ((map->probe(Miguel) != NULL) ? "Yes\n" : "No\n"); 40 | 41 | // leave a scope 42 | map->exitscope(); 43 | 44 | // print age of most-closely-nested Mary 45 | std::cout << *(map->lookup(Mary)) << "\n"; 46 | 47 | // check whether Fred is in the current scope; predicate is now true 48 | std::cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 49 | 50 | // check whether Miguel is in any scope; predicate is now false 51 | std::cout << ((map->lookup(Miguel) != NULL) ? "Yes\n" : "No\n"); 52 | 53 | return 0; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/PA4/tree.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | 8 | /////////////////////////////////////////////////////////////////////////// 9 | // 10 | // file: tree.cc 11 | // 12 | // This file defines the basic class of tree node 13 | // 14 | /////////////////////////////////////////////////////////////////////////// 15 | 16 | #include "tree.h" 17 | 18 | #define yylineno curr_lineno; 19 | 20 | extern int yylineno; 21 | 22 | /////////////////////////////////////////////////////////////////////////// 23 | // 24 | // tree_node::tree_node 25 | // 26 | // constructor of tree node 27 | // 28 | /////////////////////////////////////////////////////////////////////////// 29 | tree_node::tree_node() 30 | { 31 | line_number = yylineno; 32 | } 33 | 34 | /////////////////////////////////////////////////////////////////////////// 35 | // 36 | // tree_node::get_line_number 37 | // 38 | /////////////////////////////////////////////////////////////////////////// 39 | int tree_node::get_line_number() 40 | { 41 | return line_number; 42 | } 43 | 44 | // 45 | // Set up common area from existing node 46 | // 47 | tree_node *tree_node::set(tree_node *t) { 48 | line_number = t->line_number; 49 | return this; 50 | } 51 | -------------------------------------------------------------------------------- /src/PA5/cgen-phase.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "cool-io.h" //includes iostream 5 | #include "cool-tree.h" 6 | #include "cgen_gc.h" 7 | 8 | extern int optind; // for option processing 9 | extern char *out_filename; // name of output assembly 10 | extern Program ast_root; // root of the abstract syntax tree 11 | FILE *ast_file = stdin; // we read the AST from standard input 12 | extern int ast_yyparse(void); // entry point to the AST parser 13 | 14 | int cool_yydebug; // not used, but needed to link with handle_flags 15 | int curr_lineno; 16 | char *curr_filename; 17 | 18 | void handle_flags(int argc, char *argv[]); 19 | 20 | int main(int argc, char *argv[]) { 21 | int firstfile_index; 22 | 23 | handle_flags(argc,argv); 24 | firstfile_index = optind; 25 | 26 | if (!out_filename && optind < argc) { // no -o option 27 | char *dot = strrchr(argv[optind], '.'); 28 | if (dot) *dot = '\0'; // strip off file extension 29 | out_filename = new char[strlen(argv[optind])+8]; 30 | strcpy(out_filename, argv[optind]); 31 | strcat(out_filename, ".s"); 32 | } 33 | 34 | // 35 | // Don't touch the output file until we know that earlier phases of the 36 | // compiler have succeeded. 37 | // 38 | ast_yyparse(); 39 | 40 | if (out_filename) { 41 | ofstream s(out_filename); 42 | if (!s) { 43 | cerr << "Cannot open output file " << out_filename << endl; 44 | exit(1); 45 | } 46 | ast_root->cgen(s); 47 | } else { 48 | ast_root->cgen(cout); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /src/PA5/mycoolc: -------------------------------------------------------------------------------- 1 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 2 | -------------------------------------------------------------------------------- /src/PA5/stringtab.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | #include 8 | #include "stringtab_functions.h" 9 | #include "stringtab.h" 10 | 11 | extern char *pad(int n); 12 | 13 | // 14 | // Explicit template instantiations. 15 | // Comment out for versions of g++ prior to 2.7 16 | // 17 | template class StringTable; 18 | template class StringTable; 19 | template class StringTable; 20 | 21 | Entry::Entry(char *s, int l, int i) : len(l), index(i) { 22 | str = new char [len+1]; 23 | strncpy(str, s, len); 24 | str[len] = '\0'; 25 | } 26 | 27 | int Entry::equal_string(char *string, int length) const 28 | { 29 | return (len == length) && (strncmp(str,string,len) == 0); 30 | } 31 | 32 | ostream& Entry::print(ostream& s) const 33 | { 34 | return s << "{" << str << ", " << len << ", " << index << "}\n"; 35 | } 36 | 37 | ostream& operator<<(ostream& s, const Entry& sym) 38 | { 39 | return s << sym.get_string(); 40 | } 41 | 42 | 43 | ostream& operator<<(ostream& s, Symbol sym) 44 | { 45 | return s << *sym; 46 | } 47 | 48 | char *Entry::get_string() const 49 | { 50 | return str; 51 | } 52 | 53 | int Entry::get_len() const 54 | { 55 | return len; 56 | } 57 | 58 | // A Symbol is a pointer to an Entry. Symbols are stored directly 59 | // as nodes of the abstract syntax tree defined by the cool-tree.aps. 60 | // The APS package requires that copy and print (called dump) functions 61 | // be defined for components of the abstract syntax tree. 62 | // 63 | Symbol copy_Symbol(const Symbol s) 64 | { 65 | return s; 66 | } 67 | 68 | void dump_Symbol(ostream& s, int n, Symbol sym) 69 | { 70 | s << pad(n) << sym << endl; 71 | } 72 | 73 | StringEntry::StringEntry(char *s, int l, int i) : Entry(s,l,i) { } 74 | IdEntry::IdEntry(char *s, int l, int i) : Entry(s,l,i) { } 75 | IntEntry::IntEntry(char *s, int l, int i) : Entry(s,l,i) { } 76 | 77 | IdTable idtable; 78 | IntTable inttable; 79 | StrTable stringtable; 80 | -------------------------------------------------------------------------------- /src/PA5/tree.cc: -------------------------------------------------------------------------------- 1 | // 2 | // See copyright.h for copyright notice and limitation of liability 3 | // and disclaimer of warranty provisions. 4 | // 5 | #include "copyright.h" 6 | 7 | 8 | /////////////////////////////////////////////////////////////////////////// 9 | // 10 | // file: tree.cc 11 | // 12 | // This file defines the basic class of tree node 13 | // 14 | /////////////////////////////////////////////////////////////////////////// 15 | 16 | #include "tree.h" 17 | 18 | #define yylineno curr_lineno; 19 | 20 | extern int yylineno; 21 | 22 | /////////////////////////////////////////////////////////////////////////// 23 | // 24 | // tree_node::tree_node 25 | // 26 | // constructor of tree node 27 | // 28 | /////////////////////////////////////////////////////////////////////////// 29 | tree_node::tree_node() 30 | { 31 | line_number = yylineno; 32 | } 33 | 34 | /////////////////////////////////////////////////////////////////////////// 35 | // 36 | // tree_node::get_line_number 37 | // 38 | /////////////////////////////////////////////////////////////////////////// 39 | int tree_node::get_line_number() 40 | { 41 | return line_number; 42 | } 43 | 44 | // 45 | // Set up common area from existing node 46 | // 47 | tree_node *tree_node::set(tree_node *t) { 48 | line_number = t->line_number; 49 | return this; 50 | } 51 | --------------------------------------------------------------------------------