monoburg.c 30 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * monoburg.c: an iburg like code generator generator
 *
 * Author:
 *   Dietmar Maurer (dietmar@ximian.com)
 *
 * (C) 2001 Ximian, Inc.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "monoburg.h"

extern void yyparse (void);

static GHashTable *term_hash;
static GList *term_list;
static GHashTable *nonterm_hash;
static GList *nonterm_list;
static GList *rule_list;
static GList *prefix_list;

24
File inputs[MAX_FDS];
25
26
27
28
29
FILE *outputfd;
GHashTable *definedvars;
static FILE *deffd;
static FILE *cfd;

Benoit Perrot's avatar
Benoit Perrot committed
30
static gboolean with_glib = TRUE;
31
static gboolean with_exported_symbols = TRUE;
32
static gboolean with_references = FALSE;
33
34
35
36
static int dag_mode = 0;
static int predefined_terms = 0;
static int default_cost = 0;

37
38
39
char *namespaces[MAX_NAMESPACES];
int n_namespace = 0;

40
41
42
char **include_dirs;
int n_include_dir = 0;

43
static void output (char *fmt, ...)
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
{
	va_list ap;

	va_start(ap, fmt);
	vfprintf (outputfd, fmt, ap);
	va_end (ap);
}

Rule*
make_rule (char *id, Tree *tree)
{
	Rule *rule = g_new0 (Rule, 1);
	rule->lhs = nonterm (id);
	rule->tree = tree;

	return rule;
}

void
rule_add (Rule *rule, char *code, char *cost, char *cfunc)
{
	if (!cfunc && !cost)
		cost = g_strdup_printf ("%d", default_cost);

	rule_list = g_list_append (rule_list, rule);
	rule->cost = g_strdup (cost);
	rule->cfunc = g_strdup (cfunc);
	rule->code = g_strdup (code);

	if (cfunc) {
		if (cost)
			yyerror ("duplicated costs (constant costs and cost function)");
		else {
			if (dag_mode)
				rule->cost = g_strdup_printf ("mono_burg_cost_%d (p, data)",
							      g_list_length (rule_list));
			else
				rule->cost = g_strdup_printf ("mono_burg_cost_%d (tree, data)",
							      g_list_length (rule_list));
		}
	}

	rule->lhs->rules = g_list_append (rule->lhs->rules, rule);

	if (rule->tree->op)
		rule->tree->op->rules = g_list_append (rule->tree->op->rules, rule);
90
	else
91
92
93
		rule->tree->nonterm->chain = g_list_append (rule->tree->nonterm->chain, rule);
}

94
void
95
96
97
98
99
100
101
102
103
104
105
create_rule (char *id, Tree *tree, char *code, char *cost, char *cfunc)
{
	Rule *rule = make_rule (id, tree);

	rule_add (rule, code, cost, cfunc);
}

Tree *
create_tree (char *id, Tree *left, Tree *right)
{
	int arity = (left != NULL) + (right != NULL);
106
	Term *term = NULL;
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
	Tree *tree = g_new0 (Tree, 1);

	if (term_hash)
		term = g_hash_table_lookup (term_hash, id);

	/* try if id has termprefix */
	if (!term) {
		GList *pl;
		for (pl = prefix_list; pl; pl = pl->next) {
			char *pfx = (char *)pl->data;
			if (!strncmp (pfx, id, strlen (pfx))) {
				term = create_term (id, -1);
				break;
			}
		}

	}

	if (term) {
		if (term->arity == -1)
			term->arity = arity;

		if (term->arity != arity)
			yyerror ("changed arity of terminal %s from %d to %d",
				 id, term->arity, arity);

		tree->op = term;
		tree->left = left;
		tree->right = right;
	} else {
		tree->nonterm = nonterm (id);
	}

	return tree;
}

static void
check_term_num (char *key, Term *value, int num)
{
	if (num != -1 && value->number == num)
		yyerror ("duplicate terminal id \"%s\"", key);
}
149
150

void
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
create_term_prefix (char *id)
{
	if (!predefined_terms)
		yyerror ("%termprefix is only available with -p option");

	prefix_list = g_list_prepend (prefix_list, g_strdup (id));
}

Term *
create_term (char *id, int num)
{
	Term *term;

	if (!predefined_terms && nonterm_list)
		yyerror ("terminal definition after nonterminal definition");

	if (num < -1)
		yyerror ("invalid terminal number %d", num);

170
	if (!term_hash)
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
		term_hash = g_hash_table_new (g_str_hash , g_str_equal);

	g_hash_table_foreach (term_hash, (GHFunc) check_term_num, (gpointer) num);

	term = g_new0 (Term, 1);

	term->name = g_strdup (id);
	term->number = num;
	term->arity = -1;

	term_list = g_list_append (term_list, term);

	g_hash_table_insert (term_hash, term->name, term);

	return term;
}

NonTerm *
nonterm (char *id)
{
	NonTerm *nterm;

193
	if (!nonterm_hash)
194
195
196
197
198
199
200
201
202
203
		nonterm_hash = g_hash_table_new (g_str_hash , g_str_equal);

	if ((nterm = g_hash_table_lookup (nonterm_hash, id)))
		return nterm;

	nterm = g_new0 (NonTerm, 1);

	nterm->name = g_strdup (id);
	nonterm_list = g_list_append (nonterm_list, nterm);
	nterm->number = g_list_length (nonterm_list);
204

205
206
207
208
209
210
211
212
213
	g_hash_table_insert (nonterm_hash, nterm->name, nterm);

	return nterm;
}

