極小的運算式剖析器

執行方法

D:\ccc\sp>gcc eparse.c -o eparse

D:\ccc\sp>eparse 3+4*5
=== EBNF Grammar =====
E=T ([+-] T)*
T=F ([*/] F)*
F=N | '(' E ')'
==== parse:3+4*5 ========
E
 T
  F
   3
 +
 T
  F
   4
  *
  F
   5

請按任意鍵繼續 . . .

D:\ccc\sp>eparse 3+(4+5*6)
=== EBNF Grammar =====
E=T ([+-] T)*
T=F ([*/] F)*
F=N | '(' E ')'
==== parse:3+(4+5*6) ========
E
 T
  F
   3
 +
 T
  F
(
E
 T
  F
   4
 +
 T
  F
   5
  *
  F
   6
)
請按任意鍵繼續 . . .

語法規則

E = T ([+-] T)*
T = F ([*/] F)*
F = N | '(' E ')'
N = [0-9]

剖析程式

#include <stdio.h>
#include <assert.h>

int main(int argc, char * argv[]) {
    printf("=== EBNF Grammar =====\n");
    printf("E=T ([+-] T)*\n");
    printf("T=F ([*/] F)*\n");
    printf("F=N | '(' E ')'\n");
    printf("==== parse:%s ========\n", argv[1]);
    parse(argv[1]);
    printf("\n");
    system("pause");
}

int si = 0;
char *tokens;

char ch() {
  char c = tokens[si];
  return c;
}

int next() {
  si++;
}

int isNext(char *set) {
  return (ch()!='\0' && strchr(set, ch())!=NULL);
}

int parse(char *str) {
     tokens = str;
     E();
}

int E() {
    printf("E\n");
    T();
    while (isNext("+-")) {
          printf(" %c\n", ch());
          next();
          T();
    }
}

int T() {
    printf(" T\n");
    F();
    while (isNext("*/")) {
          printf("  %c\n", ch());
          next();
          F();
    }
}

int F() {
    printf("  F\n");
    if (ch()=='(') {
      printf("(\n");
      next();
      E();
      assert(ch()==')');
      printf(")\n");
      next();
    } else {
      printf("   %c\n", ch());
      assert(ch()>='0' && ch()<='9');
      next();
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License