Program a programming language - lesson 4

From ThorstensHome
Jump to: navigation, search

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


In this lesson, we will teach our programming language to understand several instructions in one program, e.g.

print 2+2; wait 2+2

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;
[ \t]+                  /* ignore whitespace */;
%%

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 SEMICOLON
%left  OPERATOR
%%
instructions:
  | instruction SEMICOLON instructions

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");
    }
  }
  ;

%%

How to compile

To compile and run, type

lex example.lex && yacc -d example.y && cc lex.yy.c y.tab.c -o example && ./example