You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

462 lines
12 KiB

36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
36 years ago
36 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
bpo-33416: Add end positions to Python AST (GH-11605) The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
7 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
  1. /* Parser implementation */
  2. /* For a description, see the comments at end of this file */
  3. /* XXX To do: error recovery */
  4. #include "Python.h"
  5. #include "token.h"
  6. #include "grammar.h"
  7. #include "node.h"
  8. #include "parser.h"
  9. #include "errcode.h"
  10. #include "graminit.h"
  11. #ifdef Py_DEBUG
  12. extern int Py_DebugFlag;
  13. #define D(x) if (!Py_DebugFlag); else x
  14. #else
  15. #define D(x)
  16. #endif
  17. /* STACK DATA TYPE */
  18. static void s_reset(stack *);
  19. static void
  20. s_reset(stack *s)
  21. {
  22. s->s_top = &s->s_base[MAXSTACK];
  23. }
  24. #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK])
  25. static int
  26. s_push(stack *s, const dfa *d, node *parent)
  27. {
  28. stackentry *top;
  29. if (s->s_top == s->s_base) {
  30. fprintf(stderr, "s_push: parser stack overflow\n");
  31. return E_NOMEM;
  32. }
  33. top = --s->s_top;
  34. top->s_dfa = d;
  35. top->s_parent = parent;
  36. top->s_state = 0;
  37. return 0;
  38. }
  39. #ifdef Py_DEBUG
  40. static void
  41. s_pop(stack *s)
  42. {
  43. if (s_empty(s))
  44. Py_FatalError("s_pop: parser stack underflow -- FATAL");
  45. s->s_top++;
  46. }
  47. #else /* !Py_DEBUG */
  48. #define s_pop(s) (s)->s_top++
  49. #endif
  50. /* PARSER CREATION */
  51. parser_state *
  52. PyParser_New(grammar *g, int start)
  53. {
  54. parser_state *ps;
  55. if (!g->g_accel)
  56. PyGrammar_AddAccelerators(g);
  57. ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state));
  58. if (ps == NULL)
  59. return NULL;
  60. ps->p_grammar = g;
  61. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  62. ps->p_flags = 0;
  63. #endif
  64. ps->p_tree = PyNode_New(start);
  65. if (ps->p_tree == NULL) {
  66. PyMem_FREE(ps);
  67. return NULL;
  68. }
  69. s_reset(&ps->p_stack);
  70. (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree);
  71. return ps;
  72. }
  73. void
  74. PyParser_Delete(parser_state *ps)
  75. {
  76. /* NB If you want to save the parse tree,
  77. you must set p_tree to NULL before calling delparser! */
  78. PyNode_Free(ps->p_tree);
  79. PyMem_FREE(ps);
  80. }
  81. /* PARSER STACK OPERATIONS */
  82. static int
  83. shift(stack *s, int type, char *str, int newstate, int lineno, int col_offset,
  84. int end_lineno, int end_col_offset)
  85. {
  86. int err;
  87. assert(!s_empty(s));
  88. err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset,
  89. end_lineno, end_col_offset);
  90. if (err)
  91. return err;
  92. s->s_top->s_state = newstate;
  93. return 0;
  94. }
  95. static int
  96. push(stack *s, int type, const dfa *d, int newstate, int lineno, int col_offset,
  97. int end_lineno, int end_col_offset)
  98. {
  99. int err;
  100. node *n;
  101. n = s->s_top->s_parent;
  102. assert(!s_empty(s));
  103. err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset,
  104. end_lineno, end_col_offset);
  105. if (err)
  106. return err;
  107. s->s_top->s_state = newstate;
  108. return s_push(s, d, CHILD(n, NCH(n)-1));
  109. }
  110. /* PARSER PROPER */
  111. static int
  112. classify(parser_state *ps, int type, const char *str)
  113. {
  114. grammar *g = ps->p_grammar;
  115. int n = g->g_ll.ll_nlabels;
  116. if (type == NAME) {
  117. const label *l = g->g_ll.ll_label;
  118. int i;
  119. for (i = n; i > 0; i--, l++) {
  120. if (l->lb_type != NAME || l->lb_str == NULL ||
  121. l->lb_str[0] != str[0] ||
  122. strcmp(l->lb_str, str) != 0)
  123. continue;
  124. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  125. #if 0
  126. /* Leaving this in as an example */
  127. if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) {
  128. if (str[0] == 'w' && strcmp(str, "with") == 0)
  129. break; /* not a keyword yet */
  130. else if (str[0] == 'a' && strcmp(str, "as") == 0)
  131. break; /* not a keyword yet */
  132. }
  133. #endif
  134. #endif
  135. D(printf("It's a keyword\n"));
  136. return n - i;
  137. }
  138. }
  139. {
  140. const label *l = g->g_ll.ll_label;
  141. int i;
  142. for (i = n; i > 0; i--, l++) {
  143. if (l->lb_type == type && l->lb_str == NULL) {
  144. D(printf("It's a token we know\n"));
  145. return n - i;
  146. }
  147. }
  148. }
  149. D(printf("Illegal token\n"));
  150. return -1;
  151. }
  152. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  153. #if 0
  154. /* Leaving this in as an example */
  155. static void
  156. future_hack(parser_state *ps)
  157. {
  158. node *n = ps->p_stack.s_top->s_parent;
  159. node *ch, *cch;
  160. int i;
  161. /* from __future__ import ..., must have at least 4 children */
  162. n = CHILD(n, 0);
  163. if (NCH(n) < 4)
  164. return;
  165. ch = CHILD(n, 0);
  166. if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0)
  167. return;
  168. ch = CHILD(n, 1);
  169. if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
  170. strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
  171. return;
  172. ch = CHILD(n, 3);
  173. /* ch can be a star, a parenthesis or import_as_names */
  174. if (TYPE(ch) == STAR)
  175. return;
  176. if (TYPE(ch) == LPAR)
  177. ch = CHILD(n, 4);
  178. for (i = 0; i < NCH(ch); i += 2) {
  179. cch = CHILD(ch, i);
  180. if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) {
  181. char *str_ch = STR(CHILD(cch, 0));
  182. if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) {
  183. ps->p_flags |= CO_FUTURE_WITH_STATEMENT;
  184. } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) {
  185. ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
  186. } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) {
  187. ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
  188. }
  189. }
  190. }
  191. }
  192. #endif
  193. #endif /* future keyword */
  194. int
  195. PyParser_AddToken(parser_state *ps, int type, char *str,
  196. int lineno, int col_offset,
  197. int end_lineno, int end_col_offset,
  198. int *expected_ret)
  199. {
  200. int ilabel;
  201. int err;
  202. D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
  203. /* Find out which label this token is */
  204. ilabel = classify(ps, type, str);
  205. if (ilabel < 0)
  206. return E_SYNTAX;
  207. /* Loop until the token is shifted or an error occurred */
  208. for (;;) {
  209. /* Fetch the current dfa and state */
  210. const dfa *d = ps->p_stack.s_top->s_dfa;
  211. state *s = &d->d_state[ps->p_stack.s_top->s_state];
  212. D(printf(" DFA '%s', state %d:",
  213. d->d_name, ps->p_stack.s_top->s_state));
  214. /* Check accelerator */
  215. if (s->s_lower <= ilabel && ilabel < s->s_upper) {
  216. int x = s->s_accel[ilabel - s->s_lower];
  217. if (x != -1) {
  218. if (x & (1<<7)) {
  219. /* Push non-terminal */
  220. int nt = (x >> 8) + NT_OFFSET;
  221. int arrow = x & ((1<<7)-1);
  222. if (nt == func_body_suite && !(ps->p_flags & PyCF_TYPE_COMMENTS)) {
  223. /* When parsing type comments is not requested,
  224. we can provide better errors about bad indentation
  225. by using 'suite' for the body of a funcdef */
  226. D(printf(" [switch func_body_suite to suite]"));
  227. nt = suite;
  228. }
  229. const dfa *d1 = PyGrammar_FindDFA(
  230. ps->p_grammar, nt);
  231. if ((err = push(&ps->p_stack, nt, d1,
  232. arrow, lineno, col_offset,
  233. end_lineno, end_col_offset)) > 0) {
  234. D(printf(" MemError: push\n"));
  235. return err;
  236. }
  237. D(printf(" Push '%s'\n", d1->d_name));
  238. continue;
  239. }
  240. /* Shift the token */
  241. if ((err = shift(&ps->p_stack, type, str,
  242. x, lineno, col_offset,
  243. end_lineno, end_col_offset)) > 0) {
  244. D(printf(" MemError: shift.\n"));
  245. return err;
  246. }
  247. D(printf(" Shift.\n"));
  248. /* Pop while we are in an accept-only state */
  249. while (s = &d->d_state
  250. [ps->p_stack.s_top->s_state],
  251. s->s_accept && s->s_narcs == 1) {
  252. D(printf(" DFA '%s', state %d: "
  253. "Direct pop.\n",
  254. d->d_name,
  255. ps->p_stack.s_top->s_state));
  256. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  257. #if 0
  258. if (d->d_name[0] == 'i' &&
  259. strcmp(d->d_name,
  260. "import_stmt") == 0)
  261. future_hack(ps);
  262. #endif
  263. #endif
  264. s_pop(&ps->p_stack);
  265. if (s_empty(&ps->p_stack)) {
  266. D(printf(" ACCEPT.\n"));
  267. return E_DONE;
  268. }
  269. d = ps->p_stack.s_top->s_dfa;
  270. }
  271. return E_OK;
  272. }
  273. }
  274. if (s->s_accept) {
  275. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  276. #if 0
  277. if (d->d_name[0] == 'i' &&
  278. strcmp(d->d_name, "import_stmt") == 0)
  279. future_hack(ps);
  280. #endif
  281. #endif
  282. /* Pop this dfa and try again */
  283. s_pop(&ps->p_stack);
  284. D(printf(" Pop ...\n"));
  285. if (s_empty(&ps->p_stack)) {
  286. D(printf(" Error: bottom of stack.\n"));
  287. return E_SYNTAX;
  288. }
  289. continue;
  290. }
  291. /* Stuck, report syntax error */
  292. D(printf(" Error.\n"));
  293. if (expected_ret) {
  294. if (s->s_lower == s->s_upper - 1) {
  295. /* Only one possible expected token */
  296. *expected_ret = ps->p_grammar->
  297. g_ll.ll_label[s->s_lower].lb_type;
  298. }
  299. else
  300. *expected_ret = -1;
  301. }
  302. return E_SYNTAX;
  303. }
  304. }
  305. #ifdef Py_DEBUG
  306. /* DEBUG OUTPUT */
  307. void
  308. dumptree(grammar *g, node *n)
  309. {
  310. int i;
  311. if (n == NULL)
  312. printf("NIL");
  313. else {
  314. label l;
  315. l.lb_type = TYPE(n);
  316. l.lb_str = STR(n);
  317. printf("%s", PyGrammar_LabelRepr(&l));
  318. if (ISNONTERMINAL(TYPE(n))) {
  319. printf("(");
  320. for (i = 0; i < NCH(n); i++) {
  321. if (i > 0)
  322. printf(",");
  323. dumptree(g, CHILD(n, i));
  324. }
  325. printf(")");
  326. }
  327. }
  328. }
  329. void
  330. showtree(grammar *g, node *n)
  331. {
  332. int i;
  333. if (n == NULL)
  334. return;
  335. if (ISNONTERMINAL(TYPE(n))) {
  336. for (i = 0; i < NCH(n); i++)
  337. showtree(g, CHILD(n, i));
  338. }
  339. else if (ISTERMINAL(TYPE(n))) {
  340. printf("%s", _PyParser_TokenNames[TYPE(n)]);
  341. if (TYPE(n) == NUMBER || TYPE(n) == NAME)
  342. printf("(%s)", STR(n));
  343. printf(" ");
  344. }
  345. else
  346. printf("? ");
  347. }
  348. void
  349. printtree(parser_state *ps)
  350. {
  351. if (Py_DebugFlag) {
  352. printf("Parse tree:\n");
  353. dumptree(ps->p_grammar, ps->p_tree);
  354. printf("\n");
  355. printf("Tokens:\n");
  356. showtree(ps->p_grammar, ps->p_tree);
  357. printf("\n");
  358. }
  359. printf("Listing:\n");
  360. PyNode_ListTree(ps->p_tree);
  361. printf("\n");
  362. }
  363. #endif /* Py_DEBUG */
  364. /*
  365. Description
  366. -----------
  367. The parser's interface is different than usual: the function addtoken()
  368. must be called for each token in the input. This makes it possible to
  369. turn it into an incremental parsing system later. The parsing system
  370. constructs a parse tree as it goes.
  371. A parsing rule is represented as a Deterministic Finite-state Automaton
  372. (DFA). A node in a DFA represents a state of the parser; an arc represents
  373. a transition. Transitions are either labeled with terminal symbols or
  374. with non-terminals. When the parser decides to follow an arc labeled
  375. with a non-terminal, it is invoked recursively with the DFA representing
  376. the parsing rule for that as its initial state; when that DFA accepts,
  377. the parser that invoked it continues. The parse tree constructed by the
  378. recursively called parser is inserted as a child in the current parse tree.
  379. The DFA's can be constructed automatically from a more conventional
  380. language description. An extended LL(1) grammar (ELL(1)) is suitable.
  381. Certain restrictions make the parser's life easier: rules that can produce
  382. the empty string should be outlawed (there are other ways to put loops
  383. or optional parts in the language). To avoid the need to construct
  384. FIRST sets, we can require that all but the last alternative of a rule
  385. (really: arc going out of a DFA's state) must begin with a terminal
  386. symbol.
  387. As an example, consider this grammar:
  388. expr: term (OP term)*
  389. term: CONSTANT | '(' expr ')'
  390. The DFA corresponding to the rule for expr is:
  391. ------->.---term-->.------->
  392. ^ |
  393. | |
  394. \----OP----/
  395. The parse tree generated for the input a+b is:
  396. (expr: (term: (NAME: a)), (OP: +), (term: (NAME: b)))
  397. */