diff --git a/labs/04/code_generator.py b/labs/04/code_generator.py new file mode 100644 index 0000000..842c99c --- /dev/null +++ b/labs/04/code_generator.py @@ -0,0 +1,19 @@ +import random + +lines = [ + "// basic code\n", + "//float b\n", + "f b\n", + "// integer a\n", + "i a\n", + "// a = 5\n", + "a = 5\n", + "// b = a + 3.2\n", + "b = a + 3.2\n", + "//print 8.5\n", + "p b\n" +] + +with open("example.ac", "w") as f: + for line in lines: + f.write(line) diff --git a/labs/04/example.ac b/labs/04/example.ac new file mode 100644 index 0000000..b8d4eab --- /dev/null +++ b/labs/04/example.ac @@ -0,0 +1,11 @@ +// basic code +//float b +f b +// integer a +i a +// a = 5 +a = 5 +// b = a + 3.2 +b = a + 3.2 +//print 8.5 +p b diff --git a/labs/04/lex_analyzer.l b/labs/04/lex_analyzer.l new file mode 100644 index 0000000..c93cee7 --- /dev/null +++ b/labs/04/lex_analyzer.l @@ -0,0 +1,42 @@ +%{ +#include +%} + + // Token definitions +%% +"//"[^\n]* { printf("COMMENT\n"); } // Match comments +"f" { printf("floatdcl \n"); } // Match float declarations +"i" { printf("intdcl \n"); } // Match integer declarations +"p" { printf("print \n"); } // Match print commands +[a-zA-Z][a-zA-Z0-9]* { printf("id "); } // Match identifiers (no newline here) +"=" { printf("assign "); } // Match assignment operator (no newline) +[0-9]+ { printf("inum\n"); } // Match integers +[0-9]+\.[0-9]+ { printf("fnum\n"); } // Match floating-point numbers +\+ { printf("plus "); } // Match the plus operator (no newline) +[ \t]+ { /* Ignore spaces and tabs */ } // Ignore spaces and tabs explicitly +\n { /* Ignore standalone newlines */ } +. { printf("Unrecognized token: %s\n", yytext); } // Handle unrecognized tokens + +%% + +int main(int argc, char **argv) { + if (argc != 2) { + printf("Usage: %s \n", argv[0]); + return 1; + } + + FILE *file = fopen(argv[1], "r"); + if (!file) { + perror("Error opening file"); + return 1; + } + + yyin = file; + yylex(); + fclose(file); + return 0; +} + +int yywrap() { + return 1; +} diff --git a/labs/04/makefile b/labs/04/makefile new file mode 100644 index 0000000..9f43ee1 --- /dev/null +++ b/labs/04/makefile @@ -0,0 +1,12 @@ +LEX = flex +CC = gcc +OUTPUT = lex_analyzer + +all: $(OUTPUT) + +$(OUTPUT): lex_analyzer.l + $(LEX) lex_analyzer.l + $(CC) lex.yy.c -o $(OUTPUT) + +clean: + rm -f lex.yy.c $(OUTPUT)