]> git.xonotic.org Git - xonotic/gmqcc.git/blob - correct.c
Fix another two leaks
[xonotic/gmqcc.git] / correct.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Dale Weiler
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include "gmqcc.h"
24
25 /*
26  * This is a very clever method for correcting mistakes in QuakeC code
27  * most notably when invalid identifiers are used or inproper assignments;
28  * we can proprly lookup in multiple dictonaries (depening on the rules
29  * of what the task is trying to acomplish) to find the best possible
30  * match.
31  *
32  *
33  * A little about how it works, and probability theory:
34  *
35  *  When given an identifier (which we will denote I), we're essentially
36  *  just trying to choose the most likely correction for that identifier.
37  *  (the actual "correction" can very well be the identifier itself).
38  *  There is actually no way to know for sure that certian identifers
39  *  such as "lates", need to be corrected to "late" or "latest" or any
40  *  other permutations that look lexically the same.  This is why we
41  *  must advocate the usage of probabilities.  This implies that we're
42  *  trying to find the correction for C, out of all possible corrections
43  *  that maximizes the probability of C for the original identifer I.
44  *
45  *  Bayes' Therom suggests something of the following:
46  *      AC P(I|C) P(C) / P(I)
47  *  Since P(I) is the same for every possibly I, we can ignore it giving
48  *      AC P(I|C) P(C)
49  *
50  *  This greatly helps visualize how the parts of the expression are performed
51  *  there is essentially three, from right to left we perform the following:
52  *
53  *  1: P(C), the probability that a proposed correction C will stand on its
54  *     own.  This is called the language model.
55  *
56  *  2: P(I|C), the probability that I would be used, when the programmer
57  *     really meant C.  This is the error model.
58  *
59  *  3: AC, the control mechanisim, which implies the enumeration of all
60  *     feasible values of C, and then determine the one that gives the
61  *     greatest probability score. Selecting it as the "correction"
62  *   
63  *
64  * The requirement for complex expression involving two models:
65  * 
66  *  In reality the requirement for a more complex expression involving
67  *  two seperate models is considerably a waste.  But one must recognize
68  *  that P(C|I) is already conflating two factors.  It's just much simpler
69  *  to seperate the two models and deal with them explicitaly.  To properly
70  *  estimate P(C|I) you have to consider both the probability of C and
71  *  probability of the transposition from C to I.  It's simply much more
72  *  cleaner, and direct to seperate the two factors.
73  */
74
75 /* some hashtable management for dictonaries */
76 static size_t *correct_find(ht table, const char *word) {
77     return (size_t*)util_htget(table, word);
78 }
79
80 static int correct_update(ht *table, const char *word) {
81     size_t *data = correct_find(*table, word);
82     if (!data)
83         return 0;
84
85     (*data)++;
86     return 1;
87 }
88
89
90 /*
91  * _ is valid in identifiers. I've yet to implement numerics however
92  * because they're only valid after the first character is of a _, or
93  * alpha character.
94  */
95 static const char correct_alpha[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
96
97 static char *correct_strndup(const char *src, size_t n) {
98     char   *ret;
99     size_t  len = strlen(src);
100
101     if (n < len)
102         len = n;
103
104     if (!(ret = (char*)mem_a(len + 1)))
105         return NULL;
106
107     ret[len] = '\0';
108     return (char*)memcpy(ret, src, len);
109 }
110
111 static char *correct_concat(char *str1, char *str2, bool next) {
112     char *ret = NULL;
113
114     if (!str1) {
115          str1 = mem_a(1);
116         *str1 = '\0';
117     }
118
119     str1 = mem_r (str1, strlen(str1) + strlen(str2) + 1);
120     ret  = strcat(str1, str2);
121
122     if (str2 && next)
123         mem_d(str2);
124
125     return ret;
126 }
127
128 /*
129  * correcting logic for the following forms of transformations:
130  *  1) deletion
131  *  2) transposition
132  *  3) alteration
133  *  4) insertion
134  */
135 static size_t correct_deletion(const char *ident, char **array, size_t index) {
136     size_t itr;
137     size_t len = strlen(ident);
138
139     for (itr = 0; itr < len; itr++) {
140         array[index + itr] = correct_concat (
141             correct_strndup (ident,       itr),
142             correct_strndup (ident+itr+1, len-(itr+1)),
143             true
144         );
145     }
146
147     return itr;
148 }
149
150 static size_t correct_transposition(const char *ident, char **array, size_t index) {
151     size_t itr;
152     size_t len = strlen(ident);
153
154     for (itr = 0; itr < len - 1; itr++) {
155         array[index + itr] = correct_concat (
156             correct_concat (
157                 correct_strndup(ident,     itr),
158                 correct_strndup(ident+itr+1, 1),
159                 true
160             ),
161             correct_concat (
162                 correct_strndup(ident+itr,   1),
163                 correct_strndup(ident+itr+2, len-(itr+2)),
164                 true
165             ),
166             true
167         );
168     }
169
170     return itr;
171 }
172
173 static size_t correct_alteration(const char *ident, char **array, size_t index) {
174     size_t itr;
175     size_t jtr;
176     size_t ktr;
177     size_t len    = strlen(ident);
178     char   cct[2] = { 0, 0 }; /* char code table, for concatenation */
179
180     for (itr = 0, ktr = 0; itr < len; itr++) {
181         for (jtr = 0; jtr < sizeof(correct_alpha); jtr++, ktr++) {
182             *cct = correct_alpha[jtr];
183             array[index + ktr] = correct_concat (
184                 correct_concat (
185                     correct_strndup(ident, itr),
186                     (char *) &cct,
187                     false
188                 ),
189                 correct_strndup (
190                     ident + (itr+1),
191                     len   - (itr+1)
192                 ),
193                 true
194             );
195         }
196     }
197
198     return ktr;
199 }
200
201 static size_t correct_insertion(const char *ident, char **array, size_t index) {
202     size_t itr;
203     size_t jtr;
204     size_t ktr;
205     size_t len    = strlen(ident);
206     char   cct[2] = { 0, 0 }; /* char code table, for concatenation */
207
208     for (itr = 0, ktr = 0; itr <= len; itr++) {
209         for (jtr = 0; jtr < sizeof(correct_alpha); jtr++, ktr++) {
210             *cct = correct_alpha[jtr];
211             array[index + ktr] = correct_concat (
212                 correct_concat (
213                     correct_strndup (ident, itr),
214                     (char *) &cct,
215                     false
216                 ),
217                 correct_strndup (
218                     ident+itr,
219                     len - itr
220                 ),
221                 true
222             );
223         }
224     }
225
226     return ktr;
227 }
228
229 static GMQCC_INLINE size_t correct_size(const char *ident) {
230     /*
231      * deletion      = len
232      * transposition = len - 1
233      * alteration    = len * sizeof(correct_alpha)
234      * insertion     = (len + 1) * sizeof(correct_alpha)
235      */   
236
237     register size_t len = strlen(ident);
238     return (len) + (len - 1) + (len * sizeof(correct_alpha)) + ((len + 1) * sizeof(correct_alpha));
239 }
240
241 static char **correct_edit(const char *ident) {
242     size_t next;
243     char **find = (char**)mem_a(correct_size(ident) * sizeof(char*));
244
245     if (!find)
246         return NULL;
247
248     next  = correct_deletion     (ident, find, 0);
249     next += correct_transposition(ident, find, next);
250     next += correct_alteration   (ident, find, next);
251     /*****/ correct_insertion    (ident, find, next);
252
253     return find;
254 }
255
256 /*
257  * We could use a hashtable but the space complexity isn't worth it
258  * since we're only going to determine the "did you mean?" identifier
259  * on error.
260  */   
261 static int correct_exist(char **array, size_t rows, char *ident) {
262     size_t itr;
263     for (itr = 0; itr < rows; itr++)
264         if (!strcmp(array[itr], ident))
265             return 1;
266
267     return 0;
268 }
269
270 static char **correct_known(ht table, char **array, size_t rows, size_t *next) {
271     size_t itr;
272     size_t jtr;
273     size_t len;
274     size_t row;
275     char **res = NULL;
276     char **end;
277
278     for (itr = 0, len = 0; itr < rows; itr++) {
279         end = correct_edit(array[itr]);
280         row = correct_size(array[itr]);
281
282         for (jtr = 0; jtr < row; jtr++) {
283             if (correct_find(table, end[jtr]) && !correct_exist(res, len, end[jtr])) {
284                 res        = mem_r(res, sizeof(char*) * (len + 1));
285                 res[len++] = end[jtr];
286             }
287         }
288
289         mem_d(end);
290     }
291
292     *next = len;
293     return res;
294 }
295
296 static char *correct_maximum(ht table, char **array, size_t rows) {
297     char   *str  = NULL;
298     size_t *itm  = NULL;
299     size_t  itr;
300     size_t  top;
301
302     for (itr = 0, top = 0; itr < rows; itr++) {
303         if ((itm = correct_find(table, array[itr])) && (*itm > top)) {
304             top = *itm;
305             str = array[itr];
306         }
307     }
308
309     return str;
310 }
311
312 static void correct_cleanup(char **array, size_t rows) {
313     size_t itr;
314     for (itr = 0; itr < rows; itr++)
315         mem_d(array[itr]);
316 }
317
318 /*
319  * This is the exposed interface:
320  * takes a table for the dictonary a vector of sizes (used for internal
321  * probability calculation, and an identifier to "correct"
322  *
323  * the add function works the same.  Except the identifier is used to
324  * add to the dictonary.  
325  */   
326 void correct_add(ht table, size_t ***size, const char *ident) {
327     size_t     *data = NULL;
328     const char *add  = ident;
329     
330     if (!correct_update(&table, add)) {
331         data  = (size_t*)mem_a(sizeof(size_t));
332         *data = 1;
333
334         vec_push((*size), data);
335         util_htset(table, add, data);
336     }
337 }
338
339 char *correct_correct(ht table, const char *ident) {
340     char **e1;
341     char **e2;
342     char  *e1ident;
343     char  *e2ident;
344     char  *found = util_strdup(ident);
345
346     size_t e1rows = 0;
347     size_t e2rows = 0;
348
349     /* needs to be allocated for free later */
350     if (correct_find(table, ident))
351         return found;
352
353     mem_d(found);
354     if ((e1rows = correct_size(ident))) {
355         e1      = correct_edit(ident);
356
357         if ((e1ident = correct_maximum(table, e1, e1rows))) {
358             found = util_strdup(e1ident);
359             correct_cleanup(e1, e1rows);
360             mem_d(e1);
361             return found;
362         }
363     }
364
365     e2 = correct_known(table, e1, e1rows, &e2rows);
366     if (e2rows && ((e2ident = correct_maximum(table, e2, e2rows))))
367         found = util_strdup(e2ident);
368     
369     correct_cleanup(e1, e1rows);
370     correct_cleanup(e2, e2rows);
371
372     mem_d(e1);
373     mem_d(e2);
374     
375     return found;
376 }
377
378 void correct_del(ht dictonary, size_t **data) {
379     size_t i;
380     for (i = 0; i < vec_size(data); i++)
381         mem_d(data[i]);
382
383     vec_free(data);
384     util_htdel(dictonary);
385 }
386
387 int main() {
388     opts.debug = true;
389     opts.memchk = true;
390     con_init();
391
392     ht       t = util_htnew(1024);
393     size_t **d = NULL;
394
395     correct_add(t, &d, "hellobain");
396     correct_add(t, &d, "ellor");
397     correct_add(t, &d, "world");
398
399     printf("found identifiers: (2)\n");
400     printf(" 1: hellobain\n");
401     printf(" 2: ellor\n");
402     printf(" 3: world\n");
403
404     char *b = correct_correct(t, "rld");
405     char *a = correct_correct(t, "ello");
406     char *c = correct_correct(t, "helbain");
407
408     printf("invalid identifier: `%s` (did you mean: `%s`?)\n", "ello", a);
409     printf("invalid identifier: `%s` (did you mean: `%s`?)\n", "rld", b);
410     printf("invalid identifier: `%s` (did you mean: `%s`?)\n", "helbain", c);
411
412     correct_del(t, d);
413     mem_d(b);
414     mem_d(a);
415     mem_d(c);
416
417     /*util_meminfo();*/
418
419 }