├── .gitignore ├── assignments ├── PA1 │ ├── Makefile │ ├── README │ ├── atoi.cl │ ├── class_demo │ │ ├── fact.cl │ │ ├── helloWorld.cl │ │ ├── list.cl │ │ ├── list2 │ │ └── list2.cl │ ├── stack.cl │ ├── stack.s │ └── stack.test ├── PA2 │ ├── Makefile │ ├── README │ ├── cool-lex.d │ ├── cool.lex │ ├── flex-demo │ │ ├── a.out │ │ ├── calc.lex │ │ ├── calc.tab.c │ │ ├── calc.tab.h │ │ ├── calc.y │ │ ├── demo_lg │ │ │ ├── Makefile │ │ │ ├── fb3-2.h │ │ │ ├── fb3-2.lex │ │ │ ├── fb3-2.y │ │ │ └── fb3-2funcs.c │ │ ├── fb3-1 │ │ ├── fb3-1.h │ │ ├── fb3-1.lex │ │ ├── fb3-1.lex.c │ │ ├── fb3-1.tab.c │ │ ├── fb3-1.tab.h │ │ ├── fb3-1.y │ │ ├── fb3-1funcs.c │ │ ├── fb3-2.h │ │ ├── fb3-2.lex │ │ ├── fb3-2.tab.c │ │ ├── fb3-2.tab.h │ │ ├── fb3-2.y │ │ ├── fb3-2func.c │ │ ├── lex.yy.c │ │ └── wc.lex │ ├── handle_flags.cc │ ├── handle_flags.d │ ├── lextest.cc │ ├── lextest.d │ ├── mycoolc │ ├── pa2-grading.pl │ ├── stringtab.cc │ ├── stringtab.d │ ├── test.cl │ ├── utilities.cc │ └── utilities.d ├── PA3 │ ├── Makefile │ ├── README │ ├── bad.cl │ ├── cool-parse.d │ ├── cool-tree.aps │ ├── cool-tree.cc │ ├── cool-tree.d │ ├── cool-tree.handcode.h │ ├── cool.output │ ├── cool.tab.h │ ├── cool.y │ ├── dumptype.cc │ ├── dumptype.d │ ├── good.cl │ ├── handle_flags.cc │ ├── handle_flags.d │ ├── mycoolc │ ├── myparser │ ├── pa3-grading.pl │ ├── parser-phase.cc │ ├── parser-phase.d │ ├── stringtab.cc │ ├── stringtab.d │ ├── tokens-lex.cc │ ├── tokens-lex.d │ ├── tree.cc │ ├── tree.d │ ├── utilities.cc │ └── utilities.d ├── PA4 │ ├── Makefile │ ├── README │ ├── ast-lex.cc │ ├── ast-lex.d │ ├── ast-parse.cc │ ├── ast-parse.d │ ├── bad.cl │ ├── cool-tree.aps │ ├── cool-tree.cc │ ├── cool-tree.d │ ├── cool-tree.h │ ├── cool-tree.handcode.h │ ├── dumptype.cc │ ├── dumptype.d │ ├── good.cl │ ├── handle_flags.cc │ ├── handle_flags.d │ ├── my_test │ │ ├── inheritance_basecalsss.cl │ │ ├── inheritance_bigcycle.cl │ │ ├── inheritance_nodefine.cl │ │ ├── inheritance_redefinebase.cl │ │ ├── inheritance_redefined.cl │ │ ├── inheritance_self.cl │ │ └── inheritance_with_cycle.cl │ ├── mycoolc │ ├── mysemant │ ├── pa4-grading.pl │ ├── readme.md │ ├── semant-phase.cc │ ├── semant-phase.d │ ├── semant.cc │ ├── semant.d │ ├── semant.h │ ├── stringtab.cc │ ├── stringtab.d │ ├── symtab_example.cc │ ├── symtab_example.d │ ├── tree.cc │ ├── tree.d │ ├── utilities.cc │ └── utilities.d └── PA5 │ ├── Makefile │ ├── README │ ├── ast-lex.cc │ ├── ast-lex.d │ ├── ast-parse.cc │ ├── ast-parse.d │ ├── cgen-phase.cc │ ├── cgen-phase.d │ ├── cgen.cc │ ├── cgen.d │ ├── cgen.h │ ├── cgen_supp.cc │ ├── cgen_supp.d │ ├── change.py │ ├── cool-tree.cc │ ├── cool-tree.d │ ├── cool-tree.h │ ├── cool-tree.handcode.h │ ├── dumptype.cc │ ├── dumptype.d │ ├── emit.h │ ├── example.cl │ ├── handle_flags.cc │ ├── handle_flags.d │ ├── my_test │ ├── simple.cl │ ├── simple.s │ ├── simple_out.cl │ ├── simple_out.s │ ├── simple_out_ref.s │ └── simple_ref.s │ ├── mycoolc │ ├── pa5-grading.pl │ ├── readme.md │ ├── stringtab.cc │ ├── stringtab.d │ ├── tree.cc │ ├── tree.d │ ├── utilities.cc │ └── utilities.d ├── bin ├── .i686 │ ├── anngen │ ├── aps2c++ │ ├── aps2java │ ├── cgen │ ├── coolc │ ├── lexer │ ├── parser │ ├── semant │ ├── spim │ └── xspim ├── anngen ├── aps2c++ ├── aps2java ├── cgen ├── coolc ├── lexer ├── parser ├── semant ├── spim └── xspim ├── etc └── link-object ├── examples ├── README ├── arith.cl ├── atoi.cl ├── atoi_test.cl ├── book_list.cl ├── cells.cl ├── complex.cl ├── cool.cl ├── g1.graph ├── graph.cl ├── hairyscary.cl ├── hello_world.cl ├── io.cl ├── lam.cl ├── life.cl ├── life.cl~ ├── list.cl ├── new_complex.cl ├── palindrome.cl ├── primes.cl └── sort_list.cl ├── handouts ├── PA1.pdf ├── PA2.pdf ├── PA3.pdf ├── PA4.pdf ├── PA5.pdf ├── cool-manual.pdf ├── cool-tour.pdf └── extra-credit.pdf ├── include ├── PA2 │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-parse.h │ ├── cool.h │ ├── copyright.h │ ├── list.h │ ├── stringtab.h │ ├── stringtab_functions.h │ ├── tree.h │ └── utilities.h ├── PA3 │ ├── cgen_gc.h │ ├── cool-io.h │ ├── cool-parse.h │ ├── cool-tree.h │ ├── cool.h │ ├── copyright.h │ ├── list.h │ ├── stringtab.h │ ├── stringtab_functions.h │ ├── tree.h │ └── utilities.h ├── PA4 │ ├── 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 │ └── 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 │ └── utilities.h ├── lib ├── META-INF │ └── MANIFEST.MF ├── java-cup-11a.jar ├── java_cup │ ├── CUP$parser$actions.class │ ├── ErrorManager.class │ ├── Lexer.class │ ├── Main.class │ ├── action_part.class │ ├── action_production.class │ ├── anttask │ │ └── CUPTask.class │ ├── assoc.class │ ├── emit.class │ ├── internal_error.class │ ├── lalr_item.class │ ├── lalr_item_set.class │ ├── lalr_state.class │ ├── lalr_transition.class │ ├── lr_item_core.class │ ├── non_terminal.class │ ├── nonassoc_action.class │ ├── parse_action.class │ ├── parse_action_row.class │ ├── parse_action_table.class │ ├── parse_reduce_row.class │ ├── parse_reduce_table.class │ ├── parser.class │ ├── production.class │ ├── production_part.class │ ├── reduce_action.class │ ├── runtime │ │ ├── ComplexSymbolFactory$ComplexSymbol.class │ │ ├── ComplexSymbolFactory$Location.class │ │ ├── ComplexSymbolFactory.class │ │ ├── DefaultSymbolFactory.class │ │ ├── ParserException.class │ │ ├── Scanner.class │ │ ├── Symbol.class │ │ ├── SymbolFactory.class │ │ ├── lr_parser.class │ │ └── virtual_parse_stack.class │ ├── shift_action.class │ ├── sym.class │ ├── symbol.class │ ├── symbol_part.class │ ├── symbol_set.class │ ├── terminal.class │ ├── terminal_set.class │ └── version.class ├── jlex.jar └── trap.handler ├── readme.md └── src ├── PA2 ├── handle_flags.cc ├── lextest.cc ├── mycoolc ├── stringtab.cc └── utilities.cc ├── PA3 ├── cool-tree.aps ├── cool-tree.cc ├── dumptype.cc ├── handle_flags.cc ├── mycoolc ├── myparser ├── parser-phase.cc ├── stringtab.cc ├── tokens-lex.cc ├── tokens-lex.cc~ ├── tree.cc └── utilities.cc ├── PA4 ├── ast-lex.cc ├── ast-parse.cc ├── cool-tree.aps ├── cool-tree.cc ├── dumptype.cc ├── handle_flags.cc ├── mycoolc ├── mysemant ├── semant-phase.cc ├── stringtab.cc ├── symtab_example.cc ├── tree.cc └── utilities.cc └── PA5 ├── ast-lex.cc ├── ast-lex.cc~ ├── ast-parse.cc ├── cgen-phase.cc ├── cool-tree.cc ├── dumptype.cc ├── handle_flags.cc ├── mycoolc ├── stringtab.cc ├── tree.cc └── utilities.cc /.gitignore: -------------------------------------------------------------------------------- 1 | examples/ 2 | assignments/PA2/grading -------------------------------------------------------------------------------- /assignments/PA1/Makefile: -------------------------------------------------------------------------------- 1 | 2 | ASSN = 1 3 | CLASS= cs143 4 | CLASSDIR= ../.. 5 | SRC= stack.cl README 6 | LSRC= Makefile atoi.cl stack.test 7 | 8 | CC=gcc 9 | CFLAGS=-g 10 | 11 | .c.o: 12 | ${CC} ${CFLAGS} -c $< 13 | 14 | compile: stack.s 15 | 16 | stack.s: stack.cl atoi.cl 17 | ${CLASSDIR}/bin/coolc stack.cl atoi.cl 18 | 19 | test: compile 20 | @echo stack.test 21 | ${CLASSDIR}/bin/spim -file stack.s < stack.test 22 | 23 | clean : 24 | rm -f *.s core *~ 25 | -------------------------------------------------------------------------------- /assignments/PA1/README: -------------------------------------------------------------------------------- 1 | 2 | README file for Programming Assignment 1 3 | ======================================== 4 | 5 | Your directory should now contain the following files: 6 | 7 | Makefile 8 | README 9 | atoi.cl -> [cool root]/assignments/PA1/atoi.cl 10 | stack.cl 11 | stack.test -> [cool root]/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. 27 | 28 | 29 | The symlinked files (see "man ln") are that way to emphasize 30 | that they are read-only. 31 | 32 | 33 | Instructions 34 | ------------ 35 | 36 | To compile and run your program, type: 37 | 38 | % gmake test 39 | 40 | Try it now -- it should work, and print "Nothing implemented" 41 | (among a few other things). 42 | 43 | 44 | To simply compile your program, type 45 | 46 | % gmake compile 47 | 48 | 49 | Instructions for turning in the assignment will be posted on the 50 | course web page. 51 | 52 | GOOD LUCK! 53 | 54 | ---8<------8<------8<------8<---cut here---8<------8<------8<------8<--- 55 | 56 | Questions on PA1 57 | ---------------- 58 | 59 | 1. Describe your implementation of the stack machine in a single short 60 | paragraph. 61 | 62 | 63 | 2. List 3 things that you like about the Cool programming language. 64 | 65 | 66 | 3. List 3 things you DON'T like about Cool. 67 | 68 | -------------------------------------------------------------------------------- /assignments/PA1/class_demo/fact.cl: -------------------------------------------------------------------------------- 1 | class Main inherits A2I { 2 | i : IO <- new IO; 3 | main() : Object { 4 | --i.out_string(i2a(fact(a2i(i.in_string()))).concat("\n")) 5 | i.out_string(i2a(fact2(a2i(i.in_string()))).concat("\n")) 6 | }; 7 | 8 | 9 | fact(i: Int) : Int { 10 | if (i = 0) then 11 | 1 12 | else 13 | i * fact(i - 1) 14 | fi 15 | }; 16 | 17 | 18 | fact2(i : Int) : Int { 19 | let fact: Int <- 1 in { 20 | while (not (i = 0)) loop { 21 | fact <- fact * i; 22 | i <- i - 1; 23 | } 24 | pool; 25 | fact; 26 | } 27 | }; 28 | }; -------------------------------------------------------------------------------- /assignments/PA1/class_demo/helloWorld.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main() : Object { out_string("hello world!\n") }; 3 | }; -------------------------------------------------------------------------------- /assignments/PA1/class_demo/list.cl: -------------------------------------------------------------------------------- 1 | class List { 2 | item: String; 3 | next: List; 4 | 5 | init(i: String, n : List) : List { 6 | { 7 | item <- i; 8 | next <- n; 9 | self; 10 | } 11 | }; 12 | 13 | flatten() : String { 14 | if (isvoid next) then 15 | item 16 | else 17 | item.concat(next.flatten()) 18 | fi 19 | }; 20 | }; 21 | 22 | 23 | class Main inherits IO { 24 | main() : Object { 25 | let hello : String <- "Hello ", 26 | world : String <- "World!", 27 | newline: String <- "\n", 28 | nil: List, 29 | list: List <- (new List).init(hello, 30 | (new List).init(world, 31 | (new List).init(newline, nil))) 32 | in 33 | out_string(list.flatten()) 34 | }; 35 | }; -------------------------------------------------------------------------------- /assignments/PA1/class_demo/list2.cl: -------------------------------------------------------------------------------- 1 | class List inherits A2I { 2 | item: Object; 3 | next: List; 4 | 5 | init(i: Object, n: List) : List { 6 | { 7 | item <- i; 8 | next <- n; 9 | self; 10 | } 11 | }; 12 | 13 | flatten() : String { 14 | let string: String <- 15 | -- 根据item的类型来得到对应的字符串 16 | case item of 17 | i: Int => i2a(i); 18 | s: String => s; 19 | o: Object => { abort(); "";}; 20 | esac 21 | in 22 | -- 前面定义完变量,下面进行运算 23 | if (isvoid next) then 24 | string 25 | else 26 | string.concat(next.flatten()) 27 | fi 28 | }; 29 | }; 30 | 31 | 32 | class Main inherits IO { 33 | main() : Object { 34 | let 35 | -- 定义一堆变量 36 | hello : String <- "hello ", 37 | world: String <- "world! ", 38 | i : Int <- 42, 39 | newline: String <- "\n", 40 | nil : List, -- 默认nil为空 41 | list: List <- -- 开始构造list 42 | (new List).init(hello, 43 | (new List).init(world, 44 | (new List).init(i, 45 | (new List).init(newline, nil)))) 46 | in 47 | -- 执行 48 | out_string(list.flatten()) 49 | }; 50 | }; 51 | -------------------------------------------------------------------------------- /assignments/PA1/stack.test: -------------------------------------------------------------------------------- 1 | e 2 | e 3 | 1 4 | + 5 | 2 6 | s 7 | d 8 | e 9 | e 10 | d 11 | e 12 | + 13 | 1 14 | s 15 | s 16 | s 17 | d 18 | e 19 | e 20 | s 21 | e 22 | e 23 | e 24 | d 25 | x 26 | -------------------------------------------------------------------------------- /assignments/PA2/Makefile: -------------------------------------------------------------------------------- 1 | 2 | ASSN = 2 3 | CLASS= cs143 4 | CLASSDIR= ../.. 5 | LIB= -lfl 6 | 7 | SRC= cool.lex test.cl README 8 | CSRC= lextest.cc utilities.cc stringtab.cc handle_flags.cc 9 | TSRC= mycoolc 10 | HSRC= 11 | CGEN= cool-lex.cc 12 | HGEN= 13 | LIBS= parser semant cgen 14 | CFIL= ${CSRC} ${CGEN} 15 | LSRC= Makefile 16 | OBJS= ${CFIL:.cc=.o} 17 | OUTPUT= test.output 18 | 19 | CPPINCLUDE= -I. -I${CLASSDIR}/include/PA${ASSN} -I${CLASSDIR}/src/PA${ASSN} 20 | 21 | 22 | FFLAGS= -d -ocool-lex.cc 23 | 24 | CC=g++ 25 | CFLAGS= -g -Wall -Wno-unused -Wno-write-strings ${CPPINCLUDE} 26 | FLEX=flex ${FFLAGS} 27 | DEPEND = ${CC} -MM ${CPPINCLUDE} 28 | 29 | 30 | source : ${SRC} ${TSRC} ${LSRC} ${LIBS} lsource 31 | 32 | lsource: ${LSRC} 33 | 34 | ${OUTPUT}: lexer test.cl 35 | @rm -f test.output 36 | -./lexer test.cl >test.output 2>&1 37 | 38 | lexer: ${OBJS} 39 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o lexer 40 | 41 | .cc.o: 42 | ${CC} ${CFLAGS} -c $< 43 | 44 | cool-lex.cc: cool.lex 45 | ${FLEX} cool.lex 46 | 47 | dotest: lexer test.cl 48 | ./lexer test.cl 49 | 50 | ${LIBS}: 51 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 52 | 53 | ${TSRC} ${CSRC}: 54 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 55 | 56 | ${HSRC}: 57 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 58 | 59 | clean : 60 | -rm -f ${OUTPUT} *.s core ${OBJS} lexer cool-lex.cc *~ parser cgen semant 61 | 62 | clean-compile: 63 | @-rm -f core ${OBJS} cool-lex.cc ${LSRC} 64 | 65 | %.d: %.cc ${SRC} ${LSRC} 66 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 67 | 68 | -include ${CFIL:.cc=.d} 69 | 70 | 71 | -------------------------------------------------------------------------------- /assignments/PA2/cool-lex.d: -------------------------------------------------------------------------------- 1 | cool-lex.o cool-lex.d : cool-lex.cc ../../include/PA2/cool-parse.h \ 2 | ../../include/PA2/copyright.h ../../include/PA2/cool-io.h \ 3 | ../../include/PA2/tree.h ../../include/PA2/stringtab.h \ 4 | ../../include/PA2/list.h ../../include/PA2/stringtab.h \ 5 | ../../include/PA2/utilities.h 6 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/assignments/PA2/flex-demo/a.out -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/calc.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | #include "calc.tab.h" 3 | 4 | int yylval; 5 | %} 6 | 7 | %% 8 | "+" { return ADD;} 9 | "-" { return SUB;} 10 | "*" {return MUL;} 11 | "/" {return DIV;} 12 | "|" {return ABS;} 13 | "(" {return OP;} 14 | ")" {return CP;} 15 | [0-9]+ {yylval = atoi(yytext); return NUMBER;} 16 | \n {return EOL;} 17 | [ \t] {} 18 | . {printf("Mystery character %s\n", yytext);} 19 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/calc.tab.h: -------------------------------------------------------------------------------- 1 | /* A Bison parser, made by GNU Bison 3.5.1. */ 2 | 3 | /* Bison interface for Yacc-like parsers in C 4 | 5 | Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, 6 | Inc. 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . */ 20 | 21 | /* As a special exception, you may create a larger work that contains 22 | part or all of the Bison parser skeleton and distribute that work 23 | under terms of your choice, so long as that work isn't itself a 24 | parser generator using the skeleton or a modified version thereof 25 | as a parser skeleton. Alternatively, if you modify or redistribute 26 | the parser skeleton itself, you may (at your option) remove this 27 | special exception, which will cause the skeleton and the resulting 28 | Bison output files to be licensed under the GNU General Public 29 | License without this special exception. 30 | 31 | This special exception was added by the Free Software Foundation in 32 | version 2.2 of Bison. */ 33 | 34 | /* Undocumented macros, especially those whose name start with YY_, 35 | are private implementation details. Do not rely on them. */ 36 | 37 | #ifndef YY_YY_CALC_TAB_H_INCLUDED 38 | # define YY_YY_CALC_TAB_H_INCLUDED 39 | /* Debug traces. */ 40 | #ifndef YYDEBUG 41 | # define YYDEBUG 0 42 | #endif 43 | #if YYDEBUG 44 | extern int yydebug; 45 | #endif 46 | 47 | /* Token type. */ 48 | #ifndef YYTOKENTYPE 49 | # define YYTOKENTYPE 50 | enum yytokentype 51 | { 52 | NUMBER = 258, 53 | ADD = 259, 54 | SUB = 260, 55 | MUL = 261, 56 | DIV = 262, 57 | ABS = 263, 58 | OP = 264, 59 | CP = 265, 60 | EOL = 266 61 | }; 62 | #endif 63 | 64 | /* Value type. */ 65 | #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED 66 | typedef int YYSTYPE; 67 | # define YYSTYPE_IS_TRIVIAL 1 68 | # define YYSTYPE_IS_DECLARED 1 69 | #endif 70 | 71 | 72 | extern YYSTYPE yylval; 73 | 74 | int yyparse (void); 75 | 76 | #endif /* !YY_YY_CALC_TAB_H_INCLUDED */ 77 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/calc.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | %} 4 | 5 | %token NUMBER 6 | %token ADD SUB MUL DIV ABS 7 | %token OP CP 8 | %token EOL 9 | 10 | %% 11 | 12 | calclist: 13 | | calclist exp EOL {printf("= %d\n", $2);} 14 | ; 15 | 16 | exp: factor 17 | | exp ADD factor {$$ = $1 + $3;} 18 | | exp SUB factor {$$ = $1 - $3;} 19 | ; 20 | 21 | factor: term 22 | | factor MUL term {$$ = $1 * $3;} 23 | | factor DIV term {$$ = $1 / $3;} 24 | ; 25 | 26 | term: NUMBER 27 | | ABS term {$$ = $2 > 0? $2 : -$2;} 28 | | OP exp CP {$$ = $2;} 29 | ; 30 | %% 31 | 32 | int main(int argc, char* argv[]) { 33 | yyparse(); 34 | return 0; 35 | } 36 | 37 | int yyerror(char *s) { 38 | fprintf(stderr, "error: %s\n", s); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/demo_lg/Makefile: -------------------------------------------------------------------------------- 1 | fb3-2: fb3-2.h fb3-2.lex fb3-2.y fb3-2funcs.c 2 | bison -d fb3-2.y 3 | flex -o fb3-2.lex.c fb3-2.lex 4 | gcc -o $@ fb3-2funcs.c fb3-2.tab.c fb3-2.lex.c -lm -lfl 5 | clean: 6 | rm fb3-2.tab.* fb3-2.lex.c fb3-2 7 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/demo_lg/fb3-2.h: -------------------------------------------------------------------------------- 1 | extern int yylineno; 2 | void yyerror(char *s, ...); 3 | 4 | struct symbol { /*a variable name*/ 5 | char *name; 6 | double value; 7 | struct ast *func; /* stmt for the function*/ 8 | struct symlist *syms; /*list of dummy args*/ 9 | }; 10 | 11 | #define NHASH 9997 12 | struct symbol symtab[NHASH]; 13 | 14 | struct symbol *lookup(char *); 15 | 16 | struct symlist { 17 | struct symbol *sym; 18 | struct symlist *next; 19 | }; 20 | 21 | 22 | // construct new symbol list element. 23 | struct symlist *newsymlist(struct symbol *sym, struct symlist *next); 24 | // free a symbol list 25 | void symlistfree(struct symlist *sl); 26 | 27 | /* node types 28 | + - * / | 29 | 0 - 7 comparison ops, bit coded 04 equl, 02 less, 01 greater 30 | M unary minus 31 | L expression or statement list 32 | I IF statement 33 | W WHILE statement 34 | N symbol ref 35 | = assignemnt 36 | S list of symbols 37 | F build in function call 38 | C user function call 39 | */ 40 | 41 | enum bifs { 42 | B_sqrt = 1, 43 | B_exp, 44 | B_log, 45 | B_print 46 | }; 47 | 48 | struct ast { 49 | int nodetype; 50 | struct ast *l, *r; 51 | }; 52 | 53 | // builtin function 54 | struct fncall { 55 | int nodetype; 56 | struct ast *l; // store the real param ast; 57 | enum bifs functype; // store the function type to call the correct function. 58 | }; 59 | 60 | struct ufncall { 61 | int nodetype; 62 | struct ast *l; // this is the real param ast. 63 | struct symbol *s; // this is the function name, which store the formal param ast and funciton body ast 64 | }; 65 | 66 | 67 | struct flow { 68 | int nodetype; 69 | struct ast *cond; 70 | struct ast *tl; 71 | struct ast *el; 72 | }; 73 | 74 | struct numval { 75 | int nodetype; 76 | double number; 77 | }; 78 | 79 | struct symref { 80 | int nodetype; 81 | struct symbol *s; 82 | }; 83 | 84 | struct symasgn { 85 | int nodetype; 86 | struct symbol *s; 87 | struct ast *v; 88 | }; 89 | 90 | struct ast *newast(int nodetype, struct ast *l, struct ast *r); 91 | struct ast *newcmp(int cmptype, struct ast*l, struct ast *r); 92 | struct ast *newfunc(int functype, struct ast *l); 93 | struct ast *newcall(struct symbol *s, struct ast *l); 94 | struct ast *newref(struct symbol *s); 95 | struct ast *newasgn(struct symbol *s, struct ast *v); 96 | struct ast *newnum(double d); 97 | struct ast *newflow(int nodetype, struct ast *cond, struct ast *tl, struct ast *el); 98 | 99 | // define a function 100 | void dodef(struct symbol *name, struct symlist *syms, struct ast *func); 101 | 102 | // eval an ast 103 | double eval(struct ast *); 104 | 105 | // delete and free an AST 106 | void treefree(struct ast *); 107 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/demo_lg/fb3-2.lex: -------------------------------------------------------------------------------- 1 | %option noyywrap nodefault yylineno 2 | %{ 3 | #include "fb3-2.h" 4 | #include "fb3-2.tab.h" 5 | %} 6 | 7 | EXP ([Ee][-+]?[0-9]+) 8 | 9 | %% 10 | 11 | "+" | 12 | "-" | 13 | "*" | 14 | "/" | 15 | "=" | 16 | "|" | 17 | "," | 18 | ";" | 19 | "(" | 20 | ")" { return yytext[0];} 21 | 22 | ">" {yylval.fn = 1; return CMP;} 23 | "<" {yylval.fn = 2; return CMP;} 24 | "<>" {yylval.fn = 3; return CMP;} 25 | "==" {yylval.fn = 4; return CMP;} 26 | ">=" {yylval.fn = 5; return CMP;} 27 | "<=" {yylval.fn = 6; return CMP;} 28 | 29 | "if" {return IF;} 30 | "then" {return THEN;} 31 | "else" {return ELSE;} 32 | "while" {return WHILE;} 33 | "do" {return DO;} 34 | "let" {return LET;} 35 | 36 | "sqrt" {yylval.fn = B_sqrt; return FUNC;} 37 | "exp" {yylval.fn = B_exp; return FUNC;} 38 | "log" {yylval.fn = B_log; return FUNC;} 39 | "print" {yylval.fn = B_print; return FUNC;} 40 | 41 | 42 | [a-zA-Z][a-zA-Z0-9]* {yylval.s = lookup(yytext); return NAME;} 43 | [0-9]+"."[0-9]*{EXP}? | 44 | "."?[0-9]+{EXP}? {yylval.d = atof(yytext); return NUMBER;} 45 | 46 | "//".* 47 | [ \t] 48 | 49 | \\\n {printf("c> ");} 50 | 51 | \n {return EOL;} 52 | 53 | . {yyerror("Mystery character %c\n", *yytext);} 54 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/demo_lg/fb3-2.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | #include 4 | #include "fb3-2.h" 5 | %} 6 | 7 | %union { 8 | struct ast *a; 9 | double d; 10 | struct symbol *s; // which symbol 11 | struct symlist *sl; 12 | int fn; // which function 13 | }; 14 | 15 | %token NUMBER 16 | %token NAME 17 | %token FUNC 18 | %token EOL 19 | %token IF THEN ELSE WHILE DO LET 20 | 21 | %nonassoc CMP 22 | %right '=' 23 | %left '+' '-' 24 | %left '*' '/' 25 | %nonassoc '|' UMINUS 26 | 27 | %type exp stmt list explist 28 | %type symlist 29 | 30 | %start calclist 31 | %% 32 | 33 | stmt: IF exp THEN list {$$ = newflow('I', $2, $4, NULL);} 34 | | IF exp THEN list ELSE list {$$ = newflow('I', $2, $4, $6);} 35 | | WHILE exp DO list {$$ = newflow('W', $2, $4, NULL);} 36 | | exp 37 | ; 38 | 39 | list: {$$ = NULL;} 40 | | stmt ';' list {if ($3 == NULL) 41 | $$ = $1; 42 | else 43 | $$ = newast('L', $1, $3); 44 | } 45 | ; 46 | 47 | exp: exp CMP exp {$$ = newcmp($2, $1, $3);} 48 | | exp '+' exp {$$ = newast('+', $1, $3);} 49 | | exp '-' exp {$$ = newast('-', $1, $3);} 50 | | exp '*' exp {$$ = newast('*', $1, $3);} 51 | | exp '/' exp {$$ = newast('/', $1, $3);} 52 | | '|' exp {$$ = newast('|', $2, NULL);} 53 | | '(' exp ')' {$$ = $2;} 54 | | '-' exp %prec UMINUS {$$ = newast('M', $2, NULL);} 55 | | NUMBER {$$ = newnum($1);} 56 | | NAME {$$ = newref($1);} 57 | | NAME '=' exp {$$ = newasgn($1, $3);} 58 | | FUNC '(' explist ')' {$$ = newfunc($1, $3);} 59 | | NAME '(' explist ')' {$$ = newcall($1, $3);} 60 | ; 61 | 62 | explist : exp 63 | | exp ',' explist {$$ = newast('L', $1, $3);} 64 | ; 65 | 66 | symlist: NAME {$$ = newsymlist($1, NULL);} 67 | | NAME ',' symlist {$$ = newsymlist($1, $3);} 68 | ; 69 | 70 | calclist : 71 | | calclist stmt EOL { 72 | printf("= %4.4g\n> ", eval($2)); 73 | treefree($2); 74 | } 75 | | calclist LET NAME '(' symlist ')' '=' list EOL { 76 | dodef($3, $5, $8); 77 | printf("Defined %s\n> ", $3->name); 78 | } 79 | |calclist error EOL { 80 | yyerrok; 81 | printf("> "); 82 | } 83 | ; 84 | 85 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/assignments/PA2/flex-demo/fb3-1 -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1.h: -------------------------------------------------------------------------------- 1 | extern int yylinen; 2 | void yyerror(char *s, ...); 3 | 4 | struct ast { 5 | int nodetype; 6 | struct ast *l, *r; 7 | }; 8 | 9 | struct numval{ 10 | int nodetype; 11 | double number; 12 | }; 13 | 14 | struct ast* newast(int nodetype, struct ast *l, struct ast *r); 15 | struct ast* newnum(double d); 16 | 17 | double eval(struct ast *); 18 | 19 | void treefree(struct ast *); 20 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1.lex: -------------------------------------------------------------------------------- 1 | %option noyywrap 2 | 3 | %{ 4 | #include "fb3-1.h" 5 | #include "fb3-1.tab.h" 6 | %} 7 | 8 | EXP ([Ee][-+]?[0-9]+) 9 | 10 | %% 11 | 12 | "+" | 13 | "-" | 14 | "*" | 15 | "/" | 16 | "|" | 17 | "(" | 18 | ")" {return yytext[0];} 19 | 20 | [0-9]+"."[0-9]*{EXP}? | 21 | "."?[0-9]+{EXP}? { yylval.d = atof(yytext); return NUMBER;} 22 | 23 | \n {return EOL;} 24 | 25 | "//".* 26 | [ \t] {} 27 | . {yyerror("Mystery character %c\n", *yytext);} 28 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1.tab.h: -------------------------------------------------------------------------------- 1 | /* A Bison parser, made by GNU Bison 3.5.1. */ 2 | 3 | /* Bison interface for Yacc-like parsers in C 4 | 5 | Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, 6 | Inc. 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . */ 20 | 21 | /* As a special exception, you may create a larger work that contains 22 | part or all of the Bison parser skeleton and distribute that work 23 | under terms of your choice, so long as that work isn't itself a 24 | parser generator using the skeleton or a modified version thereof 25 | as a parser skeleton. Alternatively, if you modify or redistribute 26 | the parser skeleton itself, you may (at your option) remove this 27 | special exception, which will cause the skeleton and the resulting 28 | Bison output files to be licensed under the GNU General Public 29 | License without this special exception. 30 | 31 | This special exception was added by the Free Software Foundation in 32 | version 2.2 of Bison. */ 33 | 34 | /* Undocumented macros, especially those whose name start with YY_, 35 | are private implementation details. Do not rely on them. */ 36 | 37 | #ifndef YY_YY_FB3_1_TAB_H_INCLUDED 38 | # define YY_YY_FB3_1_TAB_H_INCLUDED 39 | /* Debug traces. */ 40 | #ifndef YYDEBUG 41 | # define YYDEBUG 0 42 | #endif 43 | #if YYDEBUG 44 | extern int yydebug; 45 | #endif 46 | 47 | /* Token type. */ 48 | #ifndef YYTOKENTYPE 49 | # define YYTOKENTYPE 50 | enum yytokentype 51 | { 52 | NUMBER = 258, 53 | EOL = 259 54 | }; 55 | #endif 56 | 57 | /* Value type. */ 58 | #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED 59 | union YYSTYPE 60 | { 61 | #line 7 "fb3-1.y" 62 | 63 | struct ast *a; 64 | double d; 65 | 66 | #line 67 "fb3-1.tab.h" 67 | 68 | }; 69 | typedef union YYSTYPE YYSTYPE; 70 | # define YYSTYPE_IS_TRIVIAL 1 71 | # define YYSTYPE_IS_DECLARED 1 72 | #endif 73 | 74 | 75 | extern YYSTYPE yylval; 76 | 77 | int yyparse (void); 78 | 79 | #endif /* !YY_YY_FB3_1_TAB_H_INCLUDED */ 80 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | #include 4 | #include "fb3-1.h" 5 | %} 6 | 7 | %union { 8 | struct ast *a; 9 | double d; 10 | } 11 | 12 | %token NUMBER 13 | %token EOL 14 | 15 | %type exp factor term 16 | 17 | 18 | %% 19 | 20 | calclist: 21 | | calclist exp EOL { 22 | printf("= %4.4g\n", eval($2)); 23 | treefree($2); 24 | printf("> "); 25 | } 26 | | calclist EOL { printf("> "); } 27 | ; 28 | 29 | exp: factor 30 | | exp '+' factor {$$ = newast('+', $1, $3);} 31 | | exp '-' factor {$$ = newast('-', $1, $3);} 32 | ; 33 | 34 | factor: term 35 | | factor '*' term {$$ = newast('*', $1, $3);} 36 | | factor '/' term {$$ = newast('/', $1, $3);} 37 | ; 38 | 39 | term: NUMBER {$$ = newnum($1);} 40 | | '|' term {$$ = newast('|', $2, NULL);} 41 | | '(' exp ')' {$$ = $2;} 42 | | '-' term {$$ = newast('M', $2, NULL);} 43 | ; 44 | 45 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-1funcs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "fb3-1.h" 5 | 6 | struct ast * 7 | newast(int nodetype, struct ast *l, struct ast *r) { 8 | 9 | struct ast *a = malloc(sizeof(struct ast)); 10 | 11 | if (!a) { 12 | yyerror("out of space"); 13 | exit(0); 14 | } 15 | 16 | a->nodetype = nodetype; 17 | a->l = l; 18 | a->r = r; 19 | return a; 20 | } 21 | 22 | struct ast * 23 | newnum(double d) { 24 | 25 | struct numval *a = malloc(sizeof(struct numval)); 26 | if (!a) { 27 | yyerror("out of space"); 28 | exit(0); 29 | } 30 | a->nodetype = 'K'; 31 | a->number = d; 32 | return (struct ast*)a; 33 | } 34 | 35 | double eval(struct ast *a) { 36 | 37 | double v; 38 | switch (a->nodetype) { 39 | case 'K': v = ((struct numval*)a)->number; break; 40 | case '+': v = eval(a->l) + eval(a->r); break; 41 | case '-': v = eval(a->l) - eval(a->r); break; 42 | case '*': v = eval(a->l) * eval(a->r); break; 43 | case '/': v = eval(a->l) / eval(a->r); break; 44 | case '|': v = eval(a->l); if (v < 0) v = -v; break; 45 | case 'M': v = -eval(a->l); break; 46 | default: printf("internal error: bad node %c\n", a->nodetype); 47 | } 48 | return v; 49 | } 50 | 51 | 52 | void 53 | treefree(struct ast *a) { 54 | 55 | switch (a->nodetype) { 56 | 57 | case '+': 58 | case '-': 59 | case '*': 60 | case '/': 61 | treefree(a->r); 62 | 63 | case '|': 64 | case 'M': 65 | treefree(a->l); 66 | 67 | case 'K': 68 | free(a); 69 | break; 70 | default: 71 | printf("internal error: free bad node %c\n", a->nodetype); 72 | } 73 | } 74 | 75 | void yyerror(char *s, ...) { 76 | 77 | va_list ap; 78 | va_start(ap, s); 79 | 80 | fprintf(stderr, "error: "); 81 | vfprintf(stderr, s, ap); 82 | fprintf(stderr, "\n"); 83 | } 84 | 85 | int main() { 86 | printf("> "); 87 | return yyparse(); 88 | } 89 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-2.h: -------------------------------------------------------------------------------- 1 | extern int yylineno; 2 | void yyerror(char *s, ...); 3 | 4 | struct symbol { /*a variable name*/ 5 | char *name; 6 | double value; 7 | struct ast *func; /* stmt for the function*/ 8 | struct symlist *syms; /*list of dummy args*/ 9 | }; 10 | 11 | #define NHASH 9997 12 | struct symbol symtab[NHASH]; 13 | 14 | struct symbol *lookup(char *); 15 | 16 | struct symlist { 17 | struct symbol *sym; 18 | struct symlist *next; 19 | }; 20 | 21 | 22 | // construct new symbol list element. 23 | struct symlist *newsymlist(struct symbol *sym, struct symlist *next); 24 | // free a symbol list 25 | void symlistfree(struct symlist *sl); 26 | 27 | /* node types 28 | + - * / | 29 | 0 - 7 comparison ops, bit coded 04 equl, 02 less, 01 greater 30 | M unary minus 31 | L expression or statement list 32 | I IF statement 33 | W WHILE statement 34 | N symbol ref 35 | = assignemnt 36 | S list of symbols 37 | F build in function call 38 | C user function call 39 | */ 40 | 41 | enum bifs { 42 | B_sqrt = 1, 43 | B_exp, 44 | B_log, 45 | B_print 46 | }; 47 | 48 | struct ast { 49 | int nodetype; 50 | struct ast *l, *r; 51 | }; 52 | 53 | struct fncall { 54 | int nodetype; 55 | struct ast *l; 56 | enum bifs functype; 57 | }; 58 | 59 | struct ufncall { 60 | int nodetype; 61 | struct ast *l; 62 | struct symbol *s; 63 | }; 64 | 65 | 66 | struct flow { 67 | int nodetype; 68 | struct ast *cond; 69 | struct ast *tl; 70 | struct ast *el; 71 | }; 72 | 73 | struct numval { 74 | int nodetype; 75 | double number; 76 | }; 77 | 78 | struct symref { 79 | int nodetype; 80 | struct symbol *s; 81 | }; 82 | 83 | struct symasgn { 84 | int nodetype; 85 | struct symbol *s; 86 | struct ast *v; 87 | }; 88 | 89 | struct ast *newast(int nodetype, struct ast *l, struct ast *r); 90 | struct ast *newcmp(int cmptype, struct ast*l, struct ast *r); 91 | struct ast *newfunc(int functype, struct ast *l); 92 | struct ast *newcall(struct symbol *s, struct ast *l); 93 | struct ast *newref(struct symbol *s); 94 | struct ast *newasgn(struct symbol *s, struct ast *v); 95 | struct ast *newnum(double d); 96 | struct ast *newflow(int nodetype, struct ast *cond, struct ast *tl, struct ast *el); 97 | 98 | // define a function 99 | void dodef(struct symbol *name, struct symlist *syms, struct ast *func); 100 | 101 | // eval an ast 102 | double eval(struct ast *); 103 | 104 | // delete and free an AST 105 | void treefree(struct ast *); 106 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-2.lex: -------------------------------------------------------------------------------- 1 | %option noyywrap nodefault yylineno 2 | %{ 3 | #include "fb3-2.h" 4 | #include "fb3-2.tab.h" 5 | %} 6 | 7 | EXP ([Ee][-+]?[0-9]+) 8 | 9 | %% 10 | 11 | "+" | 12 | "-" | 13 | "*" | 14 | "/" | 15 | "=" | 16 | "|" | 17 | "," | 18 | ";" | 19 | "(" | 20 | ")" { return yytext[0];} 21 | 22 | ">" {yylval.fn = 1; return CMP;} 23 | "<" {yylval.fn = 2; return CMP;} 24 | "<>" {yylval.fn = 3; return CMP;} 25 | "==" {yylval.fn = 4; return CMP;} 26 | ">=" {yylval.fn = 5; return CMP;} 27 | "<=" {yylval.fn = 6; return CMP;} 28 | 29 | "if" {return IF;} 30 | "then" {return THEN;} 31 | "else" {return ELSE;} 32 | "while" {return WHILE;} 33 | "do" {return DO;} 34 | "let" {return LET;} 35 | 36 | "sqrt" {yylval.fn = B_sqrt; return FUNC;} 37 | "exp" {yylval.fn = B_exp; return FUNC;} 38 | "log" {yylval.fn = B_log; return FUNC;} 39 | "print" {yylval.fn = B_print; return FUNC;} 40 | 41 | 42 | [a-zA-Z][a-zA-Z0-9]* {yylval.s = lookup(yytext); return NAME;} 43 | [0-9]+"."[0-9]*{EXP}? | 44 | "."?[0-9]+{EXP}? {yylval.d = atof(yytext); return NUMBER;} 45 | 46 | "//".* 47 | [ \t] 48 | 49 | \\\n {printf("c> ");} 50 | 51 | \n {return EOL;} 52 | 53 | . {yyerror("Mystery character %c\n", *yytext);} 54 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-2.tab.h: -------------------------------------------------------------------------------- 1 | /* A Bison parser, made by GNU Bison 3.5.1. */ 2 | 3 | /* Bison interface for Yacc-like parsers in C 4 | 5 | Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, 6 | Inc. 7 | 8 | This program is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . */ 20 | 21 | /* As a special exception, you may create a larger work that contains 22 | part or all of the Bison parser skeleton and distribute that work 23 | under terms of your choice, so long as that work isn't itself a 24 | parser generator using the skeleton or a modified version thereof 25 | as a parser skeleton. Alternatively, if you modify or redistribute 26 | the parser skeleton itself, you may (at your option) remove this 27 | special exception, which will cause the skeleton and the resulting 28 | Bison output files to be licensed under the GNU General Public 29 | License without this special exception. 30 | 31 | This special exception was added by the Free Software Foundation in 32 | version 2.2 of Bison. */ 33 | 34 | /* Undocumented macros, especially those whose name start with YY_, 35 | are private implementation details. Do not rely on them. */ 36 | 37 | #ifndef YY_YY_FB3_2_TAB_H_INCLUDED 38 | # define YY_YY_FB3_2_TAB_H_INCLUDED 39 | /* Debug traces. */ 40 | #ifndef YYDEBUG 41 | # define YYDEBUG 0 42 | #endif 43 | #if YYDEBUG 44 | extern int yydebug; 45 | #endif 46 | 47 | /* Token type. */ 48 | #ifndef YYTOKENTYPE 49 | # define YYTOKENTYPE 50 | enum yytokentype 51 | { 52 | NUMBER = 258, 53 | NAME = 259, 54 | FUNC = 260, 55 | EOL = 261, 56 | IF = 262, 57 | THEN = 263, 58 | ELSE = 264, 59 | WHILE = 265, 60 | DO = 266, 61 | LET = 267, 62 | CMP = 268, 63 | UMINUS = 269 64 | }; 65 | #endif 66 | 67 | /* Value type. */ 68 | #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED 69 | union YYSTYPE 70 | { 71 | #line 7 "fb3-2.y" 72 | 73 | struct ast *a; 74 | double d; 75 | struct symbol *s; // which symbol 76 | struct symlist *sl; 77 | int fn; // which function 78 | 79 | #line 80 "fb3-2.tab.h" 80 | 81 | }; 82 | typedef union YYSTYPE YYSTYPE; 83 | # define YYSTYPE_IS_TRIVIAL 1 84 | # define YYSTYPE_IS_DECLARED 1 85 | #endif 86 | 87 | 88 | extern YYSTYPE yylval; 89 | 90 | int yyparse (void); 91 | 92 | #endif /* !YY_YY_FB3_2_TAB_H_INCLUDED */ 93 | -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/fb3-2.y: -------------------------------------------------------------------------------- 1 | %{ 2 | #include 3 | #include 4 | #include "fb3-2.h" 5 | %} 6 | 7 | %union { 8 | struct ast *a; 9 | double d; 10 | struct symbol *s; // which symbol 11 | struct symlist *sl; 12 | int fn; // which function 13 | }; 14 | 15 | %token NUMBER 16 | %token NAME 17 | %token FUNC 18 | %token EOL 19 | %token IF THEN ELSE WHILE DO LET 20 | 21 | %nonassoc CMP 22 | %right '=' 23 | %left '+' '-' 24 | %left '*' '/' 25 | %nonassoc '|' UMINUS 26 | 27 | %type exp stmt list explist 28 | %type symlist 29 | 30 | %start calclist 31 | %% 32 | 33 | stmt: IF exp THEN list {$$ = newflow('I', $2, $4, NULL);} 34 | | IF exp THEN list ELSE list {$$ = newflow('I', $2, $4, $6);} 35 | | WHILE exp DO list {$$ = newflow('W', $2, $4, NULL);} 36 | | exp 37 | ; 38 | 39 | list: {$$ = NULL;} 40 | | stmt ';' list {if ($3 == NULL) 41 | $$ = $1; 42 | else 43 | $$ = newast('L', $1, $3); 44 | } 45 | ; 46 | 47 | exp: exp CMP exp {$$ = newcmp($2, $1, $3);} 48 | | exp '+' exp {$$ = newast('+', $1, $3);} 49 | | exp '-' exp {$$ = newast('-', $1, $3);} 50 | | exp '*' exp {$$ = newast('*', $1, $3);} 51 | | exp '/' exp {$$ = newast('/', $1, $3);} 52 | | '|' exp {$$ = newast('|', $2, NULL);} 53 | | '(' exp ')' {$$ = $2;} 54 | | '-' exp %prec UMINUS {$$ = newast('M', $2, NULL);} 55 | | NUMBER {$$ = newnum($1);} 56 | | NAME {$$ = newref($1);} 57 | | NAME '=' exp {$$ = newasgn($1, $3);} 58 | | FUNC '(' explist ')' {$$ = newfunc($1, $3);} 59 | | NAME '(' explist ')' {$$ = newcall($1, $3);} 60 | ; 61 | 62 | explist : exp 63 | | exp ',' explist {$$ = newast('L', $1, $3);} 64 | ; 65 | 66 | symlist: NAME {$$ = newsymlist($1, NULL);} 67 | | NAME ',' symlist {$$ = newsymlist($1, $3);} 68 | ; 69 | 70 | calclist : 71 | | calclist stmt EOL { 72 | printf("= %4.4g\n> ", eval($2)); 73 | treefree($2); 74 | } 75 | | calclist LET NAME '(' symlist ')' '=' list EOL { 76 | dodef($3, $5, $8); 77 | printf("Defined %s\n> ", $3->name); 78 | } 79 | |calclist error EOL { 80 | yyerrok; 81 | printf("> "); 82 | } 83 | ; 84 | 85 | %% -------------------------------------------------------------------------------- /assignments/PA2/flex-demo/wc.lex: -------------------------------------------------------------------------------- 1 | %{ 2 | 3 | int chars = 0; 4 | int words = 0; 5 | int lines = 0; 6 | 7 | %} 8 | 9 | %% 10 | 11 | [a-zA-Z]+ {words++; chars += strlen(yytext);} 12 | \n {chars++; lines++;} 13 | . {chars++;} 14 | 15 | %% 16 | 17 | int main(int argc, char* argv[]) { 18 | 19 | yylex(); 20 | printf("%8d%8d%8d\n", lines, words, chars); 21 | return 0; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /assignments/PA2/handle_flags.d: -------------------------------------------------------------------------------- 1 | handle_flags.o handle_flags.d : handle_flags.cc ../../include/PA2/copyright.h \ 2 | ../../include/PA2/cool-io.h ../../include/PA2/copyright.h \ 3 | ../../include/PA2/cgen_gc.h 4 | -------------------------------------------------------------------------------- /assignments/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 // for getopt 19 | #include "cool-parse.h" // bison-generated file; defines tokens 20 | #include "utilities.h" 21 | 22 | // 23 | // The lexer keeps this global variable up to date with the line number 24 | // of the current line read from the input. 25 | // 26 | int curr_lineno = 1; 27 | char *curr_filename = ""; // this name is arbitrary 28 | FILE *fin; // This is the file pointer from which the lexer reads its input. 29 | 30 | // 31 | // cool_yylex() is the function produced by flex. It returns the next 32 | // token each time it is called. 33 | // 34 | extern int cool_yylex(); 35 | YYSTYPE cool_yylval; // Not compiled with parser, so must define this. 36 | 37 | extern int optind; // used for option processing (man 3 getopt for more info) 38 | 39 | // 40 | // Option -v sets the lex_verbose flag. The main() function prints out tokens 41 | // if the program is invoked with option -v. Option -l sets yy_flex_debug. 42 | // 43 | extern int yy_flex_debug; // Flex debugging; see flex documentation. 44 | extern int lex_verbose; // Controls printing of tokens. 45 | void handle_flags(int argc, char *argv[]); 46 | 47 | // 48 | // The full Cool compiler contains several debugging flags, all of which 49 | // are handled and set by the routine handle_flags. Here we declare 50 | // cool_yydebug, which is not used by the lexer but is needed to link 51 | // with handle_flags. 52 | // 53 | int cool_yydebug; 54 | 55 | // defined in utilities.cc 56 | extern void dump_cool_token(ostream& out, int lineno, 57 | int token, YYSTYPE yylval); 58 | 59 | 60 | int main(int argc, char** argv) { 61 | int token; 62 | 63 | handle_flags(argc,argv); 64 | 65 | while (optind < argc) { 66 | fin = fopen(argv[optind], "r"); 67 | if (fin == NULL) { 68 | cerr << "Could not open input file " << argv[optind] << endl; 69 | exit(1); 70 | } 71 | 72 | // sm: the 'coolc' compiler's file-handling loop resets 73 | // this counter, so let's make the stand-alone lexer 74 | // do the same thing 75 | curr_lineno = 1; 76 | 77 | // 78 | // Scan and print all tokens. 79 | // 80 | cout << "#name \"" << argv[optind] << "\"" << endl; 81 | while ((token = cool_yylex()) != 0) { 82 | dump_cool_token(cout, curr_lineno, token, cool_yylval); 83 | } 84 | fclose(fin); 85 | optind++; 86 | } 87 | exit(0); 88 | } 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /assignments/PA2/lextest.d: -------------------------------------------------------------------------------- 1 | lextest.o lextest.d : lextest.cc ../../include/PA2/copyright.h \ 2 | ../../include/PA2/cool-parse.h ../../include/PA2/copyright.h \ 3 | ../../include/PA2/cool-io.h ../../include/PA2/tree.h \ 4 | ../../include/PA2/stringtab.h ../../include/PA2/list.h \ 5 | ../../include/PA2/utilities.h 6 | -------------------------------------------------------------------------------- /assignments/PA2/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /assignments/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 | -------------------------------------------------------------------------------- /assignments/PA2/stringtab.d: -------------------------------------------------------------------------------- 1 | stringtab.o stringtab.d : stringtab.cc ../../include/PA2/copyright.h \ 2 | ../../include/PA2/stringtab_functions.h ../../include/PA2/copyright.h \ 3 | ../../include/PA2/cool-io.h ../../include/PA2/stringtab.h \ 4 | ../../include/PA2/list.h ../../include/PA2/stringtab.h 5 | -------------------------------------------------------------------------------- /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/utilities.d: -------------------------------------------------------------------------------- 1 | utilities.o utilities.d : utilities.cc ../../include/PA2/copyright.h \ 2 | ../../include/PA2/cool-io.h ../../include/PA2/copyright.h \ 3 | ../../include/PA2/cool-parse.h ../../include/PA2/cool-io.h \ 4 | ../../include/PA2/tree.h ../../include/PA2/stringtab.h \ 5 | ../../include/PA2/list.h ../../include/PA2/stringtab.h \ 6 | ../../include/PA2/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/PA3/Makefile: -------------------------------------------------------------------------------- 1 | 2 | ASSN = 3 3 | CLASS= cs143 4 | CLASSDIR= ../.. 5 | LIB= -lfl 6 | AR= gar 7 | ARCHIVE_NEW= -cr 8 | RANLIB= gar -qs 9 | 10 | SRC= cool.y cool-tree.handcode.h good.cl bad.cl README 11 | CSRC= parser-phase.cc utilities.cc stringtab.cc dumptype.cc \ 12 | tree.cc cool-tree.cc tokens-lex.cc handle_flags.cc 13 | TSRC= myparser mycoolc cool-tree.aps 14 | CGEN= cool-parse.cc 15 | HGEN= cool-parse.h 16 | LIBS= lexer semant cgen 17 | CFIL= ${CSRC} ${CGEN} 18 | HFIL= cool-tree.h cool-tree.handcode.h 19 | LSRC= Makefile 20 | OBJS= ${CFIL:.cc=.o} 21 | OUTPUT= good.output bad.output 22 | 23 | 24 | CPPINCLUDE= -I. -I${CLASSDIR}/include/PA${ASSN} -I${CLASSDIR}/src/PA${ASSN} 25 | 26 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 27 | 28 | CC=g++ 29 | CFLAGS=-g -Wall -Wno-unused -Wno-deprecated -Wno-write-strings -DDEBUG ${CPPINCLUDE} 30 | FLEX=flex ${FFLAGS} 31 | BISON= bison ${BFLAGS} 32 | DEPEND = ${CC} -MM ${CPPINCLUDE} 33 | 34 | source: ${SRC} ${TSRC} ${LIBS} lsource 35 | 36 | lsource: ${LSRC} 37 | 38 | ${OUTPUT}: parser good.cl bad.cl 39 | @rm -f ${OUTPUT} 40 | ./myparser good.cl >good.output 2>&1 41 | -./myparser bad.cl >bad.output 2>&1 42 | 43 | parser: ${OBJS} 44 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o parser 45 | 46 | .cc.o: 47 | ${CC} ${CFLAGS} -c $< 48 | 49 | cool-parse.cc cool-parse.h: cool.y 50 | bison ${BFLAGS} cool.y 51 | mv -f cool.tab.c cool-parse.cc 52 | 53 | dotest: parser good.cl bad.cl 54 | @echo "\nRunning parser on good.cl\n" 55 | -./myparser good.cl 56 | @echo "\nRunning parser on bad.cl\n" 57 | -./myparser bad.cl 58 | 59 | ${LIBS}: 60 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 61 | 62 | ${TSRC} ${CSRC}: 63 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 64 | 65 | ${HSRC}: 66 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 67 | 68 | clean : 69 | -rm -f ${OUTPUT} *.s core ${OBJS} ${CGEN} ${HGEN} lexer parser cgen semant *~ *.a *.o 70 | 71 | clean-compile: 72 | @-rm -f core ${OBJS} ${CGEN} ${HGEN} ${LSRC} 73 | 74 | %.d: %.cc ${LSRC} 75 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 76 | 77 | -include ${CFIL:.cc=.d} 78 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /assignments/PA3/cool-parse.d: -------------------------------------------------------------------------------- 1 | cool-parse.o cool-parse.d : cool-parse.cc ../../include/PA3/cool-tree.h \ 2 | ../../include/PA3/tree.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/stringtab.h ../../include/PA3/list.h \ 4 | ../../include/PA3/cool-io.h cool-tree.handcode.h \ 5 | ../../include/PA3/tree.h ../../include/PA3/cool.h \ 6 | ../../include/PA3/stringtab.h ../../include/PA3/stringtab.h \ 7 | ../../include/PA3/utilities.h 8 | -------------------------------------------------------------------------------- /assignments/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 | -------------------------------------------------------------------------------- /assignments/PA3/cool-tree.d: -------------------------------------------------------------------------------- 1 | cool-tree.o cool-tree.d : cool-tree.cc ../../include/PA3/tree.h \ 2 | ../../include/PA3/copyright.h ../../include/PA3/stringtab.h \ 3 | ../../include/PA3/list.h ../../include/PA3/cool-io.h \ 4 | cool-tree.handcode.h ../../include/PA3/cool.h \ 5 | ../../include/PA3/stringtab.h ../../include/PA3/cool-tree.h \ 6 | ../../include/PA3/tree.h cool-tree.handcode.h 7 | -------------------------------------------------------------------------------- /assignments/PA3/dumptype.d: -------------------------------------------------------------------------------- 1 | dumptype.o dumptype.d : dumptype.cc ../../include/PA3/copyright.h \ 2 | ../../include/PA3/cool.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/cool-io.h ../../include/PA3/tree.h \ 4 | ../../include/PA3/stringtab.h ../../include/PA3/list.h \ 5 | ../../include/PA3/cool-tree.h ../../include/PA3/tree.h \ 6 | cool-tree.handcode.h ../../include/PA3/tree.h ../../include/PA3/cool.h \ 7 | ../../include/PA3/stringtab.h ../../include/PA3/utilities.h 8 | -------------------------------------------------------------------------------- /assignments/PA3/good.cl: -------------------------------------------------------------------------------- 1 | class A { 2 | ana(): Int { 3 | (let x:Int <- 1 in 2)+3 4 | }; 5 | }; 6 | 7 | Class BB__ inherits A { 8 | }; 9 | -------------------------------------------------------------------------------- /assignments/PA3/handle_flags.d: -------------------------------------------------------------------------------- 1 | handle_flags.o handle_flags.d : handle_flags.cc ../../include/PA3/copyright.h \ 2 | ../../include/PA3/cool-io.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/cgen_gc.h 4 | -------------------------------------------------------------------------------- /assignments/PA3/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /assignments/PA3/myparser: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* 3 | -------------------------------------------------------------------------------- /assignments/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 // for getopt 17 | #include "cool-io.h" //includes iostream 18 | #include "cool-tree.h" 19 | #include "utilities.h" // for fatal_error 20 | #include "cool-parse.h" 21 | 22 | // 23 | // These globals keep everything working. 24 | // 25 | FILE *token_file = stdin; // we read from this file 26 | extern Classes parse_results; // list of classes; used for multiple files 27 | extern Program ast_root; // the AST produced by the parse 28 | 29 | char *curr_filename = ""; 30 | 31 | extern int omerrs; // a count of lex and parse errors 32 | 33 | extern int cool_yyparse(); 34 | void handle_flags(int argc, char *argv[]); 35 | 36 | int main(int argc, char *argv[]) { 37 | handle_flags(argc, argv); 38 | cool_yyparse(); 39 | if (omerrs != 0) { 40 | cerr << "Compilation halted due to lex and parse errors\n"; 41 | exit(1); 42 | } 43 | ast_root->dump_with_types(cout,0); 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /assignments/PA3/parser-phase.d: -------------------------------------------------------------------------------- 1 | parser-phase.o parser-phase.d : parser-phase.cc ../../include/PA3/copyright.h \ 2 | ../../include/PA3/cool-io.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/cool-tree.h ../../include/PA3/tree.h \ 4 | ../../include/PA3/stringtab.h ../../include/PA3/list.h \ 5 | ../../include/PA3/cool-io.h cool-tree.handcode.h \ 6 | ../../include/PA3/tree.h ../../include/PA3/cool.h \ 7 | ../../include/PA3/stringtab.h ../../include/PA3/utilities.h \ 8 | ../../include/PA3/cool-parse.h 9 | -------------------------------------------------------------------------------- /assignments/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 | -------------------------------------------------------------------------------- /assignments/PA3/stringtab.d: -------------------------------------------------------------------------------- 1 | stringtab.o stringtab.d : stringtab.cc ../../include/PA3/copyright.h \ 2 | ../../include/PA3/stringtab_functions.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/cool-io.h ../../include/PA3/stringtab.h \ 4 | ../../include/PA3/list.h ../../include/PA3/stringtab.h 5 | -------------------------------------------------------------------------------- /assignments/PA3/tokens-lex.d: -------------------------------------------------------------------------------- 1 | tokens-lex.o tokens-lex.d : tokens-lex.cc ../../include/PA3/cool-parse.h \ 2 | ../../include/PA3/copyright.h ../../include/PA3/cool-io.h \ 3 | ../../include/PA3/tree.h ../../include/PA3/stringtab.h \ 4 | ../../include/PA3/list.h ../../include/PA3/stringtab.h \ 5 | ../../include/PA3/utilities.h 6 | -------------------------------------------------------------------------------- /assignments/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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | -------------------------------------------------------------------------------- /assignments/PA3/tree.d: -------------------------------------------------------------------------------- 1 | tree.o tree.d : tree.cc ../../include/PA3/copyright.h ../../include/PA3/tree.h \ 2 | ../../include/PA3/copyright.h ../../include/PA3/stringtab.h \ 3 | ../../include/PA3/list.h ../../include/PA3/cool-io.h 4 | -------------------------------------------------------------------------------- /assignments/PA3/utilities.d: -------------------------------------------------------------------------------- 1 | utilities.o utilities.d : utilities.cc ../../include/PA3/copyright.h \ 2 | ../../include/PA3/cool-io.h ../../include/PA3/copyright.h \ 3 | ../../include/PA3/cool-parse.h ../../include/PA3/cool-io.h \ 4 | ../../include/PA3/tree.h ../../include/PA3/stringtab.h \ 5 | ../../include/PA3/list.h ../../include/PA3/stringtab.h \ 6 | ../../include/PA3/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/PA4/Makefile: -------------------------------------------------------------------------------- 1 | 2 | ASSN = 4 3 | CLASS= cs143 4 | CLASSDIR= ../.. 5 | LIB= -L/usr/pubsw/lib -lfl 6 | AR= gar 7 | ARCHIVE_NEW= -cr 8 | RANLIB= gar -qs 9 | 10 | SRC= semant.cc semant.h cool-tree.h cool-tree.handcode.h good.cl bad.cl README 11 | 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 12 | TSRC= mycoolc mysemant cool-tree.aps 13 | CGEN= 14 | HGEN= 15 | LIBS= lexer parser cgen 16 | CFIL= semant.cc ${CSRC} ${CGEN} 17 | LSRC= Makefile 18 | OBJS= ${CFIL:.cc=.o} 19 | OUTPUT= good.output bad.output 20 | 21 | 22 | CPPINCLUDE= -I. -I${CLASSDIR}/include/PA${ASSN} -I${CLASSDIR}/src/PA${ASSN} 23 | 24 | FFLAGS = -d8 -ocool-lex.cc 25 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 26 | ASTBFLAGS = -d -v -y -b ast --debug -p ast_yy 27 | 28 | CC=g++ 29 | CFLAGS=-g -Wall -Wno-unused -Wno-write-strings -Wno-deprecated ${CPPINCLUDE} -DDEBUG -std=c++17 30 | FLEX=flex ${FFLAGS} 31 | BISON= bison ${BFLAGS} 32 | DEPEND = ${CC} -MM ${CPPINCLUDE} 33 | 34 | source: ${SRC} ${TSRC} ${LIBS} lsource 35 | 36 | lsource: ${LSRC} 37 | 38 | ${OUTPUT}: semant 39 | @rm -f ${OUTPUT} 40 | ./mysemant good.cl >good.output 2>&1 41 | -./mysemant bad.cl >bad.output 2>&1 42 | 43 | compile: semant change-prot 44 | 45 | change-prot: 46 | @-chmod 660 ${SRC} ${OUTPUT} 47 | 48 | SEMANT_OBJS := ${filter-out symtab_example.o,${OBJS}} 49 | 50 | semant: ${SEMANT_OBJS} lexer parser cgen 51 | ${CC} ${CFLAGS} ${SEMANT_OBJS} ${LIB} -o semant 52 | 53 | symtab_example: symtab_example.cc 54 | ${CC} ${CFLAGS} symtab_example.cc ${LIB} -o symtab_example 55 | 56 | .cc.o: 57 | ${CC} ${CFLAGS} -c $< 58 | 59 | dotest: semant good.cl bad.cl 60 | @echo "\nRunning semantic checker on good.cl\n" 61 | -./mysemant good.cl 62 | @echo "\nRunning semantic checker on bad.cl\n" 63 | -./mysemant bad.cl 64 | 65 | ${LIBS}: 66 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 67 | 68 | ${TSRC} ${CSRC}: 69 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 70 | 71 | ${HSRC}: 72 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 73 | 74 | clean : 75 | -rm -f ${OUTPUT} *.s core ${OBJS} semant cgen symtab_example parser lexer *~ *.a *.o 76 | 77 | clean-compile: 78 | @-rm -f core ${OBJS} ${LSRC} 79 | 80 | %.d: %.cc ${SRC} 81 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 82 | 83 | -include ${CFIL:.cc=.d} 84 | 85 | -------------------------------------------------------------------------------- /assignments/PA4/ast-lex.d: -------------------------------------------------------------------------------- 1 | ast-lex.o ast-lex.d : ast-lex.cc ../../include/PA4/ast-parse.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/cool-io.h \ 3 | ../../include/PA4/tree.h ../../include/PA4/stringtab.h \ 4 | ../../include/PA4/list.h ../../include/PA4/stringtab.h \ 5 | ../../include/PA4/utilities.h 6 | -------------------------------------------------------------------------------- /assignments/PA4/ast-parse.d: -------------------------------------------------------------------------------- 1 | ast-parse.o ast-parse.d : ast-parse.cc ../../include/PA4/cool-io.h \ 2 | ../../include/PA4/copyright.h cool-tree.h ../../include/PA4/tree.h \ 3 | ../../include/PA4/stringtab.h ../../include/PA4/list.h \ 4 | ../../include/PA4/cool-io.h cool-tree.handcode.h \ 5 | ../../include/PA4/cool.h ../../include/PA4/stringtab.h \ 6 | ../../include/PA4/utilities.h 7 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /assignments/PA4/cool-tree.d: -------------------------------------------------------------------------------- 1 | cool-tree.o cool-tree.d : cool-tree.cc ../../include/PA4/tree.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/stringtab.h \ 3 | ../../include/PA4/list.h ../../include/PA4/cool-io.h \ 4 | cool-tree.handcode.h ../../include/PA4/cool.h \ 5 | ../../include/PA4/stringtab.h cool-tree.h 6 | -------------------------------------------------------------------------------- /assignments/PA4/dumptype.d: -------------------------------------------------------------------------------- 1 | dumptype.o dumptype.d : dumptype.cc ../../include/PA4/copyright.h \ 2 | ../../include/PA4/cool.h ../../include/PA4/copyright.h \ 3 | ../../include/PA4/cool-io.h ../../include/PA4/tree.h \ 4 | ../../include/PA4/stringtab.h ../../include/PA4/list.h cool-tree.h \ 5 | cool-tree.handcode.h ../../include/PA4/stringtab.h \ 6 | ../../include/PA4/utilities.h 7 | -------------------------------------------------------------------------------- /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/handle_flags.d: -------------------------------------------------------------------------------- 1 | handle_flags.o handle_flags.d : handle_flags.cc ../../include/PA4/copyright.h \ 2 | ../../include/PA4/cool-io.h ../../include/PA4/copyright.h \ 3 | ../../include/PA4/cgen_gc.h 4 | -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_basecalsss.cl: -------------------------------------------------------------------------------- 1 | class A inherits Int { 2 | 3 | }; 4 | 5 | class B inherits Object { 6 | 7 | }; 8 | 9 | class C inherits IO { 10 | 11 | }; 12 | 13 | class D inherits String { 14 | 15 | }; 16 | 17 | class E inherits Bool { 18 | 19 | }; 20 | -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_bigcycle.cl: -------------------------------------------------------------------------------- 1 | class A inherits B {}; 2 | class B inherits C {}; 3 | class C inherits D {}; 4 | class D inherits A {}; 5 | class Main {}; 6 | -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_nodefine.cl: -------------------------------------------------------------------------------- 1 | class A inherits C { 2 | 3 | }; -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_redefinebase.cl: -------------------------------------------------------------------------------- 1 | class String {}; -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_redefined.cl: -------------------------------------------------------------------------------- 1 | class A {}; 2 | 3 | class B {}; 4 | 5 | class A {}; -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_self.cl: -------------------------------------------------------------------------------- 1 | class A inherits A {}; 2 | 3 | class Main {}; 4 | -------------------------------------------------------------------------------- /assignments/PA4/my_test/inheritance_with_cycle.cl: -------------------------------------------------------------------------------- 1 | class A inherits B { 2 | 3 | }; 4 | 5 | class Main { 6 | 7 | }; 8 | class B inherits A { 9 | 10 | }; 11 | -------------------------------------------------------------------------------- /assignments/PA4/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /assignments/PA4/mysemant: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* 3 | -------------------------------------------------------------------------------- /assignments/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 | char *curr_filename; 10 | 11 | void handle_flags(int argc, char *argv[]); 12 | 13 | int main(int argc, char *argv[]) { 14 | handle_flags(argc,argv); 15 | ast_yyparse(); 16 | ast_root->semant(); 17 | ast_root->dump_with_types(cout,0); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /assignments/PA4/semant-phase.d: -------------------------------------------------------------------------------- 1 | semant-phase.o semant-phase.d : semant-phase.cc cool-tree.h ../../include/PA4/tree.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/stringtab.h \ 3 | ../../include/PA4/list.h ../../include/PA4/cool-io.h \ 4 | cool-tree.handcode.h ../../include/PA4/cool.h \ 5 | ../../include/PA4/stringtab.h 6 | -------------------------------------------------------------------------------- /assignments/PA4/semant.d: -------------------------------------------------------------------------------- 1 | semant.o semant.d : semant.cc semant.h cool-tree.h ../../include/PA4/tree.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/stringtab.h \ 3 | ../../include/PA4/list.h ../../include/PA4/cool-io.h \ 4 | cool-tree.handcode.h ../../include/PA4/cool.h \ 5 | ../../include/PA4/stringtab.h ../../include/PA4/symtab.h \ 6 | ../../include/PA4/list.h ../../include/PA4/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/PA4/semant.h: -------------------------------------------------------------------------------- 1 | #ifndef SEMANT_H_ 2 | #define SEMANT_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "cool-tree.h" 10 | #include "stringtab.h" 11 | #include "symtab.h" 12 | #include "list.h" 13 | 14 | #define TRUE 1 15 | #define FALSE 0 16 | 17 | class ClassTable; 18 | typedef ClassTable *ClassTableP; 19 | 20 | // This is a structure that may be used to contain the semantic 21 | // information such as the inheritance graph. You may use it or not as 22 | // you like: it is only here to provide a container for the supplied 23 | // methods. 24 | 25 | class ClassTable { 26 | private: 27 | int semant_errors; 28 | void install_basic_classes(); 29 | void install_user_classes(); 30 | void check_cycle(); 31 | 32 | // collect all method information and put them to env 33 | void collectAndCheckAllMethod(); 34 | 35 | void coolectAndCheckAllMethodSubroution(Symbol cur_class); 36 | 37 | void buildGraphTopDown(); 38 | 39 | 40 | void abort() { 41 | cerr << "Compilation halted due to static semantic errors." << endl; 42 | exit(1); 43 | } 44 | 45 | ostream& error_stream; 46 | 47 | Classes classes_; 48 | 49 | std::unordered_map graph_; 50 | std::unordered_map> graph_rev_; 51 | std::unordered_map symbol_to_class_; 52 | 53 | Enviro env_; 54 | 55 | public: 56 | ClassTable(Classes); 57 | 58 | void check_phase1(); 59 | 60 | void check_phase2(); 61 | 62 | std::optional getClass(Symbol class_name) { 63 | if (symbol_to_class_.find(class_name) != symbol_to_class_.end()) { 64 | return symbol_to_class_[class_name]; 65 | } else { 66 | return {}; 67 | } 68 | } 69 | 70 | std::vector getChild(Symbol cur_class) { 71 | if (graph_rev_.find(cur_class) == graph_rev_.end()) return {}; 72 | else return graph_rev_[cur_class]; 73 | } 74 | 75 | int errors() { return semant_errors; } 76 | ostream& semant_error(); 77 | ostream& semant_error(Class_ c); 78 | ostream& semant_error(Symbol filename, tree_node *t); 79 | }; 80 | 81 | 82 | #endif 83 | 84 | -------------------------------------------------------------------------------- /assignments/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 | -------------------------------------------------------------------------------- /assignments/PA4/stringtab.d: -------------------------------------------------------------------------------- 1 | stringtab.o stringtab.d : stringtab.cc ../../include/PA4/copyright.h \ 2 | ../../include/PA4/stringtab_functions.h ../../include/PA4/copyright.h \ 3 | ../../include/PA4/cool-io.h ../../include/PA4/stringtab.h \ 4 | ../../include/PA4/list.h ../../include/PA4/stringtab.h 5 | -------------------------------------------------------------------------------- /assignments/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 | cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 30 | 31 | // check whether Mary is in any scope; predicate is true 32 | 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 | cout << *(map->lookup(Mary)) << "\n"; 37 | 38 | // check whether Miguel is in the current scope; predicate is true 39 | 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 | cout << *(map->lookup(Mary)) << "\n"; 46 | 47 | // check whether Fred is in the current scope; predicate is now true 48 | cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 49 | 50 | // check whether Miguel is in any scope; predicate is now false 51 | cout << ((map->lookup(Miguel) != NULL) ? "Yes\n" : "No\n"); 52 | 53 | return 0; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /assignments/PA4/symtab_example.d: -------------------------------------------------------------------------------- 1 | symtab_example.o symtab_example.d : symtab_example.cc ../../include/PA4/symtab.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/list.h \ 3 | ../../include/PA4/cool-io.h 4 | -------------------------------------------------------------------------------- /assignments/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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | -------------------------------------------------------------------------------- /assignments/PA4/tree.d: -------------------------------------------------------------------------------- 1 | tree.o tree.d : tree.cc ../../include/PA4/copyright.h ../../include/PA4/tree.h \ 2 | ../../include/PA4/copyright.h ../../include/PA4/stringtab.h \ 3 | ../../include/PA4/list.h ../../include/PA4/cool-io.h 4 | -------------------------------------------------------------------------------- /assignments/PA4/utilities.d: -------------------------------------------------------------------------------- 1 | utilities.o utilities.d : utilities.cc ../../include/PA4/copyright.h \ 2 | ../../include/PA4/cool-io.h ../../include/PA4/copyright.h \ 3 | ../../include/PA4/cool-parse.h ../../include/PA4/cool-io.h \ 4 | ../../include/PA4/tree.h ../../include/PA4/stringtab.h \ 5 | ../../include/PA4/list.h ../../include/PA4/stringtab.h \ 6 | ../../include/PA4/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/PA5/Makefile: -------------------------------------------------------------------------------- 1 | 2 | ASSN = 5 3 | CLASS= cs143 4 | CLASSDIR= ../.. 5 | LIB= -L/usr/pubsw/lib -lfl 6 | AR= gar 7 | ARCHIVE_NEW= -cr 8 | RANLIB= gar -qs 9 | 10 | SRC= cgen.cc cgen.h cgen_supp.cc cool-tree.h cool-tree.handcode.h emit.h example.cl README 11 | CSRC= cgen-phase.cc utilities.cc stringtab.cc dumptype.cc tree.cc cool-tree.cc ast-lex.cc ast-parse.cc handle_flags.cc 12 | TSRC= mycoolc 13 | CGEN= 14 | HGEN= 15 | LIBS= lexer parser semant 16 | CFIL= cgen.cc cgen_supp.cc ${CSRC} ${CGEN} 17 | LSRC= Makefile 18 | OBJS= ${CFIL:.cc=.o} 19 | OUTPUT= good.output bad.output 20 | 21 | 22 | CPPINCLUDE= -I. -I${CLASSDIR}/include/PA${ASSN} -I${CLASSDIR}/src/PA${ASSN} 23 | 24 | 25 | FFLAGS = -d8 -ocool-lex.cc 26 | BFLAGS = -d -v -y -b cool --debug -p cool_yy 27 | 28 | CC=g++ 29 | CFLAGS=-g -Wall -Wno-unused -Wno-write-strings -Wno-deprecated ${CPPINCLUDE} -DDEBUG -std=c++17 30 | FLEX=flex ${FFLAGS} 31 | BISON= bison ${BFLAGS} 32 | DEPEND = ${CC} -MM ${CPPINCLUDE} 33 | 34 | source: ${SRC} ${TSRC} ${LIBS} lsource 35 | 36 | lsource: ${LSRC} 37 | 38 | ${OUTPUT}: cgen 39 | @rm -f ${OUTPUT} 40 | ./mycoolc example.cl >example.output 2>&1 41 | 42 | compile: cgen change-prot 43 | 44 | change-prot: 45 | @-chmod 660 ${SRC} ${OUTPUT} 46 | 47 | cgen: ${OBJS} parser semant 48 | ${CC} ${CFLAGS} ${OBJS} ${LIB} -o cgen 49 | 50 | .cc.o: 51 | ${CC} ${CFLAGS} -c $< 52 | 53 | dotest: cgen example.cl 54 | @echo "\nRunning code generator on example.cl\n" 55 | -./mycoolc example.cl 56 | 57 | ${LIBS}: 58 | ${CLASSDIR}/etc/link-object ${ASSN} $@ 59 | 60 | ${TSRC} ${CSRC}: 61 | -ln -s ${CLASSDIR}/src/PA${ASSN}/$@ $@ 62 | 63 | ${HSRC}: 64 | -ln -s ${CLASSDIR}/include/PA${ASSN}/$@ $@ 65 | 66 | clean : 67 | -rm -f ${OUTPUT} *.s core ${OBJS} cgen parser semant lexer *~ *.a *.o 68 | 69 | clean-compile: 70 | @-rm -f core ${OBJS} ${LSRC} 71 | 72 | %.d: %.cc ${SRC} 73 | ${SHELL} -ec '${DEPEND} $< | sed '\''s/\($*\.o\)[ :]*/\1 $@ : /g'\'' > $@' 74 | 75 | -include ${CFIL:.cc=.d} 76 | 77 | 78 | -------------------------------------------------------------------------------- /assignments/PA5/ast-lex.d: -------------------------------------------------------------------------------- 1 | ast-lex.o ast-lex.d : ast-lex.cc ../../include/PA5/ast-parse.h \ 2 | ../../include/PA5/copyright.h ../../include/PA5/cool-io.h \ 3 | ../../include/PA5/tree.h ../../include/PA5/stringtab.h \ 4 | ../../include/PA5/list.h ../../include/PA5/stringtab.h \ 5 | ../../include/PA5/utilities.h 6 | -------------------------------------------------------------------------------- /assignments/PA5/ast-parse.d: -------------------------------------------------------------------------------- 1 | ast-parse.o ast-parse.d : ast-parse.cc ../../include/PA5/cool-io.h \ 2 | ../../include/PA5/copyright.h cool-tree.h ../../include/PA5/tree.h \ 3 | ../../include/PA5/stringtab.h ../../include/PA5/list.h \ 4 | ../../include/PA5/cool-io.h cool-tree.handcode.h \ 5 | ../../include/PA5/cool.h ../../include/PA5/stringtab.h \ 6 | ../../include/PA5/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/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 | char *curr_filename; 16 | 17 | void handle_flags(int argc, char *argv[]); 18 | 19 | int main(int argc, char *argv[]) { 20 | int firstfile_index; 21 | 22 | handle_flags(argc,argv); 23 | firstfile_index = optind; 24 | 25 | if (!out_filename && optind < argc) { // no -o option 26 | char *dot = strrchr(argv[optind], '.'); 27 | if (dot) *dot = '\0'; // strip off file extension 28 | out_filename = new char[strlen(argv[optind])+8]; 29 | strcpy(out_filename, argv[optind]); 30 | strcat(out_filename, ".s"); 31 | } 32 | 33 | // 34 | // Don't touch the output file until we know that earlier phases of the 35 | // compiler have succeeded. 36 | // 37 | ast_yyparse(); 38 | 39 | if (out_filename) { 40 | ofstream s(out_filename); 41 | if (!s) { 42 | cerr << "Cannot open output file " << out_filename << endl; 43 | exit(1); 44 | } 45 | ast_root->cgen(s); 46 | } else { 47 | ast_root->cgen(cout); 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /assignments/PA5/cgen-phase.d: -------------------------------------------------------------------------------- 1 | cgen-phase.o cgen-phase.d : cgen-phase.cc ../../include/PA5/cool-io.h \ 2 | ../../include/PA5/copyright.h cool-tree.h ../../include/PA5/tree.h \ 3 | ../../include/PA5/stringtab.h ../../include/PA5/list.h \ 4 | ../../include/PA5/cool-io.h cool-tree.handcode.h \ 5 | ../../include/PA5/cool.h ../../include/PA5/stringtab.h \ 6 | ../../include/PA5/cgen_gc.h 7 | -------------------------------------------------------------------------------- /assignments/PA5/cgen.d: -------------------------------------------------------------------------------- 1 | cgen.o cgen.d : cgen.cc cgen.h emit.h ../../include/PA5/stringtab.h \ 2 | ../../include/PA5/copyright.h ../../include/PA5/list.h \ 3 | ../../include/PA5/cool-io.h cool-tree.h ../../include/PA5/tree.h \ 4 | ../../include/PA5/stringtab.h cool-tree.handcode.h \ 5 | ../../include/PA5/cool.h ../../include/PA5/symtab.h \ 6 | ../../include/PA5/cgen_gc.h 7 | -------------------------------------------------------------------------------- /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/cgen_supp.d: -------------------------------------------------------------------------------- 1 | cgen_supp.o cgen_supp.d : cgen_supp.cc ../../include/PA5/stringtab.h \ 2 | ../../include/PA5/copyright.h ../../include/PA5/list.h \ 3 | ../../include/PA5/cool-io.h 4 | -------------------------------------------------------------------------------- /assignments/PA5/change.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | file_list = os.listdir("grading") 4 | file_list = [x for x in file_list if x.endswith(".out")] 5 | for file in file_list: 6 | with open(os.path.join("./grading", file), 'r') as f: 7 | cont = f.read() 8 | cont = cont.split("\n") 9 | cont[4] = "Loaded: ../lib/trap.handler" 10 | with open(os.path.join("./grading", file), 'w') as f: 11 | f.write("\n".join(cont)) 12 | -------------------------------------------------------------------------------- /assignments/PA5/cool-tree.d: -------------------------------------------------------------------------------- 1 | cool-tree.o cool-tree.d : cool-tree.cc ../../include/PA5/tree.h \ 2 | ../../include/PA5/copyright.h ../../include/PA5/stringtab.h \ 3 | ../../include/PA5/list.h ../../include/PA5/cool-io.h \ 4 | cool-tree.handcode.h ../../include/PA5/cool.h \ 5 | ../../include/PA5/stringtab.h cool-tree.h 6 | -------------------------------------------------------------------------------- /assignments/PA5/dumptype.d: -------------------------------------------------------------------------------- 1 | dumptype.o dumptype.d : dumptype.cc ../../include/PA5/copyright.h \ 2 | ../../include/PA5/cool.h ../../include/PA5/copyright.h \ 3 | ../../include/PA5/cool-io.h ../../include/PA5/tree.h \ 4 | ../../include/PA5/stringtab.h ../../include/PA5/list.h cool-tree.h \ 5 | cool-tree.handcode.h ../../include/PA5/stringtab.h \ 6 | ../../include/PA5/utilities.h 7 | -------------------------------------------------------------------------------- /assignments/PA5/example.cl: -------------------------------------------------------------------------------- 1 | 2 | (* Example cool program testing as many aspects of the code generator 3 | as possible. 4 | *) 5 | 6 | class A { 7 | 8 | add(p: Int): Int { 9 | 1 10 | }; 11 | 12 | sub(p: Int): Int { 13 | 3 14 | }; 15 | }; 16 | 17 | 18 | class B inherits A { 19 | add(p: Int) : Int { 20 | 2 21 | }; 22 | }; 23 | 24 | class C { 25 | p : A <- new B; 26 | 27 | func(): Object { 28 | p.add(1) 29 | }; 30 | }; 31 | 32 | class D { 33 | p: C; 34 | }; 35 | 36 | class Main { 37 | a : Int <- 1; 38 | b : Int <- 2; 39 | c : Int <- a + b; 40 | 41 | add(p1:Int, p2: Int, p3: Int): Int { 42 | a + p1 + p2 + p3 43 | }; 44 | 45 | test(p: Int): Int { 46 | if p < 1 then 47 | p 48 | else 49 | 1 50 | fi 51 | }; 52 | 53 | test2(): Object { 54 | case 1 of 55 | e1: Int => 1; 56 | e2: Object => e2; 57 | esac 58 | }; 59 | 60 | test3(p1: Int, p2: Int): Int { 61 | p1 + p2 62 | }; 63 | 64 | test4(p1: Int, p2: Int): Bool { 65 | p1 < p2 66 | }; 67 | 68 | test5(): Int { 69 | New Int 70 | }; 71 | 72 | test6(p: Int): Int { 73 | if isvoid p then 74 | 1 75 | else 76 | 0 77 | fi 78 | }; 79 | 80 | main():Object { 81 | add(a, b, c) 82 | }; 83 | 84 | }; 85 | 86 | -------------------------------------------------------------------------------- /assignments/PA5/handle_flags.d: -------------------------------------------------------------------------------- 1 | handle_flags.o handle_flags.d : handle_flags.cc ../../include/PA5/copyright.h \ 2 | ../../include/PA5/cool-io.h ../../include/PA5/copyright.h \ 3 | ../../include/PA5/cgen_gc.h 4 | -------------------------------------------------------------------------------- /assignments/PA5/my_test/simple.cl: -------------------------------------------------------------------------------- 1 | class Main { 2 | main(): Int { 3 | 1 4 | }; 5 | }; -------------------------------------------------------------------------------- /assignments/PA5/my_test/simple_out.cl: -------------------------------------------------------------------------------- 1 | class Main inherits IO { 2 | main(): Object { 3 | out_string("hello, world!\n") 4 | }; 5 | }; -------------------------------------------------------------------------------- /assignments/PA5/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | #./lexer $* | ./parser $* | ./semant $* 4 | -------------------------------------------------------------------------------- /assignments/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 | -------------------------------------------------------------------------------- /assignments/PA5/stringtab.d: -------------------------------------------------------------------------------- 1 | stringtab.o stringtab.d : stringtab.cc ../../include/PA5/copyright.h \ 2 | ../../include/PA5/stringtab_functions.h ../../include/PA5/copyright.h \ 3 | ../../include/PA5/cool-io.h ../../include/PA5/stringtab.h \ 4 | ../../include/PA5/list.h ../../include/PA5/stringtab.h 5 | -------------------------------------------------------------------------------- /assignments/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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | -------------------------------------------------------------------------------- /assignments/PA5/tree.d: -------------------------------------------------------------------------------- 1 | tree.o tree.d : tree.cc ../../include/PA5/copyright.h ../../include/PA5/tree.h \ 2 | ../../include/PA5/copyright.h ../../include/PA5/stringtab.h \ 3 | ../../include/PA5/list.h ../../include/PA5/cool-io.h 4 | -------------------------------------------------------------------------------- /assignments/PA5/utilities.d: -------------------------------------------------------------------------------- 1 | utilities.o utilities.d : utilities.cc ../../include/PA5/copyright.h \ 2 | ../../include/PA5/cool-io.h ../../include/PA5/copyright.h \ 3 | ../../include/PA5/cool-parse.h ../../include/PA5/cool-io.h \ 4 | ../../include/PA5/tree.h ../../include/PA5/stringtab.h \ 5 | ../../include/PA5/list.h ../../include/PA5/stringtab.h \ 6 | ../../include/PA5/utilities.h 7 | -------------------------------------------------------------------------------- /bin/.i686/anngen: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/anngen -------------------------------------------------------------------------------- /bin/.i686/aps2c++: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/aps2c++ -------------------------------------------------------------------------------- /bin/.i686/aps2java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/aps2java -------------------------------------------------------------------------------- /bin/.i686/cgen: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/cgen -------------------------------------------------------------------------------- /bin/.i686/coolc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/coolc -------------------------------------------------------------------------------- /bin/.i686/lexer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/lexer -------------------------------------------------------------------------------- /bin/.i686/parser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/parser -------------------------------------------------------------------------------- /bin/.i686/semant: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/semant -------------------------------------------------------------------------------- /bin/.i686/spim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/spim -------------------------------------------------------------------------------- /bin/.i686/xspim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/bin/.i686/xspim -------------------------------------------------------------------------------- /bin/anngen: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/anngen 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/aps2c++: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | xname=$COOL_INST/bin/.$arch/aps2c++ 30 | 31 | if [ -x $xname ]; then 32 | exec $xname $* 33 | else 34 | echo aps2c++ is not compiled for $arch 35 | fi 36 | -------------------------------------------------------------------------------- /bin/aps2java: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | xname=$COOL_INST/bin/.$arch/aps2java 30 | 31 | if [ -x $xname ]; then 32 | exec $xname $* 33 | else 34 | echo aps2c++ is not compiled for $arch 35 | fi 36 | -------------------------------------------------------------------------------- /bin/cgen: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/cgen 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/coolc: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/coolc 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/lexer: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/lexer 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/parser: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/parser 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/semant: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | 25 | # set environment for spim/xspim 26 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 27 | export DEFAULT_TRAP_HANDLER 28 | 29 | 30 | xname=$COOL_INST/bin/.$arch/semant 31 | 32 | if [ -x $xname ]; then 33 | exec $xname $* 34 | else 35 | echo coolc is not compiled for $arch 36 | fi 37 | -------------------------------------------------------------------------------- /bin/spim: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | 7 | progname=`basename $0` 8 | 9 | # Resolve symlinks, so that the pathname computations below find the 10 | # directory structure they expect. 11 | while [ -h "$PRG" ]; do 12 | # Get the target of the symlink. N.B.: We assume that neither the 13 | # link's value nor the pathname leading to it contains "-> ". 14 | ls=`/bin/ls -ld "$PRG"` 15 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 16 | # If the link is absolute, use it as is; otherwise, substitute it 17 | # into the leafname part of $PRG. 18 | case $link in 19 | /*) PRG="$link";; 20 | *) PRG="`/usr/bin/dirname $PRG`/$link" 21 | esac 22 | done 23 | 24 | #COOL_INST=`/usr/bin/dirname "$PRG"`/.. 25 | COOL_INST=$(cd `dirname $0` && pwd)/.. 26 | 27 | # set environment for spim/xspim 28 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 29 | export DEFAULT_TRAP_HANDLER 30 | 31 | 32 | 33 | # function to substitute an absolute path for a relative path 34 | function getabspath { 35 | base=`basename "$1"` 36 | dir=`dirname "$1"` 37 | 38 | # use python if possible since i trust it more 39 | if [ `type -P asdfpython` ]; then 40 | abspath=`python -c 'import sys 41 | import os 42 | print os.path.abspath(sys.argv[1])' $1` 43 | # make sure the directory exists 44 | elif [ ! -d "$dir" ]; then 45 | echo "ERROR" 46 | exit 1 47 | else 48 | abspath=`cd "$dir"; pwd`/"$base" 49 | fi 50 | echo $abspath 51 | } 52 | 53 | # fix command line arguments to have relative paths rather than absolute paths 54 | # if $1 is not a flag we assume it is a file 55 | if [ ${1:0:1} != "-" ]; then 56 | abspath=`getabspath "$1"` 57 | if [ "$abspath" == "ERROR" ]; then 58 | echo "$progname: $1: No such file or directory." >&2 59 | exit 1 60 | fi 61 | set -- "$abspath" "${@:2}" 62 | fi 63 | for ((i=1; i<=$#; i++)) 64 | do 65 | if [ "${!i}" == "-file" -o "${!i}" == "-execute" -o "${!i}" == "-trap_file" ]; then 66 | next=$(($i+1)) 67 | nextnext=$(($i+2)) 68 | abspath=`getabspath "${!next}"` 69 | if [ "$abspath" == "ERROR" ]; then 70 | echo "$progname: ${!next}: No such file or directory." >&2 71 | exit 1 72 | fi 73 | set -- "${@:1:$i}" "$abspath" "${@:$nextnext}" 74 | fi 75 | done 76 | 77 | xname=$COOL_INST/bin/.$arch/spim 78 | 79 | cd $COOL_INST/bin 80 | 81 | if [ -x $xname ]; then 82 | exec $xname "$@" 83 | else 84 | echo spim is not compiled for $arch 85 | fi 86 | -------------------------------------------------------------------------------- /bin/xspim: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | arch='i686' 3 | 4 | PRG=$0 5 | #progname=`/bin/basename $0` 6 | progname=`basename $0` 7 | 8 | # Resolve symlinks, so that the pathname computations below find the 9 | # directory structure they expect. 10 | while [ -h "$PRG" ]; do 11 | # Get the target of the symlink. N.B.: We assume that neither the 12 | # link's value nor the pathname leading to it contains "-> ". 13 | ls=`/bin/ls -ld "$PRG"` 14 | link=`/usr/bin/expr "$ls" : '.*-> \(.*\)$'` 15 | # If the link is absolute, use it as is; otherwise, substitute it 16 | # into the leafname part of $PRG. 17 | case $link in 18 | /*) PRG="$link";; 19 | *) PRG="`/usr/bin/dirname $PRG`/$link" 20 | esac 21 | done 22 | 23 | #COOL_INST=`/usr/bin/dirname "$PRG"`/.. 24 | COOL_INST=$(cd `dirname $0` && pwd)/.. 25 | 26 | # set environment for spim/xspim 27 | DEFAULT_TRAP_HANDLER=$COOL_INST/lib/trap.handler 28 | export DEFAULT_TRAP_HANDLER 29 | 30 | 31 | # function to substitute an absolute path for a relative path 32 | function getabspath { 33 | base=`basename "$1"` 34 | dir=`dirname "$1"` 35 | 36 | # use python if possible since i trust it more 37 | if [ `type -P asdfpython` ]; then 38 | abspath=`python -c 'import sys 39 | import os 40 | print os.path.abspath(sys.argv[1])' $1` 41 | # make sure the directory exists 42 | elif [ ! -d "$dir" ]; then 43 | echo "ERROR" 44 | exit 1 45 | else 46 | abspath=`cd "$dir"; pwd`/"$base" 47 | fi 48 | echo $abspath 49 | } 50 | 51 | # fix command line arguments to have relative paths rather than absolute paths 52 | # if $1 is not a flag we assume it is a file 53 | if [ $1 ] && [ ${1:0:1} != "-" ]; then 54 | abspath=`getabspath "$1"` 55 | if [ "$abspath" == "ERROR" ]; then 56 | echo "$progname: $1: No such file or directory." >&2 57 | exit 1 58 | fi 59 | set -- "$abspath" "${@:2}" 60 | fi 61 | for ((i=1; i<=$#; i++)) 62 | do 63 | if [ "${!i}" == "-file" -o "${!i}" == "-execute" -o "${!i}" == "-trap_file" ]; then 64 | next=$(($i+1)) 65 | nextnext=$(($i+2)) 66 | abspath=`getabspath "${!next}"` 67 | if [ "$abspath" == "ERROR" ]; then 68 | echo "$progname: ${!next}: No such file or directory." >&2 69 | exit 1 70 | fi 71 | set -- "${@:1:$i}" "$abspath" "${@:$nextnext}" 72 | fi 73 | done 74 | 75 | 76 | xname=$COOL_INST/bin/.$arch/xspim 77 | 78 | cd $COOL_INST/bin 79 | 80 | if [ -x $xname ]; then 81 | exec $xname $* 82 | else 83 | echo xspim is not compiled for $arch 84 | fi 85 | -------------------------------------------------------------------------------- /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 | #/usr/class/cs143ECT, IN/usr/class/cs143ECT, 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 | echo $COOL_INST 44 | 45 | num=$1 46 | 47 | #arch=`arch` 48 | arch="i686" 49 | 50 | shift 51 | for f 52 | do 53 | echo "linking $f" 54 | xname=${COOL_INST}/bin/.${arch}/$f 55 | if [ -f $xname ]; then 56 | ln -s $xname $f 57 | else 58 | echo $f is not compiled for $arch 59 | fi 60 | done 61 | 62 | -------------------------------------------------------------------------------- /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 | 51 | -------------------------------------------------------------------------------- /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/g1.graph: -------------------------------------------------------------------------------- 1 | 1 2,100 2 | 2 3,200 1,150 3 | 3 2,10 4 | 4 3,55 5,100 5 | 5 1,1 2,2 3,3 4,4 5,5 6 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /handouts/PA1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/PA1.pdf -------------------------------------------------------------------------------- /handouts/PA2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/PA2.pdf -------------------------------------------------------------------------------- /handouts/PA3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/PA3.pdf -------------------------------------------------------------------------------- /handouts/PA4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/PA4.pdf -------------------------------------------------------------------------------- /handouts/PA5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/PA5.pdf -------------------------------------------------------------------------------- /handouts/cool-manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/cool-manual.pdf -------------------------------------------------------------------------------- /handouts/cool-tour.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/cool-tour.pdf -------------------------------------------------------------------------------- /handouts/extra-credit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/handouts/extra-credit.pdf -------------------------------------------------------------------------------- /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 | // 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/PA2/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/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 | /* -*-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/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/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.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/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 "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/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/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 "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/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 "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/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 | #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/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 | -------------------------------------------------------------------------------- /lib/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Ant-Version: Apache Ant 1.6.2 3 | Created-By: 1.5.0_07-b03 (Sun Microsystems Inc.) 4 | Main-Class: java_cup/Main 5 | Class-Path: java-cup-11a-runtime.jar 6 | 7 | -------------------------------------------------------------------------------- /lib/java-cup-11a.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java-cup-11a.jar -------------------------------------------------------------------------------- /lib/java_cup/CUP$parser$actions.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/CUP$parser$actions.class -------------------------------------------------------------------------------- /lib/java_cup/ErrorManager.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/ErrorManager.class -------------------------------------------------------------------------------- /lib/java_cup/Lexer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/Lexer.class -------------------------------------------------------------------------------- /lib/java_cup/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/Main.class -------------------------------------------------------------------------------- /lib/java_cup/action_part.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/action_part.class -------------------------------------------------------------------------------- /lib/java_cup/action_production.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/action_production.class -------------------------------------------------------------------------------- /lib/java_cup/anttask/CUPTask.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/anttask/CUPTask.class -------------------------------------------------------------------------------- /lib/java_cup/assoc.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/assoc.class -------------------------------------------------------------------------------- /lib/java_cup/emit.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/emit.class -------------------------------------------------------------------------------- /lib/java_cup/internal_error.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/internal_error.class -------------------------------------------------------------------------------- /lib/java_cup/lalr_item.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/lalr_item.class -------------------------------------------------------------------------------- /lib/java_cup/lalr_item_set.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/lalr_item_set.class -------------------------------------------------------------------------------- /lib/java_cup/lalr_state.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/lalr_state.class -------------------------------------------------------------------------------- /lib/java_cup/lalr_transition.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/lalr_transition.class -------------------------------------------------------------------------------- /lib/java_cup/lr_item_core.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/lr_item_core.class -------------------------------------------------------------------------------- /lib/java_cup/non_terminal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/non_terminal.class -------------------------------------------------------------------------------- /lib/java_cup/nonassoc_action.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/nonassoc_action.class -------------------------------------------------------------------------------- /lib/java_cup/parse_action.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parse_action.class -------------------------------------------------------------------------------- /lib/java_cup/parse_action_row.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parse_action_row.class -------------------------------------------------------------------------------- /lib/java_cup/parse_action_table.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parse_action_table.class -------------------------------------------------------------------------------- /lib/java_cup/parse_reduce_row.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parse_reduce_row.class -------------------------------------------------------------------------------- /lib/java_cup/parse_reduce_table.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parse_reduce_table.class -------------------------------------------------------------------------------- /lib/java_cup/parser.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/parser.class -------------------------------------------------------------------------------- /lib/java_cup/production.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/production.class -------------------------------------------------------------------------------- /lib/java_cup/production_part.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/production_part.class -------------------------------------------------------------------------------- /lib/java_cup/reduce_action.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/reduce_action.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/ComplexSymbolFactory$ComplexSymbol.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/ComplexSymbolFactory$ComplexSymbol.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/ComplexSymbolFactory$Location.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/ComplexSymbolFactory$Location.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/ComplexSymbolFactory.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/ComplexSymbolFactory.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/DefaultSymbolFactory.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/DefaultSymbolFactory.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/ParserException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/ParserException.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/Scanner.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/Scanner.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/Symbol.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/Symbol.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/SymbolFactory.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/SymbolFactory.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/lr_parser.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/lr_parser.class -------------------------------------------------------------------------------- /lib/java_cup/runtime/virtual_parse_stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/runtime/virtual_parse_stack.class -------------------------------------------------------------------------------- /lib/java_cup/shift_action.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/shift_action.class -------------------------------------------------------------------------------- /lib/java_cup/sym.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/sym.class -------------------------------------------------------------------------------- /lib/java_cup/symbol.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/symbol.class -------------------------------------------------------------------------------- /lib/java_cup/symbol_part.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/symbol_part.class -------------------------------------------------------------------------------- /lib/java_cup/symbol_set.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/symbol_set.class -------------------------------------------------------------------------------- /lib/java_cup/terminal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/terminal.class -------------------------------------------------------------------------------- /lib/java_cup/terminal_set.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/terminal_set.class -------------------------------------------------------------------------------- /lib/java_cup/version.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/java_cup/version.class -------------------------------------------------------------------------------- /lib/jlex.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangdh15/cs143/bbe449cfd7efdb0e61f3b107418ed7ea749927fe/lib/jlex.jar -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## 编译器项目 2 | 3 | 完成斯坦福cs143的课程,并从头开始实现了一个编译器,通过全部附带测试,包括一下五个实验: 4 | 1. 熟悉Cool语言,支持循环、分支、函数调用、多态等特性。 5 | 2. 词法分析,书写正则表达式,利用flex生成自动机。 6 | 3. 语法分析,书写上下文无关文法,利用bison生成AST。 7 | 4. 语义分析,在AST上进行类型检查。 8 | 5. 代码生成,利用AST生成MIPS汇编代码。采用了stack machine的方式。 9 | 10 | 编程语言CPP。 11 | -------------------------------------------------------------------------------- /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 // for getopt 19 | #include "cool-parse.h" // bison-generated file; defines tokens 20 | #include "utilities.h" 21 | 22 | // 23 | // The lexer keeps this global variable up to date with the line number 24 | // of the current line read from the input. 25 | // 26 | int curr_lineno = 1; 27 | char *curr_filename = ""; // this name is arbitrary 28 | FILE *fin; // This is the file pointer from which the lexer reads its input. 29 | 30 | // 31 | // cool_yylex() is the function produced by flex. It returns the next 32 | // token each time it is called. 33 | // 34 | extern int cool_yylex(); 35 | YYSTYPE cool_yylval; // Not compiled with parser, so must define this. 36 | 37 | extern int optind; // used for option processing (man 3 getopt for more info) 38 | 39 | // 40 | // Option -v sets the lex_verbose flag. The main() function prints out tokens 41 | // if the program is invoked with option -v. Option -l sets yy_flex_debug. 42 | // 43 | extern int yy_flex_debug; // Flex debugging; see flex documentation. 44 | extern int lex_verbose; // Controls printing of tokens. 45 | void handle_flags(int argc, char *argv[]); 46 | 47 | // 48 | // The full Cool compiler contains several debugging flags, all of which 49 | // are handled and set by the routine handle_flags. Here we declare 50 | // cool_yydebug, which is not used by the lexer but is needed to link 51 | // with handle_flags. 52 | // 53 | int cool_yydebug; 54 | 55 | // defined in utilities.cc 56 | extern void dump_cool_token(ostream& out, int lineno, 57 | int token, YYSTYPE yylval); 58 | 59 | 60 | int main(int argc, char** argv) { 61 | int token; 62 | 63 | handle_flags(argc,argv); 64 | 65 | while (optind < argc) { 66 | fin = fopen(argv[optind], "r"); 67 | if (fin == NULL) { 68 | cerr << "Could not open input file " << argv[optind] << endl; 69 | exit(1); 70 | } 71 | 72 | // sm: the 'coolc' compiler's file-handling loop resets 73 | // this counter, so let's make the stand-alone lexer 74 | // do the same thing 75 | curr_lineno = 1; 76 | 77 | // 78 | // Scan and print all tokens. 79 | // 80 | cout << "#name \"" << argv[optind] << "\"" << endl; 81 | while ((token = cool_yylex()) != 0) { 82 | dump_cool_token(cout, curr_lineno, token, cool_yylval); 83 | } 84 | fclose(fin); 85 | optind++; 86 | } 87 | exit(0); 88 | } 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /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 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* 3 | -------------------------------------------------------------------------------- /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 // for getopt 17 | #include "cool-io.h" //includes iostream 18 | #include "cool-tree.h" 19 | #include "utilities.h" // for fatal_error 20 | #include "cool-parse.h" 21 | 22 | // 23 | // These globals keep everything working. 24 | // 25 | FILE *token_file = stdin; // we read from this file 26 | extern Classes parse_results; // list of classes; used for multiple files 27 | extern Program ast_root; // the AST produced by the parse 28 | 29 | char *curr_filename = ""; 30 | 31 | extern int omerrs; // a count of lex and parse errors 32 | 33 | extern int cool_yyparse(); 34 | void handle_flags(int argc, char *argv[]); 35 | 36 | int main(int argc, char *argv[]) { 37 | handle_flags(argc, argv); 38 | cool_yyparse(); 39 | if (omerrs != 0) { 40 | cerr << "Compilation halted due to lex and parse errors\n"; 41 | exit(1); 42 | } 43 | ast_root->dump_with_types(cout,0); 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | -------------------------------------------------------------------------------- /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/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 | char *curr_filename; 10 | 11 | void handle_flags(int argc, char *argv[]); 12 | 13 | int main(int argc, char *argv[]) { 14 | handle_flags(argc,argv); 15 | ast_yyparse(); 16 | ast_root->semant(); 17 | ast_root->dump_with_types(cout,0); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /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 | cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 30 | 31 | // check whether Mary is in any scope; predicate is true 32 | 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 | cout << *(map->lookup(Mary)) << "\n"; 37 | 38 | // check whether Miguel is in the current scope; predicate is true 39 | 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 | cout << *(map->lookup(Mary)) << "\n"; 46 | 47 | // check whether Fred is in the current scope; predicate is now true 48 | cout << ((map->probe(Fred) != NULL) ? "Yes\n" : "No\n"); 49 | 50 | // check whether Miguel is in any scope; predicate is now false 51 | 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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | -------------------------------------------------------------------------------- /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 | char *curr_filename; 16 | 17 | void handle_flags(int argc, char *argv[]); 18 | 19 | int main(int argc, char *argv[]) { 20 | int firstfile_index; 21 | 22 | handle_flags(argc,argv); 23 | firstfile_index = optind; 24 | 25 | if (!out_filename && optind < argc) { // no -o option 26 | char *dot = strrchr(argv[optind], '.'); 27 | if (dot) *dot = '\0'; // strip off file extension 28 | out_filename = new char[strlen(argv[optind])+8]; 29 | strcpy(out_filename, argv[optind]); 30 | strcat(out_filename, ".s"); 31 | } 32 | 33 | // 34 | // Don't touch the output file until we know that earlier phases of the 35 | // compiler have succeeded. 36 | // 37 | ast_yyparse(); 38 | 39 | if (out_filename) { 40 | ofstream s(out_filename); 41 | if (!s) { 42 | cerr << "Cannot open output file " << out_filename << endl; 43 | exit(1); 44 | } 45 | ast_root->cgen(s); 46 | } else { 47 | ast_root->cgen(cout); 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/PA5/mycoolc: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | ./lexer $* | ./parser $* | ./semant $* | ./cgen $* 3 | -------------------------------------------------------------------------------- /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 | /* line number to assign to the current node being constructed */ 19 | int node_lineno = 1; 20 | 21 | /////////////////////////////////////////////////////////////////////////// 22 | // 23 | // tree_node::tree_node 24 | // 25 | // constructor of tree node 26 | // 27 | /////////////////////////////////////////////////////////////////////////// 28 | tree_node::tree_node() 29 | { 30 | line_number = node_lineno; 31 | } 32 | 33 | /////////////////////////////////////////////////////////////////////////// 34 | // 35 | // tree_node::get_line_number 36 | // 37 | /////////////////////////////////////////////////////////////////////////// 38 | int tree_node::get_line_number() 39 | { 40 | return line_number; 41 | } 42 | 43 | // 44 | // Set up common area from existing node 45 | // 46 | tree_node *tree_node::set(tree_node *t) { 47 | line_number = t->line_number; 48 | return this; 49 | } 50 | --------------------------------------------------------------------------------