summaryrefslogtreecommitdiff
path: root/src/trie.c
blob: 51f1363e6df9c934addeaaddb0d307255832a892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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
539
540
541
542
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
/*
 * Copyright (C) 2001,2002 Red Hat, Inc.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Library General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ident "$Id$"
#include "../config.h"
#include <sys/types.h>
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <glib.h>
#include <glib-object.h>
#include "debug.h"
#include "trie.h"

#ifdef ENABLE_NLS
#include <libintl.h>
#define _(String) dgettext(PACKAGE, String)
#else
#define _(String) String
#endif

#ifndef TRIE_MAYBE_STATIC
#define TRIE_MAYBE_STATIC
#endif

/* Structures and whatnot for tracking character classes. */
struct char_class_data {
	wchar_t c;			/* A character. */
	int i;				/* An integer. */
	char *s;			/* A string. */
	int inc;			/* An increment value. */
};

struct char_class {
	enum cclass {
		exact = 0,		/* Not a special class. */
		digit,			/* Multiple-digit special class. */
		multi,			/* Multiple-number special class. */
		any,			/* Any single character. */
		string,			/* Any string of characters. */
		invalid,		/* A placeholder. */
	} type;
	gboolean multiple;		/* Whether a sequence of multiple
					   characters in this class should be
					   counted together. */
	wchar_t *code;			/* A magic string that indicates this
					   class should be found here. */
	size_t code_length;
	size_t ccount;			/* The maximum number of characters
					   after the format specifier to
					   consume. */
	gboolean (*check)(const wchar_t c, struct char_class_data *data);
					/* Function to check if a character
					   is in this class. */
	void (*setup)(const wchar_t *s, struct char_class_data *data, int inc);
					/* Setup the data struct for use in the
					 * above check function. */
	gboolean (*extract)(const wchar_t *s, size_t length,
			    struct char_class_data *data,
			    GValueArray *array);
					/* Extract a parameter. */
};

/* A table to hold shortcuts. */
struct vte_trie_table {
	struct trie_path *paths[128];
};

/* A trie to hold control sequences. */
struct vte_trie {
	const char *result;		/* If this is a terminal node, then this
					   field contains its "value". */
	GQuark quark;			/* The quark for the value of the
					   result. */
	size_t trie_path_count;		/* Number of children of this node. */
	struct trie_path {
		struct char_class *cclass;
		struct char_class_data data;
		struct vte_trie *trie;	/* The child node corresponding to this
					   character. */
	} *trie_paths;
	struct vte_trie_table *table;	/* A table filled with pointers to the
					   child nodes. */
};

/* Functions for checking if a particular character is part of a class, and
 * for setting up a structure for use when determining matches. */
static gboolean
char_class_exact_check(wchar_t c, struct char_class_data *data)
{
	return (c == data->c) ? TRUE : FALSE;
}
static void
char_class_exact_setup(const wchar_t *s, struct char_class_data *data, int inc)
{
	data->c = s[0];
	return;
}
static void
char_class_percent_setup(const wchar_t *s, struct char_class_data *data,
			 int inc)
{
	data->c = '%';
	return;
}
static gboolean
char_class_none_extract(const wchar_t *s, size_t length,
			struct char_class_data *data, GValueArray *array)
{
	return FALSE;
}

static gboolean
char_class_digit_check(wchar_t c, struct char_class_data *data)
{
	switch (c) {
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			return TRUE;
		default:
			return FALSE;
	}
	return FALSE;
}
static void
char_class_digit_setup(const wchar_t *s, struct char_class_data *data, int inc)
{
	data->inc = inc;
	return;
}
static gboolean
char_class_digit_extract(const wchar_t *s, size_t length,
			 struct char_class_data *data, GValueArray *array)
{
	long ret = 0;
	size_t i;
	GValue value;
	for (i = 0; i < length; i++) {
		ret *= 10;
		ret += (s[i] - '0');
	}
	memset(&value, 0, sizeof(value));
	g_value_init(&value, G_TYPE_LONG);
	g_value_set_long(&value, ret - data->inc);
	g_value_array_append(array, &value);
	g_value_unset(&value);
	return TRUE;
}

