Program a programming language - lesson 5
From ThorstensHome
You are here: Main Page -> My Tutorials -> Programming Tutorials -> How to program your own programming language -> Lesson 5
In this lesson, we will teach our programming language to understand one variable, e.g.
print 3; print 2+2; dump; a:=5; dump
example.lex
%{ #include <stdio.h> #include "y.tab.h" extern YYSTYPE yylval; %} %% [0123456789]+ yylval=atoi(yytext); return NUMBER; [a-zA-Z][a-zA-Z0-9]* yylval=yytext; return COMMAND; [\+\-\*\/] return OPERATOR; ; return SEMICOLON; := return ASSIGNMENT; [ \t]+ /* ignore whitespace */; %%
example.y
%{ #include <stdio.h> #include <string.h> #include "prog.h" void yyerror(const char *str) { fprintf(stderr,"error: %s\n",str); } int yywrap() { return 1; } main() { yyparse(); } %} %token NUMBER OPERATOR COMMAND SEMICOLON ASSIGNMENT %left OPERATOR %left COMMAND %% instructions: | instruction SEMICOLON instructions ; instruction: command_expression | command ASSIGNMENT NUMBER {i=$3;} | command ; expression: NUMBER {$$=$1;} | NUMBER OPERATOR NUMBER { $$=$1+$3; } ; command: COMMAND {$$=$1; if (!strcmp((char*) $1,"print")) { $$="print"; } if (!strcmp((char*) $1,"wait")) { $$="wait"; } if (!strcmp((char*) $1,"dump")) { printf("\nPrinting all my variables:%i\n",i); } } ; command_expression: command expression { if (!strcmp((char*) $1,"print")) printf("%i",$2); if (!strcmp((char*) $1,"wait")) { sleep $2*1000000; printf("waited"); } } ; %%
prog.h
static int i=0;
How to compile and run
lex example.lex && yacc -d example.y && cc lex.yy.c y.tab.c -o example && ./example