void
start_nonterm (char *id)
{
	static gboolean start_def;
214

215
216
	if (start_def)
		yyerror ("start symbol redeclared");
217

218
	start_def = TRUE;
219
	nonterm (id);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
}

static void
emit_tree_string (Tree *tree)
{
	if (tree->op) {
		output ("%s", tree->op->name);
		if (tree->op->arity) {
			output ("(");
			emit_tree_string (tree->left);
			if (tree->right) {
				output (", ");
				emit_tree_string (tree->right);
			}
			output (")");
		}
236
	} else
237
238
239
240
241
242
243
		output ("%s", tree->nonterm->name);
}

static void
emit_rule_string (Rule *rule, char *fill)
{
	output ("%s/* ", fill);
244

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
	output ("%s: ", rule->lhs->name);

	emit_tree_string (rule->tree);

	output (" */\n");
}

static int
next_term_num ()
{
	GList *l = term_list;
	int i = 1;

	while (l) {
		Term *t = (Term *)l->data;
		if (t->number == i) {
			l = term_list;
			i++;
		} else
			l = l->next;
	}
	return i;
}

static int
term_compare_func (Term *t1, Term *t2)
{
	return t1->number - t2->number;
}

static void
Benoit Perrot's avatar
Benoit Perrot committed
276
emit_includes ()
277
{
Benoit Perrot's avatar
Benoit Perrot committed
278
279
280
281
282
	if (with_glib) {
		output ("#include <glib.h>\n");
		output ("\n");
	}
	else {
Benoit Perrot's avatar
Benoit Perrot committed
283
284
285
286
287
288
289
290
291
292
293
		output ("# include <stdio.h>\n");
		output ("# include <stdlib.h>\n");
		output ("# include <stdarg.h>\n");
		output ("# include <assert.h>\n");
	}
}

static void
emit_header ()
{
	if (!with_glib) {
Benoit Perrot's avatar
Benoit Perrot committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
		output ("#ifndef guint8\n");
		output ("# define guint8 unsigned char\n");
		output ("#endif /* !guint8 */\n");
		output ("#ifndef guint16\n");
		output ("# define guint16 unsigned short\n");
		output ("#endif /* !guint16 */\n");
		output ("#ifndef gpointer\n");
		output ("# define gpointer void*\n");
		output ("#endif /* !gpointer */\n");
		output ("\n");

		output ("#ifndef g_new\n");
		output ("static void *\n");
		output ("mono_burg_xmalloc_ (size_t size)\n");
		output ("{\n");
		output ("	void *p;\n");
		output ("\n");
		output ("	p = malloc (size);\n");
		output ("	if (!p) {\n");
		output ("		fprintf (stderr, \"Not enough memory\\n\");\n");
		output ("		exit (1);\n");
		output ("	}\n");
		output ("	return p;\n");
		output ("}\n");
		output ("# define g_new(struct_type, n_structs) ((struct_type *) mono_burg_xmalloc_ (sizeof(struct_type) * n_structs))\n");
		output ("#endif /* !g_new */\n");
		output ("\n");

		output ("#ifndef g_new0\n");
		output ("static void *\n");
		output ("mono_burg_xcalloc_ (size_t nmemb, size_t size)\n");
		output ("{\n");
		output ("	void *p;\n");
		output ("\n");
		output ("	p = calloc (nmemb, size);\n");
		output ("	if (!p) {\n");
		output ("		fprintf (stderr, \"Not enough memory\\n\");\n");
		output ("		exit (1);\n");
		output ("	}\n");
		output ("	return p;\n");
		output ("}\n");
		output ("#define g_new0(struct_type, n_structs) ((struct_type *) mono_burg_xcalloc_(1, sizeof(struct_type) * n_structs))\n");
		output ("#endif /* !g_new0 */\n");
		output ("\n");

		output ("#ifndef g_error\n");
		output ("static int\n");
		output ("mono_burg_error_ (const char *format, ...)\n");
		output ("{\n");
		output ("	int n = 0;\n");
		output ("	va_list ap;\n");
		output ("\n");
		output ("	n = fprintf (stderr, \"Error: \");\n");
		output ("	va_start (ap, format);\n");
		output ("	n += vfprintf (stderr, format, ap);\n");
		output ("	va_end (ap);\n");
		output ("\n");
		output ("	return n;\n");
		output ("}\n");
		output ("# define g_error mono_burg_error_\n");
		output ("#endif /* !g_error */\n");

		output ("#ifndef g_warning\n");
		output ("static int\n");
		output ("mono_burg_warning_ (const char *format, ...)\n");
		output ("{\n");
		output ("	int n = 0;\n");
		output ("	va_list ap;\n");
		output ("\n");
		output ("	n = fprintf (stderr, \"Warning: \");\n");
		output ("	va_start (ap, format);\n");
		output ("	n += vfprintf (stderr, format, ap);\n");
		output ("	va_end (ap);\n");
		output ("\n");
		output ("	return n;\n");
		output ("}\n");
		output ("# define g_warning mono_burg_warning_\n");
		output ("#endif /* !g_warning */\n");
		output ("\n");

		output ("#ifndef g_assert\n");
		output ("# define g_assert assert\n");
		output ("#endif /* !g_assert */\n");
		output ("\n");

		output ("#ifndef g_return_val_if_fail\n");
		output ("# ifdef NDEBUG\n");
		output ("#  define g_return_val_if_fail(expr, val)\n");
		output ("# else /* !NDEBUG */\n");
		output ("#  define g_return_val_if_fail(expr, val) do { if (! (expr)) return val; } while (0)\n");
		output ("# endif /* NDEBUG */\n");
		output ("#endif /* !g_return_val_if_fail */\n");
		output ("#ifndef g_assert_not_reached\n");
		output ("# define g_assert_not_reached(X) assert (!\"Should not be there\")\n");
		output ("#endif /* !g_assert_not_reached */\n");
		output ("\n");
	}
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407

	output ("#ifndef MBTREE_TYPE\n#error MBTREE_TYPE undefined\n#endif\n");
	output ("#ifndef MBTREE_OP\n#define MBTREE_OP(t) ((t)->op)\n#endif\n");
	output ("#ifndef MBTREE_LEFT\n#define MBTREE_LEFT(t) ((t)->left)\n#endif\n");
	output ("#ifndef MBTREE_RIGHT\n#define MBTREE_RIGHT(t) ((t)->right)\n#endif\n");
	output ("#ifndef MBTREE_STATE\n#define MBTREE_STATE(t) ((t)->state)\n#endif\n");
	output ("#ifndef MBCGEN_TYPE\n#define MBCGEN_TYPE int\n#endif\n");
	output ("#ifndef MBALLOC_STATE\n#define MBALLOC_STATE g_new (MBState, 1)\n#endif\n");
	output ("#ifndef MBCOST_DATA\n#define MBCOST_DATA gpointer\n#endif\n");
	output ("\n");
	output ("#define MBMAXCOST 32768\n");

	output ("\n");
	output ("#define MBCOND(x) if (!(x)) return MBMAXCOST;\n");

	output ("\n");

408
409
410
411
412
413
414
}

