Add solutions to the homework

This commit is contained in:
Danila Fedorin 2019-04-06 20:58:03 -07:00
parent 357d56bc96
commit 5c7f1879bf
2 changed files with 82 additions and 0 deletions

73
python.flx Normal file
View File

@ -0,0 +1,73 @@
%option noyywrap
%{
#define PRINTJ(format, str, v) printf("%s\t" format "\n", str, v)
#define PRINT(format, str, v) { int i; printf(str); i = 1 + (16 - strlen(str)) / 8; while(i--) putc('\t', yyout); printf(format "\n", v); }
#define PRINTD(name) PRINT("%s", name, yytext)
int indent_stack[128];
int indent_sp = 0;
void handle_indent(int l) {
while(l != indent_stack[indent_sp]) {
if(l > indent_stack[indent_sp]) {
indent_stack[++indent_sp] = l;
printf("INDENT\n");
} else {
indent_sp--;
printf("DEDENT\n");
}
}
}
%}
%%
^(#[^\n]*)?\n[^ ] { handle_indent(0); unput(yytext[yyleng-1]); }
^(#[^\n]*)?\n {}
\n[^ ] { printf("NEWLINE\n"); handle_indent(0); unput(yytext[1]); }
\n printf("NEWLINE\n");
<<EOF>> { handle_indent(0); return 0; }
^[ ]* handle_indent(yyleng);
[ ]* {}
-?[0-9]+\.[0-9]* PRINT("%.6g", "FLOAT", atof(yytext));
[0-9]+ PRINTD("INTEGER");
True|False PRINT("%d", "BOOLEAN", yytext[0] == 'T');
and PRINTD("AND");
break PRINTD("BREAK");
def PRINTD("DEF");
elif PRINTD("ELIF");
else PRINTD("ELSE");
for PRINTD("FOR");
if PRINTD("IF");
not PRINTD("NOT");
or PRINTD("OR");
return PRINTD("RETURN");
while PRINTD("WHILE");
[a-zA-Z_][a-zA-Z_0-9]* PRINTD("IDENTIFIER");
"=" PRINTD("ASSIGN");
"+" PRINTD("PLUS");
"-" PRINTD("MINUS");
"*" PRINTD("TIMES");
"/" PRINTD("DIVIDEDBY");
"==" PRINTD("EQ");
"!=" PRINTD("NEQ");
">" PRINTD("GT");
">=" PRINTD("GTE");
"<" PRINTD("LT");
"<=" PRINTD("LTE");
"(" PRINTD("LPAREN");
")" PRINTD("RPAREN");
"," PRINTD("COMMA");
":" PRINTD("COLON");
%%
int main() {
indent_stack[0] = 0;
yylex();
}

9
test.sh Executable file
View File

@ -0,0 +1,9 @@
flex python.flx && gcc lex.yy.c
mkdir -p real_output
mkdir -p diff_results
for file in $(ls testing_code); do
name=$(echo $file | awk -F'[.]' '{print $1}')
./a.out < testing_code/$file > real_output/$name.out
diff example_output/$name.out real_output/$name.out > diff_results/$name.diff
done