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