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 /* FIXME: Test with reduced features! */
130 static bool compile(const void *ctx,
132 struct ccan_file *file,
135 struct manifest **deps = get_example_deps(m, file);
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),
141 example_lib_list(file, deps),
142 file->compiled[COMPILE_NORMAL],
144 /* Don't keep failures, even with --keep */
145 unlink(file->compiled[COMPILE_NORMAL]);
146 file->compiled[COMPILE_NORMAL] = NULL;
152 static void start_main(char **ret, const char *why)
155 "/* The example %s, so fake function wrapper inserted */\n"
156 "int main(int argc, char *argv[])\n"
160 /* We only handle simple function definitions here. */
161 static char *add_func(const tal_t *ctx, char *others, const char *line)
163 const char *p, *end = strchr(line, '(') - 1;
166 while (cisspace(*end)) {
172 for (p = end; cisalnum(*p) || *p == '_'; p--) {
177 use = tal_fmt(ctx, "printf(\"%%p\", %.*s);\n",
178 (unsigned)(end - p), p+1);
180 use = tal_strcat(ctx, take(others), take(use));
185 static void strip_leading_whitespace(char **lines)
187 unsigned int i, min_span = -1U;
189 for (i = 0; lines[i]; i++) {
190 unsigned int span = strspn(lines[i], " \t");
191 /* All whitespace? Ignore */
198 for (i = 0; lines[i]; i++)
199 if (strlen(lines[i]) >= min_span)
200 lines[i] += min_span;
203 static bool looks_internal(char **lines, char **why)
206 bool last_ended = true; /* Did last line finish a statement? */
208 for (i = 0; lines[i]; i++) {
209 /* Skip leading whitespace. */
210 const char *line = lines[i] + strspn(lines[i], " \t");
211 unsigned len = strspn(line, IDENT_CHARS);
213 if (!line[0] || cisspace(line[0]) || strstarts(line, "//")
214 || strstarts(line, "#line"))
217 assert(line[strlen(line)-1] != '\n');
220 if (strstarts(line, "if") && len == 2) {
221 *why = cast_const(char *, "starts with if");
224 if (strstarts(line, "for") && len == 3) {
225 *why = cast_const(char *, "starts with for");
228 if (strstarts(line, "while") && len == 5) {
229 *why = cast_const(char *, "starts with while");
232 if (strstarts(line, "do") && len == 2) {
233 *why = cast_const(char *, "starts with do");
238 if (strstarts(line, "#include")) {
239 *why = cast_const(char *, "starts with #include");
243 if (last_ended && strchr(line, '(')) {
244 if (strstarts(line, "static")) {
245 *why = cast_const(char *,
250 if (strends(line, ")")) {
251 *why = cast_const(char *,
252 "contains ( and ends with )");
257 /* Previously prepended. */
258 if (strstr(line, "didn't seem to belong inside a function")) {
259 *why = cast_const(char *, "Comment said so");
263 /* Single identifier then operator == inside function. */
264 if (last_ended && len
265 && cispunct(line[len+strspn(line+len, " ")])) {
266 *why = cast_const(char *, "starts with identifier"
267 " then punctuation");
271 last_ended = (strends(line, "}")
272 || strends(line, ";")
273 || strends(line, "*/")
274 || streq(line, "..."));
277 /* No idea... Say yes? */
278 *why = cast_const(char *, "gave no clues");
282 /* Examples will often build on prior ones. Try combining them. */
283 static char **combine(const void *ctx, char **lines, char **prev)
285 unsigned int i, lines_total, prev_total, count;
287 const char *reasoning;
293 /* If it looks internal, put prev at start. */
294 if (looks_internal(lines, &why)) {
296 reasoning = "seemed to belong inside a function";
298 /* Try inserting in first elided position */
299 for (count = 0; lines[count]; count++) {
300 if (strcmp(lines[count], "...") == 0)
304 /* Try at start anyway? */
306 reasoning = "didn't seem to belong inside"
307 " a function, so we prepended the previous"
310 reasoning = "didn't seem to belong inside"
311 " a function, so we put the previous example"
318 for (i = 0; lines[i]; i++);
321 for (i = 0; prev[i]; i++);
324 ret = tal_arr(ctx, char *, 1 + lines_total + prev_total + 1);
325 ret[0] = tal_fmt(ret, "/* The example %s, thus %s */",
327 memcpy(ret+1, lines, count * sizeof(ret[0]));
328 memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
329 memcpy(ret+1 + count + prev_total, lines + count,
330 (lines_total - count + 1) * sizeof(ret[0]));
334 /* Only handles very simple comments. */
335 static char *strip_comment(const void *ctx, const char *orig_line)
337 char *p, *ret = tal_strdup(ctx, orig_line);
339 p = strstr(ret, "/*");
341 p = strstr(ret, "//");
347 static char *mangle(struct manifest *m, char **lines)
349 char *ret, *use_funcs = NULL, *why;
350 bool in_function = false, fake_function = false, has_main = false;
354 "/* Include header from module. */\n"
355 "#include <ccan/%s/%s.h>\n"
356 "/* Prepend a heap of headers. */\n"
357 "#include <assert.h>\n"
359 "#include <errno.h>\n"
360 "#include <fcntl.h>\n"
361 "#include <limits.h>\n"
362 "#include <stdbool.h>\n"
363 "#include <stdint.h>\n"
364 "#include <stdio.h>\n"
365 "#include <stdlib.h>\n"
366 "#include <string.h>\n"
367 "#include <sys/stat.h>\n"
368 "#include <sys/types.h>\n"
369 "#include <unistd.h>\n",
370 m->modname, m->basename);
372 ret = tal_strcat(m, take(ret), "/* Useful dummy functions. */\n"
373 "extern int somefunc(void);\n"
374 "int somefunc(void) { return 0; }\n"
375 "extern char somestring[];\n"
376 "char somestring[] = \"hello world\";\n");
378 if (looks_internal(lines, &why)) {
379 /* Wrap it all in main(). */
380 start_main(&ret, why);
381 fake_function = true;
386 "/* The example %s, so didn't wrap in main() */\n",
389 /* Primitive, very primitive. */
390 for (i = 0; lines[i]; i++) {
391 char *line = strip_comment(ret, lines[i]);
393 /* } at start of line ends a function. */
398 /* Character at start of line, with ( and no ;
399 * == function start. Ignore comments. */
400 if (!cisspace(line[0])
402 && !strchr(line, ';')
403 && !strstr(line, "//")) {
405 if (strncmp(line, "int main", 8) == 0)
407 if (strncmp(line, "static", 6) == 0) {
408 use_funcs = add_func(m, use_funcs,
413 /* ... means elided code. */
414 if (strcmp(line, "...") == 0) {
415 if (!in_function && !has_main
416 && looks_internal(lines + i + 1, &why)) {
417 /* This implies we start a function here. */
418 start_main(&ret, why);
420 fake_function = true;
423 ret = tal_strcat(m, take(ret), "/* ... removed */\n");
426 ret = tal_strcat(m, take(ret), lines[i]);
427 ret = tal_strcat(m, take(ret), "\n");
431 ret = tal_strcat(m, take(ret),
432 "/* Need a main to link successfully. */\n"
433 "int main(void)\n{\n");
434 fake_function = true;
438 ret = tal_strcat(m, take(ret),
439 "/* Get rid of unused warnings"
440 " by printing addresses of"
441 " static funcs. */\n");
442 if (!fake_function) {
443 ret = tal_strcat(m, take(ret),
444 "int use_funcs(void);\n"
445 "int use_funcs(void) {\n");
446 fake_function = true;
448 tal_append_fmt(&ret, " %s\n", use_funcs);
452 ret = tal_strcat(m, take(ret), "return 0;\n}\n");
456 static struct ccan_file *mangle_example(struct manifest *m,
457 struct ccan_file *example,
460 char *name, *contents;
464 name = temp_file(example, ".c",
465 take(tal_fmt(NULL, "mangled-%s", example->name)));
466 f = new_ccan_file(example,
467 take(path_dirname(example, name)),
468 take(path_basename(example, name)));
471 fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
475 contents = mangle(m, lines);
476 if (write(fd, contents, strlen(contents)) != strlen(contents)) {
481 f->contents = tal_steal(f, contents);
482 list_add(&m->mangled_examples, &f->list);
486 /* If an example has expected output, it's complete and should not be
487 * included in future examples. */
488 static bool has_expected_output(char **lines)
492 for (i = 0; lines[i]; i++) {
493 char *p = lines[i] + strspn(lines[i], " \t");
494 if (!strstarts(p, "//"))
496 p += strspn(p, "/ ");
497 if (strncasecmp(p, "given", strlen("given")) == 0)
503 static unsigned int try_compiling(struct manifest *m,
506 struct ccan_file *mangled[3],
513 /* Try standalone. */
515 res[0] = compile(i, m, mangled[0], &err[0]);
516 lines[0] = get_ccan_file_lines(i);
517 if (res[0] && streq(err[0], ""))
521 lines[1] = combine(i, get_ccan_file_lines(i), prev);
523 mangled[1] = mangle_example(m, i, lines[1]);
524 res[1] = compile(i, m, mangled[1], &err[1]);
525 if (res[1] && streq(err[1], "")) {
532 /* Try standalone. */
533 lines[num] = get_ccan_file_lines(i);
534 mangled[num] = mangle_example(m, i, lines[num]);
535 res[num] = compile(i, m, mangled[num], &err[num]);
540 static void build_examples(struct manifest *m,
541 unsigned int *timeleft, struct score *score)
545 bool warnings = false;
550 list_for_each(&m->examples, i, list) {
552 struct ccan_file *file[3] = { NULL, NULL, NULL };
560 /* Simplify our dumb parsing. */
561 strip_leading_whitespace(get_ccan_file_lines(i));
563 num = try_compiling(m, i, prev, file, res, err, lines);
565 /* First look for a compile without any warnings. */
566 for (j = 0; j < num; j++) {
567 if (res[j] && streq(err[j], "")) {
568 if (!has_expected_output(lines[j]))
575 /* Now accept anything which succeeded. */
576 for (j = 0; j < num; j++) {
578 if (!has_expected_output(lines[j]))
582 score_file_error(score, file[j], 0,
583 "Compiling extracted example"
589 get_ccan_file_contents(file[j]),
598 error = "Compiling standalone, adding headers, "
599 "and including previous "
600 "example all failed";
602 error = "Standalone compile and"
603 " adding headers both failed";
606 error = tal_fmt(score,
607 "Standalone example:\n"
610 "Combining with previous example:\n"
613 "Adding headers, wrappers:\n"
616 get_ccan_file_contents(file[0]),
618 get_ccan_file_contents(file[1]),
620 get_ccan_file_contents(file[2]),
623 error = tal_fmt(score,
624 "Standalone example:\n"
627 "Adding headers, wrappers:\n"
630 get_ccan_file_contents(file[0]),
632 get_ccan_file_contents(file[1]),
636 score_file_error(score, i, 0, "%s", error);
637 /* This didn't work, so not a candidate for combining. */
644 /* An extra point if they all compiled without warnings. */
645 if (!list_empty(&m->examples)) {
652 struct ccanlint examples_compile = {
653 .key = "examples_compile",
654 .name = "Module examples compile",
655 .check = build_examples,
657 .needs = "examples_exist module_builds"
660 REGISTER_TEST(examples_compile);