shithub: scc

Download patch

ref: 4c7497f6177a9bfef0a5630634ab8ad948048a08
parent: 500e09ac440d0b91c980fe44ffeb8e799a6e49d8
author: Roberto E. Vargas Caballero <[email protected]>
date: Mon Apr 14 07:17:46 EDT 2014

Add sizeof operator

This operator returns the size of a type or an expression.

--- a/cc.h
+++ b/cc.h
@@ -112,6 +112,8 @@
 
 extern void context(void (*fun)(void));
 
+extern Type *typename(void);
+
 extern Type *voidtype,
 	*uchartype,   *chartype,
 	*uinttype,    *inttype,
--- a/expr.c
+++ b/expr.c
@@ -300,6 +300,7 @@
 		next();
 		np = expr();
 		expect(')');
+	case ';':
 		break;
 	default:
 		error("unexpected '%s'", yytext);
@@ -335,8 +336,27 @@
 unary(void)
 {
 	register Node *np;
+	Type *tp;
+	char paren;
 
 	switch (yytoken) {
+	case SIZEOF:
+		next();
+		if (accept('('))
+			paren = 1;
+		switch (yytoken) {
+		case TQUALIFIER: case TYPE:
+			tp = typename();
+			break;
+		default:
+			tp = expr()->type;
+			/* TODO: Free memory */
+			break;
+		}
+		if (paren)
+			expect(')');
+		np = sizeofcode(tp);
+		break;
 	case INC: case DEC:
 		np = incdec(unary(), (yytoken == INC) ? OINC : ODEC);
 		next();
@@ -351,7 +371,6 @@
 {
 	Type *tp;
 	register Node *np1, *np2;
-	extern Type *typename(void);
 
 	if (yytoken == '(') {
 		switch(ahead()) {