]> git.sur5r.net Git - i3/i3/blob - src/config_parser.c
19d1d1683eaeca91b06b62b3d83aee59a14cab5e
[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  */
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18 #include <stdbool.h>
19 #include <stdint.h>
20
21 #include "all.h"
22
23 // Macros to make the YAJL API a bit easier to use.
24 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
25 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
26
27 /*******************************************************************************
28  * The data structures used for parsing. Essentially the current state and a
29  * list of tokens for that state.
30  *
31  * The GENERATED_* files are generated by generate-commands-parser.pl with the
32  * input parser-specs/configs.spec.
33  ******************************************************************************/
34
35 #include "GENERATED_config_enums.h"
36
37 typedef struct token {
38     char *name;
39     char *identifier;
40     /* This might be __CALL */
41     cmdp_state next_state;
42     union {
43         uint16_t call_identifier;
44     } extra;
45 } cmdp_token;
46
47 typedef struct tokenptr {
48     cmdp_token *array;
49     int n;
50 } cmdp_token_ptr;
51
52 #include "GENERATED_config_tokens.h"
53
54 /*******************************************************************************
55  * The (small) stack where identified literals are stored during the parsing
56  * of a single command (like $workspace).
57  ******************************************************************************/
58
59 struct stack_entry {
60     /* Just a pointer, not dynamically allocated. */
61     const char *identifier;
62     char *str;
63 };
64
65 /* 10 entries should be enough for everybody. */
66 static struct stack_entry stack[10];
67
68 /*
69  * Pushes a string (identified by 'identifier') on the stack. We simply use a
70  * single array, since the number of entries we have to store is very small.
71  *
72  */
73 static void push_string(const char *identifier, char *str) {
74     for (int c = 0; c < 10; c++) {
75         if (stack[c].identifier != NULL &&
76                     strcmp(stack[c].identifier, identifier) != 0)
77             continue;
78                 if (stack[c].identifier == NULL) {
79                         /* Found a free slot, let’s store it here. */
80                         stack[c].identifier = identifier;
81                         stack[c].str = str;
82                 } else {
83                         /* Append the value. */
84                         sasprintf(&(stack[c].str), "%s,%s", stack[c].str, str);
85                 }
86         return;
87     }
88
89     /* When we arrive here, the stack is full. This should not happen and
90      * means there’s either a bug in this parser or the specification
91      * contains a command with more than 10 identified tokens. */
92     fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
93                     "in the code, or a new command which contains more than "
94                     "10 identified tokens.\n");
95     exit(1);
96 }
97
98 // XXX: ideally, this would be const char. need to check if that works with all
99 // called functions.
100 static char *get_string(const char *identifier) {
101     for (int c = 0; c < 10; c++) {
102         if (stack[c].identifier == NULL)
103             break;
104         if (strcmp(identifier, stack[c].identifier) == 0)
105             return stack[c].str;
106     }
107     return NULL;
108 }
109
110 static void clear_stack(void) {
111     for (int c = 0; c < 10; c++) {
112         if (stack[c].str != NULL)
113             free(stack[c].str);
114         stack[c].identifier = NULL;
115         stack[c].str = NULL;
116     }
117 }
118
119 // TODO: remove this if it turns out we don’t need it for testing.
120 #if 0
121 /*******************************************************************************
122  * A dynamically growing linked list which holds the criteria for the current
123  * command.
124  ******************************************************************************/
125
126 typedef struct criterion {
127     char *type;
128     char *value;
129
130     TAILQ_ENTRY(criterion) criteria;
131 } criterion;
132
133 static TAILQ_HEAD(criteria_head, criterion) criteria =
134   TAILQ_HEAD_INITIALIZER(criteria);
135
136 /*
137  * Stores the given type/value in the list of criteria.
138  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
139  *
140  */
141 static void push_criterion(void *unused_criteria, const char *type,
142                            const char *value) {
143     struct criterion *criterion = malloc(sizeof(struct criterion));
144     criterion->type = strdup(type);
145     criterion->value = strdup(value);
146     TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
147 }
148
149 /*
150  * Clears the criteria linked list.
151  * Accepts a pointer as first argument, since it is 'call'ed by the parser.
152  *
153  */
154 static void clear_criteria(void *unused_criteria) {
155     struct criterion *criterion;
156     while (!TAILQ_EMPTY(&criteria)) {
157         criterion = TAILQ_FIRST(&criteria);
158         free(criterion->type);
159         free(criterion->value);
160         TAILQ_REMOVE(&criteria, criterion, criteria);
161         free(criterion);
162     }
163 }
164 #endif
165
166 /*******************************************************************************
167  * The parser itself.
168  ******************************************************************************/
169
170 static cmdp_state state;
171 #ifndef TEST_PARSER
172 static Match current_match;
173 #endif
174 static struct CommandResult subcommand_output;
175 static struct CommandResult command_output;
176
177 #include "GENERATED_config_call.h"
178
179
180 static void next_state(const cmdp_token *token) {
181         //printf("token = name %s identifier %s\n", token->name, token->identifier);
182         //printf("next_state = %d\n", token->next_state);
183     if (token->next_state == __CALL) {
184         subcommand_output.json_gen = command_output.json_gen;
185         subcommand_output.needs_tree_render = false;
186         GENERATED_call(token->extra.call_identifier, &subcommand_output);
187         /* If any subcommand requires a tree_render(), we need to make the
188          * whole parser result request a tree_render(). */
189         if (subcommand_output.needs_tree_render)
190             command_output.needs_tree_render = true;
191         clear_stack();
192         return;
193     }
194
195     state = token->next_state;
196     if (state == INITIAL) {
197         clear_stack();
198     }
199 }
200
201 struct CommandResult *parse_config(const char *input) {
202     DLOG("COMMAND: *%s*\n", input);
203     state = INITIAL;
204
205 /* A YAJL JSON generator used for formatting replies. */
206 #if YAJL_MAJOR >= 2
207     command_output.json_gen = yajl_gen_alloc(NULL);
208 #else
209     command_output.json_gen = yajl_gen_alloc(NULL, NULL);
210 #endif
211
212     y(array_open);
213     command_output.needs_tree_render = false;
214
215     const char *walk = input;
216     const size_t len = strlen(input);
217     int c;
218     const cmdp_token *token;
219     bool token_handled;
220
221     // TODO: make this testable
222 #ifndef TEST_PARSER
223     cmd_criteria_init(&current_match, &subcommand_output);
224 #endif
225
226     /* The "<=" operator is intentional: We also handle the terminating 0-byte
227      * explicitly by looking for an 'end' token. */
228     while ((walk - input) <= len) {
229         /* skip whitespace and newlines before every token */
230         while ((*walk == ' ' || *walk == '\t' ||
231                 *walk == '\r' || *walk == '\n') && *walk != '\0')
232             walk++;
233
234                 //printf("remaining input: %s\n", walk);
235
236         cmdp_token_ptr *ptr = &(tokens[state]);
237         token_handled = false;
238         for (c = 0; c < ptr->n; c++) {
239             token = &(ptr->array[c]);
240
241             /* A literal. */
242             if (token->name[0] == '\'') {
243                 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
244                     if (token->identifier != NULL)
245                         push_string(token->identifier, sstrdup(token->name + 1));
246                     walk += strlen(token->name) - 1;
247                     next_state(token);
248                     token_handled = true;
249                     break;
250                 }
251                 continue;
252             }
253
254             if (strcmp(token->name, "string") == 0 ||
255                 strcmp(token->name, "word") == 0) {
256                 const char *beginning = walk;
257                 /* Handle quoted strings (or words). */
258                 if (*walk == '"') {
259                     beginning++;
260                     walk++;
261                     while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
262                         walk++;
263                 } else {
264                     if (token->name[0] == 's') {
265                         /* For a string (starting with 's'), the delimiters are
266                          * comma (,) and semicolon (;) which introduce a new
267                          * operation or command, respectively. Also, newlines
268                          * end a command. */
269                         while (*walk != ';' && *walk != ',' &&
270                                *walk != '\0' && *walk != '\r' &&
271                                *walk != '\n')
272                             walk++;
273                     } else {
274                         /* For a word, the delimiters are white space (' ' or
275                          * '\t'), closing square bracket (]), comma (,) and
276                          * semicolon (;). */
277                         while (*walk != ' ' && *walk != '\t' &&
278                                *walk != ']' && *walk != ',' &&
279                                *walk !=  ';' && *walk != '\r' &&
280                                *walk != '\n' && *walk != '\0')
281                             walk++;
282                     }
283                 }
284                 if (walk != beginning) {
285                     char *str = scalloc(walk-beginning + 1);
286                     /* We copy manually to handle escaping of characters. */
287                     int inpos, outpos;
288                     for (inpos = 0, outpos = 0;
289                          inpos < (walk-beginning);
290                          inpos++, outpos++) {
291                         /* We only handle escaped double quotes to not break
292                          * backwards compatibility with people using \w in
293                          * regular expressions etc. */
294                         if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
295                             inpos++;
296                         str[outpos] = beginning[inpos];
297                     }
298                     if (token->identifier)
299                         push_string(token->identifier, str);
300                     /* If we are at the end of a quoted string, skip the ending
301                      * double quote. */
302                     if (*walk == '"')
303                         walk++;
304                     next_state(token);
305                     token_handled = true;
306                     break;
307                 }
308             }
309
310             if (strcmp(token->name, "end") == 0) {
311                 if (*walk == '\0' || *walk == ',' || *walk == ';') {
312                     next_state(token);
313                     token_handled = true;
314                     /* To make sure we start with an appropriate matching
315                      * datastructure for commands which do *not* specify any
316                      * criteria, we re-initialize the criteria system after
317                      * every command. */
318                     // TODO: make this testable
319 #ifndef TEST_PARSER
320                     if (*walk == '\0' || *walk == ';')
321                         cmd_criteria_init(&current_match, &subcommand_output);
322 #endif
323                     walk++;
324                     break;
325                }
326            }
327         }
328
329         if (!token_handled) {
330             /* Figure out how much memory we will need to fill in the names of
331              * all tokens afterwards. */
332             int tokenlen = 0;
333             for (c = 0; c < ptr->n; c++)
334                 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
335
336             /* Build up a decent error message. We include the problem, the
337              * full input, and underline the position where the parser
338              * currently is. */
339             char *errormessage;
340             char *possible_tokens = smalloc(tokenlen + 1);
341             char *tokenwalk = possible_tokens;
342             for (c = 0; c < ptr->n; c++) {
343                 token = &(ptr->array[c]);
344                 if (token->name[0] == '\'') {
345                     /* A literal is copied to the error message enclosed with
346                      * single quotes. */
347                     *tokenwalk++ = '\'';
348                     strcpy(tokenwalk, token->name + 1);
349                     tokenwalk += strlen(token->name + 1);
350                     *tokenwalk++ = '\'';
351                 } else {
352                     /* Any other token is copied to the error message enclosed
353                      * with angle brackets. */
354                     *tokenwalk++ = '<';
355                     strcpy(tokenwalk, token->name);
356                     tokenwalk += strlen(token->name);
357                     *tokenwalk++ = '>';
358                 }
359                 if (c < (ptr->n - 1)) {
360                     *tokenwalk++ = ',';
361                     *tokenwalk++ = ' ';
362                 }
363             }
364             *tokenwalk = '\0';
365             sasprintf(&errormessage, "Expected one of these tokens: %s",
366                       possible_tokens);
367             free(possible_tokens);
368
369             /* Contains the same amount of characters as 'input' has, but with
370              * the unparseable part highlighted using ^ characters. */
371             char *position = smalloc(len + 1);
372             for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
373                 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
374             position[len] = '\0';
375
376             ELOG("%s\n", errormessage);
377             ELOG("Your command: %s\n", input);
378             ELOG("              %s\n", position);
379
380             /* Format this error message as a JSON reply. */
381             y(map_open);
382             ystr("success");
383             y(bool, false);
384             /* We set parse_error to true to distinguish this from other
385              * errors. i3-nagbar is spawned upon keypresses only for parser
386              * errors. */
387             ystr("parse_error");
388             y(bool, true);
389             ystr("error");
390             ystr(errormessage);
391             ystr("input");
392             ystr(input);
393             ystr("errorposition");
394             ystr(position);
395             y(map_close);
396
397             free(position);
398             free(errormessage);
399             clear_stack();
400             break;
401         }
402     }
403
404     y(array_close);
405
406     return &command_output;
407 }
408
409 /*******************************************************************************
410  * Code for building the stand-alone binary test.commands_parser which is used
411  * by t/187-commands-parser.t.
412  ******************************************************************************/
413
414 #ifdef TEST_PARSER
415
416 /*
417  * Logs the given message to stdout while prefixing the current time to it,
418  * but only if debug logging was activated.
419  * This is to be called by DLOG() which includes filename/linenumber
420  *
421  */
422 void debuglog(char *fmt, ...) {
423     va_list args;
424
425     va_start(args, fmt);
426     fprintf(stdout, "# ");
427     vfprintf(stdout, fmt, args);
428     va_end(args);
429 }
430
431 void errorlog(char *fmt, ...) {
432     va_list args;
433
434     va_start(args, fmt);
435     vfprintf(stderr, fmt, args);
436     va_end(args);
437 }
438
439 int main(int argc, char *argv[]) {
440     if (argc < 2) {
441         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
442         return 1;
443     }
444     parse_config(argv[1]);
445 }
446 #endif