scanner.l
main.c
%{
#include <stdio.h>
#include <stdlib.h>
#define YYSTYPE double
#include "parser.h"
%}
%option noyywrap
digit [0-9]
space [\t\n ]
number {digit}+(\.{digit}*)?|\.{digit}+
abs (?i:abs)
exp (?i:exp)
log (?i:log)
mod (?i:mod)
pow (?i:pow)
%%
{number} {
yylval = strtod(yytext, NULL);
return NUMBER;
}
{abs} {
return ABS;
}
{exp} {
return EXP;
}
{log} {
return LOG;
}
{mod} {
return MOD;
}
{pow} {
return POW;
}
{space}+
= {
return 0;
}
. {
return *yytext;
}
%%
parser.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define YYSTYPE double
%}
%token NUMBER
%token ABS
%token EXP
%token LOG
%token MOD
%token POW
%%
result: expression {
printf("%lf\n", $1);
}
expression: term {
$$ = $1;
}
expression: expression '+' term {
$$ = $1 + $3;
}
expression: expression '-' term {
$$ = $1 - $3;
}
term: factor {
$$ = $1;
}
term: term '*' factor {
$$ = $1 * $3;
}
term: term '/' factor {
$$ = $1 / $3;
}
factor: '+' factor {
$$ = $2;
}
factor: '-' factor {
$$ = -$2;
}
factor: NUMBER {
$$ = $1;
}
factor: '(' expression ')' {
$$ = $2;
}
factor: ABS '(' expression ')' {
$$ = fabs($3);
}
factor: EXP '(' expression ')' {
$$ = exp($3);
}
factor: LOG '(' expression ')' {
$$ = log($3);
}
factor: MOD '(' expression ',' expression ')' {
$$ = fmod($3, $5);
}
factor: POW '(' expression ',' expression ')' {
$$ = pow($3, $5);
}
%%
main.c
#include <stdio.h>
int yyparse(void);
void yyerror(const char *msg);
int main(void) {
return yyparse();
}
void yyerror(const char *msg) {
fprintf(stderr, "%s\n", msg);
}