static void
emit_term ()
{
	GList *l;

415
416
417
418
419
420
421
	for (l = term_list; l; l = l->next) {
		Term *t = (Term *)l->data;
		if (t->number == -1)
			t->number = next_term_num ();
	}
	term_list = g_list_sort (term_list, (GCompareFunc)term_compare_func);

422
	output ("typedef enum {\n");
423
424
425
426
427
428
	for (l = term_list; l; l = l->next) {
		Term *t = (Term *)l->data;
		if (t->number == -1)
			t->number = next_term_num ();

		if (predefined_terms)
429
430
			output ("\tMB_TERM_%s = %s%s\n", t->name, t->name,
				l->next ? "," : "");
431
		else
432
433
			output ("\tMB_TERM_%s = %d%s\n", t->name, t->number,
				l->next ? "," : "");
434
	}
435
	output ("} MBTerms;\n\n");
436
437
}

438

439
440
441
442
443
static void
emit_nonterm ()
{
	GList *l;

444
	output ("typedef enum {\n");
445
446
	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
447
448
		output ("\tMB_NTERM_%s = %d%s\n", n->name, n->number,
			(l->next) ? "," : "");
449
	}
450
	output ("} MBNTerms;\n\n");
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
	output ("#define MB_MAX_NTERMS\t%d\n", g_list_length (nonterm_list));
	output ("\n");
}

static void
emit_state ()
{
	GList *l;
	int i, j;

	output ("struct _MBState {\n");
	output ("\tint\t\t op;\n");

	if (dag_mode) {
		output ("\tMBTREE_TYPE\t *tree;\n");
		output ("\tgint32 reg1, reg2;\n");
	}
468

Benoit Perrot's avatar
Benoit Perrot committed
469
	output ("\tstruct _MBState\t\t*left, *right;\n");
470
471
472
473
474
475
476
477
478
	output ("\tguint16\t\tcost[%d];\n", g_list_length (nonterm_list) + 1);

	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
		g_assert (g_list_length (n->rules) < 256);
		i = g_list_length (n->rules);
		j = 1;
		while (i >>= 1)
			j++;
479
		output ("\tunsigned int\t rule_%s:%d;\n",  n->name, j);
480
481
	}
	output ("};\n\n");
Benoit Perrot's avatar
Benoit Perrot committed
482
	output ("typedef struct _MBState MBState;\n");
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
}

static void
emit_decoders ()
{
	GList *l;
	GList *rl;

	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
		output ("const int mono_burg_decode_%s[] = {\n", n->name);
		output ("\t0,\n");
		for (rl = n->rules; rl; rl = rl->next) {
			Rule *rule = (Rule *)rl->data;
			output ("\t%d,\n", g_list_index (rule_list, rule) + 1);
		}
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
		output ("};\n\n");
	}
}

static void
emit_tree_match (char *st, Tree *t)
{
	char *tn;
	int not_first = strcmp (st, "p->");

	/* we can omit this check at the top level */
	if (not_first) {
		if (predefined_terms)
			output ("\t\t\t%sop == %s /* %s */", st, t->op->name, t->op->name);
		else
			output ("\t\t\t%sop == %d /* %s */", st, t->op->number, t->op->name);
	}

	if (t->left && t->left->op) {
		tn = g_strconcat (st, "left->", NULL);
		if (not_first)
			output (" &&\n");
		not_first = 1;
		emit_tree_match (tn, t->left);
		g_free (tn);
	}

	if (t->right && t->right->op) {
		tn = g_strconcat (st, "right->", NULL);
		if (not_first)
			output (" &&\n");
		emit_tree_match (tn, t->right);
		g_free (tn);
	}
}

