/Parser/parser.c

http://unladen-swallow.googlecode.com/ · C · 436 lines · 315 code · 54 blank · 67 comment · 98 complexity · 1da01b7fe4e60020e3d010c25c46a177 MD5 · raw file

  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 "pgenheaders.h"
  6. #include "token.h"
  7. #include "grammar.h"
  8. #include "node.h"
  9. #include "parser.h"
  10. #include "errcode.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(register stack *s, dfa *d, node *parent)
  27. {
  28. register 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(register 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(register stack *s, int type, char *str, int newstate, int lineno, int col_offset)
  84. {
  85. int err;
  86. assert(!s_empty(s));
  87. err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset);
  88. if (err)
  89. return err;
  90. s->s_top->s_state = newstate;
  91. return 0;
  92. }
  93. static int
  94. push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset)
  95. {
  96. int err;
  97. register node *n;
  98. n = s->s_top->s_parent;
  99. assert(!s_empty(s));
  100. err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset);
  101. if (err)
  102. return err;
  103. s->s_top->s_state = newstate;
  104. return s_push(s, d, CHILD(n, NCH(n)-1));
  105. }
  106. /* PARSER PROPER */
  107. static int
  108. classify(parser_state *ps, int type, char *str)
  109. {
  110. grammar *g = ps->p_grammar;
  111. register int n = g->g_ll.ll_nlabels;
  112. if (type == NAME) {
  113. register char *s = str;
  114. register label *l = g->g_ll.ll_label;
  115. register int i;
  116. for (i = n; i > 0; i--, l++) {
  117. if (l->lb_type != NAME || l->lb_str == NULL ||
  118. l->lb_str[0] != s[0] ||
  119. strcmp(l->lb_str, s) != 0)
  120. continue;
  121. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  122. if (ps->p_flags & CO_FUTURE_PRINT_FUNCTION &&
  123. s[0] == 'p' && strcmp(s, "print") == 0) {
  124. break; /* no longer a keyword */
  125. }
  126. #endif
  127. D(printf("It's a keyword\n"));
  128. return n - i;
  129. }
  130. }
  131. {
  132. register label *l = g->g_ll.ll_label;
  133. register int i;
  134. for (i = n; i > 0; i--, l++) {
  135. if (l->lb_type == type && l->lb_str == NULL) {
  136. D(printf("It's a token we know\n"));
  137. return n - i;
  138. }
  139. }
  140. }
  141. D(printf("Illegal token\n"));
  142. return -1;
  143. }
  144. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  145. static void
  146. future_hack(parser_state *ps)
  147. {
  148. node *n = ps->p_stack.s_top->s_parent;
  149. node *ch, *cch;
  150. int i;
  151. /* from __future__ import ..., must have at least 4 children */
  152. n = CHILD(n, 0);
  153. if (NCH(n) < 4)
  154. return;
  155. ch = CHILD(n, 0);
  156. if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0)
  157. return;
  158. ch = CHILD(n, 1);
  159. if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
  160. strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
  161. return;
  162. ch = CHILD(n, 3);
  163. /* ch can be a star, a parenthesis or import_as_names */
  164. if (TYPE(ch) == STAR)
  165. return;
  166. if (TYPE(ch) == LPAR)
  167. ch = CHILD(n, 4);
  168. for (i = 0; i < NCH(ch); i += 2) {
  169. cch = CHILD(ch, i);
  170. if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) {
  171. char *str_ch = STR(CHILD(cch, 0));
  172. if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) {
  173. ps->p_flags |= CO_FUTURE_WITH_STATEMENT;
  174. } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) {
  175. ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
  176. } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) {
  177. ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
  178. }
  179. }
  180. }
  181. }
  182. #endif /* future keyword */
  183. int
  184. PyParser_AddToken(register parser_state *ps, register int type, char *str,
  185. int lineno, int col_offset, int *expected_ret)
  186. {
  187. register int ilabel;
  188. int err;
  189. D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
  190. /* Find out which label this token is */
  191. ilabel = classify(ps, type, str);
  192. if (ilabel < 0)
  193. return E_SYNTAX;
  194. /* Loop until the token is shifted or an error occurred */
  195. for (;;) {
  196. /* Fetch the current dfa and state */
  197. register dfa *d = ps->p_stack.s_top->s_dfa;
  198. register state *s = &d->d_state[ps->p_stack.s_top->s_state];
  199. D(printf(" DFA '%s', state %d:",
  200. d->d_name, ps->p_stack.s_top->s_state));
  201. /* Check accelerator */
  202. if (s->s_lower <= ilabel && ilabel < s->s_upper) {
  203. register int x = s->s_accel[ilabel - s->s_lower];
  204. if (x != -1) {
  205. if (x & (1<<7)) {
  206. /* Push non-terminal */
  207. int nt = (x >> 8) + NT_OFFSET;
  208. int arrow = x & ((1<<7)-1);
  209. dfa *d1 = PyGrammar_FindDFA(
  210. ps->p_grammar, nt);
  211. if ((err = push(&ps->p_stack, nt, d1,
  212. arrow, lineno, col_offset)) > 0) {
  213. D(printf(" MemError: push\n"));
  214. return err;
  215. }
  216. D(printf(" Push ...\n"));
  217. continue;
  218. }
  219. /* Shift the token */
  220. if ((err = shift(&ps->p_stack, type, str,
  221. x, lineno, col_offset)) > 0) {
  222. D(printf(" MemError: shift.\n"));
  223. return err;
  224. }
  225. D(printf(" Shift.\n"));
  226. /* Pop while we are in an accept-only state */
  227. while (s = &d->d_state
  228. [ps->p_stack.s_top->s_state],
  229. s->s_accept && s->s_narcs == 1) {
  230. D(printf(" DFA '%s', state %d: "
  231. "Direct pop.\n",
  232. d->d_name,
  233. ps->p_stack.s_top->s_state));
  234. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  235. if (d->d_name[0] == 'i' &&
  236. strcmp(d->d_name,
  237. "import_stmt") == 0)
  238. future_hack(ps);
  239. #endif
  240. s_pop(&ps->p_stack);
  241. if (s_empty(&ps->p_stack)) {
  242. D(printf(" ACCEPT.\n"));
  243. return E_DONE;
  244. }
  245. d = ps->p_stack.s_top->s_dfa;
  246. }
  247. return E_OK;
  248. }
  249. }
  250. if (s->s_accept) {
  251. #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
  252. if (d->d_name[0] == 'i' &&
  253. strcmp(d->d_name, "import_stmt") == 0)
  254. future_hack(ps);
  255. #endif
  256. /* Pop this dfa and try again */
  257. s_pop(&ps->p_stack);
  258. D(printf(" Pop ...\n"));
  259. if (s_empty(&ps->p_stack)) {
  260. D(printf(" Error: bottom of stack.\n"));
  261. return E_SYNTAX;
  262. }
  263. continue;
  264. }
  265. /* Stuck, report syntax error */
  266. D(printf(" Error.\n"));
  267. if (expected_ret) {
  268. if (s->s_lower == s->s_upper - 1) {
  269. /* Only one possible expected token */
  270. *expected_ret = ps->p_grammar->
  271. g_ll.ll_label[s->s_lower].lb_type;
  272. }
  273. else
  274. *expected_ret = -1;
  275. }
  276. return E_SYNTAX;
  277. }
  278. }
  279. #ifdef Py_DEBUG
  280. /* DEBUG OUTPUT */
  281. void
  282. dumptree(grammar *g, node *n)
  283. {
  284. int i;
  285. if (n == NULL)
  286. printf("NIL");
  287. else {
  288. label l;
  289. l.lb_type = TYPE(n);
  290. l.lb_str = STR(n);
  291. printf("%s", PyGrammar_LabelRepr(&l));
  292. if (ISNONTERMINAL(TYPE(n))) {
  293. printf("(");
  294. for (i = 0; i < NCH(n); i++) {
  295. if (i > 0)
  296. printf(",");
  297. dumptree(g, CHILD(n, i));
  298. }
  299. printf(")");
  300. }
  301. }
  302. }
  303. void
  304. showtree(grammar *g, node *n)
  305. {
  306. int i;
  307. if (n == NULL)
  308. return;
  309. if (ISNONTERMINAL(TYPE(n))) {
  310. for (i = 0; i < NCH(n); i++)
  311. showtree(g, CHILD(n, i));
  312. }
  313. else if (ISTERMINAL(TYPE(n))) {
  314. printf("%s", _PyParser_TokenNames[TYPE(n)]);
  315. if (TYPE(n) == NUMBER || TYPE(n) == NAME)
  316. printf("(%s)", STR(n));
  317. printf(" ");
  318. }
  319. else
  320. printf("? ");
  321. }
  322. void
  323. printtree(parser_state *ps)
  324. {
  325. if (Py_DebugFlag) {
  326. printf("Parse tree:\n");
  327. dumptree(ps->p_grammar, ps->p_tree);
  328. printf("\n");
  329. printf("Tokens:\n");
  330. showtree(ps->p_grammar, ps->p_tree);
  331. printf("\n");
  332. }
  333. printf("Listing:\n");
  334. PyNode_ListTree(ps->p_tree);
  335. printf("\n");
  336. }
  337. #endif /* Py_DEBUG */
  338. /*
  339. Description
  340. -----------
  341. The parser's interface is different than usual: the function addtoken()
  342. must be called for each token in the input. This makes it possible to
  343. turn it into an incremental parsing system later. The parsing system
  344. constructs a parse tree as it goes.
  345. A parsing rule is represented as a Deterministic Finite-state Automaton
  346. (DFA). A node in a DFA represents a state of the parser; an arc represents
  347. a transition. Transitions are either labeled with terminal symbols or
  348. with non-terminals. When the parser decides to follow an arc labeled
  349. with a non-terminal, it is invoked recursively with the DFA representing
  350. the parsing rule for that as its initial state; when that DFA accepts,
  351. the parser that invoked it continues. The parse tree constructed by the
  352. recursively called parser is inserted as a child in the current parse tree.
  353. The DFA's can be constructed automatically from a more conventional
  354. language description. An extended LL(1) grammar (ELL(1)) is suitable.
  355. Certain restrictions make the parser's life easier: rules that can produce
  356. the empty string should be outlawed (there are other ways to put loops
  357. or optional parts in the language). To avoid the need to construct
  358. FIRST sets, we can require that all but the last alternative of a rule
  359. (really: arc going out of a DFA's state) must begin with a terminal
  360. symbol.
  361. As an example, consider this grammar:
  362. expr: term (OP term)*
  363. term: CONSTANT | '(' expr ')'
  364. The DFA corresponding to the rule for expr is:
  365. ------->.---term-->.------->
  366. ^ |
  367. | |
  368. \----OP----/
  369. The parse tree generated for the input a+b is:
  370. (expr: (term: (NAME: a)), (OP: +), (term: (NAME: b)))
  371. */