================================================================================ COMPILER DESIGN LABORATORY (PCCCS791) LAB ASSIGNMENTS - COMPLETE SOURCE CODE WITH SAMPLE INPUT & OUTPUT ================================================================================ ================================================================================ [LEXICAL ANALYSIS PHASE] Assignment 1: Write a C program to identify whether a given line is a comment or not. Source File: assignment1.c ================================================================================ --- SOURCE CODE --- #include #include #include int main(void) { char line[500]; printf("Enter a line: "); if (!fgets(line, sizeof(line), stdin)) return 0; char *p = line; while (isspace((unsigned char)*p)) p++; if (p[0] == '/' && p[1] == '/') { printf("Result: Single-line comment\n"); } else if (p[0] == '/' && p[1] == '*') { char *end = strstr(p + 2, "*/"); if (end) { end += 2; while (isspace((unsigned char)*end)) end++; if (*end == '\0') printf("Result: Block comment\n"); else printf("Result: Block comment with trailing characters\n"); } else { printf("Result: Unterminated block comment\n"); } } else { printf("Result: Not a comment\n"); } return 0; } --- SAMPLE INPUT --- // This is a single line comment /* This is a block comment */ int a = 10; --- SAMPLE OUTPUT --- Input: // This is a single line comment Output: Result: Single-line comment Input: /* This is a block comment */ Output: Result: Block comment Input: int a = 10; Output: Result: Not a comment ================================================================================ [LEXICAL ANALYSIS PHASE] Assignment 2: Write a C program to recognize strings under 'a', 'a*b+', 'abb'. Source File: assignment2.c ================================================================================ --- SOURCE CODE --- #include #include int matches_a_star_b_plus(const char *s) { int i = 0; while (s[i] == 'a') i++; int b_count = 0; while (s[i] == 'b') { b_count++; i++; } return (b_count >= 1 && s[i] == '\0'); } int main(void) { char str[100]; printf("Enter string: "); if (scanf("%99s", str) != 1) return 0; int matched = 0; if (strcmp(str, "a") == 0) { printf("Recognized under pattern 'a'\n"); matched = 1; } if (strcmp(str, "abb") == 0) { printf("Recognized under pattern 'abb'\n"); printf("Recognized under pattern 'a*b+'\n"); matched = 1; } else if (matches_a_star_b_plus(str)) { printf("Recognized under pattern 'a*b+'\n"); matched = 1; } if (!matched) { printf("String not recognized under 'a', 'a*b+', or 'abb'\n"); } return 0; } --- SAMPLE INPUT --- a abb aaabbb b xyz --- SAMPLE OUTPUT --- Input: a Output: Recognized under pattern 'a' Input: abb Output: Recognized under pattern 'abb' Recognized under pattern 'a*b+' Input: aaabbb Output: Recognized under pattern 'a*b+' Input: b Output: Recognized under pattern 'a*b+' Input: xyz Output: String not recognized under 'a', 'a*b+', or 'abb' ================================================================================ [LEXICAL ANALYSIS PHASE] Assignment 3: Write a C program to test whether a given identifier is valid or not. Source File: assignment3.c ================================================================================ --- SOURCE CODE --- #include #include #include const char *keywords[] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while" }; const int num_keywords = sizeof(keywords) / sizeof(keywords[0]); int is_keyword(const char *str) { for (int i = 0; i < num_keywords; i++) { if (strcmp(str, keywords[i]) == 0) return 1; } return 0; } int is_valid_identifier(const char *str) { if (str[0] == '\0') return 0; if (is_keyword(str)) { printf("Invalid: '%s' is a reserved keyword.\n", str); return 0; } if (!isalpha((unsigned char)str[0]) && str[0] != '_') { printf("Invalid: Identifier must begin with a letter or underscore.\n"); return 0; } for (int i = 1; str[i] != '\0'; i++) { if (!isalnum((unsigned char)str[i]) && str[i] != '_') { printf("Invalid: Contains invalid character '%c'.\n", str[i]); return 0; } } return 1; } int main(void) { char id[100]; printf("Enter identifier: "); if (scanf("%99s", id) != 1) return 0; if (is_valid_identifier(id)) { printf("Valid identifier: %s\n", id); } return 0; } --- SAMPLE INPUT --- my_var1 int 9count temp$val --- SAMPLE OUTPUT --- Input: my_var1 Output: Valid identifier: my_var1 Input: int Output: Invalid: 'int' is a reserved keyword. Input: 9count Output: Invalid: Identifier must begin with a letter or underscore. Input: temp$val Output: Invalid: Contains invalid character '$'. ================================================================================ [LEXICAL ANALYSIS PHASE] Assignment 4: Write a C program to simulate lexical analyzer for validating operators. Source File: assignment4.c ================================================================================ --- SOURCE CODE --- #include #include #include struct OperatorRule { const char *op; const char *type; }; static const struct OperatorRule operators[] = { {"++", "Increment Operator"}, {"--", "Decrement Operator"}, {"<=", "Relational Operator (Less Than or Equal)"}, {">=", "Relational Operator (Greater Than or Equal)"}, {"==", "Relational Operator (Equal To)"}, {"!=", "Relational Operator (Not Equal To)"}, {"&&", "Logical Operator (AND)"}, {"||", "Logical Operator (OR)"}, {"+=", "Compound Assignment Operator"}, {"-=", "Compound Assignment Operator"}, {"*=", "Compound Assignment Operator"}, {"/=", "Compound Assignment Operator"}, {"%=", "Compound Assignment Operator"}, {"<<=", "Bitwise Shift Left Assignment"}, {">>=", "Bitwise Shift Right Assignment"}, {"<<", "Bitwise Shift Left"}, {">>", "Bitwise Shift Right"}, {"+", "Arithmetic Operator (Addition)"}, {"-", "Arithmetic Operator (Subtraction)"}, {"*", "Arithmetic Operator (Multiplication)"}, {"/", "Arithmetic Operator (Division)"}, {"%", "Arithmetic Operator (Modulus)"}, {"=", "Assignment Operator"}, {"<", "Relational Operator (Less Than)"}, {">", "Relational Operator (Greater Than)"}, {"!", "Logical Operator (NOT)"}, {"&", "Bitwise Operator (AND)"}, {"|", "Bitwise Operator (OR)"}, {"^", "Bitwise Operator (XOR)"}, {"~", "Bitwise Operator (NOT)"} }; static const int op_count = sizeof(operators) / sizeof(operators[0]); const char *get_operator_type(const char *tok) { for (int i = 0; i < op_count; i++) { if (strcmp(tok, operators[i].op) == 0) return operators[i].type; } return NULL; } int is_operator_char(char c) { return (strchr("+-*/%=<>!&|^~", c) != NULL); } int main(void) { char input[256]; printf("Enter an operator or an expression: "); if (!fgets(input, sizeof(input), stdin)) return 0; char trimmed[256]; int len = strlen(input); while (len > 0 && (input[len - 1] == '\n' || input[len - 1] == '\r' || isspace((unsigned char)input[len - 1]))) { input[len - 1] = '\0'; len--; } char *start = input; while (isspace((unsigned char)*start)) start++; strcpy(trimmed, start); const char *direct_match = get_operator_type(trimmed); if (direct_match) { printf("Valid Operator: '%s' -> %s\n", trimmed, direct_match); return 0; } int found = 0; int i = 0; while (input[i] != '\0') { if (is_operator_char(input[i])) { char op_buf[5] = {0}; int k = 0; while (is_operator_char(input[i]) && k < 3) { op_buf[k++] = input[i++]; } op_buf[k] = '\0'; const char *type = get_operator_type(op_buf); if (type) { printf("Found valid operator: '%s' -> %s\n", op_buf, type); found = 1; } else { char single[2] = {op_buf[0], '\0'}; type = get_operator_type(single); if (type) { printf("Found valid operator: '%s' -> %s\n", single, type); found = 1; if (k > 1) { i -= (k - 1); } } else { printf("Invalid operator token: '%s'\n", op_buf); } } } else { i++; } } if (!found) { printf("No valid operators found or invalid operator token.\n"); } return 0; } --- SAMPLE INPUT --- == ++ a = b + c * d; --- SAMPLE OUTPUT --- Input: == Output: Valid Operator: '==' -> Relational Operator (Equal To) Input: ++ Output: Valid Operator: '++' -> Increment Operator Input: a = b + c * d; Output: Found valid operator: '=' -> Assignment Operator Found valid operator: '+' -> Arithmetic Operator (Addition) Found valid operator: '*' -> Arithmetic Operator (Multiplication) ================================================================================ [SYNTAX ANALYSIS PHASE] Assignment 5 (a): Design context free grammar for the given language - Write a C program for constructing LL (1) parsing. Source File: assignment5a.c ================================================================================ --- SOURCE CODE --- #include #include /* Grammar: E -> T E' (1) E' -> + T E' (2) | e (3) T -> F T' (4) T' -> * F T' (5) | e (6) F -> ( E ) (7) | i (8) Non-terminals: E, e (E'), T, t (T'), F Terminals: i, +, *, (, ), $ epsilon is represented by '#' */ const char *table[5][6] = { /* i + * ( ) $ */ /* E */ { "Te", NULL, NULL, "Te", NULL, NULL }, /* e */ { NULL, "+Te", NULL, NULL, "#", "#" }, /* T */ { "Ft", NULL, NULL, "Ft", NULL, NULL }, /* t */ { NULL, "#", "*Ft", NULL, "#", "#" }, /* F */ { "i", NULL, NULL, "(E)", NULL, NULL } }; int nt_index(char c) { switch (c) { case 'E': return 0; case 'e': return 1; case 'T': return 2; case 't': return 3; case 'F': return 4; default: return -1; } } int term_index(char c) { switch (c) { case 'i': return 0; case '+': return 1; case '*': return 2; case '(': return 3; case ')': return 4; case '$': return 5; default: return -1; } } int main(void) { char input[100]; char stack[200]; int top = 0; printf("LL(1) Parser for Arithmetic Expressions\n"); printf("Terminals: i, +, *, (, )\n"); printf("Enter string (e.g. i+i*i): "); if (scanf("%90s", input) != 1) return 0; int in_len = strlen(input); if (input[in_len - 1] != '$') { input[in_len] = '$'; input[in_len + 1] = '\0'; } stack[0] = '$'; stack[1] = 'E'; top = 1; int ip = 0; printf("\n%-20s %-20s %s\n", "Stack", "Input", "Action"); printf("------------------------------------------------------------\n"); while (top >= 0) { stack[top + 1] = '\0'; printf("%-20s %-20s ", stack, &input[ip]); char X = stack[top]; char a = input[ip]; if (X == a) { if (X == '$') { printf("Accepted\n"); printf("\nString successfully parsed by LL(1) parser.\n"); return 0; } printf("Match '%c'\n", a); top--; ip++; } else if (nt_index(X) != -1) { int row = nt_index(X); int col = term_index(a); if (col == -1 || table[row][col] == NULL) { printf("Error: Unexpected token '%c'\n", a); break; } const char *prod = table[row][col]; top--; if (strcmp(prod, "#") == 0) { printf("%c -> epsilon\n", X); } else { printf("%c -> %s\n", X, prod); int plen = strlen(prod); for (int i = plen - 1; i >= 0; i--) { stack[++top] = prod[i]; } } } else { printf("Error: Mismatch '%c' vs '%c'\n", X, a); break; } } printf("\nParsing failed: String rejected.\n"); return 0; } --- SAMPLE INPUT --- i+i*i --- SAMPLE OUTPUT --- Stack Input Action ------------------------------------------------------------ $E i+i*i$ E -> Te $eT i+i*i$ T -> Ft $etF i+i*i$ F -> i $eti i+i*i$ Match 'i' $et +i*i$ t -> epsilon $e +i*i$ e -> +Te $eT+ +i*i$ Match '+' $eT i*i$ T -> Ft $etF i*i$ F -> i $eti i*i$ Match 'i' $et *i$ t -> *Ft $etF* *i$ Match '*' $etF i$ F -> i $eti i$ Match 'i' $et $ t -> epsilon $e $ e -> epsilon $ $ Accepted String successfully parsed by LL(1) parser. ================================================================================ [SYNTAX ANALYSIS PHASE] Assignment 5 (b): Design context free grammar for the given language - Write a C program for constructing recursive descent parsing. Source File: assignment5b.c ================================================================================ --- SOURCE CODE --- #include #include static const char *cursor; int E(void); int Eprime(void); int T(void); int Tprime(void); int F(void); int match(char expected) { if (*cursor == expected) { cursor++; return 1; } return 0; } int E(void) { if (T()) { if (Eprime()) return 1; } return 0; } int Eprime(void) { if (*cursor == '+') { cursor++; if (T()) { if (Eprime()) return 1; } return 0; } return 1; } int T(void) { if (F()) { if (Tprime()) return 1; } return 0; } int Tprime(void) { if (*cursor == '*') { cursor++; if (F()) { if (Tprime()) return 1; } return 0; } return 1; } int F(void) { if (*cursor == '(') { cursor++; if (E()) { if (match(')')) return 1; } return 0; } else if (isalnum((unsigned char)*cursor)) { cursor++; return 1; } return 0; } int main(void) { char input[100]; printf("Grammar:\n"); printf(" E -> T E'\n"); printf(" E' -> + T E' | e\n"); printf(" T -> F T'\n"); printf(" T' -> * F T' | e\n"); printf(" F -> ( E ) | id\n\n"); printf("Enter an expression (e.g. i+i*i or (a+b)*c): "); if (scanf("%99s", input) != 1) return 0; cursor = input; if (E() && *cursor == '\0') { printf("String is successfully parsed and VALID.\n"); } else { printf("String is INVALID / Syntax error at '%c'.\n", *cursor ? *cursor : '$'); } return 0; } --- SAMPLE INPUT --- (a+b)*c i+*i --- SAMPLE OUTPUT --- Input: (a+b)*c Output: String is successfully parsed and VALID. Input: i+*i Output: String is INVALID / Syntax error at '*'. ================================================================================ [SYNTAX ANALYSIS PHASE] Assignment 6: Design an LALR grammar. Write a C program to implement LALR parsing. Source File: assignment6.c ================================================================================ --- SOURCE CODE --- #include #include /* Grammar: 1. S -> C C 2. C -> c C 3. C -> d Merged LALR(1) states: 0, 1, 2, 3 (I3+I6), 4 (I4+I7), 5, 6 (I8+I9) Action encoding: sN -> Shift to state N rN -> Reduce by rule N acc -> Accept err -> Error */ enum ActionType { ERROR, SHIFT, REDUCE, ACCEPT }; struct Action { enum ActionType type; int target; }; struct Rule { char lhs; int len; const char *str; }; static const struct Rule rules[4] = { {0, 0, ""}, {'S', 2, "S -> C C"}, {'C', 2, "C -> c C"}, {'C', 1, "C -> d"} }; static const struct Action action_table[7][3] = { /* c d $ */ /* 0 */ { {SHIFT, 3}, {SHIFT, 4}, {ERROR, 0} }, /* 1 */ { {ERROR, 0}, {ERROR, 0}, {ACCEPT, 0} }, /* 2 */ { {SHIFT, 3}, {SHIFT, 4}, {ERROR, 0} }, /* 3 */ { {SHIFT, 3}, {SHIFT, 4}, {ERROR, 0} }, /* 4 */ { {REDUCE, 3}, {REDUCE, 3}, {REDUCE, 3} }, /* 5 */ { {ERROR, 0}, {ERROR, 0}, {REDUCE, 1} }, /* 6 */ { {REDUCE, 2}, {REDUCE, 2}, {REDUCE, 2} } }; static const int goto_table[7][2] = { /* S C */ /* 0 */ { 1, 2 }, /* 1 */ { -1, -1 }, /* 2 */ { -1, 5 }, /* 3 */ { -1, 6 }, /* 4 */ { -1, -1 }, /* 5 */ { -1, -1 }, /* 6 */ { -1, -1 } }; int get_term_col(char c) { if (c == 'c') return 0; if (c == 'd') return 1; if (c == '$') return 2; return -1; } int get_nonterm_col(char c) { if (c == 'S') return 0; if (c == 'C') return 1; return -1; } int main(void) { char input[100]; int state_stack[200]; char sym_stack[200]; int top = 0; printf("LALR(1) Parser for Grammar:\n"); printf(" 1. S -> C C\n"); printf(" 2. C -> c C\n"); printf(" 3. C -> d\n"); printf("Valid terminals: 'c', 'd'\n\n"); printf("Enter string (e.g. cdd, cdcd, dd): "); if (scanf("%90s", input) != 1) return 0; int in_len = strlen(input); if (input[in_len - 1] != '$') { input[in_len] = '$'; input[in_len + 1] = '\0'; } state_stack[0] = 0; sym_stack[0] = '$'; top = 0; int ip = 0; printf("\n%-25s %-20s %s\n", "Stack", "Input", "Action"); printf("-----------------------------------------------------------------\n"); while (1) { char stack_str[200] = {0}; int s_idx = 0; for (int i = 0; i <= top; i++) { s_idx += sprintf(stack_str + s_idx, "%c%d", sym_stack[i], state_stack[i]); } printf("%-25s %-20s ", stack_str, &input[ip]); int curr_state = state_stack[top]; char a = input[ip]; int col = get_term_col(a); if (col == -1) { printf("Error: Invalid terminal '%c'\n", a); break; } struct Action act = action_table[curr_state][col]; if (act.type == SHIFT) { printf("Shift to state %d\n", act.target); top++; sym_stack[top] = a; state_stack[top] = act.target; ip++; } else if (act.type == REDUCE) { struct Rule r = rules[act.target]; printf("Reduce by %s\n", r.str); top -= r.len; int prev_state = state_stack[top]; int nt_col = get_nonterm_col(r.lhs); int next_state = goto_table[prev_state][nt_col]; top++; sym_stack[top] = r.lhs; state_stack[top] = next_state; } else if (act.type == ACCEPT) { printf("Accept\n"); printf("\nString accepted successfully by LALR parser.\n"); return 0; } else { printf("Error: Syntax error on '%c'\n", a); break; } } printf("\nParsing failed: String rejected.\n"); return 0; } --- SAMPLE INPUT --- cdd --- SAMPLE OUTPUT --- Grammar: 1. S -> C C 2. C -> c C 3. C -> d Stack Input Action ----------------------------------------------------------------- $0 cdd$ Shift to state 3 $0c3 dd$ Shift to state 4 $0c3d4 d$ Reduce by C -> d $0c3C6 d$ Reduce by C -> c C $0C2 d$ Shift to state 4 $0C2d4 $ Reduce by C -> d $0C2C5 $ Reduce by S -> C C $0S1 $ Accept String accepted successfully by LALR parser. ================================================================================ [SEMANTIC ANALYSIS PHASE] Assignment 7: Write a program in C to check the variable values stores in variables are mapped to appropriate datatypes. Source File: assignment7.c ================================================================================ --- SOURCE CODE --- #include #include #include enum DataType { TYPE_INT, TYPE_FLOAT, TYPE_CHAR, TYPE_STRING, TYPE_UNKNOWN }; const char *type_to_string(enum DataType t) { switch (t) { case TYPE_INT: return "int"; case TYPE_FLOAT: return "float"; case TYPE_CHAR: return "char"; case TYPE_STRING: return "string"; default: return "unknown"; } } enum DataType parse_type_name(const char *name) { if (strcmp(name, "int") == 0) return TYPE_INT; if (strcmp(name, "float") == 0 || strcmp(name, "double") == 0) return TYPE_FLOAT; if (strcmp(name, "char") == 0) return TYPE_CHAR; if (strcmp(name, "string") == 0 || strcmp(name, "char*") == 0) return TYPE_STRING; return TYPE_UNKNOWN; } enum DataType detect_value_type(const char *val) { int len = strlen(val); if (len >= 2 && val[0] == '\'' && val[len - 1] == '\'') { return TYPE_CHAR; } if (len >= 2 && val[0] == '"' && val[len - 1] == '"') { return TYPE_STRING; } int i = 0; if (val[0] == '+' || val[0] == '-') i++; int has_digits = 0; int dot_count = 0; for (; val[i] != '\0'; i++) { if (isdigit((unsigned char)val[i])) { has_digits = 1; } else if (val[i] == '.') { dot_count++; } else { return TYPE_UNKNOWN; } } if (has_digits && dot_count == 0) return TYPE_INT; if (has_digits && dot_count == 1) return TYPE_FLOAT; return TYPE_UNKNOWN; } void trim(char *s) { int len = strlen(s); while (len > 0 && (isspace((unsigned char)s[len - 1]) || s[len - 1] == ';')) { s[--len] = '\0'; } } void check_statement(const char *stmt) { char type_str[32], var_name[64], eq[10], val_str[128]; char copy[256]; strncpy(copy, stmt, sizeof(copy) - 1); copy[sizeof(copy) - 1] = '\0'; trim(copy); if (sscanf(copy, "%31s %63s %9s %127[^\n]", type_str, var_name, eq, val_str) != 4 || strcmp(eq, "=") != 0) { printf("Syntax: Use format ` = ;` (e.g. int x = 10;)\n"); return; } trim(val_str); enum DataType decl_type = parse_type_name(type_str); if (decl_type == TYPE_UNKNOWN) { printf("Error: Unsupported or unknown type '%s'\n", type_str); return; } enum DataType val_type = detect_value_type(val_str); if (val_type == TYPE_UNKNOWN) { printf("Error: Invalid literal constant '%s'\n", val_str); return; } int valid = 0; if (decl_type == val_type) { valid = 1; } else if (decl_type == TYPE_FLOAT && val_type == TYPE_INT) { valid = 1; // Integer literal implicitly promotable to float } if (valid) { printf("[VALID] Variable '%s' of type '%s' correctly mapped to value %s (%s)\n", var_name, type_str, val_str, type_to_string(val_type)); } else { printf("[SEMANTIC ERROR] Type mismatch: Cannot assign %s value %s to variable '%s' of type '%s'\n", type_to_string(val_type), val_str, var_name, type_str); } } int main(void) { char line[256]; printf("Semantic Analyzer - Variable Type Compatibility Checker\n"); printf("Enter statements (e.g. `int a = 10;` or `float b = \"abc\";`), or 'exit':\n"); while (1) { printf("> "); if (!fgets(line, sizeof(line), stdin)) break; char *p = line; while (isspace((unsigned char)*p)) p++; if (strncmp(p, "exit", 4) == 0) break; if (*p == '\0') continue; check_statement(p); } return 0; } --- SAMPLE INPUT --- int a = 10; float b = 3.14; char c = 'z'; int d = 3.14; char e = 25; float f = "compiler"; --- SAMPLE OUTPUT --- > int a = 10; [VALID] Variable 'a' of type 'int' correctly mapped to value 10 (int) > float b = 3.14; [VALID] Variable 'b' of type 'float' correctly mapped to value 3.14 (float) > char c = 'z'; [VALID] Variable 'c' of type 'char' correctly mapped to value 'z' (char) > int d = 3.14; [SEMANTIC ERROR] Type mismatch: Cannot assign float value 3.14 to variable 'd' of type 'int' > char e = 25; [SEMANTIC ERROR] Type mismatch: Cannot assign int value 25 to variable 'e' of type 'char' > float f = "compiler"; [SEMANTIC ERROR] Type mismatch: Cannot assign string value "compiler" to variable 'f' of type 'float' ================================================================================ [SEMANTIC ANALYSIS PHASE] Assignment 8: Write a C program to detect undeclared variables. Source File: assignment8.c ================================================================================ --- SOURCE CODE --- #include #include #include #define MAX_VARS 100 #define MAX_NAME_LEN 32 struct SymbolTable { char names[MAX_VARS][MAX_NAME_LEN]; int count; } sym_tab; void add_symbol(const char *name) { for (int i = 0; i < sym_tab.count; i++) { if (strcmp(sym_tab.names[i], name) == 0) return; } if (sym_tab.count < MAX_VARS) { strncpy(sym_tab.names[sym_tab.count++], name, MAX_NAME_LEN - 1); } } int is_declared(const char *name) { for (int i = 0; i < sym_tab.count; i++) { if (strcmp(sym_tab.names[i], name) == 0) return 1; } return 0; } int is_type_keyword(const char *tok) { return (strcmp(tok, "int") == 0 || strcmp(tok, "float") == 0 || strcmp(tok, "char") == 0 || strcmp(tok, "double") == 0); } void parse_declaration(char *line) { char *token = strtok(line, " ,;\t\n\r"); if (!token || !is_type_keyword(token)) return; while ((token = strtok(NULL, " ,;\t\n\r")) != NULL) { if (isalpha((unsigned char)token[0]) || token[0] == '_') { add_symbol(token); } } } int check_usage(const char *line, int line_num) { int errors = 0; int i = 0; while (line[i] != '\0') { if (isalpha((unsigned char)line[i]) || line[i] == '_') { char name[MAX_NAME_LEN]; int k = 0; while ((isalnum((unsigned char)line[i]) || line[i] == '_') && k < MAX_NAME_LEN - 1) { name[k++] = line[i++]; } name[k] = '\0'; if (!is_type_keyword(name)) { if (!is_declared(name)) { printf("Line %d: [SEMANTIC ERROR] Undeclared variable '%s'\n", line_num, name); errors++; } } } else { i++; } } return errors; } int main(void) { char lines[50][256]; int total_lines = 0; printf("Semantic Analyzer - Undeclared Variable Detector\n"); printf("Enter C code snippet (enter 'END' on a single line to finish):\n\n"); while (total_lines < 50) { if (!fgets(lines[total_lines], sizeof(lines[total_lines]), stdin)) break; char temp[256]; sscanf(lines[total_lines], "%255s", temp); if (strcmp(temp, "END") == 0) break; total_lines++; } for (int i = 0; i < total_lines; i++) { char copy[256]; strcpy(copy, lines[i]); char first_word[32] = {0}; sscanf(copy, "%31s", first_word); if (is_type_keyword(first_word)) { parse_declaration(copy); } } printf("\n--- Symbol Table (Declared Variables) ---\n"); if (sym_tab.count == 0) { printf("(No variables declared)\n"); } else { for (int i = 0; i < sym_tab.count; i++) { printf("%d: %s\n", i + 1, sym_tab.names[i]); } } printf("\n--- Semantic Analysis Results ---\n"); int errors = 0; for (int i = 0; i < total_lines; i++) { char first_word[32] = {0}; sscanf(lines[i], "%31s", first_word); if (!is_type_keyword(first_word)) { errors += check_usage(lines[i], i + 1); } } if (errors == 0) { printf("Semantic check passed: All variables are properly declared.\n"); } return 0; } --- SAMPLE INPUT --- int a, b; float sum; a = b + 5; sum = a + x; y = a * b + z; END --- SAMPLE OUTPUT --- --- Symbol Table (Declared Variables) --- 1: a 2: b 3: sum --- Semantic Analysis Results --- Line 4: [SEMANTIC ERROR] Undeclared variable 'x' Line 5: [SEMANTIC ERROR] Undeclared variable 'y' Line 5: [SEMANTIC ERROR] Undeclared variable 'z' ================================================================================ [SEMANTIC ANALYSIS PHASE] Assignment 9: Write a C program to check whether break keyword has been used outside any loop. Source File: assignment9.c ================================================================================ --- SOURCE CODE --- #include #include #include #define MAX_STACK 100 enum BlockKind { BLOCK_GENERAL, BLOCK_LOOP }; int is_whole_word(const char *line, const char *word, int pos) { int wlen = strlen(word); if (pos > 0 && (isalnum((unsigned char)line[pos - 1]) || line[pos - 1] == '_')) return 0; if (isalnum((unsigned char)line[pos + wlen]) || line[pos + wlen] == '_') return 0; return 1; } int has_keyword(const char *line, const char *kw) { const char *p = line; int klen = strlen(kw); while ((p = strstr(p, kw)) != NULL) { int pos = p - line; if (is_whole_word(line, kw, pos)) return 1; p += klen; } return 0; } int is_loop_header(const char *line) { return (has_keyword(line, "for") || has_keyword(line, "while") || has_keyword(line, "do") || has_keyword(line, "switch")); } int main(void) { char line[256]; enum BlockKind stack[MAX_STACK]; int top = -1; int pending_loop_block = 0; int line_num = 0; int errors = 0; printf("Semantic Analyzer - Break Statement Validator\n"); printf("Enter C code (type 'END' on a separate line to evaluate):\n\n"); while (fgets(line, sizeof(line), stdin)) { line_num++; char first[32] = {0}; sscanf(line, "%31s", first); if (strcmp(first, "END") == 0) break; int line_is_loop = is_loop_header(line); if (line_is_loop) pending_loop_block = 1; for (int i = 0; line[i] != '\0'; i++) { if (line[i] == '{') { if (top < MAX_STACK - 1) { top++; stack[top] = pending_loop_block ? BLOCK_LOOP : BLOCK_GENERAL; } pending_loop_block = 0; } else if (line[i] == '}') { if (top >= 0) top--; } } const char *p = line; while ((p = strstr(p, "break")) != NULL) { int pos = p - line; if (is_whole_word(line, "break", pos)) { int in_loop = 0; for (int s = 0; s <= top; s++) { if (stack[s] == BLOCK_LOOP) { in_loop = 1; break; } } if (!in_loop && line_is_loop) { in_loop = 1; } if (in_loop) { printf("Line %d: [VALID] 'break' statement is correctly inside a loop/switch block.\n", line_num); } else { printf("Line %d: [SEMANTIC ERROR] 'break' statement used outside any loop or switch!\n", line_num); errors++; } } p += 5; } if (strchr(line, ';')) { pending_loop_block = 0; } } if (errors == 0) { printf("\nSemantic check passed: All break statements are within valid loop/switch scopes.\n"); } else { printf("\nSemantic check failed: %d invalid break statement(s) found.\n", errors); } return 0; } --- SAMPLE INPUT --- int main() { int i = 0; break; for (i = 0; i < 10; i++) { if (i == 5) { break; } } } END --- SAMPLE OUTPUT --- Line 3: [SEMANTIC ERROR] 'break' statement used outside any loop or switch! Line 6: [VALID] 'break' statement is correctly inside a loop/switch block. Semantic check failed: 1 invalid break statement(s) found. ================================================================================ [INTERMEDIATE CODE GENERATION PHASE] Assignment 10: Write a C program to create a parse tree Test it with the input : x = (a + b * c) / (a - b * c) Source File: assignment10.c ================================================================================ --- SOURCE CODE --- #include #include #include #include struct Node { char val[16]; struct Node *left; struct Node *right; }; struct Node *create_node(const char *val, struct Node *left, struct Node *right) { struct Node *n = (struct Node *)malloc(sizeof(struct Node)); strncpy(n->val, val, sizeof(n->val) - 1); n->val[sizeof(n->val) - 1] = '\0'; n->left = left; n->right = right; return n; } static const char *src; void skip_spaces(void) { while (isspace((unsigned char)*src)) src++; } struct Node *parse_expr(void); struct Node *parse_factor(void) { skip_spaces(); if (*src == '(') { src++; struct Node *node = parse_expr(); skip_spaces(); if (*src == ')') src++; return node; } if (isalnum((unsigned char)*src) || *src == '_') { char buf[16]; int k = 0; while ((isalnum((unsigned char)*src) || *src == '_') && k < 15) { buf[k++] = *src++; } buf[k] = '\0'; return create_node(buf, NULL, NULL); } return NULL; } struct Node *parse_term(void) { struct Node *left = parse_factor(); while (1) { skip_spaces(); if (*src == '*' || *src == '/') { char op[2] = {*src++, '\0'}; struct Node *right = parse_factor(); left = create_node(op, left, right); } else { break; } } return left; } struct Node *parse_expr(void) { struct Node *left = parse_term(); while (1) { skip_spaces(); if (*src == '+' || *src == '-') { char op[2] = {*src++, '\0'}; struct Node *right = parse_term(); left = create_node(op, left, right); } else { break; } } return left; } struct Node *parse_assignment(void) { skip_spaces(); struct Node *lhs = parse_factor(); skip_spaces(); if (*src == '=') { char op[2] = {*src++, '\0'}; struct Node *rhs = parse_expr(); return create_node(op, lhs, rhs); } return lhs; } void print_tree(struct Node *root, int depth, const char *prefix, int is_left) { if (!root) return; printf("%s", prefix); printf("%s── %s\n", is_left ? "├" : "└", root->val); char new_prefix[256]; snprintf(new_prefix, sizeof(new_prefix), "%s%s ", prefix, is_left ? "│" : " "); if (root->left && root->right) { print_tree(root->left, depth + 1, new_prefix, 1); print_tree(root->right, depth + 1, new_prefix, 0); } else if (root->left) { print_tree(root->left, depth + 1, new_prefix, 0); } else if (root->right) { print_tree(root->right, depth + 1, new_prefix, 0); } } void print_inorder(struct Node *n) { if (!n) return; if (n->left || n->right) printf("( "); print_inorder(n->left); printf("%s ", n->val); print_inorder(n->right); if (n->left || n->right) printf(") "); } void print_preorder(struct Node *n) { if (!n) return; printf("%s ", n->val); print_preorder(n->left); print_preorder(n->right); } void print_postorder(struct Node *n) { if (!n) return; print_postorder(n->left); print_postorder(n->right); printf("%s ", n->val); } void free_tree(struct Node *n) { if (!n) return; free_tree(n->left); free_tree(n->right); free(n); } void normalize_input(char *dst, const char *src_str) { int j = 0; for (int i = 0; src_str[i] != '\0'; i++) { // Replace UTF-8 en-dash (0xE2 0x80 0x93) with standard hyphen '-' if ((unsigned char)src_str[i] == 0xe2 && (unsigned char)src_str[i+1] == 0x80 && (unsigned char)src_str[i+2] == 0x93) { dst[j++] = '-'; i += 2; } else { dst[j++] = src_str[i]; } } dst[j] = '\0'; } int main(void) { char raw[256]; char clean[256]; printf("Enter expression (default: x = (a + b * c) / (a - b * c)):\n> "); if (!fgets(raw, sizeof(raw), stdin) || raw[0] == '\n') { strcpy(raw, "x = (a + b * c) / (a - b * c)"); } int len = strlen(raw); if (len > 0 && raw[len - 1] == '\n') raw[len - 1] = '\0'; normalize_input(clean, raw); printf("\nParsed Expression: %s\n\n", clean); src = clean; struct Node *root = parse_assignment(); printf("Parse Tree Structure:\n"); if (root) { printf("%s\n", root->val); char prefix[256] = ""; if (root->left && root->right) { print_tree(root->left, 1, prefix, 1); print_tree(root->right, 1, prefix, 0); } else if (root->left) { print_tree(root->left, 1, prefix, 0); } } printf("\nTraversals:\n"); printf("Pre-order : "); print_preorder(root); printf("\nIn-order : "); print_inorder(root); printf("\nPost-order : "); print_postorder(root); printf("\n"); free_tree(root); return 0; } --- SAMPLE INPUT --- x = (a + b * c) / (a - b * c) --- SAMPLE OUTPUT --- Parsed Expression: x = (a + b * c) / (a - b * c) Parse Tree Structure: = ├── x └── / ├── + │ ├── a │ └── * │ ├── b │ └── c └── - ├── a └── * ├── b └── c Traversals: Pre-order : = x / + a * b c - a * b c In-order : ( x = ( ( a + ( b * c ) ) / ( a - ( b * c ) ) ) ) Post-order : x a b c * + a b c * - / = ================================================================================ [INTERMEDIATE CODE GENERATION PHASE] Assignment 11: Write a C program to generate the three address code. Test it for the expression a + b * c + d Source File: assignment11.c ================================================================================ --- SOURCE CODE --- #include #include #include #include struct Quadruple { char op[8]; char arg1[32]; char arg2[32]; char res[32]; }; int precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; } void infix_to_postfix(const char *infix, char postfix[][32], int *p_count) { char op_stack[100]; int op_top = -1; *p_count = 0; int i = 0; while (infix[i] != '\0') { if (isspace((unsigned char)infix[i])) { i++; continue; } if (isalnum((unsigned char)infix[i]) || infix[i] == '_') { char tok[32]; int k = 0; while ((isalnum((unsigned char)infix[i]) || infix[i] == '_') && k < 31) { tok[k++] = infix[i++]; } tok[k] = '\0'; strcpy(postfix[(*p_count)++], tok); } else if (infix[i] == '(') { op_stack[++op_top] = infix[i++]; } else if (infix[i] == ')') { while (op_top >= 0 && op_stack[op_top] != '(') { char op_str[2] = {op_stack[op_top--], '\0'}; strcpy(postfix[(*p_count)++], op_str); } if (op_top >= 0 && op_stack[op_top] == '(') op_top--; i++; } else if (strchr("+-*/", infix[i])) { char current_op = infix[i++]; while (op_top >= 0 && precedence(op_stack[op_top]) >= precedence(current_op)) { char op_str[2] = {op_stack[op_top--], '\0'}; strcpy(postfix[(*p_count)++], op_str); } op_stack[++op_top] = current_op; } else { i++; } } while (op_top >= 0) { char op_str[2] = {op_stack[op_top--], '\0'}; strcpy(postfix[(*p_count)++], op_str); } } int main(void) { char expr[256]; char postfix[100][32]; int p_count = 0; printf("Three Address Code (TAC) Generator\n"); printf("Enter infix expression (e.g. a + b * c + d): "); if (!fgets(expr, sizeof(expr), stdin) || expr[0] == '\n') { strcpy(expr, "a + b * c + d"); } int len = strlen(expr); if (len > 0 && expr[len - 1] == '\n') expr[len - 1] = '\0'; printf("\nInput Expression: %s\n", expr); infix_to_postfix(expr, postfix, &p_count); char val_stack[100][32]; int val_top = -1; struct Quadruple quads[100]; int q_count = 0; int temp_idx = 1; printf("\n--- Generated Three Address Code ---\n"); for (int i = 0; i < p_count; i++) { if (strlen(postfix[i]) == 1 && strchr("+-*/", postfix[i][0])) { if (val_top < 1) { printf("Error: Invalid expression syntax.\n"); return 1; } char op2[32], op1[32], temp[32]; strcpy(op2, val_stack[val_top--]); strcpy(op1, val_stack[val_top--]); sprintf(temp, "t%d", temp_idx++); printf("%s = %s %s %s\n", temp, op1, postfix[i], op2); strcpy(quads[q_count].op, postfix[i]); strcpy(quads[q_count].arg1, op1); strcpy(quads[q_count].arg2, op2); strcpy(quads[q_count].res, temp); q_count++; strcpy(val_stack[++val_top], temp); } else { strcpy(val_stack[++val_top], postfix[i]); } } printf("\n--- Quadruple Representation ---\n"); printf("%-6s %-10s %-10s %-10s\n", "Op", "Arg1", "Arg2", "Result"); printf("------------------------------------\n"); for (int i = 0; i < q_count; i++) { printf("%-6s %-10s %-10s %-10s\n", quads[i].op, quads[i].arg1, quads[i].arg2, quads[i].res); } return 0; } --- SAMPLE INPUT --- a + b * c + d --- SAMPLE OUTPUT --- Input Expression: a + b * c + d --- Generated Three Address Code --- t1 = b * c t2 = a + t1 t3 = t2 + d --- Quadruple Representation --- Op Arg1 Arg2 Result ------------------------------------ * b c t1 + a t1 t2 + t2 d t3 ================================================================================ [INTERMEDIATE CODE GENERATION PHASE] Assignment 12: Write a C program to generate the postfix representation of an. Test it for the expression: (a - b) * (c + d) + (a - b) Source File: assignment12.c ================================================================================ --- SOURCE CODE --- #include #include #include int precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; if (op == '^') return 3; return 0; } void normalize_input(char *dst, const char *src) { int j = 0; for (int i = 0; src[i] != '\0'; i++) { if ((unsigned char)src[i] == 0xe2 && (unsigned char)src[i+1] == 0x80 && (unsigned char)src[i+2] == 0x93) { dst[j++] = '-'; i += 2; } else { dst[j++] = src[i]; } } dst[j] = '\0'; } int main(void) { char raw_input[256]; char expr[256]; char stack[100]; int top = -1; char postfix[256]; int p_idx = 0; printf("Infix to Postfix Converter\n"); printf("Enter infix expression (default: (a - b) * (c + d) + (a - b)):\n> "); if (!fgets(raw_input, sizeof(raw_input), stdin) || raw_input[0] == '\n') { strcpy(raw_input, "(a - b) * (c + d) + (a - b)"); } int len = strlen(raw_input); if (len > 0 && raw_input[len - 1] == '\n') raw_input[len - 1] = '\0'; normalize_input(expr, raw_input); printf("\nInput Expression: %s\n\n", expr); printf("%-8s %-20s %-30s\n", "Token", "Stack", "Postfix Expression"); printf("------------------------------------------------------------\n"); int i = 0; while (expr[i] != '\0') { if (isspace((unsigned char)expr[i])) { i++; continue; } char tok_str[4] = {expr[i], '\0'}; if (isalnum((unsigned char)expr[i])) { postfix[p_idx++] = expr[i]; postfix[p_idx++] = ' '; postfix[p_idx] = '\0'; } else if (expr[i] == '(') { stack[++top] = '('; } else if (expr[i] == ')') { while (top >= 0 && stack[top] != '(') { postfix[p_idx++] = stack[top--]; postfix[p_idx++] = ' '; postfix[p_idx] = '\0'; } if (top >= 0 && stack[top] == '(') top--; } else if (strchr("+-*/^", expr[i])) { char current_op = expr[i]; while (top >= 0 && precedence(stack[top]) >= precedence(current_op) && current_op != '^') { postfix[p_idx++] = stack[top--]; postfix[p_idx++] = ' '; postfix[p_idx] = '\0'; } stack[++top] = current_op; } char stack_view[100] = {0}; for (int s = 0; s <= top; s++) stack_view[s] = stack[s]; printf("%-8s %-20s %-30s\n", tok_str, stack_view, postfix); i++; } while (top >= 0) { if (stack[top] != '(') { postfix[p_idx++] = stack[top--]; postfix[p_idx++] = ' '; postfix[p_idx] = '\0'; } else { top--; } char stack_view[100] = {0}; for (int s = 0; s <= top; s++) stack_view[s] = stack[s]; printf("%-8s %-20s %-30s\n", "", stack_view, postfix); } if (p_idx > 0 && postfix[p_idx - 1] == ' ') postfix[p_idx - 1] = '\0'; printf("\nFinal Postfix Expression: %s\n", postfix); return 0; } --- SAMPLE INPUT --- (a - b) * (c + d) + (a - b) --- SAMPLE OUTPUT --- Input Expression: (a - b) * (c + d) + (a - b) Token Stack Postfix Expression ------------------------------------------------------------ ( ( a ( a - (- a b (- a b ) a b - * * a b - ( *( a b - c *( a b - c + *(+ a b - c d *(+ a b - c d ) * a b - c d + + + a b - c d + * ( +( a b - c d + * a +( a b - c d + * a - +(- a b - c d + * a b +(- a b - c d + * a b ) + a b - c d + * a b - a b - c d + * a b - + Final Postfix Expression: a b - c d + * a b - +