#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Structure to represent a three-address code instruction
typedef struct Instruction {
    char operator[5];
    char operand1[10];
    char operand2[10];
    char result[10];
} Instruction;

// Function to generate three-address code for an expression
void generateTAC(char *expression, Instruction *instructions, int *count) {
    char *token;
    char *rest = expression;
    char operators[10];
    char operands[10][10];
    int top_op = -1;
    int top_val = -1;
    int temp_count = 1;

    // Tokenize the expression
    while ((token = strtok_r(rest, " ", &rest)) != NULL) {
        if (token[0] == '+' || token[0] == '-' || token[0] == '*' || token[0] == '/') {
            operators[++top_op] = token[0];
        } else if (token[0] >= 'a' && token[0] <= 'z') {
            strcpy(operands[++top_val], token);
        }
    }

    // Generate three-address code
    while (top_op >= 0) {
        Instruction instruction;
        char temp[10];

        // Pop operator and operands
        char op = operators[top_op--];
        char *operand2 = operands[top_val--];
        char *operand1 = operands[top_val--];

        // Create temporary variable
        sprintf(temp, "t%d", temp_count++);

        // Fill instruction fields
        sprintf(instruction.operator, "%c", op);
        strcpy(instruction.operand1, operand1);
        strcpy(instruction.operand2, operand2);
        strcpy(instruction.result, temp);

        // Add instruction to the list
        instructions[(*count)++] = instruction;

        // Push result back to operands stack
        strcpy(operands[++top_val], temp);
    }
}

int main() {
    char expression[100];
    Instruction instructions[100];
    int instruction_count = 0;

    // Get expression from user
    printf("Enter an arithmetic expression (e.g., a + b * c): ");
    fgets(expression, sizeof(expression), stdin);
    expression[strcspn(expression, "\n")] = 0; // Remove trailing newline

    // Generate three-address code
    generateTAC(expression, instructions, &instruction_count);

    // Print three-address code
    printf("\nThree-Address Code:\n");
    for (int i = 0; i < instruction_count; i++) {
        printf("%s = %s %s %s\n", instructions[i].result, instructions[i].operand1,
               instructions[i].operator, instructions[i].operand2);
    }

    return 0;
}