pgen.c revision 056a2d6582acf2c7f661279ab7df2003cbad1315
1/* Parser generator */
2
3/* For a description, see the comments at end of this file */
4
5#include "Python.h"
6#include "pgenheaders.h"
7#include "token.h"
8#include "node.h"
9#include "grammar.h"
10#include "metagrammar.h"
11#include "pgen.h"
12
13extern int Py_DebugFlag;
14extern int Py_IgnoreEnvironmentFlag; /* needed by Py_GETENV */
15
16
17/* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */
18
19typedef struct _nfaarc {
20	int	ar_label;
21	int	ar_arrow;
22} nfaarc;
23
24typedef struct _nfastate {
25	int	st_narcs;
26	nfaarc	*st_arc;
27} nfastate;
28
29typedef struct _nfa {
30	int		nf_type;
31	char		*nf_name;
32	int		nf_nstates;
33	nfastate	*nf_state;
34	int		nf_start, nf_finish;
35} nfa;
36
37/* Forward */
38static void compile_rhs(labellist *ll,
39			nfa *nf, node *n, int *pa, int *pb);
40static void compile_alt(labellist *ll,
41			nfa *nf, node *n, int *pa, int *pb);
42static void compile_item(labellist *ll,
43			 nfa *nf, node *n, int *pa, int *pb);
44static void compile_atom(labellist *ll,
45			 nfa *nf, node *n, int *pa, int *pb);
46
47static int
48addnfastate(nfa *nf)
49{
50	nfastate *st;
51
52	PyMem_RESIZE(nf->nf_state, nfastate, nf->nf_nstates + 1);
53	if (nf->nf_state == NULL)
54		Py_FatalError("out of mem");
55	st = &nf->nf_state[nf->nf_nstates++];
56	st->st_narcs = 0;
57	st->st_arc = NULL;
58	return st - nf->nf_state;
59}
60
61static void
62addnfaarc(nfa *nf, int from, int to, int lbl)
63{
64	nfastate *st;
65	nfaarc *ar;
66
67	st = &nf->nf_state[from];
68	PyMem_RESIZE(st->st_arc, nfaarc, st->st_narcs + 1);
69	if (st->st_arc == NULL)
70		Py_FatalError("out of mem");
71	ar = &st->st_arc[st->st_narcs++];
72	ar->ar_label = lbl;
73	ar->ar_arrow = to;
74}
75
76static nfa *
77newnfa(char *name)
78{
79	nfa *nf;
80	static int type = NT_OFFSET; /* All types will be disjunct */
81
82	nf = PyMem_NEW(nfa, 1);
83	if (nf == NULL)
84		Py_FatalError("no mem for new nfa");
85	nf->nf_type = type++;
86	nf->nf_name = name; /* XXX strdup(name) ??? */
87	nf->nf_nstates = 0;
88	nf->nf_state = NULL;
89	nf->nf_start = nf->nf_finish = -1;
90	return nf;
91}
92
93typedef struct _nfagrammar {
94	int		gr_nnfas;
95	nfa		**gr_nfa;
96	labellist	gr_ll;
97} nfagrammar;
98
99/* Forward */
100static void compile_rule(nfagrammar *gr, node *n);
101
102static nfagrammar *
103newnfagrammar(void)
104{
105	nfagrammar *gr;
106
107	gr = PyMem_NEW(nfagrammar, 1);
108	if (gr == NULL)
109		Py_FatalError("no mem for new nfa grammar");
110	gr->gr_nnfas = 0;
111	gr->gr_nfa = NULL;
112	gr->gr_ll.ll_nlabels = 0;
113	gr->gr_ll.ll_label = NULL;
114	addlabel(&gr->gr_ll, ENDMARKER, "EMPTY");
115	return gr;
116}
117
118static nfa *
119addnfa(nfagrammar *gr, char *name)
120{
121	nfa *nf;
122
123	nf = newnfa(name);
124	PyMem_RESIZE(gr->gr_nfa, nfa *, gr->gr_nnfas + 1);
125	if (gr->gr_nfa == NULL)
126		Py_FatalError("out of mem");
127	gr->gr_nfa[gr->gr_nnfas++] = nf;
128	addlabel(&gr->gr_ll, NAME, nf->nf_name);
129	return nf;
130}
131
132#ifdef Py_DEBUG
133
134static char REQNFMT[] = "metacompile: less than %d children\n";
135
136#define REQN(i, count) \
137 	if (i < count) { \
138		fprintf(stderr, REQNFMT, count); \
139		Py_FatalError("REQN"); \
140	} else
141
142#else
143#define REQN(i, count)	/* empty */
144#endif
145
146static nfagrammar *
147metacompile(node *n)
148{
149	nfagrammar *gr;
150	int i;
151
152	if (Py_DebugFlag)
153		printf("Compiling (meta-) parse tree into NFA grammar\n");
154	gr = newnfagrammar();
155	REQ(n, MSTART);
156	i = n->n_nchildren - 1; /* Last child is ENDMARKER */
157	n = n->n_child;
158	for (; --i >= 0; n++) {
159		if (n->n_type != NEWLINE)
160			compile_rule(gr, n);
161	}
162	return gr;
163}
164
165static void
166compile_rule(nfagrammar *gr, node *n)
167{
168	nfa *nf;
169
170	REQ(n, RULE);
171	REQN(n->n_nchildren, 4);
172	n = n->n_child;
173	REQ(n, NAME);
174	nf = addnfa(gr, n->n_str);
175	n++;
176	REQ(n, COLON);
177	n++;
178	REQ(n, RHS);
179	compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish);
180	n++;
181	REQ(n, NEWLINE);
182}
183
184static void
185compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
186{
187	int i;
188	int a, b;
189
190	REQ(n, RHS);
191	i = n->n_nchildren;
192	REQN(i, 1);
193	n = n->n_child;
194	REQ(n, ALT);
195	compile_alt(ll, nf, n, pa, pb);
196	if (--i <= 0)
197		return;
198	n++;
199	a = *pa;
200	b = *pb;
201	*pa = addnfastate(nf);
202	*pb = addnfastate(nf);
203	addnfaarc(nf, *pa, a, EMPTY);
204	addnfaarc(nf, b, *pb, EMPTY);
205	for (; --i >= 0; n++) {
206		REQ(n, VBAR);
207		REQN(i, 1);
208		--i;
209		n++;
210		REQ(n, ALT);
211		compile_alt(ll, nf, n, &a, &b);
212		addnfaarc(nf, *pa, a, EMPTY);
213		addnfaarc(nf, b, *pb, EMPTY);
214	}
215}
216
217static void
218compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
219{
220	int i;
221	int a, b;
222
223	REQ(n, ALT);
224	i = n->n_nchildren;
225	REQN(i, 1);
226	n = n->n_child;
227	REQ(n, ITEM);
228	compile_item(ll, nf, n, pa, pb);
229	--i;
230	n++;
231	for (; --i >= 0; n++) {
232		REQ(n, ITEM);
233		compile_item(ll, nf, n, &a, &b);
234		addnfaarc(nf, *pb, a, EMPTY);
235		*pb = b;
236	}
237}
238
239static void
240compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
241{
242	int i;
243	int a, b;
244
245	REQ(n, ITEM);
246	i = n->n_nchildren;
247	REQN(i, 1);
248	n = n->n_child;
249	if (n->n_type == LSQB) {
250		REQN(i, 3);
251		n++;
252		REQ(n, RHS);
253		*pa = addnfastate(nf);
254		*pb = addnfastate(nf);
255		addnfaarc(nf, *pa, *pb, EMPTY);
256		compile_rhs(ll, nf, n, &a, &b);
257		addnfaarc(nf, *pa, a, EMPTY);
258		addnfaarc(nf, b, *pb, EMPTY);
259		REQN(i, 1);
260		n++;
261		REQ(n, RSQB);
262	}
263	else {
264		compile_atom(ll, nf, n, pa, pb);
265		if (--i <= 0)
266			return;
267		n++;
268		addnfaarc(nf, *pb, *pa, EMPTY);
269		if (n->n_type == STAR)
270			*pb = *pa;
271		else
272			REQ(n, PLUS);
273	}
274}
275
276static void
277compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
278{
279	REQ(n, ATOM);
280	REQN(n->n_nchildren, 1);
281	n = n->n_child;
282	if (n->n_type == LPAR) {
283		REQN(n->n_nchildren, 3);
284		n++;
285		REQ(n, RHS);
286		compile_rhs(ll, nf, n, pa, pb);
287		n++;
288		REQ(n, RPAR);
289	}
290	else if (n->n_type == NAME || n->n_type == STRING) {
291		*pa = addnfastate(nf);
292		*pb = addnfastate(nf);
293		addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str));
294	}
295	else
296		REQ(n, NAME);
297}
298
299static void
300dumpstate(labellist *ll, nfa *nf, int istate)
301{
302	nfastate *st;
303	int i;
304	nfaarc *ar;
305
306	printf("%c%2d%c",
307		istate == nf->nf_start ? '*' : ' ',
308		istate,
309		istate == nf->nf_finish ? '.' : ' ');
310	st = &nf->nf_state[istate];
311	ar = st->st_arc;
312	for (i = 0; i < st->st_narcs; i++) {
313		if (i > 0)
314			printf("\n    ");
315		printf("-> %2d  %s", ar->ar_arrow,
316			PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label]));
317		ar++;
318	}
319	printf("\n");
320}
321
322static void
323dumpnfa(labellist *ll, nfa *nf)
324{
325	int i;
326
327	printf("NFA '%s' has %d states; start %d, finish %d\n",
328		nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish);
329	for (i = 0; i < nf->nf_nstates; i++)
330		dumpstate(ll, nf, i);
331}
332
333
334/* PART TWO -- CONSTRUCT DFA -- Algorithm 3.1 from [Aho&Ullman 77] */
335
336static void
337addclosure(bitset ss, nfa *nf, int istate)
338{
339	if (addbit(ss, istate)) {
340		nfastate *st = &nf->nf_state[istate];
341		nfaarc *ar = st->st_arc;
342		int i;
343
344		for (i = st->st_narcs; --i >= 0; ) {
345			if (ar->ar_label == EMPTY)
346				addclosure(ss, nf, ar->ar_arrow);
347			ar++;
348		}
349	}
350}
351
352typedef struct _ss_arc {
353	bitset	sa_bitset;
354	int	sa_arrow;
355	int	sa_label;
356} ss_arc;
357
358typedef struct _ss_state {
359	bitset	ss_ss;
360	int	ss_narcs;
361	ss_arc	*ss_arc;
362	int	ss_deleted;
363	int	ss_finish;
364	int	ss_rename;
365} ss_state;
366
367typedef struct _ss_dfa {
368	int	sd_nstates;
369	ss_state *sd_state;
370} ss_dfa;
371
372/* Forward */
373static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
374		       labellist *ll, char *msg);
375static void simplify(int xx_nstates, ss_state *xx_state);
376static void convert(dfa *d, int xx_nstates, ss_state *xx_state);
377
378static void
379makedfa(nfagrammar *gr, nfa *nf, dfa *d)
380{
381	int nbits = nf->nf_nstates;
382	bitset ss;
383	int xx_nstates;
384	ss_state *xx_state, *yy;
385	ss_arc *zz;
386	int istate, jstate, iarc, jarc, ibit;
387	nfastate *st;
388	nfaarc *ar;
389
390	ss = newbitset(nbits);
391	addclosure(ss, nf, nf->nf_start);
392	xx_state = PyMem_NEW(ss_state, 1);
393	if (xx_state == NULL)
394		Py_FatalError("no mem for xx_state in makedfa");
395	xx_nstates = 1;
396	yy = &xx_state[0];
397	yy->ss_ss = ss;
398	yy->ss_narcs = 0;
399	yy->ss_arc = NULL;
400	yy->ss_deleted = 0;
401	yy->ss_finish = testbit(ss, nf->nf_finish);
402	if (yy->ss_finish)
403		printf("Error: nonterminal '%s' may produce empty.\n",
404			nf->nf_name);
405
406	/* This algorithm is from a book written before
407	   the invention of structured programming... */
408
409	/* For each unmarked state... */
410	for (istate = 0; istate < xx_nstates; ++istate) {
411		yy = &xx_state[istate];
412		ss = yy->ss_ss;
413		/* For all its states... */
414		for (ibit = 0; ibit < nf->nf_nstates; ++ibit) {
415			if (!testbit(ss, ibit))
416				continue;
417			st = &nf->nf_state[ibit];
418			/* For all non-empty arcs from this state... */
419			for (iarc = 0; iarc < st->st_narcs; iarc++) {
420				ar = &st->st_arc[iarc];
421				if (ar->ar_label == EMPTY)
422					continue;
423				/* Look up in list of arcs from this state */
424				for (jarc = 0; jarc < yy->ss_narcs; ++jarc) {
425					zz = &yy->ss_arc[jarc];
426					if (ar->ar_label == zz->sa_label)
427						goto found;
428				}
429				/* Add new arc for this state */
430				PyMem_RESIZE(yy->ss_arc, ss_arc,
431					     yy->ss_narcs + 1);
432				if (yy->ss_arc == NULL)
433					Py_FatalError("out of mem");
434				zz = &yy->ss_arc[yy->ss_narcs++];
435				zz->sa_label = ar->ar_label;
436				zz->sa_bitset = newbitset(nbits);
437				zz->sa_arrow = -1;
438			 found:	;
439				/* Add destination */
440				addclosure(zz->sa_bitset, nf, ar->ar_arrow);
441			}
442		}
443		/* Now look up all the arrow states */
444		for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) {
445			zz = &xx_state[istate].ss_arc[jarc];
446			for (jstate = 0; jstate < xx_nstates; jstate++) {
447				if (samebitset(zz->sa_bitset,
448					xx_state[jstate].ss_ss, nbits)) {
449					zz->sa_arrow = jstate;
450					goto done;
451				}
452			}
453			PyMem_RESIZE(xx_state, ss_state, xx_nstates + 1);
454			if (xx_state == NULL)
455				Py_FatalError("out of mem");
456			zz->sa_arrow = xx_nstates;
457			yy = &xx_state[xx_nstates++];
458			yy->ss_ss = zz->sa_bitset;
459			yy->ss_narcs = 0;
460			yy->ss_arc = NULL;
461			yy->ss_deleted = 0;
462			yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish);
463		 done:	;
464		}
465	}
466
467	if (Py_DebugFlag)
468		printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
469						"before minimizing");
470
471	simplify(xx_nstates, xx_state);
472
473	if (Py_DebugFlag)
474		printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
475						"after minimizing");
476
477	convert(d, xx_nstates, xx_state);
478
479	/* XXX cleanup */
480}
481
482static void
483printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
484	   labellist *ll, char *msg)
485{
486	int i, ibit, iarc;
487	ss_state *yy;
488	ss_arc *zz;
489
490	printf("Subset DFA %s\n", msg);
491	for (i = 0; i < xx_nstates; i++) {
492		yy = &xx_state[i];
493		if (yy->ss_deleted)
494			continue;
495		printf(" Subset %d", i);
496		if (yy->ss_finish)
497			printf(" (finish)");
498		printf(" { ");
499		for (ibit = 0; ibit < nbits; ibit++) {
500			if (testbit(yy->ss_ss, ibit))
501				printf("%d ", ibit);
502		}
503		printf("}\n");
504		for (iarc = 0; iarc < yy->ss_narcs; iarc++) {
505			zz = &yy->ss_arc[iarc];
506			printf("  Arc to state %d, label %s\n",
507				zz->sa_arrow,
508				PyGrammar_LabelRepr(
509					&ll->ll_label[zz->sa_label]));
510		}
511	}
512}
513
514
515/* PART THREE -- SIMPLIFY DFA */
516
517/* Simplify the DFA by repeatedly eliminating states that are
518   equivalent to another oner.  This is NOT Algorithm 3.3 from
519   [Aho&Ullman 77].  It does not always finds the minimal DFA,
520   but it does usually make a much smaller one...  (For an example
521   of sub-optimal behavior, try S: x a b+ | y a b+.)
522*/
523
524static int
525samestate(ss_state *s1, ss_state *s2)
526{
527	int i;
528
529	if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish)
530		return 0;
531	for (i = 0; i < s1->ss_narcs; i++) {
532		if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow ||
533			s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label)
534			return 0;
535	}
536	return 1;
537}
538
539static void
540renamestates(int xx_nstates, ss_state *xx_state, int from, int to)
541{
542	int i, j;
543
544	if (Py_DebugFlag)
545		printf("Rename state %d to %d.\n", from, to);
546	for (i = 0; i < xx_nstates; i++) {
547		if (xx_state[i].ss_deleted)
548			continue;
549		for (j = 0; j < xx_state[i].ss_narcs; j++) {
550			if (xx_state[i].ss_arc[j].sa_arrow == from)
551				xx_state[i].ss_arc[j].sa_arrow = to;
552		}
553	}
554}
555
556static void
557simplify(int xx_nstates, ss_state *xx_state)
558{
559	int changes;
560	int i, j;
561
562	do {
563		changes = 0;
564		for (i = 1; i < xx_nstates; i++) {
565			if (xx_state[i].ss_deleted)
566				continue;
567			for (j = 0; j < i; j++) {
568				if (xx_state[j].ss_deleted)
569					continue;
570				if (samestate(&xx_state[i], &xx_state[j])) {
571					xx_state[i].ss_deleted++;
572					renamestates(xx_nstates, xx_state,
573						     i, j);
574					changes++;
575					break;
576				}
577			}
578		}
579	} while (changes);
580}
581
582
583/* PART FOUR -- GENERATE PARSING TABLES */
584
585/* Convert the DFA into a grammar that can be used by our parser */
586
587static void
588convert(dfa *d, int xx_nstates, ss_state *xx_state)
589{
590	int i, j;
591	ss_state *yy;
592	ss_arc *zz;
593
594	for (i = 0; i < xx_nstates; i++) {
595		yy = &xx_state[i];
596		if (yy->ss_deleted)
597			continue;
598		yy->ss_rename = addstate(d);
599	}
600
601	for (i = 0; i < xx_nstates; i++) {
602		yy = &xx_state[i];
603		if (yy->ss_deleted)
604			continue;
605		for (j = 0; j < yy->ss_narcs; j++) {
606			zz = &yy->ss_arc[j];
607			addarc(d, yy->ss_rename,
608				xx_state[zz->sa_arrow].ss_rename,
609				zz->sa_label);
610		}
611		if (yy->ss_finish)
612			addarc(d, yy->ss_rename, yy->ss_rename, 0);
613	}
614
615	d->d_initial = 0;
616}
617
618
619/* PART FIVE -- GLUE IT ALL TOGETHER */
620
621static grammar *
622maketables(nfagrammar *gr)
623{
624	int i;
625	nfa *nf;
626	dfa *d;
627	grammar *g;
628
629	if (gr->gr_nnfas == 0)
630		return NULL;
631	g = newgrammar(gr->gr_nfa[0]->nf_type);
632			/* XXX first rule must be start rule */
633	g->g_ll = gr->gr_ll;
634
635	for (i = 0; i < gr->gr_nnfas; i++) {
636		nf = gr->gr_nfa[i];
637		if (Py_DebugFlag) {
638			printf("Dump of NFA for '%s' ...\n", nf->nf_name);
639			dumpnfa(&gr->gr_ll, nf);
640			printf("Making DFA for '%s' ...\n", nf->nf_name);
641		}
642		d = adddfa(g, nf->nf_type, nf->nf_name);
643		makedfa(gr, gr->gr_nfa[i], d);
644	}
645
646	return g;
647}
648
649grammar *
650pgen(node *n)
651{
652	nfagrammar *gr;
653	grammar *g;
654
655	gr = metacompile(n);
656	g = maketables(gr);
657	translatelabels(g);
658	addfirstsets(g);
659	return g;
660}
661
662grammar *
663Py_pgen(node *n)
664{
665  return pgen(n);
666}
667
668/*
669
670Description
671-----------
672
673Input is a grammar in extended BNF (using * for repetition, + for
674at-least-once repetition, [] for optional parts, | for alternatives and
675() for grouping).  This has already been parsed and turned into a parse
676tree.
677
678Each rule is considered as a regular expression in its own right.
679It is turned into a Non-deterministic Finite Automaton (NFA), which
680is then turned into a Deterministic Finite Automaton (DFA), which is then
681optimized to reduce the number of states.  See [Aho&Ullman 77] chapter 3,
682or similar compiler books (this technique is more often used for lexical
683analyzers).
684
685The DFA's are used by the parser as parsing tables in a special way
686that's probably unique.  Before they are usable, the FIRST sets of all
687non-terminals are computed.
688
689Reference
690---------
691
692[Aho&Ullman 77]
693	Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977
694	(first edition)
695
696*/
697