home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
CataniaB
/
teach-act
/
laboratorio
/
lab-26-4-99
/
parser+getsym.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-05-25
|
2KB
|
136 lines
#include <stdio.h>
#include <stdlib.h>
#define NOFSYM 8
typedef enum{NOTREC = -2,PLUS = 0, MINUS, TIMES, DIV, MOD, EQUAL,
LPAR, RPAR, NUMBER} symkind;
typedef struct {symkind kind; int value;} symbol;
const char tab[NOFSYM] = {'+','-','*','/','%','=','(',')'};
void parse(void);
void parseE(void);
void parseT(void);
void parseF(void);
symbol getsym();
static symbol sym;
int main()
{
parse();
}
void parse(void)
{
sym = getsym();
parseE();
if (sym.kind == EQUAL)
{
printf("\n Successful parsing \n");
exit(EXIT_SUCCESS);
}
else
{
printf("\n Error: expecting equal symbol \n");
exit(EXIT_FAILURE);
}
}
void parseE(void)
{
parseT();
if (sym.kind == PLUS || sym.kind == MINUS)
{
sym = getsym();
parseE();
}
}
void parseT(void)
{
parseF();
if (sym.kind == TIMES || sym.kind == DIV)
{
sym = getsym();
parseT();
}
}
void parseF(void)
{
switch(sym.kind)
{
case LPAR:
sym = getsym();
parseE();
if (sym.kind != RPAR)
{
printf("\n Error: expecting right parenthesis \n");
exit(EXIT_FAILURE);
}
sym = getsym();
break;
case MINUS:
sym = getsym();
parseF();
break;
case NUMBER:
sym = getsym();
break;
default:
printf("\n Error: expecting left parenthesis or minus symbol or a number \n");
exit(EXIT_FAILURE);
break;
}
}
symbol getsym()
{
symbol s;
static char c = ' ';
s.kind = NOTREC; /* pessimistic view! */
while (c != EOF && (c == ' ' || c == '\n' || c == '\t') )
c = getchar(); /* skip blank, new line and tabbing */
if (c == EOF) /* unexpected end of input */
{
printf("\n Error: unexpected end of file \n");
exit(EXIT_FAILURE);
}
if (c >= '0' && c <= '9') /* number */
{
s.kind = NUMBER;
s.value = 0;
do
s.value = s.value * 10 + c - '0';
while ((c = getchar()) != EOF && c >= '0' && c <= '9');
}
else /* operation or unrecognized symbol */
{
symKind i;
for (i = PLUS; i <= RPAR; i++)
if (tab[i] == c)
s.kind = i;
if (s.kind == NOTREC)
{
printf("\n Error: unrecognized character: %c \n",c);
exit(EXIT_FAILURE);
}
c = getchar(); /* input synchronization */
}
return s;
}