ccanlint: make tests non-compulsory, always print score.
[ccan] / tools / ccanlint / tests / examples_compile.c
1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/str/str.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <stdint.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <ctype.h>
12 #include <assert.h>
13
14 static const char *can_run(struct manifest *m)
15 {
16         if (safe_mode)
17                 return "Safe mode enabled";
18         return NULL;
19 }
20
21 /* FIXME: We should build if it doesn't exist... */
22 static bool expect_obj_file(const char *dir)
23 {
24         struct manifest *dep_man;
25         bool has_c_files;
26
27         dep_man = get_manifest(dir, dir);
28
29         /* If it has C files, we expect an object file built from them. */
30         has_c_files = !list_empty(&dep_man->c_files);
31         talloc_free(dep_man);
32         return has_c_files;
33 }
34
35 static char *add_dep(const struct manifest *m, char *list, const char *mod)
36 {
37         char **deps, *obj;
38         unsigned int i;
39
40         /* Not ourselves. */
41         if (streq(m->basename, mod))
42                 return list;
43
44         /* Not if there's no object file for that module */
45         if (!expect_obj_file(talloc_asprintf(list, "%s/ccan/%s", ccan_dir,mod)))
46                 return list;
47
48         obj = talloc_asprintf(list, "%s/ccan/%s.o", ccan_dir, mod);
49
50         /* Not anyone we've already included. */
51         if (strstr(list, obj))
52                 return list;
53
54         list = talloc_asprintf_append(list, " %s", obj);
55
56         /* Get that modules depends as well... */
57         assert(!safe_mode);
58         deps = get_deps(m, talloc_asprintf(list, "%s/ccan/%s", ccan_dir, mod),
59                         false, NULL);
60
61         for (i = 0; deps[i]; i++) {
62                 if (strstarts(deps[i], "ccan/"))
63                         list = add_dep(m, list, deps[i] + strlen("ccan/"));
64         }
65         return list;
66 }
67
68 static char *obj_list(const struct manifest *m, struct ccan_file *f)
69 {
70         char *list = talloc_strdup(m, "");
71         struct ccan_file *i;
72         char **lines;
73
74         /* Object files for this module. */
75         list_for_each(&m->c_files, i, list)
76                 list = talloc_asprintf_append(list, " %s", i->compiled);
77
78         /* Other ccan modules we depend on. */
79         list_for_each(&m->dep_dirs, i, list) {
80                 if (i->compiled)
81                         list = talloc_asprintf_append(list, " %s", i->compiled);
82         }
83
84         /* Other modules implied by includes. */
85         for (lines = get_ccan_file_lines(f); *lines; lines++) {
86                 unsigned preflen = strspn(*lines, " \t");
87                 if (strstarts(*lines + preflen, "#include <ccan/")) {
88                         const char *mod;
89                         unsigned modlen;
90
91                         mod = *lines + preflen + strlen("#include <ccan/");
92                         modlen = strcspn(mod, "/");
93                         mod = talloc_strndup(f, mod, modlen);
94                         list = add_dep(m, list, mod);
95                 }
96         }
97
98         return list;
99 }
100
101 static char *lib_list(const struct manifest *m)
102 {
103         unsigned int i, num;
104         char **libs = get_libs(m, ".", &num, &m->info_file->compiled);
105         char *ret = talloc_strdup(m, "");
106
107         for (i = 0; i < num; i++)
108                 ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
109         return ret;
110 }
111
112 static char *compile(const void *ctx,
113                      struct manifest *m,
114                      struct ccan_file *file,
115                      bool keep)
116 {
117         char *errmsg;
118
119         file->compiled = maybe_temp_file(ctx, "", keep, file->fullname);
120         errmsg = compile_and_link(ctx, file->fullname, ccan_dir,
121                                   obj_list(m, file),
122                                   "", lib_list(m), file->compiled);
123         if (errmsg) {
124                 talloc_free(file->compiled);
125                 return errmsg;
126         }
127         return NULL;
128 }
129
130 struct score {
131         unsigned int score;
132         char *errors;
133 };
134
135 static char *start_main(char *ret, const char *why)
136 {
137         return talloc_asprintf_append(ret,
138               "/* The example %s, so fake function wrapper inserted */\n"
139               "int main(int argc, char *argv[])\n"
140               "{\n", why);
141 }
142
143 /* We only handle simple function definitions here. */
144 static char *add_func(char *others, const char *line)
145 {
146         const char *p, *end = strchr(line, '(') - 1;
147         while (isblank(*end)) {
148                 end--;
149                 if (end == line)
150                         return others;
151         }
152
153         for (p = end; isalnum(*p) || *p == '_'; p--) {
154                 if (p == line)
155                         return others;
156         }
157
158         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
159                                       (unsigned)(end - p + 1), p);
160 }
161
162 static void strip_leading_whitespace(char **lines)
163 {
164         unsigned int i, min_span = -1U;
165
166         for (i = 0; lines[i]; i++) {
167                 unsigned int span = strspn(lines[i], " \t");
168                 /* All whitespace?  Ignore */
169                 if (!lines[i][span])
170                         continue;
171                 if (span < min_span)
172                         min_span = span;
173         }
174
175         for (i = 0; lines[i]; i++)
176                 if (strlen(lines[i]) >= min_span)
177                         lines[i] += min_span;
178 }
179
180 static bool looks_internal(char **lines, char **why)
181 {
182         unsigned int i;
183         bool last_ended = true; /* Did last line finish a statement? */
184
185         for (i = 0; lines[i]; i++) {
186                 /* Skip leading whitespace. */
187                 const char *line = lines[i] + strspn(lines[i], " \t");
188                 unsigned len = strspn(line, IDENT_CHARS);
189
190                 if (!line[0] || isblank(line[0]) || strstarts(line, "//"))
191                         continue;
192
193                 /* The winners. */
194                 if (strstarts(line, "if") && len == 2) {
195                         *why = "starts with if";
196                         return true;
197                 }
198                 if (strstarts(line, "for") && len == 3) {
199                         *why = "starts with for";
200                         return true;
201                 }
202                 if (strstarts(line, "while") && len == 5) {
203                         *why = "starts with while";
204                         return true;
205                 }
206                 if (strstarts(line, "do") && len == 2) {
207                         *why = "starts with do";
208                         return true;
209                 }
210
211                 /* The losers. */
212                 if (strstarts(line, "#include")) {
213                         *why = "starts with #include";
214                         return false;
215                 }
216
217                 if (last_ended && strchr(line, '(')) {
218                         if (strstarts(line, "static")) {
219                                 *why = "starts with static and contains (";
220                                 return false;
221                         }
222                         if (strends(line, ")")) {
223                                 *why = "contains ( and ends with )";
224                                 return false;
225                         }
226                 }
227
228                 /* Single identifier then operator == inside function. */
229                 if (last_ended && len
230                     && ispunct(line[len+strspn(line+len, " ")])) {
231                         *why = "starts with identifier then punctuation";
232                         return true;
233                 }
234
235                 last_ended = (strends(line, "}")
236                               || strends(line, ";")
237                               || streq(line, "..."));
238         }
239
240         /* No idea... Say yes? */
241         *why = "gave no clues";
242         return true;
243 }
244
245 /* Examples will often build on prior ones.  Try combining them. */
246 static char **combine(const void *ctx, char **lines, char **prev)
247 {
248         unsigned int i, lines_total, prev_total, count;
249         char **ret;
250         const char *reasoning;
251         char *why = NULL;
252
253         if (!prev)
254                 return NULL;
255
256         /* If it looks internal, put prev at start. */
257         if (looks_internal(lines, &why)) {
258                 count = 0;
259                 reasoning = "seemed to belong inside a function";
260         } else {
261                 /* Try inserting in first elided position */
262                 for (count = 0; lines[count]; count++) {
263                         if (strcmp(lines[count], "...") == 0)
264                                 break;
265                 }
266                 if (!lines[count]) {
267                         /* Try at start anyway? */
268                         count = 0;
269                         reasoning = "didn't seem to belong inside"
270                                 " a function, so we prepended the previous"
271                                 " example";
272                 } else {
273                         reasoning = "didn't seem to belong inside"
274                                 " a function, so we put the previous example"
275                                 " at the first ...";
276
277                         count++;
278                 }
279         }
280
281         for (i = 0; lines[i]; i++);
282         lines_total = i;
283
284         for (i = 0; prev[i]; i++);
285         prev_total = i;
286
287         ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
288         ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */\n",
289                                  why, reasoning);
290         memcpy(ret+1, lines, count * sizeof(ret[0]));
291         memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
292         memcpy(ret+1 + count + prev_total, lines + count,
293                (lines_total - count + 1) * sizeof(ret[0]));
294         return ret;
295 }
296
297 static char *mangle(struct manifest *m, char **lines)
298 {
299         char *ret, *use_funcs = NULL, *why;
300         bool in_function = false, fake_function = false, has_main = false;
301         unsigned int i;
302
303         ret = talloc_strdup(m, "/* Prepend a heap of headers. */\n"
304                             "#include <assert.h>\n"
305                             "#include <err.h>\n"
306                             "#include <errno.h>\n"
307                             "#include <fcntl.h>\n"
308                             "#include <limits.h>\n"
309                             "#include <stdbool.h>\n"
310                             "#include <stdint.h>\n"
311                             "#include <stdio.h>\n"
312                             "#include <stdlib.h>\n"
313                             "#include <string.h>\n"
314                             "#include <sys/stat.h>\n"
315                             "#include <sys/types.h>\n"
316                             "#include <unistd.h>\n");
317         ret = talloc_asprintf_append(ret, "/* Include header from module. */\n"
318                                      "#include <ccan/%s/%s.h>\n",
319                                      m->basename, m->basename);
320
321         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
322                                      "extern int somefunc(void);\n"
323                                      "int somefunc(void) { return 0; }\n"
324                                      "extern char somestring[];\n"
325                                      "char somestring[] = \"hello world\";\n");
326
327         if (looks_internal(lines, &why)) {
328                 /* Wrap it all in main(). */
329                 ret = start_main(ret, why);
330                 fake_function = true;
331                 in_function = true;
332                 has_main = true;
333         } else
334                 ret = talloc_asprintf_append(ret,
335                              "/* The example %s, so didn't wrap in main() */\n",
336                                      why);
337
338         /* Primitive, very primitive. */
339         for (i = 0; lines[i]; i++) {
340                 /* } at start of line ends a function. */
341                 if (in_function) {
342                         if (lines[i][0] == '}')
343                                 in_function = false;
344                 } else {
345                         /* Character at start of line, with ( and no ;
346                          * == function start.  Ignore comments. */
347                         if (!isblank(lines[i][0])
348                             && strchr(lines[i], '(')
349                             && !strchr(lines[i], ';')
350                             && !strstr(lines[i], "//")) {
351                                 in_function = true;
352                                 if (strncmp(lines[i], "int main", 8) == 0)
353                                         has_main = true;
354                                 if (strncmp(lines[i], "static", 6) == 0) {
355                                         use_funcs = add_func(use_funcs,
356                                                              lines[i]);
357                                 }
358                         }
359                 }
360                 /* ... means elided code. */
361                 if (strcmp(lines[i], "...") == 0) {
362                         if (!in_function && !has_main
363                             && looks_internal(lines + i + 1, &why)) {
364                                 /* This implies we start a function here. */
365                                 ret = start_main(ret, why);
366                                 has_main = true;
367                                 fake_function = true;
368                                 in_function = true;
369                         }
370                         ret = talloc_asprintf_append(ret,
371                                                      "/* ... removed */\n");
372                         continue;
373                 }
374                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
375         }
376
377         if (!has_main) {
378                 ret = talloc_asprintf_append(ret,
379                              "/* Need a main to link successfully. */\n"
380                              "int main(void)\n{\n");
381                 fake_function = true;
382         }
383
384         if (use_funcs) {
385                 ret = talloc_asprintf_append(ret,
386                                              "/* Get rid of unused warnings"
387                                              " by printing addresses of"
388                                              " static funcs. */");
389                 if (!fake_function) {
390                         ret = talloc_asprintf_append(ret,
391                                                      "int use_funcs(void);\n"
392                                                      "int use_funcs(void) {\n");
393                         fake_function = true;
394                 }
395                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
396         }
397
398         if (fake_function)
399                 ret = talloc_asprintf_append(ret, "return 0;\n"
400                                              "}\n");
401         return ret;
402 }
403
404 static struct ccan_file *mangle_example(struct manifest *m,
405                                         struct ccan_file *example,
406                                         char **lines,
407                                         bool keep)
408 {
409         char *name, *contents;
410         int fd;
411         struct ccan_file *f;
412
413         name = maybe_temp_file(example, ".c", keep, 
414                                talloc_asprintf(m, "%s/mangled-%s",
415                                                m->dir, example->name));
416         f = new_ccan_file(example,
417                           talloc_dirname(example, name),
418                           talloc_basename(example, name));
419         talloc_steal(f, name);
420
421         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
422         if (fd < 0)
423                 return NULL;
424
425         contents = mangle(m, lines);
426         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
427                 close(fd);
428                 return NULL;
429         }
430         close(fd);
431         f->contents = talloc_steal(f, contents);
432         return f;
433 }
434
435 static void *build_examples(struct manifest *m, bool keep,
436                             unsigned int *timeleft)
437 {
438         struct ccan_file *i;
439         struct score *score = talloc(m, struct score);
440         char **prev = NULL;
441
442         score->score = 0;
443         score->errors = talloc_strdup(score, "");
444
445         examples_compile.total_score = 0;
446         list_for_each(&m->examples, i, list) {
447                 char *ret, *ret1 = NULL, *ret2;
448                 struct ccan_file *mangle1 = NULL, *mangle2;
449
450                 examples_compile.total_score++;
451                 /* Simplify our dumb parsing. */
452                 strip_leading_whitespace(get_ccan_file_lines(i));
453                 ret = compile(score, m, i, keep);
454                 if (!ret) {
455                         prev = get_ccan_file_lines(i);
456                         score->score++;
457                         continue;
458                 }
459
460                 /* Try combining with previous (successful) example... */
461                 if (prev) {
462                         char **new = combine(i, get_ccan_file_lines(i), prev);
463
464                         mangle1 = mangle_example(m, i, new, keep);
465                         ret1 = compile(score, m, mangle1, keep);
466                         if (!ret1) {
467                                 prev = new;
468                                 score->score++;
469                                 continue;
470                         }
471                 }
472
473                 /* Try standalone. */
474                 mangle2 = mangle_example(m, i, get_ccan_file_lines(i), keep);
475                 ret2 = compile(score, m, mangle2, keep);
476                 if (!ret2) {
477                         prev = get_ccan_file_lines(i);
478                         score->score++;
479                         continue;
480                 }
481
482                 score->errors = talloc_asprintf_append(score->errors,
483                                        "%s: tried standalone example:\n"
484                                        "%s\n"
485                                        "Errors: %s\n\n",
486                                        i->name,
487                                        get_ccan_file_contents(i),
488                                        ret);
489                 if (mangle1) {
490                         score->errors = talloc_asprintf_append(score->errors,
491                                                "%s: tried combining with"
492                                                " previous example:\n"
493                                                "%s\n"
494                                                "Errors: %s\n\n",
495                                                i->name,
496                                                get_ccan_file_contents(mangle1),
497                                                ret1);
498                 }
499                 score->errors = talloc_asprintf_append(score->errors,
500                                        "%s: tried adding headers, wrappers:\n"
501                                        "%s\n"
502                                        "Errors: %s\n\n",
503                                        i->name,
504                                        get_ccan_file_contents(mangle2),
505                                        ret2);
506                 /* This didn't work, so not a candidate for combining. */
507                 prev = NULL;
508         }
509
510         if (strcmp(score->errors, "") == 0) {
511                 talloc_free(score);
512                 return NULL;
513         }
514         return score;
515 }
516
517 static unsigned int score_examples(struct manifest *m, void *check_result)
518 {
519         struct score *score = check_result;
520         return score->score;
521 }
522
523 static const char *describe(struct manifest *m, void *check_result)
524 {
525         struct score *score = check_result;
526         if (verbose >= 2 && score->errors)
527                 return talloc_asprintf(m, "Compile errors building examples:\n"
528                                        "%s", score->errors);
529         return NULL;
530 }
531
532 struct ccanlint examples_compile = {
533         .key = "examples-compile",
534         .name = "Module examples compile",
535         .score = score_examples,
536         .total_score = 3, /* This gets changed to # examples, if they exist */
537         .check = build_examples,
538         .describe = describe,
539         .can_run = can_run,
540 };
541
542 REGISTER_TEST(examples_compile, &has_examples, NULL);