static void
emit_rule_match (Rule *rule)
{
539
	Tree *t = rule->tree;
540

541
542
	if ((t->left && t->left->op) ||
	    (t->right && t->right->op)) {
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
		output ("\t\tif (\n");
		emit_tree_match ("p->", t);
		output ("\n\t\t)\n");
	}
}

static void
emit_costs (char *st, Tree *t)
{
	char *tn;

	if (t->op) {

		if (t->left) {
			tn = g_strconcat (st, "left->", NULL);
			emit_costs (tn, t->left);
			g_free (tn);
		}

		if (t->right) {
			tn = g_strconcat (st, "right->", NULL);
			emit_costs (tn, t->right);
		}
	} else
		output ("%scost[MB_NTERM_%s] + ", st, t->nonterm->name);
}

static void
emit_cond_assign (Rule *rule, char *cost, char *fill)
{
	char *rc;

	if (cost)
		rc = g_strconcat ("c + ", cost, NULL);
	else
		rc = g_strdup ("c");


	output ("%sif (%s < p->cost[MB_NTERM_%s]) {\n", fill, rc, rule->lhs->name);

	output ("%s\tp->cost[MB_NTERM_%s] = %s;\n", fill, rule->lhs->name, rc);

585
	output ("%s\tp->rule_%s = %d;\n", fill, rule->lhs->name,
586
587
588
		g_list_index (rule->lhs->rules, rule) + 1);

	if (rule->lhs->chain)
589
		output ("%s\tclosure_%s (p, %s);\n", fill, rule->lhs->name, rc);
590
591
592
593

	output ("%s}\n", fill);

	g_free (rc);
594

595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
}

static void
emit_label_func ()
{
	GList *l;
	int i;

	if (dag_mode) {
		output ("static void\n");
		output ("mono_burg_label_priv (MBTREE_TYPE *tree, MBCOST_DATA *data, MBState *p) {\n");
	} else {
		output ("static MBState *\n");
		output ("mono_burg_label_priv (MBTREE_TYPE *tree, MBCOST_DATA *data) {\n");
	}

	output ("\tint arity;\n");
	output ("\tint c;\n");
613
	if (!dag_mode)
614
615
616
617
618
619
620
621
622
		output ("\tMBState *p;\n");
	output ("\tMBState *left = NULL, *right = NULL;\n\n");

	output ("\tswitch (mono_burg_arity [MBTREE_OP(tree)]) {\n");
	output ("\tcase 0:\n");
	output ("\t\tbreak;\n");
	output ("\tcase 1:\n");
	if (dag_mode) {
		output ("\t\tleft = MBALLOC_STATE;\n");
623
		output ("\t\tmono_burg_label_priv (MBTREE_LEFT(tree), data, left);\n");
624
625
626
627
628
629
630
631
	} else {
		output ("\t\tleft = mono_burg_label_priv (MBTREE_LEFT(tree), data);\n");
		output ("\t\tright = NULL;\n");
	}
	output ("\t\tbreak;\n");
	output ("\tcase 2:\n");
	if (dag_mode) {
		output ("\t\tleft = MBALLOC_STATE;\n");
632
		output ("\t\tmono_burg_label_priv (MBTREE_LEFT(tree), data, left);\n");
633
		output ("\t\tright = MBALLOC_STATE;\n");
634
		output ("\t\tmono_burg_label_priv (MBTREE_RIGHT(tree), data, right);\n");
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
	} else {
		output ("\t\tleft = mono_burg_label_priv (MBTREE_LEFT(tree), data);\n");
		output ("\t\tright = mono_burg_label_priv (MBTREE_RIGHT(tree), data);\n");
	}
	output ("\t}\n\n");

	output ("\tarity = (left != NULL) + (right != NULL);\n");
	output ("\tg_assert (arity == mono_burg_arity [MBTREE_OP(tree)]);\n\n");

	if (!dag_mode)
		output ("\tp = MBALLOC_STATE;\n");

	output ("\tmemset (p, 0, sizeof (MBState));\n");
	output ("\tp->op = MBTREE_OP(tree);\n");
	output ("\tp->left = left;\n");
	output ("\tp->right = right;\n");

	if (dag_mode)
653
654
		output ("\tp->tree = tree;\n");

655
656
657
658
659
660
661
662
663
	for (l = nonterm_list, i = 0; l; l = l->next) {
		output ("\tp->cost [%d] = 32767;\n", ++i);
	}
	output ("\n");

	output ("\tswitch (MBTREE_OP(tree)) {\n");
	for (l = term_list; l; l = l->next) {
		Term *t = (Term *)l->data;
		GList *rl;
664

665
666
667
668
669
670
		if (predefined_terms)
			output ("\tcase %s: /* %s */\n", t->name, t->name);
		else
			output ("\tcase %d: /* %s */\n", t->number, t->name);

		for (rl = t->rules; rl; rl = rl->next) {
671
			Rule *rule = (Rule *)rl->data;
672
673
674
675
676
			Tree *t = rule->tree;

			emit_rule_string (rule, "\t\t");

			emit_rule_match (rule);
677

678
679
680
			output ("\t\t{\n");

			output ("\t\t\tc = ");
681

682
			emit_costs ("", t);
683

684
685
686
687
688
689
690
691
692
			output ("%s;\n", rule->cost);

			emit_cond_assign (rule, NULL, "\t\t\t");

			output ("\t\t}\n");
		}

		output ("\t\tbreak;\n");
	}
693

694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
	output ("\tdefault:\n");
	output ("#ifdef MBGET_OP_NAME\n");
	output ("\t\tg_error (\"unknown operator: %%s\", MBGET_OP_NAME(MBTREE_OP(tree)));\n");
	output ("#else\n");
	output ("\t\tg_error (\"unknown operator: 0x%%04x\", MBTREE_OP(tree));\n");
	output ("#endif\n");
	output ("\t}\n\n");

	if (!dag_mode) {
		output ("\tMBTREE_STATE(tree) = p;\n");
		output ("\treturn p;\n");
	}

	output ("}\n\n");

709
710
	if (!with_exported_symbols)
		output ("static ");
711
712
713
714
	output ("MBState *\n");
	output ("mono_burg_label (MBTREE_TYPE *tree, MBCOST_DATA *data)\n{\n");
	if (dag_mode) {
		output ("\tMBState *p = MBALLOC_STATE;\n");
715
		output ("\tmono_burg_label_priv (tree, data, p);\n");
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
	} else {
		output ("\tMBState *p = mono_burg_label_priv (tree, data);\n");
	}
	output ("\treturn p->rule_%s ? p : NULL;\n", ((NonTerm *)nonterm_list->data)->name);
	output ("}\n\n");
}

