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