|
| 1 | +import re |
| 2 | +from collections import defaultdict |
| 3 | + |
| 4 | +from sly.lex import Token |
| 5 | + |
| 6 | +from mindsdb_sql_parser.exceptions import ParsingException |
| 7 | +from mindsdb_sql_parser.ast import * |
| 8 | + |
| 9 | + |
| 10 | +class ErrorHandling: |
| 11 | + |
| 12 | + def __init__(self, lexer, parser): |
| 13 | + self.parser = parser |
| 14 | + self.lexer = lexer |
| 15 | + |
| 16 | + def process(self, error_info): |
| 17 | + self.tokens = [t for t in error_info['tokens'] if t is not None] |
| 18 | + self.bad_token = error_info['bad_token'] |
| 19 | + self.expected_tokens = error_info['expected_tokens'] |
| 20 | + |
| 21 | + if len(self.tokens) == 0: |
| 22 | + return 'Empty input' |
| 23 | + |
| 24 | + # show error location |
| 25 | + msgs = self.error_location() |
| 26 | + |
| 27 | + # suggestion |
| 28 | + suggestions = self.make_suggestion() |
| 29 | + |
| 30 | + if suggestions: |
| 31 | + prefix = 'Possible inputs: ' if len(suggestions) > 1 else 'Expected symbol: ' |
| 32 | + msgs.append(prefix + ', '.join([f'"{item}"' for item in suggestions])) |
| 33 | + return '\n'.join(msgs) |
| 34 | + |
| 35 | + def error_location(self): |
| 36 | + |
| 37 | + # restore query text |
| 38 | + lines_idx = defaultdict(str) |
| 39 | + |
| 40 | + # used + unused tokens |
| 41 | + for token in self.tokens: |
| 42 | + if token is None: |
| 43 | + continue |
| 44 | + line = lines_idx[token.lineno] |
| 45 | + |
| 46 | + if len(line) > token.index: |
| 47 | + line = line[: token.index] |
| 48 | + else: |
| 49 | + line = line.ljust(token.index) |
| 50 | + |
| 51 | + line += token.value |
| 52 | + lines_idx[token.lineno] = line |
| 53 | + |
| 54 | + msgs = [] |
| 55 | + |
| 56 | + # error message and location |
| 57 | + if self.bad_token is None: |
| 58 | + msgs.append('Syntax error, unexpected end of query:') |
| 59 | + error_len = 1 |
| 60 | + # last line |
| 61 | + error_line_num = list(lines_idx.keys())[-1] |
| 62 | + error_index = len(lines_idx[error_line_num]) |
| 63 | + else: |
| 64 | + msgs.append('Syntax error, unknown input:') |
| 65 | + error_len = len(self.bad_token.value) |
| 66 | + error_line_num = self.bad_token.lineno |
| 67 | + error_index = self.bad_token.index |
| 68 | + |
| 69 | + # shift lines indexes (it removes spaces from beginnings of the lines) |
| 70 | + lines = [] |
| 71 | + shift = 0 |
| 72 | + error_line = 0 |
| 73 | + for i, line_num in enumerate(lines_idx.keys()): |
| 74 | + if line_num == error_line_num: |
| 75 | + error_index -= shift |
| 76 | + error_line = i |
| 77 | + |
| 78 | + line = lines_idx[line_num] |
| 79 | + lines.append(line[shift:]) |
| 80 | + shift = len(line) |
| 81 | + |
| 82 | + # add source code |
| 83 | + first_line = error_line - 2 if error_line > 1 else 0 |
| 84 | + for line in lines[first_line: error_line + 1]: |
| 85 | + msgs.append('>' + line) |
| 86 | + |
| 87 | + # error position |
| 88 | + msgs.append('-' * (error_index + 1) + '^' * error_len) |
| 89 | + return msgs |
| 90 | + |
| 91 | + def make_suggestion(self): |
| 92 | + if len(self.expected_tokens) == 0: |
| 93 | + return [] |
| 94 | + |
| 95 | + # find error index |
| 96 | + error_index = None |
| 97 | + for i, token in enumerate(self.tokens): |
| 98 | + if token is self.bad_token : |
| 99 | + error_index = i |
| 100 | + |
| 101 | + expected = {} # value: token |
| 102 | + |
| 103 | + for token_name in self.expected_tokens: |
| 104 | + value = getattr(self.lexer, token_name, None) |
| 105 | + if token_name == 'ID': |
| 106 | + # a lot of other tokens could be ID |
| 107 | + expected = {'[identifier]': token_name} |
| 108 | + break |
| 109 | + elif token_name in ('FLOAT', 'INTEGER'): |
| 110 | + expected['[number]'] = token_name |
| 111 | + |
| 112 | + elif token_name in ('DQUOTE_STRING', 'QUOTE_STRING'): |
| 113 | + expected['[string]'] = token_name |
| 114 | + |
| 115 | + elif isinstance(value, str): |
| 116 | + value = value.replace('\\b', '').replace('\\', '') |
| 117 | + |
| 118 | + # doesn't content regexp |
| 119 | + if '\\s' not in value and '|' not in value: |
| 120 | + expected[value] = token_name |
| 121 | + |
| 122 | + suggestions = [] |
| 123 | + if len(expected) == 1: |
| 124 | + # use only it |
| 125 | + first_value = list(expected.keys())[0] |
| 126 | + suggestions.append(first_value) |
| 127 | + |
| 128 | + elif 1 < len(expected) < 20: |
| 129 | + if self.bad_token is None: |
| 130 | + # if this is the end of query, just show next expected keywords |
| 131 | + return list(expected.keys()) |
| 132 | + |
| 133 | + # not every suggestion satisfy the end of the query. we have to check if it works |
| 134 | + for value, token_name in expected.items(): |
| 135 | + # make up a token |
| 136 | + token = Token() |
| 137 | + token.type = token_name |
| 138 | + token.value = value |
| 139 | + token.end = 0 |
| 140 | + token.index = 0 |
| 141 | + token.lineno = 0 |
| 142 | + |
| 143 | + # try to add token |
| 144 | + tokens2 = self.tokens[:error_index] + [token] + self.tokens[error_index:] |
| 145 | + if self.query_is_valid(tokens2): |
| 146 | + suggestions.append(value) |
| 147 | + continue |
| 148 | + |
| 149 | + # try to replace token |
| 150 | + tokens2 = self.tokens[:error_index - 1] + [token] + self.tokens[error_index:] |
| 151 | + if self.query_is_valid(tokens2): |
| 152 | + suggestions.append(value) |
| 153 | + continue |
| 154 | + |
| 155 | + return suggestions |
| 156 | + |
| 157 | + def query_is_valid(self, tokens): |
| 158 | + # try to parse list of tokens |
| 159 | + |
| 160 | + ast = self.parser.parse(iter(tokens)) |
| 161 | + return ast is not None |
| 162 | + |
| 163 | + |
| 164 | +def parse_sql(sql): |
| 165 | + from mindsdb_sql_parser.lexer import MindsDBLexer |
| 166 | + from mindsdb_sql_parser.parser import MindsDBParser |
| 167 | + lexer, parser = MindsDBLexer(), MindsDBParser() |
| 168 | + |
| 169 | + # remove ending semicolon and spaces |
| 170 | + sql = re.sub(r'[\s;]+$', '', sql) |
| 171 | + |
| 172 | + tokens = lexer.tokenize(sql) |
| 173 | + ast = parser.parse(tokens) |
| 174 | + |
| 175 | + if ast is None: |
| 176 | + |
| 177 | + eh = ErrorHandling(lexer, parser) |
| 178 | + message = eh.process(parser.error_info) |
| 179 | + |
| 180 | + raise ParsingException(message) |
| 181 | + |
| 182 | + return ast |
0 commit comments