static char *
compute_kids (char *ts, Tree *tree, int *n)
{
	char *res;

	if (tree->nonterm) {
		return g_strdup_printf ("\t\tkids[%d] = %s;\n", (*n)++, ts);
	} else if (tree->op && tree->op->arity) {
		char *res2 = NULL;

		if (dag_mode) {
734
			res = compute_kids (g_strdup_printf ("%s->left", ts),
735
736
					    tree->left, n);
			if (tree->op->arity == 2)
737
				res2 = compute_kids (g_strdup_printf ("%s->right", ts),
738
739
						     tree->right, n);
		} else {
740
			res = compute_kids (g_strdup_printf ("MBTREE_LEFT(%s)", ts),
741
742
					    tree->left, n);
			if (tree->op->arity == 2)
743
				res2 = compute_kids (g_strdup_printf ("MBTREE_RIGHT(%s)", ts),
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
						     tree->right, n);
		}

		return g_strconcat (res, res2, NULL);
	}
	return "";
}

static void
emit_kids ()
{
	GList *l, *nl;
	int i, j, c, n, *si;
	char **sa;

759
760
	if (!with_exported_symbols)
		output ("static ");
761
762
763
	output ("int\n");
	output ("mono_burg_rule (MBState *state, int goal)\n{\n");

764
	output ("\tg_return_val_if_fail (state != NULL, 0);\n");
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
	output ("\tg_return_val_if_fail (goal > 0, 0);\n\n");

	output ("\tswitch (goal) {\n");

	for (nl = nonterm_list; nl; nl = nl->next) {
		NonTerm *n = (NonTerm *)nl->data;
		output ("\tcase MB_NTERM_%s:\n", n->name);
		output ("\t\treturn mono_burg_decode_%s [state->rule_%s];\n",
			n->name, n->name);
	}

	output ("\tdefault: g_assert_not_reached ();\n");
	output ("\t}\n");
	output ("\treturn 0;\n");
	output ("}\n\n");


	if (dag_mode) {
783
784
		if (!with_exported_symbols)
			output ("static ");
785
786
787
788
789
790
		output ("MBState **\n");
		output ("mono_burg_kids (MBState *state, int rulenr, MBState *kids [])\n{\n");
		output ("\tg_return_val_if_fail (state != NULL, NULL);\n");
		output ("\tg_return_val_if_fail (kids != NULL, NULL);\n\n");

	} else {
791
792
		if (!with_exported_symbols)
			output ("static ");
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
		output ("MBTREE_TYPE **\n");
		output ("mono_burg_kids (MBTREE_TYPE *tree, int rulenr, MBTREE_TYPE *kids [])\n{\n");
		output ("\tg_return_val_if_fail (tree != NULL, NULL);\n");
		output ("\tg_return_val_if_fail (kids != NULL, NULL);\n\n");
	}

	output ("\tswitch (rulenr) {\n");

	n = g_list_length (rule_list);
	sa = g_new0 (char *, n);
	si = g_new0 (int, n);

	/* compress the case statement */
	for (l = rule_list, i = 0, c = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		int kn = 0;
		char *k;

		if (dag_mode)
			k = compute_kids ("state", rule->tree, &kn);
		else
			k = compute_kids ("tree", rule->tree, &kn);

		for (j = 0; j < c; j++)
			if (!strcmp (sa [j], k))
				break;

		si [i++] = j;
		if (j == c)
			sa [c++] = k;
	}

	for (i = 0; i < c; i++) {
		for (l = rule_list, j = 0; l; l = l->next, j++)
			if (i == si [j])
				output ("\tcase %d:\n", j + 1);
		output ("%s", sa [i]);
		output ("\t\tbreak;\n");
	}

	output ("\tdefault:\n\t\tg_assert_not_reached ();\n");
	output ("\t}\n");
	output ("\treturn kids;\n");
	output ("}\n\n");

}