static gboolean
char_class_multi_check(wchar_t c, struct char_class_data *data)
{
	switch (c) {
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		case ';':
			return TRUE;
		default:
			return FALSE;
	}
	return FALSE;
}
static void
char_class_multi_setup(const wchar_t *s, struct char_class_data *data, int inc)
{
	data->inc = inc;
	return;
}
static gboolean
char_class_multi_extract(const wchar_t *s, size_t length,
			 struct char_class_data *data, GValueArray *array)
{
	long ret = 0;
	size_t i;
	GValue value;
	memset(&value, 0, sizeof(value));
	g_value_init(&value, G_TYPE_LONG);
	for (i = 0; i < length; i++) {
		if (s[i] == ';') {
			g_value_set_long(&value, ret - data->inc);
			g_value_array_append(array, &value);
			ret = 0;
		} else {
			ret *= 10;
			ret += (s[i] - '0');
		}
	}
	g_value_set_long(&value, ret - data->inc);
	g_value_array_append(array, &value);
	g_value_unset(&value);
	return TRUE;
}

static gboolean
char_class_any_check(wchar_t c, struct char_class_data *data)
{
	return (c >= data->c) ? TRUE : FALSE;
}
static void
char_class_any_setup(const wchar_t *s, struct char_class_data *data, int inc)
{
	data->c = s[0] + inc;
	return;
}
static gboolean
char_class_any_extract(const wchar_t *s, size_t length,
		       struct char_class_data *data, GValueArray *array)
{
	long ret = 0;
	GValue value;
	ret = s[0] - data->c;
	memset(&value, 0, sizeof(value));
	g_value_init(&value, G_TYPE_LONG);
	g_value_set_long(&value, ret - data->inc);
	g_value_array_append(array, &value);
	g_value_unset(&value);
	return TRUE;
}

static gboolean
char_class_string_check(wchar_t c, struct char_class_data *data)
{
	return (c != data->c) ? TRUE : FALSE;
}
static void
char_class_string_setup(const wchar_t *s, struct char_class_data *data, int inc)
{
	data->c = s[0];
	return;
}
static size_t
xwcsnlen(const wchar_t *s, size_t length)
{
	size_t i;
	for (i = 0; i < length; i++) {
		if (s[i] == '\0') {
			return i;
		}
	}
	return length;
}
static gboolean
char_class_string_extract(const wchar_t *s, size_t length,
			  struct char_class_data *data, GValueArray *array)
{
	wchar_t *ret = NULL;
	size_t len;
	GValue value;

	len = xwcsnlen(s, length);
	ret = g_malloc0((len + 1) * sizeof(wchar_t));
	wcsncpy(ret, s, len);
#ifdef VTE_DEBUG
	if (vte_debug_on(VTE_DEBUG_PARSE)) {
		fprintf(stderr, "Extracting string `%ls'.\n", ret);
	}
#endif
	memset(&value, 0, sizeof(value));

	g_value_init(&value, G_TYPE_POINTER);
	g_value_set_pointer(&value, ret);
	g_value_array_append(array, &value);
	g_value_unset(&value);

	return TRUE;
}

static wchar_t empty_wstring[] = {'\0'};
static wchar_t digit_wstring1[] = {'%', '2', '\0'};
static wchar_t digit_wstring2[] = {'%', 'd', '\0'};
static wchar_t any_wstring[] = {'%', '+', '\0'};
static wchar_t exact_wstring[] = {'%', '%', '\0'};
static wchar_t string_wstring[] = {'%', 's', '\0'};
static wchar_t multi_wstring[] = {'%', 'm', '\0'};

static struct char_class char_classes[] = {
	{exact, FALSE, empty_wstring, 0, 1,
	 char_class_exact_check,
	 char_class_exact_setup,
	 char_class_none_extract},
	{digit, TRUE, digit_wstring1, 2, 0,
	 char_class_digit_check,
	 char_class_digit_setup,
	 char_class_digit_extract},
	{digit, TRUE, digit_wstring2, 2, 0,
	 char_class_digit_check,
	 char_class_digit_setup,
	 char_class_digit_extract},
	{multi, TRUE, multi_wstring, 2, 0,
	 char_class_multi_check,
	 char_class_multi_setup,
	 char_class_multi_extract},
	{any, FALSE, any_wstring, 2, 1,
	 char_class_any_check,
	 char_class_any_setup,
	 char_class_any_extract},
	{exact, FALSE, exact_wstring, 2, 0,
	 char_class_exact_check,
	 char_class_percent_setup,
	 char_class_none_extract},
	{string, TRUE, string_wstring, 2, 0,
	 char_class_string_check,
	 char_class_string_setup,
	 char_class_string_extract},
};

