]> git.sur5r.net Git - i3/i3/blob - src/config_parser.c
889179a9ad169bbdfac18813d76fa986e8ddec98
[i3/i3] / src / config_parser.c
1 #undef I3__FILE__
2 #define I3__FILE__ "config_parser.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * config_parser.c: hand-written parser to parse configuration directives.
10  *
11  * See also src/commands_parser.c for rationale on why we use a custom parser.
12  *
13  * This parser works VERY MUCH like src/commands_parser.c, so read that first.
14  * The differences are:
15  *
16  * 1. config_parser supports the 'number' token type (in addition to 'word' and
17  *    'string'). Numbers are referred to using &num (like $str).
18  *
19  * 2. Criteria are not executed immediately, they are just stored.
20  *
21  * 3. config_parser recognizes \n and \r as 'end' token, while commands_parser
22  *    ignores them.
23  *
24  */
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <stdbool.h>
30 #include <stdint.h>
31
32 #include "all.h"
33
34 // Macros to make the YAJL API a bit easier to use.
35 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
36 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
37
38 /*******************************************************************************
39  * The data structures used for parsing. Essentially the current state and a
40  * list of tokens for that state.
41  *
42  * The GENERATED_* files are generated by generate-commands-parser.pl with the
43  * input parser-specs/configs.spec.
44  ******************************************************************************/
45
46 #include "GENERATED_config_enums.h"
47
48 typedef struct token {
49     char *name;
50     char *identifier;
51     /* This might be __CALL */
52     cmdp_state next_state;
53     union {
54         uint16_t call_identifier;
55     } extra;
56 } cmdp_token;
57
58 typedef struct tokenptr {
59     cmdp_token *array;
60     int n;
61 } cmdp_token_ptr;
62
63 #include "GENERATED_config_tokens.h"
64
65 /*******************************************************************************
66  * The (small) stack where identified literals are stored during the parsing
67  * of a single command (like $workspace).
68  ******************************************************************************/
69
70 struct stack_entry {
71     /* Just a pointer, not dynamically allocated. */
72     const char *identifier;
73     enum {
74         STACK_STR = 0,
75         STACK_LONG = 1,
76     } type;
77     union {
78         char *str;
79         long num;
80     } val;
81 };
82
83 /* 10 entries should be enough for everybody. */
84 static struct stack_entry stack[10];
85
86 /*
87  * Pushes a string (identified by 'identifier') on the stack. We simply use a
88  * single array, since the number of entries we have to store is very small.
89  *
90  */
91 static void push_string(const char *identifier, char *str) {
92     for (int c = 0; c < 10; c++) {
93         if (stack[c].identifier != NULL &&
94             strcmp(stack[c].identifier, identifier) != 0)
95             continue;
96         if (stack[c].identifier == NULL) {
97             /* Found a free slot, let’s store it here. */
98             stack[c].identifier = identifier;
99             stack[c].val.str = str;
100             stack[c].type = STACK_STR;
101         } else {
102             /* Append the value. */
103             sasprintf(&(stack[c].val.str), "%s,%s", stack[c].val.str, str);
104         }
105         return;
106     }
107
108     /* When we arrive here, the stack is full. This should not happen and
109      * means there’s either a bug in this parser or the specification
110      * contains a command with more than 10 identified tokens. */
111     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
112                     "in the code, or a new command which contains more than "
113                     "10 identified tokens.\n");
114     exit(1);
115 }
116
117 static void push_long(const char *identifier, long num) {
118     for (int c = 0; c < 10; c++) {
119         if (stack[c].identifier != NULL)
120             continue;
121         /* Found a free slot, let’s store it here. */
122         stack[c].identifier = identifier;
123         stack[c].val.num = num;
124         stack[c].type = STACK_LONG;
125         return;
126     }
127
128     /* When we arrive here, the stack is full. This should not happen and
129      * means there’s either a bug in this parser or the specification
130      * contains a command with more than 10 identified tokens. */
131     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
132                     "in the code, or a new command which contains more than "
133                     "10 identified tokens.\n");
134     exit(1);
135
136 }
137
138 static const char *get_string(const char *identifier) {
139     for (int c = 0; c < 10; c++) {
140         if (stack[c].identifier == NULL)
141             break;
142         if (strcmp(identifier, stack[c].identifier) == 0)
143             return stack[c].val.str;
144     }
145     return NULL;
146 }
147
148 static const long get_long(const char *identifier) {
149     for (int c = 0; c < 10; c++) {
150         if (stack[c].identifier == NULL)
151             break;
152         if (strcmp(identifier, stack[c].identifier) == 0)
153             return stack[c].val.num;
154     }
155     return 0;
156 }
157
158 static void clear_stack(void) {
159     for (int c = 0; c < 10; c++) {
160         if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
161             free(stack[c].val.str);
162         stack[c].identifier = NULL;
163         stack[c].val.str = NULL;
164         stack[c].val.num = 0;
165     }
166 }
167
168 // TODO: remove this if it turns out we don’t need it for testing.
169 #if 0
170 /*******************************************************************************
171  * A dynamically growing linked list which holds the criteria for the current
172  * command.
173  ******************************************************************************/
174
175 typedef struct criterion {
176     char *type;
177     char *value;
178
179     TAILQ_ENTRY(criterion) criteria;
180 } criterion;
181
182 static TAILQ_HEAD(criteria_head, criterion) criteria =
183   TAILQ_HEAD_INITIALIZER(criteria);
184
185 /*
186  * Stores the given type/value in the list of criteria.
187  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
188  *
189  */
190 static void push_criterion(void *unused_criteria, const char *type,
191                            const char *value) {
192     struct criterion *criterion = malloc(sizeof(struct criterion));
193     criterion->type = strdup(type);
194     criterion->value = strdup(value);
195     TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
196 }
197
198 /*
199  * Clears the criteria linked list.
200  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
201  *
202  */
203 static void clear_criteria(void *unused_criteria) {
204     struct criterion *criterion;
205     while (!TAILQ_EMPTY(&criteria)) {
206         criterion = TAILQ_FIRST(&criteria);
207         free(criterion->type);
208         free(criterion->value);
209         TAILQ_REMOVE(&criteria, criterion, criteria);
210         free(criterion);
211     }
212 }
213 #endif
214
215 /*******************************************************************************
216  * The parser itself.
217  ******************************************************************************/
218
219 static cmdp_state state;
220 static Match current_match;
221 static struct ConfigResult subcommand_output;
222 static struct ConfigResult command_output;
223
224 #include "GENERATED_config_call.h"
225
226
227 static void next_state(const cmdp_token *token) {
228         //printf("token = name %s identifier %s\n", token->name, token->identifier);
229         //printf("next_state = %d\n", token->next_state);
230     if (token->next_state == __CALL) {
231         subcommand_output.json_gen = command_output.json_gen;
232         GENERATED_call(token->extra.call_identifier, &subcommand_output);
233         clear_stack();
234         return;
235     }
236
237     state = token->next_state;
238     if (state == INITIAL) {
239         clear_stack();
240     }
241 }
242
243 /*
244  * Returns a pointer to the start of the line (one byte after the previous \r,
245  * \n) or the start of the input, if this is the first line.
246  *
247  */
248 static const char *start_of_line(const char *walk, const char *beginning) {
249     while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
250         walk--;
251     }
252
253     return walk + 1;
254 }
255
256 /*
257  * Copies the line and terminates it at the next \n, if any.
258  *
259  * The caller has to free() the result.
260  *
261  */
262 static char *single_line(const char *start) {
263     char *result = sstrdup(start);
264     char *end = strchr(result, '\n');
265     if (end != NULL)
266         *end = '\0';
267     return result;
268 }
269
270 struct ConfigResult *parse_config(const char *input, struct context *context) {
271     /* Dump the entire config file into the debug log. We cannot just use
272      * DLOG("%s", input); because one log message must not exceed 4 KiB. */
273     const char *dumpwalk = input;
274     int linecnt = 1;
275     while (*dumpwalk != '\0') {
276         char *next_nl = strchr(dumpwalk, '\n');
277         if (next_nl != NULL) {
278             DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
279             dumpwalk = next_nl + 1;
280         } else {
281             DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
282             break;
283         }
284         linecnt++;
285     }
286     state = INITIAL;
287
288 /* A YAJL JSON generator used for formatting replies. */
289 #if YAJL_MAJOR >= 2
290     command_output.json_gen = yajl_gen_alloc(NULL);
291 #else
292     command_output.json_gen = yajl_gen_alloc(NULL, NULL);
293 #endif
294
295     y(array_open);
296
297     const char *walk = input;
298     const size_t len = strlen(input);
299     int c;
300     const cmdp_token *token;
301     bool token_handled;
302     linecnt = 1;
303
304     // TODO: make this testable
305 #ifndef TEST_PARSER
306     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
307 #endif
308
309     /* The "<=" operator is intentional: We also handle the terminating 0-byte
310      * explicitly by looking for an 'end' token. */
311     while ((walk - input) <= len) {
312         /* Skip whitespace before every token, newlines are relevant since they
313          * separate configuration directives. */
314         while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
315             walk++;
316
317                 //printf("remaining input: %s\n", walk);
318
319         cmdp_token_ptr *ptr = &(tokens[state]);
320         token_handled = false;
321         for (c = 0; c < ptr->n; c++) {
322             token = &(ptr->array[c]);
323
324             /* A literal. */
325             if (token->name[0] == '\'') {
326                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
327                     if (token->identifier != NULL)
328                         push_string(token->identifier, sstrdup(token->name + 1));
329                     walk += strlen(token->name) - 1;
330                     next_state(token);
331                     token_handled = true;
332                     break;
333                 }
334                 continue;
335             }
336
337             if (strcmp(token->name, "number") == 0) {
338                 /* Handle numbers. We only accept decimal numbers for now. */
339                 char *end = NULL;
340                 errno = 0;
341                 long int num = strtol(walk, &end, 10);
342                 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
343                     (errno != 0 && num == 0))
344                     continue;
345
346                 /* No valid numbers found */
347                 if (end == walk)
348                     continue;
349
350                 if (token->identifier != NULL)
351                     push_long(token->identifier, num);
352
353                 /* Set walk to the first non-number character */
354                 walk = end;
355                 next_state(token);
356                 token_handled = true;
357                 break;
358             }
359
360             if (strcmp(token->name, "string") == 0 ||
361                 strcmp(token->name, "word") == 0) {
362                 const char *beginning = walk;
363                 /* Handle quoted strings (or words). */
364                 if (*walk == '"') {
365                     beginning++;
366                     walk++;
367                     while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
368                         walk++;
369                 } else {
370                     if (token->name[0] == 's') {
371                         while (*walk != '\0' && *walk != '\r' && *walk != '\n')
372                             walk++;
373                     } else {
374                         /* For a word, the delimiters are white space (' ' or
375                          * '\t'), closing square bracket (]), comma (,) and
376                          * semicolon (;). */
377                         while (*walk != ' ' && *walk != '\t' &&
378                                *walk != ']' && *walk != ',' &&
379                                *walk !=  ';' && *walk != '\r' &&
380                                *walk != '\n' && *walk != '\0')
381                             walk++;
382                     }
383                 }
384                 if (walk != beginning) {
385                     char *str = scalloc(walk-beginning + 1);
386                     /* We copy manually to handle escaping of characters. */
387                     int inpos, outpos;
388                     for (inpos = 0, outpos = 0;
389                          inpos < (walk-beginning);
390                          inpos++, outpos++) {
391                         /* We only handle escaped double quotes to not break
392                          * backwards compatibility with people using \w in
393                          * regular expressions etc. */
394                         if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
395                             inpos++;
396                         str[outpos] = beginning[inpos];
397                     }
398                     if (token->identifier)
399                         push_string(token->identifier, str);
400                     /* If we are at the end of a quoted string, skip the ending
401                      * double quote. */
402                     if (*walk == '"')
403                         walk++;
404                     next_state(token);
405                     token_handled = true;
406                     break;
407                 }
408             }
409
410             if (strcmp(token->name, "end") == 0) {
411                 //printf("checking for end: *%s*\n", walk);
412                 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
413                     next_state(token);
414                     token_handled = true;
415                     /* To make sure we start with an appropriate matching
416                      * datastructure for commands which do *not* specify any
417                      * criteria, we re-initialize the criteria system after
418                      * every command. */
419                     // TODO: make this testable
420 #ifndef TEST_PARSER
421                     cfg_criteria_init(&current_match, &subcommand_output, INITIAL);
422 #endif
423                     linecnt++;
424                     walk++;
425                     break;
426                }
427            }
428         }
429
430         if (!token_handled) {
431             /* Figure out how much memory we will need to fill in the names of
432              * all tokens afterwards. */
433             int tokenlen = 0;
434             for (c = 0; c < ptr->n; c++)
435                 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
436
437             /* Build up a decent error message. We include the problem, the
438              * full input, and underline the position where the parser
439              * currently is. */
440             char *errormessage;
441             char *possible_tokens = smalloc(tokenlen + 1);
442             char *tokenwalk = possible_tokens;
443             for (c = 0; c < ptr->n; c++) {
444                 token = &(ptr->array[c]);
445                 if (token->name[0] == '\'') {
446                     /* A literal is copied to the error message enclosed with
447                      * single quotes. */
448                     *tokenwalk++ = '\'';
449                     strcpy(tokenwalk, token->name + 1);
450                     tokenwalk += strlen(token->name + 1);
451                     *tokenwalk++ = '\'';
452                 } else {
453                     /* Any other token is copied to the error message enclosed
454                      * with angle brackets. */
455                     *tokenwalk++ = '<';
456                     strcpy(tokenwalk, token->name);
457                     tokenwalk += strlen(token->name);
458                     *tokenwalk++ = '>';
459                 }
460                 if (c < (ptr->n - 1)) {
461                     *tokenwalk++ = ',';
462                     *tokenwalk++ = ' ';
463                 }
464             }
465             *tokenwalk = '\0';
466             sasprintf(&errormessage, "Expected one of these tokens: %s",
467                       possible_tokens);
468             free(possible_tokens);
469
470
471             /* Go back to the beginning of the line */
472             const char *error_line = start_of_line(walk, input);
473
474             /* Contains the same amount of characters as 'input' has, but with
475              * the unparseable part highlighted using ^ characters. */
476             char *position = scalloc(strlen(error_line) + 1);
477             const char *copywalk;
478             for (copywalk = error_line;
479                  *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
480                  copywalk++)
481                 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
482             position[(copywalk - error_line)] = '\0';
483
484             ELOG("CONFIG: %s\n", errormessage);
485             ELOG("CONFIG: (in file %s)\n", context->filename);
486             char *error_copy = single_line(error_line);
487
488             /* Print context lines *before* the error, if any. */
489             if (linecnt > 1) {
490                 const char *context_p1_start = start_of_line(error_line-2, input);
491                 char *context_p1_line = single_line(context_p1_start);
492                 if (linecnt > 2) {
493                     const char *context_p2_start = start_of_line(context_p1_start-2, input);
494                     char *context_p2_line = single_line(context_p2_start);
495                     ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
496                     free(context_p2_line);
497                 }
498                 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
499                 free(context_p1_line);
500             }
501             ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
502             ELOG("CONFIG:           %s\n", position);
503             free(error_copy);
504             /* Print context lines *after* the error, if any. */
505             for (int i = 0; i < 2; i++) {
506                 char *error_line_end = strchr(error_line, '\n');
507                 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
508                     error_line = error_line_end + 1;
509                     error_copy = single_line(error_line);
510                     ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
511                     free(error_copy);
512                 }
513             }
514
515             context->has_errors = true;
516
517             /* Format this error message as a JSON reply. */
518             y(map_open);
519             ystr("success");
520             y(bool, false);
521             /* We set parse_error to true to distinguish this from other
522              * errors. i3-nagbar is spawned upon keypresses only for parser
523              * errors. */
524             ystr("parse_error");
525             y(bool, true);
526             ystr("error");
527             ystr(errormessage);
528             ystr("input");
529             ystr(input);
530             ystr("errorposition");
531             ystr(position);
532             y(map_close);
533
534             free(position);
535             free(errormessage);
536             clear_stack();
537             break;
538         }
539     }
540
541     y(array_close);
542
543     return &command_output;
544 }
545
546 /*******************************************************************************
547  * Code for building the stand-alone binary test.commands_parser which is used
548  * by t/187-commands-parser.t.
549  ******************************************************************************/
550
551 #ifdef TEST_PARSER
552
553 /*
554  * Logs the given message to stdout while prefixing the current time to it,
555  * but only if debug logging was activated.
556  * This is to be called by DLOG() which includes filename/linenumber
557  *
558  */
559 void debuglog(char *fmt, ...) {
560     va_list args;
561
562     va_start(args, fmt);
563     fprintf(stdout, "# ");
564     vfprintf(stdout, fmt, args);
565     va_end(args);
566 }
567
568 void errorlog(char *fmt, ...) {
569     va_list args;
570
571     va_start(args, fmt);
572     vfprintf(stderr, fmt, args);
573     va_end(args);
574 }
575
576 static int criteria_next_state;
577
578 void cfg_criteria_init(I3_CFG, int _state) {
579     criteria_next_state = _state;
580 }
581
582 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
583 }
584
585 void cfg_criteria_pop_state(I3_CFG) {
586     result->next_state = criteria_next_state;
587 }
588
589 int main(int argc, char *argv[]) {
590     if (argc < 2) {
591         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
592         return 1;
593     }
594     struct context context;
595     context.filename = "<stdin>";
596     parse_config(argv[1], &context);
597 }
598 #endif