static void
emit_emitter_func ()
{
	GList *l;
	int i, rulen;
	GHashTable *cache = g_hash_table_new (g_str_hash, g_str_equal);

	for (l =  rule_list, i = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
849

850
851
852
853
854
855
856
857
858
859
860
861
		if (rule->code) {
			if ((rulen = GPOINTER_TO_INT (g_hash_table_lookup (cache, rule->code)))) {
				emit_rule_string (rule, "");
				output ("#define mono_burg_emit_%d mono_burg_emit_%d\n\n", i, rulen);
				i++;
				continue;
			}
			output ("static void ");

			emit_rule_string (rule, "");

			if (dag_mode)
862
863
				output ("mono_burg_emit_%d (MBState *state, MBTREE_TYPE %ctree, MBCGEN_TYPE *s)\n", i,
					  (with_references ? '&' : '*'));
864
			else
865
866
867
				output ("mono_burg_emit_%d (MBTREE_TYPE %ctree, MBCGEN_TYPE *s)\n", i,
					(with_references ? '&' : '*'));

868
			output ("{\n");
869
870
871
872
			output ("(void) tree; (void) s;");
			if (dag_mode)
				output (" (void) state;");
			output ("\n%s\n", rule->code);
873
874
875
876
877
878
879
880
			output ("}\n\n");
			g_hash_table_insert (cache, rule->code, GINT_TO_POINTER (i));
		}
		i++;
	}

	g_hash_table_destroy (cache);

881
882
	if (!with_exported_symbols)
		output ("static ");
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
	output ("MBEmitFunc const mono_burg_func [] = {\n");
	output ("\tNULL,\n");
	for (l =  rule_list, i = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		if (rule->code)
			output ("\tmono_burg_emit_%d,\n", i);
		else
			output ("\tNULL,\n");
		i++;
	}
	output ("};\n\n");
}

static void
emit_cost_func ()
{
	GList *l;
	int i;

902
903
904
	if (!with_exported_symbols)
		output ("static int mono_burg_rule (MBState *state, int goal);\n");

905
906
	for (l =  rule_list, i = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
907

908
909
910
911
		if (rule->cfunc) {
			output ("inline static guint16\n");

			emit_rule_string (rule, "");
912

913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
			if (dag_mode)
				output ("mono_burg_cost_%d (MBState *state, MBCOST_DATA *data)\n", i + 1);
			else
				output ("mono_burg_cost_%d (MBTREE_TYPE *tree, MBCOST_DATA *data)\n", i + 1);
			output ("{\n");
			output ("%s\n", rule->cfunc);
			output ("}\n\n");
		}
		i++;
	}
}

static void
emit_closure ()
{
	GList *l, *rl;

	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
932

933
934
935
936
937
938
939
940
		if (n->chain)
			output ("static void closure_%s (MBState *p, int c);\n", n->name);
	}

	output ("\n");

	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
941

942
943
944
945
946
		if (n->chain) {
			output ("static void\n");
			output ("closure_%s (MBState *p, int c)\n{\n", n->name);
			for (rl = n->chain; rl; rl = rl->next) {
				Rule *rule = (Rule *)rl->data;
947

948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
				emit_rule_string (rule, "\t");
				emit_cond_assign (rule, rule->cost, "\t");
			}
			output ("}\n\n");
		}
	}
}

static char *
compute_nonterms (Tree *tree)
{
	if (!tree)
		return "";

	if (tree->nonterm) {
		return g_strdup_printf ("MB_NTERM_%s, ", tree->nonterm->name);
	} else {
		return g_strconcat (compute_nonterms (tree->left),
				    compute_nonterms (tree->right), NULL);
967
	}
968
969
970
971
972
973
974
975
976
977
}

static void
emit_vardefs ()
{
	GList *l;
	int i, j, c, n, *si;
	char **sa;

	if (predefined_terms) {
978
979
980
		output ("guint8 mono_burg_arity [MBMAX_OPCODES];\n");
		if (!with_exported_symbols)
			output ("static ");
981
982
983
984
985
986
987
988
989
990
991
992
		output ("void\nmono_burg_init (void)\n{\n");

		for (l = term_list, i = 0; l; l = l->next) {
			Term *t = (Term *)l->data;

			output ("\tmono_burg_arity [%s] = %d; /* %s */\n", t->name, t->arity, t->name);

		}

		output ("}\n\n");

	} else {
993
		output ("const guint8 mono_burg_arity [] = {\n");
994
995
996
997
998
999
1000
		for (l = term_list, i = 0; l; l = l->next) {
			Term *t = (Term *)l->data;

			while (i < t->number) {
				output ("\t0,\n");
				i++;
			}
1001

1002
1003
1004
1005
1006
1007
			output ("\t%d, /* %s */\n", t->arity, t->name);

			i++;
		}
		output ("};\n\n");

1008
		if (with_exported_symbols) {
Benoit Perrot's avatar
Benoit Perrot committed
1009
1010
1011
1012
1013
1014
1015
			output ("const char *const mono_burg_term_string [] = {\n");
			output ("\tNULL,\n");
			for (l = term_list, i = 0; l; l = l->next) {
				Term *t = (Term *)l->data;
				output ("\t\"%s\",\n", t->name);
			}
			output ("};\n\n");
1016
1017
1018
		}
	}

1019
1020
1021
1022
1023
1024
1025
1026
1027
	if (!with_exported_symbols)
		output ("static ");
	output ("const char * const mono_burg_rule_string [] = {\n");
	output ("\tNULL,\n");
	for (l = rule_list, i = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		output ("\t\"%s: ", rule->lhs->name);
		emit_tree_string (rule->tree);
		output ("\",\n");
1028
	}
1029
	output ("};\n\n");
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048

	n = g_list_length (rule_list);
	sa = g_new0 (char *, n);
	si = g_new0 (int, n);

	/* compress the _nts array */
	for (l = rule_list, i = 0, c = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		char *s = compute_nonterms (rule->tree);

		for (j = 0; j < c; j++)
			if (!strcmp (sa [j], s))
				break;

		si [i++] = j;
		if (j == c) {
			output ("static const guint16 mono_burg_nts_%d [] = { %s0 };\n", c, s);
			sa [c++] = s;
		}
1049
	}
1050
1051
	output ("\n");

1052
1053
	if (!with_exported_symbols)
		output ("static ");
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
	output ("const guint16 *const mono_burg_nts [] = {\n");
	output ("\t0,\n");
	for (l = rule_list, i = 0; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		output ("\tmono_burg_nts_%d, ", si [i++]);
		emit_rule_string (rule, "");
	}
	output ("};\n\n");
}

