]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - correct.c
Add a notice
[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  *  Bayes' Therom suggests something of the following:
48  *      AC P(I|C) P(C) / P(I)
49  *  Since P(I) is the same for every possibly I, we can ignore it giving
50  *      AC P(I|C) P(C)
51  *
52  *  This greatly helps visualize how the parts of the expression are performed
53  *  there is essentially three, from right to left we perform the following:
54  *
55  *  1: P(C), the probability that a proposed correction C will stand on its
56  *     own.  This is called the language model.
57  *
58  *  2: P(I|C), the probability that I would be used, when the programmer
59  *     really meant C.  This is the error model.
60  *
61  *  3: AC, the control mechanisim, an enumerator if you will, one that
62  *     enumerates all feasible values of C, to determine the one that
63  *     gives the greatest probability score.
64  * 
65  *      In reality the requirement for a more complex expression involving
66  *  two seperate models is considerably a waste.  But one must recognize
67  *  that P(C|I) is already conflating two factors.  It's just much simpler
68  *  to seperate the two models and deal with them explicitaly.  To properly
69  *  estimate P(C|I) you have to consider both the probability of C and
70  *  probability of the transposition from C to I.  It's simply much more
71  *  cleaner, and direct to seperate the two factors.
72  *
73  *  Research tells us that 80% to 95% of all spelling errors have an edit
74  *  distance no greater than one.  Knowing this we can optimize for most
75  *  cases of mistakes without taking a performance hit.  Which is what we
76  *  base longer edit distances off of.  Opposed to the original method of
77  *  I had concieved of checking everything.     
78  *  
79  * A little information on additional algorithms used:
80  *
81  *   Initially when I implemented this corrector, it was very slow.
82  *   Need I remind you this is essentially a brute force attack on strings,
83  *   and since every transformation requires dynamic memory allocations,
84  *   you can easily imagine where most of the runtime conflated.  Yes
85  *   It went right to malloc.  More than THREE MILLION malloc calls are
86  *   performed for an identifier about 16 bytes long.  This was such a
87  *   shock to me.  A forward allocator (or as some call it a bump-point
88  *   allocator, or just a memory pool) was implemented. To combat this.
89  *
90  *   But of course even other factors were making it slow.  Initially
91  *   this used a hashtable.  And hashtables have a good constant lookup
92  *   time complexity.  But the problem wasn't in the hashtable, it was
93  *   in the hashing (despite having one of the fastest hash functions
94  *   known).  Remember those 3 million mallocs? Well for every malloc
95  *   there is also a hash.  After 3 million hashes .. you start to get
96  *   very slow.  To combat this I had suggested burst tries to Blub.
97  *   The next day he had implemented them. Sure enough this brought
98  *   down the runtime by a factory > 100%
99  *
100  * Future Work (If we really need it)
101  *
102  *   Currently we can only distinguishes one source of error in the
103  *   language model we use.  This could become an issue for identifiers
104  *   that have close colliding rates, e.g colate->coat yields collate.
105  *
106  *   Currently the error model has been fairly trivial, the smaller the
107  *   edit distance the smaller the error.  This usually causes some un-
108  *   expected problems. e.g reciet->recite yields recipt.  For QuakeC
109  *   this could become a problem when lots of identifiers are involved. 
110  *
111  *   Our control mechanisim could use a limit, i.e limit the number of
112  *   sets of edits for distance X.  This would also increase execution
113  *   speed considerably.  
114  */
115
116
117 #define CORRECT_POOLSIZE (128*1024*1024)
118 /*
119  * A forward allcator for the corrector.  This corrector requires a lot
120  * of allocations.  This forward allocator combats all those allocations
121  * and speeds us up a little.  It also saves us space in a way since each
122  * allocation isn't wasting a little header space for when NOTRACK isn't
123  * defined.
124  */    
125 static unsigned char **correct_pool_data = NULL;
126 static unsigned char  *correct_pool_this = NULL;
127 static size_t          correct_pool_addr = 0;
128
129 static GMQCC_INLINE void correct_pool_new(void) {
130     correct_pool_addr = 0;
131     correct_pool_this = (unsigned char *)mem_a(CORRECT_POOLSIZE);
132
133     vec_push(correct_pool_data, correct_pool_this);
134 }
135
136 static GMQCC_INLINE void *correct_pool_alloc(size_t bytes) {
137     void *data;
138     if (correct_pool_addr + bytes >= CORRECT_POOLSIZE)
139         correct_pool_new();
140
141     data               = correct_pool_this;
142     correct_pool_this += bytes;
143     correct_pool_addr += bytes;
144
145     return data;
146 }
147
148 static GMQCC_INLINE void correct_pool_delete(void) {
149     size_t i;
150     for (i = 0; i < vec_size(correct_pool_data); ++i)
151         mem_d(correct_pool_data[i]);
152
153     correct_pool_data = NULL;
154     correct_pool_this = NULL;
155     correct_pool_addr = 0;
156 }
157
158
159 static GMQCC_INLINE char *correct_pool_claim(const char *data) {
160     char *claim = util_strdup(data);
161     correct_pool_delete();
162     return claim;
163 }
164
165 /*
166  * A fast space efficent trie for a disctonary of identifiers.  This is
167  * faster than a hashtable for one reason.  A hashtable itself may have
168  * fast constant lookup time, but the hash itself must be very fast. We
169  * have one of the fastest hash functions for strings, but if you do a
170  * lost of hashing (which we do, almost 3 million hashes per identifier)
171  * a hashtable becomes slow. Very Very Slow.
172  */   
173 correct_trie_t* correct_trie_new() {
174     correct_trie_t *t = (correct_trie_t*)mem_a(sizeof(correct_trie_t));
175     t->value   = NULL;
176     t->entries = NULL;
177     return t;
178 }
179
180 void correct_trie_del_sub(correct_trie_t *t) {
181     size_t i;
182     for (i = 0; i < vec_size(t->entries); ++i)
183         correct_trie_del_sub(&t->entries[i]);
184     vec_free(t->entries);
185 }
186
187 void correct_trie_del(correct_trie_t *t) {
188     size_t i;
189     for (i = 0; i < vec_size(t->entries); ++i)
190         correct_trie_del_sub(&t->entries[i]);
191     vec_free(t->entries);
192     mem_d(t);
193 }
194
195 void* correct_trie_get(const correct_trie_t *t, const char *key) {
196     const unsigned char *data = (const unsigned char*)key;
197     while (*data) {
198         unsigned char ch = *data;
199         const size_t  vs = vec_size(t->entries);
200         size_t        i;
201         const correct_trie_t *entries = t->entries;
202         for (i = 0; i < vs; ++i) {
203             if (entries[i].ch == ch) {
204                 t = &entries[i];
205                 ++data;
206                 break;
207             }
208         }
209         if (i == vs)
210             return NULL;
211     }
212     return t->value;
213 }
214
215 void correct_trie_set(correct_trie_t *t, const char *key, void * const value) {
216     const unsigned char *data = (const unsigned char*)key;
217     while (*data) {
218         const size_t    vs      = vec_size(t->entries);
219         unsigned char   ch      = *data;
220         correct_trie_t *entries = t->entries;
221         size_t          i;
222
223         for (i = 0; i < vs; ++i) {
224             if (entries[i].ch == ch) {
225                 t = &entries[i];
226                 break;
227             }
228         }
229         if (i == vs) {
230             correct_trie_t *elem  = (correct_trie_t*)vec_add(t->entries, 1);
231
232             elem->ch      = ch;
233             elem->value   = NULL;
234             elem->entries = NULL;
235             t             = elem;
236         }
237         ++data;
238     }
239     t->value = value;
240 }
241
242
243 /*
244  * Implementation of the corrector algorithm commences. A very efficent
245  * brute-force attack (thanks to tries and mempool :-)).
246  */  
247 static size_t *correct_find(correct_trie_t *table, const char *word) {
248     return (size_t*)correct_trie_get(table, word);
249 }
250
251 static int correct_update(correct_trie_t* *table, const char *word) {
252     size_t *data = correct_find(*table, word);
253     if (!data)
254         return 0;
255
256     (*data)++;
257     return 1;
258 }
259
260 void correct_add(correct_trie_t* table, size_t ***size, const char *ident) {
261     size_t     *data = NULL;
262     const char *add  = ident;
263     
264     if (!correct_update(&table, add)) {
265         data  = (size_t*)mem_a(sizeof(size_t));
266         *data = 1;
267
268         vec_push((*size), data);
269         correct_trie_set(table, add, data);
270     }
271 }
272
273 void correct_del(correct_trie_t* dictonary, size_t **data) {
274     size_t       i;
275     const size_t vs = vec_size(data);
276
277     for (i = 0; i < vs; i++)
278         mem_d(data[i]);
279
280     vec_free(data);
281     correct_trie_del(dictonary);
282 }
283
284 /*
285  * _ is valid in identifiers. I've yet to implement numerics however
286  * because they're only valid after the first character is of a _, or
287  * alpha character.
288  */
289 static const char correct_alpha[] = "abcdefghijklmnopqrstuvwxyz"
290                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
291                                     "_"; /* TODO: Numbers ... */
292
293 /*
294  * correcting logic for the following forms of transformations:
295  *  1) deletion
296  *  2) transposition
297  *  3) alteration
298  *  4) insertion
299  *
300  * These functions could take an additional size_t **size paramater
301  * and store back the results of their new length in an array that
302  * is the same as **array for the memcmp in correct_exists. I'm just
303  * not able to figure out how to do that just yet.  As my brain is
304  * not in the mood to figure out that logic.  This is a reminder to
305  * do it, or for someone else to :-) correct_edit however would also
306  * need to take a size_t ** to carry it along (would all the argument
307  * overhead be worth it?)  
308  */
309 static size_t correct_deletion(const char *ident, char **array, size_t index) {
310     size_t       itr = 0;
311     const size_t len = strlen(ident);
312
313     for (; itr < len; itr++) {
314         char *a = (char*)correct_pool_alloc(len+1);
315         memcpy(a, ident, itr);
316         memcpy(a + itr, ident + itr + 1, len - itr);
317         array[index + itr] = a;
318     }
319
320     return itr;
321 }
322
323 static size_t correct_transposition(const char *ident, char **array, size_t index) {
324     size_t       itr = 0;
325     const size_t len = strlen(ident);
326
327     for (; itr < len - 1; itr++) {
328         char  tmp;
329         char *a = (char*)correct_pool_alloc(len+1);
330         memcpy(a, ident, len+1);
331         tmp      = a[itr];
332         a[itr  ] = a[itr+1];
333         a[itr+1] = tmp;
334         array[index + itr] = a;
335     }
336
337     return itr;
338 }
339
340 static size_t correct_alteration(const char *ident, char **array, size_t index) {
341     size_t       itr = 0;
342     size_t       jtr = 0;
343     size_t       ktr = 0;
344     const size_t len = strlen(ident);
345
346     for (; itr < len; itr++) {
347         for (jtr = 0; jtr < sizeof(correct_alpha)-1; jtr++, ktr++) {
348             char *a = (char*)correct_pool_alloc(len+1);
349             memcpy(a, ident, len+1);
350             a[itr] = correct_alpha[jtr];
351             array[index + ktr] = a;
352         }
353     }
354
355     return ktr;
356 }
357
358 static size_t correct_insertion(const char *ident, char **array, size_t index) {
359     size_t       itr = 0;
360     size_t       jtr = 0;
361     size_t       ktr = 0;
362     const size_t len = strlen(ident);
363
364     for (; itr <= len; itr++) {
365         for (jtr = 0; jtr < sizeof(correct_alpha)-1; jtr++, ktr++) {
366             char *a = (char*)correct_pool_alloc(len+2);
367             memcpy(a, ident, itr);
368             memcpy(a + itr + 1, ident + itr, len - itr + 1);
369             a[itr] = correct_alpha[jtr];
370             array[index + ktr] = a;
371         }
372     }
373
374     return ktr;
375 }
376
377 static GMQCC_INLINE size_t correct_size(const char *ident) {
378     /*
379      * deletion      = len
380      * transposition = len - 1
381      * alteration    = len * sizeof(correct_alpha)
382      * insertion     = (len + 1) * sizeof(correct_alpha)
383      */   
384
385     register size_t len = strlen(ident);
386     return (len) + (len - 1) + (len * (sizeof(correct_alpha)-1)) + ((len + 1) * (sizeof(correct_alpha)-1));
387 }
388
389 static char **correct_edit(const char *ident) {
390     size_t next;
391     char **find = (char**)correct_pool_alloc(correct_size(ident) * sizeof(char*));
392
393     if (!find)
394         return NULL;
395
396     next  = correct_deletion     (ident, find, 0);
397     next += correct_transposition(ident, find, next);
398     next += correct_alteration   (ident, find, next);
399     /*****/ correct_insertion    (ident, find, next);
400
401     return find;
402 }
403
404 /*
405  * We could use a hashtable but the space complexity isn't worth it
406  * since we're only going to determine the "did you mean?" identifier
407  * on error.
408  */   
409 static int correct_exist(char **array, size_t rows, char *ident) {
410     size_t itr;
411     for (itr = 0; itr < rows; itr++)
412         if (!memcmp(array[itr], ident, strlen(ident)))
413             return 1;
414
415     return 0;
416 }
417
418 static GMQCC_INLINE char **correct_known_resize(char **res, size_t *allocated, size_t size) {
419     size_t oldallocated = *allocated;
420     char **out;
421     if (size+1 < *allocated)
422         return res;
423
424     *allocated += 32;
425     out = correct_pool_alloc(sizeof(*res) * *allocated);
426     memcpy(out, res, sizeof(*res) * oldallocated);
427     return out;
428 }
429
430 static char **correct_known(correct_trie_t* table, char **array, size_t rows, size_t *next) {
431     size_t itr = 0;
432     size_t jtr = 0;
433     size_t len = 0;
434     size_t row = 0;
435     size_t nxt = 8;
436     char **res = correct_pool_alloc(sizeof(char *) * nxt);
437     char **end = NULL;
438
439     for (; itr < rows; itr++) {
440         end = correct_edit(array[itr]);
441         row = correct_size(array[itr]);
442
443         for (; jtr < row; jtr++) {
444             if (correct_find(table, end[jtr]) && !correct_exist(res, len, end[jtr])) {
445                 res        = correct_known_resize(res, &nxt, len+1);
446                 res[len++] = end[jtr];
447             }
448         }
449     }
450
451     *next = len;
452     return res;
453 }
454
455 static char *correct_maximum(correct_trie_t* table, char **array, size_t rows) {
456     char   *str = NULL;
457     size_t *itm = NULL;
458     size_t  itr = 0;
459     size_t  top = 0;
460
461     for (; itr < rows; itr++) {
462         if ((itm = correct_find(table, array[itr])) && (*itm > top)) {
463             top = *itm;
464             str = array[itr];
465         }
466     }
467
468     return str;
469 }
470
471 /*
472  * This is the exposed interface:
473  * takes a table for the dictonary a vector of sizes (used for internal
474  * probability calculation, and an identifier to "correct"
475  *
476  * the add function works the same.  Except the identifier is used to
477  * add to the dictonary.  
478  */
479 char *correct_str(correct_trie_t* table, const char *ident) {
480     char **e1      = NULL;
481     char **e2      = NULL;
482     char  *e1ident = NULL;
483     char  *e2ident = NULL;
484     size_t e1rows  = 0;
485     size_t e2rows  = 0;
486
487     correct_pool_new();
488
489     /* needs to be allocated for free later */
490     if (correct_find(table, ident))
491         return correct_pool_claim(ident);
492
493     if ((e1rows = correct_size(ident))) {
494         e1      = correct_edit(ident);
495
496         if ((e1ident = correct_maximum(table, e1, e1rows)))
497             return correct_pool_claim(e1ident);
498     }
499
500     e2 = correct_known(table, e1, e1rows, &e2rows);
501     if (e2rows && ((e2ident = correct_maximum(table, e2, e2rows))))
502         return correct_pool_claim(e2ident);
503
504
505     correct_pool_delete();
506     return util_strdup(ident);
507 }