pegen_errors.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #include <Python.h>
  2. #include <errcode.h>
  3. #include "tokenizer.h"
  4. #include "pegen.h"
  5. // TOKENIZER ERRORS
  6. void
  7. _PyPegen_raise_tokenizer_init_error(PyObject *filename)
  8. {
  9. if (!(PyErr_ExceptionMatches(PyExc_LookupError)
  10. || PyErr_ExceptionMatches(PyExc_SyntaxError)
  11. || PyErr_ExceptionMatches(PyExc_ValueError)
  12. || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
  13. return;
  14. }
  15. PyObject *errstr = NULL;
  16. PyObject *tuple = NULL;
  17. PyObject *type;
  18. PyObject *value;
  19. PyObject *tback;
  20. PyErr_Fetch(&type, &value, &tback);
  21. errstr = PyObject_Str(value);
  22. if (!errstr) {
  23. goto error;
  24. }
  25. PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
  26. if (!tmp) {
  27. goto error;
  28. }
  29. tuple = PyTuple_Pack(2, errstr, tmp);
  30. Py_DECREF(tmp);
  31. if (!value) {
  32. goto error;
  33. }
  34. PyErr_SetObject(PyExc_SyntaxError, tuple);
  35. error:
  36. Py_XDECREF(type);
  37. Py_XDECREF(value);
  38. Py_XDECREF(tback);
  39. Py_XDECREF(errstr);
  40. Py_XDECREF(tuple);
  41. }
  42. static inline void
  43. raise_unclosed_parentheses_error(Parser *p) {
  44. int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
  45. int error_col = p->tok->parencolstack[p->tok->level-1];
  46. RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
  47. error_lineno, error_col, error_lineno, -1,
  48. "'%c' was never closed",
  49. p->tok->parenstack[p->tok->level-1]);
  50. }
  51. int
  52. _Pypegen_tokenizer_error(Parser *p)
  53. {
  54. if (PyErr_Occurred()) {
  55. return -1;
  56. }
  57. const char *msg = NULL;
  58. PyObject* errtype = PyExc_SyntaxError;
  59. Py_ssize_t col_offset = -1;
  60. p->error_indicator = 1;
  61. switch (p->tok->done) {
  62. case E_TOKEN:
  63. msg = "invalid token";
  64. break;
  65. case E_EOF:
  66. if (p->tok->level) {
  67. raise_unclosed_parentheses_error(p);
  68. } else {
  69. RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
  70. }
  71. return -1;
  72. case E_DEDENT:
  73. RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
  74. return -1;
  75. case E_INTR:
  76. if (!PyErr_Occurred()) {
  77. PyErr_SetNone(PyExc_KeyboardInterrupt);
  78. }
  79. return -1;
  80. case E_NOMEM:
  81. PyErr_NoMemory();
  82. return -1;
  83. case E_TABSPACE:
  84. errtype = PyExc_TabError;
  85. msg = "inconsistent use of tabs and spaces in indentation";
  86. break;
  87. case E_TOODEEP:
  88. errtype = PyExc_IndentationError;
  89. msg = "too many levels of indentation";
  90. break;
  91. case E_LINECONT: {
  92. col_offset = p->tok->cur - p->tok->buf - 1;
  93. msg = "unexpected character after line continuation character";
  94. break;
  95. }
  96. case E_COLUMNOVERFLOW:
  97. PyErr_SetString(PyExc_OverflowError,
  98. "Parser column offset overflow - source line is too big");
  99. return -1;
  100. default:
  101. msg = "unknown parsing error";
  102. }
  103. RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno,
  104. col_offset >= 0 ? col_offset : 0,
  105. p->tok->lineno, -1, msg);
  106. return -1;
  107. }
  108. int
  109. _Pypegen_raise_decode_error(Parser *p)
  110. {
  111. assert(PyErr_Occurred());
  112. const char *errtype = NULL;
  113. if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
  114. errtype = "unicode error";
  115. }
  116. else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
  117. errtype = "value error";
  118. }
  119. if (errtype) {
  120. PyObject *type;
  121. PyObject *value;
  122. PyObject *tback;
  123. PyObject *errstr;
  124. PyErr_Fetch(&type, &value, &tback);
  125. errstr = PyObject_Str(value);
  126. if (errstr) {
  127. RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
  128. Py_DECREF(errstr);
  129. }
  130. else {
  131. PyErr_Clear();
  132. RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
  133. }
  134. Py_XDECREF(type);
  135. Py_XDECREF(value);
  136. Py_XDECREF(tback);
  137. }
  138. return -1;
  139. }
  140. static int
  141. _PyPegen_tokenize_full_source_to_check_for_errors(Parser *p) {
  142. // Tokenize the whole input to see if there are any tokenization
  143. // errors such as mistmatching parentheses. These will get priority
  144. // over generic syntax errors only if the line number of the error is
  145. // before the one that we had for the generic error.
  146. // We don't want to tokenize to the end for interactive input
  147. if (p->tok->prompt != NULL) {
  148. return 0;
  149. }
  150. PyObject *type, *value, *traceback;
  151. PyErr_Fetch(&type, &value, &traceback);
  152. Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
  153. Py_ssize_t current_err_line = current_token->lineno;
  154. int ret = 0;
  155. struct token new_token;
  156. _PyToken_Init(&new_token);
  157. for (;;) {
  158. switch (_PyTokenizer_Get(p->tok, &new_token)) {
  159. case ERRORTOKEN:
  160. if (PyErr_Occurred()) {
  161. ret = -1;
  162. goto exit;
  163. }
  164. if (p->tok->level != 0) {
  165. int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
  166. if (current_err_line > error_lineno) {
  167. raise_unclosed_parentheses_error(p);
  168. ret = -1;
  169. goto exit;
  170. }
  171. }
  172. break;
  173. case ENDMARKER:
  174. break;
  175. default:
  176. continue;
  177. }
  178. break;
  179. }
  180. exit:
  181. _PyToken_Free(&new_token);
  182. // If we're in an f-string, we want the syntax error in the expression part
  183. // to propagate, so that tokenizer errors (like expecting '}') that happen afterwards
  184. // do not swallow it.
  185. if (PyErr_Occurred() && p->tok->tok_mode_stack_index <= 0) {
  186. Py_XDECREF(value);
  187. Py_XDECREF(type);
  188. Py_XDECREF(traceback);
  189. } else {
  190. PyErr_Restore(type, value, traceback);
  191. }
  192. return ret;
  193. }
  194. // PARSER ERRORS
  195. void *
  196. _PyPegen_raise_error(Parser *p, PyObject *errtype, int use_mark, const char *errmsg, ...)
  197. {
  198. // Bail out if we already have an error set.
  199. if (p->error_indicator && PyErr_Occurred()) {
  200. return NULL;
  201. }
  202. if (p->fill == 0) {
  203. va_list va;
  204. va_start(va, errmsg);
  205. _PyPegen_raise_error_known_location(p, errtype, 0, 0, 0, -1, errmsg, va);
  206. va_end(va);
  207. return NULL;
  208. }
  209. if (use_mark && p->mark == p->fill && _PyPegen_fill_token(p) < 0) {
  210. p->error_indicator = 1;
  211. return NULL;
  212. }
  213. Token *t = p->known_err_token != NULL
  214. ? p->known_err_token
  215. : p->tokens[use_mark ? p->mark : p->fill - 1];
  216. Py_ssize_t col_offset;
  217. Py_ssize_t end_col_offset = -1;
  218. if (t->col_offset == -1) {
  219. if (p->tok->cur == p->tok->buf) {
  220. col_offset = 0;
  221. } else {
  222. const char* start = p->tok->buf ? p->tok->line_start : p->tok->buf;
  223. col_offset = Py_SAFE_DOWNCAST(p->tok->cur - start, intptr_t, int);
  224. }
  225. } else {
  226. col_offset = t->col_offset + 1;
  227. }
  228. if (t->end_col_offset != -1) {
  229. end_col_offset = t->end_col_offset + 1;
  230. }
  231. va_list va;
  232. va_start(va, errmsg);
  233. _PyPegen_raise_error_known_location(p, errtype, t->lineno, col_offset, t->end_lineno, end_col_offset, errmsg, va);
  234. va_end(va);
  235. return NULL;
  236. }
  237. static PyObject *
  238. get_error_line_from_tokenizer_buffers(Parser *p, Py_ssize_t lineno)
  239. {
  240. /* If the file descriptor is interactive, the source lines of the current
  241. * (multi-line) statement are stored in p->tok->interactive_src_start.
  242. * If not, we're parsing from a string, which means that the whole source
  243. * is stored in p->tok->str. */
  244. assert((p->tok->fp == NULL && p->tok->str != NULL) || p->tok->fp != NULL);
  245. char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
  246. if (cur_line == NULL) {
  247. assert(p->tok->fp_interactive);
  248. // We can reach this point if the tokenizer buffers for interactive source have not been
  249. // initialized because we failed to decode the original source with the given locale.
  250. return PyUnicode_FromStringAndSize("", 0);
  251. }
  252. Py_ssize_t relative_lineno = p->starting_lineno ? lineno - p->starting_lineno + 1 : lineno;
  253. const char* buf_end = p->tok->fp_interactive ? p->tok->interactive_src_end : p->tok->inp;
  254. if (buf_end < cur_line) {
  255. buf_end = cur_line + strlen(cur_line);
  256. }
  257. for (int i = 0; i < relative_lineno - 1; i++) {
  258. char *new_line = strchr(cur_line, '\n');
  259. // The assert is here for debug builds but the conditional that
  260. // follows is there so in release builds we do not crash at the cost
  261. // to report a potentially wrong line.
  262. assert(new_line != NULL && new_line + 1 < buf_end);
  263. if (new_line == NULL || new_line + 1 > buf_end) {
  264. break;
  265. }
  266. cur_line = new_line + 1;
  267. }
  268. char *next_newline;
  269. if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
  270. next_newline = cur_line + strlen(cur_line);
  271. }
  272. return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
  273. }
  274. void *
  275. _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
  276. Py_ssize_t lineno, Py_ssize_t col_offset,
  277. Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
  278. const char *errmsg, va_list va)
  279. {
  280. // Bail out if we already have an error set.
  281. if (p->error_indicator && PyErr_Occurred()) {
  282. return NULL;
  283. }
  284. PyObject *value = NULL;
  285. PyObject *errstr = NULL;
  286. PyObject *error_line = NULL;
  287. PyObject *tmp = NULL;
  288. p->error_indicator = 1;
  289. if (end_lineno == CURRENT_POS) {
  290. end_lineno = p->tok->lineno;
  291. }
  292. if (end_col_offset == CURRENT_POS) {
  293. end_col_offset = p->tok->cur - p->tok->line_start;
  294. }
  295. errstr = PyUnicode_FromFormatV(errmsg, va);
  296. if (!errstr) {
  297. goto error;
  298. }
  299. if (p->tok->fp_interactive && p->tok->interactive_src_start != NULL) {
  300. error_line = get_error_line_from_tokenizer_buffers(p, lineno);
  301. }
  302. else if (p->start_rule == Py_file_input) {
  303. error_line = _PyErr_ProgramDecodedTextObject(p->tok->filename,
  304. (int) lineno, p->tok->encoding);
  305. }
  306. if (!error_line) {
  307. /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
  308. then we need to find the error line from some other source, because
  309. p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
  310. failed or we're parsing from a string or the REPL. There's a third edge case where
  311. we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
  312. `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
  313. does not physically exist */
  314. assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
  315. if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) {
  316. Py_ssize_t size = p->tok->inp - p->tok->buf;
  317. error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
  318. }
  319. else if (p->tok->fp == NULL || p->tok->fp == stdin) {
  320. error_line = get_error_line_from_tokenizer_buffers(p, lineno);
  321. }
  322. else {
  323. error_line = PyUnicode_FromStringAndSize("", 0);
  324. }
  325. if (!error_line) {
  326. goto error;
  327. }
  328. }
  329. Py_ssize_t col_number = col_offset;
  330. Py_ssize_t end_col_number = end_col_offset;
  331. col_number = _PyPegen_byte_offset_to_character_offset(error_line, col_offset);
  332. if (col_number < 0) {
  333. goto error;
  334. }
  335. if (end_col_offset > 0) {
  336. end_col_number = _PyPegen_byte_offset_to_character_offset(error_line, end_col_offset);
  337. if (end_col_number < 0) {
  338. goto error;
  339. }
  340. }
  341. tmp = Py_BuildValue("(OnnNnn)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
  342. if (!tmp) {
  343. goto error;
  344. }
  345. value = PyTuple_Pack(2, errstr, tmp);
  346. Py_DECREF(tmp);
  347. if (!value) {
  348. goto error;
  349. }
  350. PyErr_SetObject(errtype, value);
  351. Py_DECREF(errstr);
  352. Py_DECREF(value);
  353. return NULL;
  354. error:
  355. Py_XDECREF(errstr);
  356. Py_XDECREF(error_line);
  357. return NULL;
  358. }
  359. void
  360. _Pypegen_set_syntax_error(Parser* p, Token* last_token) {
  361. // Existing sintax error
  362. if (PyErr_Occurred()) {
  363. // Prioritize tokenizer errors to custom syntax errors raised
  364. // on the second phase only if the errors come from the parser.
  365. int is_tok_ok = (p->tok->done == E_DONE || p->tok->done == E_OK);
  366. if (is_tok_ok && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
  367. _PyPegen_tokenize_full_source_to_check_for_errors(p);
  368. }
  369. // Propagate the existing syntax error.
  370. return;
  371. }
  372. // Initialization error
  373. if (p->fill == 0) {
  374. RAISE_SYNTAX_ERROR("error at start before reading any input");
  375. }
  376. // Parser encountered EOF (End of File) unexpectedtly
  377. if (last_token->type == ERRORTOKEN && p->tok->done == E_EOF) {
  378. if (p->tok->level) {
  379. raise_unclosed_parentheses_error(p);
  380. } else {
  381. RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
  382. }
  383. return;
  384. }
  385. // Indentation error in the tokenizer
  386. if (last_token->type == INDENT || last_token->type == DEDENT) {
  387. RAISE_INDENTATION_ERROR(last_token->type == INDENT ? "unexpected indent" : "unexpected unindent");
  388. return;
  389. }
  390. // Unknown error (generic case)
  391. // Use the last token we found on the first pass to avoid reporting
  392. // incorrect locations for generic syntax errors just because we reached
  393. // further away when trying to find specific syntax errors in the second
  394. // pass.
  395. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
  396. // _PyPegen_tokenize_full_source_to_check_for_errors will override the existing
  397. // generic SyntaxError we just raised if errors are found.
  398. _PyPegen_tokenize_full_source_to_check_for_errors(p);
  399. }
  400. void
  401. _Pypegen_stack_overflow(Parser *p)
  402. {
  403. p->error_indicator = 1;
  404. PyErr_SetString(PyExc_MemoryError,
  405. "Parser stack overflowed - Python source too complex to parse");
  406. }