]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - correct.c
A little faster, plus some more research
[xonotic/gmqcc.git] / correct.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Dale Weiler
4  *     Wolfgang Bumiller
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include "gmqcc.h"
25
26 /*
27  * This is a very clever method for correcting mistakes in QuakeC code
28  * most notably when invalid identifiers are used or inproper assignments;
29  * we can proprly lookup in multiple dictonaries (depening on the rules
30  * of what the task is trying to acomplish) to find the best possible
31  * match.
32  *
33  *
34  * A little about how it works, and probability theory:
35  *
36  *  When given an identifier (which we will denote I), we're essentially
37  *  just trying to choose the most likely correction for that identifier.
38  *  (the actual "correction" can very well be the identifier itself).
39  *  There is actually no way to know for sure that certian identifers
40  *  such as "lates", need to be corrected to "late" or "latest" or any
41  *  other permutations that look lexically the same.  This is why we
42  *  must advocate the usage of probabilities.  This means that instead of
43  *  just guessing, instead we're trying to find the correction for C,
44  *  out of all possible corrections that maximizes the probability of C
45  *  for the original identifer I.
46  *
47  *  Thankfully there exists some theroies for probalistic interpretations
48  *  of data.  Since we're operating on two distictive intepretations, the
49  *  transposition from I to C. We need something that can express how much
50  *  degree of I should rationally change to become C.  this is called the
51  *  Bayesian interpretation. You can read more about it from here:
52  *  http://www.celiagreen.com/charlesmccreery/statistics/bayestutorial.pdf
53  *  (which is probably the only good online documentation for bayes theroy
54  *  no lie.  Everything else just sucks ..)  
55  * 
56  *  Bayes' Thereom suggests something like the following:
57  *      AC P(I|C) P(C) / P(I)
58  * 
59  *  However since P(I) is the same for every possibility of I, we can
60  *  completley ignore it giving just:
61  *      AC P(I|C) P(C)
62  *
63  *  This greatly helps visualize how the parts of the expression are performed
64  *  there is essentially three, from right to left we perform the following:
65  *
66  *  1: P(C), the probability that a proposed correction C will stand on its
67  *     own.  This is called the language model.
68  *
69  *  2: P(I|C), the probability that I would be used, when the programmer
70  *     really meant C.  This is the error model.
71  *
72  *  3: AC, the control mechanisim, an enumerator if you will, one that
73  *     enumerates all feasible values of C, to determine the one that
74  *     gives the greatest probability score.
75  * 
76  *  In reality the requirement for a more complex expression involving
77  *  two seperate models is considerably a waste.  But one must recognize
78  *  that P(C|I) is already conflating two factors.  It's just much simpler
79  *  to seperate the two models and deal with them explicitaly.  To properly
80  *  estimate P(C|I) you have to consider both the probability of C and
81  *  probability of the transposition from C to I.  It's simply much more
82  *  cleaner, and direct to seperate the two factors.
83  *
84  *  Research tells us that 80% to 95% of all spelling errors have an edit
85  *  distance no greater than one.  Knowing this we can optimize for most
86  *  cases of mistakes without taking a performance hit.  Which is what we
87  *  base longer edit distances off of.  Opposed to the original method of
88  *  I had concieved of checking everything.     
89  *  
90  * A little information on additional algorithms used:
91  *
92  *   Initially when I implemented this corrector, it was very slow.
93  *   Need I remind you this is essentially a brute force attack on strings,
94  *   and since every transformation requires dynamic memory allocations,
95  *   you can easily imagine where most of the runtime conflated.  Yes
96  *   It went right to malloc.  More than THREE MILLION malloc calls are
97  *   performed for an identifier about 16 bytes long.  This was such a
98  *   shock to me.  A forward allocator (or as some call it a bump-point
99  *   allocator, or just a memory pool) was implemented. To combat this.
100  *
101  *   But of course even other factors were making it slow.  Initially
102  *   this used a hashtable.  And hashtables have a good constant lookup
103  *   time complexity.  But the problem wasn't in the hashtable, it was
104  *   in the hashing (despite having one of the fastest hash functions
105  *   known).  Remember those 3 million mallocs? Well for every malloc
106  *   there is also a hash.  After 3 million hashes .. you start to get
107  *   very slow.  To combat this I had suggested burst tries to Blub.
108  *   The next day he had implemented them. Sure enough this brought
109  *   down the runtime by a factory > 100%
110  *
111  * Future Work (If we really need it)
112  *
113  *   Currently we can only distinguishes one source of error in the
114  *   language model we use.  This could become an issue for identifiers
115  *   that have close colliding rates, e.g colate->coat yields collate.
116  *
117  *   Currently the error model has been fairly trivial, the smaller the
118  *   edit distance the smaller the error.  This usually causes some un-
119  *   expected problems. e.g reciet->recite yields recipt.  For QuakeC
120  *   this could become a problem when lots of identifiers are involved. 
121  *
122  *   Our control mechanisim could use a limit, i.e limit the number of
123  *   sets of edits for distance X.  This would also increase execution
124  *   speed considerably.
125  */
126
127
128 #define CORRECT_POOL_SIZE (128*1024*1024)
129 #define CORRECT_POOL_GETLEN(X) *((size_t*)(X) - 1)
130 /*
131  * A forward allcator for the corrector.  This corrector requires a lot
132  * of allocations.  This forward allocator combats all those allocations
133  * and speeds us up a little.  It also saves us space in a way since each
134  * allocation isn't wasting a little header space for when NOTRACK isn't
135  * defined.
136  */    
137 static unsigned char **correct_pool_data = NULL;
138 static unsigned char  *correct_pool_this = NULL;
139 static size_t          correct_pool_addr = 0;
140
141 static GMQCC_INLINE void correct_pool_new(void) {
142     correct_pool_addr = 0;
143     correct_pool_this = (unsigned char *)mem_a(CORRECT_POOL_SIZE);
144
145     vec_push(correct_pool_data, correct_pool_this);
146 }
147
148 static GMQCC_INLINE void *correct_pool_alloc(size_t bytes) {
149     void *data;
150     if (correct_pool_addr + bytes>= CORRECT_POOL_SIZE)
151         correct_pool_new();
152
153     data               = (void*)correct_pool_this;
154     correct_pool_this += bytes;
155     correct_pool_addr += bytes;
156     return data;
157 }
158
159 static GMQCC_INLINE void correct_pool_delete(void) {
160     size_t i;
161     for (i = 0; i < vec_size(correct_pool_data); ++i)
162         mem_d(correct_pool_data[i]);
163
164     correct_pool_data = NULL;
165     correct_pool_this = NULL;
166     correct_pool_addr = 0;
167 }
168
169
170 static GMQCC_INLINE char *correct_pool_claim(const char *data) {
171     char *claim = util_strdup(data);
172     correct_pool_delete();
173     return claim;
174 }
175
176 /*
177  * A fast space efficent trie for a dictionary of identifiers.  This is
178  * faster than a hashtable for one reason.  A hashtable itself may have
179  * fast constant lookup time, but the hash itself must be very fast. We
180  * have one of the fastest hash functions for strings, but if you do a
181  * lost of hashing (which we do, almost 3 million hashes per identifier)
182  * a hashtable becomes slow.
183  */   
184 correct_trie_t* correct_trie_new() {
185     correct_trie_t *t = (correct_trie_t*)mem_a(sizeof(correct_trie_t));
186     t->value   = NULL;
187     t->entries = NULL;
188     return t;
189 }
190
191 void correct_trie_del_sub(correct_trie_t *t) {
192     size_t i;
193     for (i = 0; i < vec_size(t->entries); ++i)
194         correct_trie_del_sub(&t->entries[i]);
195     vec_free(t->entries);
196 }
197
198 void correct_trie_del(correct_trie_t *t) {
199     size_t i;
200     for (i = 0; i < vec_size(t->entries); ++i)
201         correct_trie_del_sub(&t->entries[i]);
202     vec_free(t->entries);
203     mem_d(t);
204 }
205
206 void* correct_trie_get(const correct_trie_t *t, const char *key) {
207     const unsigned char *data = (const unsigned char*)key;
208
209     while (*data) {
210         const correct_trie_t *entries = t->entries;
211         unsigned char         ch      = *data;
212         const size_t          vs      = vec_size(entries);
213         size_t                i;
214
215         for (i = 0; i < vs; ++i) {
216             if (entries[i].ch == ch) {
217                 t = &entries[i];
218                 ++data;
219                 break;
220             }
221         }
222         if (i == vs)
223             return NULL;
224     }
225     return t->value;
226 }
227
228 void correct_trie_set(correct_trie_t *t, const char *key, void * const value) {
229     const unsigned char *data = (const unsigned char*)key;
230     while (*data) {
231         correct_trie_t *entries = t->entries;
232         const size_t    vs      = vec_size(entries);
233         unsigned char   ch      = *data;
234         size_t          i;
235
236         for (i = 0; i < vs; ++i) {
237             if (entries[i].ch == ch) {
238                 t = &entries[i];
239                 break;
240             }
241         }
242         if (i == vs) {
243             correct_trie_t *elem  = (correct_trie_t*)vec_add(t->entries, 1);
244
245             elem->ch      = ch;
246             elem->value   = NULL;
247             elem->entries = NULL;
248             t             = elem;
249         }
250         ++data;
251     }
252     t->value = value;
253 }
254
255
256 /*
257  * Implementation of the corrector algorithm commences. A very efficent
258  * brute-force attack (thanks to tries and mempool :-)).
259  */  
260 static GMQCC_INLINE size_t *correct_find(correct_trie_t *table, const char *word) {
261     return (size_t*)correct_trie_get(table, word);
262 }
263
264 static GMQCC_INLINE bool correct_update(correct_trie_t* *table, const char *word) {
265     size_t *data = correct_find(*table, word);
266     if (!data)
267         return false;
268
269     (*data)++;
270     return true;
271 }
272
273 void correct_add(correct_trie_t* table, size_t ***size, const char *ident) {
274     size_t     *data = NULL;
275     const char *add  = ident;
276     
277     if (!correct_update(&table, add)) {
278         data  = (size_t*)mem_a(sizeof(size_t));
279         *data = 1;
280
281         vec_push((*size), data);
282         correct_trie_set(table, add, data);
283     }
284 }
285
286 void correct_del(correct_trie_t* dictonary, size_t **data) {
287     size_t       i;
288     const size_t vs = vec_size(data);
289
290     for (i = 0; i < vs; i++)
291         mem_d(data[i]);
292
293     vec_free(data);
294     correct_trie_del(dictonary);
295 }
296
297 /*
298  * _ is valid in identifiers. I've yet to implement numerics however
299  * because they're only valid after the first character is of a _, or
300  * alpha character.
301  */
302 static const char correct_alpha[] = "abcdefghijklmnopqrstuvwxyz"
303                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
304                                     "_"; /* TODO: Numbers ... */
305
306 /*
307  * correcting logic for the following forms of transformations:
308  *  1) deletion
309  *  2) transposition
310  *  3) alteration
311  *  4) insertion
312  *
313  * These functions could take an additional size_t **size paramater
314  * and store back the results of their new length in an array that
315  * is the same as **array for the memcmp in correct_exists. I'm just
316  * not able to figure out how to do that just yet.  As my brain is
317  * not in the mood to figure out that logic.  This is a reminder to
318  * do it, or for someone else to :-) correct_edit however would also
319  * need to take a size_t ** to carry it along (would all the argument
320  * overhead be worth it?)  
321  */
322 static size_t correct_deletion(const char *ident, char **array, size_t index) {
323     size_t       itr = 0;
324     const size_t len = strlen(ident);
325
326     for (; itr < len; itr++) {
327         char *a = (char*)correct_pool_alloc(len+1);
328         memcpy(a, ident, itr);
329         memcpy(a + itr, ident + itr + 1, len - itr);
330         array[index + itr] = a;
331     }
332
333     return itr;
334 }
335
336 static size_t correct_transposition(const char *ident, char **array, size_t index) {
337     size_t       itr = 0;
338     const size_t len = strlen(ident);
339
340     for (; itr < len - 1; itr++) {
341         char  tmp;
342         char *a = (char*)correct_pool_alloc(len+1);
343         memcpy(a, ident, len+1);
344         tmp      = a[itr];
345         a[itr  ] = a[itr+1];
346         a[itr+1] = tmp;
347         array[index + itr] = a;
348     }
349
350     return itr;
351 }
352
353 static size_t correct_alteration(const char *ident, char **array, size_t index) {
354     size_t       itr = 0;
355     size_t       jtr = 0;
356     size_t       ktr = 0;
357     const size_t len = strlen(ident);
358
359     for (; itr < len; itr++) {
360         for (jtr = 0; jtr < sizeof(correct_alpha)-1; jtr++, ktr++) {
361             char *a = (char*)correct_pool_alloc(len+1);
362             memcpy(a, ident, len+1);
363             a[itr] = correct_alpha[jtr];
364             array[index + ktr] = a;
365         }
366     }
367
368     return ktr;
369 }
370
371 static size_t correct_insertion(const char *ident, char **array, size_t index) {
372     size_t       itr = 0;
373     size_t       jtr = 0;
374     size_t       ktr = 0;
375     const size_t len = strlen(ident);
376
377     for (; itr <= len; itr++) {
378         for (jtr = 0; jtr < sizeof(correct_alpha)-1; jtr++, ktr++) {
379             char *a = (char*)correct_pool_alloc(len+2);
380             memcpy(a, ident, itr);
381             memcpy(a + itr + 1, ident + itr, len - itr + 1);
382             a[itr] = correct_alpha[jtr];
383             array[index + ktr] = a;
384         }
385     }
386
387     return ktr;
388 }
389
390 static GMQCC_INLINE size_t correct_size(const char *ident) {
391     /*
392      * deletion      = len
393      * transposition = len - 1
394      * alteration    = len * sizeof(correct_alpha)
395      * insertion     = (len + 1) * sizeof(correct_alpha)
396      */   
397
398     register size_t len = strlen(ident);
399     return (len) + (len - 1) + (len * (sizeof(correct_alpha)-1)) + ((len + 1) * (sizeof(correct_alpha)-1));
400 }
401
402 static char **correct_edit(const char *ident) {
403     size_t next;
404     char **find = (char**)correct_pool_alloc(correct_size(ident) * sizeof(char*));
405
406     if (!find)
407         return NULL;
408
409     next  = correct_deletion     (ident, find, 0);
410     next += correct_transposition(ident, find, next);
411     next += correct_alteration   (ident, find, next);
412     /*****/ correct_insertion    (ident, find, next);
413
414     return find;
415 }
416
417 /*
418  * We could use a hashtable but the space complexity isn't worth it
419  * since we're only going to determine the "did you mean?" identifier
420  * on error.
421  */   
422 static int correct_exist(char **array, size_t rows, char *ident) {
423     size_t itr;
424     /*
425      * As an experiment I tried the following assembly for memcmp here:
426      *
427      * correct_cmp_loop: 
428      * incl %eax            ; eax =  LHS
429      * incl %edx            ; edx =  LRS
430      * cmpl %eax, %ebx      ; ebx = &LHS[END_POS]
431      *
432      * jbe correct_cmp_eq
433      * movb (%edx), %cl     ; micro-optimized on even atoms :-)
434      * cmpb %cl, (%eax)     ; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
435      * jg  correct_cmp_gt
436      * jge correct_cmp_loop
437      * ...
438      *
439      * Despite how much optimization went in to this, the speed was the
440      * being conflicted by the strlen(ident) used for &LHS[END_POS]
441      * If we could eliminate the strlen with what I suggested on line
442      * 311 ... we can accelerate this whole damn thing quite a bit.
443      *
444      * However there is still something we can do here that does give
445      * us a little more speed.  Although one more branch, we know for
446      * sure there is at least one byte to compare, if that one byte
447      * simply isn't the same we can skip the full check. Which means
448      * we skip a whole strlen call.
449      */
450     for (itr = 0; itr < rows; itr++) {
451         if (!memcmp(array[itr], ident, strlen(ident)))
452             return 1;
453     }
454
455     return 0;
456 }
457
458 static GMQCC_INLINE char **correct_known_resize(char **res, size_t *allocated, size_t size) {
459     size_t oldallocated = *allocated;
460     char **out;
461     if (size+1 < *allocated)
462         return res;
463
464     *allocated += 32;
465     out = correct_pool_alloc(sizeof(*res) * *allocated);
466     memcpy(out, res, sizeof(*res) * oldallocated);
467     return out;
468 }
469
470 static char **correct_known(correct_trie_t* table, char **array, size_t rows, size_t *next) {
471     size_t itr = 0;
472     size_t jtr = 0;
473     size_t len = 0;
474     size_t row = 0;
475     size_t nxt = 8;
476     char **res = correct_pool_alloc(sizeof(char *) * nxt);
477     char **end = NULL;
478
479     for (; itr < rows; itr++) {
480         end = correct_edit(array[itr]);
481         row = correct_size(array[itr]);
482
483         /* removing jtr=0 here speeds it up by 100ms O_o */
484         for (jtr = 0; jtr < row; jtr++) {
485             if (correct_find(table, end[jtr]) && !correct_exist(res, len, end[jtr])) {
486                 res        = correct_known_resize(res, &nxt, len+1);
487                 res[len++] = end[jtr];
488             }
489         }
490     }
491
492     *next = len;
493     return res;
494 }
495
496 static char *correct_maximum(correct_trie_t* table, char **array, size_t rows) {
497     char   *str = NULL;
498     size_t *itm = NULL;
499     size_t  itr = 0;
500     size_t  top = 0;
501
502     for (; itr < rows; itr++) {
503         if ((itm = correct_find(table, array[itr])) && (*itm > top)) {
504             top = *itm;
505             str = array[itr];
506         }
507     }
508
509     return str;
510 }
511
512 /*
513  * This is the exposed interface:
514  * takes a table for the dictonary a vector of sizes (used for internal
515  * probability calculation, and an identifier to "correct"
516  *
517  * the add function works the same.  Except the identifier is used to
518  * add to the dictonary.  
519  */
520 char *correct_str(correct_trie_t* table, const char *ident) {
521     char **e1      = NULL;
522     char **e2      = NULL;
523     char  *e1ident = NULL;
524     char  *e2ident = NULL;
525     size_t e1rows  = 0;
526     size_t e2rows  = 0;
527
528     correct_pool_new();
529
530     /* needs to be allocated for free later */
531     if (correct_find(table, ident))
532         return correct_pool_claim(ident);
533
534     if ((e1rows = correct_size(ident))) {
535         e1      = correct_edit(ident);
536
537         if ((e1ident = correct_maximum(table, e1, e1rows)))
538             return correct_pool_claim(e1ident);
539     }
540
541     e2 = correct_known(table, e1, e1rows, &e2rows);
542     if (e2rows && ((e2ident = correct_maximum(table, e2, e2rows))))
543         return correct_pool_claim(e2ident);
544
545
546     correct_pool_delete();
547     return util_strdup(ident);
548 }