Program a programming language - lesson 6

From ThorstensHome
Revision as of 11:05, 14 August 2007 by WikiSysop (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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


In this lesson, we will teach our programming language to understand expressions with a variable, e.g.:

a:=3; print 1+a+1;

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 WORD;
[\+\-\*\/]              return OPERATOR;
;                       return SEMICOLON;
:=                      return ASSIGNMENT;
[ \t]+                  /* ignore whitespace */;
%%

example.y

%{
#include <stdio.h>
#include <string.h>

static int i=0;

void yyerror(const char *str)
{
        fprintf(stderr,"error: %s\n",str);
}

int yywrap()
{
        return 1;
}

main()
{
        yyparse();
}

%}

%token NUMBER OPERATOR WORD SEMICOLON ASSIGNMENT
%left  OPERATOR
%left  WORD
%%
instructions:
  | instruction SEMICOLON instructions
  ;

instruction:
  command_expression
  | command ASSIGNMENT NUMBER {i=$3;}
  | command
  ;


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

command:
  WORD {$$=$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");
    }
  }
  ;

%%

How to compile and run

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