static void
emit_prototypes ()
{
	if (dag_mode)
1068
1069
		output ("typedef void (*MBEmitFunc) (MBState *state, MBTREE_TYPE %ctree, MBCGEN_TYPE *s);\n\n",
			(with_references ? '&' : '*'));
1070
	else
1071
1072
		output ("typedef void (*MBEmitFunc) (MBTREE_TYPE %ctree, MBCGEN_TYPE *s);\n\n",
			(with_references ? '&' : '*'));
Benoit Perrot's avatar
Benoit Perrot committed
1073

1074
	if (with_exported_symbols) {
Benoit Perrot's avatar
Benoit Perrot committed
1075
1076
		output ("extern const char * const mono_burg_term_string [];\n");
		output ("extern const char * const mono_burg_rule_string [];\n");
1077
1078
		output ("extern const guint16 *const mono_burg_nts [];\n");
		output ("extern MBEmitFunc const mono_burg_func [];\n");
1079

1080
1081
		output ("MBState *mono_burg_label (MBTREE_TYPE *tree, MBCOST_DATA *data);\n");
		output ("int mono_burg_rule (MBState *state, int goal);\n");
1082

1083
		if (dag_mode)
1084
			output ("MBState **mono_burg_kids (MBState *state, int rulenr, MBState *kids []);\n");
1085
		else
1086
			output ("MBTREE_TYPE **mono_burg_kids (MBTREE_TYPE *tree, int rulenr, MBTREE_TYPE *kids []);\n");
1087

1088
1089
		output ("extern void mono_burg_init (void);\n");
	}
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
	output ("\n");
}

static void check_reach (NonTerm *n);

static void
mark_reached (Tree *tree)
{
	if (tree->nonterm && !tree->nonterm->reached)
		check_reach (tree->nonterm);
	if (tree->left)
		mark_reached (tree->left);
	if (tree->right)
		mark_reached (tree->right);
}

static void
check_reach (NonTerm *n)
{
	GList *l;

	n->reached = 1;
	for (l = n->rules; l; l = l->next) {
		Rule *rule = (Rule *)l->data;
		mark_reached (rule->tree);
	}
}

static void
check_result ()
{
	GList *l;

	for (l = term_list; l; l = l->next) {
		Term *term = (Term *)l->data;
		if (term->arity == -1)
			g_warning ("unused terminal \"%s\"",term->name);
1127
	}
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

	check_reach (((NonTerm *)nonterm_list->data));

	for (l = nonterm_list; l; l = l->next) {
		NonTerm *n = (NonTerm *)l->data;
		if (!n->reached)
			g_warning ("unreachable nonterm \"%s\"", n->name);
	}
}

1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
void
warn_cpp (const gchar *use_of)
{
	static int b_said = FALSE;

	if (!b_said) {
		g_warning ("using %s will lead to produce C++ only code",
			   use_of);
		b_said = TRUE;
	}
}

1150
1151
1152
1153
1154
1155
1156
1157
static void
usage ()
{
	fprintf (stderr,
		 "Usage is: monoburg -d file.h -s file.c [inputfile] \n");
	exit (1);
}

1158
1159
1160
1161
1162
1163
1164
1165

static void
version ()
{
	printf ("%s\n", PACKAGE_STRING);
	exit (0);
}

1166
1167
1168
1169
1170
1171
static void
warning_handler (const gchar *log_domain,
		 GLogLevelFlags log_level,
		 const gchar *message,
		 gpointer user_data)
{
1172
1173
	(void) log_domain;
	(void) log_level;
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
	(void) fprintf ((FILE *) user_data, "** WARNING **: %s\n", message);
}

