assignment
parent
cb3527a247
commit
32ac19d671
|
@ -2,24 +2,38 @@
|
|||
#include "test.tab.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
%}
|
||||
|
||||
%%
|
||||
|
||||
[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++; }
|
||||
[^{}]+ {
|
||||
yylval.str = strdup(yytext);
|
||||
return TEXT;
|
||||
. {
|
||||
fprintf(stderr, "\033[91mUnexpected character at line %i: %c\033[0m\n",
|
||||
CURRENT_LINE_NUMBER, yytext[0]);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
%%
|
||||
|
||||
int yywrap() {
|
||||
|
|
|
@ -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 <str> TEXT
|
||||
%token LBRACE RBRACE
|
||||
%token <str> IDENTIFIER NUMBER TEXT
|
||||
%token ASSIGN LBRACE RBRACE
|
||||
|
||||
%type <str> 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;
|
||||
|
|
|
@ -1,13 +1,8 @@
|
|||
a := 1
|
||||
{
|
||||
{ 1 231233
|
||||
{1}{}
|
||||
block1 {
|
||||
block2 { block3 }
|
||||
block4 asjdb asd bajds ba
|
||||
} 126316
|
||||
block5
|
||||
}
|
||||
a := 1
|
||||
{
|
||||
123
|
||||
|
||||
b := 2
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue