1#include <Parsers/TokenIterator.h>
2
3
4namespace DB
5{
6
7UnmatchedParentheses checkUnmatchedParentheses(TokenIterator begin, Token * last)
8{
9 /// We have just two kind of parentheses: () and [].
10 UnmatchedParentheses stack;
11
12 for (TokenIterator it = begin; it.isValid() && &it.get() <= last; ++it)
13 {
14 if (it->type == TokenType::OpeningRoundBracket || it->type == TokenType::OpeningSquareBracket)
15 {
16 stack.push_back(*it);
17 }
18 else if (it->type == TokenType::ClosingRoundBracket || it->type == TokenType::ClosingSquareBracket)
19 {
20 if (stack.empty())
21 {
22 /// Excessive closing bracket.
23 stack.push_back(*it);
24 return stack;
25 }
26 else if ((stack.back().type == TokenType::OpeningRoundBracket && it->type == TokenType::ClosingRoundBracket)
27 || (stack.back().type == TokenType::OpeningSquareBracket && it->type == TokenType::ClosingSquareBracket))
28 {
29 /// Valid match.
30 stack.pop_back();
31 }
32 else
33 {
34 /// Closing bracket type doesn't match opening bracket type.
35 stack.push_back(*it);
36 return stack;
37 }
38 }
39 }
40
41 /// If stack is not empty, we have unclosed brackets.
42 return stack;
43}
44
45}
46