2 #define I3__FILE__ "commands_parser.c"
4 * vim:ts=4:sw=4:expandtab
6 * i3 - an improved dynamic tiling window manager
7 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
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').
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.
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()).
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).
37 // Macros to make the YAJL API a bit easier to use.
38 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
39 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
41 /*******************************************************************************
42 * The data structures used for parsing. Essentially the current state and a
43 * list of tokens for that state.
45 * The GENERATED_* files are generated by generate-commands-parser.pl with the
46 * input parser-specs/commands.spec.
47 ******************************************************************************/
49 #include "GENERATED_command_enums.h"
51 typedef struct token {
54 /* This might be __CALL */
55 cmdp_state next_state;
57 uint16_t call_identifier;
61 typedef struct tokenptr {
66 #include "GENERATED_command_tokens.h"
68 /*******************************************************************************
69 * The (small) stack where identified literals are stored during the parsing
70 * of a single command (like $workspace).
71 ******************************************************************************/
74 /* Just a pointer, not dynamically allocated. */
75 const char *identifier;
79 /* 10 entries should be enough for everybody. */
80 static struct stack_entry stack[10];
83 * Pushes a string (identified by 'identifier') on the stack. We simply use a
84 * single array, since the number of entries we have to store is very small.
87 static void push_string(const char *identifier, char *str) {
88 for (int c = 0; c < 10; c++) {
89 if (stack[c].identifier != NULL)
91 /* Found a free slot, let’s store it here. */
92 stack[c].identifier = identifier;
97 /* When we arrive here, the stack is full. This should not happen and
98 * means there’s either a bug in this parser or the specification
99 * contains a command with more than 10 identified tokens. */
100 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
101 "in the code, or a new command which contains more than "
102 "10 identified tokens.\n");
106 // XXX: ideally, this would be const char. need to check if that works with all
108 static char *get_string(const char *identifier) {
109 for (int c = 0; c < 10; c++) {
110 if (stack[c].identifier == NULL)
112 if (strcmp(identifier, stack[c].identifier) == 0)
118 static void clear_stack(void) {
119 for (int c = 0; c < 10; c++) {
120 if (stack[c].str != NULL)
122 stack[c].identifier = NULL;
127 // TODO: remove this if it turns out we don’t need it for testing.
129 /*******************************************************************************
130 * A dynamically growing linked list which holds the criteria for the current
132 ******************************************************************************/
134 typedef struct criterion {
138 TAILQ_ENTRY(criterion) criteria;
141 static TAILQ_HEAD(criteria_head, criterion) criteria =
142 TAILQ_HEAD_INITIALIZER(criteria);
145 * Stores the given type/value in the list of criteria.
146 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
149 static void push_criterion(void *unused_criteria, const char *type,
151 struct criterion *criterion = malloc(sizeof(struct criterion));
152 criterion->type = strdup(type);
153 criterion->value = strdup(value);
154 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
158 * Clears the criteria linked list.
159 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
162 static void clear_criteria(void *unused_criteria) {
163 struct criterion *criterion;
164 while (!TAILQ_EMPTY(&criteria)) {
165 criterion = TAILQ_FIRST(&criteria);
166 free(criterion->type);
167 free(criterion->value);
168 TAILQ_REMOVE(&criteria, criterion, criteria);
174 /*******************************************************************************
176 ******************************************************************************/
178 static cmdp_state state;
180 static Match current_match;
182 static struct CommandResultIR subcommand_output;
183 static struct CommandResultIR command_output;
185 #include "GENERATED_command_call.h"
188 static void next_state(const cmdp_token *token) {
189 if (token->next_state == __CALL) {
190 subcommand_output.json_gen = command_output.json_gen;
191 subcommand_output.needs_tree_render = false;
192 GENERATED_call(token->extra.call_identifier, &subcommand_output);
193 state = subcommand_output.next_state;
194 /* If any subcommand requires a tree_render(), we need to make the
195 * whole parser result request a tree_render(). */
196 if (subcommand_output.needs_tree_render)
197 command_output.needs_tree_render = true;
202 state = token->next_state;
203 if (state == INITIAL) {
208 struct CommandResultIR *parse_command(const char *input) {
209 DLOG("COMMAND: *%s*\n", input);
212 /* A YAJL JSON generator used for formatting replies. */
213 command_output.json_gen = yajl_gen_alloc(NULL);
216 command_output.needs_tree_render = false;
218 const char *walk = input;
219 const size_t len = strlen(input);
221 const cmdp_token *token;
224 // TODO: make this testable
226 cmd_criteria_init(¤t_match, &subcommand_output);
229 /* The "<=" operator is intentional: We also handle the terminating 0-byte
230 * explicitly by looking for an 'end' token. */
231 while ((size_t)(walk - input) <= len) {
232 /* skip whitespace and newlines before every token */
233 while ((*walk == ' ' || *walk == '\t' ||
234 *walk == '\r' || *walk == '\n') && *walk != '\0')
237 cmdp_token_ptr *ptr = &(tokens[state]);
238 token_handled = false;
239 for (c = 0; c < ptr->n; c++) {
240 token = &(ptr->array[c]);
243 if (token->name[0] == '\'') {
244 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
245 if (token->identifier != NULL)
246 push_string(token->identifier, sstrdup(token->name + 1));
247 walk += strlen(token->name) - 1;
249 token_handled = true;
255 if (strcmp(token->name, "string") == 0 ||
256 strcmp(token->name, "word") == 0) {
257 const char *beginning = walk;
258 /* Handle quoted strings (or words). */
262 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
265 if (token->name[0] == 's') {
266 /* For a string (starting with 's'), the delimiters are
267 * comma (,) and semicolon (;) which introduce a new
268 * operation or command, respectively. Also, newlines
270 while (*walk != ';' && *walk != ',' &&
271 *walk != '\0' && *walk != '\r' &&
275 /* For a word, the delimiters are white space (' ' or
276 * '\t'), closing square bracket (]), comma (,) and
278 while (*walk != ' ' && *walk != '\t' &&
279 *walk != ']' && *walk != ',' &&
280 *walk != ';' && *walk != '\r' &&
281 *walk != '\n' && *walk != '\0')
285 if (walk != beginning) {
286 char *str = scalloc(walk-beginning + 1);
287 /* We copy manually to handle escaping of characters. */
289 for (inpos = 0, outpos = 0;
290 inpos < (walk-beginning);
292 /* We only handle escaped double quotes to not break
293 * backwards compatibility with people using \w in
294 * regular expressions etc. */
295 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
297 str[outpos] = beginning[inpos];
299 if (token->identifier)
300 push_string(token->identifier, str);
301 /* If we are at the end of a quoted string, skip the ending
306 token_handled = true;
311 if (strcmp(token->name, "end") == 0) {
312 if (*walk == '\0' || *walk == ',' || *walk == ';') {
314 token_handled = true;
315 /* To make sure we start with an appropriate matching
316 * datastructure for commands which do *not* specify any
317 * criteria, we re-initialize the criteria system after
319 // TODO: make this testable
321 if (*walk == '\0' || *walk == ';')
322 cmd_criteria_init(¤t_match, &subcommand_output);
330 if (!token_handled) {
331 /* Figure out how much memory we will need to fill in the names of
332 * all tokens afterwards. */
334 for (c = 0; c < ptr->n; c++)
335 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
337 /* Build up a decent error message. We include the problem, the
338 * full input, and underline the position where the parser
341 char *possible_tokens = smalloc(tokenlen + 1);
342 char *tokenwalk = possible_tokens;
343 for (c = 0; c < ptr->n; c++) {
344 token = &(ptr->array[c]);
345 if (token->name[0] == '\'') {
346 /* A literal is copied to the error message enclosed with
349 strcpy(tokenwalk, token->name + 1);
350 tokenwalk += strlen(token->name + 1);
353 /* Any other token is copied to the error message enclosed
354 * with angle brackets. */
356 strcpy(tokenwalk, token->name);
357 tokenwalk += strlen(token->name);
360 if (c < (ptr->n - 1)) {
366 sasprintf(&errormessage, "Expected one of these tokens: %s",
368 free(possible_tokens);
370 /* Contains the same amount of characters as 'input' has, but with
371 * the unparseable part highlighted using ^ characters. */
372 char *position = smalloc(len + 1);
373 for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
374 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
375 position[len] = '\0';
377 ELOG("%s\n", errormessage);
378 ELOG("Your command: %s\n", input);
379 ELOG(" %s\n", position);
381 /* Format this error message as a JSON reply. */
385 /* We set parse_error to true to distinguish this from other
386 * errors. i3-nagbar is spawned upon keypresses only for parser
394 ystr("errorposition");
407 return &command_output;
410 /*******************************************************************************
411 * Code for building the stand-alone binary test.commands_parser which is used
412 * by t/187-commands-parser.t.
413 ******************************************************************************/
418 * Logs the given message to stdout while prefixing the current time to it,
419 * but only if debug logging was activated.
420 * This is to be called by DLOG() which includes filename/linenumber
423 void debuglog(char *fmt, ...) {
427 fprintf(stdout, "# ");
428 vfprintf(stdout, fmt, args);
432 void errorlog(char *fmt, ...) {
436 vfprintf(stderr, fmt, args);
440 int main(int argc, char *argv[]) {
442 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
445 parse_command(argv[1]);