自己动手写C语言编译器(5)

2014-11-23 22:37:13 · 作者: · 浏览: 5

C代码

%{

#define YYSTYPE double

#include

int yylex (void);

void yyerror (char const *);

%}

%token NUM

%%

input:

|input line

;

line: '\n'

| exp '\n' {printf("\t%.10g\n", $1);}

;

exp: NUM { $$ = $1; }

| exp exp '+' { $$ = $1 + $2; }

| exp exp '-' { $$ = $1 - $2; }

| exp exp '*' { $$ = $1 * $2; }

| exp exp '/' { $$ = $1 / $2; }

/* Unary minus */

| exp 'n' { $$ = -$1; }

;

%%

#include

int yylex (void)

{

int c;

/* Skip white space. */

while ((c = getchar ()) == ' ' || c == '\t')

;

/* Process numbers. */

if (c == '.' || isdigit (c))

{

ungetc (c, stdin);

scanf ("%lf", &yylval);

return NUM;

}

/* Return end-of-input. */

if (c == EOF)

return 0;

/* Return a single char. */

return c;

}

void yyerror (char const * error)

{

}

int main()

{

return yyparse ();

}

在Ubuntu的linux下安装Bison2.5,运行:

bison first.y

gcc -o first first.tab.c

运行

./fisrt

1 4 +

5

3 10 *

30

OK。