ref: ca11c7774accc8688b3614e5ec367a802ae7643d
parent: fd1b69bdb18359773bf43ebea4fbe693c72aa542
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Mon Mar 31 07:05:30 EDT 2014
Add castcode function This function simplify the generation of casts
--- a/cc.h
+++ b/cc.h
@@ -204,6 +204,7 @@
Type *type;
union unode {
Symbol *sym;
+ Type *type;
char op;
} u;
struct node *childs[];
@@ -222,9 +223,11 @@
extern Node
*node(Inst code, Type *tp, union unode u, uint8_t nchilds),
*unarycode(char op, Type *tp, Node *child),
- *bincode(char op, Type *tp, Node *np1, Node *np2);
+ *bincode(char op, Type *tp, Node *np1, Node *np2),
+ *castcode(Node *child, Type *tp);
#define SYM(s) ((union unode) {.sym = s})
#define OP(s) ((union unode) {.op = s})
+#define TYP(s) ((union unode) {.type = s})
#endif
--- a/code.c
+++ b/code.c
@@ -22,23 +22,6 @@
return np;
}
-Node *
-unarycode(char op, Type *tp, Node *child)
-{
- Node *np = node(emitunary, tp, OP(op), 1);
- np->childs[0] = child;
- return np;
-}
-
-Node *
-bincode(char op, Type *tp, Node *np1, Node *np2)
-{
- Node *np = node(emitbin, tp, OP(op), 2);
- np->childs[0] = np1;
- np->childs[1] = np2;
- return np;
-}
-
void
emitsym(Node *np)
{
@@ -57,6 +40,15 @@
}
void
+emitcast(Node *np)
+{
+ Node *child = np->childs[0];
+
+ (*child->code)(child);
+ printf("\t%c%c", np->u.type->letter, np->type->letter);
+}
+
+void
emitunary(Node *np)
{
Node *child;
@@ -65,17 +57,7 @@
letter = np->type->letter;
child = np->childs[0];
(*child->code)(child);
- switch (op = np->u.op) {
- case OCAST:
- printf("\t%c%c", child->type->letter, letter);
- break;
- case OARY:
- fputs("\t'", stdout);
- break;
- default:
- printf("\t%s%c", opcodes[op], letter);
- break;
- }
+ printf("\t%s%c", opcodes[np->u.op], letter);
}
void
@@ -113,4 +95,30 @@
emitret(Symbol *sym)
{
puts("}");
+}
+
+Node *
+castcode(Node *child, Type *tp)
+{
+ Node *np = node(emitcast, tp, TYP(child->type), 1);
+
+ np->childs[0] = child;
+ return np;
+}
+
+Node *
+unarycode(char op, Type *tp, Node *child)
+{
+ Node *np = node(emitunary, tp, OP(op), 1);
+ np->childs[0] = child;
+ return np;
+}
+
+Node *
+bincode(char op, Type *tp, Node *np1, Node *np2)
+{
+ Node *np = node(emitbin, tp, OP(op), 2);
+ np->childs[0] = np1;
+ np->childs[1] = np2;
+ return np;
}
--- a/expr.c
+++ b/expr.c
@@ -80,7 +80,7 @@
floatconv(&np1, &np2);
break;
case INT:
-int_float: np2 = unarycode(OCAST, np1->type, np2);
+int_float: np2 = castcode(np2, np1->type);
break;
default:
goto incorrect;
@@ -91,7 +91,7 @@
tp1 = mktype(tp1->type, PTR, NULL, 0);
if (t2 != INT)
goto incorrect;
- np2 = unarycode(OCAST, tp1, np2);
+ np2 = castcode(np2, tp1);
break;
default:
goto incorrect;
--
⑨