fixes full pinyin parser
[platform/upstream/libpinyin.git] / src / storage / pinyin_parser2.cpp
1 /* 
2  *  libpinyin
3  *  Library to deal with pinyin.
4  *  
5  *  Copyright (C) 2011 Peng Wu <alexepico@gmail.com>
6  *  
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  * 
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  *  GNU General Public License for more details.
16  *  
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20  */
21
22
23 #include "pinyin_parser2.h"
24 #include <ctype.h>
25 #include <assert.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include "stl_lite.h"
29 #include "pinyin_phrase2.h"
30 #include "pinyin_custom2.h"
31 #include "chewing_key.h"
32 #include "pinyin_parser_table.h"
33 #include "double_pinyin_table.h"
34 #include "chewing_table.h"
35
36
37 using namespace pinyin;
38
39 static bool check_pinyin_options(pinyin_option_t options, const pinyin_index_item_t * item) {
40     guint32 flags = item->m_flags;
41     assert (flags & IS_PINYIN);
42
43     /* handle incomplete pinyin. */
44     if (flags & PINYIN_INCOMPLETE) {
45         if (!(options & PINYIN_INCOMPLETE))
46             return false;
47     }
48
49     /* handle correct pinyin, currently only one flag per item. */
50     flags &= PINYIN_CORRECT_ALL;
51     options &= PINYIN_CORRECT_ALL;
52
53     if (flags) {
54         if ((flags & options) != flags)
55             return false;
56     }
57
58     return true;
59 }
60
61 static bool check_chewing_options(pinyin_option_t options, const chewing_index_item_t * item) {
62     guint32 flags = item->m_flags;
63     assert (flags & IS_CHEWING);
64
65     /* handle incomplete chewing. */
66     if (flags & CHEWING_INCOMPLETE) {
67         if (!(options & CHEWING_INCOMPLETE))
68             return false;
69     }
70
71     return true;
72 }
73
74
75 gint ChewingKey::get_table_index() {
76     assert(m_initial <  CHEWING_NUMBER_OF_INITIALS);
77     assert(m_middle < CHEWING_NUMBER_OF_MIDDLES);
78     assert(m_final < CHEWING_NUMBER_OF_FINALS);
79
80     gint index = chewing_key_table[(m_initial * CHEWING_NUMBER_OF_MIDDLES + m_middle) * CHEWING_NUMBER_OF_FINALS + m_final];
81     return index == -1 ? 0 : index;
82 }
83
84 gchar * ChewingKey::get_pinyin_string() {
85     assert(m_tone < CHEWING_NUMBER_OF_TONES);
86     gint index = get_table_index();
87     assert(index < G_N_ELEMENTS(content_table));
88     const content_table_item_t & item = content_table[index];
89
90     if (CHEWING_ZERO_TONE == m_tone) {
91         return g_strdup(item.m_pinyin_str);
92     } else {
93         return g_strdup_printf("%s%d", item.m_pinyin_str, m_tone);
94     }
95 }
96
97 gchar * ChewingKey::get_chewing_string() {
98     assert(m_tone < CHEWING_NUMBER_OF_TONES);
99     gint index = get_table_index();
100     assert(index < G_N_ELEMENTS(content_table));
101     const content_table_item_t & item = content_table[index];
102
103     if (CHEWING_ZERO_TONE == m_tone) {
104         return g_strdup(item.m_chewing_str);
105     } else {
106         return g_strdup_printf("%s%s", item.m_chewing_str,
107                                chewing_tone_table[m_tone]);
108     }
109 }
110
111
112 /* Pinyin Parsers */
113
114 /* internal information for pinyin parsers. */
115 struct parse_value_t{
116     ChewingKey m_key;
117     ChewingKeyRest m_key_rest;
118     gint16 m_num_keys;
119     gint16 m_parsed_len;
120     gint16 m_last_step;
121
122     /* constructor */
123 public:
124     parse_value_t(){
125         m_num_keys = 0;
126         m_parsed_len = 0;
127         m_last_step = -1;
128     }
129 };
130
131 const guint16 max_full_pinyin_length   = 7;  /* include tone. */
132
133 const guint16 max_double_pinyin_length = 3;  /* include tone. */
134
135 const guint16 max_chewing_length       = 4;  /* include tone. */
136
137 static bool compare_pinyin_less_than(const pinyin_index_item_t & lhs,
138                                      const pinyin_index_item_t & rhs){
139     return 0 > strcmp(lhs.m_pinyin_input, rhs.m_pinyin_input);
140 }
141
142 static inline bool search_pinyin_index(pinyin_option_t options,
143                                        const char * pinyin,
144                                        ChewingKey & key){
145     pinyin_index_item_t item;
146     memset(&item, 0, sizeof(item));
147     item.m_pinyin_input = pinyin;
148
149     std_lite::pair<const pinyin_index_item_t *,
150                    const pinyin_index_item_t *> range;
151     range = std_lite::equal_range
152         (pinyin_index, pinyin_index + G_N_ELEMENTS(pinyin_index),
153          item, compare_pinyin_less_than);
154
155     guint16 range_len = range.second - range.first;
156     assert(range_len <= 1);
157     if (range_len == 1) {
158         const pinyin_index_item_t * index = range.first;
159
160         if (!check_pinyin_options(options, index))
161             return false;
162
163         key = content_table[index->m_table_index].m_chewing_key;
164         assert(key.get_table_index() == index->m_table_index);
165         return true;
166     }
167
168     return false;
169 }
170
171 static bool compare_chewing_less_than(const chewing_index_item_t & lhs,
172                                       const chewing_index_item_t & rhs){
173     return 0 > strcmp(lhs.m_chewing_input, rhs.m_chewing_input);
174 }
175
176 static inline bool search_chewing_index(pinyin_option_t options,
177                                         const char * chewing,
178                                         ChewingKey & key){
179     chewing_index_item_t item;
180     memset(&item, 0, sizeof(item));
181     item.m_chewing_input = chewing;
182
183     std_lite::pair<const chewing_index_item_t *,
184                    const chewing_index_item_t *> range;
185     range = std_lite::equal_range
186         (chewing_index, chewing_index + G_N_ELEMENTS(chewing_index),
187          item, compare_chewing_less_than);
188
189     guint16 range_len = range.second - range.first;
190     assert (range_len <= 1);
191
192     if (range_len == 1) {
193         const chewing_index_item_t * index = range.first;
194
195         if (!check_chewing_options(options, index))
196             return false;
197
198         key = content_table[index->m_table_index].m_chewing_key;
199         assert(key.get_table_index() == index->m_table_index);
200         return true;
201     }
202
203     return false;
204 }
205
206 /* Full Pinyin Parser */
207 FullPinyinParser2::FullPinyinParser2 (){
208     m_parse_steps = g_array_new(TRUE, FALSE, sizeof(parse_value_t));
209 }
210
211
212 bool FullPinyinParser2::parse_one_key (pinyin_option_t options,
213                                        ChewingKey & key,
214                                        const char * pinyin, int len) const {
215     /* "'" are not accepted in parse_one_key. */
216     gchar * input = g_strndup(pinyin, len);
217     assert(NULL == strchr(input, '\''));
218
219     guint16 tone = CHEWING_ZERO_TONE; guint16 tone_pos = 0;
220     guint16 parsed_len = len;
221     key = ChewingKey();
222
223     if (options & USE_TONE) {
224         /* find the tone in the last character. */
225         char chr = input[parsed_len - 1];
226         if ( '0' < chr && chr <= '5' ) {
227             tone = chr - '0';
228             parsed_len --;
229             tone_pos = parsed_len;
230         }
231     }
232
233     /* parse pinyin core staff here. */
234
235     /* Note: optimize here? */
236     input[parsed_len] = '\0';
237     if (!search_pinyin_index(options, input, key)) {
238         g_free(input);
239         return false;
240     }
241
242     if (options & USE_TONE) {
243         /* post processing tone. */
244         if ( parsed_len == tone_pos ) {
245             if (tone != CHEWING_ZERO_TONE) {
246                 key.m_tone = tone;
247                 parsed_len ++;
248             }
249         }
250     }
251
252     g_free(input);
253     return parsed_len == len;
254 }
255
256
257 int FullPinyinParser2::parse (pinyin_option_t options, ChewingKeyVector & keys,
258                               ChewingKeyRestVector & key_rests,
259                               const char *str, int len) const {
260     int i;
261     /* clear arrays. */
262     g_array_set_size(keys, 0);
263     g_array_set_size(key_rests, 0);
264
265     /* init m_parse_steps, and prepare dynamic programming. */
266     int step_len = len + 1;
267     g_array_set_size(m_parse_steps, 0);
268     parse_value_t value;
269     for (i = 0; i < step_len; ++i) {
270         g_array_append_val(m_parse_steps, value);
271     }
272
273     size_t next_sep = 0;
274     gchar * input = g_strndup(str, len);
275     parse_value_t * curstep = NULL, * nextstep = NULL;
276
277     for (i = 0; i < len; ++i) {
278         if (input[i] == '\'') {
279             curstep = &g_array_index(m_parse_steps, parse_value_t, i);
280             nextstep = &g_array_index(m_parse_steps, parse_value_t, i + 1);
281
282             /* propagate current step into next step. */
283             nextstep->m_key = ChewingKey();
284             nextstep->m_key_rest = ChewingKeyRest();
285             nextstep->m_num_keys = curstep->m_num_keys;
286             nextstep->m_parsed_len = curstep->m_parsed_len + 1;
287             nextstep->m_last_step = i;
288             next_sep = 0;
289             continue;
290         }
291
292         /* forward to next "'" */
293         if ( 0 == next_sep ) {
294             int k;
295             for (k = i;  k < len; ++k) {
296                 if (input[k] == '\'')
297                     break;
298             }
299             next_sep = k;
300         }
301
302 #if 0
303         /* Heuristic Method:
304          *   do maximum forward match first. */
305         for (size_t pos = i; pos < next_sep; ++pos) {
306             curstep = &g_array_index(m_parse_steps, parse_value_t, pos);
307             size_t try_len = std_lite::min
308                 (pos + max_full_pinyin_length, next_sep);
309             for (size_t n = try_len; n > pos; --n) {
310                 nextstep = &g_array_index(m_parse_steps, parse_value_t, n);
311
312                 /* gen next step */
313                 const char * onepinyin = input + pos;
314                 gint16 onepinyinlen = n - pos;
315                 value = parse_value_t();
316
317                 ChewingKey key; ChewingKeyRest rest;
318                 bool parsed = parse_one_key
319                     (options, key, onepinyin, onepinyinlen);
320                 rest.m_raw_begin = pos; rest.m_raw_end = n;
321
322                 if (!parsed)
323                     continue;
324
325                 //printf("onepinyin:%s len:%d\n", onepinyin, onepinyinlen);
326                 value.m_key = key; value.m_key_rest = rest;
327                 value.m_num_keys = curstep->m_num_keys + 1;
328                 value.m_parsed_len = curstep->m_parsed_len + onepinyinlen;
329                 value.m_last_step = pos;
330
331                 /* save next step */
332                 if (-1 == nextstep->m_last_step)
333                     *nextstep = value;
334                 if (value.m_parsed_len > nextstep->m_parsed_len)
335                     *nextstep = value;
336                 if (value.m_parsed_len == nextstep->m_parsed_len &&
337                     value.m_num_keys < nextstep->m_num_keys)
338                     *nextstep = value;
339
340                 /* maximum forward, set pos to n in next iteration. */
341                 pos = n - 1;
342                 break;
343             }
344         }
345 #endif
346
347         /* dynamic programming here. */
348         /* for (size_t m = i; m < next_sep; ++m) */
349         {
350             size_t m = i;
351             curstep = &g_array_index(m_parse_steps, parse_value_t, m);
352             size_t try_len = std_lite::min
353                 (m + max_full_pinyin_length, next_sep);
354             for (size_t n = m + 1; n < try_len + 1; ++n) {
355                 nextstep = &g_array_index(m_parse_steps, parse_value_t, n);
356
357                 /* gen next step */
358                 const char * onepinyin = input + m;
359                 gint16 onepinyinlen = n - m;
360                 value = parse_value_t();
361
362                 ChewingKey key; ChewingKeyRest rest;
363                 bool parsed = parse_one_key
364                     (options, key, onepinyin, onepinyinlen);
365                 rest.m_raw_begin = m; rest.m_raw_end = n;
366                 if (!parsed)
367                     continue;
368
369                 //printf("onepinyin:%s len:%d\n", onepinyin, onepinyinlen);
370
371                 value.m_key = key; value.m_key_rest = rest;
372                 value.m_num_keys = curstep->m_num_keys + 1;
373                 value.m_parsed_len = curstep->m_parsed_len + onepinyinlen;
374                 value.m_last_step = m;
375
376                 /* save next step */
377                 /* no previous result */
378                 if (-1 == nextstep->m_last_step)
379                     *nextstep = value;
380                 /* prefer the longest pinyin */
381                 if (value.m_parsed_len > nextstep->m_parsed_len)
382                     *nextstep = value;
383                 /* prefer the shortest keys with the same pinyin length */
384                 if (value.m_parsed_len == nextstep->m_parsed_len &&
385                     value.m_num_keys < nextstep->m_num_keys)
386                     *nextstep = value;
387
388                 /* handle with the same pinyin length and the number of keys */
389                 if (value.m_parsed_len == nextstep->m_parsed_len &&
390                     value.m_num_keys == nextstep->m_num_keys) {
391
392 #if 0
393                     /* prefer the complete pinyin with shengmu
394                      * over without shengmu,
395                      * ex: "kaneiji" -> "ka'nei'ji".
396                      */
397                     if ((value.m_key.m_initial != CHEWING_ZERO_INITIAL &&
398                          !(value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
399                            value.m_key.m_final == CHEWING_ZERO_FINAL)) &&
400                         nextstep->m_key.m_initial == CHEWING_ZERO_INITIAL)
401                         *nextstep = value;
402
403                     /* prefer the complete pinyin 'er'
404                      * over the in-complete pinyin 'r',
405                      * ex: "xierqi" -> "xi'er'qi."
406                      */
407                     if ((value.m_key.m_initial == CHEWING_ZERO_INITIAL &&
408                         value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
409                         value.m_key.m_final == CHEWING_ER) &&
410                         (nextstep->m_key.m_initial == CHEWING_R &&
411                          nextstep->m_key.m_middle == CHEWING_ZERO_MIDDLE &&
412                          nextstep->m_key.m_final == CHEWING_ZERO_FINAL))
413                         *nextstep = value;
414 #endif
415
416                     /* prefer the 'a' at the end of clause,
417                      * ex: "zheyanga$" -> "zhe'yang'a$".
418                      */
419                     if (value.m_parsed_len == len &&
420                         (nextstep->m_key.m_initial != CHEWING_ZERO_INITIAL &&
421                          nextstep->m_key.m_final == CHEWING_A) &&
422                         (value.m_key.m_initial == CHEWING_ZERO_INITIAL &&
423                          value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
424                          value.m_key.m_final == CHEWING_A))
425                         *nextstep = value;
426                 }
427             }
428         }
429     }
430
431     /* final step for back tracing. */
432     gint16 parsed_len = final_step(step_len, keys, key_rests);
433
434     /* post processing for re-split table. */
435     if (options & USE_RESPLIT_TABLE) {
436         post_process(options, keys, key_rests);
437     }
438
439     g_free(input);
440     return parsed_len;
441 }
442
443 int FullPinyinParser2::final_step(size_t step_len, ChewingKeyVector & keys,
444                                   ChewingKeyRestVector & key_rests) const{
445     int i;
446     gint16 parsed_len = 0;
447     parse_value_t * curstep = NULL;
448
449     /* find longest match, which starts from the beginning of input. */
450     for (i = step_len - 1; i >= 0; --i) {
451         curstep = &g_array_index(m_parse_steps, parse_value_t, i);
452         if (i == curstep->m_parsed_len)
453             break;
454     }
455     /* prepare saving. */
456     parsed_len = curstep->m_parsed_len;
457     gint16 num_keys = curstep->m_num_keys;
458     g_array_set_size(keys, num_keys);
459     g_array_set_size(key_rests, num_keys);
460
461     /* save the match. */
462     while (curstep->m_last_step != -1) {
463         gint16 pos = curstep->m_num_keys - 1;
464
465         /* skip "'" */
466         if (0 != curstep->m_key.get_table_index()) {
467             ChewingKey * key = &g_array_index(keys, ChewingKey, pos);
468             ChewingKeyRest * rest = &g_array_index
469                 (key_rests, ChewingKeyRest, pos);
470             *key = curstep->m_key; *rest = curstep->m_key_rest;
471         }
472
473         /* back ward */
474         curstep = &g_array_index(m_parse_steps, parse_value_t,
475                                  curstep->m_last_step);
476     }
477     return parsed_len;
478 }
479
480
481 bool FullPinyinParser2::post_process(pinyin_option_t options,
482                                      ChewingKeyVector & keys,
483                                      ChewingKeyRestVector & key_rests) const {
484     int i;
485     assert(keys->len == key_rests->len);
486     gint16 num_keys = keys->len;
487
488     ChewingKey * cur_key = NULL, * next_key = NULL;
489     ChewingKeyRest * cur_rest = NULL, * next_rest = NULL;
490     guint16 next_tone = CHEWING_ZERO_TONE;
491
492     for (i = 0; i < num_keys - 1; ++i) {
493         cur_rest = &g_array_index(key_rests, ChewingKeyRest, i);
494         next_rest = &g_array_index(key_rests, ChewingKeyRest, i + 1);
495
496         /* some "'" here */
497         if (cur_rest->m_raw_end != next_rest->m_raw_begin)
498             continue;
499
500         cur_key = &g_array_index(keys, ChewingKey, i);
501         next_key = &g_array_index(keys, ChewingKey, i + 1);
502
503         /* some tone here */
504         if (CHEWING_ZERO_TONE != cur_key->m_tone)
505             continue;
506
507         if (options & USE_TONE) {
508             next_tone = next_key->m_tone;
509             next_key->m_tone = CHEWING_ZERO_TONE;
510         }
511
512         /* lookup re-split table */
513         size_t k;
514         const resplit_table_item_t * item = NULL;
515         for (k = 0; k < G_N_ELEMENTS(resplit_table); ++k) {
516             item = resplit_table + k;
517             /* no ops */
518             if (item->m_orig_freq >= item->m_new_freq)
519                 continue;
520
521             /* use pinyin_exact_compare2 here. */
522             if (0 == pinyin_exact_compare2(item->m_orig_keys,
523                                            cur_key, 2))
524                 break;
525
526         }
527
528         /* find the match */
529         if (k < G_N_ELEMENTS(resplit_table)) {
530             /* do re-split */
531             item = resplit_table + k;
532             *cur_key = item->m_new_keys[0];
533             *next_key = item->m_new_keys[1];
534             /* assumes only moved one char in gen_all_resplit script. */
535             cur_rest->m_raw_end ++;
536             next_rest->m_raw_begin ++;
537         }
538
539         /* save back tones */
540         if (options & USE_TONE) {
541             next_key->m_tone = next_tone;
542         }
543     }
544
545     return true;
546 }
547
548 #define IS_KEY(x)   (('a' <= x && x <= 'z') || x == ';')
549
550 bool DoublePinyinParser2::parse_one_key(pinyin_option_t options,
551                                         ChewingKey & key,
552                                         const char *str, int len) const {
553     options &= ~(PINYIN_CORRECT_ALL|PINYIN_AMB_ALL);
554
555     if (1 == len) {
556         if (!(options & PINYIN_INCOMPLETE))
557             return false;
558
559         char ch = str[0];
560         if (!IS_KEY(ch))
561             return false;
562
563         int charid = ch == ';' ? 26 : ch - 'a';
564         const char * sheng = m_shengmu_table[charid].m_shengmu;
565         if (NULL == sheng || strcmp(sheng, "'") == 0)
566             return false;
567
568         if (search_pinyin_index(options, sheng, key)) {
569             return true;
570         } else {
571             return false;
572         }
573     }
574
575     ChewingTone tone = CHEWING_ZERO_TONE;
576     options &= ~(PINYIN_INCOMPLETE|CHEWING_INCOMPLETE);
577
578     /* parse tone */
579     if (3 == len) {
580         if (!(options & USE_TONE))
581             return false;
582         char ch = str[2];
583         if (!('0' < ch && ch <= '5'))
584             return false;
585         tone = (ChewingTone) (ch - '0');
586     }
587
588     if (2 == len || 3 == len) {
589         /* parse shengmu here. */
590         char ch = str[0];
591         if (!IS_KEY(ch))
592             return false;
593
594         int charid = ch == ';' ? 26 : ch - 'a';
595         const char * sheng = m_shengmu_table[charid].m_shengmu;
596         if (NULL == sheng)
597             return false;
598         if (strcmp(sheng, "'") == 0)
599             sheng = "";
600
601         /* parse yunmu here. */
602         ch = str[1];
603         if (!IS_KEY(ch))
604             return false;
605
606         charid = ch == ';' ? 26 : ch - 'a';
607         /* first yunmu */
608         const char * yun = m_yunmu_table[charid].m_yunmus[0];
609         if (NULL == yun)
610             return false;
611
612         gchar * pinyin = g_strdup_printf("%s%s", sheng, yun);
613         if (search_pinyin_index(options, pinyin, key)) {
614             key.m_tone = tone;
615             g_free(pinyin);
616             return true;
617         }
618         g_free(pinyin);
619
620         /* second yunmu */
621         yun = m_yunmu_table[charid].m_yunmus[1];
622         if (NULL == yun)
623             return false;
624
625         pinyin = g_strdup_printf("%s%s", sheng, yun);
626         if (search_pinyin_index(options, pinyin, key)) {
627             key.m_tone = tone;
628             g_free(pinyin);
629             return true;
630         }
631         g_free(pinyin);
632
633     }
634
635     return false;
636 }
637
638
639 /* only 'a'-'z' and ';' are accepted here. */
640 int DoublePinyinParser2::parse(pinyin_option_t options, ChewingKeyVector & keys,
641                                ChewingKeyRestVector & key_rests,
642                                const char *str, int len) const {
643     g_array_set_size(keys, 0);
644     g_array_set_size(key_rests, 0);
645
646     int maximum_len = 0; int i;
647     /* probe the longest possible double pinyin string. */
648     for (i = 0; i < len; ++i) {
649         const char ch = str[i];
650         if (!(IS_KEY(ch) || ('0' < ch && ch <= '5')))
651             break;
652     }
653     maximum_len = i;
654
655     /* maximum forward match for double pinyin. */
656     int parsed_len = 0;
657     while (parsed_len < maximum_len) {
658         const char * cur_str = str + parsed_len;
659         i = std_lite::min(maximum_len - parsed_len,
660                           (int)max_double_pinyin_length);
661
662         ChewingKey key; ChewingKeyRest key_rest;
663         for (; i > 0; --i) {
664             bool success = parse_one_key(options, key, cur_str, i);
665             if (success)
666                 break;
667         }
668
669         if (0 == i)        /* no more possible double pinyins. */
670             break;
671
672         key_rest.m_raw_begin = parsed_len; key_rest.m_raw_end = parsed_len + i;
673         parsed_len += i;
674
675         /* save the pinyin */
676         g_array_append_val(keys, key);
677         g_array_append_val(key_rests, key_rest);
678     }
679
680     return parsed_len;
681 }
682
683 #undef IS_KEY
684
685 bool DoublePinyinParser2::set_scheme(DoublePinyinScheme scheme) {
686
687     switch (scheme) {
688     case DOUBLE_PINYIN_ZRM:
689         m_shengmu_table = double_pinyin_zrm_sheng;
690         m_yunmu_table   = double_pinyin_zrm_yun;
691         return true;
692     case DOUBLE_PINYIN_MS:
693         m_shengmu_table = double_pinyin_mspy_sheng;
694         m_yunmu_table   = double_pinyin_mspy_yun;
695         return true;
696     case DOUBLE_PINYIN_ZIGUANG:
697         m_shengmu_table = double_pinyin_zgpy_sheng;
698         m_yunmu_table   = double_pinyin_zgpy_yun;
699         return true;
700     case DOUBLE_PINYIN_ABC:
701         m_shengmu_table = double_pinyin_abc_sheng;
702         m_yunmu_table   = double_pinyin_abc_yun;
703         return true;
704     case DOUBLE_PINYIN_PYJJ:
705         m_shengmu_table = double_pinyin_pyjj_sheng;
706         m_yunmu_table   = double_pinyin_pyjj_yun;
707         return true;
708     case DOUBLE_PINYIN_XHE:
709         m_shengmu_table = double_pinyin_xhe_sheng;
710         m_yunmu_table   = double_pinyin_xhe_yun;
711         return true;
712     case DOUBLE_PINYIN_CUSTOMIZED:
713         assert(FALSE);
714     };
715
716     return false; /* no such scheme. */
717 }
718
719 /* the chewing string must be freed with g_free. */
720 static bool search_chewing_symbols(const chewing_symbol_item_t * symbol_table,
721                                    const char key, const char ** chewing) {
722     *chewing = NULL;
723     /* just iterate the table, as we only have < 50 items. */
724     while (symbol_table->m_input != '\0') {
725         if (symbol_table->m_input == key) {
726             *chewing = symbol_table->m_chewing;
727             return true;
728         }
729         symbol_table ++;
730     }
731     return false;
732 }
733
734 static bool search_chewing_tones(const chewing_tone_item_t * tone_table,
735                                  const char key, char * tone) {
736     *tone = CHEWING_ZERO_TONE;
737     /* just iterate the table, as we only have < 10 items. */
738     while (tone_table->m_input != '\0') {
739         if (tone_table->m_input == key) {
740             *tone = tone_table->m_tone;
741             return true;
742         }
743         tone_table ++;
744     }
745     return false;
746 }
747
748
749 bool ChewingParser2::parse_one_key(pinyin_option_t options,
750                                    ChewingKey & key,
751                                    const char *str, int len) const {
752     options &= ~(PINYIN_CORRECT_ALL|PINYIN_AMB_ALL);
753     char tone = CHEWING_ZERO_TONE;
754
755     int symbols_len = len;
756     /* probe whether the last key is tone key in str. */
757     if (options & USE_TONE) {
758         char ch = str[len - 1];
759         /* remove tone from input */
760         if (search_chewing_tones(m_tone_table, ch, &tone))
761             symbols_len --;
762     }
763
764     int i;
765     gchar * chewing = NULL; const char * onechar = NULL;
766
767     /* probe the possible chewing map in the rest of str. */
768     for (i = 0; i < symbols_len; ++i) {
769         if (!search_chewing_symbols(m_symbol_table, str[i], &onechar)) {
770             g_free(chewing);
771             return false;
772         }
773
774         if (!chewing) {
775             chewing = g_strdup(onechar);
776         } else {
777             gchar * tmp = chewing;
778             chewing = g_strconcat(chewing, onechar, NULL);
779             g_free(tmp);
780         }
781     }
782
783     /* search the chewing in the chewing index table. */
784     if (chewing && search_chewing_index(options, chewing, key)) {
785         /* save back tone if available. */
786         key.m_tone = tone;
787         g_free(chewing);
788         return true;
789     }
790
791     g_free(chewing);
792     return false;
793 }
794
795
796 /* only characters in chewing keyboard scheme are accepted here. */
797 int ChewingParser2::parse(pinyin_option_t options, ChewingKeyVector & keys,
798                           ChewingKeyRestVector & key_rests,
799                           const char *str, int len) const {
800     g_array_set_size(keys, 0);
801     g_array_set_size(key_rests, 0);
802
803     int maximum_len = 0; int i;
804     /* probe the longest possible chewing string. */
805     for (i = 0; i < len; ++i) {
806         if (!in_chewing_scheme(options, str[i], NULL))
807             break;
808     }
809     maximum_len = i;
810
811     /* maximum forward match for chewing. */
812     int parsed_len = 0;
813     while (parsed_len < maximum_len) {
814         const char * cur_str = str + parsed_len;
815         i = std_lite::min(maximum_len - parsed_len,
816                           (int)max_chewing_length);
817
818         ChewingKey key; ChewingKeyRest key_rest;
819         for (; i > 0; --i) {
820             bool success = parse_one_key(options, key, cur_str, i);
821             if (success)
822                 break;
823         }
824
825         if (0 == i)        /* no more possible chewings. */
826             break;
827
828         key_rest.m_raw_begin = parsed_len; key_rest.m_raw_end = parsed_len + i;
829         parsed_len += i;
830
831         /* save the pinyin. */
832         g_array_append_val(keys, key);
833         g_array_append_val(key_rests, key_rest);
834     }
835
836     return parsed_len;
837 }
838
839
840 bool ChewingParser2::set_scheme(ChewingScheme scheme) {
841     switch(scheme) {
842     case CHEWING_STANDARD:
843         m_symbol_table = chewing_standard_symbols;
844         m_tone_table   = chewing_standard_tones;
845         return true;
846     case CHEWING_IBM:
847         m_symbol_table = chewing_ibm_symbols;
848         m_tone_table   = chewing_ibm_tones;
849         return true;
850     case CHEWING_GINYIEH:
851         m_symbol_table = chewing_ginyieh_symbols;
852         m_tone_table   = chewing_ginyieh_tones;
853         return true;
854     case CHEWING_ETEN:
855         m_symbol_table = chewing_eten_symbols;
856         m_tone_table   = chewing_eten_tones;
857         return true;
858     }
859
860     return false;
861 }
862
863
864 bool ChewingParser2::in_chewing_scheme(pinyin_option_t options,
865                                        const char key, const char ** symbol)
866  const {
867     const gchar * chewing = NULL;
868     char tone = CHEWING_ZERO_TONE;
869
870     if (search_chewing_symbols(m_symbol_table, key, &chewing)) {
871         if (symbol)
872             *symbol = chewing;
873         return true;
874     }
875
876     if (!(options & USE_TONE))
877         return false;
878
879     if (search_chewing_tones(m_tone_table, key, &tone)) {
880         if (symbol)
881             *symbol = chewing_tone_table[tone];
882         return true;
883     }
884
885     return false;
886 }