/* Create a new trie. */
TRIE_MAYBE_STATIC struct vte_trie *
vte_trie_new(void)
{
	return g_malloc0(sizeof(struct vte_trie));
}

TRIE_MAYBE_STATIC void
vte_trie_free(struct vte_trie *trie)
{
	unsigned int i;
	for (i = 0; i < trie->trie_path_count; i++) {
		vte_trie_free(trie->trie_paths[i].trie);
	}
	if (trie->trie_path_count > 0) {
		g_free(trie->trie_paths);
	}
	if (trie->table != NULL) {
		g_free(trie->table);
		trie->table = NULL;
	}
	g_free(trie);
}

/* Add the given pattern, with its own result string, to the trie, with the
 * given initial increment value. */
static void
vte_trie_addx(struct vte_trie *trie, wchar_t *pattern, size_t length,
	      const char *result, GQuark quark, int inc)
{
	unsigned long i;
	struct char_class *cclass = NULL;
	struct char_class_data data;
	wchar_t *code;
	size_t len = 0, ccount = 0;
	wchar_t inc_wstring[] = {'%', 'i', '\0'};

	/* The trivial case -- we'll just set the result at this node. */
	if (length == 0) {
		if (trie->result == NULL) {
			trie->quark = g_quark_from_string(result);
			trie->result = g_quark_to_string(trie->quark);
		} else {
#ifdef VTE_DEBUG
			if (vte_debug_on(VTE_DEBUG_PARSE)) {
				g_warning(_("Duplicate (%s/%s)!"),
					  result, trie->result);
			}
#endif
		}
		return;
	}

	/* If this part of the control sequence indicates incrementing a
	 * parameter, keep track of the incrementing, skip over the increment
	 * substring, and keep going. */
	if ((length >= 2) && (wcsncmp(pattern, inc_wstring, 2) == 0)) {
		vte_trie_addx(trie, pattern + 2, length - 2,
			      result, quark, inc + 1);
		return;
	}

	/* Now check for examples of character class specifiers, and use that
	 * to put this part of the pattern in a character class. */
	for (i = G_N_ELEMENTS(char_classes) - 1; i >= 0; i--) {
		len = char_classes[i].code_length;
		code = char_classes[i].code;
		ccount = char_classes[i].ccount;
		if ((len <= length) && (wcsncmp(pattern, code, len) == 0)) {
			cclass = &char_classes[i];
			break;
		}
	}
	g_assert(i >= 0);

	/* Initialize the data item using the data we have here. */
	memset(&data, 0, sizeof(data));
	cclass->setup(pattern + len, &data, inc);

	/* Hunt for a subtrie which matches this class / data pair. */
	for (i = 0; i < trie->trie_path_count; i++) {
		struct char_class_data *tdata;
		tdata =  &trie->trie_paths[i].data;
		if ((trie->trie_paths[i].cclass == cclass) &&
		    (memcmp(&data, tdata, sizeof(data)) == 0)) {
			/* It matches, so insert the rest of the pattern into
			 * this subtrie. */
			vte_trie_addx(trie->trie_paths[i].trie,
				      pattern + (len + ccount),
				      length - (len + ccount),
				      result,
				      quark,
				      inc);
			return;
		}
	}

	/* Add a new subtrie to contain the rest of this pattern. */
	trie->trie_path_count++;
	trie->trie_paths = g_realloc(trie->trie_paths,
				     trie->trie_path_count *
				     sizeof(trie->trie_paths[0]));
	i = trie->trie_path_count - 1;
	memset(&trie->trie_paths[i], 0, sizeof(trie->trie_paths[i]));
	trie->trie_paths[i].trie = vte_trie_new();
	cclass->setup(pattern + len, &trie->trie_paths[i].data, inc);
	trie->trie_paths[i].cclass = cclass;

	/* Now insert the rest of the pattern into the node we just created. */
	vte_trie_addx(trie->trie_paths[i].trie,
		      pattern + (len + ccount),
		      length - (len + ccount),
		      result,
		      quark,
		      inc);
}

