ccanlint: give a point per compile_ok/compile_fail test
[ccan] / tools / ccanlint / file_analysis.c
1 #include "ccanlint.h"
2 #include <ccan/talloc/talloc.h>
3 #include <ccan/str/str.h>
4 #include <ccan/str_talloc/str_talloc.h>
5 #include <ccan/talloc_link/talloc_link.h>
6 #include <ccan/hash/hash.h>
7 #include <ccan/htable/htable_type.h>
8 #include <ccan/grab_file/grab_file.h>
9 #include <ccan/noerr/noerr.h>
10 #include <ccan/foreach/foreach.h>
11 #include <ccan/asort/asort.h>
12 #include "../tools.h"
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <err.h>
18 #include <errno.h>
19 #include <dirent.h>
20 #include <ctype.h>
21 #include <stdarg.h>
22 #include <assert.h>
23
24 const char *ccan_dir;
25
26 static size_t dir_hash(const char *name)
27 {
28         return hash(name, strlen(name), 0);
29 }
30
31 static const char *manifest_name(const struct manifest *m)
32 {
33         return m->dir;
34 }
35
36 static bool dir_cmp(const struct manifest *m, const char *dir)
37 {
38         return strcmp(m->dir, dir) == 0;
39 }
40
41 HTABLE_DEFINE_TYPE(struct manifest, manifest_name, dir_hash, dir_cmp, manifest);
42 static struct htable_manifest *manifests;
43
44 const char *get_ccan_file_contents(struct ccan_file *f)
45 {
46         if (!f->contents) {
47                 f->contents = grab_file(f, f->fullname, &f->contents_size);
48                 if (!f->contents)
49                         err(1, "Reading file %s", f->fullname);
50         }
51         return f->contents;
52 }
53
54 char **get_ccan_file_lines(struct ccan_file *f)
55 {
56         if (!f->lines)
57                 f->lines = strsplit(f, get_ccan_file_contents(f), "\n");
58
59         /* FIXME: is f->num_lines necessary? */
60         f->num_lines = talloc_array_length(f->lines) - 1;
61         return f->lines;
62 }
63
64 struct list_head *get_ccan_file_docs(struct ccan_file *f)
65 {
66         if (!f->doc_sections) {
67                 get_ccan_file_lines(f);
68                 f->doc_sections = extract_doc_sections(f->lines);
69         }
70         return f->doc_sections;
71 }
72
73 struct ccan_file *new_ccan_file(const void *ctx, const char *dir, char *name)
74 {
75         struct ccan_file *f;
76
77         assert(dir[0] == '/');
78
79         f = talloc(ctx, struct ccan_file);
80         f->lines = NULL;
81         f->line_info = NULL;
82         f->doc_sections = NULL;
83         f->compiled = NULL;
84         f->name = talloc_steal(f, name);
85         f->fullname = talloc_asprintf(f, "%s/%s", dir, f->name);
86         f->contents = NULL;
87         f->cov_compiled = NULL;
88         return f;
89 }
90
91 static void add_files(struct manifest *m, const char *dir)
92 {
93         DIR *d;
94         struct dirent *ent;
95         char **subs = NULL;
96
97         if (dir[0])
98                 d = opendir(dir);
99         else
100                 d = opendir(".");
101         if (!d)
102                 err(1, "Opening directory %s", dir[0] ? dir : ".");
103
104         while ((ent = readdir(d)) != NULL) {
105                 struct stat st;
106                 struct ccan_file *f;
107                 struct list_head *dest;
108                 bool is_c_src;
109
110                 if (ent->d_name[0] == '.')
111                         continue;
112
113                 f = new_ccan_file(m, m->dir,
114                                   talloc_asprintf(m, "%s%s",
115                                                   dir, ent->d_name));
116                 if (lstat(f->name, &st) != 0)
117                         err(1, "lstat %s", f->name);
118
119                 if (S_ISDIR(st.st_mode)) {
120                         size_t len = talloc_array_length(subs);
121                         subs = talloc_realloc(m, subs, char *, len+1);
122                         subs[len] = talloc_append_string(f->name, "/");
123                         continue;
124                 }
125                 if (!S_ISREG(st.st_mode)) {
126                         talloc_free(f);
127                         continue;
128                 }
129
130                 if (streq(f->name, "_info")) {
131                         m->info_file = f;
132                         continue;
133                 }
134
135                 is_c_src = strends(f->name, ".c");
136                 if (!is_c_src && !strends(f->name, ".h")) {
137                         dest = &m->other_files;
138                         continue;
139                 }
140
141                 if (!strchr(f->name, '/')) {
142                         if (is_c_src)
143                                 dest = &m->c_files;
144                         else
145                                 dest = &m->h_files;
146                 } else if (strstarts(f->name, "test/")) {
147                         if (is_c_src) {
148                                 if (strstarts(f->name, "test/api"))
149                                         dest = &m->api_tests;
150                                 else if (strstarts(f->name, "test/run"))
151                                         dest = &m->run_tests;
152                                 else if (strstarts(f->name, "test/compile_ok"))
153                                         dest = &m->compile_ok_tests;
154                                 else if (strstarts(f->name, "test/compile_fail"))
155                                         dest = &m->compile_fail_tests;
156                                 else
157                                         dest = &m->other_test_c_files;
158                         } else
159                                 dest = &m->other_test_files;
160                 } else
161                         dest = &m->other_files;
162
163                 list_add(dest, &f->list);
164         }
165         closedir(d);
166
167         /* Before we recurse, sanity check this is a ccan module. */ 
168         if (!dir[0]) {
169                 size_t i;
170
171                 if (!m->info_file
172                     && list_empty(&m->c_files)
173                     && list_empty(&m->h_files))
174                         errx(1, "No _info, C or H files found here!");
175
176                 for (i = 0; i < talloc_array_length(subs); i++)
177                         add_files(m, subs[i]);
178         }
179         talloc_free(subs);
180 }
181
182 static int cmp_names(struct ccan_file *const *a, struct ccan_file *const *b,
183                      void *unused)
184 {
185         return strcmp((*a)->name, (*b)->name);
186 }
187
188 static void sort_files(struct list_head *list)
189 {
190         struct ccan_file **files = NULL, *f;
191         unsigned int i, num;
192
193         num = 0;
194         while ((f = list_top(list, struct ccan_file, list)) != NULL) {
195                 files = talloc_realloc(NULL, files, struct ccan_file *, num+1);
196                 files[num++] = f;
197                 list_del(&f->list);
198         }
199         asort(files, num, cmp_names, NULL);
200
201         for (i = 0; i < num; i++)
202                 list_add_tail(list, &files[i]->list);
203         talloc_free(files);
204 }
205
206 struct manifest *get_manifest(const void *ctx, const char *dir)
207 {
208         struct manifest *m;
209         char *olddir, *canon_dir;
210         unsigned int len;
211         struct list_head *list;
212
213         if (!manifests)
214                 manifests = htable_manifest_new();
215
216         olddir = talloc_getcwd(NULL);
217         if (!olddir)
218                 err(1, "Getting current directory");
219
220         if (chdir(dir) != 0)
221                 err(1, "Failed to chdir to %s", dir);
222
223         canon_dir = talloc_getcwd(olddir);
224         if (!canon_dir)
225                 err(1, "Getting current directory");
226
227         m = htable_manifest_get(manifests, canon_dir);
228         if (m)
229                 goto done;
230
231         m = talloc_linked(ctx, talloc(NULL, struct manifest));
232         m->info_file = NULL;
233         m->compiled = NULL;
234         m->dir = talloc_steal(m, canon_dir);
235         list_head_init(&m->c_files);
236         list_head_init(&m->h_files);
237         list_head_init(&m->api_tests);
238         list_head_init(&m->run_tests);
239         list_head_init(&m->compile_ok_tests);
240         list_head_init(&m->compile_fail_tests);
241         list_head_init(&m->other_test_c_files);
242         list_head_init(&m->other_test_files);
243         list_head_init(&m->other_files);
244         list_head_init(&m->examples);
245         list_head_init(&m->mangled_examples);
246         list_head_init(&m->deps);
247
248         len = strlen(m->dir);
249         while (len && m->dir[len-1] == '/')
250                 m->dir[--len] = '\0';
251
252         m->basename = strrchr(m->dir, '/');
253         if (!m->basename)
254                 errx(1, "I don't expect to be run from the root directory");
255         m->basename++;
256
257         /* We expect the ccan dir to be two levels above module dir. */
258         if (!ccan_dir) {
259                 char *p;
260                 ccan_dir = talloc_strdup(NULL, m->dir);
261                 p = strrchr(ccan_dir, '/');
262                 if (!p)
263                         errx(1, "I expect the ccan root directory in ../..");
264                 *p = '\0';
265                 p = strrchr(ccan_dir, '/');
266                 if (!p)
267                         errx(1, "I expect the ccan root directory in ../..");
268                 *p = '\0';
269         }
270
271         add_files(m, "");
272
273         /* Nicer to run tests in a predictable order. */
274         foreach_ptr(list, &m->api_tests, &m->run_tests, &m->compile_ok_tests,
275                     &m->compile_fail_tests)
276                 sort_files(list);
277
278         htable_manifest_add(manifests, m);
279
280 done:
281         if (chdir(olddir) != 0)
282                 err(1, "Returning to original directory '%s'", olddir);
283         talloc_free(olddir);
284
285         return m;
286 }
287
288
289 /**
290  * remove_comments - strip comments from a line, return copy.
291  * @line: line to copy
292  * @in_comment: are we already within a comment (from prev line).
293  * @unterminated: are we still in a comment for next line.
294  */
295 static char *remove_comments(const char *line, bool in_comment,
296                              bool *unterminated)
297 {
298         char *p, *ret = talloc_array(line, char, strlen(line) + 1);
299
300         p = ret;
301         for (;;) {
302                 if (!in_comment) {
303                         /* Find first comment. */
304                         const char *old_comment = strstr(line, "/*");
305                         const char *new_comment = strstr(line, "//");
306                         const char *comment;
307
308                         if (new_comment && old_comment)
309                                 comment = new_comment < old_comment
310                                         ? new_comment : old_comment;
311                         else if (old_comment)
312                                 comment = old_comment;
313                         else if (new_comment)
314                                 comment = new_comment;
315                         else {
316                                 /* Nothing more. */
317                                 strcpy(p, line);
318                                 *unterminated = false;
319                                 break;
320                         }
321
322                         /* Copy up to comment. */
323                         memcpy(p, line, comment - line);
324                         p += comment - line;
325                         line += comment - line + 2;
326
327                         if (comment == new_comment) {
328                                 /* We're done: goes to EOL. */
329                                 p[0] = '\0';
330                                 *unterminated = false;
331                                 break;
332                         }
333                         in_comment = true;
334                 }
335
336                 if (in_comment) {
337                         const char *end = strstr(line, "*/");
338                         if (!end) {
339                                 *unterminated = true;
340                                 p[0] = '\0';
341                                 break;
342                         }
343                         line = end+2;
344                         in_comment = false;
345                 }
346         }
347         return ret;
348 }
349
350 static bool is_empty(const char *line)
351 {
352         return strspn(line, " \t") == strlen(line);
353 }
354
355 static bool continues(const char *line)
356 {
357         /* Technically, any odd number of these.  But who cares? */
358         return strends(line, "\\");
359 }
360
361 /* Get token if it's equal to token. */
362 bool get_token(const char **line, const char *token)
363 {
364         unsigned int toklen;
365
366         *line += strspn(*line, " \t");
367         if (isalnum(token[0]) || token[0] == '_')
368                 toklen = strspn(*line, IDENT_CHARS);
369         else {
370                 /* FIXME: real tokenizer handles ++ and other multi-chars.  */
371                 toklen = strlen(token);
372         }
373
374         if (toklen == strlen(token) && !strncmp(*line, token, toklen)) {
375                 *line += toklen;
376                 return true;
377         }
378         return false;
379 }
380
381 char *get_symbol_token(void *ctx, const char **line)
382 {
383         unsigned int toklen;
384         char *ret;
385
386         *line += strspn(*line, " \t");
387         toklen = strspn(*line, IDENT_CHARS);
388         if (!toklen)
389                 return NULL;
390         ret = talloc_strndup(ctx, *line, toklen);
391         *line += toklen;
392         return ret;
393 }
394
395 static bool parse_hash_if(struct pp_conditions *cond, const char **line)
396 {
397         bool brackets, defined;
398
399         cond->inverse = get_token(line, "!");
400         defined = get_token(line, "defined");
401         brackets = get_token(line, "(");
402         cond->symbol = get_symbol_token(cond, line);
403         if (!cond->symbol)
404                 return false;
405         if (brackets && !get_token(line, ")"))
406                 return false;
407         if (!defined)
408                 cond->type = PP_COND_IF;
409         return true;
410 }
411
412 /* FIXME: Get serious! */
413 static struct pp_conditions *analyze_directive(struct ccan_file *f,
414                                                const char *line,
415                                                struct pp_conditions *parent)
416 {
417         struct pp_conditions *cond = talloc(f, struct pp_conditions);
418         bool unused;
419
420         line = remove_comments(line, false, &unused);
421
422         cond->parent = parent;
423         cond->type = PP_COND_IFDEF;
424
425         if (!get_token(&line, "#"))
426                 abort();
427
428         if (get_token(&line, "if")) {
429                 if (!parse_hash_if(cond, &line))
430                         goto unknown;
431         } else if (get_token(&line, "elif")) {
432                 /* Malformed? */
433                 if (!parent)
434                         return NULL;
435                 cond->parent = parent->parent;
436                 /* FIXME: Not quite true.  This implies !parent, but we don't
437                  * do multiple conditionals yet. */
438                 if (!parse_hash_if(cond, &line))
439                         goto unknown;
440         } else if (get_token(&line, "ifdef")) {
441                 bool brackets;
442                 cond->inverse = false;
443                 brackets = get_token(&line, "(");
444                 cond->symbol = get_symbol_token(cond, &line);
445                 if (!cond->symbol)
446                         goto unknown;
447                 if (brackets && !get_token(&line, ")"))
448                         goto unknown;
449         } else if (get_token(&line, "ifndef")) {
450                 bool brackets;
451                 cond->inverse = true;
452                 brackets = get_token(&line, "(");
453                 cond->symbol = get_symbol_token(cond, &line);
454                 if (!cond->symbol)
455                         goto unknown;
456                 if (brackets && !get_token(&line, ")"))
457                         goto unknown;
458         } else if (get_token(&line, "else")) {
459                 /* Malformed? */
460                 if (!parent)
461                         return NULL;
462
463                 *cond = *parent;
464                 cond->inverse = !cond->inverse;
465                 return cond;
466         } else if (get_token(&line, "endif")) {
467                 talloc_free(cond);
468                 /* Malformed? */
469                 if (!parent)
470                         return NULL;
471                 /* Back up one! */
472                 return parent->parent;
473         } else {
474                 /* Not a conditional. */
475                 talloc_free(cond);
476                 return parent;
477         }
478
479         if (!is_empty(line))
480                 goto unknown;
481         return cond;
482
483 unknown:
484         cond->type = PP_COND_UNKNOWN;
485         return cond;
486 }
487
488 /* This parser is rough, but OK if code is reasonably neat. */
489 struct line_info *get_ccan_line_info(struct ccan_file *f)
490 {
491         bool continued = false, in_comment = false;
492         struct pp_conditions *cond = NULL;
493         unsigned int i;
494
495         if (f->line_info)
496                 return f->line_info;
497
498         get_ccan_file_lines(f);
499         f->line_info = talloc_array(f->lines, struct line_info, f->num_lines);
500
501         for (i = 0; i < f->num_lines; continued = continues(f->lines[i++])) {
502                 char *p;
503                 bool still_doc_line;
504
505                 /* Current conditions apply to this line. */
506                 f->line_info[i].cond = cond;
507                 f->line_info[i].continued = continued;
508
509                 if (continued) {
510                         /* Same as last line. */
511                         f->line_info[i].type = f->line_info[i-1].type;
512                         /* Update in_comment. */
513                         remove_comments(f->lines[i], in_comment, &in_comment);
514                         continue;
515                 }
516
517                 /* Preprocessor directive? */
518                 if (!in_comment
519                     && f->lines[i][strspn(f->lines[i], " \t")] == '#') {
520                         f->line_info[i].type = PREPROC_LINE;
521                         cond = analyze_directive(f, f->lines[i], cond);
522                         continue;
523                 }
524
525                 still_doc_line = (in_comment
526                                   && f->line_info[i-1].type == DOC_LINE);
527
528                 p = remove_comments(f->lines[i], in_comment, &in_comment);
529                 if (is_empty(p)) {
530                         if (strstarts(f->lines[i], "/**") || still_doc_line)
531                                 f->line_info[i].type = DOC_LINE;
532                         else
533                                 f->line_info[i].type = COMMENT_LINE;
534                 } else
535                         f->line_info[i].type = CODE_LINE;
536                 talloc_free(p);
537         }
538         return f->line_info;
539 }
540
541 struct symbol {
542         struct list_node list;
543         const char *name;
544         const unsigned int *value;
545 };
546
547 static struct symbol *find_symbol(struct list_head *syms, const char *sym)
548 {
549         struct symbol *i;
550
551         list_for_each(syms, i, list)
552                 if (streq(sym, i->name))
553                         return i;
554         return NULL;
555 }
556
557 static enum line_compiled get_pp(struct pp_conditions *cond,
558                                  struct list_head *syms)
559 {
560         struct symbol *sym;
561         unsigned int val;
562         enum line_compiled parent, ret;
563
564         /* No conditions?  Easy. */
565         if (!cond)
566                 return COMPILED;
567
568         /* Check we get here at all. */
569         parent = get_pp(cond->parent, syms);
570         if (parent == NOT_COMPILED)
571                 return NOT_COMPILED;
572
573         if (cond->type == PP_COND_UNKNOWN)
574                 return MAYBE_COMPILED;
575
576         sym = find_symbol(syms, cond->symbol);
577         if (!sym)
578                 return MAYBE_COMPILED;
579
580         switch (cond->type) {
581         case PP_COND_IF:
582                 /* Undefined is 0. */
583                 val = sym->value ? *sym->value : 0;
584                 if (!val == cond->inverse)
585                         ret = COMPILED;
586                 else
587                         ret = NOT_COMPILED;
588                 break;
589
590         case PP_COND_IFDEF:
591                 if (cond->inverse == !sym->value)
592                         ret = COMPILED;
593                 else
594                         ret = NOT_COMPILED;
595                 break;
596
597         default:
598                 abort();
599         }
600
601         /* If parent didn't know, NO == NO, but YES == MAYBE. */
602         if (parent == MAYBE_COMPILED && ret == COMPILED)
603                 ret = MAYBE_COMPILED;
604         return ret;
605 }
606
607 static void add_symbol(struct list_head *head,
608                        const char *symbol, const unsigned int *value)
609 {
610         struct symbol *sym = talloc(head, struct symbol);
611         sym->name = symbol;
612         sym->value = value;
613         list_add(head, &sym->list);
614 }
615         
616 enum line_compiled get_ccan_line_pp(struct pp_conditions *cond,
617                                     const char *symbol,
618                                     const unsigned int *value,
619                                     ...)
620 {
621         enum line_compiled ret;
622         struct list_head *head;
623         va_list ap;
624
625         head = talloc(NULL, struct list_head);
626         list_head_init(head);
627
628         va_start(ap, value);
629         add_symbol(head, symbol, value);
630
631         while ((symbol = va_arg(ap, const char *)) != NULL) {
632                 value = va_arg(ap, const unsigned int *);
633                 add_symbol(head, symbol, value);
634         }
635         ret = get_pp(cond, head);
636         talloc_free(head);
637         return ret;
638 }
639
640 void score_file_error(struct score *score, struct ccan_file *f, unsigned line,
641                       const char *errorfmt, ...)
642 {
643         va_list ap;
644
645         struct file_error *fe = talloc(score, struct file_error);
646         fe->file = f;
647         fe->line = line;
648         list_add_tail(&score->per_file_errors, &fe->list);
649
650         if (!score->error)
651                 score->error = talloc_strdup(score, "");
652         
653         if (verbose < 2 && strcount(score->error, "\n") > 5)
654                 return;
655
656         if (line)
657                 score->error = talloc_asprintf_append(score->error,
658                                                       "%s:%u:",
659                                                       f->fullname, line);
660         else
661                 score->error = talloc_asprintf_append(score->error,
662                                                       "%s:", f->fullname);
663
664         va_start(ap, errorfmt);
665         score->error = talloc_vasprintf_append(score->error, errorfmt, ap);
666         va_end(ap);
667         score->error = talloc_append_string(score->error, "\n");
668
669         if (verbose < 2 && strcount(score->error, "\n") > 5)
670                 score->error = talloc_append_string(score->error,
671                                     "... more (use -vv to see them all)\n");
672 }