Program a programming language - lesson 3

From ThorstensHome
Jump to: navigation, search

You are here: Main Page -> My Tutorials -> Programming Tutorials -> How to program your own programming language -> Lesson 3


Our programming language in the third lesson can already understand

print 2+2

or

wait 2+2

a program can only consist of one instruction. The parameter of wait is how many seconds the system will wait ("sleep").

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;
%%

example.y

%{
#include <stdio.h>
#include <string.h>
void yyerror(const char *str)
{
        fprintf(stderr,"error: %s\n",str);
}

int yywrap()
{
        return 1;
}

main()
{
        yyparse();
}

%}

%token NUMBER OPERATOR COMMAND
%left  OPERATOR
%%
instruction:
  | command_expression
  ;


expression:
  NUMBER {$$=$1;}
  | NUMBER OPERATOR NUMBER
  {
    $$=$1+$3;
  }
  ;

command:
  COMMAND {$$=$1;
           if (!strcmp((char*) $1,"print"))
           {
             $$="print";
           }
           if (!strcmp((char*) $1,"wait"))
           {
             $$="wait";
           }
          }
  ;

command_expression:
  command expression
  {
    if (!strcmp((char*) $1,"print")) printf("%i",$2);
    if (!strcmp((char*) $1,"wait"))
    {
      sleep $2*1000000; printf("waited");
    }
  }
  ;

%%

compile and run it

lex example.lex && yacc -d example.y && cc lex.yy.c y.tab.c -o example && ./example
...
print 2+2
 4