/* Add the given pattern, with its own result string, to the trie. */
TRIE_MAYBE_STATIC void
vte_trie_add(struct vte_trie *trie, const char *pattern, size_t length,
	     const char *result, GQuark quark)
{
	mbstate_t state;
	char *wpattern, *wpattern_end, *tpattern;
	GIConv conv;
	size_t wlength;

	g_return_if_fail(trie != NULL);
	g_return_if_fail(pattern != NULL);
	g_return_if_fail(length > 0);
	g_return_if_fail(result != NULL);
	if (quark == 0) {
		quark = g_quark_from_string(result);
	}

	wlength = sizeof(wchar_t) * (length + 1);
	wpattern = wpattern_end = g_malloc0(wlength + 1);
	memset(&state, 0, sizeof(state));

	conv = g_iconv_open("WCHAR_T", "UTF-8");
	if (conv != NULL) {
		tpattern = (char*)pattern;
		g_iconv(conv, &tpattern, &length, &wpattern_end, &wlength);
		if (length == 0) {
			wlength = (wpattern_end - wpattern) / sizeof(wchar_t);
			vte_trie_addx(trie, (wchar_t*)wpattern, wlength,
				      result, quark, 0);
		}
		g_iconv_close(conv);
	}

	g_free(wpattern);
}

/* Check if the given pattern matches part of the given trie, returning an
 * empty string on a partial initial match, a NULL if there's no match in the
 * works, and the result string if we have an exact match. */
static const char *
vte_trie_matchx(struct vte_trie *trie, const wchar_t *pattern, size_t length,
		gboolean greedy,
		const char **res, const wchar_t **consumed,
		GQuark *quark, GValueArray *array)
{
	unsigned int i;
	const char *hres;
	enum cclass cc;
	ssize_t partial;
	struct trie_path *path;
	const char *best = NULL;
	GValueArray *bestarray = NULL;
	GQuark bestquark = 0;
	const wchar_t *bestconsumed = pattern;

	/* Make sure that attempting to save output values doesn't kill us. */
	if (res == NULL) {
		res = &hres;
	}

	/* Trivial cases.  We've matched an entire pattern, or we're out of
	 * pattern to match. */
	if (trie->result != NULL) {
		*res = trie->result;
		*quark = trie->quark;
		*consumed = pattern;
		return *res;
	}
	if (length <= 0) {
		if (trie->trie_path_count > 0) {
			*res = "";
			*quark = g_quark_from_static_string("");
			*consumed = pattern;
			return *res;
		} else {
			*res = NULL;
			*quark = 0;
			*consumed = pattern;
			return *res;
		}
	}

	/* Try the precomputed table. */
	if ((trie->table != NULL) &&
	    (pattern[0] < G_N_ELEMENTS(trie->table->paths))) {
		if (trie->table->paths[pattern[0]] != NULL) {
			path = trie->table->paths[pattern[0]];
			if (path->cclass->multiple) {
				for (partial = 0; partial < length; partial++) {
					if (trie->table->paths[pattern[partial]] != path) {
						break;
					}
				}
			} else {
				partial = 1;
			}
			if (partial > 0) {
				path->cclass->extract(pattern,
						      partial,
						      &path->data,
						      array);
				return vte_trie_matchx(path->trie,
						       pattern + partial,
						       length - partial,
						       FALSE,
						       res,
						       consumed,
						       quark,
						       array);
			}
		}
	}

	/* Now figure out which (if any) subtrees to search.  First, see
	 * which character class this character matches. */
	for (cc = exact; cc < invalid; cc++)
	for (i = 0; i < trie->trie_path_count; i++) {
		struct vte_trie *subtrie = trie->trie_paths[i].trie;
		struct char_class *cclass = trie->trie_paths[i].cclass;
		struct char_class_data *data = &trie->trie_paths[i].data;
		if (trie->trie_paths[i].cclass->type == cc) {
			/* If it matches this character class... */
			if (cclass->check(pattern[0], data)) {
				const wchar_t *prospect = pattern + 1;
				const char *tmp;
				GQuark tmpquark = 0;
				GValueArray *tmparray;
				gboolean better = FALSE;
				/* Move past characters which might match this
				 * part of the string... */
				while (cclass->multiple &&
				       ((prospect - pattern) < length) &&
				       cclass->check(prospect[0], data)) {
					prospect++;
				}
				/* ... see if there's a parameter here, ... */
				tmparray = g_value_array_new(0);
				cclass->extract(pattern,
						prospect - pattern,
						data,
						tmparray);
				/* ... and check if the subtree matches the
				 * rest of the input string.  Any parameters
				 * further on will be appended to the array. */
				vte_trie_matchx(subtrie,
						prospect,
						length - (prospect - pattern),
						greedy,
						&tmp,
						consumed,
						&tmpquark,
						tmparray);
				/* If we haven't seen any matches yet, go ahead
				 * and go by this result. */
				if (best == NULL) {
					better = TRUE;
				}
				/* If we have a match, and we didn't have one
				 * already, go by this result. */
				if ((best != NULL) &&
				    (best[0] == '\0') &&
				    (tmp != NULL) &&
				    (tmp[0] != '\0')) {
					better = TRUE;
				}
				/* If we already have a match, and this one's
				 * better (longer if we're greedy, shorter if
				 * we're not), then go by this result. */
				if ((tmp != NULL) &&
				    (tmp[0] != '\0') &&
				    (bestconsumed != NULL) &&
				    (consumed != NULL) &&
				    (*consumed != NULL)) {
					if (greedy &&
					    (bestconsumed < *consumed)) {
						better = TRUE;
					}
					if (!greedy &&
					    (bestconsumed > *consumed)) {
						better = TRUE;
					}
				}
				if (better) {
					best = tmp;
					if (bestarray != NULL) {
						g_value_array_free(bestarray);
					}
					bestarray = tmparray;
					bestquark = tmpquark;
					bestconsumed = *consumed;
				} else {
					g_value_array_free(tmparray);
					tmparray = NULL;
				}
			}
		}
	}

	/* We're done searching.  Copy out any parameters we picked up. */
	if (bestarray != NULL) {
		for (i = 0; i < bestarray->n_values; i++) {
			g_value_array_append(array,
					     g_value_array_get_nth(bestarray,
						     		   i));
		}
		g_value_array_free(bestarray);
	}
#if 0
	g_print("`%s' ", best);
	dump_array(array);
#endif
	*quark = bestquark;
	*res = best;
	*consumed = bestconsumed;
	return *res;
}

