From 32ac19d67119d66796fd4946e284119b225fbff2 Mon Sep 17 00:00:00 2001 From: serr Date: Tue, 13 May 2025 14:09:44 +0300 Subject: [PATCH] assignment --- analyzers/test/test.l | 32 +++++++++++++++++++++++--------- analyzers/test/test.y | 32 ++++++++++++++++++++++++++------ tests/test_blocks.txt | 13 ++++--------- 3 files changed, 53 insertions(+), 24 deletions(-) diff --git a/analyzers/test/test.l b/analyzers/test/test.l index 76e5112..78ea550 100644 --- a/analyzers/test/test.l +++ b/analyzers/test/test.l @@ -2,24 +2,38 @@ #include "test.tab.h" #include #include +#include -int CURRENT_LINE_NUMBER = 0; +int CURRENT_LINE_NUMBER = 1; void yyerror(const char *s) { - fprintf(stderr, "\033[91mError at line %i\033[0m", CURRENT_LINE_NUMBER); + fprintf(stderr, "\033[91mError at line %i: %s\033[0m\n", CURRENT_LINE_NUMBER, s); exit(1); } %} %% -"{" { return LBRACE; } -"}" { return RBRACE; } -\n { CURRENT_LINE_NUMBER++; } -[^{}]+ { - yylval.str = strdup(yytext); - return TEXT; - } + +[a-zA-Z_][a-zA-Z0-9_]* { + yylval.str = strdup(yytext); + return IDENTIFIER; +} +[0-9]+ { + yylval.str = strdup(yytext); + return NUMBER; +} +":=" { return ASSIGN; } +"{" { return LBRACE; } +"}" { return RBRACE; } +[ \t]+ ; // Пропускаем пробелы и табы +\n { CURRENT_LINE_NUMBER++; } +. { + fprintf(stderr, "\033[91mUnexpected character at line %i: %c\033[0m\n", + CURRENT_LINE_NUMBER, yytext[0]); + exit(1); +} + %% int yywrap() { diff --git a/analyzers/test/test.y b/analyzers/test/test.y index 186576f..a82f697 100644 --- a/analyzers/test/test.y +++ b/analyzers/test/test.y @@ -9,35 +9,55 @@ extern char *yytext; extern void yyerror(const char *s); extern int yylex(); extern FILE *yyin; + +void free_node(char *str) { + if (str) free(str); +} %} %union { char *str; } -%token TEXT -%token LBRACE RBRACE +%token IDENTIFIER NUMBER TEXT +%token ASSIGN LBRACE RBRACE + +%type expr %% +program: + | program expr + | program block + ; + block: LBRACE content RBRACE ; content: | content TEXT { - printf("TOKEN ('%s')\n", $2); - free($2); } + printf("TEXT: '%s'\n", $2); + free_node($2); } | content block + | content expr ; + +expr: + IDENTIFIER ASSIGN NUMBER { + printf("Assignment: %s := %s\n", $1, $3); + free_node($1); + free_node($3); + } + ; + %% int main(int argc, char **argv) { - if (argc > 1) { FILE *f = fopen(argv[1], "r"); if (!f) { - perror("\033[91mFail open file\033[0m"); + perror("\033[91mFailed to open file\033[0m"); return 1; } yyin = f; diff --git a/tests/test_blocks.txt b/tests/test_blocks.txt index 57acaa9..89d6f21 100644 --- a/tests/test_blocks.txt +++ b/tests/test_blocks.txt @@ -1,13 +1,8 @@ +a := 1 { - { 1 231233 - {1}{} - block1 { - block2 { block3 } - block4 asjdb asd bajds ba - } 126316 - block5 - } + a := 1 { - 123 + + b := 2 } } \ No newline at end of file