Below is a single C source file—compiler.c—that reads a sequence of assignment statements from an input file (input.txt), prints them, builds intermediate code (quadruples) via an LR (shift-reduce) parser for expressions, and finally emits 8086 MASM-style assembly. It includes full definitions of the Stack, Data and Code segments (with all user and temporary variables), and is ready to compile under Visual Studio 2022.
// =====================================================================================
// compiler.c
// – Read assignment statements from "input.txt"
// – Print source
// – Lex + Shift-Reduce parse (OP-precedence) → Quadruples
// – Print Quadruples
// – Emit 8086 MASM assembly with SEGMENT defs
//
// Usage in VS2022: create a C console project, add this file, place input.txt alongside
// =====================================================================================
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_SOURCE_SIZE 8192
#define MAX_TOKEN_LEN 64
#define MAX_SYMBOLS 256
#define MAX_QUADS 512
#define STACK_SIZE 256
//-----------------------------------------------------------------------------
// 1. Read Source from File
//-----------------------------------------------------------------------------
char source[MAX_SOURCE_SIZE + 1];
const char *src_ptr;
// load the entire file "input.txt" into `source[]`
void load_source() {
FILE *f = fopen("input.txt", "r");
if (!f) {
perror("Cannot open input.txt");
exit(1);
}
size_t n = fread(source, 1, MAX_SOURCE_SIZE, f);
source[n] = '\0';
fclose(f);
src_ptr = source;
}
//-----------------------------------------------------------------------------
// 2. Lexical Analysis
//-----------------------------------------------------------------------------
typedef enum {
TOK_ID, TOK_NUM,
TOK_PLUS, TOK_MINUS, TOK_MUL, TOK_DIV,
TOK_ASSIGN,
TOK_LPAREN, TOK_RPAREN,
TOK_SEMI,
TOK_EOF
} TokenType;
typedef struct {
TokenType type;
char lexeme[MAX_TOKEN_LEN];
} Token;
Token currentToken;
void error(const char *msg, const char *detail) {
fprintf(stderr, "Error: %s (%s)\n", msg, detail);
exit(1);
}
void getNextToken() {
// skip whitespace
while (isspace(*src_ptr)) src_ptr++;
if (*src_ptr == '\0') {
currentToken.type = TOK_EOF;
strcpy(currentToken.lexeme, "EOF");
return;
}
if (isalpha(*src_ptr)) {
// identifier
int i = 0;
while (isalnum(*src_ptr)) {
if (i < MAX_TOKEN_LEN - 1) currentToken.lexeme[i++] = *src_ptr;
src_ptr++;
}
currentToken.lexeme[i] = '\0';
currentToken.type = TOK_ID;
return;
}
if (isdigit(*src_ptr)) {
// number
int i = 0;
while (isdigit(*src_ptr)) {
if (i < MAX_TOKEN_LEN - 1) currentToken.lexeme[i++] = *src_ptr;
src_ptr++;
}
currentToken.lexeme[i] = '\0';
currentToken.type = TOK_NUM;
return;
}
// single-char tokens
char c = *src_ptr++;
switch (c) {
case '+': currentToken.type = TOK_PLUS; strcpy(currentToken.lexeme, "+"); break;
case '-': currentToken.type = TOK_MINUS; strcpy(currentToken.lexeme, "-"); break;
case '*': currentToken.type = TOK_MUL; strcpy(currentToken.lexeme, "*"); break;
case '/': currentToken.type = TOK_DIV; strcpy(currentToken.lexeme, "/"); break;
case '=': currentToken.type = TOK_ASSIGN; strcpy(currentToken.lexeme, "="); break;
case '(': currentToken.type = TOK_LPAREN; strcpy(currentToken.lexeme, "("); break;
case ')': currentToken.type = TOK_RPAREN; strcpy(currentToken.lexeme, ")"); break;
case ';': currentToken.type = TOK_SEMI; strcpy(currentToken.lexeme, ";"); break;
default:
{
char e[2] = {c,0};
error("Unrecognized character", e);
}
}
}
//-----------------------------------------------------------------------------
// 3. Symbol Table & Quadruples
//-----------------------------------------------------------------------------
typedef struct { char name[MAX_TOKEN_LEN]; } Symbol;
Symbol symtab[MAX_SYMBOLS];
int symcount = 0;
typedef struct {
char op[8], a1[MAX_TOKEN_LEN], a2[MAX_TOKEN_LEN], res[MAX_TOKEN_LEN];
} Quad;
Quad quads[MAX_QUADS];
int qcount = 0;
// add to symbol table if new
void add_symbol(const char *name) {
for (int i = 0; i < symcount; i++)
if (strcmp(symtab[i].name, name)==0) return;
if (symcount >= MAX_SYMBOLS) error("Symbol table overflow", "");
strcpy(symtab[symcount++].name, name);
}
// create a fresh temporary name
char *new_temp() {
static int tcount = 0;
static char buf[32];
sprintf(buf, "_T%d", tcount++);
add_symbol(buf);
return buf;
}
// emit one quadruple
void emit_quad(const char *op, const char *a1, const char *a2, const char *res) {
if (qcount >= MAX_QUADS) error("Quad table overflow", "");
strcpy(quads[qcount].op, op);
strcpy(quads[qcount].a1, a1? a1:"");
strcpy(quads[qcount].a2, a2? a2:"");
strcpy(quads[qcount].res, res?res:"");
qcount++;
}
//-----------------------------------------------------------------------------
// 4. Shift-Reduce Parser (Operator‐Precedence) for expressions
//-----------------------------------------------------------------------------
TokenType opstack[STACK_SIZE]; int otop = -1;
char valstack[STACK_SIZE][MAX_TOKEN_LEN]; int vtop = -1;
// precedence
int prec(TokenType t) {
switch(t) {
case TOK_MUL: case TOK_DIV: return 3;
case TOK_PLUS:case TOK_MINUS:return 2;
case TOK_LPAREN: return 1;
default: return 0;
}
}
void push_op(TokenType t) { opstack[++otop] = t; }
TokenType pop_op() { return opstack[otop--]; }
TokenType top_op() { return (otop>=0)?opstack[otop]:TOK_SEMI; }
void push_val(const char *s) { strcpy(valstack[++vtop], s); }
void pop_val(char *out) { strcpy(out, valstack[vtop--]); }
// perform one reduce
void do_reduce() {
TokenType op = pop_op();
char b[MAX_TOKEN_LEN], a[MAX_TOKEN_LEN];
pop_val(b);
pop_val(a);
char *t = new_temp();
char ops[2]={0};
switch(op) {
case TOK_PLUS: strcpy(ops,"+"); break;
case TOK_MINUS: strcpy(ops,"-"); break;
case TOK_MUL: strcpy(ops,"*"); break;
case TOK_DIV: strcpy(ops,"/"); break;
default: error("Bad reduce op","");
}
emit_quad(ops, a, b, t);
push_val(t);
}
// parse“expression” until SEMI or RPAREN
void parse_expr() {
while (1) {
// shift operands
if (currentToken.type==TOK_ID||currentToken.type==TOK_NUM) {
add_symbol(currentToken.lexeme);
push_val(currentToken.lexeme);
getNextToken();
continue;
}
// shift '('
if (currentToken.type==TOK_LPAREN) {
push_op(TOK_LPAREN);
getNextToken();
continue;
}
// reduce until '(' on ')'
if (currentToken.type==TOK_RPAREN) {
while (otop>=0 && top_op()!=TOK_LPAREN) do_reduce();
if (top_op()==TOK_LPAREN) pop_op();
else error("Mismatched parentheses","");
getNextToken();
return;
}
// end
if (currentToken.type==TOK_SEMI||currentToken.type==TOK_EOF) break;
// an operator
while (otop>=0 && prec(top_op()) >= prec(currentToken.type))
do_reduce();
push_op(currentToken.type);
getNextToken();
}
// reduce any left
while(otop>=0) {
if (top_op()==TOK_LPAREN)
error("Mismatched parentheses","");
do_reduce();
}
}
// parse one assignment: ID = expr ;
void parse_assignment() {
if (currentToken.type != TOK_ID)
error("Expected identifier", currentToken.lexeme);
char lhs[MAX_TOKEN_LEN];
strcpy(lhs, currentToken.lexeme);
add_symbol(lhs);
getNextToken();
if (currentToken.type != TOK_ASSIGN)
error("Expected '='", currentToken.lexeme);
getNextToken();
parse_expr();
if (currentToken.type != TOK_SEMI)
error("Expected ';'", currentToken.lexeme);
getNextToken();
// the single result is on valstack
if (vtop!=0) error("Parse stack error","");
char rhs[MAX_TOKEN_LEN];
pop_val(rhs);
emit_quad("=", rhs, NULL, lhs);
}
// top‐level
void parse_program() {
getNextToken();
while (currentToken.type != TOK_EOF) {
parse_assignment();
}
}
//-----------------------------------------------------------------------------
// 5. Print Results & 6. Emit 8086 MASM Assembly
//-----------------------------------------------------------------------------
int is_number(const char *s) {
if (!*s) return 0;
for (int i=0; s[i]; i++)
if (!isdigit(s[i])) return 0;
return 1;
}
void print_symbol_table() {
printf("=== Symbol Table ===\n");
for (int i = 0; i < symcount; i++)
printf(" %s\n", symtab[i].name);
printf("\n");
}
void print_quads() {
printf("=== Quadruples ===\n");
for (int i = 0; i < qcount; i++) {
printf(" %2d: (%-2s, %-8s, %-8s, %-8s)\n",
i, quads[i].op, quads[i].a1, quads[i].a2, quads[i].res);
}
printf("\n");
}
void emit_8086() {
// stack seg
printf("; --- STACK SEGMENT ---\n");
printf("STACKSG SEGMENT PARA STACK 'STACK'\n");
printf(" DW 128 DUP(?)\n");
printf("STACKSG ENDS\n\n");
// data seg
printf("; --- DATA SEGMENT ---\n");
printf("DATASG SEGMENT PARA 'DATA'\n");
for (int i = 0; i < symcount; i++)
printf(" %s DW ?\n", symtab[i].name);
printf("DATASG ENDS\n\n");
// code seg
printf("; --- CODE SEGMENT ---\n");
printf("CODESG SEGMENT PARA 'CODE'\n");
printf("START PROC FAR\n");
printf(" ASSUME CS:CODESG, DS:DATASG, SS:STACKSG\n");
printf(" MOV AX, DATASG\n");
printf(" MOV DS, AX\n\n");
// body
for (int i = 0; i < qcount; i++) {
Quad *q = &quads[i];
printf("; quad %2d: (%s,%s,%s,%s)\n",
i, q->op, q->a1, q->a2, q->res);
if (strcmp(q->op, "=")==0) {
printf(" MOV AX, %s\n", q->a1);
printf(" MOV %s, AX\n\n", q->res);
}
else if (strcmp(q->op, "+")==0) {
printf(" MOV AX, %s\n", q->a1);
printf(" ADD AX, %s\n", q->a2);
printf(" MOV %s, AX\n\n", q->res);
}
else if (strcmp(q->op, "-")==0) {
printf(" MOV AX, %s\n", q->a1);
printf(" SUB AX, %s\n", q->a2);
printf(" MOV %s, AX\n\n", q->res);
}
else if (strcmp(q->op, "*")==0) {
printf(" MOV AX, %s\n", q->a1);
if (is_number(q->a2)) {
printf(" MOV BX, %s\n", q->a2);
printf(" IMUL BX\n");
} else {
printf(" IMUL %s\n", q->a2);
}
printf(" MOV %s, AX\n\n", q->res);
}
else if (strcmp(q->op, "/")==0) {
printf(" MOV AX, %s\n", q->a1);
printf(" CWD\n");
if (is_number(q->a2)) {
printf(" MOV BX, %s\n", q->a2);
printf(" IDIV BX\n");
} else {
printf(" IDIV %s\n", q->a2);
}
printf(" MOV %s, AX\n\n", q->res);
}
}
// exit
printf(" MOV AH,4CH\n");
printf(" INT 21H\n");
printf("START ENDP\n");
printf("CODESG ENDS\n");
printf("END START\n");
}
//-----------------------------------------------------------------------------
// 7. Main
//-----------------------------------------------------------------------------
int main() {
load_source();
printf("=== Source Code ===\n%s\n", source);
parse_program();
printf("=== Parsing & ICG done ===\n\n");
print_symbol_table();
print_quads();
emit_8086();
return 0;
}
— Place your assignment statements in input.txt, for example:
a = 5;
b = 10;
c = a + b * 2;
d = (a + b) * 2 + a / b;
Compile and run compiler.c under Visual Studio 2022. It will:
-
Print the original source.
-
Show the symbol table (user vars + temporaries).
-
Show the generated quadruples.
-
Emit a complete 8086 MASM program, including:
- STACKSG segment
- DATASG segment (all symbols)
- CODESG segment, with prologue, per-quad assembly, and DOS exit
The output assembly is directly usable in “Masm for Windows Integrated Experiment Environment 2015.”