/* Attempt to precompute all of the paths we might take when passing this
 * node, and use that information to fill in a table. */
TRIE_MAYBE_STATIC void
vte_trie_precompute(struct vte_trie *trie)
{
	struct vte_trie_table *table;
	enum cclass cc;
	int i;
	wchar_t c;

	/* Free the precomputed table (if there is one). */
	if (trie->table != NULL) {
		g_free(trie->table);
		trie->table = NULL;
	}

	/* If there are no child nodes, then there's nothing for us to do. */
	if (trie->trie_path_count == 0) {
		return;
	}

	/* Create a new table and clear it. */
	table = trie->table = g_malloc(sizeof(*table));
	for (c = 0; c < G_N_ELEMENTS(trie->table->paths); c++) {
		trie->table->paths[c] = NULL;
	}

	/* Decide which path a given character would cause us to take, and
	 * store it at a fixed offset in the table. */
	for (cc = exact; cc < invalid; cc++)
	for (i = 0; i < trie->trie_path_count; i++) {
		struct char_class *cclass = trie->trie_paths[i].cclass;
		if (cclass->type == cc)
		for (c = 0; c < G_N_ELEMENTS(trie->table->paths); c++)
		if (trie->table->paths[c] == NULL)
		if (cclass->check(c, &trie->trie_paths[i].data)) {
			trie->table->paths[c] = &trie->trie_paths[i];
		}
	}

	/* Precompute the node's children. */
	for (i = 0; i < trie->trie_path_count; i++) {
		vte_trie_precompute(trie->trie_paths[i].trie);
	}
}

/* Check if the given pattern matches part of the given trie, returning an
 * empty string on a partial initial match, a NULL if there's no match in the
 * works, and the result string if we have an exact match. */
