Search This Blog

Tuesday, 24 September 2024

Implementing a Parser in C

0 comments

 IMPLEMENTING A RECURSIVE DESCENT PARSER

AIM:

            To implement a Recursive Descent Parser in C that can analyze and evaluate an expression consisting of simple arithmetic operations.

 

ALGORITHM:

1.      Get the input expression from the user

2.      Declare and implement the functions exp(), term() and factor() for analyzing the structure of the given expression.

3.      Call the functions from appropriate places. For instance, the function exp() is called from main() and the function term() is called from exp().

4.      Then write the code for implementing the operations ‘+’ and ‘-’ and print the result.

5.      Implement and call the function error() when an error is found in the syntactical structure of the given expression.

 

PROGRAM:

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>


char token;


int expr(void);

int term(void);

int factor(void);


void error(void)

{

fprintf(stderr, "Error\n");

exit(1);

}


void match(char expectedToken)

{

if(token == expectedToken)

token = getchar();

else

error();

}


int main()

{

int result;

token = getchar();


result = expr();

if (token == '\n')

printf("Result = %d\n", result);

else

error();

return 0;

}


int expr(void)

{

int temp = term();

while ((token == '+') || (token == '-'))

switch (token)

{

case '+':

match('+');

temp += term();

break;

case '-':

match('-');

temp -= term();

break;

}

return temp;

}


int term(void)

{

int temp = factor();

while (token == '*')

{

match('*');

temp *= factor();

}

return temp;

}


int factor(void)

{

int temp;

if (token == '(')

{

match('(');

temp = expr();

match(')');

}

else if (isdigit(token))

{

ungetc(token, stdin);

scanf("%d", &temp);

token = getchar();

}

else error();

return temp;

}



Sample Output:



Leave a Reply