Assignment-1/python.flx

74 lines
2.1 KiB
Plaintext

%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");
}
}
}
%}
%%
^[^ ] { handle_indent(0); REJECT }
^(#[^\n]*)?\n {}
\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();
}