TRIE_MAYBE_STATIC const char *
vte_trie_match(struct vte_trie *trie, const wchar_t *pattern, size_t length,
	       const char **res, const wchar_t **consumed,
	       GQuark *quark, GValueArray **array)
{
	const char *ret = NULL;
	GQuark tmpquark;
	GValueArray *valuearray;
	GValue *value;
	const wchar_t *dummyconsumed;
	gpointer ptr;
	gboolean greedy = FALSE;
	int i;

	valuearray = g_value_array_new(0);
	if (quark == NULL) {
		quark = &tmpquark;
	}
	*quark = 0;

	if (consumed == NULL) {
		consumed = &dummyconsumed;
	}
	*consumed = pattern;

	ret = vte_trie_matchx(trie, pattern, length, greedy,
			      res, consumed, quark, valuearray);

	if (((ret == NULL) || (ret[0] == '\0')) || (valuearray->n_values == 0)){
		if (valuearray != NULL) {
			for (i = 0; i < valuearray->n_values; i++) {
				value = g_value_array_get_nth(valuearray, i);
				if (G_VALUE_HOLDS_POINTER(value)) {
					ptr = g_value_get_pointer(value);
					if (ptr != NULL) {
						g_free(ptr);
					}
				}
			}
			g_value_array_free(valuearray);
		}
		*array = NULL;
	} else {
		*array = valuearray;
	}

	return ret;
}

/* Print the next layer of the trie, indented by length spaces. */
static void
vte_trie_printx(struct vte_trie *trie, const char *previous, size_t *nodecount)
{
	unsigned int i;
	char buf[LINE_MAX];

	if ((nodecount) && (trie->trie_path_count > 0)) {
		(*nodecount)++;
	}

	for (i = 0; i < trie->trie_path_count; i++) {
		memset(buf, '\0', sizeof(buf));
		snprintf(buf, sizeof(buf), "%s", previous);
		switch (trie->trie_paths[i].cclass->type) {
			case exact:
				if (trie->trie_paths[i].data.c < 32) {
					snprintf(buf + strlen(buf),
						 sizeof(buf) - strlen(buf),
						 "^%lc",
						 (wint_t)trie->trie_paths[i].data.c +
						 64);
				} else
				if (trie->trie_paths[i].data.c > 126) {
					snprintf(buf + strlen(buf),
						 sizeof(buf) - strlen(buf),
						 "[:%ld:]",
						 (long)trie->trie_paths[i].data.c);
				} else {
					snprintf(buf + strlen(buf),
						 sizeof(buf) - strlen(buf),
						 "%lc",
						 (wint_t)trie->trie_paths[i].data.c);
				}
				break;
			case digit:
				snprintf(buf + strlen(buf),
					 sizeof(buf) - strlen(buf),
					 "{num+%d}",
					 trie->trie_paths[i].data.inc);
				break;
			case multi:
				snprintf(buf + strlen(buf),
					 sizeof(buf) - strlen(buf),
					 "{multinum+%d}",
					 trie->trie_paths[i].data.inc);
				break;
			case any:
				if (trie->trie_paths[i].data.c < 32) {
					snprintf(buf + strlen(buf),
						 sizeof(buf) - strlen(buf),
						 "{char+0x%02lx}",
						 (long)trie->trie_paths[i].data.c);
				} else {
					snprintf(buf + strlen(buf),
						 sizeof(buf) - strlen(buf),
						 "{char+`%lc'}",
						 (wint_t)trie->trie_paths[i].data.c);
				}
				break;
			case string:
				snprintf(buf + strlen(buf),
					 sizeof(buf) - strlen(buf),
					 "{string}");
				break;
			case invalid:
				break;
		}
		if (trie->trie_paths[i].trie->result != NULL) {
			g_print("%s = `%s'\n", buf,
			        trie->trie_paths[i].trie->result);
		}
		vte_trie_printx(trie->trie_paths[i].trie, buf, nodecount);
	}
}

/* Print the trie. */
TRIE_MAYBE_STATIC void
vte_trie_print(struct vte_trie *trie)
{
	size_t nodecount = 0;
	vte_trie_printx(trie, "", &nodecount);
	g_print("Trie has %ld nodes.\n", (long) nodecount);
}

#ifdef TRIE_MAIN
static void
dump_array(GValueArray *array)
{
	unsigned int i;
	if (array != NULL) {
		g_print("args = {");
		for (i = 0; i < array->n_values; i++) {
			GValue *value;
			value = g_value_array_get_nth(array, i);
			if (i > 0) {
				g_print(", ");
			}
			if (G_VALUE_HOLDS_LONG(value)) {
				g_print("%ld", g_value_get_long(value));
			}
			if (G_VALUE_HOLDS_STRING(value)) {
				g_print("`%s'", g_value_get_string(value));
			}
			if (G_VALUE_HOLDS_POINTER(value)) {
				printf("`%ls'",
				       (wchar_t*)g_value_get_pointer(value));
			}
		}
		g_print("}\n");
	}
}

