staticboolmake_token(char *e) { int position = 0; int i; int index=0; regmatch_t pmatch; nr_token = 0; while (e[position] != '\0') { /* Try all rules one by one. */ for (i = 0; i < NR_REGEX; i ++) { if (regexec(&re[i], e + position, 1, &pmatch, 0) == 0 && pmatch.rm_so == 0) { char *substr_start = e + position; int substr_len = pmatch.rm_eo; Log("match rules[%d] = \"%s\" at position %d with len %d: %.*s", i, rules[i].regex, position, substr_len, substr_len, substr_start); position += substr_len; /* TODO: Now a new token is recognized with rules[i]. Add codes * to record the token in the array `tokens'. For certain types * of tokens, some extra actions should be performed. */ switch (rules[i].token_type) { case TK_NUM: tokens[index].type = rules[i].token_type; for(int j=0;j<substr_len;j++) tokens[index].str[j] = substr_start[j]; // printf("The num is %s\n",tokens[index].str); break; default: tokens[index].type = rules[i].token_type; } index++; break; } } if (i == NR_REGEX) { printf("no match at position %d\n%s\n%*.s^\n", position, e, position, ""); returnfalse; } } returntrue; }
eval(p, q) { if (p > q) { /* Bad expression */ } elseif (p == q) { /* Single token. * For now this token should be a number. * Return the value of the number. */ } elseif (check_parentheses(p, q) == true) { /* The expression is surrounded by a matched pair of parentheses. * If that is the case, just throw away the parentheses. */ return eval(p + 1, q - 1); } else { /* We should do more things here. */ } }
eval(p, q) { if (p > q) { /* Bad expression */ } elseif (p == q) { /* Single token. * For now this token should be a number. * Return the value of the number. */ } elseif (check_parentheses(p, q) == true) { /* The expression is surrounded by a matched pair of parentheses. * If that is the case, just throw away the parentheses. */ return eval(p + 1, q - 1); } else { op = the position of 主运算符 in the token expression; val1 = eval(p, op - 1); val2 = eval(op + 1, q);