]> git.sur5r.net Git - i3/i3/blobdiff - src/commands_parser.c
Merge pull request #1591 from Airblader/feature-child-cleanup
[i3/i3] / src / commands_parser.c
index d739f4e146ad7ae11449829c464457a019d4df96..fa4c2360101513e4796490c9720ff9b63533915f 100644 (file)
@@ -13,7 +13,7 @@
  * We use a hand-written parser instead of lex/yacc because our commands are
  * easy for humans, not for computers. Thus, it’s quite hard to specify a
  * context-free grammar for the commands. A PEG grammar would be easier, but
- * there’s downsides to every PEG parser generator I have come accross so far.
+ * there’s downsides to every PEG parser generator I have come across so far.
  *
  * This parser is basically a state machine which looks for literals or strings
  * and can push either on a stack. After identifying a literal or string, it
@@ -35,8 +35,8 @@
 #include "all.h"
 
 // Macros to make the YAJL API a bit easier to use.
-#define y(x, ...) yajl_gen_ ## x (command_output.json_gen, ##__VA_ARGS__)
-#define ystr(str) yajl_gen_string(command_output.json_gen, (unsigned char*)str, strlen(str))
+#define y(x, ...) (command_output.json_gen != NULL ? yajl_gen_##x(command_output.json_gen, ##__VA_ARGS__) : 0)
+#define ystr(str) (command_output.json_gen != NULL ? yajl_gen_string(command_output.json_gen, (unsigned char *)str, strlen(str)) : 0)
 
 /*******************************************************************************
  * The data structures used for parsing. Essentially the current state and a
@@ -46,7 +46,7 @@
  * input parser-specs/commands.spec.
  ******************************************************************************/
 
-#include "GENERATED_enums.h"
+#include "GENERATED_command_enums.h"
 
 typedef struct token {
     char *name;
@@ -63,7 +63,7 @@ typedef struct tokenptr {
     int n;
 } cmdp_token_ptr;
 
-#include "GENERATED_tokens.h"
+#include "GENERATED_command_tokens.h"
 
 /*******************************************************************************
  * The (small) stack where identified literals are stored during the parsing
@@ -179,17 +179,17 @@ static cmdp_state state;
 #ifndef TEST_PARSER
 static Match current_match;
 #endif
-static struct CommandResult subcommand_output;
-static struct CommandResult command_output;
-
-#include "GENERATED_call.h"
+static struct CommandResultIR subcommand_output;
+static struct CommandResultIR command_output;
 
+#include "GENERATED_command_call.h"
 
 static void next_state(const cmdp_token *token) {
     if (token->next_state == __CALL) {
         subcommand_output.json_gen = command_output.json_gen;
         subcommand_output.needs_tree_render = false;
         GENERATED_call(token->extra.call_identifier, &subcommand_output);
+        state = subcommand_output.next_state;
         /* If any subcommand requires a tree_render(), we need to make the
          * whole parser result request a tree_render(). */
         if (subcommand_output.needs_tree_render)
@@ -204,16 +204,76 @@ static void next_state(const cmdp_token *token) {
     }
 }
 
