1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/tal/tal.h>
4 #include <ccan/tal/str/str.h>
5 #include <ccan/take/take.h>
6 #include <ccan/cast/cast.h>
7 #include <ccan/tal/path/path.h>
8 #include <ccan/str/str.h>
20 static const char *can_run(struct manifest *m)
23 return "Safe mode enabled";
24 if (list_empty(&m->examples))
25 return "No examples to compile";
29 static void add_mod(struct manifest ***deps, struct manifest *m)
31 unsigned int num = tal_count(*deps);
32 tal_resize(deps, num + 1);
36 static bool have_mod(struct manifest *deps[], const char *modname)
40 for (i = 0; i < tal_count(deps); i++)
41 if (strcmp(deps[i]->modname, modname) == 0)
46 static void add_dep(struct manifest ***deps, const char *modname)
52 if (have_mod(*deps, modname))
55 m = get_manifest(*deps,
56 tal_fmt(*deps, "%s/ccan/%s", ccan_dir, modname));
57 errstr = build_submodule(m, cflags, COMPILE_NORMAL);
59 errx(1, "%s", errstr);
63 /* Get that modules depends as well... */
68 infodeps = get_deps(m, m->dir, "depends", false,
71 for (i = 0; infodeps[i]; i++) {
72 if (strstarts(infodeps[i], "ccan/"))
73 add_dep(deps, infodeps[i] + strlen("ccan/"));
78 static struct manifest **get_example_deps(struct manifest *m,
82 struct manifest **deps = tal_arr(f, struct manifest *, 0);
84 /* This one for a start. */
85 add_dep(&deps, m->modname);
87 /* Other modules implied by includes. */
88 for (lines = get_ccan_file_lines(f); *lines; lines++) {
90 if (tal_strreg(f, *lines,
91 "^[ \t]*#[ \t]*include[ \t]*[<\"]"
92 "ccan/+(.+)/+[^/]+\\.h", &modname)) {
93 if (!have_mod(deps, modname))
94 add_dep(&deps, modname);
101 static char *example_obj_list(const void *ctx, struct manifest **deps)
103 char *list = tal_strdup(ctx, "");
106 for (i = 0; i < tal_count(deps); i++) {
107 if (deps[i]->compiled[COMPILE_NORMAL])
108 tal_append_fmt(&list, " %s",
109 deps[i]->compiled[COMPILE_NORMAL]);
114 static char *example_lib_list(const void *ctx, struct manifest **deps)
116 char *list = tal_strdup(ctx, "");
120 /* FIXME: This doesn't uniquify. */
121 for (i = 0; i < tal_count(deps); i++) {
122 libs = get_libs(ctx, deps[i]->dir, NULL, get_or_compile_info);
123 for (j = 0; libs[j]; j++)
124 tal_append_fmt(&list, "-l%s ", libs[j]);
129 static char *cflags_list(const struct manifest *m)
132 char *ret = tal_strdup(m, cflags);
134 char **flags = get_cflags(m, m->dir, get_or_compile_info);
135 for (i = 0; flags[i]; i++)
136 tal_append_fmt(&ret, " %s", flags[i]);
140 /* FIXME: Test with reduced features! */
141 static bool compile(const void *ctx,
143 struct ccan_file *file,
146 struct manifest **deps = get_example_deps(m, file);
147 const char *flags = cflags_list(m);
149 file->compiled[COMPILE_NORMAL] = temp_file(ctx, "", file->fullname);
150 if (!compile_and_link(ctx, file->fullname, ccan_dir,
151 example_obj_list(file, deps),
153 example_lib_list(file, deps),
154 file->compiled[COMPILE_NORMAL],
156 /* Don't keep failures, even with --keep */
157 unlink(file->compiled[COMPILE_NORMAL]);
158 file->compiled[COMPILE_NORMAL] = NULL;
164 static void start_main(char **ret, const char *why)
167 "/* The example %s, so fake function wrapper inserted */\n"
168 "int main(int argc, char *argv[])\n"
172 /* We only handle simple function definitions here. */
173 static char *add_func(const tal_t *ctx, char *others, const char *line)
175 const char *p, *end = strchr(line, '(') - 1;
178 while (cisspace(*end)) {
184 for (p = end; cisalnum(*p) || *p == '_'; p--) {
189 use = tal_fmt(ctx, "printf(\"%%p\", %.*s);\n",
190 (unsigned)(end - p), p+1);
192 use = tal_strcat(ctx, take(others), take(use));
197 static void strip_leading_whitespace(char **lines)
199 unsigned int i, min_span = -1U;
201 for (i = 0; lines[i]; i++) {
202 unsigned int span = strspn(lines[i], " \t");
203 /* All whitespace? Ignore */
210 for (i = 0; lines[i]; i++)
211 if (strlen(lines[i]) >= min_span)
212 lines[i] += min_span;
215 static bool looks_internal(char **lines, char **why)
218 bool last_ended = true; /* Did last line finish a statement? */
220 for (i = 0; lines[i]; i++) {
221 /* Skip leading whitespace. */
222 const char *line = lines[i] + strspn(lines[i], " \t");
223 unsigned len = strspn(line, IDENT_CHARS);
225 if (!line[0] || cisspace(line[0]) || strstarts(line, "//")
226 || strstarts(line, "#line"))
229 assert(line[strlen(line)-1] != '\n');
232 if (strstarts(line, "if") && len == 2) {
233 *why = cast_const(char *, "starts with if");
236 if (strstarts(line, "for") && len == 3) {
237 *why = cast_const(char *, "starts with for");
240 if (strstarts(line, "while") && len == 5) {
241 *why = cast_const(char *, "starts with while");
244 if (strstarts(line, "do") && len == 2) {
245 *why = cast_const(char *, "starts with do");
250 if (strstarts(line, "#include")) {
251 *why = cast_const(char *, "starts with #include");
255 if (last_ended && strchr(line, '(')) {
256 if (strstarts(line, "static")) {
257 *why = cast_const(char *,
262 if (strends(line, ")")) {
263 *why = cast_const(char *,
264 "contains ( and ends with )");
269 /* Previously prepended. */
270 if (strstr(line, "didn't seem to belong inside a function")) {
271 *why = cast_const(char *, "Comment said so");
275 /* Single identifier then operator == inside function. */
276 if (last_ended && len
277 && cispunct(line[len+strspn(line+len, " ")])) {
278 *why = cast_const(char *, "starts with identifier"
279 " then punctuation");
283 last_ended = (strends(line, "}")
284 || strends(line, ";")
285 || strends(line, "*/")
286 || streq(line, "..."));
289 /* No idea... Say yes? */
290 *why = cast_const(char *, "gave no clues");
294 /* Examples will often build on prior ones. Try combining them. */
295 static char **combine(const void *ctx, char **lines, char **prev)
297 unsigned int i, lines_total, prev_total, count;
299 const char *reasoning;
305 /* If it looks internal, put prev at start. */
306 if (looks_internal(lines, &why)) {
308 reasoning = "seemed to belong inside a function";
310 /* Try inserting in first elided position */
311 for (count = 0; lines[count]; count++) {
312 if (strcmp(lines[count], "...") == 0)
316 /* Try at start anyway? */
318 reasoning = "didn't seem to belong inside"
319 " a function, so we prepended the previous"
322 reasoning = "didn't seem to belong inside"
323 " a function, so we put the previous example"
330 for (i = 0; lines[i]; i++);
333 for (i = 0; prev[i]; i++);
336 ret = tal_arr(ctx, char *, 1 + lines_total + prev_total + 1);
337 ret[0] = tal_fmt(ret, "/* The example %s, thus %s */",
339 memcpy(ret+1, lines, count * sizeof(ret[0]));
340 memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
341 memcpy(ret+1 + count + prev_total, lines + count,
342 (lines_total - count + 1) * sizeof(ret[0]));
346 /* Only handles very simple comments. */
347 static char *strip_comment(const void *ctx, const char *orig_line)
349 char *p, *ret = tal_strdup(ctx, orig_line);
351 p = strstr(ret, "/*");
353 p = strstr(ret, "//");
359 static char *mangle(struct manifest *m, char **lines)
361 char *ret, *use_funcs = NULL, *why;
362 bool in_function = false, fake_function = false, has_main = false,
367 "/* Include header from module. */\n"
368 "#include <ccan/%s/%s.h>\n"
369 "/* Prepend a heap of headers. */\n"
370 "#include <assert.h>\n"
372 "#include <errno.h>\n"
373 "#include <fcntl.h>\n"
374 "#include <limits.h>\n"
375 "#include <stdbool.h>\n"
376 "#include <stdint.h>\n"
377 "#include <stdio.h>\n"
378 "#include <stdlib.h>\n"
379 "#include <string.h>\n"
380 "#include <sys/stat.h>\n"
381 "#include <sys/types.h>\n"
382 "#include <unistd.h>\n",
383 m->modname, m->basename);
385 ret = tal_strcat(m, take(ret), "/* Useful dummy functions. */\n"
386 "extern int somefunc(void);\n"
387 "int somefunc(void) { return 0; }\n"
388 "extern char somestring[];\n"
389 "char somestring[] = \"hello world\";\n");
391 if (looks_internal(lines, &why)) {
392 /* Wrap it all in main(). */
393 start_main(&ret, why);
394 fake_function = true;
400 "/* The example %s, so didn't wrap in main() */\n",
403 /* Primitive, very primitive. */
404 for (i = 0; lines[i]; i++) {
405 char *line = strip_comment(ret, lines[i]);
407 /* } at start of line ends a function. */
412 /* Character at start of line, with ( and no ;
413 * == function start. Ignore comments. */
414 if (!cisspace(line[0])
416 && !strchr(line, ';')
417 && !strstr(line, "//")) {
419 if (strncmp(line, "int main", 8) == 0)
421 if (strncmp(line, "static", 6) == 0) {
422 use_funcs = add_func(m, use_funcs,
427 /* ... means elided code. */
428 if (strcmp(line, "...") == 0) {
429 if (!in_function && !has_main
430 && looks_internal(lines + i + 1, &why)) {
431 /* This implies we start a function here. */
432 start_main(&ret, why);
435 fake_function = true;
438 ret = tal_strcat(m, take(ret), "/* ... removed */\n");
441 ret = tal_strcat(m, take(ret), lines[i]);
442 ret = tal_strcat(m, take(ret), "\n");
446 ret = tal_strcat(m, take(ret),
447 "/* Need a main to link successfully. */\n"
448 "int main(int argc, char *argv[])\n{\n");
449 fake_function = true;
454 ret = tal_strcat(m, take(ret),
455 "/* Get rid of unused warnings"
456 " by printing addresses of"
457 " static funcs. */\n");
458 if (!fake_function) {
459 ret = tal_strcat(m, take(ret),
460 "int use_funcs(void);\n"
461 "int use_funcs(void) {\n");
462 fake_function = true;
464 tal_append_fmt(&ret, " %s\n", use_funcs);
468 ret = tal_strcat(m, take(ret),
469 "(void)argc; (void)argv;\n");
472 ret = tal_strcat(m, take(ret),
477 static struct ccan_file *mangle_example(struct manifest *m,
478 struct ccan_file *example,
481 char *name, *contents;
485 name = temp_file(example, ".c",
486 take(tal_fmt(NULL, "mangled-%s", example->name)));
487 f = new_ccan_file(example,
488 take(path_dirname(example, name)),
489 take(path_basename(example, name)));
492 fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
496 contents = mangle(m, lines);
497 if (write(fd, contents, strlen(contents)) != (int)strlen(contents)) {
502 f->contents = tal_steal(f, contents);
503 list_add(&m->mangled_examples, &f->list);
507 /* If an example has expected output, it's complete and should not be
508 * included in future examples. */
509 static bool has_expected_output(char **lines)
513 for (i = 0; lines[i]; i++) {
514 char *p = lines[i] + strspn(lines[i], " \t");
515 if (!strstarts(p, "//"))
517 p += strspn(p, "/ ");
518 if (strncasecmp(p, "given", strlen("given")) == 0)
524 static unsigned int try_compiling(struct manifest *m,
527 struct ccan_file *mangled[3],
534 /* Try standalone. */
536 res[0] = compile(i, m, mangled[0], &err[0]);
537 lines[0] = get_ccan_file_lines(i);
538 if (res[0] && streq(err[0], ""))
542 lines[1] = combine(i, get_ccan_file_lines(i), prev);
544 mangled[1] = mangle_example(m, i, lines[1]);
545 res[1] = compile(i, m, mangled[1], &err[1]);
546 if (res[1] && streq(err[1], "")) {
553 /* Try standalone. */
554 lines[num] = get_ccan_file_lines(i);
555 mangled[num] = mangle_example(m, i, lines[num]);
556 res[num] = compile(i, m, mangled[num], &err[num]);
561 static void build_examples(struct manifest *m,
562 unsigned int *timeleft UNNEEDED, struct score *score)
566 bool warnings = false;
571 list_for_each(&m->examples, i, list) {
573 struct ccan_file *file[3] = { NULL, NULL, NULL };
581 /* Simplify our dumb parsing. */
582 strip_leading_whitespace(get_ccan_file_lines(i));
584 num = try_compiling(m, i, prev, file, res, err, lines);
586 /* First look for a compile without any warnings. */
587 for (j = 0; j < num; j++) {
588 if (res[j] && streq(err[j], "")) {
589 if (!has_expected_output(lines[j]))
596 /* Now accept anything which succeeded. */
597 for (j = 0; j < num; j++) {
599 if (!has_expected_output(lines[j]))
603 score_file_error(score, file[j], 0,
604 "Compiling extracted example"
610 get_ccan_file_contents(file[j]),
619 error = "Compiling standalone, adding headers, "
620 "and including previous "
621 "example all failed";
623 error = "Standalone compile and"
624 " adding headers both failed";
627 error = tal_fmt(score,
628 "Standalone example:\n"
631 "Combining with previous example:\n"
634 "Adding headers, wrappers:\n"
637 get_ccan_file_contents(file[0]),
639 get_ccan_file_contents(file[1]),
641 get_ccan_file_contents(file[2]),
644 error = tal_fmt(score,
645 "Standalone example:\n"
648 "Adding headers, wrappers:\n"
651 get_ccan_file_contents(file[0]),
653 get_ccan_file_contents(file[1]),
657 score_file_error(score, i, 0, "%s", error);
658 /* This didn't work, so not a candidate for combining. */
665 /* An extra point if they all compiled without warnings. */
666 if (!list_empty(&m->examples)) {
673 struct ccanlint examples_compile = {
674 .key = "examples_compile",
675 .name = "Module examples compile",
676 .check = build_examples,
678 .needs = "examples_exist module_builds"
681 REGISTER_TEST(examples_compile);