2 #define I3__FILE__ "config_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 * config_parser.c: hand-written parser to parse configuration directives.
11 * See also src/commands_parser.c for rationale on why we use a custom parser.
13 * This parser works VERY MUCH like src/commands_parser.c, so read that first.
14 * The differences are:
16 * 1. config_parser supports the 'number' token type (in addition to 'word' and
17 * 'string'). Numbers are referred to using &num (like $str).
19 * 2. Criteria are not executed immediately, they are just stored.
21 * 3. config_parser recognizes \n and \r as 'end' token, while commands_parser
24 * 4. config_parser skips the current line on invalid inputs and follows the
25 * nearest <error> token.
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/configs.spec.
47 ******************************************************************************/
49 #include "GENERATED_config_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_config_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;
86 /* 10 entries should be enough for everybody. */
87 static struct stack_entry stack[10];
90 * Pushes a string (identified by 'identifier') on the stack. We simply use a
91 * single array, since the number of entries we have to store is very small.
94 static void push_string(const char *identifier, char *str) {
95 for (int c = 0; c < 10; c++) {
96 if (stack[c].identifier != NULL &&
97 strcmp(stack[c].identifier, identifier) != 0)
99 if (stack[c].identifier == NULL) {
100 /* Found a free slot, let’s store it here. */
101 stack[c].identifier = identifier;
102 stack[c].val.str = str;
103 stack[c].type = STACK_STR;
105 /* Append the value. */
106 sasprintf(&(stack[c].val.str), "%s,%s", stack[c].val.str, str);
111 /* When we arrive here, the stack is full. This should not happen and
112 * means there’s either a bug in this parser or the specification
113 * contains a command with more than 10 identified tokens. */
114 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
115 "in the code, or a new command which contains more than "
116 "10 identified tokens.\n");
120 static void push_long(const char *identifier, long num) {
121 for (int c = 0; c < 10; c++) {
122 if (stack[c].identifier != NULL)
124 /* Found a free slot, let’s store it here. */
125 stack[c].identifier = identifier;
126 stack[c].val.num = num;
127 stack[c].type = STACK_LONG;
131 /* When we arrive here, the stack is full. This should not happen and
132 * means there’s either a bug in this parser or the specification
133 * contains a command with more than 10 identified tokens. */
134 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
135 "in the code, or a new command which contains more than "
136 "10 identified tokens.\n");
141 static const char *get_string(const char *identifier) {
142 for (int c = 0; c < 10; c++) {
143 if (stack[c].identifier == NULL)
145 if (strcmp(identifier, stack[c].identifier) == 0)
146 return stack[c].val.str;
151 static const long get_long(const char *identifier) {
152 for (int c = 0; c < 10; c++) {
153 if (stack[c].identifier == NULL)
155 if (strcmp(identifier, stack[c].identifier) == 0)
156 return stack[c].val.num;
161 static void clear_stack(void) {
162 for (int c = 0; c < 10; c++) {
163 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
164 free(stack[c].val.str);
165 stack[c].identifier = NULL;
166 stack[c].val.str = NULL;
167 stack[c].val.num = 0;
171 // TODO: remove this if it turns out we don’t need it for testing.
173 /*******************************************************************************
174 * A dynamically growing linked list which holds the criteria for the current
176 ******************************************************************************/
178 typedef struct criterion {
182 TAILQ_ENTRY(criterion) criteria;
185 static TAILQ_HEAD(criteria_head, criterion) criteria =
186 TAILQ_HEAD_INITIALIZER(criteria);
189 * Stores the given type/value in the list of criteria.
190 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
193 static void push_criterion(void *unused_criteria, const char *type,
195 struct criterion *criterion = malloc(sizeof(struct criterion));
196 criterion->type = strdup(type);
197 criterion->value = strdup(value);
198 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
202 * Clears the criteria linked list.
203 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
206 static void clear_criteria(void *unused_criteria) {
207 struct criterion *criterion;
208 while (!TAILQ_EMPTY(&criteria)) {
209 criterion = TAILQ_FIRST(&criteria);
210 free(criterion->type);
211 free(criterion->value);
212 TAILQ_REMOVE(&criteria, criterion, criteria);
218 /*******************************************************************************
220 ******************************************************************************/
222 static cmdp_state state;
223 static Match current_match;
224 static struct ConfigResult subcommand_output;
225 static struct ConfigResult command_output;
227 /* A list which contains the states that lead to the current state, e.g.
228 * INITIAL, WORKSPACE_LAYOUT.
229 * When jumping back to INITIAL, statelist_idx will simply be set to 1
230 * (likewise for other states, e.g. MODE or BAR).
231 * This list is used to process the nearest error token. */
232 static cmdp_state statelist[10] = { INITIAL };
233 /* NB: statelist_idx points to where the next entry will be inserted */
234 static int statelist_idx = 1;
236 #include "GENERATED_config_call.h"
239 static void next_state(const cmdp_token *token) {
240 cmdp_state _next_state = token->next_state;
242 //printf("token = name %s identifier %s\n", token->name, token->identifier);
243 //printf("next_state = %d\n", token->next_state);
244 if (token->next_state == __CALL) {
245 subcommand_output.json_gen = command_output.json_gen;
246 GENERATED_call(token->extra.call_identifier, &subcommand_output);
247 _next_state = subcommand_output.next_state;
252 if (state == INITIAL) {
256 /* See if we are jumping back to a state in which we were in previously
257 * (statelist contains INITIAL) and just move statelist_idx accordingly. */
258 for (int i = 0; i < statelist_idx; i++) {
259 if (statelist[i] != _next_state)
265 /* Otherwise, the state is new and we add it to the list */
266 statelist[statelist_idx++] = _next_state;
270 * Returns a pointer to the start of the line (one byte after the previous \r,
271 * \n) or the start of the input, if this is the first line.
274 static const char *start_of_line(const char *walk, const char *beginning) {
275 while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
283 * Copies the line and terminates it at the next \n, if any.
285 * The caller has to free() the result.
288 static char *single_line(const char *start) {
289 char *result = sstrdup(start);
290 char *end = strchr(result, '\n');
296 struct ConfigResult *parse_config(const char *input, struct context *context) {
297 /* Dump the entire config file into the debug log. We cannot just use
298 * DLOG("%s", input); because one log message must not exceed 4 KiB. */
299 const char *dumpwalk = input;
301 while (*dumpwalk != '\0') {
302 char *next_nl = strchr(dumpwalk, '\n');
303 if (next_nl != NULL) {
304 DLOG("CONFIG(line %3d): %.*s\n", linecnt, (int)(next_nl - dumpwalk), dumpwalk);
305 dumpwalk = next_nl + 1;
307 DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
315 /* A YAJL JSON generator used for formatting replies. */
317 command_output.json_gen = yajl_gen_alloc(NULL);
319 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
324 const char *walk = input;
325 const size_t len = strlen(input);
327 const cmdp_token *token;
331 // TODO: make this testable
333 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
336 /* The "<=" operator is intentional: We also handle the terminating 0-byte
337 * explicitly by looking for an 'end' token. */
338 while ((walk - input) <= len) {
339 /* Skip whitespace before every token, newlines are relevant since they
340 * separate configuration directives. */
341 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
344 //printf("remaining input: %s\n", walk);
346 cmdp_token_ptr *ptr = &(tokens[state]);
347 token_handled = false;
348 for (c = 0; c < ptr->n; c++) {
349 token = &(ptr->array[c]);
352 if (token->name[0] == '\'') {
353 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
354 if (token->identifier != NULL)
355 push_string(token->identifier, sstrdup(token->name + 1));
356 walk += strlen(token->name) - 1;
358 token_handled = true;
364 if (strcmp(token->name, "number") == 0) {
365 /* Handle numbers. We only accept decimal numbers for now. */
368 long int num = strtol(walk, &end, 10);
369 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
370 (errno != 0 && num == 0))
373 /* No valid numbers found */
377 if (token->identifier != NULL)
378 push_long(token->identifier, num);
380 /* Set walk to the first non-number character */
383 token_handled = true;
387 if (strcmp(token->name, "string") == 0 ||
388 strcmp(token->name, "word") == 0) {
389 const char *beginning = walk;
390 /* Handle quoted strings (or words). */
394 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
397 if (token->name[0] == 's') {
398 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
401 /* For a word, the delimiters are white space (' ' or
402 * '\t'), closing square bracket (]), comma (,) and
404 while (*walk != ' ' && *walk != '\t' &&
405 *walk != ']' && *walk != ',' &&
406 *walk != ';' && *walk != '\r' &&
407 *walk != '\n' && *walk != '\0')
411 if (walk != beginning) {
412 char *str = scalloc(walk-beginning + 1);
413 /* We copy manually to handle escaping of characters. */
415 for (inpos = 0, outpos = 0;
416 inpos < (walk-beginning);
418 /* We only handle escaped double quotes to not break
419 * backwards compatibility with people using \w in
420 * regular expressions etc. */
421 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
423 str[outpos] = beginning[inpos];
425 if (token->identifier)
426 push_string(token->identifier, str);
427 /* If we are at the end of a quoted string, skip the ending
432 token_handled = true;
437 if (strcmp(token->name, "end") == 0) {
438 //printf("checking for end: *%s*\n", walk);
439 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
441 token_handled = true;
442 /* To make sure we start with an appropriate matching
443 * datastructure for commands which do *not* specify any
444 * criteria, we re-initialize the criteria system after
446 // TODO: make this testable
448 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
457 if (!token_handled) {
458 /* Figure out how much memory we will need to fill in the names of
459 * all tokens afterwards. */
461 for (c = 0; c < ptr->n; c++)
462 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
464 /* Build up a decent error message. We include the problem, the
465 * full input, and underline the position where the parser
468 char *possible_tokens = smalloc(tokenlen + 1);
469 char *tokenwalk = possible_tokens;
470 for (c = 0; c < ptr->n; c++) {
471 token = &(ptr->array[c]);
472 if (token->name[0] == '\'') {
473 /* A literal is copied to the error message enclosed with
476 strcpy(tokenwalk, token->name + 1);
477 tokenwalk += strlen(token->name + 1);
480 /* Skip error tokens in error messages, they are used
481 * internally only and might confuse users. */
482 if (strcmp(token->name, "error") == 0)
484 /* Any other token is copied to the error message enclosed
485 * with angle brackets. */
487 strcpy(tokenwalk, token->name);
488 tokenwalk += strlen(token->name);
491 if (c < (ptr->n - 1)) {
497 sasprintf(&errormessage, "Expected one of these tokens: %s",
499 free(possible_tokens);
502 /* Go back to the beginning of the line */
503 const char *error_line = start_of_line(walk, input);
505 /* Contains the same amount of characters as 'input' has, but with
506 * the unparseable part highlighted using ^ characters. */
507 char *position = scalloc(strlen(error_line) + 1);
508 const char *copywalk;
509 for (copywalk = error_line;
510 *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
512 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
513 position[(copywalk - error_line)] = '\0';
515 ELOG("CONFIG: %s\n", errormessage);
516 ELOG("CONFIG: (in file %s)\n", context->filename);
517 char *error_copy = single_line(error_line);
519 /* Print context lines *before* the error, if any. */
521 const char *context_p1_start = start_of_line(error_line-2, input);
522 char *context_p1_line = single_line(context_p1_start);
524 const char *context_p2_start = start_of_line(context_p1_start-2, input);
525 char *context_p2_line = single_line(context_p2_start);
526 ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
527 free(context_p2_line);
529 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
530 free(context_p1_line);
532 ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
533 ELOG("CONFIG: %s\n", position);
535 /* Print context lines *after* the error, if any. */
536 for (int i = 0; i < 2; i++) {
537 char *error_line_end = strchr(error_line, '\n');
538 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
539 error_line = error_line_end + 1;
540 error_copy = single_line(error_line);
541 ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
546 context->has_errors = true;
548 /* Format this error message as a JSON reply. */
552 /* We set parse_error to true to distinguish this from other
553 * errors. i3-nagbar is spawned upon keypresses only for parser
561 ystr("errorposition");
565 /* Skip the rest of this line, but continue parsing. */
566 while ((walk - input) <= len && *walk != '\n')
573 /* To figure out in which state to go (e.g. MODE or INITIAL),
574 * we find the nearest state which contains an <error> token
575 * and follow that one. */
576 bool error_token_found = false;
577 for (int i = statelist_idx-1; (i >= 0) && !error_token_found; i--) {
578 cmdp_token_ptr *errptr = &(tokens[statelist[i]]);
579 for (int j = 0; j < errptr->n; j++) {
580 if (strcmp(errptr->array[j].name, "error") != 0)
582 next_state(&(errptr->array[j]));
583 error_token_found = true;
588 assert(error_token_found);
594 return &command_output;
597 /*******************************************************************************
598 * Code for building the stand-alone binary test.commands_parser which is used
599 * by t/187-commands-parser.t.
600 ******************************************************************************/
605 * Logs the given message to stdout while prefixing the current time to it,
606 * but only if debug logging was activated.
607 * This is to be called by DLOG() which includes filename/linenumber
610 void debuglog(char *fmt, ...) {
614 fprintf(stdout, "# ");
615 vfprintf(stdout, fmt, args);
619 void errorlog(char *fmt, ...) {
623 vfprintf(stderr, fmt, args);
627 static int criteria_next_state;
629 void cfg_criteria_init(I3_CFG, int _state) {
630 criteria_next_state = _state;
633 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
636 void cfg_criteria_pop_state(I3_CFG) {
637 result->next_state = criteria_next_state;
640 int main(int argc, char *argv[]) {
642 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
645 struct context context;
646 context.filename = "<stdin>";
647 parse_config(argv[1], &context);