2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
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').
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 accross so far.
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()).
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).
35 /*******************************************************************************
36 * The data structures used for parsing. Essentially the current state and a
37 * list of tokens for that state.
39 * The GENERATED_* files are generated by generate-commands-parser.pl with the
40 * input parser-specs/commands.spec.
41 ******************************************************************************/
43 #include "GENERATED_enums.h"
45 typedef struct token {
48 /* This might be __CALL */
49 cmdp_state next_state;
51 uint16_t call_identifier;
55 typedef struct tokenptr {
60 #include "GENERATED_tokens.h"
62 /*******************************************************************************
63 * The (small) stack where identified literals are stored during the parsing
64 * of a single command (like $workspace).
65 ******************************************************************************/
68 /* Just a pointer, not dynamically allocated. */
69 const char *identifier;
73 /* 10 entries should be enough for everybody. */
74 static struct stack_entry stack[10];
77 * Pushes a string (identified by 'identifier') on the stack. We simply use a
78 * single array, since the number of entries we have to store is very small.
81 static void push_string(const char *identifier, char *str) {
82 for (int c = 0; c < 10; c++) {
83 if (stack[c].identifier != NULL)
85 /* Found a free slot, let’s store it here. */
86 stack[c].identifier = identifier;
91 /* When we arrive here, the stack is full. This should not happen and
92 * means there’s either a bug in this parser or the specification
93 * contains a command with more than 10 identified tokens. */
94 printf("argh! stack full\n");
98 // XXX: ideally, this would be const char. need to check if that works with all
100 static char *get_string(const char *identifier) {
101 DLOG("Getting string %s from stack...\n", identifier);
102 for (int c = 0; c < 10; c++) {
103 if (stack[c].identifier == NULL)
105 if (strcmp(identifier, stack[c].identifier) == 0)
111 static void clear_stack() {
112 DLOG("clearing stack.\n");
113 for (int c = 0; c < 10; c++) {
114 if (stack[c].str != NULL)
116 stack[c].identifier = NULL;
121 // TODO: remove this if it turns out we don’t need it for testing.
123 /*******************************************************************************
124 * A dynamically growing linked list which holds the criteria for the current
126 ******************************************************************************/
128 typedef struct criterion {
132 TAILQ_ENTRY(criterion) criteria;
135 static TAILQ_HEAD(criteria_head, criterion) criteria =
136 TAILQ_HEAD_INITIALIZER(criteria);
139 * Stores the given type/value in the list of criteria.
140 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
143 static void push_criterion(void *unused_criteria, const char *type,
145 struct criterion *criterion = malloc(sizeof(struct criterion));
146 criterion->type = strdup(type);
147 criterion->value = strdup(value);
148 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
152 * Clears the criteria linked list.
153 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
156 static void clear_criteria(void *unused_criteria) {
157 struct criterion *criterion;
158 while (!TAILQ_EMPTY(&criteria)) {
159 criterion = TAILQ_FIRST(&criteria);
160 free(criterion->type);
161 free(criterion->value);
162 TAILQ_REMOVE(&criteria, criterion, criteria);
168 /*******************************************************************************
170 ******************************************************************************/
172 static cmdp_state state;
174 static Match current_match;
176 static struct CommandResult subcommand_output;
177 static struct CommandResult command_output;
179 #include "GENERATED_call.h"
182 static void next_state(const cmdp_token *token) {
183 if (token->next_state == __CALL) {
184 DLOG("should call stuff, yay. call_id = %d\n",
185 token->extra.call_identifier);
186 subcommand_output.json_output = NULL;
187 subcommand_output.needs_tree_render = false;
188 GENERATED_call(token->extra.call_identifier, &subcommand_output);
189 if (subcommand_output.json_output) {
190 DLOG("Subcommand JSON output: %s\n", subcommand_output.json_output);
192 /* In the beginning, the contents of json_output are "[\0". */
193 if (command_output.json_output[1] == '\0')
194 sasprintf(&buffer, "%s%s", command_output.json_output, subcommand_output.json_output);
195 else sasprintf(&buffer, "%s, %s", command_output.json_output, subcommand_output.json_output);
196 free(command_output.json_output);
197 command_output.json_output = buffer;
198 DLOG("merged command JSON output: %s\n", command_output.json_output);
200 /* If any subcommand requires a tree_render(), we need to make the
201 * whole parser result request a tree_render(). */
202 if (subcommand_output.needs_tree_render)
203 command_output.needs_tree_render = true;
208 state = token->next_state;
209 if (state == INITIAL) {
214 /* TODO: Return parsing errors via JSON. */
215 struct CommandResult *parse_command(const char *input) {
216 DLOG("new parser handling: %s\n", input);
218 command_output.json_output = sstrdup("[");
219 command_output.needs_tree_render = false;
221 const char *walk = input;
222 const size_t len = strlen(input);
224 const cmdp_token *token;
227 // TODO: make this testable
229 cmd_criteria_init(¤t_match, &subcommand_output);
232 /* The "<=" operator is intentional: We also handle the terminating 0-byte
233 * explicitly by looking for an 'end' token. */
234 while ((walk - input) <= len) {
235 /* skip whitespace and newlines before every token */
236 while ((*walk == ' ' || *walk == '\t' ||
237 *walk == '\r' || *walk == '\n') && *walk != '\0')
240 DLOG("remaining input = %s\n", walk);
242 cmdp_token_ptr *ptr = &(tokens[state]);
243 token_handled = false;
244 for (c = 0; c < ptr->n; c++) {
245 token = &(ptr->array[c]);
246 DLOG("trying token %d = %s\n", c, token->name);
249 if (token->name[0] == '\'') {
251 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
252 DLOG("found literal, moving to next state\n");
253 if (token->identifier != NULL)
254 push_string(token->identifier, sstrdup(token->name + 1));
255 walk += strlen(token->name) - 1;
257 token_handled = true;
263 if (strcmp(token->name, "string") == 0 ||
264 strcmp(token->name, "word") == 0) {
265 DLOG("parsing this as a string\n");
266 const char *beginning = walk;
267 /* Handle quoted strings (or words). */
271 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
274 if (token->name[0] == 's') {
275 /* For a string (starting with 's'), the delimiters are
276 * comma (,) and semicolon (;) which introduce a new
277 * operation or command, respectively. Also, newlines
279 while (*walk != ';' && *walk != ',' &&
280 *walk != '\0' && *walk != '\r' &&
284 /* For a word, the delimiters are white space (' ' or
285 * '\t'), closing square bracket (]), comma (,) and
287 while (*walk != ' ' && *walk != '\t' &&
288 *walk != ']' && *walk != ',' &&
289 *walk != ';' && *walk != '\r' &&
290 *walk != '\n' && *walk != '\0')
294 if (walk != beginning) {
295 char *str = scalloc(walk-beginning + 1);
296 /* We copy manually to handle escaping of characters. */
298 for (inpos = 0, outpos = 0;
299 inpos < (walk-beginning);
301 /* We only handle escaped double quotes to not break
302 * backwards compatibility with people using \w in
303 * regular expressions etc. */
304 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
306 str[outpos] = beginning[inpos];
308 if (token->identifier)
309 push_string(token->identifier, str);
310 DLOG("str is \"%s\"\n", str);
311 /* If we are at the end of a quoted string, skip the ending
316 token_handled = true;
321 if (strcmp(token->name, "end") == 0) {
322 DLOG("checking for the end token.\n");
323 if (*walk == '\0' || *walk == ',' || *walk == ';') {
324 DLOG("yes, indeed. end\n");
326 token_handled = true;
327 /* To make sure we start with an appropriate matching
328 * datastructure for commands which do *not* specify any
329 * criteria, we re-initialize the criteria system after
331 // TODO: make this testable
333 if (*walk == '\0' || *walk == ';')
334 cmd_criteria_init(¤t_match, &subcommand_output);
342 if (!token_handled) {
343 /* Figure out how much memory we will need to fill in the names of
344 * all tokens afterwards. */
346 for (c = 0; c < ptr->n; c++)
347 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
349 /* Build up a decent error message. We include the problem, the
350 * full input, and underline the position where the parser
353 char *possible_tokens = smalloc(tokenlen + 1);
354 char *tokenwalk = possible_tokens;
355 for (c = 0; c < ptr->n; c++) {
356 token = &(ptr->array[c]);
357 if (token->name[0] == '\'') {
358 /* A literal is copied to the error message enclosed with
361 strcpy(tokenwalk, token->name + 1);
362 tokenwalk += strlen(token->name + 1);
365 /* Any other token is copied to the error message enclosed
366 * with angle brackets. */
368 strcpy(tokenwalk, token->name);
369 tokenwalk += strlen(token->name);
372 if (c < (ptr->n - 1)) {
378 sasprintf(&errormessage, "Expected one of these tokens: %s",
380 free(possible_tokens);
382 /* Contains the same amount of characters as 'input' has, but with
383 * the unparseable part highlighted using ^ characters. */
384 char *position = smalloc(len + 1);
385 for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
386 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
387 position[len] = '\0';
389 printf("%s\n", errormessage);
390 printf("Your command: %s\n", input);
391 printf(" %s\n", position);
400 sasprintf(&buffer, "%s]", command_output.json_output);
401 free(command_output.json_output);
402 command_output.json_output = buffer;
403 DLOG("command_output.json_output = %s\n", command_output.json_output);
404 DLOG("command_output.needs_tree_render = %d\n", command_output.needs_tree_render);
405 return &command_output;
408 /*******************************************************************************
409 * Code for building the stand-alone binary test.commands_parser which is used
410 * by t/187-commands-parser.t.
411 ******************************************************************************/
416 * Logs the given message to stdout while prefixing the current time to it,
417 * but only if the corresponding debug loglevel was activated.
418 * This is to be called by DLOG() which includes filename/linenumber
421 void debuglog(uint64_t lev, char *fmt, ...) {
425 fprintf(stderr, "# ");
426 vfprintf(stderr, fmt, args);
430 int main(int argc, char *argv[]) {
432 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
435 parse_command(argv[1]);