1 #line 2 "commands_parser.c"
3 * vim:ts=4:sw=4:expandtab
5 * i3 - an improved dynamic tiling window manager
6 * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8 * commands_parser.c: hand-written parser to parse commands (commands are what
9 * you bind on keys and what you can send to i3 using the IPC interface, like
10 * 'move left' or 'workspace 4').
12 * We use a hand-written parser instead of lex/yacc because our commands are
13 * easy for humans, not for computers. Thus, it’s quite hard to specify a
14 * context-free grammar for the commands. A PEG grammar would be easier, but
15 * there’s downsides to every PEG parser generator I have come accross so far.
17 * This parser is basically a state machine which looks for literals or strings
18 * and can push either on a stack. After identifying a literal or string, it
19 * will either transition to the current state, to a different state, or call a
20 * function (like cmd_move()).
22 * Special care has been taken that error messages are useful and the code is
23 * well testable (when compiled with -DTEST_PARSER it will output to stdout
24 * instead of actually calling any function).
36 // Macros to make the YAJL API a bit easier to use.
37 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
38 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
40 /*******************************************************************************
41 * The data structures used for parsing. Essentially the current state and a
42 * list of tokens for that state.
44 * The GENERATED_* files are generated by generate-commands-parser.pl with the
45 * input parser-specs/commands.spec.
46 ******************************************************************************/
48 #include "GENERATED_enums.h"
50 typedef struct token {
53 /* This might be __CALL */
54 cmdp_state next_state;
56 uint16_t call_identifier;
60 typedef struct tokenptr {
65 #include "GENERATED_tokens.h"
67 /*******************************************************************************
68 * The (small) stack where identified literals are stored during the parsing
69 * of a single command (like $workspace).
70 ******************************************************************************/
73 /* Just a pointer, not dynamically allocated. */
74 const char *identifier;
78 /* 10 entries should be enough for everybody. */
79 static struct stack_entry stack[10];
82 * Pushes a string (identified by 'identifier') on the stack. We simply use a
83 * single array, since the number of entries we have to store is very small.
86 static void push_string(const char *identifier, char *str) {
87 for (int c = 0; c < 10; c++) {
88 if (stack[c].identifier != NULL)
90 /* Found a free slot, let’s store it here. */
91 stack[c].identifier = identifier;
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");
105 // XXX: ideally, this would be const char. need to check if that works with all
107 static char *get_string(const char *identifier) {
108 for (int c = 0; c < 10; c++) {
109 if (stack[c].identifier == NULL)
111 if (strcmp(identifier, stack[c].identifier) == 0)
117 static void clear_stack(void) {
118 for (int c = 0; c < 10; c++) {
119 if (stack[c].str != NULL)
121 stack[c].identifier = NULL;
126 // TODO: remove this if it turns out we don’t need it for testing.
128 /*******************************************************************************
129 * A dynamically growing linked list which holds the criteria for the current
131 ******************************************************************************/
133 typedef struct criterion {
137 TAILQ_ENTRY(criterion) criteria;
140 static TAILQ_HEAD(criteria_head, criterion) criteria =
141 TAILQ_HEAD_INITIALIZER(criteria);
144 * Stores the given type/value in the list of criteria.
145 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
148 static void push_criterion(void *unused_criteria, const char *type,
150 struct criterion *criterion = malloc(sizeof(struct criterion));
151 criterion->type = strdup(type);
152 criterion->value = strdup(value);
153 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
157 * Clears the criteria linked list.
158 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
161 static void clear_criteria(void *unused_criteria) {
162 struct criterion *criterion;
163 while (!TAILQ_EMPTY(&criteria)) {
164 criterion = TAILQ_FIRST(&criteria);
165 free(criterion->type);
166 free(criterion->value);
167 TAILQ_REMOVE(&criteria, criterion, criteria);
173 /*******************************************************************************
175 ******************************************************************************/
177 static cmdp_state state;
179 static Match current_match;
181 static struct CommandResult subcommand_output;
182 static struct CommandResult command_output;
184 #include "GENERATED_call.h"
187 static void next_state(const cmdp_token *token) {
188 if (token->next_state == __CALL) {
189 subcommand_output.json_gen = command_output.json_gen;
190 subcommand_output.needs_tree_render = false;
191 GENERATED_call(token->extra.call_identifier, &subcommand_output);
192 /* If any subcommand requires a tree_render(), we need to make the
193 * whole parser result request a tree_render(). */
194 if (subcommand_output.needs_tree_render)
195 command_output.needs_tree_render = true;
200 state = token->next_state;
201 if (state == INITIAL) {
206 /* TODO: Return parsing errors via JSON. */
207 struct CommandResult *parse_command(const char *input) {
208 DLOG("COMMAND: *%s*\n", input);
211 /* A YAJL JSON generator used for formatting replies. */
213 command_output.json_gen = yajl_gen_alloc(NULL);
215 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
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 cmdp_token_ptr *ptr = &(tokens[state]);
241 token_handled = false;
242 for (c = 0; c < ptr->n; c++) {
243 token = &(ptr->array[c]);
246 if (token->name[0] == '\'') {
247 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
248 if (token->identifier != NULL)
249 push_string(token->identifier, sstrdup(token->name + 1));
250 walk += strlen(token->name) - 1;
252 token_handled = true;
258 if (strcmp(token->name, "string") == 0 ||
259 strcmp(token->name, "word") == 0) {
260 const char *beginning = walk;
261 /* Handle quoted strings (or words). */
265 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
268 if (token->name[0] == 's') {
269 /* For a string (starting with 's'), the delimiters are
270 * comma (,) and semicolon (;) which introduce a new
271 * operation or command, respectively. Also, newlines
273 while (*walk != ';' && *walk != ',' &&
274 *walk != '\0' && *walk != '\r' &&
278 /* For a word, the delimiters are white space (' ' or
279 * '\t'), closing square bracket (]), comma (,) and
281 while (*walk != ' ' && *walk != '\t' &&
282 *walk != ']' && *walk != ',' &&
283 *walk != ';' && *walk != '\r' &&
284 *walk != '\n' && *walk != '\0')
288 if (walk != beginning) {
289 char *str = scalloc(walk-beginning + 1);
290 /* We copy manually to handle escaping of characters. */
292 for (inpos = 0, outpos = 0;
293 inpos < (walk-beginning);
295 /* We only handle escaped double quotes to not break
296 * backwards compatibility with people using \w in
297 * regular expressions etc. */
298 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
300 str[outpos] = beginning[inpos];
302 if (token->identifier)
303 push_string(token->identifier, str);
304 /* If we are at the end of a quoted string, skip the ending
309 token_handled = true;
314 if (strcmp(token->name, "end") == 0) {
315 if (*walk == '\0' || *walk == ',' || *walk == ';') {
317 token_handled = true;
318 /* To make sure we start with an appropriate matching
319 * datastructure for commands which do *not* specify any
320 * criteria, we re-initialize the criteria system after
322 // TODO: make this testable
324 if (*walk == '\0' || *walk == ';')
325 cmd_criteria_init(¤t_match, &subcommand_output);
333 if (!token_handled) {
334 /* Figure out how much memory we will need to fill in the names of
335 * all tokens afterwards. */
337 for (c = 0; c < ptr->n; c++)
338 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
340 /* Build up a decent error message. We include the problem, the
341 * full input, and underline the position where the parser
344 char *possible_tokens = smalloc(tokenlen + 1);
345 char *tokenwalk = possible_tokens;
346 for (c = 0; c < ptr->n; c++) {
347 token = &(ptr->array[c]);
348 if (token->name[0] == '\'') {
349 /* A literal is copied to the error message enclosed with
352 strcpy(tokenwalk, token->name + 1);
353 tokenwalk += strlen(token->name + 1);
356 /* Any other token is copied to the error message enclosed
357 * with angle brackets. */
359 strcpy(tokenwalk, token->name);
360 tokenwalk += strlen(token->name);
363 if (c < (ptr->n - 1)) {
369 sasprintf(&errormessage, "Expected one of these tokens: %s",
371 free(possible_tokens);
373 /* Contains the same amount of characters as 'input' has, but with
374 * the unparseable part highlighted using ^ characters. */
375 char *position = smalloc(len + 1);
376 for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
377 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
378 position[len] = '\0';
380 ELOG("%s\n", errormessage);
381 ELOG("Your command: %s\n", input);
382 ELOG(" %s\n", position);
384 /* Format this error message as a JSON reply. */
392 ystr("errorposition");
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 debug logging was activated.
418 * This is to be called by DLOG() which includes filename/linenumber
421 void debuglog(char *fmt, ...) {
425 fprintf(stdout, "# ");
426 vfprintf(stdout, fmt, args);
430 void errorlog(char *fmt, ...) {
434 vfprintf(stderr, fmt, args);
438 int main(int argc, char *argv[]) {
440 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
443 parse_command(argv[1]);