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
34 // Macros to make the YAJL API a bit easier to use.
35 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
36 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
38 /*******************************************************************************
39 * The data structures used for parsing. Essentially the current state and a
40 * list of tokens for that state.
42 * The GENERATED_* files are generated by generate-commands-parser.pl with the
43 * input parser-specs/configs.spec.
44 ******************************************************************************/
46 #include "GENERATED_config_enums.h"
48 typedef struct token {
51 /* This might be __CALL */
52 cmdp_state next_state;
54 uint16_t call_identifier;
58 typedef struct tokenptr {
63 #include "GENERATED_config_tokens.h"
65 /*******************************************************************************
66 * The (small) stack where identified literals are stored during the parsing
67 * of a single command (like $workspace).
68 ******************************************************************************/
71 /* Just a pointer, not dynamically allocated. */
72 const char *identifier;
83 /* 10 entries should be enough for everybody. */
84 static struct stack_entry stack[10];
87 * Pushes a string (identified by 'identifier') on the stack. We simply use a
88 * single array, since the number of entries we have to store is very small.
91 static void push_string(const char *identifier, char *str) {
92 for (int c = 0; c < 10; c++) {
93 if (stack[c].identifier != NULL &&
94 strcmp(stack[c].identifier, identifier) != 0)
96 if (stack[c].identifier == NULL) {
97 /* Found a free slot, let’s store it here. */
98 stack[c].identifier = identifier;
99 stack[c].val.str = str;
100 stack[c].type = STACK_STR;
102 /* Append the value. */
103 sasprintf(&(stack[c].val.str), "%s,%s", stack[c].val.str, str);
108 /* When we arrive here, the stack is full. This should not happen and
109 * means there’s either a bug in this parser or the specification
110 * contains a command with more than 10 identified tokens. */
111 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
112 "in the code, or a new command which contains more than "
113 "10 identified tokens.\n");
117 static void push_long(const char *identifier, long num) {
118 for (int c = 0; c < 10; c++) {
119 if (stack[c].identifier != NULL)
121 /* Found a free slot, let’s store it here. */
122 stack[c].identifier = identifier;
123 stack[c].val.num = num;
124 stack[c].type = STACK_LONG;
128 /* When we arrive here, the stack is full. This should not happen and
129 * means there’s either a bug in this parser or the specification
130 * contains a command with more than 10 identified tokens. */
131 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
132 "in the code, or a new command which contains more than "
133 "10 identified tokens.\n");
138 static const char *get_string(const char *identifier) {
139 for (int c = 0; c < 10; c++) {
140 if (stack[c].identifier == NULL)
142 if (strcmp(identifier, stack[c].identifier) == 0)
143 return stack[c].val.str;
148 static const long get_long(const char *identifier) {
149 for (int c = 0; c < 10; c++) {
150 if (stack[c].identifier == NULL)
152 if (strcmp(identifier, stack[c].identifier) == 0)
153 return stack[c].val.num;
158 static void clear_stack(void) {
159 for (int c = 0; c < 10; c++) {
160 if (stack[c].type == STACK_STR && stack[c].val.str != NULL)
161 free(stack[c].val.str);
162 stack[c].identifier = NULL;
163 stack[c].val.str = NULL;
164 stack[c].val.num = 0;
168 // TODO: remove this if it turns out we don’t need it for testing.
170 /*******************************************************************************
171 * A dynamically growing linked list which holds the criteria for the current
173 ******************************************************************************/
175 typedef struct criterion {
179 TAILQ_ENTRY(criterion) criteria;
182 static TAILQ_HEAD(criteria_head, criterion) criteria =
183 TAILQ_HEAD_INITIALIZER(criteria);
186 * Stores the given type/value in the list of criteria.
187 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
190 static void push_criterion(void *unused_criteria, const char *type,
192 struct criterion *criterion = malloc(sizeof(struct criterion));
193 criterion->type = strdup(type);
194 criterion->value = strdup(value);
195 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
199 * Clears the criteria linked list.
200 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
203 static void clear_criteria(void *unused_criteria) {
204 struct criterion *criterion;
205 while (!TAILQ_EMPTY(&criteria)) {
206 criterion = TAILQ_FIRST(&criteria);
207 free(criterion->type);
208 free(criterion->value);
209 TAILQ_REMOVE(&criteria, criterion, criteria);
215 /*******************************************************************************
217 ******************************************************************************/
219 static cmdp_state state;
220 static Match current_match;
221 static struct ConfigResult subcommand_output;
222 static struct ConfigResult command_output;
224 #include "GENERATED_config_call.h"
227 static void next_state(const cmdp_token *token) {
228 //printf("token = name %s identifier %s\n", token->name, token->identifier);
229 //printf("next_state = %d\n", token->next_state);
230 if (token->next_state == __CALL) {
231 subcommand_output.json_gen = command_output.json_gen;
232 GENERATED_call(token->extra.call_identifier, &subcommand_output);
237 state = token->next_state;
238 if (state == INITIAL) {
244 * Returns a pointer to the start of the line (one byte after the previous \r,
245 * \n) or the start of the input, if this is the first line.
248 static const char *start_of_line(const char *walk, const char *beginning) {
249 while (*walk != '\n' && *walk != '\r' && walk >= beginning) {
257 * Copies the line and terminates it at the next \n, if any.
259 * The caller has to free() the result.
262 static char *single_line(const char *start) {
263 char *result = sstrdup(start);
264 char *end = strchr(result, '\n');
270 struct ConfigResult *parse_config(const char *input, struct context *context) {
271 /* Dump the entire config file into the debug log. We cannot just use
272 * DLOG("%s", input); because one log message must not exceed 4 KiB. */
273 const char *dumpwalk = input;
275 while (*dumpwalk != '\0') {
276 char *next_nl = strchr(dumpwalk, '\n');
277 if (next_nl != NULL) {
278 DLOG("CONFIG(line %3d): %.*s\n", linecnt, (next_nl - dumpwalk), dumpwalk);
279 dumpwalk = next_nl + 1;
281 DLOG("CONFIG(line %3d): %s\n", linecnt, dumpwalk);
288 /* A YAJL JSON generator used for formatting replies. */
290 command_output.json_gen = yajl_gen_alloc(NULL);
292 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
297 const char *walk = input;
298 const size_t len = strlen(input);
300 const cmdp_token *token;
304 // TODO: make this testable
306 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
309 /* The "<=" operator is intentional: We also handle the terminating 0-byte
310 * explicitly by looking for an 'end' token. */
311 while ((walk - input) <= len) {
312 /* Skip whitespace before every token, newlines are relevant since they
313 * separate configuration directives. */
314 while ((*walk == ' ' || *walk == '\t') && *walk != '\0')
317 //printf("remaining input: %s\n", walk);
319 cmdp_token_ptr *ptr = &(tokens[state]);
320 token_handled = false;
321 for (c = 0; c < ptr->n; c++) {
322 token = &(ptr->array[c]);
325 if (token->name[0] == '\'') {
326 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
327 if (token->identifier != NULL)
328 push_string(token->identifier, sstrdup(token->name + 1));
329 walk += strlen(token->name) - 1;
331 token_handled = true;
337 if (strcmp(token->name, "number") == 0) {
338 /* Handle numbers. We only accept decimal numbers for now. */
341 long int num = strtol(walk, &end, 10);
342 if ((errno == ERANGE && (num == LONG_MIN || num == LONG_MAX)) ||
343 (errno != 0 && num == 0))
346 /* No valid numbers found */
350 if (token->identifier != NULL)
351 push_long(token->identifier, num);
353 /* Set walk to the first non-number character */
356 token_handled = true;
360 if (strcmp(token->name, "string") == 0 ||
361 strcmp(token->name, "word") == 0) {
362 const char *beginning = walk;
363 /* Handle quoted strings (or words). */
367 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
370 if (token->name[0] == 's') {
371 while (*walk != '\0' && *walk != '\r' && *walk != '\n')
374 /* For a word, the delimiters are white space (' ' or
375 * '\t'), closing square bracket (]), comma (,) and
377 while (*walk != ' ' && *walk != '\t' &&
378 *walk != ']' && *walk != ',' &&
379 *walk != ';' && *walk != '\r' &&
380 *walk != '\n' && *walk != '\0')
384 if (walk != beginning) {
385 char *str = scalloc(walk-beginning + 1);
386 /* We copy manually to handle escaping of characters. */
388 for (inpos = 0, outpos = 0;
389 inpos < (walk-beginning);
391 /* We only handle escaped double quotes to not break
392 * backwards compatibility with people using \w in
393 * regular expressions etc. */
394 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
396 str[outpos] = beginning[inpos];
398 if (token->identifier)
399 push_string(token->identifier, str);
400 /* If we are at the end of a quoted string, skip the ending
405 token_handled = true;
410 if (strcmp(token->name, "end") == 0) {
411 //printf("checking for end: *%s*\n", walk);
412 if (*walk == '\0' || *walk == '\n' || *walk == '\r') {
414 token_handled = true;
415 /* To make sure we start with an appropriate matching
416 * datastructure for commands which do *not* specify any
417 * criteria, we re-initialize the criteria system after
419 // TODO: make this testable
421 cfg_criteria_init(¤t_match, &subcommand_output, INITIAL);
430 if (!token_handled) {
431 /* Figure out how much memory we will need to fill in the names of
432 * all tokens afterwards. */
434 for (c = 0; c < ptr->n; c++)
435 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
437 /* Build up a decent error message. We include the problem, the
438 * full input, and underline the position where the parser
441 char *possible_tokens = smalloc(tokenlen + 1);
442 char *tokenwalk = possible_tokens;
443 for (c = 0; c < ptr->n; c++) {
444 token = &(ptr->array[c]);
445 if (token->name[0] == '\'') {
446 /* A literal is copied to the error message enclosed with
449 strcpy(tokenwalk, token->name + 1);
450 tokenwalk += strlen(token->name + 1);
453 /* Any other token is copied to the error message enclosed
454 * with angle brackets. */
456 strcpy(tokenwalk, token->name);
457 tokenwalk += strlen(token->name);
460 if (c < (ptr->n - 1)) {
466 sasprintf(&errormessage, "Expected one of these tokens: %s",
468 free(possible_tokens);
471 /* Go back to the beginning of the line */
472 const char *error_line = start_of_line(walk, input);
474 /* Contains the same amount of characters as 'input' has, but with
475 * the unparseable part highlighted using ^ characters. */
476 char *position = scalloc(strlen(error_line) + 1);
477 const char *copywalk;
478 for (copywalk = error_line;
479 *copywalk != '\n' && *copywalk != '\r' && *copywalk != '\0';
481 position[(copywalk - error_line)] = (copywalk >= walk ? '^' : (*copywalk == '\t' ? '\t' : ' '));
482 position[(copywalk - error_line)] = '\0';
484 ELOG("CONFIG: %s\n", errormessage);
485 ELOG("CONFIG: (in file %s)\n", context->filename);
486 char *error_copy = single_line(error_line);
488 /* Print context lines *before* the error, if any. */
490 const char *context_p1_start = start_of_line(error_line-2, input);
491 char *context_p1_line = single_line(context_p1_start);
493 const char *context_p2_start = start_of_line(context_p1_start-2, input);
494 char *context_p2_line = single_line(context_p2_start);
495 ELOG("CONFIG: Line %3d: %s\n", linecnt - 2, context_p2_line);
496 free(context_p2_line);
498 ELOG("CONFIG: Line %3d: %s\n", linecnt - 1, context_p1_line);
499 free(context_p1_line);
501 ELOG("CONFIG: Line %3d: %s\n", linecnt, error_copy);
502 ELOG("CONFIG: %s\n", position);
504 /* Print context lines *after* the error, if any. */
505 for (int i = 0; i < 2; i++) {
506 char *error_line_end = strchr(error_line, '\n');
507 if (error_line_end != NULL && *(error_line_end + 1) != '\0') {
508 error_line = error_line_end + 1;
509 error_copy = single_line(error_line);
510 ELOG("CONFIG: Line %3d: %s\n", linecnt + i + 1, error_copy);
515 context->has_errors = true;
517 /* Format this error message as a JSON reply. */
521 /* We set parse_error to true to distinguish this from other
522 * errors. i3-nagbar is spawned upon keypresses only for parser
530 ystr("errorposition");
543 return &command_output;
546 /*******************************************************************************
547 * Code for building the stand-alone binary test.commands_parser which is used
548 * by t/187-commands-parser.t.
549 ******************************************************************************/
554 * Logs the given message to stdout while prefixing the current time to it,
555 * but only if debug logging was activated.
556 * This is to be called by DLOG() which includes filename/linenumber
559 void debuglog(char *fmt, ...) {
563 fprintf(stdout, "# ");
564 vfprintf(stdout, fmt, args);
568 void errorlog(char *fmt, ...) {
572 vfprintf(stderr, fmt, args);
576 static int criteria_next_state;
578 void cfg_criteria_init(I3_CFG, int _state) {
579 criteria_next_state = _state;
582 void cfg_criteria_add(I3_CFG, const char *ctype, const char *cvalue) {
585 void cfg_criteria_pop_state(I3_CFG) {
586 result->next_state = criteria_next_state;
589 int main(int argc, char *argv[]) {
591 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
594 struct context context;
595 context.filename = "<stdin>";
596 parse_config(argv[1], &context);