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