Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions labs/04/code_generator.py
Original file line number Diff line number Diff line change
@@ -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)
11 changes: 11 additions & 0 deletions labs/04/example.ac
Original file line number Diff line number Diff line change
@@ -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
42 changes: 42 additions & 0 deletions labs/04/lex_analyzer.l
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
%{
#include <stdio.h>
%}

// 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 <input_file>\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;
}
12 changes: 12 additions & 0 deletions labs/04/makefile
Original file line number Diff line number Diff line change
@@ -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)