-
Notifications
You must be signed in to change notification settings - Fork 8
/
spellfix.c
3076 lines (2923 loc) · 101 KB
/
spellfix.c
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
/*
** 2012 April 10
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This module implements the spellfix1 VIRTUAL TABLE that can be used
** to search a large vocabulary for close matches. See separate
** documentation (http://www.sqlite.org/spellfix1.html) for details.
*/
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#ifndef SQLITE_AMALGAMATION
# if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
# define NDEBUG 1
# endif
# if defined(NDEBUG) && defined(SQLITE_DEBUG)
# undef NDEBUG
# endif
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>
# define ALWAYS(X) 1
# define NEVER(X) 0
typedef unsigned char u8;
typedef unsigned short u16;
#endif
#include <ctype.h>
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Character classes for ASCII characters:
**
** 0 '' Silent letters: H W
** 1 'A' Any vowel: A E I O U (Y)
** 2 'B' A bilabeal stop or fricative: B F P V W
** 3 'C' Other fricatives or back stops: C G J K Q S X Z
** 4 'D' Alveolar stops: D T
** 5 'H' Letter H at the beginning of a word
** 6 'L' Glide: L
** 7 'R' Semivowel: R
** 8 'M' Nasals: M N
** 9 'Y' Letter Y at the beginning of a word.
** 10 '9' Digits: 0 1 2 3 4 5 6 7 8 9
** 11 ' ' White space
** 12 '?' Other.
*/
#define CCLASS_SILENT 0
#define CCLASS_VOWEL 1
#define CCLASS_B 2
#define CCLASS_C 3
#define CCLASS_D 4
#define CCLASS_H 5
#define CCLASS_L 6
#define CCLASS_R 7
#define CCLASS_M 8
#define CCLASS_Y 9
#define CCLASS_DIGIT 10
#define CCLASS_SPACE 11
#define CCLASS_OTHER 12
/*
** The following table gives the character class for non-initial ASCII
** characters.
*/
static const unsigned char midClass[] = {
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE,
/* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER,
/* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER,
/* ' */ CCLASS_SILENT, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER,
/* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER,
/* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER,
/* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT,
/* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT,
/* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT,
/* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER,
/* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER,
/* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL,
/* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D,
/* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C,
/* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C,
/* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M,
/* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B,
/* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C,
/* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B,
/* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_VOWEL,
/* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER,
/* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER,
/* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B,
/* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL,
/* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT,
/* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C,
/* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M,
/* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C,
/* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D,
/* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B,
/* x */ CCLASS_C, /* y */ CCLASS_VOWEL, /* z */ CCLASS_C,
/* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER,
/* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER,
};
/*
** This tables gives the character class for ASCII characters that form the
** initial character of a word. The only difference from midClass is with
** the letters H, W, and Y.
*/
static const unsigned char initClass[] = {
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
/* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE,
/* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER,
/* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER,
/* ' */ CCLASS_OTHER, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER,
/* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER,
/* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER,
/* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT,
/* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT,
/* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT,
/* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER,
/* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER,
/* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL,
/* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D,
/* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C,
/* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C,
/* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M,
/* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B,
/* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C,
/* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B,
/* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_Y,
/* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER,
/* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER,
/* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B,
/* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL,
/* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT,
/* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C,
/* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M,
/* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C,
/* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D,
/* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B,
/* x */ CCLASS_C, /* y */ CCLASS_Y, /* z */ CCLASS_C,
/* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER,
/* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER,
};
/*
** Mapping from the character class number (0-13) to a symbol for each
** character class. Note that initClass[] can be used to map the class
** symbol back into the class number.
*/
static const unsigned char className[] = ".ABCDHLRMY9 ?";
/*
** Generate a "phonetic hash" from a string of ASCII characters
** in zIn[0..nIn-1].
**
** * Map characters by character class as defined above.
** * Omit double-letters
** * Omit vowels beside R and L
** * Omit T when followed by CH
** * Omit W when followed by R
** * Omit D when followed by J or G
** * Omit K in KN or G in GN at the beginning of a word
**
** Space to hold the result is obtained from sqlite3_malloc()
**
** Return NULL if memory allocation fails.
*/
static unsigned char *phoneticHash(const unsigned char *zIn, int nIn){
unsigned char *zOut = sqlite3_malloc64( nIn + 1 );
int i;
int nOut = 0;
char cPrev = 0x77;
char cPrevX = 0x77;
const unsigned char *aClass = initClass;
if( zOut==0 ) return 0;
if( nIn>2 ){
switch( zIn[0] ){
case 'g':
case 'k': {
if( zIn[1]=='n' ){ zIn++; nIn--; }
break;
}
}
}
for(i=0; i<nIn; i++){
unsigned char c = zIn[i];
if( i+1<nIn ){
if( c=='w' && zIn[i+1]=='r' ) continue;
if( c=='d' && (zIn[i+1]=='j' || zIn[i+1]=='g') ) continue;
if( i+2<nIn ){
if( c=='t' && zIn[i+1]=='c' && zIn[i+2]=='h' ) continue;
}
}
c = aClass[c&0x7f];
if( c==CCLASS_SPACE ) continue;
if( c==CCLASS_OTHER && cPrev!=CCLASS_DIGIT ) continue;
aClass = midClass;
if( c==CCLASS_VOWEL && (cPrevX==CCLASS_R || cPrevX==CCLASS_L) ){
continue; /* No vowels beside L or R */
}
if( (c==CCLASS_R || c==CCLASS_L) && cPrevX==CCLASS_VOWEL ){
nOut--; /* No vowels beside L or R */
}
cPrev = c;
if( c==CCLASS_SILENT ) continue;
cPrevX = c;
c = className[c];
assert( nOut>=0 );
if( nOut==0 || c!=zOut[nOut-1] ) zOut[nOut++] = c;
}
zOut[nOut] = 0;
return zOut;
}
/*
** This is an SQL function wrapper around phoneticHash(). See
** the description of phoneticHash() for additional information.
*/
static void phoneticHashSqlFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const unsigned char *zIn;
unsigned char *zOut;
zIn = sqlite3_value_text(argv[0]);
if( zIn==0 ) return;
zOut = phoneticHash(zIn, sqlite3_value_bytes(argv[0]));
if( zOut==0 ){
sqlite3_result_error_nomem(context);
}else{
sqlite3_result_text(context, (char*)zOut, -1, sqlite3_free);
}
}
/*
** Return the character class number for a character given its
** context.
*/
static char characterClass(char cPrev, char c){
return cPrev==0 ? initClass[c&0x7f] : midClass[c&0x7f];
}
/*
** Return the cost of inserting or deleting character c immediately
** following character cPrev. If cPrev==0, that means c is the first
** character of the word.
*/
static int insertOrDeleteCost(char cPrev, char c, char cNext){
char classC = characterClass(cPrev, c);
char classCprev;
if( classC==CCLASS_SILENT ){
/* Insert or delete "silent" characters such as H or W */
return 1;
}
if( cPrev==c ){
/* Repeated characters, or miss a repeat */
return 10;
}
if( classC==CCLASS_VOWEL && (cPrev=='r' || cNext=='r') ){
return 20; /* Insert a vowel before or after 'r' */
}
classCprev = characterClass(cPrev, cPrev);
if( classC==classCprev ){
if( classC==CCLASS_VOWEL ){
/* Remove or add a new vowel to a vowel cluster */
return 15;
}else{
/* Remove or add a consonant not in the same class */
return 50;
}
}
/* any other character insertion or deletion */
return 100;
}
/*
** Divide the insertion cost by this factor when appending to the
** end of the word.
*/
#define FINAL_INS_COST_DIV 4
/*
** Return the cost of substituting cTo in place of cFrom assuming
** the previous character is cPrev. If cPrev==0 then cTo is the first
** character of the word.
*/
static int substituteCost(char cPrev, char cFrom, char cTo){
char classFrom, classTo;
if( cFrom==cTo ){
/* Exact match */
return 0;
}
if( cFrom==(cTo^0x20) && ((cTo>='A' && cTo<='Z') || (cTo>='a' && cTo<='z')) ){
/* differ only in case */
return 0;
}
classFrom = characterClass(cPrev, cFrom);
classTo = characterClass(cPrev, cTo);
if( classFrom==classTo ){
/* Same character class */
return 40;
}
if( classFrom>=CCLASS_B && classFrom<=CCLASS_Y
&& classTo>=CCLASS_B && classTo<=CCLASS_Y ){
/* Convert from one consonant to another, but in a different class */
return 75;
}
/* Any other subsitution */
return 100;
}
/*
** Given two strings zA and zB which are pure ASCII, return the cost
** of transforming zA into zB. If zA ends with '*' assume that it is
** a prefix of zB and give only minimal penalty for extra characters
** on the end of zB.
**
** Smaller numbers mean a closer match.
**
** Negative values indicate an error:
** -1 One of the inputs is NULL
** -2 Non-ASCII characters on input
** -3 Unable to allocate memory
**
** If pnMatch is not NULL, then *pnMatch is set to the number of bytes
** of zB that matched the pattern in zA. If zA does not end with a '*',
** then this value is always the number of bytes in zB (i.e. strlen(zB)).
** If zA does end in a '*', then it is the number of bytes in the prefix
** of zB that was deemed to match zA.
*/
static int editdist1(const char *zA, const char *zB, int *pnMatch){
int nA, nB; /* Number of characters in zA[] and zB[] */
int xA, xB; /* Loop counters for zA[] and zB[] */
char cA = 0, cB; /* Current character of zA and zB */
char cAprev, cBprev; /* Previous character of zA and zB */
char cAnext, cBnext; /* Next character in zA and zB */
int d; /* North-west cost value */
int dc = 0; /* North-west character value */
int res; /* Final result */
int *m; /* The cost matrix */
char *cx; /* Corresponding character values */
int *toFree = 0; /* Malloced space */
int nMatch = 0;
int mStack[60+15]; /* Stack space to use if not too much is needed */
/* Early out if either input is NULL */
if( zA==0 || zB==0 ) return -1;
/* Skip any common prefix */
while( zA[0] && zA[0]==zB[0] ){ dc = zA[0]; zA++; zB++; nMatch++; }
if( pnMatch ) *pnMatch = nMatch;
if( zA[0]==0 && zB[0]==0 ) return 0;
#if 0
printf("A=\"%s\" B=\"%s\" dc=%c\n", zA, zB, dc?dc:' ');
#endif
/* Verify input strings and measure their lengths */
for(nA=0; zA[nA]; nA++){
if( zA[nA]&0x80 ) return -2;
}
for(nB=0; zB[nB]; nB++){
if( zB[nB]&0x80 ) return -2;
}
/* Special processing if either string is empty */
if( nA==0 ){
cBprev = (char)dc;
for(xB=res=0; (cB = zB[xB])!=0; xB++){
res += insertOrDeleteCost(cBprev, cB, zB[xB+1])/FINAL_INS_COST_DIV;
cBprev = cB;
}
return res;
}
if( nB==0 ){
cAprev = (char)dc;
for(xA=res=0; (cA = zA[xA])!=0; xA++){
res += insertOrDeleteCost(cAprev, cA, zA[xA+1]);
cAprev = cA;
}
return res;
}
/* A is a prefix of B */
if( zA[0]=='*' && zA[1]==0 ) return 0;
/* Allocate and initialize the Wagner matrix */
if( nB<(sizeof(mStack)*4)/(sizeof(mStack[0])*5) ){
m = mStack;
}else{
m = toFree = sqlite3_malloc64( (nB+1)*5*sizeof(m[0])/4 );
if( m==0 ) return -3;
}
cx = (char*)&m[nB+1];
/* Compute the Wagner edit distance */
m[0] = 0;
cx[0] = (char)dc;
cBprev = (char)dc;
for(xB=1; xB<=nB; xB++){
cBnext = zB[xB];
cB = zB[xB-1];
cx[xB] = cB;
m[xB] = m[xB-1] + insertOrDeleteCost(cBprev, cB, cBnext);
cBprev = cB;
}
cAprev = (char)dc;
for(xA=1; xA<=nA; xA++){
int lastA = (xA==nA);
cA = zA[xA-1];
cAnext = zA[xA];
if( cA=='*' && lastA ) break;
d = m[0];
dc = cx[0];
m[0] = d + insertOrDeleteCost(cAprev, cA, cAnext);
cBprev = 0;
for(xB=1; xB<=nB; xB++){
int totalCost, insCost, delCost, subCost, ncx;
cB = zB[xB-1];
cBnext = zB[xB];
/* Cost to insert cB */
insCost = insertOrDeleteCost(cx[xB-1], cB, cBnext);
if( lastA ) insCost /= FINAL_INS_COST_DIV;
/* Cost to delete cA */
delCost = insertOrDeleteCost(cx[xB], cA, cBnext);
/* Cost to substitute cA->cB */
subCost = substituteCost(cx[xB-1], cA, cB);
/* Best cost */
totalCost = insCost + m[xB-1];
ncx = cB;
if( (delCost + m[xB])<totalCost ){
totalCost = delCost + m[xB];
ncx = cA;
}
if( (subCost + d)<totalCost ){
totalCost = subCost + d;
}
#if 0
printf("%d,%d d=%4d u=%4d r=%4d dc=%c cA=%c cB=%c"
" ins=%4d del=%4d sub=%4d t=%4d ncx=%c\n",
xA, xB, d, m[xB], m[xB-1], dc?dc:' ', cA, cB,
insCost, delCost, subCost, totalCost, ncx?ncx:' ');
#endif
/* Update the matrix */
d = m[xB];
dc = cx[xB];
m[xB] = totalCost;
cx[xB] = (char)ncx;
cBprev = cB;
}
cAprev = cA;
}
/* Free the wagner matrix and return the result */
if( cA=='*' ){
res = m[1];
for(xB=1; xB<=nB; xB++){
if( m[xB]<res ){
res = m[xB];
if( pnMatch ) *pnMatch = xB+nMatch;
}
}
}else{
res = m[nB];
/* In the current implementation, pnMatch is always NULL if zA does
** not end in "*" */
assert( pnMatch==0 );
}
sqlite3_free(toFree);
return res;
}
/*
** Function: editdist(A,B)
**
** Return the cost of transforming string A into string B. Both strings
** must be pure ASCII text. If A ends with '*' then it is assumed to be
** a prefix of B and extra characters on the end of B have minimal additional
** cost.
*/
static void editdistSqlFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
int res = editdist1(
(const char*)sqlite3_value_text(argv[0]),
(const char*)sqlite3_value_text(argv[1]),
0);
if( res<0 ){
if( res==(-3) ){
sqlite3_result_error_nomem(context);
}else if( res==(-2) ){
sqlite3_result_error(context, "non-ASCII input to editdist()", -1);
}else{
sqlite3_result_error(context, "NULL input to editdist()", -1);
}
}else{
sqlite3_result_int(context, res);
}
}
/* End of the fixed-cost edit distance implementation
******************************************************************************
*****************************************************************************
** Begin: Configurable cost unicode edit distance routines
*/
/* Forward declaration of structures */
typedef struct EditDist3Cost EditDist3Cost;
typedef struct EditDist3Config EditDist3Config;
typedef struct EditDist3Point EditDist3Point;
typedef struct EditDist3From EditDist3From;
typedef struct EditDist3FromString EditDist3FromString;
typedef struct EditDist3To EditDist3To;
typedef struct EditDist3ToString EditDist3ToString;
typedef struct EditDist3Lang EditDist3Lang;
/*
** An entry in the edit cost table
*/
struct EditDist3Cost {
EditDist3Cost *pNext; /* Next cost element */
u8 nFrom; /* Number of bytes in aFrom */
u8 nTo; /* Number of bytes in aTo */
u16 iCost; /* Cost of this transformation */
char a[4] ; /* FROM string followed by TO string */
/* Additional TO and FROM string bytes appended as necessary */
};
/*
** Edit costs for a particular language ID
*/
struct EditDist3Lang {
int iLang; /* Language ID */
int iInsCost; /* Default insertion cost */
int iDelCost; /* Default deletion cost */
int iSubCost; /* Default substitution cost */
EditDist3Cost *pCost; /* Costs */
};
/*
** The default EditDist3Lang object, with default costs.
*/
static const EditDist3Lang editDist3Lang = { 0, 100, 100, 150, 0 };
/*
** Complete configuration
*/
struct EditDist3Config {
int nLang; /* Number of language IDs. Size of a[] */
EditDist3Lang *a; /* One for each distinct language ID */
};
/*
** Extra information about each character in the FROM string.
*/
struct EditDist3From {
int nSubst; /* Number of substitution cost entries */
int nDel; /* Number of deletion cost entries */
int nByte; /* Number of bytes in this character */
EditDist3Cost **apSubst; /* Array of substitution costs for this element */
EditDist3Cost **apDel; /* Array of deletion cost entries */
};
/*
** A precompiled FROM string.
*
** In the common case we expect the FROM string to be reused multiple times.
** In other words, the common case will be to measure the edit distance
** from a single origin string to multiple target strings.
*/
struct EditDist3FromString {
char *z; /* The complete text of the FROM string */
int n; /* Number of characters in the FROM string */
int isPrefix; /* True if ends with '*' character */
EditDist3From *a; /* Extra info about each char of the FROM string */
};
/*
** Extra information about each character in the TO string.
*/
struct EditDist3To {
int nIns; /* Number of insertion cost entries */
int nByte; /* Number of bytes in this character */
EditDist3Cost **apIns; /* Array of deletion cost entries */
};
/*
** A precompiled FROM string
*/
struct EditDist3ToString {
char *z; /* The complete text of the TO string */
int n; /* Number of characters in the TO string */
EditDist3To *a; /* Extra info about each char of the TO string */
};
/*
** Clear or delete an instance of the object that records all edit-distance
** weights.
*/
static void editDist3ConfigClear(EditDist3Config *p){
int i;
if( p==0 ) return;
for(i=0; i<p->nLang; i++){
EditDist3Cost *pCost, *pNext;
pCost = p->a[i].pCost;
while( pCost ){
pNext = pCost->pNext;
sqlite3_free(pCost);
pCost = pNext;
}
}
sqlite3_free(p->a);
memset(p, 0, sizeof(*p));
}
static void editDist3ConfigDelete(void *pIn){
EditDist3Config *p = (EditDist3Config*)pIn;
editDist3ConfigClear(p);
sqlite3_free(p);
}
/* Compare the FROM values of two EditDist3Cost objects, for sorting.
** Return negative, zero, or positive if the A is less than, equal to,
** or greater than B.
*/
static int editDist3CostCompare(EditDist3Cost *pA, EditDist3Cost *pB){
int n = pA->nFrom;
int rc;
if( n>pB->nFrom ) n = pB->nFrom;
rc = strncmp(pA->a, pB->a, n);
if( rc==0 ) rc = pA->nFrom - pB->nFrom;
return rc;
}
/*
** Merge together two sorted lists of EditDist3Cost objects, in order
** of increasing FROM.
*/
static EditDist3Cost *editDist3CostMerge(
EditDist3Cost *pA,
EditDist3Cost *pB
){
EditDist3Cost *pHead = 0;
EditDist3Cost **ppTail = &pHead;
EditDist3Cost *p;
while( pA && pB ){
if( editDist3CostCompare(pA,pB)<=0 ){
p = pA;
pA = pA->pNext;
}else{
p = pB;
pB = pB->pNext;
}
*ppTail = p;
ppTail = &p->pNext;
}
if( pA ){
*ppTail = pA;
}else{
*ppTail = pB;
}
return pHead;
}
/*
** Sort a list of EditDist3Cost objects into order of increasing FROM
*/
static EditDist3Cost *editDist3CostSort(EditDist3Cost *pList){
EditDist3Cost *ap[60], *p;
int i;
int mx = 0;
ap[0] = 0;
ap[1] = 0;
while( pList ){
p = pList;
pList = p->pNext;
p->pNext = 0;
for(i=0; ap[i]; i++){
p = editDist3CostMerge(ap[i],p);
ap[i] = 0;
}
ap[i] = p;
if( i>mx ){
mx = i;
ap[i+1] = 0;
}
}
p = 0;
for(i=0; i<=mx; i++){
if( ap[i] ) p = editDist3CostMerge(p,ap[i]);
}
return p;
}
/*
** Load all edit-distance weights from a table.
*/
static int editDist3ConfigLoad(
EditDist3Config *p, /* The edit distance configuration to load */
sqlite3 *db, /* Load from this database */
const char *zTable /* Name of the table from which to load */
){
sqlite3_stmt *pStmt;
int rc, rc2;
char *zSql;
int iLangPrev = -9999;
EditDist3Lang *pLang = 0;
zSql = sqlite3_mprintf("SELECT iLang, cFrom, cTo, iCost"
" FROM \"%w\" WHERE iLang>=0 ORDER BY iLang", zTable);
if( zSql==0 ) return SQLITE_NOMEM;
rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
sqlite3_free(zSql);
if( rc ) return rc;
editDist3ConfigClear(p);
while( sqlite3_step(pStmt)==SQLITE_ROW ){
int iLang = sqlite3_column_int(pStmt, 0);
const char *zFrom = (const char*)sqlite3_column_text(pStmt, 1);
int nFrom = zFrom ? sqlite3_column_bytes(pStmt, 1) : 0;
const char *zTo = (const char*)sqlite3_column_text(pStmt, 2);
int nTo = zTo ? sqlite3_column_bytes(pStmt, 2) : 0;
int iCost = sqlite3_column_int(pStmt, 3);
assert( zFrom!=0 || nFrom==0 );
assert( zTo!=0 || nTo==0 );
if( nFrom>100 || nTo>100 ) continue;
if( iCost<0 ) continue;
if( iCost>=10000 ) continue; /* Costs above 10K are considered infinite */
if( pLang==0 || iLang!=iLangPrev ){
EditDist3Lang *pNew;
pNew = sqlite3_realloc64(p->a, (p->nLang+1)*sizeof(p->a[0]));
if( pNew==0 ){ rc = SQLITE_NOMEM; break; }
p->a = pNew;
pLang = &p->a[p->nLang];
p->nLang++;
pLang->iLang = iLang;
pLang->iInsCost = 100;
pLang->iDelCost = 100;
pLang->iSubCost = 150;
pLang->pCost = 0;
iLangPrev = iLang;
}
if( nFrom==1 && zFrom[0]=='?' && nTo==0 ){
pLang->iDelCost = iCost;
}else if( nFrom==0 && nTo==1 && zTo[0]=='?' ){
pLang->iInsCost = iCost;
}else if( nFrom==1 && nTo==1 && zFrom[0]=='?' && zTo[0]=='?' ){
pLang->iSubCost = iCost;
}else{
EditDist3Cost *pCost;
int nExtra = nFrom + nTo - 4;
if( nExtra<0 ) nExtra = 0;
pCost = sqlite3_malloc64( sizeof(*pCost) + nExtra );
if( pCost==0 ){ rc = SQLITE_NOMEM; break; }
pCost->nFrom = (u8)nFrom;
pCost->nTo = (u8)nTo;
pCost->iCost = (u16)iCost;
memcpy(pCost->a, zFrom, nFrom);
memcpy(pCost->a + nFrom, zTo, nTo);
pCost->pNext = pLang->pCost;
pLang->pCost = pCost;
}
}
rc2 = sqlite3_finalize(pStmt);
if( rc==SQLITE_OK ) rc = rc2;
if( rc==SQLITE_OK ){
int iLang;
for(iLang=0; iLang<p->nLang; iLang++){
p->a[iLang].pCost = editDist3CostSort(p->a[iLang].pCost);
}
}
return rc;
}
/*
** Return the length (in bytes) of a utf-8 character. Or return a maximum
** of N.
*/
static int utf8Len(unsigned char c, int N){
int len = 1;
if( c>0x7f ){
if( (c&0xe0)==0xc0 ){
len = 2;
}else if( (c&0xf0)==0xe0 ){
len = 3;
}else{
len = 4;
}
}
if( len>N ) len = N;
return len;
}
/*
** Return TRUE (non-zero) if the To side of the given cost matches
** the given string.
*/
static int matchTo(EditDist3Cost *p, const char *z, int n){
assert( n>0 );
if( p->a[p->nFrom]!=z[0] ) return 0;
if( p->nTo>n ) return 0;
if( strncmp(p->a+p->nFrom, z, p->nTo)!=0 ) return 0;
return 1;
}
/*
** Return TRUE (non-zero) if the From side of the given cost matches
** the given string.
*/
static int matchFrom(EditDist3Cost *p, const char *z, int n){
assert( p->nFrom<=n );
if( p->nFrom ){
if( p->a[0]!=z[0] ) return 0;
if( strncmp(p->a, z, p->nFrom)!=0 ) return 0;
}
return 1;
}
/*
** Return TRUE (non-zero) of the next FROM character and the next TO
** character are the same.
*/
static int matchFromTo(
EditDist3FromString *pStr, /* Left hand string */
int n1, /* Index of comparison character on the left */
const char *z2, /* Right-handl comparison character */
int n2 /* Bytes remaining in z2[] */
){
int b1 = pStr->a[n1].nByte;
if( b1>n2 ) return 0;
assert( b1>0 );
if( pStr->z[n1]!=z2[0] ) return 0;
if( strncmp(pStr->z+n1, z2, b1)!=0 ) return 0;
return 1;
}
/*
** Delete an EditDist3FromString objecct
*/
static void editDist3FromStringDelete(EditDist3FromString *p){
int i;
if( p ){
for(i=0; i<p->n; i++){
sqlite3_free(p->a[i].apDel);
sqlite3_free(p->a[i].apSubst);
}
sqlite3_free(p);
}
}
/*
** Create a EditDist3FromString object.
*/
static EditDist3FromString *editDist3FromStringNew(
const EditDist3Lang *pLang,
const char *z,
int n
){
EditDist3FromString *pStr;
EditDist3Cost *p;
int i;
if( z==0 ) return 0;
if( n<0 ) n = (int)strlen(z);
pStr = sqlite3_malloc64( sizeof(*pStr) + sizeof(pStr->a[0])*n + n + 1 );
if( pStr==0 ) return 0;
pStr->a = (EditDist3From*)&pStr[1];
memset(pStr->a, 0, sizeof(pStr->a[0])*n);
pStr->n = n;
pStr->z = (char*)&pStr->a[n];
memcpy(pStr->z, z, n+1);
if( n && z[n-1]=='*' ){
pStr->isPrefix = 1;
n--;
pStr->n--;
pStr->z[n] = 0;
}else{
pStr->isPrefix = 0;
}
for(i=0; i<n; i++){
EditDist3From *pFrom = &pStr->a[i];
memset(pFrom, 0, sizeof(*pFrom));
pFrom->nByte = utf8Len((unsigned char)z[i], n-i);
for(p=pLang->pCost; p; p=p->pNext){
EditDist3Cost **apNew;
if( i+p->nFrom>n ) continue;
if( matchFrom(p, z+i, n-i)==0 ) continue;
if( p->nTo==0 ){
apNew = sqlite3_realloc64(pFrom->apDel,
sizeof(*apNew)*(pFrom->nDel+1));
if( apNew==0 ) break;
pFrom->apDel = apNew;
apNew[pFrom->nDel++] = p;
}else{
apNew = sqlite3_realloc64(pFrom->apSubst,
sizeof(*apNew)*(pFrom->nSubst+1));
if( apNew==0 ) break;
pFrom->apSubst = apNew;
apNew[pFrom->nSubst++] = p;
}
}
if( p ){
editDist3FromStringDelete(pStr);
pStr = 0;
break;
}
}
return pStr;
}
/*
** Update entry m[i] such that it is the minimum of its current value
** and m[j]+iCost.
*/
static void updateCost(
unsigned int *m,
int i,
int j,
int iCost
){
unsigned int b;
assert( iCost>=0 );
assert( iCost<10000 );
b = m[j] + iCost;
if( b<m[i] ) m[i] = b;
}
/*
** How much stack space (int bytes) to use for Wagner matrix in
** editDist3Core(). If more space than this is required, the entire
** matrix is taken from the heap. To reduce the load on the memory
** allocator, make this value as large as practical for the
** architecture in use.
*/
#ifndef SQLITE_SPELLFIX_STACKALLOC_SZ
# define SQLITE_SPELLFIX_STACKALLOC_SZ (1024)
#endif
/* Compute the edit distance between two strings.
**
** If an error occurs, return a negative number which is the error code.
**
** If pnMatch is not NULL, then *pnMatch is set to the number of characters
** (not bytes) in z2 that matched the search pattern in *pFrom. If pFrom does
** not contain the pattern for a prefix-search, then this is always the number
** of characters in z2. If pFrom does contain a prefix search pattern, then
** it is the number of characters in the prefix of z2 that was deemed to
** match pFrom.
*/
static int editDist3Core(
EditDist3FromString *pFrom, /* The FROM string */
const char *z2, /* The TO string */
int n2, /* Length of the TO string */
const EditDist3Lang *pLang, /* Edit weights for a particular language ID */
int *pnMatch /* OUT: Characters in matched prefix */
){
int k, n;
int i1, b1;
int i2, b2;
EditDist3FromString f = *pFrom;