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