#include <stdio.h>
#include <string.h>
const char *s;
char a[4096], t;
char compile(int pri)
{
char r, q, op;
if (*s == '(') {
s++; r = compile(99); s++; // ')'を読み飛ばす.
} else {
r = *s++; // 数値もしくは変数.
}
for (;;) {
op = *s++;
if (pri >= 4 && (op == '*' || op == '/' || op == '%')) {
q = compile(3); sprintf(a + strlen(a), "%c %c,%c,%c\n", op, t, r, q); r = t++;
} else if (pri >= 5 && (op == '+' || op == '-')) {
q = compile(4); sprintf(a + strlen(a), "%c %c,%c,%c\n", op, t, r, q); r = t++;
} else
break;
}
s--; return r;
}
int main(int argc, const char **argv)
{
s = argv[1]; if (s == NULL) return 1;
t = 't'; char r = compile(99); printf("%sresult=%c\n", a, r);
return 0;
}>reg 1+2*3 * t,2,3 → MUL(t, 2, 3); // t=2*3; + u,1,t → ADD(u, 1, t); // u=1+t; result=u → 計算結果はuに入っています、という意味です。 tとかuは一時変数です。 >reg (1+2)*3 + t,1,2 * u,t,3 result=u >reg (X+Y-1)*(A+B) + t,X,Y - u,t,1 + v,A,B * w,u,v result=w
#include <stdio.h>
#include <string.h>
const char *s;
char a[4096];
void compile(int pri)
{
char op;
if (*s == '(') {
s++; compile(99); s++; // ')'を読み飛ばす.
} else {
sprintf(a + strlen(a), "push %c\n", *s++); // 数値もしくは変数.
}
for (;;) {
op = *s++;
if (pri >= 4 && (op == '*' || op == '/' || op == '%')) {
compile(3); sprintf(a + strlen(a), "%c\n", op);
} else if (pri >= 5 && (op == '+' || op == '-')) {
compile(4); sprintf(a + strlen(a), "%c\n", op);
} else
break;
}
s--;
}
int main(int argc, const char **argv)
{
s = argv[1]; if (s == NULL) return 1;
compile(99); printf("%s", a);
return 0;
}>stk 1+2*3 push 1 push 2 push 3 * + >stk (1+2)*3 push 1 push 2 + push 3 * >stk (X+Y-1)*(A+B) push X push Y + push 1 - push A push B + *
#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv)
{
const char *s = argv[1]; if (s == NULL) return 1;
char t = 't', a[4096], *p = &a[4096], c; a[0] = 0;
while ((c = *s++) != '\0') {
if (strchr("*/%+-", c) != 0) {
sprintf(a + strlen(a), "%c %c,%c,%c\n", c, t, p[1], p[0]); *++p = t++;
} else {
*--p = c;
}
}
printf("%sresult=%c\n", a, *p);
return 0;
}
>cnv 123*+
* t,2,3
+ u,1,t
result=u
>cnv 12+3*
+ t,1,2
* u,t,3
result=u
>cnv XY+1-AB+*
+ t,X,Y
- u,t,1
+ v,A,B
* w,u,v
result=w