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 // Macros to make the YAJL API a bit easier to use.
36 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
37 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
39 /*******************************************************************************
40 * The data structures used for parsing. Essentially the current state and a
41 * list of tokens for that state.
43 * The GENERATED_* files are generated by generate-commands-parser.pl with the
44 * input parser-specs/commands.spec.
45 ******************************************************************************/
47 #include "GENERATED_enums.h"
49 typedef struct token {
52 /* This might be __CALL */
53 cmdp_state next_state;
55 uint16_t call_identifier;
59 typedef struct tokenptr {
64 #include "GENERATED_tokens.h"
66 /*******************************************************************************
67 * The (small) stack where identified literals are stored during the parsing
68 * of a single command (like $workspace).
69 ******************************************************************************/
72 /* Just a pointer, not dynamically allocated. */
73 const char *identifier;
77 /* 10 entries should be enough for everybody. */
78 static struct stack_entry stack[10];
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.
85 static void push_string(const char *identifier, char *str) {
86 for (int c = 0; c < 10; c++) {
87 if (stack[c].identifier != NULL)
89 /* Found a free slot, let’s store it here. */
90 stack[c].identifier = identifier;
95 /* When we arrive here, the stack is full. This should not happen and
96 * means there’s either a bug in this parser or the specification
97 * contains a command with more than 10 identified tokens. */
98 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
99 "in the code, or a new command which contains more than "
100 "10 identified tokens.\n");
104 // XXX: ideally, this would be const char. need to check if that works with all
106 static char *get_string(const char *identifier) {
107 for (int c = 0; c < 10; c++) {
108 if (stack[c].identifier == NULL)
110 if (strcmp(identifier, stack[c].identifier) == 0)
116 static void clear_stack(void) {
117 for (int c = 0; c < 10; c++) {
118 if (stack[c].str != NULL)
120 stack[c].identifier = NULL;
125 // TODO: remove this if it turns out we don’t need it for testing.
127 /*******************************************************************************
128 * A dynamically growing linked list which holds the criteria for the current
130 ******************************************************************************/
132 typedef struct criterion {
136 TAILQ_ENTRY(criterion) criteria;
139 static TAILQ_HEAD(criteria_head, criterion) criteria =
140 TAILQ_HEAD_INITIALIZER(criteria);
143 * Stores the given type/value in the list of criteria.
144 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
147 static void push_criterion(void *unused_criteria, const char *type,
149 struct criterion *criterion = malloc(sizeof(struct criterion));
150 criterion->type = strdup(type);
151 criterion->value = strdup(value);
152 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
156 * Clears the criteria linked list.
157 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
160 static void clear_criteria(void *unused_criteria) {
161 struct criterion *criterion;
162 while (!TAILQ_EMPTY(&criteria)) {
163 criterion = TAILQ_FIRST(&criteria);
164 free(criterion->type);
165 free(criterion->value);
166 TAILQ_REMOVE(&criteria, criterion, criteria);
172 /*******************************************************************************
174 ******************************************************************************/
176 static cmdp_state state;
178 static Match current_match;
180 static struct CommandResult subcommand_output;
181 static struct CommandResult command_output;
183 #include "GENERATED_call.h"
186 static void next_state(const cmdp_token *token) {
187 if (token->next_state == __CALL) {
188 subcommand_output.json_gen = command_output.json_gen;
189 subcommand_output.needs_tree_render = false;
190 GENERATED_call(token->extra.call_identifier, &subcommand_output);
191 /* If any subcommand requires a tree_render(), we need to make the
192 * whole parser result request a tree_render(). */
193 if (subcommand_output.needs_tree_render)
194 command_output.needs_tree_render = true;
199 state = token->next_state;
200 if (state == INITIAL) {
205 /* TODO: Return parsing errors via JSON. */
206 struct CommandResult *parse_command(const char *input) {
207 DLOG("COMMAND: *%s*\n", input);
210 /* A YAJL JSON generator used for formatting replies. */
212 command_output.json_gen = yajl_gen_alloc(NULL);
214 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
218 command_output.needs_tree_render = false;
220 const char *walk = input;
221 const size_t len = strlen(input);
223 const cmdp_token *token;
226 // TODO: make this testable
228 cmd_criteria_init(¤t_match, &subcommand_output);
231 /* The "<=" operator is intentional: We also handle the terminating 0-byte
232 * explicitly by looking for an 'end' token. */
233 while ((walk - input) <= len) {
234 /* skip whitespace and newlines before every token */
235 while ((*walk == ' ' || *walk == '\t' ||
236 *walk == '\r' || *walk == '\n') && *walk != '\0')
239 cmdp_token_ptr *ptr = &(tokens[state]);
240 token_handled = false;
241 for (c = 0; c < ptr->n; c++) {
242 token = &(ptr->array[c]);
245 if (token->name[0] == '\'') {
246 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
247 if (token->identifier != NULL)
248 push_string(token->identifier, sstrdup(token->name + 1));
249 walk += strlen(token->name) - 1;
251 token_handled = true;
257 if (strcmp(token->name, "string") == 0 ||
258 strcmp(token->name, "word") == 0) {
259 const char *beginning = walk;
260 /* Handle quoted strings (or words). */
264 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
267 if (token->name[0] == 's') {
268 /* For a string (starting with 's'), the delimiters are
269 * comma (,) and semicolon (;) which introduce a new
270 * operation or command, respectively. Also, newlines
272 while (*walk != ';' && *walk != ',' &&
273 *walk != '\0' && *walk != '\r' &&
277 /* For a word, the delimiters are white space (' ' or
278 * '\t'), closing square bracket (]), comma (,) and
280 while (*walk != ' ' && *walk != '\t' &&
281 *walk != ']' && *walk != ',' &&
282 *walk != ';' && *walk != '\r' &&
283 *walk != '\n' && *walk != '\0')
287 if (walk != beginning) {
288 char *str = scalloc(walk-beginning + 1);
289 /* We copy manually to handle escaping of characters. */
291 for (inpos = 0, outpos = 0;
292 inpos < (walk-beginning);
294 /* We only handle escaped double quotes to not break
295 * backwards compatibility with people using \w in
296 * regular expressions etc. */
297 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
299 str[outpos] = beginning[inpos];
301 if (token->identifier)
302 push_string(token->identifier, str);
303 /* If we are at the end of a quoted string, skip the ending
308 token_handled = true;
313 if (strcmp(token->name, "end") == 0) {
314 if (*walk == '\0' || *walk == ',' || *walk == ';') {
316 token_handled = true;
317 /* To make sure we start with an appropriate matching
318 * datastructure for commands which do *not* specify any
319 * criteria, we re-initialize the criteria system after
321 // TODO: make this testable
323 if (*walk == '\0' || *walk == ';')
324 cmd_criteria_init(¤t_match, &subcommand_output);
332 if (!token_handled) {
333 /* Figure out how much memory we will need to fill in the names of
334 * all tokens afterwards. */
336 for (c = 0; c < ptr->n; c++)
337 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
339 /* Build up a decent error message. We include the problem, the
340 * full input, and underline the position where the parser
343 char *possible_tokens = smalloc(tokenlen + 1);
344 char *tokenwalk = possible_tokens;
345 for (c = 0; c < ptr->n; c++) {
346 token = &(ptr->array[c]);
347 if (token->name[0] == '\'') {
348 /* A literal is copied to the error message enclosed with
351 strcpy(tokenwalk, token->name + 1);
352 tokenwalk += strlen(token->name + 1);
355 /* Any other token is copied to the error message enclosed
356 * with angle brackets. */
358 strcpy(tokenwalk, token->name);
359 tokenwalk += strlen(token->name);
362 if (c < (ptr->n - 1)) {
368 sasprintf(&errormessage, "Expected one of these tokens: %s",
370 free(possible_tokens);
372 /* Contains the same amount of characters as 'input' has, but with
373 * the unparseable part highlighted using ^ characters. */
374 char *position = smalloc(len + 1);
375 for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
376 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
377 position[len] = '\0';
379 ELOG("%s\n", errormessage);
380 ELOG("Your command: %s\n", input);
381 ELOG(" %s\n", position);
383 /* Format this error message as a JSON reply. */
391 ystr("errorposition");
404 return &command_output;
407 /*******************************************************************************
408 * Code for building the stand-alone binary test.commands_parser which is used
409 * by t/187-commands-parser.t.
410 ******************************************************************************/
415 * Logs the given message to stdout while prefixing the current time to it,
416 * but only if debug logging was activated.
417 * This is to be called by DLOG() which includes filename/linenumber
420 void debuglog(char *fmt, ...) {
424 fprintf(stdout, "# ");
425 vfprintf(stdout, fmt, args);
429 void errorlog(char *fmt, ...) {
433 vfprintf(stderr, fmt, args);
437 int main(int argc, char *argv[]) {
439 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
442 parse_command(argv[1]);