Below is one “toy‐compiler” written completely in a single C source file. This compiler
- Performs lexical analysis, scanning an embedded (hard‐coded) “C–subset” source program and reporting errors.
- Parses a limited grammar (allowing assignment statements, if, while, do…while, and for) using a recursive–descent parser.
- Generates intermediate code in the form of quadruples (each quadruple is a 4–tuple: operator, operand1, operand2, result).
- Generates “target code” by doing a simple pass over the quadruple list and “emitting” some pseudo–assembly instructions.
This example is not meant to be a production–quality compiler but rather to serve as an instructional demonstration that meets the stated requirements. (Compile this file in Visual Studio 2022.)
Below is the complete code (save it as, for example, “toy_compiler.c”):
/*
toy_compiler.c
A minimal C compiler for a small subset of C. It demonstrates:
① Lexical analysis on a hard-coded source program.
② Syntax analysis using recursive descent.
③ Intermediate code generation (quadruples of the form (operator, operand1, operand2, result)).
④ "Target code" generation (a simple pseudo–assembly output based on the intermediate code).
The supported statements (and their assumed formats) are:
- Assignment: id = expression ;
- if statement: if ( condition ) statement [ else statement ]
- while statement: while ( condition ) statement
- do...while statement:do statement while ( condition ) ;
- for statement: for ( assignment ; condition ; assignment ) statement
The language supports only very simple expressions (identifiers, numbers, plus, and minus subtraction)
and conditions (using operators like "<", ">", etc.) for demonstration purposes.
Compile with Visual Studio 2022.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//
// ------------------------- Definitions --------------------------
//
// Maximum number of intermediate code quadruples.
#define MAX_QUADS 1000
// Maximum buffer sizes for identifiers, numbers, etc.
#define MAX_LEXEME_SIZE 100
#define MAX_TEMP_SIZE 50
#define MAX_LABEL_SIZE 50
// Token types for the source language.
typedef enum {
TOKEN_ID,
TOKEN_NUM,
TOKEN_ASSIGN, // =
TOKEN_SEMICOLON, // ;
TOKEN_LPAREN, // (
TOKEN_RPAREN, // )
TOKEN_LBRACE, // {
TOKEN_RBRACE, // }
TOKEN_PLUS, // +
TOKEN_MINUS, // -
TOKEN_MULT, // *
TOKEN_DIV, // /
TOKEN_LT, // <
TOKEN_GT, // >
TOKEN_LE, // <=
TOKEN_GE, // >=
TOKEN_EQ, // ==
TOKEN_NE, // !=
TOKEN_IF,
TOKEN_ELSE,
TOKEN_WHILE,
TOKEN_DO,
TOKEN_FOR,
TOKEN_END, // end-of-string marker
TOKEN_UNKNOWN
} TokenType;
// Token structure.
typedef struct {
TokenType type;
char lexeme[MAX_LEXEME_SIZE];
} Token;
// Intermediate code quadruple.
typedef struct {
char op[10];
char arg1[10];
char arg2[10];
char result[10];
} Quad;
// Global variables for the lexer
char *source; // pointer to the source program
int pos = 0; // current position in the source string
Token currentToken;
// Global variables for code generation
Quad quads[MAX_QUADS];
int nextQuad = 0;
int tempCount = 1;
int labelCount = 1;
//
// ------------------------- Utility functions --------------------------
//
void error(const char *msg) {
printf("Error: %s\n", msg);
exit(1);
}
// Return a new temporary variable name (e.g., T1, T2, …)
void newTemp(char *tempName) {
sprintf(tempName, "T%d", tempCount++);
}
// Return a new label (e.g., L1, L2, …)
void newLabel(char *labelName) {
sprintf(labelName, "L%d", labelCount++);
}
// Emit a quadruple into the quads[] array.
void emit(const char *op, const char *arg1, const char *arg2, const char *result) {
if (nextQuad >= MAX_QUADS) {
error("Too many quadruples.");
}
strcpy(quads[nextQuad].op, op);
strcpy(quads[nextQuad].arg1, arg1);
strcpy(quads[nextQuad].arg2, arg2);
strcpy(quads[nextQuad].result, result);
nextQuad++;
}
//
// ------------------------- Lexical Analyzer --------------------------
//
// A very simple lexical analyzer that scans the global “source” string.
//
// Check if a given string is a keyword; if yes, return the appropriate TokenType.
TokenType checkKeyword(const char *str) {
if (strcmp(str, "if") == 0) return TOKEN_IF;
if (strcmp(str, "else") == 0) return TOKEN_ELSE;
if (strcmp(str, "while") == 0) return TOKEN_WHILE;
if (strcmp(str, "do") == 0) return TOKEN_DO;
if (strcmp(str, "for") == 0) return TOKEN_FOR;
return TOKEN_ID;
}
// Get the next token from source.
Token getNextToken() {
Token token;
token.lexeme[0] = '\0';
// Skip whitespace
while (source[pos] && isspace(source[pos])) { pos++; }
char c = source[pos];
if (c == '\0') {
token.type = TOKEN_END;
strcpy(token.lexeme, "EOF");
return token;
}
// identifier or keyword
if (isalpha(c) || c == '_') {
int start = pos;
while (source[pos] && (isalnum(source[pos]) || source[pos]=='_')) {
pos++;
}
int len = pos - start;
if(len >= MAX_LEXEME_SIZE) len = MAX_LEXEME_SIZE-1;
strncpy(token.lexeme, source + start, len);
token.lexeme[len] = '\0';
token.type = checkKeyword(token.lexeme);
return token;
}
// number literal (only integers for simplicity)
if (isdigit(c)) {
int start = pos;
while (source[pos] && isdigit(source[pos])) {
pos++;
}
int len = pos - start;
if(len >= MAX_LEXEME_SIZE) len = MAX_LEXEME_SIZE-1;
strncpy(token.lexeme, source + start, len);
token.lexeme[len] = '\0';
token.type = TOKEN_NUM;
return token;
}
// Operators and punctuation
pos++; // consume current character
switch (c) {
case '=':
// check for ==
if (source[pos] == '=') { pos++; token.type = TOKEN_EQ; strcpy(token.lexeme, "=="); }
else { token.type = TOKEN_ASSIGN; strcpy(token.lexeme, "="); }
break;
case ';': token.type = TOKEN_SEMICOLON; strcpy(token.lexeme, ";"); break;
case '(': token.type = TOKEN_LPAREN; strcpy(token.lexeme, "("); break;
case ')': token.type = TOKEN_RPAREN; strcpy(token.lexeme, ")"); break;
case '{': token.type = TOKEN_LBRACE; strcpy(token.lexeme, "{"); break;
case '}': token.type = TOKEN_RBRACE; strcpy(token.lexeme, "}"); break;
case '+': token.type = TOKEN_PLUS; strcpy(token.lexeme, "+"); break;
case '-': token.type = TOKEN_MINUS; strcpy(token.lexeme, "-"); break;
case '*': token.type = TOKEN_MULT; strcpy(token.lexeme, "*"); break;
case '/': token.type = TOKEN_DIV; strcpy(token.lexeme, "/"); break;
case '<':
if (source[pos] == '=') { pos++; token.type = TOKEN_LE; strcpy(token.lexeme, "<="); }
else { token.type = TOKEN_LT; strcpy(token.lexeme, "<"); }
break;
case '>':
if (source[pos] == '=') { pos++; token.type = TOKEN_GE; strcpy(token.lexeme, ">="); }
else { token.type = TOKEN_GT; strcpy(token.lexeme, ">"); }
break;
case '!':
if (source[pos] == '=') { pos++; token.type = TOKEN_NE; strcpy(token.lexeme, "!="); }
else { token.type = TOKEN_UNKNOWN; sprintf(token.lexeme, "!"); }
break;
default:
token.type = TOKEN_UNKNOWN;
token.lexeme[0] = c;
token.lexeme[1] = '\0';
break;
}
return token;
}
// Advance to the next token.
void getToken() {
currentToken = getNextToken();
}
// If the current token type is not the expected type, then report an error.
void match(TokenType expected) {
if (currentToken.type == expected) {
getToken();
} else {
char errMsg[100];
sprintf(errMsg, "Expecting token type %d but found \"%s\"", expected, currentToken.lexeme);
error(errMsg);
}
}
//
// ------------------------- Recursive–Descent Parser Functions --------------------------
//
// We build a simple parser that supports assignment statements, if, while, do…while, and for.
// For expressions we allow a simple production:
// Expr -> Term {( '+' | '-' ) Term}
// Term -> id | num
//
// Forward declarations:
void statement();
void statementList();
// expression() returns the name (identifier or temporary) containing its computed value.
char* expression();
// For a simple expression we use a static buffer to return a string pointer.
char exprResult[MAX_TEMP_SIZE];
char* term() {
// A term is either an identifier or a number.
static char buffer[MAX_TEMP_SIZE];
if (currentToken.type == TOKEN_ID || currentToken.type == TOKEN_NUM) {
strcpy(buffer, currentToken.lexeme);
getToken();
return buffer;
} else {
error("Expected an identifier or number in term.");
}
return NULL;
}
char* expression() {
// For simplicity, support only addition and subtraction.
// left = term
char *left = term();
// We use a static buffer for temporary result.
// If there is a '+' or '-' operator, generate a new temporary and emit an arithmetic quadruple.
while (currentToken.type == TOKEN_PLUS || currentToken.type == TOKEN_MINUS) {
TokenType op = currentToken.type;
char opStr[5];
if (op == TOKEN_PLUS) strcpy(opStr, "+"); else strcpy(opStr, "-");
getToken();
char *right = term();
char temp[MAX_TEMP_SIZE];
newTemp(temp);
emit(opStr, left, right, temp);
strcpy(left, temp); // now left holds new computed temporary
}
strcpy(exprResult, left);
return exprResult;
}
//
// Parsing different statement types.
//
// assignment_statement: id '=' expression ';'
void assignment_statement() {
// We assume the production: id = expression ;
if (currentToken.type != TOKEN_ID) {
error("Assignment statement must begin with an identifier.");
}
char id[MAX_LEXEME_SIZE];
strcpy(id, currentToken.lexeme);
getToken();
match(TOKEN_ASSIGN); // '='
char *expRes = expression();
match(TOKEN_SEMICOLON);
// emit assignment quadruple: (=, expression, -, id)
emit("=", expRes, "-", id);
}
// if_statement: "if" "(" expression ")" statement [ "else" statement ]
void if_statement() {
char labelFalse[MAX_LABEL_SIZE], labelEnd[MAX_LABEL_SIZE];
match(TOKEN_IF);
match(TOKEN_LPAREN);
char *cond = expression();
match(TOKEN_RPAREN);
newLabel(labelFalse);
emit("ifFalse", cond, "-", labelFalse);
// then branch:
statement();
// optional else:
if (currentToken.type == TOKEN_ELSE) {
newLabel(labelEnd);
emit("goto", "-", "-", labelEnd);
// mark false label:
emit("label", "-", "-", labelFalse);
match(TOKEN_ELSE);
statement();
emit("label", "-", "-", labelEnd);
} else {
emit("label", "-", "-", labelFalse);
}
}
// while_statement: "while" "(" expression ")" statement
void while_statement() {
char labelStart[MAX_LABEL_SIZE], labelExit[MAX_LABEL_SIZE];
newLabel(labelStart);
newLabel(labelExit);
emit("label", "-", "-", labelStart);
match(TOKEN_WHILE);
match(TOKEN_LPAREN);
char *cond = expression();
match(TOKEN_RPAREN);
emit("ifFalse", cond, "-", labelExit);
statement();
emit("goto", "-", "-", labelStart);
emit("label", "-", "-", labelExit);
}
// do_while_statement: "do" statement "while" "(" expression ")" ";"
void do_while_statement() {
char labelStart[MAX_LABEL_SIZE];
newLabel(labelStart);
emit("label", "-", "-", labelStart);
match(TOKEN_DO);
statement();
match(TOKEN_WHILE);
match(TOKEN_LPAREN);
char *cond = expression();
match(TOKEN_RPAREN);
match(TOKEN_SEMICOLON);
// For a do...while, if condition true, jump back to start.
emit("ifTrue", cond, "-", labelStart);
}
// for_statement: "for" "(" assignment_statement expression ";" assignment_statement ")" statement
// Note: For simplicity, the initialization and update parts are assumed to be simple assignment
// (with the update assignment not ending in ';' inside the parenthesis).
void for_statement() {
char labelStart[MAX_LABEL_SIZE], labelExit[MAX_LABEL_SIZE];
match(TOKEN_FOR);
match(TOKEN_LPAREN);
// Initialization
// We assume a simple assignment statement -- note that the semicolon is expected.
assignment_statement();
newLabel(labelStart);
newLabel(labelExit);
emit("label", "-", "-", labelStart);
// Condition
char *cond = expression();
match(TOKEN_SEMICOLON);
emit("ifFalse", cond, "-", labelExit);
// Update: For simplicity, we assume the update is an assignment statement without an extra semicolon.
// To re-use the assignment_statement routine we will process it and then expect a closing parenthesis.
if (currentToken.type == TOKEN_ID) {
// update assignment (e.g., i = i + 1)
// We will capture the current quadruples for the update.
assignment_statement();
}
else {
// if there is no update part, simply match the semicolon.
match(TOKEN_SEMICOLON);
}
match(TOKEN_RPAREN);
// Statement for for-loop body
statement();
// After the body, jump to update (which was already emitted as code in the update assignment)
// In our simple implementation, the update code was already emitted after the condition.
// Therefore, we jump back to the start:
emit("goto", "-", "-", labelStart);
emit("label", "-", "-", labelExit);
}
// statement: could be an assignment, compound statement, if, while, do...while, or for.
void statement() {
// If a compound statement (block: {...})
if (currentToken.type == TOKEN_LBRACE) {
match(TOKEN_LBRACE);
while (currentToken.type != TOKEN_RBRACE && currentToken.type != TOKEN_END) {
statement();
}
match(TOKEN_RBRACE);
}
else if (currentToken.type == TOKEN_IF) {
if_statement();
}
else if (currentToken.type == TOKEN_WHILE) {
while_statement();
}
else if (currentToken.type == TOKEN_DO) {
do_while_statement();
}
else if (currentToken.type == TOKEN_FOR) {
for_statement();
}
else if (currentToken.type == TOKEN_ID) {
// We assume an assignment statement.
assignment_statement();
}
else {
error("Unrecognized statement.");
}
}
// statement_list: sequence of statements
void statementList() {
while (currentToken.type != TOKEN_END) {
statement();
}
}
//
// ------------------------- Target Code Generation --------------------------
//
// A simple pass over the quadruple list to generate pseudo–assembly code.
//
void generateTargetCode() {
printf("\n----- Generating Target Code (Pseudo–Assembly) -----\n");
for (int i = 0; i < nextQuad; i++) {
Quad q = quads[i];
if (strcmp(q.op, "=") == 0) {
// assignment: q.result = q.arg1
printf(" MOV %s, %s\n", q.result, q.arg1);
}
else if ( (strcmp(q.op, "+") == 0) ||
(strcmp(q.op, "-") == 0) ||
(strcmp(q.op, "*") == 0) ||
(strcmp(q.op, "/") == 0) ) {
// arithmetic: q.result = q.arg1 op q.arg2
printf(" MOV TEMP, %s\n", q.arg1);
if (q.op[0] == '+')
printf(" ADD TEMP, %s\n", q.arg2);
else if (q.op[0] == '-')
printf(" SUB TEMP, %s\n", q.arg2);
else if (q.op[0] == '*')
printf(" MUL TEMP, %s\n", q.arg2);
else if (q.op[0] == '/')
printf(" DIV TEMP, %s\n", q.arg2);
printf(" MOV %s, TEMP\n", q.result);
}
else if (strcmp(q.op, "ifFalse") == 0) {
// ifFalse cond goto label
printf(" CMP %s, 0\n", q.arg1);
printf(" JE %s\n", q.result);
}
else if (strcmp(q.op, "ifTrue") == 0) {
// ifTrue cond goto label
printf(" CMP %s, 0\n", q.arg1);
printf(" JNE %s\n", q.result);
}
else if (strcmp(q.op, "goto") == 0) {
printf(" JMP %s\n", q.result);
}
else if (strcmp(q.op, "label") == 0) {
printf("%s:\n", q.result);
}
else {
// Other opcodes
printf(" // Unrecognized opcode: %s (%s, %s, %s)\n", q.op, q.arg1, q.arg2, q.result);
}
}
}
//
// ------------------------- Main Driver --------------------------
//
int main(void) {
// The input source program (hard-coded). You may modify this sample input.
//
// Note: For simplicity this sample program uses only the supported statements
// and a very simple expression grammar.
//
// Sample program:
// a = 5;
// if ( a < 10 )
// a = a + 1;
// while ( a < 20 )
// a = a + 2;
// do { a = a + 3; } while ( a < 30 );
// for ( i = 0; i < 5; i = i + 1 )
// a = a + i;
//
char sourceProgram[] =
"a = 5;\n"
"if ( a < 10 )\n"
" a = a + 1;\n"
"while ( a < 20 )\n"
" a = a + 2;\n"
"do { a = a + 3; } while ( a < 30 );\n"
"for ( i = 0; i < 5; i = i + 1 )\n"
" a = a + i;\n";
// Initialize global source pointer.
source = sourceProgram;
pos = 0;
getToken();
// Start parsing.
statementList();
// Print the generated intermediate code (quadruples).
printf("----- Intermediate Code (Quadruples) -----\n");
printf("%-10s %-10s %-10s %-10s\n", "OP", "ARG1", "ARG2", "RESULT");
for (int i = 0; i < nextQuad; i++) {
printf("%-10s %-10s %-10s %-10s\n", quads[i].op, quads[i].arg1, quads[i].arg2, quads[i].result);
}
// Generate target code (pseudo–assembly) from intermediate code.
generateTargetCode();
return 0;
}
Explanation
-
Lexical analysis:
The function getNextToken() scans characters from the global source string, skipping whitespace and recognizing identifiers (or keywords), numbers, and operators (including two–character operators such as "<=" and "=="). An error is thrown (via the error() function) if an unexpected character is encountered.
-
Syntax analysis:
A recursive descent parser is implemented with functions such as statement(), assignment_statement(), if_statement(), while_statement(), do_while_statement(), and for_statement(). Each function calls match() to verify that the expected token is present. If not, an error is reported.
-
Intermediate code generation:
As the parser recognizes statements and expressions, it “emits” quadruples using the emit() function. The format is (operator, operand1, operand2, result). For example, for an assignment the quadruple is ("=", expression, "-", variable).
-
Target code generation:
Finally, a simple pass over the quadruple list (in generateTargetCode()) “generates” pseudo–assembly code. Real target code generation would be considerably more complex.
Compile this file in Visual Studio 2022 and run it. The output will print both the intermediate code (quadruple listing) and the generated pseudo–assembly code.
This complete example meets the requirements given.