1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/str_talloc/str_talloc.h>
5 #include <ccan/cast/cast.h>
6 #include <ccan/str/str.h>
18 static const char *can_run(struct manifest *m)
21 return "Safe mode enabled";
22 if (list_empty(&m->examples))
23 return "No examples to compile";
27 static void add_mod(struct manifest ***deps, struct manifest *m)
29 unsigned int num = talloc_get_size(*deps) / sizeof(*deps);
30 *deps = talloc_realloc(NULL, *deps, struct manifest *, num + 1);
34 static bool have_mod(struct manifest *deps[], const char *modname)
38 for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++)
39 if (strcmp(deps[i]->modname, modname) == 0)
44 static void add_dep(struct manifest ***deps, const char *modname)
50 if (have_mod(*deps, modname))
53 m = get_manifest(*deps, talloc_asprintf(*deps, "%s/ccan/%s",
55 errstr = build_submodule(m, cflags, COMPILE_NORMAL);
57 errx(1, "%s", errstr);
61 /* Get that modules depends as well... */
66 infodeps = get_deps(m, m->dir, "depends", false,
69 for (i = 0; infodeps[i]; i++) {
70 if (strstarts(infodeps[i], "ccan/"))
71 add_dep(deps, infodeps[i] + strlen("ccan/"));
76 static struct manifest **get_example_deps(struct manifest *m,
80 struct manifest **deps = talloc_array(f, struct manifest *, 0);
82 /* This one for a start. */
83 add_dep(&deps, m->modname);
85 /* Other modules implied by includes. */
86 for (lines = get_ccan_file_lines(f); *lines; lines++) {
89 "^[ \t]*#[ \t]*include[ \t]*[<\"]"
90 "ccan/+(.+)/+[^/]+\\.h", &modname)) {
91 if (!have_mod(deps, modname))
92 add_dep(&deps, modname);
99 static char *example_obj_list(const void *ctx, struct manifest **deps)
101 char *list = talloc_strdup(ctx, "");
104 for (i = 0; i < talloc_array_length(deps); i++) {
105 if (deps[i]->compiled[COMPILE_NORMAL])
106 list = talloc_asprintf_append(list, " %s",
113 static char *example_lib_list(const void *ctx, struct manifest **deps)
115 char *list = talloc_strdup(ctx, "");
119 /* FIXME: This doesn't uniquify. */
120 for (i = 0; i < talloc_array_length(deps); i++) {
121 libs = get_libs(ctx, deps[i]->dir, NULL, get_or_compile_info);
122 for (j = 0; libs[j]; j++)
123 list = talloc_asprintf_append(list, "-l%s ", libs[j]);
128 /* FIXME: Test with reduced features! */
129 static bool compile(const void *ctx,
131 struct ccan_file *file,
134 struct manifest **deps = get_example_deps(m, file);
136 file->compiled[COMPILE_NORMAL] = temp_file(ctx, "", file->fullname);
137 if (!compile_and_link(ctx, file->fullname, ccan_dir,
138 example_obj_list(file, deps),
140 example_lib_list(file, deps),
141 file->compiled[COMPILE_NORMAL],
143 /* Don't keep failures, even with --keep */
144 unlink(file->compiled[COMPILE_NORMAL]);
145 file->compiled[COMPILE_NORMAL] = NULL;
151 static char *start_main(char *ret, const char *why)
153 return talloc_asprintf_append(ret,
154 "/* The example %s, so fake function wrapper inserted */\n"
155 "int main(int argc, char *argv[])\n"
159 /* We only handle simple function definitions here. */
160 static char *add_func(char *others, const char *line)
162 const char *p, *end = strchr(line, '(') - 1;
163 while (cisspace(*end)) {
169 for (p = end; cisalnum(*p) || *p == '_'; p--) {
174 return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
175 (unsigned)(end - p), p+1);
178 static void strip_leading_whitespace(char **lines)
180 unsigned int i, min_span = -1U;
182 for (i = 0; lines[i]; i++) {
183 unsigned int span = strspn(lines[i], " \t");
184 /* All whitespace? Ignore */
191 for (i = 0; lines[i]; i++)
192 if (strlen(lines[i]) >= min_span)
193 lines[i] += min_span;
196 static bool looks_internal(char **lines, char **why)
199 bool last_ended = true; /* Did last line finish a statement? */
201 for (i = 0; lines[i]; i++) {
202 /* Skip leading whitespace. */
203 const char *line = lines[i] + strspn(lines[i], " \t");
204 unsigned len = strspn(line, IDENT_CHARS);
206 if (!line[0] || cisspace(line[0]) || strstarts(line, "//")
207 || strstarts(line, "#line"))
210 assert(line[strlen(line)-1] != '\n');
213 if (strstarts(line, "if") && len == 2) {
214 *why = cast_const(char *, "starts with if");
217 if (strstarts(line, "for") && len == 3) {
218 *why = cast_const(char *, "starts with for");
221 if (strstarts(line, "while") && len == 5) {
222 *why = cast_const(char *, "starts with while");
225 if (strstarts(line, "do") && len == 2) {
226 *why = cast_const(char *, "starts with do");
231 if (strstarts(line, "#include")) {
232 *why = cast_const(char *, "starts with #include");
236 if (last_ended && strchr(line, '(')) {
237 if (strstarts(line, "static")) {
238 *why = cast_const(char *,
243 if (strends(line, ")")) {
244 *why = cast_const(char *,
245 "contains ( and ends with )");
250 /* Previously prepended. */
251 if (strstr(line, "didn't seem to belong inside a function")) {
252 *why = cast_const(char *, "Comment said so");
256 /* Single identifier then operator == inside function. */
257 if (last_ended && len
258 && cispunct(line[len+strspn(line+len, " ")])) {
259 *why = cast_const(char *, "starts with identifier"
260 " then punctuation");
264 last_ended = (strends(line, "}")
265 || strends(line, ";")
266 || strends(line, "*/")
267 || streq(line, "..."));
270 /* No idea... Say yes? */
271 *why = cast_const(char *, "gave no clues");
275 /* Examples will often build on prior ones. Try combining them. */
276 static char **combine(const void *ctx, char **lines, char **prev)
278 unsigned int i, lines_total, prev_total, count;
280 const char *reasoning;
286 /* If it looks internal, put prev at start. */
287 if (looks_internal(lines, &why)) {
289 reasoning = "seemed to belong inside a function";
291 /* Try inserting in first elided position */
292 for (count = 0; lines[count]; count++) {
293 if (strcmp(lines[count], "...") == 0)
297 /* Try at start anyway? */
299 reasoning = "didn't seem to belong inside"
300 " a function, so we prepended the previous"
303 reasoning = "didn't seem to belong inside"
304 " a function, so we put the previous example"
311 for (i = 0; lines[i]; i++);
314 for (i = 0; prev[i]; i++);
317 ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
318 ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */",
320 memcpy(ret+1, lines, count * sizeof(ret[0]));
321 memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
322 memcpy(ret+1 + count + prev_total, lines + count,
323 (lines_total - count + 1) * sizeof(ret[0]));
327 /* Only handles very simple comments. */
328 static char *strip_comment(const void *ctx, const char *orig_line)
330 char *p, *ret = talloc_strdup(ctx, orig_line);
332 p = strstr(ret, "/*");
334 p = strstr(ret, "//");
340 static char *mangle(struct manifest *m, char **lines)
342 char *ret, *use_funcs = NULL, *why;
343 bool in_function = false, fake_function = false, has_main = false;
346 ret = talloc_asprintf(m,
347 "/* Include header from module. */\n"
348 "#include <ccan/%s/%s.h>\n"
349 "/* Prepend a heap of headers. */\n"
350 "#include <assert.h>\n"
352 "#include <errno.h>\n"
353 "#include <fcntl.h>\n"
354 "#include <limits.h>\n"
355 "#include <stdbool.h>\n"
356 "#include <stdint.h>\n"
357 "#include <stdio.h>\n"
358 "#include <stdlib.h>\n"
359 "#include <string.h>\n"
360 "#include <sys/stat.h>\n"
361 "#include <sys/types.h>\n"
362 "#include <unistd.h>\n",
363 m->modname, m->basename);
365 ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
366 "extern int somefunc(void);\n"
367 "int somefunc(void) { return 0; }\n"
368 "extern char somestring[];\n"
369 "char somestring[] = \"hello world\";\n");
371 if (looks_internal(lines, &why)) {
372 /* Wrap it all in main(). */
373 ret = start_main(ret, why);
374 fake_function = true;
378 ret = talloc_asprintf_append(ret,
379 "/* The example %s, so didn't wrap in main() */\n",
382 /* Primitive, very primitive. */
383 for (i = 0; lines[i]; i++) {
384 char *line = strip_comment(ret, lines[i]);
386 /* } at start of line ends a function. */
391 /* Character at start of line, with ( and no ;
392 * == function start. Ignore comments. */
393 if (!cisspace(line[0])
395 && !strchr(line, ';')
396 && !strstr(line, "//")) {
398 if (strncmp(line, "int main", 8) == 0)
400 if (strncmp(line, "static", 6) == 0) {
401 use_funcs = add_func(use_funcs,
406 /* ... means elided code. */
407 if (strcmp(line, "...") == 0) {
408 if (!in_function && !has_main
409 && looks_internal(lines + i + 1, &why)) {
410 /* This implies we start a function here. */
411 ret = start_main(ret, why);
413 fake_function = true;
416 ret = talloc_asprintf_append(ret,
417 "/* ... removed */\n");
420 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
424 ret = talloc_asprintf_append(ret,
425 "/* Need a main to link successfully. */\n"
426 "int main(void)\n{\n");
427 fake_function = true;
431 ret = talloc_asprintf_append(ret,
432 "/* Get rid of unused warnings"
433 " by printing addresses of"
434 " static funcs. */\n");
435 if (!fake_function) {
436 ret = talloc_asprintf_append(ret,
437 "int use_funcs(void);\n"
438 "int use_funcs(void) {\n");
439 fake_function = true;
441 ret = talloc_asprintf_append(ret, " %s\n", use_funcs);
445 ret = talloc_asprintf_append(ret, "return 0;\n"
450 static struct ccan_file *mangle_example(struct manifest *m,
451 struct ccan_file *example,
454 char *name, *contents;
458 name = temp_file(example, ".c",
459 talloc_asprintf(m, "%s/mangled-%s",
460 m->dir, example->name));
461 f = new_ccan_file(example,
462 talloc_dirname(example, name),
463 talloc_basename(example, name));
464 talloc_steal(f, name);
466 fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
470 contents = mangle(m, lines);
471 if (write(fd, contents, strlen(contents)) != strlen(contents)) {
476 f->contents = talloc_steal(f, contents);
477 list_add(&m->mangled_examples, &f->list);
481 /* If an example has expected output, it's complete and should not be
482 * included in future examples. */
483 static bool has_expected_output(char **lines)
487 for (i = 0; lines[i]; i++) {
488 char *p = lines[i] + strspn(lines[i], " \t");
489 if (!strstarts(p, "//"))
491 p += strspn(p, "/ ");
492 if (strncasecmp(p, "given", strlen("given")) == 0)
498 static unsigned int try_compiling(struct manifest *m,
501 struct ccan_file *mangled[3],
508 /* Try standalone. */
510 res[0] = compile(i, m, mangled[0], &err[0]);
511 lines[0] = get_ccan_file_lines(i);
512 if (res[0] && streq(err[0], ""))
516 lines[1] = combine(i, get_ccan_file_lines(i), prev);
518 mangled[1] = mangle_example(m, i, lines[1]);
519 res[1] = compile(i, m, mangled[1], &err[1]);
520 if (res[1] && streq(err[1], "")) {
527 /* Try standalone. */
528 lines[num] = get_ccan_file_lines(i);
529 mangled[num] = mangle_example(m, i, lines[num]);
530 res[num] = compile(i, m, mangled[num], &err[num]);
535 static void build_examples(struct manifest *m,
536 unsigned int *timeleft, struct score *score)
540 bool warnings = false;
545 list_for_each(&m->examples, i, list) {
547 struct ccan_file *file[3] = { NULL, NULL, NULL };
555 /* Simplify our dumb parsing. */
556 strip_leading_whitespace(get_ccan_file_lines(i));
558 num = try_compiling(m, i, prev, file, res, err, lines);
560 /* First look for a compile without any warnings. */
561 for (j = 0; j < num; j++) {
562 if (res[j] && streq(err[j], "")) {
563 if (!has_expected_output(lines[j]))
570 /* Now accept anything which succeeded. */
571 for (j = 0; j < num; j++) {
573 if (!has_expected_output(lines[j]))
577 score_file_error(score, file[j], 0,
578 "Compiling extracted example"
584 get_ccan_file_contents(file[j]),
593 error = "Compiling standalone, adding headers, "
594 "and including previous "
595 "example all failed";
597 error = "Standalone compile and"
598 " adding headers both failed";
601 error = talloc_asprintf(score,
602 "Standalone example:\n"
605 "Combining with previous example:\n"
608 "Adding headers, wrappers:\n"
611 get_ccan_file_contents(file[0]),
613 get_ccan_file_contents(file[1]),
615 get_ccan_file_contents(file[2]),
618 error = talloc_asprintf(score,
619 "Standalone example:\n"
622 "Adding headers, wrappers:\n"
625 get_ccan_file_contents(file[0]),
627 get_ccan_file_contents(file[1]),
631 score_file_error(score, i, 0, "%s", error);
632 /* This didn't work, so not a candidate for combining. */
639 /* An extra point if they all compiled without warnings. */
640 if (!list_empty(&m->examples)) {
647 struct ccanlint examples_compile = {
648 .key = "examples_compile",
649 .name = "Module examples compile",
650 .check = build_examples,
652 .needs = "examples_exist module_builds"
655 REGISTER_TEST(examples_compile);