xref: /netbsd-src/external/bsd/byacc/dist/graph.c (revision 107c160af6c3e8860518cef217297b5cee8ea310)
1 /*	$NetBSD: graph.c,v 1.9 2021/02/20 22:57:56 christos Exp $	*/
2 
3 #include "defs.h"
4 /* Id: graph.c,v 1.9 2020/09/10 17:22:51 tom Exp  */
5 
6 #include <sys/cdefs.h>
7 __RCSID("$NetBSD: graph.c,v 1.9 2021/02/20 22:57:56 christos Exp $");
8 
9 static void graph_state(int stateno);
10 static void graph_LA(int ruleno);
11 
12 static unsigned int larno;
13 
14 void
graph(void)15 graph(void)
16 {
17     int i;
18     int j;
19     shifts *sp;
20     int sn;
21     int as;
22 
23     if (!gflag)
24 	return;
25 
26     for (i = 0; i < nstates; ++i)
27     {
28 	closure(state_table[i]->items, state_table[i]->nitems);
29 	graph_state(i);
30     }
31 
32     fprintf(graph_file, "\n\n");
33     for (i = 0; i < nstates; ++i)
34     {
35 
36 	sp = shift_table[i];
37 	if (sp)
38 	    for (j = 0; j < sp->nshifts; ++j)
39 	    {
40 		sn = sp->shift[j];
41 		as = accessing_symbol[sn];
42 		fprintf(graph_file,
43 			"\tq%d -> q%d [label=\"%s\"];\n",
44 			i, sn, symbol_pname[as]);
45 	    }
46     }
47 
48     fprintf(graph_file, "}\n");
49 
50     for (i = 0; i < nsyms; ++i)
51 	FREE(symbol_pname[i]);
52     FREE(symbol_pname);
53 }
54 
55 static void
graph_state(int stateno)56 graph_state(int stateno)
57 {
58     Value_t *isp;
59     Value_t *sp;
60 
61     larno = (unsigned)lookaheads[stateno];
62     fprintf(graph_file, "\n\tq%d [label=\"%d:\\l", stateno, stateno);
63 
64     for (isp = itemset; isp < itemsetend; isp++)
65     {
66 	Value_t *sp1;
67 	int rule;
68 
69 	sp1 = sp = ritem + *isp;
70 
71 	while (*sp >= 0)
72 	    ++sp;
73 	rule = -(*sp);
74 	fprintf(graph_file, "  %s -> ", symbol_pname[rlhs[rule]]);
75 
76 	for (sp = ritem + rrhs[rule]; sp < sp1; sp++)
77 	    fprintf(graph_file, "%s ", symbol_pname[*sp]);
78 
79 	putc('.', graph_file);
80 
81 	while (*sp >= 0)
82 	{
83 	    fprintf(graph_file, " %s", symbol_pname[*sp]);
84 	    sp++;
85 	}
86 
87 	if (*sp1 < 0)
88 	    graph_LA(-*sp1);
89 
90 	fprintf(graph_file, "\\l");
91     }
92     fprintf(graph_file, "\"];");
93 }
94 
95 static void
graph_LA(int ruleno)96 graph_LA(int ruleno)
97 {
98     unsigned tokensetsize;
99 
100     tokensetsize = (unsigned)WORDSIZE(ntokens);
101 
102     if (ruleno == LAruleno[larno])
103     {
104 	int i;
105 	unsigned *rowp = LA + larno * tokensetsize;
106 
107 	fprintf(graph_file, " { ");
108 	for (i = ntokens - 1; i >= 0; i--)
109 	{
110 	    if (BIT(rowp, i))
111 		fprintf(graph_file, "%s ", symbol_pname[i]);
112 	}
113 	fprintf(graph_file, "}");
114 	++larno;
115     }
116 }
117