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.
23 // Macros to make the YAJL API a bit easier to use.
24 #define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
25 #define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
27 /*******************************************************************************
28 * The data structures used for parsing. Essentially the current state and a
29 * list of tokens for that state.
31 * The GENERATED_* files are generated by generate-commands-parser.pl with the
32 * input parser-specs/configs.spec.
33 ******************************************************************************/
35 #include "GENERATED_config_enums.h"
37 typedef struct token {
40 /* This might be __CALL */
41 cmdp_state next_state;
43 uint16_t call_identifier;
47 typedef struct tokenptr {
52 #include "GENERATED_config_tokens.h"
54 /*******************************************************************************
55 * The (small) stack where identified literals are stored during the parsing
56 * of a single command (like $workspace).
57 ******************************************************************************/
60 /* Just a pointer, not dynamically allocated. */
61 const char *identifier;
65 /* 10 entries should be enough for everybody. */
66 static struct stack_entry stack[10];
69 * Pushes a string (identified by 'identifier') on the stack. We simply use a
70 * single array, since the number of entries we have to store is very small.
73 static void push_string(const char *identifier, char *str) {
74 for (int c = 0; c < 10; c++) {
75 if (stack[c].identifier != NULL &&
76 strcmp(stack[c].identifier, identifier) != 0)
78 if (stack[c].identifier == NULL) {
79 /* Found a free slot, let’s store it here. */
80 stack[c].identifier = identifier;
83 /* Append the value. */
84 sasprintf(&(stack[c].str), "%s,%s", stack[c].str, str);
89 /* When we arrive here, the stack is full. This should not happen and
90 * means there’s either a bug in this parser or the specification
91 * contains a command with more than 10 identified tokens. */
92 fprintf(stderr, "BUG: commands_parser stack full. This means either a bug "
93 "in the code, or a new command which contains more than "
94 "10 identified tokens.\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 for (int c = 0; c < 10; c++) {
102 if (stack[c].identifier == NULL)
104 if (strcmp(identifier, stack[c].identifier) == 0)
110 static void clear_stack(void) {
111 for (int c = 0; c < 10; c++) {
112 if (stack[c].str != NULL)
114 stack[c].identifier = NULL;
119 // TODO: remove this if it turns out we don’t need it for testing.
121 /*******************************************************************************
122 * A dynamically growing linked list which holds the criteria for the current
124 ******************************************************************************/
126 typedef struct criterion {
130 TAILQ_ENTRY(criterion) criteria;
133 static TAILQ_HEAD(criteria_head, criterion) criteria =
134 TAILQ_HEAD_INITIALIZER(criteria);
137 * Stores the given type/value in the list of criteria.
138 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
141 static void push_criterion(void *unused_criteria, const char *type,
143 struct criterion *criterion = malloc(sizeof(struct criterion));
144 criterion->type = strdup(type);
145 criterion->value = strdup(value);
146 TAILQ_INSERT_TAIL(&criteria, criterion, criteria);
150 * Clears the criteria linked list.
151 * Accepts a pointer as first argument, since it is 'call'ed by the parser.
154 static void clear_criteria(void *unused_criteria) {
155 struct criterion *criterion;
156 while (!TAILQ_EMPTY(&criteria)) {
157 criterion = TAILQ_FIRST(&criteria);
158 free(criterion->type);
159 free(criterion->value);
160 TAILQ_REMOVE(&criteria, criterion, criteria);
166 /*******************************************************************************
168 ******************************************************************************/
170 static cmdp_state state;
172 static Match current_match;
174 static struct CommandResult subcommand_output;
175 static struct CommandResult command_output;
177 #include "GENERATED_config_call.h"
180 static void next_state(const cmdp_token *token) {
181 //printf("token = name %s identifier %s\n", token->name, token->identifier);
182 //printf("next_state = %d\n", token->next_state);
183 if (token->next_state == __CALL) {
184 subcommand_output.json_gen = command_output.json_gen;
185 subcommand_output.needs_tree_render = false;
186 GENERATED_call(token->extra.call_identifier, &subcommand_output);
187 /* If any subcommand requires a tree_render(), we need to make the
188 * whole parser result request a tree_render(). */
189 if (subcommand_output.needs_tree_render)
190 command_output.needs_tree_render = true;
195 state = token->next_state;
196 if (state == INITIAL) {
201 struct CommandResult *parse_config(const char *input) {
202 DLOG("COMMAND: *%s*\n", input);
205 /* A YAJL JSON generator used for formatting replies. */
207 command_output.json_gen = yajl_gen_alloc(NULL);
209 command_output.json_gen = yajl_gen_alloc(NULL, NULL);
213 command_output.needs_tree_render = false;
215 const char *walk = input;
216 const size_t len = strlen(input);
218 const cmdp_token *token;
221 // TODO: make this testable
223 cmd_criteria_init(¤t_match, &subcommand_output);
226 /* The "<=" operator is intentional: We also handle the terminating 0-byte
227 * explicitly by looking for an 'end' token. */
228 while ((walk - input) <= len) {
229 /* skip whitespace and newlines before every token */
230 while ((*walk == ' ' || *walk == '\t' ||
231 *walk == '\r' || *walk == '\n') && *walk != '\0')
234 //printf("remaining input: %s\n", walk);
236 cmdp_token_ptr *ptr = &(tokens[state]);
237 token_handled = false;
238 for (c = 0; c < ptr->n; c++) {
239 token = &(ptr->array[c]);
242 if (token->name[0] == '\'') {
243 if (strncasecmp(walk, token->name + 1, strlen(token->name) - 1) == 0) {
244 if (token->identifier != NULL)
245 push_string(token->identifier, sstrdup(token->name + 1));
246 walk += strlen(token->name) - 1;
248 token_handled = true;
254 if (strcmp(token->name, "string") == 0 ||
255 strcmp(token->name, "word") == 0) {
256 const char *beginning = walk;
257 /* Handle quoted strings (or words). */
261 while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
264 if (token->name[0] == 's') {
265 /* For a string (starting with 's'), the delimiters are
266 * comma (,) and semicolon (;) which introduce a new
267 * operation or command, respectively. Also, newlines
269 while (*walk != ';' && *walk != ',' &&
270 *walk != '\0' && *walk != '\r' &&
274 /* For a word, the delimiters are white space (' ' or
275 * '\t'), closing square bracket (]), comma (,) and
277 while (*walk != ' ' && *walk != '\t' &&
278 *walk != ']' && *walk != ',' &&
279 *walk != ';' && *walk != '\r' &&
280 *walk != '\n' && *walk != '\0')
284 if (walk != beginning) {
285 char *str = scalloc(walk-beginning + 1);
286 /* We copy manually to handle escaping of characters. */
288 for (inpos = 0, outpos = 0;
289 inpos < (walk-beginning);
291 /* We only handle escaped double quotes to not break
292 * backwards compatibility with people using \w in
293 * regular expressions etc. */
294 if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
296 str[outpos] = beginning[inpos];
298 if (token->identifier)
299 push_string(token->identifier, str);
300 /* If we are at the end of a quoted string, skip the ending
305 token_handled = true;
310 if (strcmp(token->name, "end") == 0) {
311 if (*walk == '\0' || *walk == ',' || *walk == ';') {
313 token_handled = true;
314 /* To make sure we start with an appropriate matching
315 * datastructure for commands which do *not* specify any
316 * criteria, we re-initialize the criteria system after
318 // TODO: make this testable
320 if (*walk == '\0' || *walk == ';')
321 cmd_criteria_init(¤t_match, &subcommand_output);
329 if (!token_handled) {
330 /* Figure out how much memory we will need to fill in the names of
331 * all tokens afterwards. */
333 for (c = 0; c < ptr->n; c++)
334 tokenlen += strlen(ptr->array[c].name) + strlen("'', ");
336 /* Build up a decent error message. We include the problem, the
337 * full input, and underline the position where the parser
340 char *possible_tokens = smalloc(tokenlen + 1);
341 char *tokenwalk = possible_tokens;
342 for (c = 0; c < ptr->n; c++) {
343 token = &(ptr->array[c]);
344 if (token->name[0] == '\'') {
345 /* A literal is copied to the error message enclosed with
348 strcpy(tokenwalk, token->name + 1);
349 tokenwalk += strlen(token->name + 1);
352 /* Any other token is copied to the error message enclosed
353 * with angle brackets. */
355 strcpy(tokenwalk, token->name);
356 tokenwalk += strlen(token->name);
359 if (c < (ptr->n - 1)) {
365 sasprintf(&errormessage, "Expected one of these tokens: %s",
367 free(possible_tokens);
369 /* Contains the same amount of characters as 'input' has, but with
370 * the unparseable part highlighted using ^ characters. */
371 char *position = smalloc(len + 1);
372 for (const char *copywalk = input; *copywalk != '\0'; copywalk++)
373 position[(copywalk - input)] = (copywalk >= walk ? '^' : ' ');
374 position[len] = '\0';
376 ELOG("%s\n", errormessage);
377 ELOG("Your command: %s\n", input);
378 ELOG(" %s\n", position);
380 /* Format this error message as a JSON reply. */
384 /* We set parse_error to true to distinguish this from other
385 * errors. i3-nagbar is spawned upon keypresses only for parser
393 ystr("errorposition");
406 return &command_output;
409 /*******************************************************************************
410 * Code for building the stand-alone binary test.commands_parser which is used
411 * by t/187-commands-parser.t.
412 ******************************************************************************/
417 * Logs the given message to stdout while prefixing the current time to it,
418 * but only if debug logging was activated.
419 * This is to be called by DLOG() which includes filename/linenumber
422 void debuglog(char *fmt, ...) {
426 fprintf(stdout, "# ");
427 vfprintf(stdout, fmt, args);
431 void errorlog(char *fmt, ...) {
435 vfprintf(stderr, fmt, args);
439 int main(int argc, char *argv[]) {
441 fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
444 parse_config(argv[1]);