-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyntaxChecker.cpp
60 lines (55 loc) · 1.67 KB
/
SyntaxChecker.cpp
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
#include "SyntaxChecker.h"
#include <future>
#include <iostream>
#include <thread>
#include <vector>
SyntaxChecker::SyntaxChecker() {}
SyntaxChecker::~SyntaxChecker() {}
int SyntaxChecker::checkSyntax(const std::string& code) {
auto futureParens = std::async(&SyntaxChecker::checkBalancedParens, this, code);
auto futureQuotes = std::async(&SyntaxChecker::checkBalancedQuotes, this, code);
int ret = futureParens.get();
if (ret < 0) return ret;
ret = futureQuotes.get();
if (ret < 0) return ret;
return 0;
}
int SyntaxChecker::checkBalancedParens(const std::string& code) {
// Check balanced parentheses
std::vector<std::size_t> parenStack;
for (std::size_t i = 0; i < code.size(); ++i) {
if (code[i] == '(') {
parenStack.push_back(i);
} else if (code[i] == ')') {
if (parenStack.size() == 0) {
std::cout << "Unbalanced parenthesis at position " << i << ".\n";
return -1;
} else {
parenStack.pop_back();
}
}
}
if (parenStack.size() != 0) {
std::cout << "Unterminated parenthesis at position ";
for (std::size_t i = 0; i < parenStack.size(); ++i) {
std::cout << parenStack.at(i) << ", ";
}
std::cout << "\n";
return -1;
}
return 0;
}
int SyntaxChecker::checkBalancedQuotes(const std::string& code) {
int quoteCount = 0;
for (std::size_t i = 0; i < code.size(); ++i) {
if (code[i] == '"') {
quoteCount++;
}
}
if (quoteCount % 2) {
std::cout << "Error. Unbalanced quotes.\n";
return -1;
} else {
return 0;
}
}