Program a programming language - lesson 2

From ThorstensHome
Revision as of 12:32, 12 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 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;
%%

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;/*command is %s*/}
  ;

command_expression:
  command expression
  {
    if (strcmp($1,"print")) printf("%i",$2);
  }
  ;

%%

Compile and run it like:

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