-struct CommandResult *parse_command(const char *input) {
+/*
+ * Parses a string (or word, if as_word is true). Extracted out of
+ * parse_command so that it can be used in src/workspace.c for interpreting
+ * workspace commands.
+ *
+ */
+char *parse_string(const char **walk, bool as_word) {
+    const char *beginning = *walk;
+    /* Handle quoted strings (or words). */
+    if (**walk == '"') {
+        beginning++;
+        (*walk)++;
+        for (; **walk != '\0' && **walk != '"'; (*walk)++)
+            if (**walk == '\\' && *(*walk + 1) != '\0')
+                (*walk)++;
+    } else {
+        if (!as_word) {
+            /* For a string (starting with 's'), the delimiters are
+             * comma (,) and semicolon (;) which introduce a new
+             * operation or command, respectively. Also, newlines
+             * end a command. */
+            while (**walk != ';' && **walk != ',' &&
+                   **walk != '\0' && **walk != '\r' &&
+                   **walk != '\n')
+                (*walk)++;
+        } else {
+            /* For a word, the delimiters are white space (' ' or
+             * '\t'), closing square bracket (]), comma (,) and
+             * semicolon (;). */
+            while (**walk != ' ' && **walk != '\t' &&
+                   **walk != ']' && **walk != ',' &&
+                   **walk != ';' && **walk != '\r' &&
+                   **walk != '\n' && **walk != '\0')
+                (*walk)++;
+        }
+    }
+    if (*walk == beginning)
+        return NULL;
+
+    char *str = scalloc(*walk - beginning + 1);
+    /* We copy manually to handle escaping of characters. */
+    int inpos, outpos;
+    for (inpos = 0, outpos = 0;
+         inpos < (*walk - beginning);
+         inpos++, outpos++) {
+        /* We only handle escaped double quotes and backslashes to not break
+         * backwards compatibility with people using \w in regular expressions
+         * etc. */
+        if (beginning[inpos] == '\\' && (beginning[inpos + 1] == '"' || beginning[inpos + 1] == '\\'))
+            inpos++;
+        str[outpos] = beginning[inpos];
+    }
+
+    return str;
+}
+
+/*
+ * Parses and executes the given command. If a caller-allocated yajl_gen is
+ * passed, a json reply will be generated in the format specified by the ipc
+ * protocol. Pass NULL if no json reply is required.
+ *
+ * Free the returned CommandResult with command_result_free().
+ */
+CommandResult *parse_command(const char *input, yajl_gen gen) {
     DLOG("COMMAND: *%s*\n", input);
     state = INITIAL;
+    CommandResult *result = scalloc(sizeof(CommandResult));
 
-/* A YAJL JSON generator used for formatting replies. */
-#if YAJL_MAJOR >= 2
-    command_output.json_gen = yajl_gen_alloc(NULL);
-#else
-    command_output.json_gen = yajl_gen_alloc(NULL, NULL);
-#endif
+    /* A YAJL JSON generator used for formatting replies. */
+    command_output.json_gen = gen;
 
     y(array_open);
     command_output.needs_tree_render = false;
@@ -224,17 +284,18 @@ struct CommandResult *parse_command(const char *input) {
     const cmdp_token *token;
     bool token_handled;
 
-    // TODO: make this testable
+// TODO: make this testable
 #ifndef TEST_PARSER
     cmd_criteria_init(&current_match, &subcommand_output);
 #endif
 
     /* The "<=" operator is intentional: We also handle the terminating 0-byte
      * explicitly by looking for an 'end' token. */
-    while ((walk - input) <= len) {
+    while ((size_t)(walk - input) <= len) {
         /* skip whitespace and newlines before every token */
         while ((*walk == ' ' || *walk == '\t' ||
-                *walk == '\r' || *walk == '\n') && *walk != '\0')
+                *walk == '\r' || *walk == '\n') &&
+               *walk != '\0')
             walk++;
 
         cmdp_token_ptr *ptr = &(tokens[state]);
@@ -257,48 +318,8 @@ struct CommandResult *parse_command(const char *input) {
 
             if (strcmp(token->name, "string") == 0 ||
                 strcmp(token->name, "word") == 0) {
-                const char *beginning = walk;
-                /* Handle quoted strings (or words). */
-                if (*walk == '"') {
-                    beginning++;
-                    walk++;
-                    while (*walk != '\0' && (*walk != '"' || *(walk-1) == '\\'))
-                        walk++;
-                } else {
-                    if (token->name[0] == 's') {
-                        /* For a string (starting with 's'), the delimiters are
-                         * comma (,) and semicolon (;) which introduce a new
-                         * operation or command, respectively. Also, newlines
-                         * end a command. */
-                        while (*walk != ';' && *walk != ',' &&
-                               *walk != '\0' && *walk != '\r' &&
-                               *walk != '\n')
-                            walk++;
-                    } else {
-                        /* For a word, the delimiters are white space (' ' or
-                         * '\t'), closing square bracket (]), comma (,) and
-                         * semicolon (;). */
-                        while (*walk != ' ' && *walk != '\t' &&
-                               *walk != ']' && *walk != ',' &&
-                               *walk !=  ';' && *walk != '\r' &&
-                               *walk != '\n' && *walk != '\0')
-                            walk++;
-                    }
-                }
-                if (walk != beginning) {
-                    char *str = scalloc(walk-beginning + 1);
-                    /* We copy manually to handle escaping of characters. */
-                    int inpos, outpos;
-                    for (inpos = 0, outpos = 0;
-                         inpos < (walk-beginning);
-                         inpos++, outpos++) {
-                        /* We only handle escaped double quotes to not break
-                         * backwards compatibility with people using \w in
-                         * regular expressions etc. */
-                        if (beginning[inpos] == '\\' && beginning[inpos+1] == '"')
-                            inpos++;
-                        str[outpos] = beginning[inpos];
-                    }
+                char *str = parse_string(&walk, (token->name[0] != 's'));
+                if (str != NULL) {
                     if (token->identifier)
                         push_string(token->identifier, str);
                     /* If we are at the end of a quoted string, skip the ending
@@ -315,19 +336,19 @@ struct CommandResult *parse_command(const char *input) {
                 if (*walk == '\0' || *walk == ',' || *walk == ';') {
                     next_state(token);
                     token_handled = true;
-                    /* To make sure we start with an appropriate matching
+/* To make sure we start with an appropriate matching
                      * datastructure for commands which do *not* specify any
                      * criteria, we re-initialize the criteria system after
                      * every command. */
-                    // TODO: make this testable
+// TODO: make this testable
 #ifndef TEST_PARSER
                     if (*walk == '\0' || *walk == ';')
                         cmd_criteria_init(&current_match, &subcommand_output);
 #endif
                     walk++;
                     break;
-               }
-           }
+                }
+            }
         }
 
         if (!token_handled) {
@@ -381,6 +402,9 @@ struct CommandResult *parse_command(const char *input) {
             ELOG("Your command: %s\n", input);
             ELOG("              %s\n", position);
 
+            result->parse_error = true;
+            result->error_message = errormessage;
+
             /* Format this error message as a JSON reply. */
             y(map_open);
             ystr("success");
@@ -399,7 +423,6 @@ struct CommandResult *parse_command(const char *input) {
             y(map_close);
 
             free(position);
-            free(errormessage);
             clear_stack();
             break;
         }
@@ -407,7 +430,19 @@ struct CommandResult *parse_command(const char *input) {
 
     y(array_close);
 
-    return &command_output;
+    result->needs_tree_render = command_output.needs_tree_render;
+    return result;
+}
+
+/*
+ * Frees a CommandResult
+ */
+void command_result_free(CommandResult *result) {
+    if (result == NULL)
+        return;
+
+    FREE(result->error_message);
+    FREE(result);
 }
 
 /*******************************************************************************
@@ -445,6 +480,12 @@ int main(int argc, char *argv[]) {
         fprintf(stderr, "Syntax: %s <command>\n", argv[0]);
         return 1;
     }
-    parse_command(argv[1]);
+    yajl_gen gen = yajl_gen_alloc(NULL);
+
+    CommandResult *result = parse_command(argv[1], gen);
+
+    command_result_free(result);
+
+    yajl_gen_free(gen);
 }
 #endif