Advertisement
cd62131

Recursive descent parser for paren

Nov 1st, 2013
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include "paren_recur.h"
  2.  
  3. bool paren(void) {
  4.   int c;
  5.   for (c = getchar(); c != EOF; c = getchar()) {
  6.     if ((unsigned char) c == '(') {
  7.       if (paren()) continue;
  8.       printf(") not appear\n");
  9.       return false;
  10.     }
  11.     if ((unsigned char) c == '{') {
  12.       if (brace()) continue;
  13.       printf("} not appear\n");
  14.       return false;
  15.     }
  16.     if ((unsigned char) c == ')') return true;
  17.     if ((unsigned char) c == '}') {
  18.       printf("(} mismatch\n");
  19.       return false;
  20.     }
  21.   }
  22.   return false;
  23. }
  24.  
  25. bool brace(void) {
  26.   int c;
  27.   for (c = getchar(); c != EOF; c = getchar()) {
  28.     if ((unsigned char) c == '(') {
  29.       if (paren()) continue;
  30.       printf(") not appear\n");
  31.       return false;
  32.     }
  33.     if ((unsigned char) c == '{') {
  34.       if (brace()) continue;
  35.       printf("} not appear\n");
  36.       return false;
  37.     }
  38.     if ((unsigned char) c == ')') {
  39.       printf("{) mismatch\n");
  40.       return false;
  41.     }
  42.     if ((unsigned char) c == '}') return true;
  43.  
  44.   }
  45.   return false;
  46. }
  47.  
  48. int main(int ac, char **av) {
  49.   int c;
  50.   for (c = getchar(); c != EOF; c = getchar()) {
  51.     if ((unsigned char) c == '(') {
  52.       if (paren()) continue;
  53.       printf("() unmatch\n");
  54.       return EXIT_FAILURE;
  55.     }
  56.     if ((unsigned char) c == '{') {
  57.       if (brace()) continue;
  58.       printf("{} unmatch\n");
  59.       return EXIT_FAILURE;
  60.     }
  61.   }
  62.   printf("(){} match\n");
  63.   return EXIT_SUCCESS;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement