]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/tests/examples_compile.c
ccanlint: add #line directives to examples.
[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/cast/cast.h>
5 #include <ccan/str/str.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <stdint.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <ctype.h>
13 #include <assert.h>
14 #include <err.h>
15 #include "build.h"
16
17 static const char *can_run(struct manifest *m)
18 {
19         if (safe_mode)
20                 return "Safe mode enabled";
21         if (list_empty(&m->examples))
22                 return "No examples to compile";
23         return NULL;
24 }
25
26 static void add_mod(struct manifest ***deps, struct manifest *m)
27 {
28         unsigned int num = talloc_get_size(*deps) / sizeof(*deps);
29         *deps = talloc_realloc(NULL, *deps, struct manifest *, num + 1);
30         (*deps)[num] = m;
31 }
32
33 static bool have_mod(struct manifest *deps[], const char *basename)
34 {
35         unsigned int i;
36
37         for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++)
38                 if (strcmp(deps[i]->basename, basename) == 0)
39                         return true;
40         return false;
41 }
42
43 static void add_dep(struct manifest ***deps, const char *basename)
44 {
45         unsigned int i;
46         struct manifest *m;
47         char *errstr;
48
49         if (have_mod(*deps, basename))
50                 return;
51
52         m = get_manifest(*deps, talloc_asprintf(*deps, "%s/ccan/%s",
53                                                 ccan_dir, basename));
54         errstr = build_submodule(m, cflags, COMPILE_NORMAL);
55         if (errstr)
56                 errx(1, "%s", errstr);
57
58         add_mod(deps, m);
59
60         /* Get that modules depends as well... */
61         assert(!safe_mode);
62         if (m->info_file) {
63                 char **infodeps;
64
65                 infodeps = get_deps(m, m->dir, false, get_or_compile_info);
66
67                 for (i = 0; infodeps[i]; i++) {
68                         if (strstarts(infodeps[i], "ccan/"))
69                                 add_dep(deps, infodeps[i] + strlen("ccan/"));
70                 }
71         }
72 }
73
74 static struct manifest **get_example_deps(struct manifest *m,
75                                           struct ccan_file *f)
76 {
77         char **lines;
78         struct manifest **deps = talloc_array(f, struct manifest *, 0);
79
80         /* This one for a start. */
81         add_dep(&deps, m->basename);
82
83         /* Other modules implied by includes. */
84         for (lines = get_ccan_file_lines(f); *lines; lines++) {
85                 unsigned preflen = strspn(*lines, " \t");
86                 if (strstarts(*lines + preflen, "#include <ccan/")) {
87                         char *modname;
88
89                         modname = talloc_strdup(f, *lines + preflen
90                                                 + strlen("#include <ccan/"));
91                         modname[strcspn(modname, "/")] = '\0';
92                         if (!have_mod(deps, modname))
93                                 add_dep(&deps, modname);
94                 }
95         }
96
97         return deps;
98 }
99
100 static char *example_obj_list(const void *ctx, struct manifest **deps)
101 {
102         char *list = talloc_strdup(ctx, "");
103         unsigned int i;
104
105         for (i = 0; i < talloc_array_length(deps); i++) {
106                 if (deps[i]->compiled[COMPILE_NORMAL])
107                         list = talloc_asprintf_append(list, " %s",
108                                                       deps[i]->compiled
109                                                       [COMPILE_NORMAL]);
110         }
111         return list;
112 }
113
114 static char *example_lib_list(const void *ctx, struct manifest **deps)
115 {
116         char *list = talloc_strdup(ctx, "");
117         char **libs;
118         unsigned int i, j;
119
120         /* FIXME: This doesn't uniquify. */
121         for (i = 0; i < talloc_array_length(deps); i++) {
122                 libs = get_libs(ctx, deps[i]->dir, false, get_or_compile_info);
123                 for (j = 0; libs[j]; j++)
124                         list = talloc_asprintf_append(list, "-l%s ", libs[j]);
125         }
126         return list;
127 }
128
129 /* FIXME: Test with reduced features! */
130 static bool compile(const void *ctx,
131                     struct manifest *m,
132                     struct ccan_file *file,
133                     char **output)
134 {
135         struct manifest **deps = get_example_deps(m, file);
136
137         file->compiled[COMPILE_NORMAL] = temp_file(ctx, "", file->fullname);
138         if (!compile_and_link(ctx, file->fullname, ccan_dir,
139                               example_obj_list(file, deps),
140                               compiler, cflags,
141                               example_lib_list(file, deps),
142                               file->compiled[COMPILE_NORMAL],
143                               output)) {
144                 /* Don't keep failures, even with --keep */
145                 unlink(file->compiled[COMPILE_NORMAL]);
146                 file->compiled[COMPILE_NORMAL] = NULL;
147                 return false;
148         }
149         return true;
150 }
151
152 static char *start_main(char *ret, const char *why)
153 {
154         return talloc_asprintf_append(ret,
155               "/* The example %s, so fake function wrapper inserted */\n"
156               "int main(int argc, char *argv[])\n"
157               "{\n", why);
158 }
159
160 /* We only handle simple function definitions here. */
161 static char *add_func(char *others, const char *line)
162 {
163         const char *p, *end = strchr(line, '(') - 1;
164         while (cisspace(*end)) {
165                 end--;
166                 if (end == line)
167                         return others;
168         }
169
170         for (p = end; cisalnum(*p) || *p == '_'; p--) {
171                 if (p == line)
172                         return others;
173         }
174
175         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
176                                       (unsigned)(end - p), p+1);
177 }
178
179 static void strip_leading_whitespace(char **lines)
180 {
181         unsigned int i, min_span = -1U;
182
183         for (i = 0; lines[i]; i++) {
184                 unsigned int span = strspn(lines[i], " \t");
185                 /* All whitespace?  Ignore */
186                 if (!lines[i][span])
187                         continue;
188                 if (span < min_span)
189                         min_span = span;
190         }
191
192         for (i = 0; lines[i]; i++)
193                 if (strlen(lines[i]) >= min_span)
194                         lines[i] += min_span;
195 }
196
197 static bool looks_internal(char **lines, char **why)
198 {
199         unsigned int i;
200         bool last_ended = true; /* Did last line finish a statement? */
201
202         for (i = 0; lines[i]; i++) {
203                 /* Skip leading whitespace. */
204                 const char *line = lines[i] + strspn(lines[i], " \t");
205                 unsigned len = strspn(line, IDENT_CHARS);
206
207                 if (!line[0] || cisspace(line[0]) || strstarts(line, "//")
208                     || strstarts(line, "#line"))
209                         continue;
210
211                 assert(line[strlen(line)-1] != '\n');
212
213                 /* The winners. */
214                 if (strstarts(line, "if") && len == 2) {
215                         *why = cast_const(char *, "starts with if");
216                         return true;
217                 }
218                 if (strstarts(line, "for") && len == 3) {
219                         *why = cast_const(char *, "starts with for");
220                         return true;
221                 }
222                 if (strstarts(line, "while") && len == 5) {
223                         *why = cast_const(char *, "starts with while");
224                         return true;
225                 }
226                 if (strstarts(line, "do") && len == 2) {
227                         *why = cast_const(char *, "starts with do");
228                         return true;
229                 }
230
231                 /* The losers. */
232                 if (strstarts(line, "#include")) {
233                         *why = cast_const(char *, "starts with #include");
234                         return false;
235                 }
236
237                 if (last_ended && strchr(line, '(')) {
238                         if (strstarts(line, "static")) {
239                                 *why = cast_const(char *,
240                                                   "starts with static"
241                                                   " and contains (");
242                                 return false;
243                         }
244                         if (strends(line, ")")) {
245                                 *why = cast_const(char *,
246                                                   "contains ( and ends with )");
247                                 return false;
248                         }
249                 }
250
251                 /* Previously prepended. */
252                 if (strstr(line, "didn't seem to belong inside a function")) {
253                         *why = cast_const(char *, "Comment said so");
254                         return false;
255                 }
256
257                 /* Single identifier then operator == inside function. */
258                 if (last_ended && len
259                     && cispunct(line[len+strspn(line+len, " ")])) {
260                         *why = cast_const(char *, "starts with identifier"
261                                           " then punctuation");
262                         return true;
263                 }
264
265                 last_ended = (strends(line, "}")
266                               || strends(line, ";")
267                               || strends(line, "*/")
268                               || streq(line, "..."));
269         }
270
271         /* No idea... Say yes? */
272         *why = cast_const(char *, "gave no clues");
273         return true;
274 }
275
276 /* Examples will often build on prior ones.  Try combining them. */
277 static char **combine(const void *ctx, char **lines, char **prev)
278 {
279         unsigned int i, lines_total, prev_total, count;
280         char **ret;
281         const char *reasoning;
282         char *why = NULL;
283
284         if (!prev)
285                 return NULL;
286
287         /* If it looks internal, put prev at start. */
288         if (looks_internal(lines, &why)) {
289                 count = 0;
290                 reasoning = "seemed to belong inside a function";
291         } else {
292                 /* Try inserting in first elided position */
293                 for (count = 0; lines[count]; count++) {
294                         if (strcmp(lines[count], "...") == 0)
295                                 break;
296                 }
297                 if (!lines[count]) {
298                         /* Try at start anyway? */
299                         count = 0;
300                         reasoning = "didn't seem to belong inside"
301                                 " a function, so we prepended the previous"
302                                 " example";
303                 } else {
304                         reasoning = "didn't seem to belong inside"
305                                 " a function, so we put the previous example"
306                                 " at the first ...";
307
308                         count++;
309                 }
310         }
311
312         for (i = 0; lines[i]; i++);
313         lines_total = i;
314
315         for (i = 0; prev[i]; i++);
316         prev_total = i;
317
318         ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
319         ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */",
320                                  why, reasoning);
321         memcpy(ret+1, lines, count * sizeof(ret[0]));
322         memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
323         memcpy(ret+1 + count + prev_total, lines + count,
324                (lines_total - count + 1) * sizeof(ret[0]));
325         return ret;
326 }
327
328 /* Only handles very simple comments. */
329 static char *strip_comment(const void *ctx, const char *orig_line)
330 {
331         char *p, *ret = talloc_strdup(ctx, orig_line);
332
333         p = strstr(ret, "/*");
334         if (!p)
335                 p = strstr(ret, "//");
336         if (p)
337                 *p = '\0';
338         return ret;
339 }
340
341 static char *mangle(struct manifest *m, char **lines)
342 {
343         char *ret, *use_funcs = NULL, *why;
344         bool in_function = false, fake_function = false, has_main = false;
345         unsigned int i;
346
347         ret = talloc_asprintf(m, 
348                               "/* Include header from module. */\n"
349                               "#include <ccan/%s/%s.h>\n"
350                               "/* Prepend a heap of headers. */\n"
351                               "#include <assert.h>\n"
352                               "#include <err.h>\n"
353                               "#include <errno.h>\n"
354                               "#include <fcntl.h>\n"
355                               "#include <limits.h>\n"
356                               "#include <stdbool.h>\n"
357                               "#include <stdint.h>\n"
358                               "#include <stdio.h>\n"
359                               "#include <stdlib.h>\n"
360                               "#include <string.h>\n"
361                               "#include <sys/stat.h>\n"
362                               "#include <sys/types.h>\n"
363                               "#include <unistd.h>\n",
364                               m->basename, m->basename);
365
366         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
367                                      "extern int somefunc(void);\n"
368                                      "int somefunc(void) { return 0; }\n"
369                                      "extern char somestring[];\n"
370                                      "char somestring[] = \"hello world\";\n");
371
372         if (looks_internal(lines, &why)) {
373                 /* Wrap it all in main(). */
374                 ret = start_main(ret, why);
375                 fake_function = true;
376                 in_function = true;
377                 has_main = true;
378         } else
379                 ret = talloc_asprintf_append(ret,
380                              "/* The example %s, so didn't wrap in main() */\n",
381                                      why);
382
383         /* Primitive, very primitive. */
384         for (i = 0; lines[i]; i++) {
385                 char *line = strip_comment(ret, lines[i]);
386
387                 /* } at start of line ends a function. */
388                 if (in_function) {
389                         if (line[0] == '}')
390                                 in_function = false;
391                 } else {
392                         /* Character at start of line, with ( and no ;
393                          * == function start.  Ignore comments. */
394                         if (!cisspace(line[0])
395                             && strchr(line, '(')
396                             && !strchr(line, ';')
397                             && !strstr(line, "//")) {
398                                 in_function = true;
399                                 if (strncmp(line, "int main", 8) == 0)
400                                         has_main = true;
401                                 if (strncmp(line, "static", 6) == 0) {
402                                         use_funcs = add_func(use_funcs,
403                                                              line);
404                                 }
405                         }
406                 }
407                 /* ... means elided code. */
408                 if (strcmp(line, "...") == 0) {
409                         if (!in_function && !has_main
410                             && looks_internal(lines + i + 1, &why)) {
411                                 /* This implies we start a function here. */
412                                 ret = start_main(ret, why);
413                                 has_main = true;
414                                 fake_function = true;
415                                 in_function = true;
416                         }
417                         ret = talloc_asprintf_append(ret,
418                                                      "/* ... removed */\n");
419                         continue;
420                 }
421                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
422         }
423
424         if (!has_main) {
425                 ret = talloc_asprintf_append(ret,
426                              "/* Need a main to link successfully. */\n"
427                              "int main(void)\n{\n");
428                 fake_function = true;
429         }
430
431         if (use_funcs) {
432                 ret = talloc_asprintf_append(ret,
433                                              "/* Get rid of unused warnings"
434                                              " by printing addresses of"
435                                              " static funcs. */\n");
436                 if (!fake_function) {
437                         ret = talloc_asprintf_append(ret,
438                                                      "int use_funcs(void);\n"
439                                                      "int use_funcs(void) {\n");
440                         fake_function = true;
441                 }
442                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
443         }
444
445         if (fake_function)
446                 ret = talloc_asprintf_append(ret, "return 0;\n"
447                                              "}\n");
448         return ret;
449 }
450
451 static struct ccan_file *mangle_example(struct manifest *m,
452                                         struct ccan_file *example,
453                                         char **lines)
454 {
455         char *name, *contents;
456         int fd;
457         struct ccan_file *f;
458
459         name = temp_file(example, ".c",
460                          talloc_asprintf(m, "%s/mangled-%s",
461                                          m->dir, example->name));
462         f = new_ccan_file(example,
463                           talloc_dirname(example, name),
464                           talloc_basename(example, name));
465         talloc_steal(f, name);
466
467         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
468         if (fd < 0)
469                 return NULL;
470
471         contents = mangle(m, lines);
472         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
473                 close(fd);
474                 return NULL;
475         }
476         close(fd);
477         f->contents = talloc_steal(f, contents);
478         list_add(&m->mangled_examples, &f->list);
479         return f;
480 }
481
482 /* If an example has expected output, it's complete and should not be
483  * included in future examples. */
484 static bool has_expected_output(char **lines)
485 {
486         unsigned int i;
487
488         for (i = 0; lines[i]; i++) {
489                 char *p = lines[i] + strspn(lines[i], " \t");
490                 if (!strstarts(p, "//"))
491                         continue;
492                 p += strspn(p, "/ ");
493                 if (strncasecmp(p, "given", strlen("given")) == 0)
494                         return true;
495         }
496         return false;
497 }
498
499 static unsigned int try_compiling(struct manifest *m,
500                                   struct ccan_file *i,
501                                   char **prev,
502                                   struct ccan_file *mangled[3],
503                                   bool res[3],
504                                   char *err[3],
505                                   char **lines[3])
506 {
507         unsigned int num;
508
509         /* Try standalone. */
510         mangled[0] = i;
511         res[0] = compile(i, m, mangled[0], &err[0]);
512         lines[0] = get_ccan_file_lines(i);
513         if (res[0] && streq(err[0], ""))
514                 return 1;
515
516         if (prev) {
517                 lines[1] = combine(i, get_ccan_file_lines(i), prev);
518
519                 mangled[1] = mangle_example(m, i, lines[1]);
520                 res[1] = compile(i, m, mangled[1], &err[1]);
521                 if (res[1] && streq(err[1], "")) {
522                         return 2;
523                 }
524                 num = 2;
525         } else
526                 num = 1;
527
528         /* Try standalone. */
529         lines[num] = get_ccan_file_lines(i);
530         mangled[num] = mangle_example(m, i, lines[num]);
531         res[num] = compile(i, m, mangled[num], &err[num]);
532
533         return num+1;
534 }
535
536 static void build_examples(struct manifest *m,
537                            unsigned int *timeleft, struct score *score)
538 {
539         struct ccan_file *i;
540         char **prev = NULL;
541         bool warnings = false;
542
543         score->total = 0;
544         score->pass = true;
545
546         list_for_each(&m->examples, i, list) {
547                 char *err[3];
548                 struct ccan_file *file[3] = { NULL, NULL, NULL };
549                 bool res[3];
550                 unsigned num, j;
551                 char **lines[3];
552                 const char *error;
553
554                 score->total++;
555
556                 /* Simplify our dumb parsing. */
557                 strip_leading_whitespace(get_ccan_file_lines(i));
558
559                 num = try_compiling(m, i, prev, file, res, err, lines);
560
561                 /* First look for a compile without any warnings. */
562                 for (j = 0; j < num; j++) {
563                         if (res[j] && streq(err[j], "")) {
564                                 if (!has_expected_output(lines[j]))
565                                         prev = lines[j];
566                                 score->score++;
567                                 goto next;
568                         }
569                 }
570
571                 /* Now accept anything which succeeded. */
572                 for (j = 0; j < num; j++) {
573                         if (res[j]) {
574                                 if (!has_expected_output(lines[j]))
575                                         prev = lines[j];
576                                 score->score++;
577                                 warnings = true;
578                                 score_file_error(score, file[j], 0,
579                                                  "Compiling extracted example"
580                                                  " gave warnings:\n"
581                                                  "Example:\n"
582                                                  "%s\n"
583                                                  "Compiler:\n"
584                                                  "%s",
585                                                  get_ccan_file_contents(file[j]),
586                                                  err[j]);
587                                 goto next;
588                         }
589                 }
590
591                 score->pass = false;
592                 if (!verbose) {
593                         if (num == 3)
594                                 error = "Compiling standalone, adding headers, "
595                                         "and including previous "
596                                         "example all failed";
597                         else
598                                 error = "Standalone compile and"
599                                         " adding headers both failed";
600                 } else {
601                         if (num == 3) {
602                                 error = talloc_asprintf(score,
603                                       "Standalone example:\n"
604                                       "%s\n"
605                                       "Errors: %s\n\n"
606                                       "Combining with previous example:\n"
607                                       "%s\n"
608                                       "Errors: %s\n\n"
609                                       "Adding headers, wrappers:\n"
610                                       "%s\n"
611                                       "Errors: %s\n\n",
612                                       get_ccan_file_contents(file[0]),
613                                       err[0],
614                                       get_ccan_file_contents(file[1]),
615                                       err[1],
616                                       get_ccan_file_contents(file[2]),
617                                       err[2]);
618                         } else {
619                                 error = talloc_asprintf(score,
620                                       "Standalone example:\n"
621                                       "%s\n"
622                                       "Errors: %s\n\n"
623                                       "Adding headers, wrappers:\n"
624                                       "%s\n"
625                                       "Errors: %s\n\n",
626                                       get_ccan_file_contents(file[0]),
627                                       err[0],
628                                       get_ccan_file_contents(file[1]),
629                                       err[1]);
630                         }
631                 }
632                 score_file_error(score, i, 0, "%s", error);
633                 /* This didn't work, so not a candidate for combining. */
634                 prev = NULL;
635
636         next:
637                 ;
638         }
639
640         /* An extra point if they all compiled without warnings. */
641         if (!list_empty(&m->examples)) {
642                 score->total++;
643                 if (!warnings)
644                         score->score++;
645         }
646 }
647
648 struct ccanlint examples_compile = {
649         .key = "examples_compile",
650         .name = "Module examples compile",
651         .check = build_examples,
652         .can_run = can_run,
653         .needs = "examples_exist module_builds"
654 };
655
656 REGISTER_TEST(examples_compile);