Advertisement
Coder_22

Predictive Parser

Jan 3rd, 2025
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. char rel(string& s, string& r) {
  4.     if (s == "id" && r == "id") return '-'; if (s == "$" && r == "$" ) return 'A';
  5.     if (s == "id" or r == "$") return '>'; if (s == "$" or r == "id") return '<';
  6.     if (s == "+") { if (r == "*" or r == "^") return '<'; return '>'; }
  7.     if (s == "*") { if (r == "+" or r == "^") return '>'; return '<'; }
  8.     if (s == "^") { if (r == "+" or r == "*") return '>'; return '<'; }
  9. }
  10. int main() {
  11.     map<string, string> grammar;
  12.     grammar["E + E"] = grammar["E * E"] = grammar["E ^ E"] = grammar["id"] = "E";
  13.     cout << "Enter the production: "; string s; getline(cin, s);
  14.     vector<string> w; string r;
  15.     for (char c : s) { if (c == ' ') w.push_back(r), r.clear(); else r += c; }
  16.     if (!r.empty()) w.push_back(r); w.push_back("$");
  17.     int i = 0; string ip = w[i]; stack<string> sk, terminal; sk.push("$");
  18.     while (true) {
  19.         if (sk.top() == "$" && ip == "$" && terminal.size() == 1 && terminal.top() == grammar.begin()->second) { cout << "Accepted!\n"; break; }
  20.         string a = sk.top(), b = ip; char relation = rel(a, b);
  21.         if (relation == '<') {
  22.             sk.push(b); ip = w[++i]; cout << "Shift Operation Performed!\n";
  23.         }
  24.         else if (relation == '>') {
  25.             do {
  26.                 string recent = sk.top(); sk.pop();
  27.                 if (recent != w[0]) {
  28.                     string st = terminal.top(); terminal.pop();
  29.                     st += " " + recent + " " + terminal.top();
  30.                     terminal.pop(); terminal.push(grammar[st]);
  31.                 }
  32.                 else terminal.push(grammar[w[0]]);
  33.                 cout << "Reduce Operation Performed!\n";
  34.             } while (rel(sk.top(), ip) == '>');
  35.         }
  36.     }
  37.     return 0;
  38. }
  39.  
  40. /*
  41. Input:
  42. id * id + id
  43. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement