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