-
Notifications
You must be signed in to change notification settings - Fork 0
/
shift_reduce.c
112 lines (92 loc) · 3.1 KB
/
shift_reduce.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// 21BCB0007
// Izhan Ahmed H
#include <stdio.h>
#include <string.h>
struct ProductionRule
{
char left[10];
char right[10];
};
int main()
{
char input[20], stack[50], temp[50], ch[2], *token1, *token2, *substring;
int i, j, stack_length, substring_length, stack_top, rule_count = 0;
struct ProductionRule rules[10];
stack[0] = '\0';
// User input for the number of production rules
printf("\nEnter the number of production rules: ");
scanf("%d", &rule_count);
// User input for each production rule in the form 'left->right'
printf("\nEnter the production rules (in the form 'left->right'): \n");
for (i = 0; i < rule_count; i++)
{
scanf("%s", temp);
token1 = strtok(temp, "->");
token2 = strtok(NULL, "->");
strcpy(rules[i].left, token1);
strcpy(rules[i].right, token2);
}
// User input for the input string
printf("\nEnter the input string: ");
scanf("%s", input);
i = 0;
while (1)
{
// If there are more characters in the input string, add the next character to the stack
if (i < strlen(input))
{
ch[0] = input[i];
ch[1] = '\0';
i++;
strcat(stack, ch);
printf("%s\t", stack);
for (int k = i; k < strlen(input); k++)
{
printf("%c", input[k]);
}
printf("\tShift %s\n", ch);
}
// Iterate through the production rules
for (j = 0; j < rule_count; j++)
{
// Check if the right-hand side of the production rule matches a substring in the stack
substring = strstr(stack, rules[j].right);
if (substring != NULL)
{
// Replace the matched substring with the left-hand side of the production rule
stack_length = strlen(stack);
substring_length = strlen(substring);
stack_top = stack_length - substring_length;
stack[stack_top] = '\0';
strcat(stack, rules[j].left);
printf("%s\t", stack);
for (int k = i; k < strlen(input); k++)
{
printf("%c", input[k]);
}
printf("\tReduce %s->%s\n", rules[j].left, rules[j].right);
j = -1; // Restart the loop to ensure immediate reduction of the newly derived production rule
}
}
// Check if the stack contains only the start symbol and if the entire input string has been processed
if (strcmp(stack, rules[0].left) == 0 && i == strlen(input))
{
printf("\nAccepted");
break;
}
// Check if the entire input string has been processed but the stack doesn't match the start symbol
if (i == strlen(input))
{
printf("\nNot Accepted");
break;
}
}
return 0;
}
//Enter the number of production rules: 4
//Enter the production rules (in the form 'left->right'):
//E->E+E
//E->E*E
//E->(E)
//E->i
//Enter the input string: i*i+1