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