Program a programming language - lesson 1

From ThorstensHome
Revision as of 10:09, 18 October 2008 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 1

We want to program a language that understands print 2+2:

print     2        +      2
        number operator number
command       expression
     instruction

As a first step, we program a language that understands "print 2":

Here is our lex code:

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]*    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
%%
instruction:
  | command_number
  ;

command_number:
  COMMAND NUMBER
  {
    printf("%i",$2);
  }
  ;
%%

How to compile

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