static void
convert_mbstowcs(const char *i, size_t ilen,
		 wchar_t *o, size_t *olen, size_t max_olen)
{
	GIConv conv;
	size_t outlen;
	conv = g_iconv_open("WCHAR_T", "UTF-8");
	if (conv != NULL) {
		memset(o, 0, max_olen);
		outlen = max_olen;
		g_iconv(conv, (char**)&i, &ilen, (char**)&o, &outlen);
		g_iconv_close(conv);
	}
	if (olen) {
		*olen = (max_olen - outlen) / sizeof(wchar_t);
	}
}

int
main(int argc, char **argv)
{
	struct vte_trie *trie;
	GValueArray *array = NULL;
	GQuark quark;
	wchar_t buf[LINE_MAX];
	const wchar_t *consumed;
	size_t buflen;

	g_type_init();
	trie = vte_trie_new();

	vte_trie_add(trie, "abcdef", 6, "abcdef",
		     g_quark_from_string("abcdef"));
	vte_trie_add(trie, "abcde", 5, "abcde",
		     g_quark_from_string("abcde"));
	vte_trie_add(trie, "abcdeg", 6, "abcdeg",
		     g_quark_from_string("abcdeg"));
	vte_trie_add(trie, "abc%+Aeg", 8, "abc%+Aeg",
		     g_quark_from_string("abc%+Aeg"));
	vte_trie_add(trie, "abc%deg", 7, "abc%deg",
		     g_quark_from_string("abc%deg"));
	vte_trie_add(trie, "abc%%eg", 7, "abc%%eg",
		     g_quark_from_string("abc%%eg"));
	vte_trie_add(trie, "abc%%%i%deg", 11, "abc%%%i%deg",
		     g_quark_from_string("abc%%%i%deg"));
	vte_trie_add(trie, "<esc>[%i%d;%dH", 14, "vtmatch",
		     g_quark_from_string("vtmatch"));
	vte_trie_add(trie, "<esc>[%i%mL", 11, "multimatch",
		     g_quark_from_string("multimatch"));
	vte_trie_add(trie, "<esc>[%mL<esc>[%mL", 18, "greedy",
		     g_quark_from_string("greedy"));
	vte_trie_add(trie, "<esc>]2;%sh", 11, "decset-title",
		     g_quark_from_string("decset-title"));
	if (argc > 1) {
		if (strcmp(argv[1], "--precompute") == 0) {
			vte_trie_precompute(trie);
		}
	}
	vte_trie_print(trie);
	g_print("\n");

	quark = 0;
	convert_mbstowcs("abc", 3, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abc",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abcdef", 6, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abcdef",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abcde", 5, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abcde",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abcdeg", 6, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abcdeg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abc%deg", 7, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abc%deg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abc10eg", 7, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abc10eg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abc%eg", 6, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abc%eg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abc%10eg", 8, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abc%10eg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("abcBeg", 6, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "abcBeg",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("<esc>[25;26H", 12, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>[25;26H",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("<esc>[25;2", 10, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>[25;2",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
	}

	quark = 0;
	convert_mbstowcs("<esc>[25L", 9, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>[25L",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
	}

	quark = 0;
	convert_mbstowcs("<esc>[25L<esc>[24L", 18, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>[25L<esc>[24L",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
	}

	quark = 0;
	convert_mbstowcs("<esc>[25;26L", 12, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>[25;26L",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
	}

	quark = 0;
	convert_mbstowcs("<esc>]2;WoofWoofh", 17, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>]2;WoofWoofh",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("<esc>]2;WoofWoofh<esc>]2;WoofWoofh", 34,
			 buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>]2;WoofWoofh<esc>]2;WoofWoofh",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	quark = 0;
	convert_mbstowcs("<esc>]2;WoofWoofhfoo", 20, buf, &buflen, sizeof(buf));
	g_print("`%s' = `%s'\n", "<esc>]2;WoofWoofhfoo",
	        vte_trie_match(trie, buf, buflen,
			       NULL, &consumed, &quark, &array));
	g_print("=> `%s' (%d)\n", g_quark_to_string(quark), consumed - buf);
	if (array != NULL) {
		dump_array(array);
		g_value_array_free(array);
		array = NULL;
	}

	vte_trie_free(trie);

	return 0;
}
#endif