int
main (int argc, char *argv [])
{
	char *cfile = NULL;
	char *deffile = NULL;
	GList *infiles = NULL;
	int i;

        definedvars = g_hash_table_new (g_str_hash, g_str_equal);
	g_log_set_handler (NULL, G_LOG_LEVEL_WARNING, warning_handler, stderr);
1187
1188
	include_dirs = g_new (char *, 10);
	include_dirs [n_include_dir++] = ".";
1189
1190
1191

	for (i = 1; i < argc; i++){
		if (argv [i][0] == '-'){
Benoit Perrot's avatar
Benoit Perrot committed
1192
			/* Short options */
1193
1194
			if (argv [i][1] == 'h') {
				usage ();
1195
1196
			} else if (argv [i][1] == 'v') {
				version ();
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
			} else if (argv [i][1] == 'e') {
				dag_mode = 1;
			} else if (argv [i][1] == 'p') {
				predefined_terms = 1;
			} else if (argv [i][1] == 'd') {
				deffile = argv [++i];
			} else if (argv [i][1] == 's') {
				cfile = argv [++i];
			} else if (argv [i][1] == 'c') {
				default_cost = atoi (argv [++i]);
			} else if (argv [i][1] == 'D') {
                                g_hash_table_insert (definedvars, &argv [i][2],
                                                     GUINT_TO_POINTER (1));
1210
1211
1212
1213
			} else if (argv [i][1] == 'I') {
				if (n_include_dir % 10 == 0)
					include_dirs = g_renew (char *, include_dirs, n_include_dir + 10);
				include_dirs [n_include_dir++] = argv [++i];
Benoit Perrot's avatar
Benoit Perrot committed
1214
1215
1216
			} else if (argv [i][1] == '-') {

				/* Long options */
1217
				if (strcmp (argv [i] + 2, "without-glib") == 0) {
Benoit Perrot's avatar
Benoit Perrot committed
1218
					with_glib = FALSE;
1219
1220
1221
				} else if (strcmp(argv [i] + 2, "version") == 0) {
					version ();
				} else if (strcmp(argv [i] + 2, "without-exported-symbols") == 0) {
1222
					with_exported_symbols = FALSE;
1223
				} else if (strcmp(argv [i] + 2, "with-references") == 0) {
1224
					warn_cpp ("`--with-references' option");
1225
					with_references = TRUE;
Benoit Perrot's avatar
Benoit Perrot committed
1226
1227
1228
1229
				} else {
					usage ();
				}

1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
			} else {
				usage ();
			}
		} else {
			infiles = g_list_append (infiles, argv [i]);
		}
	}

	if (deffile) {
		if (!(deffd = fopen (deffile, "w"))) {
			perror ("cant open header output file");
			exit (-1);
		}
		outputfd = deffd;
		output ("#ifndef _MONO_BURG_DEFS_\n");
		output ("#define _MONO_BURG_DEFS_\n\n");
1246
	} else
1247
1248
		outputfd = stdout;

Benoit Perrot's avatar
Benoit Perrot committed
1249
	emit_includes ();
1250

1251
	inputs[0].yylineno = 0;
1252
1253
1254
1255
	if (infiles) {
		GList *l = infiles;
		while (l) {
			char *infile = (char *)l->data;
1256
			if (!(inputs[0].fd = fopen (infile, "r"))) {
1257
1258
1259
				perror ("cant open input file");
				exit (-1);
			}
1260
			inputs[0].filename = infile;
1261

1262
			output ("#line %d \"%s\"\n", 1, infile);
1263
1264
1265
1266
			yyparse ();

			reset_parser ();

1267
			l->data = inputs[0].fd;
1268
1269
1270
			l = l->next;
		}
	} else {
1271
1272
		inputs[0].fd = stdin;
		inputs[0].filename = "stdin";
1273
1274
1275
1276
1277
1278
1279
1280
1281
		yyparse ();
	}

	check_result ();

	if (!nonterm_list)
		g_error ("no start symbol found");

	emit_header ();
1282
1283
	for (i = 0; i < n_namespace; ++i)
	  output ("namespace %s {\n", namespaces[i]);
1284
	emit_term ();
1285
1286
1287
	emit_nonterm ();
	emit_state ();
	emit_prototypes ();
1288
1289
	for (i = 0; i < n_namespace; ++i)
	  output ("}\n");
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308

	if (deffd) {
		output ("#endif /* _MONO_BURG_DEFS_ */\n");
		fclose (deffd);

		if (cfile == NULL)
			outputfd = stdout;
		else {
			if (!(cfd = fopen (cfile, "w"))) {
				perror ("cant open c output file");
				(void) remove (deffile);
				exit (-1);
			}

			outputfd = cfd;
		}

		output ("#include \"%s\"\n\n", deffile);
	}
1309

1310
1311
	for (i = 0; i < n_namespace; ++i)
	  output ("namespace %s {\n", namespaces[i]);
1312
1313
1314
1315
1316
1317
1318
1319
1320
	emit_vardefs ();
	emit_cost_func ();
	emit_emitter_func ();
	emit_decoders ();

	emit_closure ();
	emit_label_func ();

	emit_kids ();
1321
1322
	for (i = 0; i < n_namespace; ++i)
	  output ("}\n");
1323
1324
1325
1326

	if (infiles) {
		GList *l = infiles;
		while (l) {
1327
			inputs[0].fd = l->data;
1328
			yyparsetail ();
1329
			fclose (inputs[0].fd);
1330
1331
1332
1333
1334
1335
1336
1337
			l = l->next;
		}
	} else {
		yyparsetail ();
	}

	if (cfile)
		fclose (cfd);
1338
	g_free (include_dirs);
1339
1340
	return 0;
}