Skip to content

Instantly share code, notes, and snippets.

@alesapin
Created April 8, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alesapin/5b0cd7d2160b9608cb974b77e49487ae to your computer and use it in GitHub Desktop.
Save alesapin/5b0cd7d2160b9608cb974b77e49487ae to your computer and use it in GitHub Desktop.
#include "parser.hpp"
#include <iostream>
static char getChar()
{
char c;
std::cin >> c;
return c;
}
void A::parse(char c, std::stack<std::string> & stk) {
if (c == 'd') {
stk.push("(4");
A().parse(getChar(), stk);
if (stk.top() == "(4")
stk.pop();
else
throw c;
}
}
void S::parse(char c, std::stack<std::string> & stk) {
if (c == 'a') {
stk.push("(2");
S().parse(getChar(), stk);
if (stk.top() == "(2")
stk.pop();
else
throw c;
} else if (c == 'd') {
stk.push("(3");
A().parse(getChar(), stk);
if (stk.top() == "(3")
stk.pop();
else
throw c;
}
else
throw c;
}
void P::parse(char c, std::stack<std::string> & stk) {
stk.push("(1");
S().parse(c, stk);
if (stk.top() == "(1")
stk.pop();
else
throw c;
if (c != '@')
throw c;
}
void Parser::analyze() {
try {
P().parse(getChar(), stk);
std::cout << "OK" << std::endl;
} catch(char c) {
std::cout << "Wrong symbol: " << c << std::endl;
}
}
std::stack<std::string> Parser::stk;
int main () {
Parser().analyze();
return 0;
}
#ifndef MY_PARSER_HPP_INCLUDED
#define MY_PARSER_HPP_INCLUDED
#include <string>
#include <stack>
class P {
public:
void parse(char c, std::stack<std::string> & stk);
};
class S {
public:
void parse(char c, std::stack<std::string> & stk);
};
class A {
public:
void parse(char c, std::stack<std::string> & stk);
};
class Parser {
static std::stack<std::string> stk;
public:
void analyze();
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment