i3
commands_parser.c
Go to the documentation of this file.
1/*
2 * vim:ts=4:sw=4:expandtab
3 *
4 * i3 - an improved tiling window manager
5 * © 2009 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 across 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 "all.h"
27
28// Macros to make the YAJL API a bit easier to use.
29#define y(x, ...) (command_output.json_gen != NULL ? yajl_gen_##x(command_output.json_gen, ##__VA_ARGS__) : 0)
30#define ystr(str) (command_output.json_gen != NULL ? yajl_gen_string(command_output.json_gen, (unsigned char *)str, strlen(str)) : 0)
31
32/*******************************************************************************
33 * The data structures used for parsing. Essentially the current state and a
34 * list of tokens for that state.
35 *
36 * The GENERATED_* files are generated by generate-commands-parser.pl with the
37 * input parser-specs/commands.spec.
38 ******************************************************************************/
39
40#include "GENERATED_command_enums.h"
41
42typedef struct token {
43 char *name;
45 /* This might be __CALL */
46 cmdp_state next_state;
47 union {
51
56
57#include "GENERATED_command_tokens.h"
58
59/*
60 * Pushes a string (identified by 'identifier') on the stack. We simply use a
61 * single array, since the number of entries we have to store is very small.
62 *
63 */
64static void push_string(struct stack *stack, const char *identifier, char *str) {
65 for (int c = 0; c < 10; c++) {
66 if (stack->stack[c].identifier != NULL) {
67 continue;
68 }
69 /* Found a free slot, let’s store it here. */
70 stack->stack[c].identifier = identifier;
71 stack->stack[c].val.str = str;
72 stack->stack[c].type = STACK_STR;
73 return;
74 }
75
76 /* When we arrive here, the stack is full. This should not happen and
77 * means there’s either a bug in this parser or the specification
78 * contains a command with more than 10 identified tokens. */
79 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
80 "in the code, or a new command which contains more than "
81 "10 identified tokens.\n");
82 exit(EXIT_FAILURE);
83}
84
85// TODO move to a common util
86static void push_long(struct stack *stack, const char *identifier, long num) {
87 for (int c = 0; c < 10; c++) {
88 if (stack->stack[c].identifier != NULL) {
89 continue;
90 }
91
92 stack->stack[c].identifier = identifier;
93 stack->stack[c].val.num = num;
94 stack->stack[c].type = STACK_LONG;
95 return;
96 }
97
98 /* When we arrive here, the stack is full. This should not happen and
99 * means there’s either a bug in this parser or the specification
100 * contains a command with more than 10 identified tokens. */
101 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
102 "in the code, or a new command which contains more than "
103 "10 identified tokens.\n");
104 exit(EXIT_FAILURE);
105}
106
107// TODO move to a common util
108static const char *get_string(struct stack *stack, const char *identifier) {
109 for (int c = 0; c < 10; c++) {
110 if (stack->stack[c].identifier == NULL) {
111 break;
112 }
113 if (strcmp(identifier, stack->stack[c].identifier) == 0) {
114 return stack->stack[c].val.str;
115 }
116 }
117 return NULL;
118}
119
120// TODO move to a common util
121static long get_long(struct stack *stack, const char *identifier) {
122 for (int c = 0; c < 10; c++) {
123 if (stack->stack[c].identifier == NULL) {
124 break;
125 }
126 if (strcmp(identifier, stack->stack[c].identifier) == 0) {
127 return stack->stack[c].val.num;
128 }
129 }
130
131 return 0;
132}
133
134// TODO move to a common util
135static void clear_stack(struct stack *stack) {
136 for (int c = 0; c < 10; c++) {
137 if (stack->stack[c].type == STACK_STR) {
138 free(stack->stack[c].val.str);
139 }
140 stack->stack[c].identifier = NULL;
141 stack->stack[c].val.str = NULL;
142 stack->stack[c].val.num = 0;
143 }
144}
145
146/*******************************************************************************
147 * The parser itself.
148 ******************************************************************************/
149
150static cmdp_state state;
152/*******************************************************************************
153 * The (small) stack where identified literals are stored during the parsing
154 * of a single command (like $workspace).
155 ******************************************************************************/
156static struct stack stack;
159
160#include "GENERATED_command_call.h"
161
162static void next_state(const cmdp_token *token) {
163 if (token->next_state == __CALL) {
169 /* If any subcommand requires a tree_render(), we need to make the
170 * whole parser result request a tree_render(). */
173 }
175 return;
176 }
177
179 if (state == INITIAL) {
181 }
182}
183
184/*
185 * Parses a string (or word, if as_word is true). Extracted out of
186 * parse_command so that it can be used in src/workspace.c for interpreting
187 * workspace commands.
188 *
189 */
190char *parse_string(const char **walk, bool as_word) {
191 const char *beginning = *walk;
192 /* Handle quoted strings (or words). */
193 if (**walk == '"') {
194 beginning++;
195 (*walk)++;
196 for (; **walk != '\0' && **walk != '"'; (*walk)++) {
197 if (**walk == '\\' && *(*walk + 1) != '\0') {
198 (*walk)++;
199 }
200 }
201 } else {
202 if (!as_word) {
203 /* For a string (starting with 's'), the delimiters are
204 * comma (,) and semicolon (;) which introduce a new
205 * operation or command, respectively. Also, newlines
206 * end a command. */
207 while (**walk != ';' && **walk != ',' &&
208 **walk != '\0' && **walk != '\r' &&
209 **walk != '\n') {
210 (*walk)++;
211 }
212 } else {
213 /* For a word, the delimiters are white space (' ' or
214 * '\t'), closing square bracket (]), comma (,) and
215 * semicolon (;). */
216 while (**walk != ' ' && **walk != '\t' &&
217 **walk != ']' && **walk != ',' &&
218 **walk != ';' && **walk != '\r' &&
219 **walk != '\n' && **walk != '\0') {
220 (*walk)++;
221 }
222 }
223 }
224 if (*walk == beginning) {
225 return NULL;
226 }
227
228 char *str = scalloc(*walk - beginning + 1, 1);
229 /* We copy manually to handle escaping of characters. */
230 int inpos, outpos;
231 for (inpos = 0, outpos = 0;
232 inpos < (*walk - beginning);
233 inpos++, outpos++) {
234 /* We only handle escaped double quotes and backslashes to not break
235 * backwards compatibility with people using \w in regular expressions
236 * etc. */
237 if (beginning[inpos] == '\\' && (beginning[inpos + 1] == '"' || beginning[inpos + 1] == '\\')) {
238 inpos++;
239 }
240 str[outpos] = beginning[inpos];
241 }
242
243 return str;
244}
245
246/*
247 * Parses and executes the given command. If a caller-allocated yajl_gen is
248 * passed, a json reply will be generated in the format specified by the ipc
249 * protocol. Pass NULL if no json reply is required.
250 *
251 * Free the returned CommandResult with command_result_free().
252 */
253CommandResult *parse_command(const char *input, yajl_gen gen, ipc_client *client) {
254 DLOG("COMMAND: *%.4000s*\n", input);
255 state = INITIAL;
256 CommandResult *result = scalloc(1, sizeof(CommandResult));
257
259
260 /* A YAJL JSON generator used for formatting replies. */
262
263 y(array_open);
265
266 const char *walk = input;
267 const size_t len = strlen(input);
268 int c;
269 const cmdp_token *token;
270 bool token_handled;
271
272// TODO: make this testable
273#ifndef TEST_PARSER
275#endif
276
277 /* The "<=" operator is intentional: We also handle the terminating 0-byte
278 * explicitly by looking for an 'end' token. */
279 while ((size_t)(walk - input) <= len) {
280 /* skip whitespace and newlines before every token */
281 while ((*walk == ' ' || *walk == '\t' ||
282 *walk == '\r' || *walk == '\n') &&
283 *walk != '\0') {
284 walk++;
285 }
286
287 cmdp_token_ptr *ptr = &(tokens[state]);
288 token_handled = false;
289 for (c = 0; c < ptr->n; c++) {
290 token = &(ptr->array[c]);
291
292 /* A literal. */
293 if (token->name[0] == '\'') {
294 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
295 if (token->identifier != NULL) {
297 }
298 walk += strlen(token->name) - 1;
300 token_handled = true;
301 break;
302 }
303 continue;
304 }
305
306 if (strcmp(token->name, "number") == 0) {
307 /* Handle numbers. We only accept decimal numbers for now. */
308 char *end = NULL;
309 errno = 0;
310 long int num = strtol(walk, &end, 10);
311 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
312 (errno != 0 && num == 0)) {
313 continue;
314 }
315
316 /* No valid numbers found */
317 if (end == walk) {
318 continue;
319 }
320
321 if (token->identifier != NULL) {
323 }
324
325 /* Set walk to the first non-number character */
326 walk = end;
328 token_handled = true;
329 break;
330 }
331
332 if (strcmp(token->name, "string") == 0 ||
333 strcmp(token->name, "word") == 0) {
334 char *str = parse_string(&walk, (token->name[0] != 's'));
335 if (str != NULL) {
336 if (token->identifier) {
338 }
339 /* If we are at the end of a quoted string, skip the ending
340 * double quote. */
341 if (*walk == '"') {
342 walk++;
343 }
345 token_handled = true;
346 break;
347 }
348 }
349
350 if (strcmp(token->name, "end") == 0) {
351 if (*walk == '\0' || *walk == ',' || *walk == ';') {
353 token_handled = true;
354 /* To make sure we start with an appropriate matching
355 * datastructure for commands which do *not* specify any
356 * criteria, we re-initialize the criteria system after
357 * every command. */
358// TODO: make this testable
359#ifndef TEST_PARSER
360 if (*walk == '\0' || *walk == ';') {
362 }
363#endif
364 walk++;
365 break;
366 }
367 }
368 }
369
370 if (!token_handled) {
371 /* Figure out how much memory we will need to fill in the names of
372 * all tokens afterwards. */
373 int tokenlen = 0;
374 for (c = 0; c < ptr->n; c++) {
375 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
376 }
377
378 /* Build up a decent error message. We include the problem, the
379 * full input, and underline the position where the parser
380 * currently is. */
381 char *errormessage;
382 char *possible_tokens = smalloc(tokenlen + 1);
383 char *tokenwalk = possible_tokens;
384 for (c = 0; c < ptr->n; c++) {
385 token = &(ptr->array[c]);
386 if (token->name[0] == '\'') {
387 /* A literal is copied to the error message enclosed with
388 * single quotes. */
389 *tokenwalk++ = '\'';
390 strcpy(tokenwalk, token->name + 1);
391 tokenwalk += strlen(token->name + 1);
392 *tokenwalk++ = '\'';
393 } else {
394 /* Any other token is copied to the error message enclosed
395 * with angle brackets. */
396 *tokenwalk++ = '<';
397 strcpy(tokenwalk, token->name);
398 tokenwalk += strlen(token->name);
399 *tokenwalk++ = '>';
400 }
401 if (c < (ptr->n - 1)) {
402 *tokenwalk++ = ',';
403 *tokenwalk++ = ' ';
404 }
405 }
406 *tokenwalk = '\0';
407 sasprintf(&errormessage, "Expected one of these tokens: %s",
408 possible_tokens);
409 free(possible_tokens);
410
411 /* Contains the same amount of characters as 'input' has, but with
412 * the unparsable part highlighted using ^ characters. */
413 char *position = smalloc(len + 1);
414 for (const char *copywalk = input; *copywalk != '\0'; copywalk++) {
415 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
416 }
417 position[len] = '\0';
418
419 ELOG("%s\n", errormessage);
420 ELOG("Your command: %s\n", input);
421 ELOG(" %s\n", position);
422
423 result->parse_error = true;
424 result->error_message = errormessage;
425
426 /* Format this error message as a JSON reply. */
427 y(map_open);
428 ystr("success");
429 y(bool, false);
430 /* We set parse_error to true to distinguish this from other
431 * errors. i3-nagbar is spawned upon keypresses only for parser
432 * errors. */
433 ystr("parse_error");
434 y(bool, true);
435 ystr("error");
436 ystr(errormessage);
437 ystr("input");
438 ystr(input);
439 ystr("errorposition");
440 ystr(position);
441 y(map_close);
442
443 free(position);
445 break;
446 }
447 }
448
449 y(array_close);
450
452 return result;
453}
454
455/*
456 * Frees a CommandResult
457 */
459 if (result == NULL) {
460 return;
461 }
462
463 FREE(result->error_message);
464 FREE(result);
465}
466
467/*******************************************************************************
468 * Code for building the stand-alone binary test.commands_parser which is used
469 * by t/187-commands-parser.t.
470 ******************************************************************************/
471
472#ifdef TEST_PARSER
473
474/*
475 * Logs the given message to stdout while prefixing the current time to it,
476 * but only if debug logging was activated.
477 * This is to be called by DLOG() which includes filename/linenumber
478 *
479 */
480void debuglog(char *fmt, ...) {
481 va_list args;
482
483 va_start(args, fmt);
484 fprintf(stdout, "# ");
485 vfprintf(stdout, fmt, args);
486 va_end(args);
487}
488
489void errorlog(char *fmt, ...) {
490 va_list args;
491
492 va_start(args, fmt);
493 vfprintf(stderr, fmt, args);
494 va_end(args);
495}
496
497int main(int argc, char *argv[]) {
498 if (argc < 2) {
499 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
500 return 1;
501 }
502 yajl_gen gen = yajl_gen_alloc(NULL);
503
504 CommandResult *result = parse_command(argv[1], gen, NULL);
505
506 command_result_free(result);
507
508 yajl_gen_free(gen);
509}
510#endif
#define y(x,...)
struct tokenptr cmdp_token_ptr
CommandResult * parse_command(const char *input, yajl_gen gen, ipc_client *client)
Parses and executes the given command.
static Match current_match
static void push_long(struct stack *stack, const char *identifier, long num)
struct token cmdp_token
static void push_string(struct stack *stack, const char *identifier, char *str)
#define ystr(str)
static const char * get_string(struct stack *stack, const char *identifier)
static long get_long(struct stack *stack, const char *identifier)
char * parse_string(const char **walk, bool as_word)
Parses a string (or word, if as_word is true).
static struct CommandResultIR command_output
static void clear_stack(struct stack *stack)
static struct CommandResultIR subcommand_output
void command_result_free(CommandResult *result)
Frees a CommandResult.
static cmdp_state state
static void next_state(const cmdp_token *token)
void errorlog(char *fmt,...)
Definition log.c:325
void debuglog(char *fmt,...)
Definition log.c:348
int main(int argc, char *argv[])
Definition main.c:279
void cmd_criteria_init(I3_CMD)
Initializes the specified 'Match' data structure and the initial state of commands....
#define DLOG(fmt,...)
Definition libi3.h:105
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
#define ELOG(fmt,...)
Definition libi3.h:100
void * scalloc(size_t num, size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
#define FREE(pointer)
Definition util.h:47
char * name
char * identifier
union token::@0 extra
cmdp_state next_state
uint16_t call_identifier
cmdp_token * array
Holds an intermediate representation of the result of a call to any command.
ipc_client * client
A struct that contains useful information about the result of a command as a whole (e....
union stack_entry::@3 val
enum stack_entry::@2 type
const char * identifier
struct stack_entry stack[10]
A "match" is a data structure which acts like a mask or expression to match certain windows or not.
Definition data.h:529