added yacc and lex example to ast-lex-yacc

This commit is contained in:
Sven Vogel 2023-11-22 12:58:21 +01:00
parent 326d148d9f
commit 7c3ddc3b80
5 changed files with 91 additions and 21 deletions

View File

@ -1,21 +0,0 @@
BUILDDIR = build
TARGET_SRC = main
build: mkdir main
all: mkdir main run
mkdir: # create build directory
mkdir -p $(BUILDDIR)
run: # run binary
./$(BUILDDIR)/main
main: lex.yy.c # compile c file
cc $(BUILDDIR)/lex.yy.c -o $(BUILDDIR)/$(TARGET_SRC) -lfl
lex.yy.c: main.lex # generate c file
flex -o $(BUILDDIR)/lex.yy.c $(TARGET_SRC).lex
clean: # wipe the build directory
rm -f $(BUILDDIR)/*

26
ast-lex-yacc/Makefile Normal file
View File

@ -0,0 +1,26 @@
BUILDDIR = build
TARGET_SRC = main
build: mkdir main
all: mkdir main run
mkdir: # create build directory
mkdir -p $(BUILDDIR)
run: # run binary
./$(BUILDDIR)/main
main: lex.yy.c yacc.yy.c
cc $(BUILDDIR)/yacc.yy.c $(BUILDDIR)/lex.yy.c -o $(BUILDDIR)/$(TARGET_SRC) -lfl
# generate c file for lex
lex.yy.c:
flex -o $(BUILDDIR)/lex.yy.c $(TARGET_SRC).l
# generate c file for yacc
yacc.yy.c:
yacc -d -o $(BUILDDIR)/yacc.yy.c $(TARGET_SRC).y
clean: # wipe the build directory
rm -f $(BUILDDIR)/*

37
ast-lex-yacc/main.l Normal file
View File

@ -0,0 +1,37 @@
%option noyywrap
%{
#include <stdio.h>
#include "yacc.yy.h"
#define YYDEBUG 1
int yyLineNumber = 1;
%}
%%
\n yyLineNumber++;
0|[1-9][0-9]* return(Number); // integer numbers
"VAR"|"var" return(Variable);
"INT"|"int" return(Integer);
[a-zA-Z]+ return(Ident);
"," return(',');
":" return(':');
";" return(';');
"+" return('+');
"-" return('-');
"(" return('(');
")" return(')');
[ \t]
. print_stdout("unknown Symbol");
%%
/*
int main()
{
printf("Programm eingeben: \n");
yylex();
return 0;
}
*/
int print_stdout(char token[]) {
printf("\nFLEX/[INF] >>> Token (%d) AS %s ```%s```\n", yyLineNumber, token, yytext);
}

28
ast-lex-yacc/main.y Normal file
View File

@ -0,0 +1,28 @@
%{
#include <stdio.h>
extern int yylineno;
%}
%token Variable
%token Integer
%token Ident
%token Number
%%
program: decllist exprlist;
decllist: decl ';' | decllist decl ';' | /* empty */ | error ';' { yyerror(" im Deklarationsteil\n"); };
decl: Variable idlist ':' type;
idlist: Ident | idlist ',' Ident;
type: Integer;
exprlist: /* empty */ ;
%%
int main() {
printf("Bitte geben Sie ein Program ein: \n");
yyparse();
return 0;
}
int yyerror(char *s) {
printf("YACC/[ERR] >>> Failed parsing grammar (%d): ```%s```", yylineno, s);
}

View File