add get_shengmu/yunmu_string
[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_shengmu_string() {
98     gint index = get_table_index();
99     assert(index < G_N_ELEMENTS(content_table));
100     const content_table_item_t & item = content_table[index];
101     return g_strdup(item.m_shengmu_str);
102 }
103
104 gchar * ChewingKey::get_yunmu_string() {
105     gint index = get_table_index();
106     assert(index < G_N_ELEMENTS(content_table));
107     const content_table_item_t & item = content_table[index];
108     return g_strdup(item.m_yunmu_str);
109 }
110
111 gchar * ChewingKey::get_chewing_string() {
112     assert(m_tone < CHEWING_NUMBER_OF_TONES);
113     gint index = get_table_index();
114     assert(index < G_N_ELEMENTS(content_table));
115     const content_table_item_t & item = content_table[index];
116
117     if (CHEWING_ZERO_TONE == m_tone) {
118         return g_strdup(item.m_chewing_str);
119     } else {
120         return g_strdup_printf("%s%s", item.m_chewing_str,
121                                chewing_tone_table[m_tone]);
122     }
123 }
124
125
126 /* Pinyin Parsers */
127
128 /* internal information for pinyin parsers. */
129 struct parse_value_t{
130     ChewingKey m_key;
131     ChewingKeyRest m_key_rest;
132     gint16 m_num_keys;
133     gint16 m_parsed_len;
134     gint16 m_last_step;
135
136     /* constructor */
137 public:
138     parse_value_t(){
139         m_num_keys = 0;
140         m_parsed_len = 0;
141         m_last_step = -1;
142     }
143 };
144
145 const guint16 max_full_pinyin_length   = 7;  /* include tone. */
146
147 const guint16 max_double_pinyin_length = 3;  /* include tone. */
148
149 const guint16 max_chewing_length       = 4;  /* include tone. */
150
151 static bool compare_pinyin_less_than(const pinyin_index_item_t & lhs,
152                                      const pinyin_index_item_t & rhs){
153     return 0 > strcmp(lhs.m_pinyin_input, rhs.m_pinyin_input);
154 }
155
156 static inline bool search_pinyin_index(pinyin_option_t options,
157                                        const char * pinyin,
158                                        ChewingKey & key){
159     pinyin_index_item_t item;
160     memset(&item, 0, sizeof(item));
161     item.m_pinyin_input = pinyin;
162
163     std_lite::pair<const pinyin_index_item_t *,
164                    const pinyin_index_item_t *> range;
165     range = std_lite::equal_range
166         (pinyin_index, pinyin_index + G_N_ELEMENTS(pinyin_index),
167          item, compare_pinyin_less_than);
168
169     guint16 range_len = range.second - range.first;
170     assert(range_len <= 1);
171     if (range_len == 1) {
172         const pinyin_index_item_t * index = range.first;
173
174         if (!check_pinyin_options(options, index))
175             return false;
176
177         key = content_table[index->m_table_index].m_chewing_key;
178         assert(key.get_table_index() == index->m_table_index);
179         return true;
180     }
181
182     return false;
183 }
184
185 static bool compare_chewing_less_than(const chewing_index_item_t & lhs,
186                                       const chewing_index_item_t & rhs){
187     return 0 > strcmp(lhs.m_chewing_input, rhs.m_chewing_input);
188 }
189
190 static inline bool search_chewing_index(pinyin_option_t options,
191                                         const char * chewing,
192                                         ChewingKey & key){
193     chewing_index_item_t item;
194     memset(&item, 0, sizeof(item));
195     item.m_chewing_input = chewing;
196
197     std_lite::pair<const chewing_index_item_t *,
198                    const chewing_index_item_t *> range;
199     range = std_lite::equal_range
200         (chewing_index, chewing_index + G_N_ELEMENTS(chewing_index),
201          item, compare_chewing_less_than);
202
203     guint16 range_len = range.second - range.first;
204     assert (range_len <= 1);
205
206     if (range_len == 1) {
207         const chewing_index_item_t * index = range.first;
208
209         if (!check_chewing_options(options, index))
210             return false;
211
212         key = content_table[index->m_table_index].m_chewing_key;
213         assert(key.get_table_index() == index->m_table_index);
214         return true;
215     }
216
217     return false;
218 }
219
220 /* Full Pinyin Parser */
221 FullPinyinParser2::FullPinyinParser2 (){
222     m_parse_steps = g_array_new(TRUE, FALSE, sizeof(parse_value_t));
223 }
224
225
226 bool FullPinyinParser2::parse_one_key (pinyin_option_t options,
227                                        ChewingKey & key,
228                                        const char * pinyin, int len) const {
229     /* "'" are not accepted in parse_one_key. */
230     gchar * input = g_strndup(pinyin, len);
231     assert(NULL == strchr(input, '\''));
232
233     guint16 tone = CHEWING_ZERO_TONE; guint16 tone_pos = 0;
234     guint16 parsed_len = len;
235     key = ChewingKey();
236
237     if (options & USE_TONE) {
238         /* find the tone in the last character. */
239         char chr = input[parsed_len - 1];
240         if ( '0' < chr && chr <= '5' ) {
241             tone = chr - '0';
242             parsed_len --;
243             tone_pos = parsed_len;
244         }
245     }
246
247     /* parse pinyin core staff here. */
248
249     /* Note: optimize here? */
250     input[parsed_len] = '\0';
251     if (!search_pinyin_index(options, input, key)) {
252         g_free(input);
253         return false;
254     }
255
256     if (options & USE_TONE) {
257         /* post processing tone. */
258         if ( parsed_len == tone_pos ) {
259             if (tone != CHEWING_ZERO_TONE) {
260                 key.m_tone = tone;
261                 parsed_len ++;
262             }
263         }
264     }
265
266     g_free(input);
267     return parsed_len == len;
268 }
269
270
271 int FullPinyinParser2::parse (pinyin_option_t options, ChewingKeyVector & keys,
272                               ChewingKeyRestVector & key_rests,
273                               const char *str, int len) const {
274     int i;
275     /* clear arrays. */
276     g_array_set_size(keys, 0);
277     g_array_set_size(key_rests, 0);
278
279     /* init m_parse_steps, and prepare dynamic programming. */
280     int step_len = len + 1;
281     g_array_set_size(m_parse_steps, 0);
282     parse_value_t value;
283     for (i = 0; i < step_len; ++i) {
284         g_array_append_val(m_parse_steps, value);
285     }
286
287     size_t next_sep = 0;
288     gchar * input = g_strndup(str, len);
289     parse_value_t * curstep = NULL, * nextstep = NULL;
290
291     for (i = 0; i < len; ++i) {
292         if (input[i] == '\'') {
293             curstep = &g_array_index(m_parse_steps, parse_value_t, i);
294             nextstep = &g_array_index(m_parse_steps, parse_value_t, i + 1);
295
296             /* propagate current step into next step. */
297             nextstep->m_key = ChewingKey();
298             nextstep->m_key_rest = ChewingKeyRest();
299             nextstep->m_num_keys = curstep->m_num_keys;
300             nextstep->m_parsed_len = curstep->m_parsed_len + 1;
301             nextstep->m_last_step = i;
302             next_sep = 0;
303             continue;
304         }
305
306         /* forward to next "'" */
307         if ( 0 == next_sep ) {
308             int k;
309             for (k = i;  k < len; ++k) {
310                 if (input[k] == '\'')
311                     break;
312             }
313             next_sep = k;
314         }
315
316         /* dynamic programming here. */
317         /* for (size_t m = i; m < next_sep; ++m) */
318         {
319             size_t m = i;
320             curstep = &g_array_index(m_parse_steps, parse_value_t, m);
321             size_t try_len = std_lite::min
322                 (m + max_full_pinyin_length, next_sep);
323             for (size_t n = m + 1; n < try_len + 1; ++n) {
324                 nextstep = &g_array_index(m_parse_steps, parse_value_t, n);
325
326                 /* gen next step */
327                 const char * onepinyin = input + m;
328                 gint16 onepinyinlen = n - m;
329                 value = parse_value_t();
330
331                 ChewingKey key; ChewingKeyRest rest;
332                 bool parsed = parse_one_key
333                     (options, key, onepinyin, onepinyinlen);
334                 rest.m_raw_begin = m; rest.m_raw_end = n;
335                 if (!parsed)
336                     continue;
337
338                 //printf("onepinyin:%s len:%d\n", onepinyin, onepinyinlen);
339
340                 value.m_key = key; value.m_key_rest = rest;
341                 value.m_num_keys = curstep->m_num_keys + 1;
342                 value.m_parsed_len = curstep->m_parsed_len + onepinyinlen;
343                 value.m_last_step = m;
344
345                 /* save next step */
346                 /* no previous result */
347                 if (-1 == nextstep->m_last_step)
348                     *nextstep = value;
349                 /* prefer the longest pinyin */
350                 if (value.m_parsed_len > nextstep->m_parsed_len)
351                     *nextstep = value;
352                 /* prefer the shortest keys with the same pinyin length */
353                 if (value.m_parsed_len == nextstep->m_parsed_len &&
354                     value.m_num_keys < nextstep->m_num_keys)
355                     *nextstep = value;
356
357                 /* handle with the same pinyin length and the number of keys */
358                 if (value.m_parsed_len == nextstep->m_parsed_len &&
359                     value.m_num_keys == nextstep->m_num_keys) {
360
361 #if 0
362                     /* prefer the complete pinyin with shengmu
363                      * over without shengmu,
364                      * ex: "kaneiji" -> "ka'nei'ji".
365                      */
366                     if ((value.m_key.m_initial != CHEWING_ZERO_INITIAL &&
367                          !(value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
368                            value.m_key.m_final == CHEWING_ZERO_FINAL)) &&
369                         nextstep->m_key.m_initial == CHEWING_ZERO_INITIAL)
370                         *nextstep = value;
371
372                     /* prefer the complete pinyin 'er'
373                      * over the in-complete pinyin 'r',
374                      * ex: "xierqi" -> "xi'er'qi."
375                      */
376                     if ((value.m_key.m_initial == CHEWING_ZERO_INITIAL &&
377                         value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
378                         value.m_key.m_final == CHEWING_ER) &&
379                         (nextstep->m_key.m_initial == CHEWING_R &&
380                          nextstep->m_key.m_middle == CHEWING_ZERO_MIDDLE &&
381                          nextstep->m_key.m_final == CHEWING_ZERO_FINAL))
382                         *nextstep = value;
383 #endif
384
385                     /* prefer the 'a' at the end of clause,
386                      * ex: "zheyanga$" -> "zhe'yang'a$".
387                      */
388                     if (value.m_parsed_len == len &&
389                         (nextstep->m_key.m_initial != CHEWING_ZERO_INITIAL &&
390                          nextstep->m_key.m_final == CHEWING_A) &&
391                         (value.m_key.m_initial == CHEWING_ZERO_INITIAL &&
392                          value.m_key.m_middle == CHEWING_ZERO_MIDDLE &&
393                          value.m_key.m_final == CHEWING_A))
394                         *nextstep = value;
395                 }
396             }
397         }
398     }
399
400     /* final step for back tracing. */
401     gint16 parsed_len = final_step(step_len, keys, key_rests);
402
403     /* post processing for re-split table. */
404     if (options & USE_RESPLIT_TABLE) {
405         post_process2(options, keys, key_rests, str, len);
406     }
407
408     g_free(input);
409     return parsed_len;
410 }
411
412 int FullPinyinParser2::final_step(size_t step_len, ChewingKeyVector & keys,
413                                   ChewingKeyRestVector & key_rests) const{
414     int i;
415     gint16 parsed_len = 0;
416     parse_value_t * curstep = NULL;
417
418     /* find longest match, which starts from the beginning of input. */
419     for (i = step_len - 1; i >= 0; --i) {
420         curstep = &g_array_index(m_parse_steps, parse_value_t, i);
421         if (i == curstep->m_parsed_len)
422             break;
423     }
424     /* prepare saving. */
425     parsed_len = curstep->m_parsed_len;
426     gint16 num_keys = curstep->m_num_keys;
427     g_array_set_size(keys, num_keys);
428     g_array_set_size(key_rests, num_keys);
429
430     /* save the match. */
431     while (curstep->m_last_step != -1) {
432         gint16 pos = curstep->m_num_keys - 1;
433
434         /* skip "'" */
435         if (0 != curstep->m_key.get_table_index()) {
436             ChewingKey * key = &g_array_index(keys, ChewingKey, pos);
437             ChewingKeyRest * rest = &g_array_index
438                 (key_rests, ChewingKeyRest, pos);
439             *key = curstep->m_key; *rest = curstep->m_key_rest;
440         }
441
442         /* back ward */
443         curstep = &g_array_index(m_parse_steps, parse_value_t,
444                                  curstep->m_last_step);
445     }
446     return parsed_len;
447 }
448
449 bool FullPinyinParser2::post_process2(pinyin_option_t options,
450                                       ChewingKeyVector & keys,
451                                       ChewingKeyRestVector & key_rests,
452                                       const char * str,
453                                       int len) const {
454     int i;
455     assert(keys->len == key_rests->len);
456     gint num_keys = keys->len;
457
458     ChewingKey * cur_key = NULL, * next_key = NULL;
459     ChewingKeyRest * cur_rest = NULL, * next_rest = NULL;
460     guint16 next_tone = CHEWING_ZERO_TONE;
461
462     for (i = 0; i < num_keys - 1; ++i) {
463         cur_rest = &g_array_index(key_rests, ChewingKeyRest, i);
464         next_rest = &g_array_index(key_rests, ChewingKeyRest, i + 1);
465
466         /* some "'" here */
467         if (cur_rest->m_raw_end != next_rest->m_raw_begin)
468             continue;
469
470         cur_key = &g_array_index(keys, ChewingKey, i);
471         next_key = &g_array_index(keys, ChewingKey, i + 1);
472
473         /* some tone here */
474         if (CHEWING_ZERO_TONE != cur_key->m_tone)
475             continue;
476
477         /* back up tone */
478         if (options & USE_TONE) {
479             next_tone = next_key->m_tone;
480             if (CHEWING_ZERO_TONE != next_tone) {
481                 next_key->m_tone = CHEWING_ZERO_TONE;
482                 next_rest->m_raw_end --;
483             }
484         }
485
486         /* lookup re-split table */
487         const resplit_table_item_t * item = NULL;
488
489         item = retrieve_resplit_item_by_original_pinyins
490             (options, cur_key, cur_rest, next_key, next_rest, str, len);
491
492         if (item) {
493             /* no ops */
494             if (item->m_orig_freq >= item->m_new_freq)
495                 continue;
496
497             /* do re-split */
498             const char * onepinyin = str + cur_rest->m_raw_begin;
499             size_t len = strlen(item->m_new_keys[0]);
500
501             assert(parse_one_key(options, *cur_key, onepinyin, len));
502             cur_rest->m_raw_end = cur_rest->m_raw_begin + len;
503
504             next_rest->m_raw_begin = cur_rest->m_raw_end;
505             onepinyin = str + next_rest->m_raw_begin;
506             len = strlen(item->m_new_keys[1]);
507
508             assert(parse_one_key(options, *next_key, onepinyin, len));
509         }
510
511         /* restore tones */
512         if (options & USE_TONE) {
513             if (CHEWING_ZERO_TONE != next_tone) {
514                 next_key->m_tone = next_tone;
515                 next_rest->m_raw_end ++;
516             }
517         }
518     }
519
520     return true;
521 }
522
523 const divided_table_item_t * FullPinyinParser2::retrieve_divided_item
524 (pinyin_option_t options, ChewingKey * key, ChewingKeyRest * rest,
525  const char * str, int len) const {
526
527     /* lookup divided table */
528     size_t k;
529     const divided_table_item_t * item = NULL;
530     for (k = 0; k < G_N_ELEMENTS(divided_table); ++k) {
531         item = divided_table + k;
532
533         const char * onepinyin = str + rest->m_raw_begin;
534         size_t len = strlen(item->m_orig_key);
535
536         if (rest->length() != len)
537             continue;
538
539         if (0 == strncmp(onepinyin, item->m_orig_key, len))
540             break;
541     }
542
543     /* found the match */
544     if (k < G_N_ELEMENTS(divided_table)) {
545         /* do divided */
546         item = divided_table + k;
547         return item;
548     }
549
550     return NULL;
551 }
552
553
554 const resplit_table_item_t * FullPinyinParser2::retrieve_resplit_item_by_original_pinyins
555 (pinyin_option_t options,
556  ChewingKey * cur_key, ChewingKeyRest * cur_rest,
557  ChewingKey * next_key, ChewingKeyRest * next_rest,
558  const char * str, int len) const{
559     /* lookup re-split table */
560     size_t k;
561     const resplit_table_item_t * item = NULL;
562
563     for (k = 0; k < G_N_ELEMENTS(resplit_table); ++k) {
564         item = resplit_table + k;
565
566         const char * onepinyin = str + cur_rest->m_raw_begin;
567         size_t len = strlen(item->m_orig_keys[0]);
568
569         if (cur_rest->length() != len)
570             continue;
571
572         if (0 != strncmp(onepinyin, item->m_orig_keys[0], len))
573             continue;
574
575         onepinyin = str + next_rest->m_raw_begin;
576         len = strlen(item->m_orig_keys[1]);
577
578         if (next_rest->length() != len)
579             continue;
580
581         if (0 == strncmp(onepinyin, item->m_orig_keys[1], len))
582             break;
583     }
584
585     /* found the match */
586     if (k < G_N_ELEMENTS(resplit_table)) {
587         item = resplit_table + k;
588         return item;
589     }
590
591     return NULL;
592 }
593
594 const resplit_table_item_t * FullPinyinParser2::retrieve_resplit_item_by_resplit_pinyins
595 (pinyin_option_t options,
596  ChewingKey * cur_key, ChewingKeyRest * cur_rest,
597  ChewingKey * next_key, ChewingKeyRest * next_rest,
598  const char * str, int len) const {
599     /* lookup divide table */
600     size_t k;
601     const resplit_table_item_t * item = NULL;
602
603     for (k = 0; k < G_N_ELEMENTS(resplit_table); ++k) {
604         item = resplit_table + k;
605
606         const char * onepinyin = str + cur_rest->m_raw_begin;
607         size_t len = strlen(item->m_new_keys[0]);
608
609         if (cur_rest->length() != len)
610             continue;
611
612         if (0 != strncmp(onepinyin, item->m_new_keys[0], len))
613             continue;
614
615         onepinyin = str + next_rest->m_raw_begin;
616         len = strlen(item->m_new_keys[1]);
617
618         if (next_rest->length() != len)
619             continue;
620
621         if (0 == strncmp(onepinyin, item->m_new_keys[1], len))
622             break;
623     }
624
625     /* found the match */
626     if (k < G_N_ELEMENTS(resplit_table)) {
627         item = resplit_table + k;
628         return item;
629     }
630
631     return NULL;
632 }
633
634 #define IS_KEY(x)   (('a' <= x && x <= 'z') || x == ';')
635
636 bool DoublePinyinParser2::parse_one_key(pinyin_option_t options,
637                                         ChewingKey & key,
638                                         const char *str, int len) const {
639     options &= ~(PINYIN_CORRECT_ALL|PINYIN_AMB_ALL);
640
641     if (1 == len) {
642         if (!(options & PINYIN_INCOMPLETE))
643             return false;
644
645         char ch = str[0];
646         if (!IS_KEY(ch))
647             return false;
648
649         int charid = ch == ';' ? 26 : ch - 'a';
650         const char * sheng = m_shengmu_table[charid].m_shengmu;
651         if (NULL == sheng || strcmp(sheng, "'") == 0)
652             return false;
653
654         if (search_pinyin_index(options, sheng, key)) {
655             return true;
656         } else {
657             return false;
658         }
659     }
660
661     ChewingTone tone = CHEWING_ZERO_TONE;
662     options &= ~(PINYIN_INCOMPLETE|CHEWING_INCOMPLETE);
663     options |= PINYIN_CORRECT_UE_VE | PINYIN_CORRECT_V_U;
664
665     /* parse tone */
666     if (3 == len) {
667         if (!(options & USE_TONE))
668             return false;
669         char ch = str[2];
670         if (!('0' < ch && ch <= '5'))
671             return false;
672         tone = (ChewingTone) (ch - '0');
673     }
674
675     if (2 == len || 3 == len) {
676         /* parse shengmu here. */
677         char ch = str[0];
678         if (!IS_KEY(ch))
679             return false;
680
681         int charid = ch == ';' ? 26 : ch - 'a';
682         const char * sheng = m_shengmu_table[charid].m_shengmu;
683         if (NULL == sheng)
684             return false;
685         if (strcmp(sheng, "'") == 0)
686             sheng = "";
687
688         /* parse yunmu here. */
689         ch = str[1];
690         if (!IS_KEY(ch))
691             return false;
692
693         charid = ch == ';' ? 26 : ch - 'a';
694         /* first yunmu */
695         const char * yun = m_yunmu_table[charid].m_yunmus[0];
696         if (NULL == yun)
697             return false;
698
699         gchar * pinyin = g_strdup_printf("%s%s", sheng, yun);
700         if (search_pinyin_index(options, pinyin, key)) {
701             key.m_tone = tone;
702             g_free(pinyin);
703             return true;
704         }
705         g_free(pinyin);
706
707         /* second yunmu */
708         yun = m_yunmu_table[charid].m_yunmus[1];
709         if (NULL == yun)
710             return false;
711
712         pinyin = g_strdup_printf("%s%s", sheng, yun);
713         if (search_pinyin_index(options, pinyin, key)) {
714             key.m_tone = tone;
715             g_free(pinyin);
716             return true;
717         }
718         g_free(pinyin);
719
720     }
721
722     return false;
723 }
724
725
726 /* only 'a'-'z' and ';' are accepted here. */
727 int DoublePinyinParser2::parse(pinyin_option_t options, ChewingKeyVector & keys,
728                                ChewingKeyRestVector & key_rests,
729                                const char *str, int len) const {
730     g_array_set_size(keys, 0);
731     g_array_set_size(key_rests, 0);
732
733     int maximum_len = 0; int i;
734     /* probe the longest possible double pinyin string. */
735     for (i = 0; i < len; ++i) {
736         const char ch = str[i];
737         if (!(IS_KEY(ch) || ('0' < ch && ch <= '5')))
738             break;
739     }
740     maximum_len = i;
741
742     /* maximum forward match for double pinyin. */
743     int parsed_len = 0;
744     while (parsed_len < maximum_len) {
745         const char * cur_str = str + parsed_len;
746         i = std_lite::min(maximum_len - parsed_len,
747                           (int)max_double_pinyin_length);
748
749         ChewingKey key; ChewingKeyRest key_rest;
750         for (; i > 0; --i) {
751             bool success = parse_one_key(options, key, cur_str, i);
752             if (success)
753                 break;
754         }
755
756         if (0 == i)        /* no more possible double pinyins. */
757             break;
758
759         key_rest.m_raw_begin = parsed_len; key_rest.m_raw_end = parsed_len + i;
760         parsed_len += i;
761
762         /* save the pinyin */
763         g_array_append_val(keys, key);
764         g_array_append_val(key_rests, key_rest);
765     }
766
767     return parsed_len;
768 }
769
770 #undef IS_KEY
771
772 bool DoublePinyinParser2::set_scheme(DoublePinyinScheme scheme) {
773
774     switch (scheme) {
775     case DOUBLE_PINYIN_ZRM:
776         m_shengmu_table = double_pinyin_zrm_sheng;
777         m_yunmu_table   = double_pinyin_zrm_yun;
778         return true;
779     case DOUBLE_PINYIN_MS:
780         m_shengmu_table = double_pinyin_mspy_sheng;
781         m_yunmu_table   = double_pinyin_mspy_yun;
782         return true;
783     case DOUBLE_PINYIN_ZIGUANG:
784         m_shengmu_table = double_pinyin_zgpy_sheng;
785         m_yunmu_table   = double_pinyin_zgpy_yun;
786         return true;
787     case DOUBLE_PINYIN_ABC:
788         m_shengmu_table = double_pinyin_abc_sheng;
789         m_yunmu_table   = double_pinyin_abc_yun;
790         return true;
791     case DOUBLE_PINYIN_PYJJ:
792         m_shengmu_table = double_pinyin_pyjj_sheng;
793         m_yunmu_table   = double_pinyin_pyjj_yun;
794         return true;
795     case DOUBLE_PINYIN_XHE:
796         m_shengmu_table = double_pinyin_xhe_sheng;
797         m_yunmu_table   = double_pinyin_xhe_yun;
798         return true;
799     case DOUBLE_PINYIN_CUSTOMIZED:
800         assert(FALSE);
801     };
802
803     return false; /* no such scheme. */
804 }
805
806 /* the chewing string must be freed with g_free. */
807 static bool search_chewing_symbols(const chewing_symbol_item_t * symbol_table,
808                                    const char key, const char ** chewing) {
809     *chewing = NULL;
810     /* just iterate the table, as we only have < 50 items. */
811     while (symbol_table->m_input != '\0') {
812         if (symbol_table->m_input == key) {
813             *chewing = symbol_table->m_chewing;
814             return true;
815         }
816         symbol_table ++;
817     }
818     return false;
819 }
820
821 static bool search_chewing_tones(const chewing_tone_item_t * tone_table,
822                                  const char key, char * tone) {
823     *tone = CHEWING_ZERO_TONE;
824     /* just iterate the table, as we only have < 10 items. */
825     while (tone_table->m_input != '\0') {
826         if (tone_table->m_input == key) {
827             *tone = tone_table->m_tone;
828             return true;
829         }
830         tone_table ++;
831     }
832     return false;
833 }
834
835
836 bool ChewingParser2::parse_one_key(pinyin_option_t options,
837                                    ChewingKey & key,
838                                    const char *str, int len) const {
839     options &= ~(PINYIN_CORRECT_ALL|PINYIN_AMB_ALL);
840     char tone = CHEWING_ZERO_TONE;
841
842     int symbols_len = len;
843     /* probe whether the last key is tone key in str. */
844     if (options & USE_TONE) {
845         char ch = str[len - 1];
846         /* remove tone from input */
847         if (search_chewing_tones(m_tone_table, ch, &tone))
848             symbols_len --;
849     }
850
851     int i;
852     gchar * chewing = NULL; const char * onechar = NULL;
853
854     /* probe the possible chewing map in the rest of str. */
855     for (i = 0; i < symbols_len; ++i) {
856         if (!search_chewing_symbols(m_symbol_table, str[i], &onechar)) {
857             g_free(chewing);
858             return false;
859         }
860
861         if (!chewing) {
862             chewing = g_strdup(onechar);
863         } else {
864             gchar * tmp = chewing;
865             chewing = g_strconcat(chewing, onechar, NULL);
866             g_free(tmp);
867         }
868     }
869
870     /* search the chewing in the chewing index table. */
871     if (chewing && search_chewing_index(options, chewing, key)) {
872         /* save back tone if available. */
873         key.m_tone = tone;
874         g_free(chewing);
875         return true;
876     }
877
878     g_free(chewing);
879     return false;
880 }
881
882
883 /* only characters in chewing keyboard scheme are accepted here. */
884 int ChewingParser2::parse(pinyin_option_t options, ChewingKeyVector & keys,
885                           ChewingKeyRestVector & key_rests,
886                           const char *str, int len) const {
887     g_array_set_size(keys, 0);
888     g_array_set_size(key_rests, 0);
889
890     int maximum_len = 0; int i;
891     /* probe the longest possible chewing string. */
892     for (i = 0; i < len; ++i) {
893         if (!in_chewing_scheme(options, str[i], NULL))
894             break;
895     }
896     maximum_len = i;
897
898     /* maximum forward match for chewing. */
899     int parsed_len = 0;
900     while (parsed_len < maximum_len) {
901         const char * cur_str = str + parsed_len;
902         i = std_lite::min(maximum_len - parsed_len,
903                           (int)max_chewing_length);
904
905         ChewingKey key; ChewingKeyRest key_rest;
906         for (; i > 0; --i) {
907             bool success = parse_one_key(options, key, cur_str, i);
908             if (success)
909                 break;
910         }
911
912         if (0 == i)        /* no more possible chewings. */
913             break;
914
915         key_rest.m_raw_begin = parsed_len; key_rest.m_raw_end = parsed_len + i;
916         parsed_len += i;
917
918         /* save the pinyin. */
919         g_array_append_val(keys, key);
920         g_array_append_val(key_rests, key_rest);
921     }
922
923     return parsed_len;
924 }
925
926
927 bool ChewingParser2::set_scheme(ChewingScheme scheme) {
928     switch(scheme) {
929     case CHEWING_STANDARD:
930         m_symbol_table = chewing_standard_symbols;
931         m_tone_table   = chewing_standard_tones;
932         return true;
933     case CHEWING_IBM:
934         m_symbol_table = chewing_ibm_symbols;
935         m_tone_table   = chewing_ibm_tones;
936         return true;
937     case CHEWING_GINYIEH:
938         m_symbol_table = chewing_ginyieh_symbols;
939         m_tone_table   = chewing_ginyieh_tones;
940         return true;
941     case CHEWING_ETEN:
942         m_symbol_table = chewing_eten_symbols;
943         m_tone_table   = chewing_eten_tones;
944         return true;
945     }
946
947     return false;
948 }
949
950
951 bool ChewingParser2::in_chewing_scheme(pinyin_option_t options,
952                                        const char key, const char ** symbol)
953  const {
954     const gchar * chewing = NULL;
955     char tone = CHEWING_ZERO_TONE;
956
957     if (search_chewing_symbols(m_symbol_table, key, &chewing)) {
958         if (symbol)
959             *symbol = chewing;
960         return true;
961     }
962
963     if (!(options & USE_TONE))
964         return false;
965
966     if (search_chewing_tones(m_tone_table, key, &tone)) {
967         if (symbol)
968             *symbol = chewing_tone_table[tone];
969         return true;
970     }
971
972     return false;
973 }