@@ -788,4 +788,98 @@ int main() {
788788 grammar.print();
789789
790790 return 0;
791- }
791+ }
792+
793+ // Shift-Reduce Parser
794+ #include <iostream>
795+ #include <string>
796+
797+ using namespace std;
798+
799+ class ShiftReduceParser {
800+ string grammar = "E->E+E | E->E*E | E->(E) | E->id";
801+
802+ void reduce(string& stack) {
803+ bool reduced;
804+ do {
805+ reduced = false;
806+ size_t pos;
807+
808+ if ((pos = stack.find("id")) != string::npos) {
809+ stack.replace(pos, 2, "E");
810+ print_step("REDUCE TO E");
811+ reduced = true;
812+ continue;
813+ }
814+
815+ if ((pos = stack.find("E+E")) != string::npos) {
816+ stack.replace(pos, 3, "E");
817+ print_step("REDUCE TO E");
818+ reduced = true;
819+ continue;
820+ }
821+
822+ if ((pos = stack.find("E*E")) != string::npos) {
823+ stack.replace(pos, 3, "E");
824+ print_step("REDUCE TO E");
825+ reduced = true;
826+ continue;
827+ }
828+
829+ if ((pos = stack.find("(E)")) != string::npos) {
830+ stack.replace(pos, 3, "E");
831+ print_step("REDUCE TO E");
832+ reduced = true;
833+ continue;
834+ }
835+ } while (reduced);
836+ }
837+
838+ void print_step(const string& action) {
839+ cout << "$" << stack << "\t$" << input << "\t" << action << endl;
840+ }
841+
842+ public:
843+ string input;
844+ string stack;
845+
846+ void parse() {
847+ cout << "GRAMMAR: " << grammar << "\nEnter input: " << input << endl;
848+ cout << "Stack\tInput\tAction" << endl;
849+
850+ size_t j = 0;
851+ while (j < input.length()) {
852+ if (input[j] == ' ') {
853+ j++;
854+ continue;
855+ }
856+
857+ string action;
858+ if (j+1 < input.length() && input.substr(j, 2) == "id") {
859+ stack += "id";
860+ action = "SHIFT->id";
861+ input.replace(j, 2, " ");
862+ j += 2;
863+ } else {
864+ stack += input[j];
865+ action = "SHIFT->" + string(1, input[j]);
866+ input[j] = ' ';
867+ j++;
868+ }
869+
870+ print_step(action);
871+ reduce(stack);
872+ }
873+
874+ cout << "\nFinal result: ";
875+ cout << (stack == "E" ? "Accepted" : "Rejected") << endl;
876+ }
877+ };
878+
879+ int main() {
880+ ShiftReduceParser parser;
881+ cout << "Enter input string: ";
882+ getline(cin, parser.input);
883+ parser.parse();
884+ return 0;
885+ }
0 commit comments