qobject: switch JSON parser to push
v3 cover qobject: switch JSON parser to push
This rewrites the json-parser to use a push parser aka state machine. While push parsers are inherently more complex than recursive descent, the grammar for JSON is simple enough that the parser remains readable. There is therefore no need to use e.g. QEMU coroutines.
Unlike the suggestion in commit 62815d85aed ("json: Redesign the callback to consume JSON values", 2018-08-24), I kept the json-streamer concept. It helps in handling input limits, it performs error recovery, and it converts the token-at-a-time push interface to callbacks---all things that are more easily done in a separate layer to keep the parser clean. However, there is no need anymore for it to store partial JSON objects in tokenized form, because the current state is stored in the push parser's stack.
Another benefit is that QEMU can report the first parsing error immediately, without waiting for parentheses to be balanced or for a lexing error. Error recovery then proceeds as before (i.e., the next parse still starts after balanced parentheses or a lexing error).
On top of the benefits intrinsic in the push architecture, it so happens that it's really easy to add a location to JSON parsing errors now, so do that as well.
The diffstat is unfavorable, but most of the new lines delta is really new comments explaining the grammar and state machines.
Paolo
v2->v3:
- accept interpolation for the key of a dictionary
v1->v2:
- remove part of the patch to pass around the lookahead token, it was hard to review and added little value
- separate patch to reuse the JSONParser
- separate patch to make brace/bracket count unsigned
- add comment with the structure of the stack
- add big comment with the grammar
- split long lines
- remove QObject **value argument to pop_entry()
- add assertions about the type of the top-of-stack
- change error to "key is not a string in object"
- split out json_parser_reset() already in the first patch
- rename json_parser_parse_token() to parse_token()
- do not use single quotes in commit messages
- move initialization of JSONToken close to usage
Paolo Bonzini (7):
json-parser: constify JSONToken
json-parser: replace with a push parser
json-streamer: reuse parser
json-streamer: make brace/bracket count unsigned
json-streamer: remove token queue
json-streamer: do not heap-allocate JSONToken
json-parser: add location to JSON parsing errors
include/qobject/json-parser.h | 16 +- qobject/json-parser-int.h | 13 +- qobject/json-lexer.c | 11 +- qobject/json-parser.c | 580 +++++++++++++++++++--------------- qobject/json-streamer.c | 120 +++---- 5 files changed, 415 insertions(+), 325 deletions(-)
Signature · 1 line
2.54.0
PATCH v3 1/7 json-parser: constify JSONToken
--- qobject/json-parser.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-)
qobject/json-parser.c +12 -11
@@ -55,7 +55,8 @@ static QObject *parse_value(JSONParserContext *ctxt);* Error handler */ static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt, - JSONToken *token, const char *msg, ...) + const JSONToken *token, + const char *msg, ...) {va_list ap;char message[1024 ];
@@ -126,7 +127,7 @@ static int cvt4hex(const char *s)* - Invalid Unicode characters are rejected. * - Control characters \x00..\x1F are rejected by the lexer. */ -static QString *parse_string (JSONParserContext *ctxt,JSONToken *token) +static QString *parse_string (JSONParserContext *ctxt,const JSONToken *token) {const char *ptr = token->str;GString *str;
@@ -239,14 +240,14 @@ out:* parser_context_pop_token is deleted as soon as parser_context_pop_token * is called again. */ -static JSONToken *parser_context_pop_token (JSONParserContext *ctxt) +static const JSONToken *parser_context_pop_token (JSONParserContext *ctxt) {g_free (ctxt->current); ctxt->current =g_queue_pop_head (ctxt->buf);return ctxt->current; } -static JSONToken *parser_context_peek_token (JSONParserContext *ctxt) +static const JSONToken *parser_context_peek_token (JSONParserContext *ctxt) {return g_queue_peek_head (ctxt->buf); }
@@ -259,7 +260,7 @@ static int parse_pair(JSONParserContext *ctxt, QDict *dict)QObject *key_obj =NULL ;QString *key;QObject *value; -JSONToken *peek, *token; +const JSONToken *peek, *token; peek =parser_context_peek_token (ctxt);if (peek ==NULL ) {
@@ -309,7 +310,7 @@ out:static QObject *parse_object (JSONParserContext *ctxt) {QDict *dict =NULL ; -JSONToken *token, *peek; +const JSONToken *token, *peek; token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_LCURLY );
@@ -363,7 +364,7 @@ out:static QObject *parse_array (JSONParserContext *ctxt) {QList *list =NULL ; -JSONToken *token, *peek; +const JSONToken *token, *peek; token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_LSQUARE );
@@ -426,7 +427,7 @@ out:static QObject *parse_keyword (JSONParserContext *ctxt) { -JSONToken *token; +const JSONToken *token; token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_KEYWORD );
@@ -444,7 +445,7 @@ static QObject *parse_keyword(JSONParserContext *ctxt)static QObject *parse_interpolation (JSONParserContext *ctxt) { -JSONToken *token; +const JSONToken *token; token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_INTERP );
@@ -480,7 +481,7 @@ static QObject *parse_interpolation(JSONParserContext *ctxt)static QObject *parse_literal (JSONParserContext *ctxt) { -JSONToken *token; +const JSONToken *token; token =parser_context_pop_token (ctxt);assert (token);
@@ -532,7 +533,7 @@ static QObject *parse_literal(JSONParserContext *ctxt)static QObject *parse_value (JSONParserContext *ctxt) { -JSONToken *token; +const JSONToken *token; token =parser_context_peek_token (ctxt);if (token ==NULL ) {
Signature · 1 line
2.54.0
PATCH v3 2/7 json-parser: replace with a push parser
In reply to Paolo BonziniIn order to avoid stashing all the tokens corresponding to a JSON value, embed the parsing stack and state machine in JSONParser. This is more efficient and allows for more prompt error recovery; it also does not make the code substantially larger than the current recursive descent parser, though the state machine is probably a bit harder to follow.
The stack consists of QLists and QDicts corresponding to open brackets and braces, plus optionally a QString with the current key on top of each QDict.
After each value is parsed, it is added to the top array or dictionary or, if the stack is empty, json_parser_feed returns the complete QObject.
For now, json-streamer.c keeps tracking the tokens up until braces and brackets are balanced, and then shoves the whole queue of tokens into the push parser. The only logic change is that JSON_END_OF_INPUT always triggers the emptying of the queue; the parser takes notice and checks that there is nothing on the stack. Not using brace_count and bracket_count for this is the first step towards improved separation of concerns between json-parser.c and json-streamer.c.
--- include/qobject/json-parser.h | 6 + qobject/json-parser-int.h | 5 +- qobject/json-parser.c | 551 ++++++++++++++++++++-------------- qobject/json-streamer.c | 21 +- 4 files changed, 345 insertions(+), 238 deletions(-)
include/qobject/json-parser.h +6 -0
@@ -20,6 +20,12 @@ typedef struct JSONLexer {int x, y; } JSONLexer; +typedef struct JSONParserContext { +Error *err; +GQueue *stack; +va_list *ap; +}JSONParserContext ; + typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque;
qobject/json-parser-int.h +4 -1
@@ -49,6 +49,9 @@ void json_message_process_token(JSONLexer *lexer, GString *input,/* json-parser.c */ JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr); -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp); +void json_parser_init (JSONParserContext *ctxt,va_list *ap); +void json_parser_reset (JSONParserContext *ctxt); +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp); +void json_parser_destroy (JSONParserContext *ctxt);#endif
qobject/json-parser.c +318 -233
614 lines not on this page · raw message
qobject/json-streamer.c +17 -4
@@ -32,6 +32,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y) { JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer); +JSONParserContext ctxt;QObject *json =NULL ;Error *err =NULL ;JSONToken *token;
@@ -56,8 +57,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input,if (g_queue_is_empty (&parser->tokens)) {return ; } - json =json_parser_parse (&parser->tokens, parser->ap, &err); - goto out_emit; +break ;default :break ; }
@@ -85,11 +85,24 @@ void json_message_process_token(JSONLexer *lexer, GString *input,g_queue_push_tail (&parser->tokens, token);if ((parser->brace_count >0 || parser->bracket_count >0 ) - && parser->brace_count >=0 && parser->bracket_count >=0 ) { + && parser->brace_count >=0 && parser->bracket_count >=0 + && type !=JSON_END_OF_INPUT ) {return ; } - json =json_parser_parse (&parser->tokens, parser->ap, &err); +json_parser_init (&ctxt, parser->ap); + +/* Process all tokens in the queue */ +while (!g_queue_is_empty (&parser->tokens)) { + token =g_queue_pop_head (&parser->tokens); + json =json_parser_feed (&ctxt, token, &err); +g_free (token); +if (json || err) { +break ; + } + } + +json_parser_destroy (&ctxt); out_emit: parser->brace_count =0 ;
Signature · 1 line
2.54.0
Re: [PATCH v3 2/7] json-parser: replace with a push parser
Quoted 69 lines · Paolo Bonzini
In order to avoid stashing all the tokens corresponding to a JSON value, embed the parsing stack and state machine in JSONParser. This is more efficient and allows for more prompt error recovery; it also does not make the code substantially larger than the current recursive descent parser, though the state machine is probably a bit harder to follow.
The stack consists of QLists and QDicts corresponding to open brackets and braces, plus optionally a QString with the current key on top of each QDict.
After each value is parsed, it is added to the top array or dictionary or, if the stack is empty,
json_parser_feedreturns the complete QObject.For now,
json-streamer.ckeeps tracking the tokens up until braces and brackets are balanced, and then shoves the whole queue of tokens into the push parser. The only logic change is thatJSON_END_OF_INPUTalways triggers the emptying of the queue; the parser takes notice and checks that there is nothing on the stack. Not usingbrace_countandbracket_countfor this is the first step towards improved separation of concerns betweenjson-parser.candjson-streamer.c.Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 6 + qobject/json-parser-int.h | 5 +- qobject/json-parser.c | 551 ++++++++++++++++++++-------------- qobject/json-streamer.c | 21 +- 4 files changed, 345 insertions(+), 238 deletions(-)include/qobject/json-parser.h +6
-0@@ -20,6 +20,12 @@ typedef struct JSONLexer {int x, y; } JSONLexer; +typedef struct JSONParserContext { +Error *err; +GQueue *stack; +va_list *ap; +}JSONParserContext ; + typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque;qobject/json-parser-int.h +4
-1@@ -49,6 +49,9 @@ void json_message_process_token(JSONLexer *lexer, GString *input,/* json-parser.c */ JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr); -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp); +void json_parser_init (JSONParserContext *ctxt,va_list *ap); +void json_parser_reset (JSONParserContext *ctxt); +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp); +void json_parser_destroy (JSONParserContext *ctxt);#endif qobject/json-parser.c +0
-0@@ -31,12 +31,105 @@ struct JSONToken {char str[]; };
qobject/json-parser.c struct JSONToken { · line 36
Quoted 10 lines
qobject/json-parser.c +3
-6-typedef struct JSONParserContext { -Error *err; -JSONToken *current; -GQueue *buf; -va_list *ap; -}JSONParserContext ; +/* +* The JSON parser is a push parser, returning to the caller after every +* token.
The thing that returns after every token is json_parser_feed(), right?
Detail not mentioned here: the value it returns. Leaving that to json_parser_feed()'s contract feels fine, but pointing from here to there could be useful.
Quoted 38 lines
qobject/json-parser.c +37
-0Therefore it has an explicit representation of its parser +* stack; each stack entry consists of a parser state and a QObject: +* - a QList, for an array that is being added to +* - a QDict, for a dictionary that is being added to +* - a QString, for the key of the next pair that will be added to a QDict +* +* The stack represents an arbitrary nesting of arrays and dictionaries +* (whose next key has been parsed); it can also have a dictionary whose +* next key has not been parsed, but that can only happen at the top level. +* Because of this, the stack contents are always of the form +* "(QList | QDict QString)* QDict?". +* +* An empty stack represents the beginning of the parsing process, with +* start state BEFORE_VALUE. +*/ + +typedef enum JSONParserState { +AFTER_LCURLY , +AFTER_LSQUARE , +BEFORE_KEY , +BEFORE_VALUE , +END_OF_KEY , +END_OF_VALUE , +}JSONParserState ; + +typedef struct JSONParserStackEntry { +/* +* State when the container is completed or, for the top of the stack, +* entry state for the next token. +*/ +JSONParserState state; + +/* +* A QString with the last parsed key, or a QList/QDict for the current +* container. +*/ +QObject *partial; +}JSONParserStackEntry ;
qobject/json-parser.c struct JSONToken { · line 83
Quoted 10 lines
qobject/json-parser.c +10
-0+ +/* +* This is the JSON grammar that's parsed, with the state transition and +* action at each point of the grammar. While this is not a formal +* description, "-> action" represents the pseudocode of the action +* and "-> STATE" sets the top stack entry's state to STATE. +* +* // The initial state is BEFORE_VALUE. +* input := value -> END_OF_VALUE -> return parsed value +* END_OF_INPUT -> check stack is empty
How can the stack *not* be empty here?
Quoted 39 lines
qobject/json-parser.c +39
-0+* +* // entered on BEFORE_VALUE; after any of these rules are processed, the +* // parser has completed a QObject and is in the END_OF_VALUE state. +* // +* // When the parser reaches the END_OF_VALUE state, it examines the +* // top of the stack to see if it's coming from "input" (stack empty), +* // "array_items" (TOS is a QList) or "dict_pairs" (TOS is a QString; the +* // item below will be a QDict). It then proceeds with the corresponding +* // actions, which will be one of: +* // - return parsed value +* // - add value to QList +* // - pop QString with the key, add key/value to the QDict +* value := literal -> END_OF_VALUE +* | '[' -> push empty QList -> AFTER_LSQUARE +* after_lsquare -> END_OF_VALUE +* | '{' -> push empty QDict -> AFTER_LCURLY +* after_lcurly -> END_OF_VALUE +* +* // non-recursive values, entered on BEFORE_VALUE +* literal := INTEGER -> END_OF_VALUE +* | FLOAT -> END_OF_VALUE +* | KEYWORD -> END_OF_VALUE +* | STRING -> END_OF_VALUE +* | INTERP -> END_OF_VALUE +* +* // entered on AFTER_LSQUARE +* after_lsquare := ']' -> pop completed QList -> END_OF_VALUE +* | ϵ -> BEFORE_VALUE +* array_items -> END_OF_VALUE +* +* // entered on BEFORE_VALUE, with TOS being a QList +* array_items := value -> add value to QList -> END_OF_VALUE +* (']' -> pop completed QList -> END_OF_VALUE +* | ',' -> BEFORE_VALUE +* array_items) -> END_OF_VALUE +* +* // entered on AFTER_LCURLY +* after_lcurly := '}' -> pop completed QDict -> END_OF_VALUE +* | ϵ -> BEFORE_KEY
qobject/json-parser.c struct JSONToken { · line 132
Quoted 10 lines
qobject/json-parser.c +10
-0+* dict_pairs -> END_OF_VALUE +* +* // entered on BEFORE_KEY, with TOS being a QDict +* dict_pairs := (STRING | INTERP) -> push QString -> END_OF_KEY +* ':' -> BEFORE_VALUE +* value -> pop QString + add pair to QDict -> END_OF_VALUE +* ('}' -> pop completed QDict -> END_OF_VALUE +* | ',' -> BEFORE_KEY +* dict_pairs) -> END_OF_VALUE +*/
This is useful.
It doesn't mention how we do parse errors. Leaving that to json_parser_feed()'s contract feels fine.
Quoted 18 lines
qobject/json-parser.c +10
-1#define BUG_ON (cond) assert(!(cond))@@ -49,7 +142,26 @@ typedef struct JSONParseCrontext {* 4) deal with premature EOI */ -static QObject *parse_value (JSONParserContext *ctxt); +static inline JSONParserStackEntry *current_entry (JSONParserContext *ctxt) +{ +return g_queue_peek_tail (ctxt->stack); +} + +static void push_entry (JSONParserContext *ctxt,QObject *partial, +JSONParserState state) +{ +JSONParserStackEntry *entry =g_new (JSONParserStackEntry,1 ); + entry->partial = partial;
qobject/json-parser.c typedef struct JSONParseCrontext { · line 164
Quoted 10 lines
qobject/json-parser.c +10
-0+ entry->state = state; +g_queue_push_tail (ctxt->stack, entry); +} + +static JSONParserStackEntry *pop_entry (JSONParserContext *ctxt) +{ +JSONParserStackEntry *entry =g_queue_pop_tail (ctxt->stack); +g_free (entry); +return current_entry (ctxt); +}
This pops the stack and returns the entry now on top. Slightly surprising; pop operations commonly return the entry popped from the stack.
It's this way because you use it like
// invariant: @entry is the entry on top of ctxt->stack, null if empty
value = entry->partial;
entry = pop_entry(ctxt);Okay. A function comment might reduce surprise.
Quoted 294 lines
qobject/json-parser.c +33
-215/** * Error handler @@ -236,200 +348,10 @@ out:return NULL ; } -/* Note: the token object returned by parser_context_peek_token or -* parser_context_pop_token is deleted as soon as parser_context_pop_token -* is called again. -*/ -static const JSONToken *parser_context_pop_token (JSONParserContext *ctxt) +/* Terminals */ + +static QObject *parse_keyword (JSONParserContext *ctxt,const JSONToken *token) { -g_free (ctxt->current); - ctxt->current =g_queue_pop_head (ctxt->buf); -return ctxt->current; -} - -static const JSONToken *parser_context_peek_token (JSONParserContext *ctxt) -{ -return g_queue_peek_head (ctxt->buf); -} - -/** -* Parsing rules -*/ -static int parse_pair (JSONParserContext *ctxt,QDict *dict) -{ -QObject *key_obj =NULL ; -QString *key; -QObject *value; -const JSONToken *peek, *token; - - peek =parser_context_peek_token (ctxt); -if (peek ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - - key_obj =parse_value (ctxt); - key =qobject_to (QString, key_obj); -if (!key) { -parse_error (ctxt, peek,"key is not a string in object" ); - goto out; - } - - token =parser_context_pop_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - -if (token->type !=JSON_COLON ) { -parse_error (ctxt, token,"missing : in object pair" ); - goto out; - } - - value =parse_value (ctxt); -if (value ==NULL ) { -parse_error (ctxt, token,"Missing value in dict" ); - goto out; - } - -if (qdict_haskey (dict,qstring_get_str (key))) { -parse_error (ctxt, token,"duplicate key" ); - goto out; - } - -qdict_put_obj (dict,qstring_get_str (key), value); - -qobject_unref (key_obj); -return 0 ; - -out: -qobject_unref (key_obj); -return -1 ; -} - -static QObject *parse_object (JSONParserContext *ctxt) -{ -QDict *dict =NULL ; -const JSONToken *token, *peek; - - token =parser_context_pop_token (ctxt); -assert (token && token->type ==JSON_LCURLY ); - - dict =qdict_new (); - - peek =parser_context_peek_token (ctxt); -if (peek ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - -if (peek->type !=JSON_RCURLY ) { -if (parse_pair (ctxt, dict) ==-1 ) { - goto out; - } - - token =parser_context_pop_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - -while (token->type !=JSON_RCURLY ) { -if (token->type !=JSON_COMMA ) { -parse_error (ctxt, token,"expected separator in dict" ); - goto out; - } - -if (parse_pair (ctxt, dict) ==-1 ) { - goto out; - } - - token =parser_context_pop_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - } - }else { - (void )parser_context_pop_token (ctxt); - } - -return QOBJECT (dict); - -out: -qobject_unref (dict); -return NULL ; -} - -static QObject *parse_array (JSONParserContext *ctxt) -{ -QList *list =NULL ; -const JSONToken *token, *peek; - - token =parser_context_pop_token (ctxt); -assert (token && token->type ==JSON_LSQUARE ); - - list =qlist_new (); - - peek =parser_context_peek_token (ctxt); -if (peek ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - -if (peek->type !=JSON_RSQUARE ) { -QObject *obj; - - obj =parse_value (ctxt); -if (obj ==NULL ) { -parse_error (ctxt, token,"expecting value" ); - goto out; - } - -qlist_append_obj (list, obj); - - token =parser_context_pop_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - -while (token->type !=JSON_RSQUARE ) { -if (token->type !=JSON_COMMA ) { -parse_error (ctxt, token,"expected separator in list" ); - goto out; - } - - obj =parse_value (ctxt); -if (obj ==NULL ) { -parse_error (ctxt, token,"expecting value" ); - goto out; - } - -qlist_append_obj (list, obj); - - token =parser_context_pop_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); - goto out; - } - } - }else { - (void )parser_context_pop_token (ctxt); - } - -return QOBJECT (list); - -out: -qobject_unref (list); -return NULL ; -} - -static QObject *parse_keyword (JSONParserContext *ctxt) -{ -const JSONToken *token; - - token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_KEYWORD );if (!strcmp (token->str,"true" )) {@@ -443,11 +365,9 @@ static QObject *parse_keyword(JSONParserContext *ctxt)return NULL ; } -static QObject *parse_interpolation (JSONParserContext *ctxt) +static QObject *parse_interpolation (JSONParserContext *ctxt, +const JSONToken *token) { -const JSONToken *token; - - token =parser_context_pop_token (ctxt);assert (token && token->type ==JSON_INTERP );if (!strcmp (token->str,"%p" )) {@@ -479,11 +399,8 @@ static QObject *parse_interpolation(JSONParserContext *ctxt)return NULL ; } -static QObject *parse_literal (JSONParserContext *ctxt) +static QObject *parse_literal (JSONParserContext *ctxt,const JSONToken *token) { -const JSONToken *token; - - token =parser_context_pop_token (ctxt);assert (token);switch (token->type) {@@ -531,35 +448,167 @@ static QObject *parse_literal(JSONParserContext *ctxt) } } -static QObject *parse_value (JSONParserContext *ctxt) +/* Parsing state machine */ + +static QObject *parse_begin_value (JSONParserContext *ctxt, +const JSONToken *token) { -const JSONToken *token; - - token =parser_context_peek_token (ctxt); -if (token ==NULL ) { -parse_error (ctxt,NULL ,"premature EOI" ); -return NULL ; - } -switch (token->type) {case JSON_LCURLY : -return parse_object (ctxt); +push_entry (ctxt,QOBJECT (qdict_new ()),AFTER_LCURLY ); +return NULL ;case JSON_LSQUARE : -return parse_array (ctxt); +push_entry (ctxt,QOBJECT (qlist_new ()),AFTER_LSQUARE ); +return NULL ;case JSON_INTERP : -return parse_interpolation (ctxt); +return parse_interpolation (ctxt, token);case JSON_INTEGER :case JSON_FLOAT :case JSON_STRING : -return parse_literal (ctxt); +return parse_literal (ctxt, token);case JSON_KEYWORD : -return parse_keyword (ctxt); +return parse_keyword (ctxt, token);default :parse_error (ctxt, token,"expecting value" );return NULL ; } } +static QObject *parse_token (JSONParserContext *ctxt,const JSONToken *token) +{ +JSONParserStackEntry *entry; +JSONParserState state; +QString *key; +QObject *key_obj =NULL , *value =NULL ; + + entry =current_entry (ctxt); + state = entry ? entry->state :BEFORE_VALUE ; +switch (state) { +case AFTER_LCURLY : +/* Grab '}' for empty object or fall through to BEFORE_KEY */ +assert (qobject_type (entry->partial) ==QTYPE_QDICT ); +if (token->type ==JSON_RCURLY ) { + value = entry->partial; + entry =pop_entry (ctxt);
qobject/json-parser.c static QObject *parse_literal(JSONParserContext *ctxt) · line 502
Quoted 10 lines
qobject/json-parser.c +10
-0+break ; + } + entry->state =BEFORE_KEY ; +/* fall through */ + +case BEFORE_KEY : +/* Expecting object key */ +assert (qobject_type (entry->partial) ==QTYPE_QDICT ); +if (token->type ==JSON_STRING || token->type ==JSON_INTERP ) { + key_obj =parse_begin_value (ctxt, token);
v2 used parse_string() here, which broke interpolation with %s. This version works.
Quoted 71 lines
qobject/json-parser.c +71
-0+if (!key_obj) { +/* parse error happened */ +return NULL ; + } + } +if (!key_obj ||qobject_type (key_obj) !=QTYPE_QSTRING ) { +parse_error (ctxt, token,"key is not a string in object" ); +return NULL ; + } + +/* Store key in a special entry on the stack */ +push_entry (ctxt, key_obj,END_OF_KEY ); +return NULL ; + +case END_OF_KEY : +/* Expecting ':' after key */ +assert (qobject_type (entry->partial) ==QTYPE_QSTRING ); +if (token->type ==JSON_COLON ) { + entry->state =BEFORE_VALUE ; + }else { +parse_error (ctxt, token,"expecting ':'" ); + } +return NULL ; + +case AFTER_LSQUARE : +/* Grab ']' for empty array or fall through to BEFORE_VALUE */ +assert (qobject_type (entry->partial) ==QTYPE_QLIST ); +if (token->type ==JSON_RSQUARE ) { + value = entry->partial; + entry =pop_entry (ctxt); +break ; + } + entry->state =BEFORE_VALUE ; +/* fall through */ + +case BEFORE_VALUE : +/* Expecting value */ +assert (!entry ||qobject_type (entry->partial) !=QTYPE_QDICT ); + value =parse_begin_value (ctxt, token); +if (!value) { +/* Error or '['/'{' */ +return NULL ; + } +/* Return value or insert it into a container */ +break ; + +case END_OF_VALUE : +/* Grab ',' or ']' for array; ',' or '}' for object */ +if (qobject_to (QList, entry->partial)) { +/* Array */ +if (token->type !=JSON_RSQUARE ) { +if (token->type ==JSON_COMMA ) { + entry->state =BEFORE_VALUE ; + }else { +parse_error (ctxt, token,"expected ',' or ']'" ); + } +return NULL ; + } + }else if (qobject_to (QDict, entry->partial)) { +/* Object */ +if (token->type !=JSON_RCURLY ) { +if (token->type ==JSON_COMMA ) { + entry->state =BEFORE_KEY ; + }else { +parse_error (ctxt, token,"expected ',' or '}'" ); + } +return NULL ; + } + }else { +g_assert_not_reached (); + }
qobject/json-parser.c static QObject *parse_literal(JSONParserContext *ctxt) · line 583
Quoted 10 lines
qobject/json-parser.c +10
-0+ +/* Got ']' or '}'; return full value or insert into parent container */ + value = entry->partial; + entry =pop_entry (ctxt); +break ; + } + +assert (value); +if (entry ==NULL ) { +/* The toplevel value is complete. */
Maybe
/* Parse stack is empty, top level value is complete */
qobject/json-parser.c static QObject *parse_literal(JSONParserContext *ctxt) · line 586
Quoted 3 lines
qobject/json-parser.c +3
-0+return value; + } +
Suggest
/*
* Parse stack is not empty.
* If we're parsing an object, it's QString (key) on top of
* QDict. Pop off key, and store (key, value) in QDict.
* If we're parsing an array, it's QList. Store value in it. */
Quoted 61 lines
qobject/json-parser.c +39
-11+ key =qobject_to (QString, entry->partial); +if (key) { +const char *key_str; +QDict *dict; + + entry =pop_entry (ctxt); + dict =qobject_to (QDict, entry->partial); +assert (dict); + key_str =qstring_get_str (key); +if (qdict_haskey (dict, key_str)) { +parse_error (ctxt, token,"duplicate key" ); +qobject_unref (value); +return NULL ; + } +qdict_put_obj (dict, key_str, value); +qobject_unref (key); + }else { +/* Add to array */ +qlist_append_obj (qobject_to (QList, entry->partial), value); + } + + entry->state =END_OF_VALUE ; +return NULL ; +} +JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr) {JSONToken *token =g_malloc (sizeof (JSONToken) + tokstr->len +1 );@@ -572,20 +621,56 @@ JSONToken *json_token(JSONTokenType type, int x, int y, GString *tokstr)return token; } -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp) +void json_parser_reset (JSONParserContext *ctxt) { -JSONParserContext ctxt = { .buf = tokens, .ap = ap }; -QObject *result; +JSONParserStackEntry *entry; - result =parse_value (&ctxt); -assert (ctxt.err ||g_queue_is_empty (ctxt.buf)); - -error_propagate (errp, ctxt.err); - -while (!g_queue_is_empty (ctxt.buf)) { -parser_context_pop_token (&ctxt); + ctxt->err =NULL ; +while ((entry =g_queue_pop_tail (ctxt->stack)) !=NULL ) { +qobject_unref (entry->partial); +g_free (entry); } -g_free (ctxt.current); +} +void json_parser_init (JSONParserContext *ctxt,va_list *ap) +{ + ctxt->stack =g_queue_new (); + ctxt->ap = ap; +json_parser_reset (ctxt); +} +
qobject/json-parser.c JSONToken *json_token(JSONTokenType type, int x, int y, GString *tokstr) · line 651
Quoted 10 lines
qobject/json-parser.c +10
-0+void json_parser_destroy (JSONParserContext *ctxt) +{ +json_parser_reset (ctxt); +g_queue_free (ctxt->stack); + ctxt->stack =NULL ; +} + +/* +* Advance the parser based on the token that is passed. +* Return the finished toplevel value if the token completes it.
My dictionary wants "top level" or "top-level".
Quoted 74 lines
qobject/json-parser.c +23
-0+* If an error is returned, the function must not be called without +* first resetting the parser. +*/ +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token, +Error **errp) +{ +QObject *result =NULL ; + +assert (!ctxt->err); +switch (token->type) { +case JSON_END_OF_INPUT : +/* Check for premature end of input */ +if (!g_queue_is_empty (ctxt->stack)) { +parse_error (ctxt, token,"premature end of input" ); + } +break ; + +default : + result =parse_token (ctxt, token); +break ; + } + +error_propagate (errp, ctxt->err);return result; }qobject/json-streamer.c +17
-4@@ -32,6 +32,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y) { JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer); +JSONParserContext ctxt;QObject *json =NULL ;Error *err =NULL ;JSONToken *token;@@ -56,8 +57,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input,if (g_queue_is_empty (&parser->tokens)) {return ; } - json =json_parser_parse (&parser->tokens, parser->ap, &err); - goto out_emit; +break ;default :break ; }@@ -85,11 +85,24 @@ void json_message_process_token(JSONLexer *lexer, GString *input,g_queue_push_tail (&parser->tokens, token);if ((parser->brace_count >0 || parser->bracket_count >0 ) - && parser->brace_count >=0 && parser->bracket_count >=0 ) { + && parser->brace_count >=0 && parser->bracket_count >=0 + && type !=JSON_END_OF_INPUT ) {return ; } - json =json_parser_parse (&parser->tokens, parser->ap, &err); +json_parser_init (&ctxt, parser->ap); + +/* Process all tokens in the queue */ +while (!g_queue_is_empty (&parser->tokens)) { + token =g_queue_pop_head (&parser->tokens); + json =json_parser_feed (&ctxt, token, &err); +g_free (token); +if (json || err) { +break ; + } + } + +json_parser_destroy (&ctxt); out_emit: parser->brace_count =0 ;
Re: [PATCH v3 2/7] json-parser: replace with a push parser
Quoted 84 lines · Markus Armbruster
Quoted 69 lines · Paolo Bonzini
In order to avoid stashing all the tokens corresponding to a JSON value, embed the parsing stack and state machine in JSONParser. This is more efficient and allows for more prompt error recovery; it also does not make the code substantially larger than the current recursive descent parser, though the state machine is probably a bit harder to follow.
The stack consists of QLists and QDicts corresponding to open brackets and braces, plus optionally a QString with the current key on top of each QDict.
After each value is parsed, it is added to the top array or dictionary or, if the stack is empty,
json_parser_feedreturns the complete QObject.For now,
json-streamer.ckeeps tracking the tokens up until braces and brackets are balanced, and then shoves the whole queue of tokens into the push parser. The only logic change is thatJSON_END_OF_INPUTalways triggers the emptying of the queue; the parser takes notice and checks that there is nothing on the stack. Not usingbrace_countandbracket_countfor this is the first step towards improved separation of concerns betweenjson-parser.candjson-streamer.c.Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 6 + qobject/json-parser-int.h | 5 +- qobject/json-parser.c | 551 ++++++++++++++++++++-------------- qobject/json-streamer.c | 21 +- 4 files changed, 345 insertions(+), 238 deletions(-)include/qobject/json-parser.h +6
-0@@ -20,6 +20,12 @@ typedef struct JSONLexer {int x, y; } JSONLexer; +typedef struct JSONParserContext { +Error *err; +GQueue *stack; +va_list *ap; +}JSONParserContext ; + typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque;qobject/json-parser-int.h +4
-1@@ -49,6 +49,9 @@ void json_message_process_token(JSONLexer *lexer, GString *input,/* json-parser.c */ JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr); -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp); +void json_parser_init (JSONParserContext *ctxt,va_list *ap); +void json_parser_reset (JSONParserContext *ctxt); +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp); +void json_parser_destroy (JSONParserContext *ctxt);#endif qobject/json-parser.c +0
-0@@ -31,12 +31,105 @@ struct JSONToken {char str[]; };qobject/json-parser.c struct JSONToken { · line 36
Quoted 10 lines
qobject/json-parser.c +3
-6-typedef struct JSONParserContext { -Error *err; -JSONToken *current; -GQueue *buf; -va_list *ap; -}JSONParserContext ; +/* +* The JSON parser is a push parser, returning to the caller after every +* token. The thing that returns after every token is
json_parser_feed(), right?
Quoted 3 lines
Detail not mentioned here: the value it returns. Leaving that to json_parser_feed()'s contract feels fine, but pointing from here to there could be useful.
"returning a completed top-level object, an error, or NULL (if the object is incomplete and no error happened) after every token"?
Quoted 5 lines
qobject/json-parser.c struct JSONToken { · line 83
Quoted 3 lines
qobject/json-parser.c +3
-0+* // The initial state is BEFORE_VALUE. +* input := value -> END_OF_VALUE -> return parsed value +* END_OF_INPUT -> check stack is empty How can the stack *not* be empty here?
Right, this is not END_OF_INPUT in the middle of the stream. Will delete.
Quoted 9 lines
qobject/json-parser.c struct JSONToken { · line 132
Quoted 8 lines
qobject/json-parser.c +8
-0+* // entered on BEFORE_KEY, with TOS being a QDict +* dict_pairs := (STRING | INTERP) -> push QString -> END_OF_KEY +* ':' -> BEFORE_VALUE +* value -> pop QString + add pair to QDict -> END_OF_VALUE +* ('}' -> pop completed QDict -> END_OF_VALUE +* | ',' -> BEFORE_KEY +* dict_pairs) -> END_OF_VALUE +*/
Quoted 4 lines
This is useful.
It doesn't mention how we do parse errors. Leaving that to json_parser_feed()'s contract feels fine.
Right---parse errors are out of the scope because recovery happens in json-streamer.c.
I can add a note for this and everything else, thanks for the review! Rewrites are not the most enticing form of thing to receive, or the most polite to send.
Paolo
Re: [PATCH v3 2/7] json-parser: replace with a push parser
Quoted 85 lines · Paolo Bonzini
Quoted 75 lines · Markus Armbruster
Quoted 73 lines · Paolo Bonzini
In order to avoid stashing all the tokens corresponding to a JSON value, embed the parsing stack and state machine in JSONParser. This is more efficient and allows for more prompt error recovery; it also does not make the code substantially larger than the current recursive descent parser, though the state machine is probably a bit harder to follow.
The stack consists of QLists and QDicts corresponding to open brackets and braces, plus optionally a QString with the current key on top of each QDict.
After each value is parsed, it is added to the top array or dictionary or, if the stack is empty,
json_parser_feedreturns the complete QObject.For now,
json-streamer.ckeeps tracking the tokens up until braces and brackets are balanced, and then shoves the whole queue of tokens into the push parser. The only logic change is thatJSON_END_OF_INPUTalways triggers the emptying of the queue; the parser takes notice and checks that there is nothing on the stack. Not usingbrace_countandbracket_countfor this is the first step towards improved separation of concerns betweenjson-parser.candjson-streamer.c.Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 6 + qobject/json-parser-int.h | 5 +- qobject/json-parser.c | 551 ++++++++++++++++++++-------------- qobject/json-streamer.c | 21 +- 4 files changed, 345 insertions(+), 238 deletions(-)include/qobject/json-parser.h +5
-0@@ -20,6 +20,12 @@ typedef struct JSONLexer {int x, y; } JSONLexer; +typedef struct JSONParserContext { +Error *err; +GQueue *stack; +va_list *ap; +} JSONParserContext; + typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque;qobject/json-parser-int.h +4
-1@@ -49,6 +49,9 @@ void json_message_process_token(JSONLexer *lexer, GString *input,/* json-parser.c */ JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr); -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp); +void json_parser_init (JSONParserContext *ctxt,va_list *ap); +void json_parser_reset (JSONParserContext *ctxt); +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp); +void json_parser_destroy (JSONParserContext *ctxt);#endif qobject/json-parser.c +0
-6@@ -31,12 +31,105 @@ struct JSONToken {char str[]; }; -typedef struct JSONParserContext { -Error *err; -JSONToken *current; -GQueue *buf; -va_list *ap; -}JSONParserContext ;Quoted 8 lines
qobject/json-parser.c struct JSONToken {
Quoted 3 lines
qobject/json-parser.c +3
-0+/* +* The JSON parser is a push parser, returning to the caller after every +* token. The thing that returns after every token is
json_parser_feed(), right? Detail not mentioned here: the value it returns. Leaving that to json_parser_feed()'s contract feels fine, but pointing from here to there could be useful.
Quoted 1 line
"returning a completed top-level object, an error, or NULL (if the object is incomplete and no error happened) after every token"?
I like it!
Quoted 18 lines
Quoted 5 lines
qobject/json-parser.c struct JSONToken { · line 83
Quoted 3 lines
qobject/json-parser.c +3
-0+* // The initial state is BEFORE_VALUE. +* input := value -> END_OF_VALUE -> return parsed value +* END_OF_INPUT -> check stack is empty How can the stack *not* be empty here?
Right, this is not
END_OF_INPUTin the middle of the stream. Will delete.Quoted 11 lines
qobject/json-parser.c struct JSONToken { · line 132
Quoted 8 lines
qobject/json-parser.c +8
-0+* // entered on BEFORE_KEY, with TOS being a QDict +* dict_pairs := (STRING | INTERP) -> push QString -> END_OF_KEY +* ':' -> BEFORE_VALUE +* value -> pop QString + add pair to QDict -> END_OF_VALUE +* ('}' -> pop completed QDict -> END_OF_VALUE +* | ',' -> BEFORE_KEY +* dict_pairs) -> END_OF_VALUE +*/ This is useful.
Quoted 8 lines
Quoted 2 lines
It doesn't mention how we do parse errors. Leaving that to json_parser_feed()'s contract feels fine.
Right---parse errors are out of the scope because recovery happens in
json-streamer.c.I can add a note for this and everything else, thanks for the review! Rewrites are not the most enticing form of thing to receive, or the most polite to send.
Paolo
In all fairness, I had moaned about this parser more than once, e.g. "it's half-assed: it's a push lexer wed to a pull parser with parenthesis counting."
Re: [PATCH v3 2/7] json-parser: replace with a push parser
In reply to Paolo BonziniQuoted 23 lines · Paolo Bonzini
In order to avoid stashing all the tokens corresponding to a JSON value, embed the parsing stack and state machine in JSONParser. This is more efficient and allows for more prompt error recovery; it also does not make the code substantially larger than the current recursive descent parser, though the state machine is probably a bit harder to follow.
The stack consists of QLists and QDicts corresponding to open brackets and braces, plus optionally a QString with the current key on top of each QDict.
After each value is parsed, it is added to the top array or dictionary or, if the stack is empty,
json_parser_feedreturns the complete QObject.For now,
json-streamer.ckeeps tracking the tokens up until braces and brackets are balanced, and then shoves the whole queue of tokens into the push parser. The only logic change is thatJSON_END_OF_INPUTalways triggers the emptying of the queue; the parser takes notice and checks that there is nothing on the stack. Not usingbrace_countandbracket_countfor this is the first step towards improved separation of concerns betweenjson-parser.candjson-streamer.c.Signed-off-by Paolo Bonzini <[email protected]>
[...]
qobject/json-parser-int.h void json_message_process_token(JSONLexer *lexer, GString *input, · line 54
Quoted 12 lines
qobject/json-parser-int.h +3
-1@@ -49,6 +49,9 @@ void json_message_process_token(JSONLexer *lexer, GString *input,/* json-parser.c */ JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr); -QObject *json_parser_parse (GQueue *tokens,va_list *ap,Error **errp); +void json_parser_init (JSONParserContext *ctxt,va_list *ap); +void json_parser_reset (JSONParserContext *ctxt); +QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp);
checkpatch WARNING: line over 80 characters. It's just a warning, but the line is *really* easy to break.
Quoted 3 lines
qobject/json-parser-int.h +1
-0+void json_parser_destroy (JSONParserContext *ctxt);#endif
[...]
Re: [PATCH v3 2/7] json-parser: replace with a push parser
In reply to Paolo BonziniThe error reported for
{"abc":32,}changes from
JSON parse error, expecting value
to
JSON parse error, key is not a string in object
I like the new one less.
This is check-qjson.c case /errors/invalid_dict_comma.
Re: [PATCH v3 2/7] json-parser: replace with a push parser
Quoted 8 lines · Markus Armbruster
The error reported for
{"abc":32,}changes from
JSON parse error, expecting value
Quoted 7 lines
to
JSON parse error, key is not a string in object
I like the new one less.
This is
check-qjson.ccase /errors/invalid_dict_comma.
sure, this is due to conflating two separate error cases. Easily fixed (untested):
/* Expecting object key */
assert(qobject_type(entry->partial) == QTYPE_QDICT);
if (token->type != JSON_STRING && token->type != JSON_INTERP) {
parse_error(ctxt, token, "expecting value");
return NULL;
}
key_obj = parse_begin_value(ctxt, token);
if (!key_obj) {
/* Parse error already reported */
} else if (qobject_type(key_obj) != QTYPE_QSTRING) {
/* An interpolation was valid syntactically but not %s */
parse_error(ctxt, token, "key is not a string in object");
} else {
/* Store key in a special entry on the stack */
push_entry(ctxt, key_obj, END_OF_KEY);
}Paolo
PATCH v3 3/7 json-streamer: reuse parser
In reply to Paolo BonziniThe push parser can be reset, so reuse it when the json-streamer detects a completed toplevel object.
--- include/qobject/json-parser.h | 2 +- qobject/json-streamer.c | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-)
include/qobject/json-parser.h +1 -1
@@ -29,8 +29,8 @@ typedef struct JSONParserContext { typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque; - va_list *ap; JSONLexer lexer; + JSONParserContext parser; int brace_count; int bracket_count; GQueue tokens;
qobject/json-streamer.c +4 -7
@@ -32,7 +32,6 @@ void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y) { JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer); -JSONParserContext ctxt;QObject *json =NULL ;Error *err =NULL ;JSONToken *token;
@@ -90,26 +89,23 @@ void json_message_process_token(JSONLexer *lexer, GString *input,return ; } -json_parser_init (&ctxt, parser->ap); -/* Process all tokens in the queue */ while (!g_queue_is_empty (&parser->tokens)) { token =g_queue_pop_head (&parser->tokens); - json =json_parser_feed (&ctxt, token, &err); + json =json_parser_feed (&parser->parser, token, &err);g_free (token);if (json || err) {break ; } } -json_parser_destroy (&ctxt); - out_emit: parser->brace_count =0 ; parser->bracket_count =0 ;json_message_free_tokens (parser); parser->token_size =0 ; parser->emit (parser->opaque, json, err); +json_parser_reset (&parser->parser); } void json_message_parser_init(JSONMessageParser *parser,
@@ -119,12 +115,12 @@ void json_message_parser_init(JSONMessageParser *parser, { parser->emit = emit; parser->opaque = opaque; - parser->ap = ap; parser->brace_count =0 ; parser->bracket_count =0 ;g_queue_init (&parser->tokens); parser->token_size =0 ; +json_parser_init (&parser->parser, ap);json_lexer_init (&parser->lexer, !!ap); }
@@ -144,4 +140,5 @@ void json_message_parser_destroy(JSONMessageParser *parser) {json_lexer_destroy (&parser->lexer);json_message_free_tokens (parser); +json_parser_destroy (&parser->parser); }
Signature · 1 line
2.54.0
Re: [PATCH v3 3/7] json-streamer: reuse parser
Quoted 52 lines · Paolo Bonzini
The push parser can be reset, so reuse it when the json-streamer detects a completed toplevel object.
Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 2 +- qobject/json-streamer.c | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-)include/qobject/json-parser.h +1
-1@@ -29,8 +29,8 @@ typedef struct JSONParserContext { typedef struct JSONMessageParser { void (*emit)(void *opaque, QObject *json, Error *err); void *opaque; - va_list *ap; JSONLexer lexer; + JSONParserContext parser; int brace_count; int bracket_count; GQueue tokens;qobject/json-streamer.c +1
-4@@ -32,7 +32,6 @@ void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y) { JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer); -JSONParserContext ctxt;QObject *json =NULL ;Error *err =NULL ;JSONToken *token;@@ -90,26 +89,23 @@ void json_message_process_token(JSONLexer *lexer, GString *input,return ; } -json_parser_init (&ctxt, parser->ap); -/* Process all tokens in the queue */ while (!g_queue_is_empty (&parser->tokens)) { token =g_queue_pop_head (&parser->tokens); - json =json_parser_feed (&ctxt, token, &err); + json =json_parser_feed (&parser->parser, token, &err);g_free (token);if (json || err) {break ; } }
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 109
Quoted 10 lines
qobject/json-streamer.c +1
-2-json_parser_destroy (&ctxt); - out_emit: parser->brace_count =0 ; parser->bracket_count =0 ;json_message_free_tokens (parser); parser->token_size =0 ; parser->emit (parser->opaque, json, err); +json_parser_reset (&parser->parser); }
This made me stop and think.
I figure the more obvious *delta* would be to json_parser_reset() right where json_parser_destroy() was.
But putting it here makes the code more obviously correct, I think.
No objection. A hint in the commit message could've saved me a minute or two.
Quoted 17 lines
qobject/json-streamer.c +1
-1void json_message_parser_init(JSONMessageParser *parser,@@ -119,12 +115,12 @@ void json_message_parser_init(JSONMessageParser *parser, { parser->emit = emit; parser->opaque = opaque; - parser->ap = ap; parser->brace_count =0 ; parser->bracket_count =0 ;g_queue_init (&parser->tokens); parser->token_size =0 ; +json_parser_init (&parser->parser, ap);json_lexer_init (&parser->lexer, !!ap); }
qobject/json-streamer.c void json_message_parser_destroy(JSONMessageParser *parser) · line 144
Quoted 5 lines
qobject/json-streamer.c +1
-0@@ -144,4 +140,5 @@ void json_message_parser_destroy(JSONMessageParser *parser) {json_lexer_destroy (&parser->lexer);json_message_free_tokens (parser); +json_parser_destroy (&parser->parser); }
PATCH v3 4/7 json-streamer: make brace/bracket count unsigned
In reply to Paolo BonziniIt makes no sense to let brace_count and bracket_count go negative, also because it immediately ends error recovery and sets them both back to zero. Instead set them to zero *before* choosing whether to process the token queue; this makes it possible to have the fields as unsigned.
Note that JSON_END_OF_INPUT now forces the parentheses to appear balanced, so that the queue is emptied and an error is reported; hence, the "type != JSON_END_OF_INPUT" condition can be removed.
--- include/qobject/json-parser.h | 4 ++-- qobject/json-streamer.c | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-)
include/qobject/json-parser.h +2 -2
@@ -31,8 +31,8 @@ typedef struct JSONMessageParser {void *opaque;JSONLexer lexer;JSONParserContext parser; -int brace_count; -int bracket_count; +unsigned int brace_count; +unsigned int bracket_count;GQueue tokens;uint64_t token_size; } JSONMessageParser;
qobject/json-streamer.c +16 -3
@@ -41,12 +41,18 @@ void json_message_process_token(JSONLexer *lexer, GString *input, parser->brace_count++;break ;case JSON_RCURLY : +if (parser->brace_count <=0 ) { + goto end_error_recovery; + } parser->brace_count--;break ;case JSON_LSQUARE : parser->bracket_count++;break ;case JSON_RSQUARE : +if (parser->bracket_count <=0 ) { + goto end_error_recovery; + } parser->bracket_count--;break ;case JSON_ERROR :
@@ -56,6 +62,15 @@ void json_message_process_token(JSONLexer *lexer, GString *input,if (g_queue_is_empty (&parser->tokens)) {return ; } + end_error_recovery: +/* +* Cause error recovery to end immediately. +* If not in error recovery, the parser will raise an error +* (due to JSON_ERROR or unexpected JSON_R{CURLY,SQUARE}) +* but error recovery won't be entered at all. +*/ + parser->brace_count =0 ; + parser->bracket_count =0 ;break ;default :break ;
@@ -83,9 +98,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input,g_queue_push_tail (&parser->tokens, token); -if ((parser->brace_count >0 || parser->bracket_count >0 ) - && parser->brace_count >=0 && parser->bracket_count >=0 - && type !=JSON_END_OF_INPUT ) { +if (parser->brace_count >0 || parser->bracket_count >0 ) {return ; }
Signature · 1 line
2.54.0
Re: [PATCH v3 4/7] json-streamer: make brace/bracket count unsigned
Quoted 36 lines · Paolo Bonzini
It makes no sense to let
brace_countandbracket_countgo negative, also because it immediately ends error recovery and sets them both back to zero. Instead set them to zero *before* choosing whether to process the token queue; this makes it possible to have the fields as unsigned.Note that
JSON_END_OF_INPUTnow forces the parentheses to appear balanced, so that the queue is emptied and an error is reported; hence, the "type !=JSON_END_OF_INPUT" condition can be removed.Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 4 ++-- qobject/json-streamer.c | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-)include/qobject/json-parser.h +2
-2@@ -31,8 +31,8 @@ typedef struct JSONMessageParser {void *opaque;JSONLexer lexer;JSONParserContext parser; -int brace_count; -int bracket_count; +unsigned int brace_count; +unsigned int bracket_count;GQueue tokens;uint64_t token_size; } JSONMessageParser;qobject/json-streamer.c +0
-0
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 44
Quoted 4 lines
qobject/json-streamer.c +1
-0@@ -41,12 +41,18 @@ void json_message_process_token(JSONLexer *lexer, GString *input, parser->brace_count++;break ;case JSON_RCURLY : +if (parser->brace_count <=0 ) {
Why <= 0? parser->brace_count is unsigned now...
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 53
Quoted 9 lines
qobject/json-streamer.c +3
-0+ goto end_error_recovery; + } parser->brace_count--;break ;case JSON_LSQUARE : parser->bracket_count++;break ;case JSON_RSQUARE : +if (parser->bracket_count <=0 ) {
Likewise.
Quoted 6 lines
qobject/json-streamer.c +2
-0+ goto end_error_recovery; + } parser->bracket_count--;break ;case JSON_ERROR :
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 69
Quoted 8 lines
qobject/json-streamer.c +5
-0@@ -56,6 +62,15 @@ void json_message_process_token(JSONLexer *lexer, GString *input,if (g_queue_is_empty (&parser->tokens)) {return ; } + end_error_recovery: +/* +* Cause error recovery to end immediately. +* If not in error recovery, the parser will raise an error +* (due to JSON_ERROR or unexpected JSON_R{CURLY,SQUARE})
What do you mean by "due to JSON_ERROR"?
We get here on unmatched } or ]: that's the gotos
you add above.
We also get here on end of non-empty input: that's when the if right above doesn't return.
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 71
Quoted 2 lines
qobject/json-streamer.c +2
-0+* but error recovery won't be entered at all. +*/
This is the only comment on error recovery. Would a comment giving a brief overview on error recovery be useful?
Quoted 6 lines
qobject/json-streamer.c +2
-0+ parser->brace_count =0 ; + parser->bracket_count =0 ;break ;default :break ;
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 103
Quoted 9 lines
qobject/json-streamer.c +1
-3@@ -83,9 +98,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input,g_queue_push_tail (&parser->tokens, token); -if ((parser->brace_count >0 || parser->bracket_count >0 ) - && parser->brace_count >=0 && parser->bracket_count >=0 - && type !=JSON_END_OF_INPUT ) { +if (parser->brace_count >0 || parser->bracket_count >0 ) {return ; }
We get here when
* no lexical error, and
* no limits exceeded, and
* the curlies and squares are balanced, either in fact or because we passed through end_error_recovery.
Good.
/* Process all tokens in the queue */
while (!g_queue_is_empty(&parser->tokens)) {Re: [PATCH v3 4/7] json-streamer: make brace/bracket count unsigned
Quoted 5 lines · Markus Armbruster
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 69
Quoted 3 lines
qobject/json-streamer.c +3
-0+* Cause error recovery to end immediately. +* If not in error recovery, the parser will raise an error +* (due to JSON_ERROR or unexpected JSON_R{CURLY,SQUARE}) What do you mean by "due to
JSON_ERROR"?
due to passing it to json_parser_feed(). Rewritten:
/*
* We goto here due to receiving either JSON_ERROR or a
* JSON_R{CURLY,SQUARE}) that is known to be unbalanced.
* If in error recovery, end it immediately. If not in
* error recovery, json_parser_feed() will raise an error
* but error recovery won't be entered at all. */
Quoted 11 lines
We get here on unmatched } or ]: that's the gotos
you add above.We also get here on end of non-empty input: that's when the if right above doesn't return.
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 71
Quoted 2 lines
qobject/json-streamer.c +2
-0+* but error recovery won't be entered at all. +*/ This is the only comment on error recovery. Would a comment giving a brief overview on error recovery be useful?
It is added in the next commit. At this point there are still relics of the GQueue so it's kinda pointless.
Paolo
Quoted 32 lines
Quoted 6 lines
qobject/json-streamer.c +2
-0+ parser->brace_count =0 ; + parser->bracket_count =0 ;break ;default :break ;qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 103
Quoted 9 lines
qobject/json-streamer.c +1
-3@@ -83,9 +98,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input,g_queue_push_tail (&parser->tokens, token); -if ((parser->brace_count >0 || parser->bracket_count >0 ) - && parser->brace_count >=0 && parser->bracket_count >=0 - && type !=JSON_END_OF_INPUT ) { +if (parser->brace_count >0 || parser->bracket_count >0 ) {return ; }We get here when
* no lexical error, and
* no limits exceeded, and
* the curlies and squares are balanced, either in fact or because we passed through
end_error_recovery.Good.
/* Process all tokens in the queue */ while (!g_queue_is_empty(&parser->tokens)) {
PATCH v3 5/7 json-streamer: remove token queue
In reply to Paolo BonziniNow fully exploit the push parser, feeding it one token at a time without having to wait until braces and brackets are balanced.
While the nesting counts are retained for error recovery purposes, the system can now report the first parsing error without waiting for parentheses to be balanced. This also means that JSON_ERROR can be handled in json-parser.c, not json-streamer.c.
After reporting the error, json-streamer.c then enters an error recovery mode where subsequent errors are suppressed. This mimics the previous error reporting behavior, but it provides prompt feedback on parsing errors. As an example, here is an example interaction with qemu-ga.
BEFORE (error reported only once braces are balanced):
Quoted 2 lines
Quoted 2 lines
{"execute":foo
}
<< {"error": {"class": "GenericError", "desc": "JSON parse error, invalid keyword 'foo'"}}
Quoted 1 line
Quoted 1 line
{"execute":"somecommand"}
<< {"error": {"class": "CommandNotFound", "desc": "The command somecommand has not been found"}}
AFTER (error reported immediately, but similar error recovery as before):
Quoted 1 line
Quoted 1 line
{"execute":foo
<< {"error": {"class": "GenericError", "desc": "JSON parse error, invalid keyword 'foo'"}}
Quoted 2 lines
Quoted 2 lines
}
{"execute":"somecommand"}
<< {"error": {"class": "CommandNotFound", "desc": "The command somecommand has not been found"}}
--- include/qobject/json-parser.h | 3 +- qobject/json-parser.c | 4 ++ qobject/json-streamer.c | 100 ++++++++++++++-------------------- 3 files changed, 46 insertions(+), 61 deletions(-)
include/qobject/json-parser.h +2 -1
@@ -33,7 +33,8 @@ typedef struct JSONMessageParser {JSONParserContext parser;unsigned int brace_count;unsigned int bracket_count; -GQueue tokens; +unsigned int token_count; +bool error;uint64_t token_size; } JSONMessageParser;
qobject/json-parser.c +4 -0
@@ -659,6 +659,10 @@ QObject *json_parser_feed(JSONParserContext *ctxt, const JSONToken *token,assert (!ctxt->err);switch (token->type) { +case JSON_ERROR : +parse_error (ctxt, token,"JSON parse error, stray '%s'" , token->str); +break ; +case JSON_END_OF_INPUT :/* Check for premature end of input */ if (!g_queue_is_empty (ctxt->stack)) {
qobject/json-streamer.c +40 -60
150 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v3 5/7] json-streamer: remove token queue
Quoted 21 lines · Paolo Bonzini
Now fully exploit the push parser, feeding it one token at a time without having to wait until braces and brackets are balanced.
While the nesting counts are retained for error recovery purposes, the system can now report the first parsing error without waiting for parentheses to be balanced. This also means that
JSON_ERRORcan be handled injson-parser.c, notjson-streamer.c.After reporting the error,
json-streamer.cthen enters an error recovery mode where subsequent errors are suppressed. This mimics the previous error reporting behavior, but it provides prompt feedback on parsing errors. As an example, here is an example interaction with qemu-ga.BEFORE (error reported only once braces are balanced):
Quoted 2 lines
Quoted 2 lines
{"execute":foo
}<< {"error": {"class": "GenericError", "desc": "JSON parse error, invalid keyword 'foo'"}}
Quoted 1 line
Quoted 1 line
{"execute":"somecommand"}
<< {"error": {"class": "CommandNotFound", "desc": "The command somecommand has not been found"}}
Quoted 7 lines
AFTER (error reported immediately, but similar error recovery as before):
Quoted 1 line
Quoted 1 line
{"execute":foo
<< {"error": {"class": "GenericError", "desc": "JSON parse error, invalid keyword 'foo'"}}
Quoted 2 lines
Quoted 2 lines
}
{"execute":"somecommand"}<< {"error": {"class": "CommandNotFound", "desc": "The command somecommand has not been found"}}
Welcome quality of life improvement for human use of QMP, such as manual testing. The experience is still sub-par when you miss closing
parenthesis: you still get the silent treatment. However, the confused input a confused user is likely to send then is now more likely to produce an error, and thus a parser reset.
Quoted 42 lines
Signed-off-by Paolo Bonzini <[email protected]>--- include/qobject/json-parser.h | 3 +- qobject/json-parser.c | 4 ++ qobject/json-streamer.c | 100 ++++++++++++++-------------------- 3 files changed, 46 insertions(+), 61 deletions(-)include/qobject/json-parser.h +2
-1@@ -33,7 +33,8 @@ typedef struct JSONMessageParser {JSONParserContext parser;unsigned int brace_count;unsigned int bracket_count; -GQueue tokens; +unsigned int token_count; +bool error;uint64_t token_size; } JSONMessageParser;qobject/json-parser.c +4
-0@@ -659,6 +659,10 @@ QObject *json_parser_feed(JSONParserContext *ctxt, const JSONToken *token,assert (!ctxt->err);switch (token->type) { +case JSON_ERROR : +parse_error (ctxt, token,"JSON parse error, stray '%s'" , token->str); +break ; +case JSON_END_OF_INPUT :/* Check for premature end of input */ if (!g_queue_is_empty (ctxt->stack)) {qobject/json-streamer.c +0
-0
qobject/json-streamer.c line 2
Quoted 3 lines
qobject/json-streamer.c +1
-1@@ -1,5 +1,5 @@/* -* JSON streaming support +* JSON parser - callback interface and error recovery
The file name is now a bit of a misnomer. I don't care.
Quoted 16 lines
qobject/json-streamer.c +0
-9* * Copyright IBM, Corp. 2009 * @@ -19,23 +19,16 @@#define MAX_TOKEN_COUNT (2ULL << 20)#define MAX_NESTING (1 << 10) -static void json_message_free_tokens (JSONMessageParser *parser) -{ -JSONToken *token; - -while ((token =g_queue_pop_head (&parser->tokens))) { -g_free (token); - } -} -
qobject/json-streamer.c line 29
Quoted 10 lines
qobject/json-streamer.c +2
-2void json_message_process_token (JSONLexer *lexer,GString *input,JSONTokenType type,int x,int y) {JSONMessageParser *parser =container_of (lexer, JSONMessageParser, lexer); -QObject *json =NULL ;Error *err =NULL ; -JSONToken *token; + parser->token_size += input->len; + parser->token_count++;
Note for later: @token_size and @token_count are incremented early rather than late.
Quoted 19 lines
qobject/json-streamer.c +2
-6+ +/* Detect message boundaries for error recovery purposes. */ switch (type) {case JSON_LCURLY : parser->brace_count++;@@ -56,12 +49,6 @@ void json_message_process_token(JSONLexer *lexer, GString *input, parser->bracket_count--;break ;case JSON_ERROR : -error_setg (&err,"JSON parse error, stray '%s'" , input->str); - goto out_emit; -case JSON_END_OF_INPUT : -if (g_queue_is_empty (&parser->tokens)) { -return ; - } end_error_recovery:/* * Cause error recovery to end immediately.
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 83
Quoted 8 lines
qobject/json-streamer.c +0
-5@@ -76,49 +63,43 @@ void json_message_process_token(JSONLexer *lexer, GString *input,break ; } -/* -* Security consideration, we limit total memory allocated per object -* and the maximum recursion depth that a message can force. -*/ -if (parser->token_size + input->len +1 >MAX_TOKEN_SIZE ) {
Left operand of > is unincremented token_size plus increment plus 1.
Quoted 9 lines
qobject/json-streamer.c +0
-9-error_setg (&err,"JSON token size limit exceeded" ); - goto out_emit; - } -if (g_queue_get_length (&parser->tokens) +1 >MAX_TOKEN_COUNT ) { -error_setg (&err,"JSON token count limit exceeded" ); - goto out_emit; - } -if (parser->bracket_count + parser->brace_count >MAX_NESTING ) { -error_setg (&err,"JSON nesting depth limit exceeded" );
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 73
Quoted 10 lines
qobject/json-streamer.c +8
-2- goto out_emit; - } +if (parser->error) { +/* error recovery, eat tokens until parentheses balance */ + }else { +/* +* Safety consideration, we limit total memory allocated per object +* and the maximum nesting depth that a message can force. +*/ +if (parser->token_size >MAX_TOKEN_SIZE ) {
Left operand of > is incremented token size.
Isn't this one less than before the patch?
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 75
Quoted 2 lines
qobject/json-streamer.c +2
-0+error_setg (&err,"JSON token size limit exceeded" ); + }else if (parser->token_count >MAX_TOKEN_COUNT ) {
Likewise.
Quoted 33 lines
qobject/json-streamer.c +14
-16+error_setg (&err,"JSON token count limit exceeded" ); + }else if (parser->bracket_count + parser->brace_count >MAX_NESTING ) { +error_setg (&err,"JSON nesting depth limit exceeded" ); + }else { + g_autofree JSONToken *token = json_token(type, x, y, input); +QObject *json =json_parser_feed (&parser->parser, token, &err); +if (json) { + parser->emit (parser->opaque, json,NULL ); + } + } - token =json_token (type, x, y, input); - parser->token_size += input->len; - -g_queue_push_tail (&parser->tokens, token); - -if (parser->brace_count >0 || parser->bracket_count >0 ) { -return ; - } - -/* Process all tokens in the queue */ -while (!g_queue_is_empty (&parser->tokens)) { - token =g_queue_pop_head (&parser->tokens); - json =json_parser_feed (&parser->parser, token, &err); -g_free (token); -if (json || err) { -break ; +if (err) { + parser->emit (parser->opaque,NULL , err); +/* start recovery */ + parser->error = true; } }
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 95
Quoted 10 lines
qobject/json-streamer.c +2
-7-out_emit: - parser->brace_count =0 ; - parser->bracket_count =0 ; -json_message_free_tokens (parser); - parser->token_size =0 ; - parser->emit (parser->opaque, json, err); -json_parser_reset (&parser->parser); +if ((parser->brace_count ==0 && parser->bracket_count ==0 ) + || type ==JSON_END_OF_INPUT ) {
We need to check for JSON_END_OF_INPUT, because this is the one error that cannot go through normal error recovery "eat tokens until curlies and squares balance or we ate JSON_END_OF_INPUT". Took me a few minutes to figure out.
Quoted 35 lines
qobject/json-streamer.c +9
-3+ parser->error = false; + parser->brace_count =0 ; + parser->bracket_count =0 ; + parser->token_count =0 ; + parser->token_size =0 ; +json_parser_reset (&parser->parser); + } } void json_message_parser_init(JSONMessageParser *parser,@@ -128,9 +109,10 @@ void json_message_parser_init(JSONMessageParser *parser, { parser->emit = emit; parser->opaque = opaque; + parser->error = false; parser->brace_count =0 ; parser->bracket_count =0 ; -g_queue_init (&parser->tokens); + parser->token_count =0 ; parser->token_size =0 ;json_parser_init (&parser->parser, ap);@@ -146,12 +128,10 @@ void json_message_parser_feed(JSONMessageParser *parser,void json_message_parser_flush (JSONMessageParser *parser) {json_lexer_flush (&parser->lexer); -assert (g_queue_is_empty (&parser->tokens)); }void json_message_parser_destroy (JSONMessageParser *parser) {json_lexer_destroy (&parser->lexer); -json_message_free_tokens (parser);json_parser_destroy (&parser->parser); }
Re: [PATCH v3 5/7] json-streamer: remove token queue
Quoted 5 lines · Markus Armbruster
qobject/json-streamer.c line 29
Quoted 2 lines
qobject/json-streamer.c +2
-0+ parser->token_size += input->len; + parser->token_count++;Note for later: @token_size and @token_count are incremented early rather than late.
Yes.
Quoted 16 lines
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 83
Quoted 5 lines
qobject/json-streamer.c +0
-5-/* -* Security consideration, we limit total memory allocated per object -* and the maximum recursion depth that a message can force. -*/ -if (parser->token_size + input->len +1 >MAX_TOKEN_SIZE ) {Left operand of > is unincremented
token_sizeplus increment plus 1.Quoted 8 lines
qobject/json-streamer.c +0
-8-if (g_queue_get_length (&parser->tokens) +1 >MAX_TOKEN_COUNT ) { -error_setg (&err,"JSON token count limit exceeded" ); - goto out_emit; - } -if (parser->bracket_count + parser->brace_count >MAX_NESTING ) { -error_setg (&err,"JSON nesting depth limit exceeded" ); - goto out_emit; - }
...
Quoted 8 lines
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 73
Quoted 4 lines
qobject/json-streamer.c +4
-0+* Safety consideration, we limit total memory allocated per object +* and the maximum nesting depth that a message can force. +*/ +if (parser->token_size >MAX_TOKEN_SIZE ) {Left operand of > is incremented token size.
Isn't this one less than before the patch?
Yes.
Quoted 4 lines
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 75
Quoted 2 lines
qobject/json-streamer.c +2
-0+error_setg (&err,"JSON token size limit exceeded" ); + }else if (parser->token_count >MAX_TOKEN_COUNT ) {Likewise.
Not here, g_queue_get_length() was incremented before g_queue_push_tail().
The MAX_NESTING comparison is pre-incremented both before and after my patch.
In the end the only difference between before and after is for MAX_TOKEN_SIZE. I honestly didn't notice, but it seems to me that the difference is irrelevant and the new code is more consistent.
I'm not sure if the code before was written to mimic the two pre-incremented conditionals, but either way the first "+ 1" does not make much sense logically:
if (parser->token_size + input->len + 1 > MAX_TOKEN_SIZE) {
if (g_queue_get_length(&parser->tokens) + 1 > MAX_TOKEN_COUNT) {and (unlike the second) would be better written as >=.
Paolo
Quoted 51 lines
qobject/json-streamer.c void json_message_process_token(JSONLexer *lexer, GString *input, · line 95
Quoted 9 lines
qobject/json-streamer.c +2
-7-out_emit: - parser->brace_count =0 ; - parser->bracket_count =0 ; -json_message_free_tokens (parser); - parser->token_size =0 ; - parser->emit (parser->opaque, json, err); -json_parser_reset (&parser->parser); +if ((parser->brace_count ==0 && parser->bracket_count ==0 ) + || type ==JSON_END_OF_INPUT ) {We need to check for
JSON_END_OF_INPUT, because this is the one error that cannot go through normal error recovery "eat tokens until curlies and squares balance or we ateJSON_END_OF_INPUT". Took me a few minutes to figure out.Quoted 35 lines
qobject/json-streamer.c +9
-3+ parser->error = false; + parser->brace_count =0 ; + parser->bracket_count =0 ; + parser->token_count =0 ; + parser->token_size =0 ; +json_parser_reset (&parser->parser); + } } void json_message_parser_init(JSONMessageParser *parser,@@ -128,9 +109,10 @@ void json_message_parser_init(JSONMessageParser *parser, { parser->emit = emit; parser->opaque = opaque; + parser->error = false; parser->brace_count =0 ; parser->bracket_count =0 ; -g_queue_init (&parser->tokens); + parser->token_count =0 ; parser->token_size =0 ;json_parser_init (&parser->parser, ap);@@ -146,12 +128,10 @@ void json_message_parser_feed(JSONMessageParser *parser,void json_message_parser_flush (JSONMessageParser *parser) {json_lexer_flush (&parser->lexer); -assert (g_queue_is_empty (&parser->tokens)); }void json_message_parser_destroy (JSONMessageParser *parser) {json_lexer_destroy (&parser->lexer); -json_message_free_tokens (parser);json_parser_destroy (&parser->parser); }
Re: [PATCH v3 5/7] json-streamer: remove token queue
In reply to Paolo BonziniLexical errors change from
JSON parse error, stray '@'
to
JSON parse error, JSON parse error, stray '@'
Re: [PATCH v3 5/7] json-streamer: remove token queue
Quoted 8 lines · Markus Armbruster
Lexical errors change from
JSON parse error, stray '@'
to
JSON parse error, JSON parse error, stray '@'
Oops...
Paolo
PATCH v3 6/7 json-streamer: do not heap-allocate JSONToken
In reply to Paolo BonziniThis is not needed with a push parser. Since it processes tokens immediately, the JSONToken can be created directly on the stack and does not need to copy the lexer's string data.
--- qobject/json-parser-int.h | 8 ++++++-- qobject/json-parser.c | 18 ------------------ qobject/json-streamer.c | 9 +++++++-- 3 files changed, 13 insertions(+), 22 deletions(-)
qobject/json-parser-int.h +6 -2
@@ -35,7 +35,12 @@ typedef enum json_token_type { JSON_MAX = JSON_END_OF_INPUT } JSONTokenType; -typedef struct JSONToken JSONToken ; +typedef struct JSONToken { +JSONTokenType type; +int x; +int y; +char *str; +}JSONToken ;/* json-lexer.c */ void json_lexer_init (JSONLexer *lexer,bool enable_interpolation);
@@ -48,7 +53,6 @@ void json_message_process_token(JSONLexer *lexer, GString *input, JSONTokenType type, int x, int y);/* json-parser.c */ -JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr);void json_parser_init (JSONParserContext *ctxt,va_list *ap);void json_parser_reset (JSONParserContext *ctxt);QObject *json_parser_feed (JSONParserContext *ctxt,const JSONToken *token,Error **errp);
qobject/json-parser.c +0 -18
@@ -24,13 +24,6 @@#include "qobject/qstring.h" #include "json-parser-int.h" -struct JSONToken { -JSONTokenType type; -int x; -int y; -char str[]; -}; -/* * The JSON parser is a push parser, returning to the caller after every * token. Therefore it has an explicit representation of its parser
@@ -609,17 +602,6 @@ static QObject *parse_token(JSONParserContext *ctxt, const JSONToken *token)return NULL ; } -JSONToken *json_token (JSONTokenType type,int x,int y,GString *tokstr) -{ -JSONToken *token =g_malloc (sizeof (JSONToken) + tokstr->len +1 ); - - token->type = type; -memcpy (token->str, tokstr->str, tokstr->len); - token->str[tokstr->len] =0 ; - token->x = x; - token->y = y; -return token; -}void json_parser_reset (JSONParserContext *ctxt) {
qobject/json-streamer.c +7 -2
@@ -77,8 +77,13 @@ void json_message_process_token(JSONLexer *lexer, GString *input, }else if (parser->bracket_count + parser->brace_count >MAX_NESTING ) {error_setg (&err,"JSON nesting depth limit exceeded" ); }else { - g_autofree JSONToken *token = json_token(type, x, y, input); -QObject *json =json_parser_feed (&parser->parser, token, &err); +JSONToken token = (JSONToken ) { + .type = type, + .x = x, + .y = y, + .str = input->str + }; +QObject *json =json_parser_feed (&parser->parser, &token, &err);if (json) { parser->emit (parser->opaque, json,NULL ); }
Signature · 1 line
2.54.0
PATCH v3 7/7 json-parser: add location to JSON parsing errors
In reply to Paolo BonziniNow that all calls to parse_error have a token, add the line and column to the message. As far as I can see the two important TODOs (better errors and better EOI handling) are done, and the others (token range information and "parsed size"?) do not really matter or are handled better by json-streamer.c. So remove the list, which had sat unchanged since 2009.
This needs some adjustments to provide a good x and y for error messages. First of all, they switch from zero-based to one-based, which is safe because they were both sitting unused. Second, right now the x and y are those of the *last* character in the token. Modify json-lexer.c to freeze tok->x and tok->y at the first character added to the GString.
--- include/qobject/json-parser.h | 1 + qobject/json-lexer.c | 11 +++++++---- qobject/json-parser.c | 12 ++---------- 3 files changed, 10 insertions(+), 14 deletions(-)
include/qobject/json-parser.h +1 -0
@@ -17,6 +17,7 @@typedef struct JSONLexer {int start_state, state;GString *token; +int cur_x, cur_y;int x, y; }JSONLexer ;
qobject/json-lexer.c +7 -4
@@ -277,7 +277,8 @@ void json_lexer_init(JSONLexer *lexer, bool enable_interpolation) lexer->start_state = lexer->state = enable_interpolation ?IN_START_INTERP :IN_START ; lexer->token =g_string_sized_new (3 ); - lexer->x = lexer->y =0 ; + lexer->cur_x = lexer->cur_y =1 ; + lexer->x = lexer->y =1 ; }static void json_lexer_feed_char (JSONLexer *lexer,char ch,bool flush)
@@ -285,10 +286,10 @@ static void json_lexer_feed_char(JSONLexer *lexer, char ch, bool flush)int new_state;bool char_consumed = false; - lexer->x++; + lexer->cur_x++;if (ch =='\n' ) { - lexer->x =0 ; - lexer->y++; + lexer->cur_x =1 ; + lexer->cur_y++; }while (flush ? lexer->state != lexer->start_state : !char_consumed) {
@@ -316,6 +317,8 @@ static void json_lexer_feed_char(JSONLexer *lexer, char ch, bool flush)case IN_START :g_string_truncate (lexer->token,0 ); new_state = lexer->start_state; + lexer->x = lexer->cur_x; + lexer->y = lexer->cur_y;break ;case JSON_ERROR : json_message_process_token(lexer, lexer->token, JSON_ERROR,
qobject/json-parser.c +2 -10
@@ -126,15 +126,6 @@ typedef struct JSONParserStackEntry {#define BUG_ON (cond) assert(!(cond)) -/** -* TODO -* -* 0) make errors meaningful again -* 1) add geometry information to tokens -* 3) should we return a parsed size? -* 4) deal with premature EOI -*/ -static inline JSONParserStackEntry *current_entry (JSONParserContext *ctxt) {return g_queue_peek_tail (ctxt->stack);
@@ -172,7 +163,8 @@ static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt,va_start (ap, msg);vsnprintf (message,sizeof (message), msg, ap);va_end (ap); -error_setg (&ctxt->err,"JSON parse error, %s" , message); +error_setg (&ctxt->err,"JSON parse error at line %d, column %d, %s" , + token->y, token->x, message); }static int cvt4hex (const char *s)
Signature · 1 line
2.54.0
Re: [PATCH v3 7/7] json-parser: add location to JSON parsing errors
Quoted 7 lines · Paolo Bonzini
Now that all calls to
parse_errorhave a token, add the line and column to the message. As far as I can see the two important TODOs (better errors and better EOI handling) are done, and the others (token range information and "parsed size"?) do not really matter or are handled better byjson-streamer.c. So remove the list, which had sat unchanged since 2009.
Quoted 7 lines
This needs some adjustments to provide a good x and y for error messages. First of all, they switch from zero-based to one-based, which is safe because they were both sitting unused. Second, right now the x and y are those of the *last* character in the token. Modify
json-lexer.cto freezetok->xandtok->yat the first character added to the GString.Signed-off-by Paolo Bonzini <[email protected]>
QMP errors become obviously better, e.g.
-> {"execute": "qmp_capabilities", "arguments": {"enable": ["oob"]}}
<- {"return": {}}
-> {"execute": "query-commands"]
<- {"error": {"class": "GenericError", "desc": "JSON parse error, expected ',' or '}'"}}improves to
<- {"error": {"class": "GenericError", "desc": "JSON parse error at line 2, column 29, expected ',' or '}'"}}The change to CLI errors is a mixed bag, e.g.
$ qemu-system-x86_64 -S -blockdev '{"driver": "host_cdrom", "node-name": "blk0", "filename": "/dev/sr0"'
qemu-system-x86_64: -blockdev {"driver": "host_cdrom", "node-name": "blk0", "filename": "/dev/sr0": JSON parse error, premature end of inputbecomes
qemu-system-x86_64: -blockdev {"driver": "host_cdrom", "node-name": "blk0", "filename": "/dev/sr0": JSON parse error at line 1, column 69, premature end of input
I fear this is confusing. If you understand what's happening here, the "column 69" part has value. The "line 1" part is mostly noise.
Might be less of an issue with more compact location information. See below.
Quoted 76 lines
--- include/qobject/json-parser.h | 1 + qobject/json-lexer.c | 11 +++++++---- qobject/json-parser.c | 12 ++---------- 3 files changed, 10 insertions(+), 14 deletions(-)include/qobject/json-parser.h +1
-0@@ -17,6 +17,7 @@typedef struct JSONLexer {int start_state, state;GString *token; +int cur_x, cur_y;int x, y; }JSONLexer ;qobject/json-lexer.c +7
-4@@ -277,7 +277,8 @@ void json_lexer_init(JSONLexer *lexer, bool enable_interpolation) lexer->start_state = lexer->state = enable_interpolation ?IN_START_INTERP :IN_START ; lexer->token =g_string_sized_new (3 ); - lexer->x = lexer->y =0 ; + lexer->cur_x = lexer->cur_y =1 ; + lexer->x = lexer->y =1 ; }static void json_lexer_feed_char (JSONLexer *lexer,char ch,bool flush)@@ -285,10 +286,10 @@ static void json_lexer_feed_char(JSONLexer *lexer, char ch, bool flush)int new_state;bool char_consumed = false; - lexer->x++; + lexer->cur_x++;if (ch =='\n' ) { - lexer->x =0 ; - lexer->y++; + lexer->cur_x =1 ; + lexer->cur_y++; }while (flush ? lexer->state != lexer->start_state : !char_consumed) {@@ -316,6 +317,8 @@ static void json_lexer_feed_char(JSONLexer *lexer, char ch, bool flush)case IN_START :g_string_truncate (lexer->token,0 ); new_state = lexer->start_state; + lexer->x = lexer->cur_x; + lexer->y = lexer->cur_y;break ;case JSON_ERROR : json_message_process_token(lexer, lexer->token, JSON_ERROR,qobject/json-parser.c +0
-9@@ -126,15 +126,6 @@ typedef struct JSONParserStackEntry {#define BUG_ON (cond) assert(!(cond)) -/** -* TODO -* -* 0) make errors meaningful again -* 1) add geometry information to tokens -* 3) should we return a parsed size? -* 4) deal with premature EOI -*/ -static inline JSONParserStackEntry *current_entry (JSONParserContext *ctxt) {return g_queue_peek_tail (ctxt->stack);
qobject/json-parser.c static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt, · line 166
Quoted 5 lines
qobject/json-parser.c +1
-1@@ -172,7 +163,8 @@ static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt,va_start (ap, msg);vsnprintf (message,sizeof (message), msg, ap);va_end (ap); -error_setg (&ctxt->err,"JSON parse error, %s" , message); + error_setg(&ctxt->err, "JSON parse error at line %d, column %d, %s",
The usual format used by code parsing tools such as compilers is like
"%d:%d: JSON parse error: %s, token->x, token->y, message
Should we use it?
Quoted 4 lines
qobject/json-parser.c +1
-0+ token->y, token->x, message); }static int cvt4hex (const char *s)
Re: [PATCH v3 7/7] json-parser: add location to JSON parsing errors
Quoted 8 lines · Markus Armbruster
qobject/json-parser.c static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt, · line 166
Quoted 2 lines
qobject/json-parser.c +1
-1-error_setg (&ctxt->err,"JSON parse error, %s" , message); + error_setg(&ctxt->err, "JSON parse error at line %d, column %d, %s",The usual format used by code parsing tools such as compilers is like
"%d:%d: JSON parse error: %s, token->x, token->y, messageShould we use it?
Sure, why not.
Paolo
Just a heads up that I'm planning to include this in a pull request around mid June.
Paolo
Quoted 67 lines · Paolo Bonzini
This rewrites the json-parser to use a push parser aka state machine. While push parsers are inherently more complex than recursive descent, the grammar for JSON is simple enough that the parser remains readable. There is therefore no need to use e.g. QEMU coroutines.
Unlike the suggestion in commit
62815d85aed("json: Redesign the callback to consume JSON values", 2018-08-24), I kept the json-streamer concept. It helps in handling input limits, it performs error recovery, and it converts the token-at-a-time push interface to callbacks---all things that are more easily done in a separate layer to keep the parser clean. However, there is no need anymore for it to store partial JSON objects in tokenized form, because the current state is stored in the push parser's stack.Another benefit is that QEMU can report the first parsing error immediately, without waiting for parentheses to be balanced or for a lexing error. Error recovery then proceeds as before (i.e., the next parse still starts after balanced parentheses or a lexing error).
On top of the benefits intrinsic in the push architecture, it so happens that it's really easy to add a location to JSON parsing errors now, so do that as well.
The diffstat is unfavorable, but most of the new lines delta is really new comments explaining the grammar and state machines.
Paolo
v2->v3:
- accept interpolation for the key of a dictionary
v1->v2:
- remove part of the patch to pass around the lookahead token, it was hard to review and added little value
- separate patch to reuse the JSONParser
- separate patch to make brace/bracket count unsigned
- add comment with the structure of the stack
- add big comment with the grammar
- split long lines
- remove QObject **value argument topop_entry()
- add assertions about the type of the top-of-stack
- change error to "key is not a string in object"
- split outjson_parser_reset()already in the first patch
- renamejson_parser_parse_token()toparse_token()
- do not use single quotes in commit messages
- move initialization of JSONToken close to usagePaolo Bonzini (7):
json-parser: constify JSONToken
json-parser: replace with a push parser
json-streamer: reuse parser
json-streamer: make brace/bracket count unsigned
json-streamer: remove token queue
json-streamer: do not heap-allocate JSONToken
json-parser: add location to JSON parsing errorsinclude/qobject/json-parser.h | 16 +- qobject/json-parser-int.h | 13 +- qobject/json-lexer.c | 11 +- qobject/json-parser.c | 580 +++++++++++++++++++--------------- qobject/json-streamer.c | 120 +++---- 5 files changed, 415 insertions(+), 325 deletions(-)--
2.54.0
Looks pretty good. One more respin should get us there.
Thank you!
Quoted 1 line · Markus Armbruster
Looks pretty good. One more respin should get us there.
Cool, I attach the current overall delta from your review comments.
Paolo
qobject/json-parser.c +31 -17
@@ -71,9 +71,12 @@ typedef struct JSONParserStackEntry {* description, "-> action" represents the pseudocode of the action * and "-> STATE" sets the top stack entry's state to STATE. * +* The state alone is enough to tell you what to parse; the state plus +* the type of the top of stack tells you which action to take. +* * // The initial state is BEFORE_VALUE. * input := value -> END_OF_VALUE -> return parsed value -* END_OF_INPUT -> check stack is empty +* (input | END_OF_INPUT) * * // entered on BEFORE_VALUE; after any of these rules are processed, the * // parser has completed a QObject and is in the END_OF_VALUE state.
@@ -122,6 +125,9 @@ typedef struct JSONParserStackEntry {* ('}' -> pop completed QDict -> END_OF_VALUE * | ',' -> BEFORE_KEY * dict_pairs) -> END_OF_VALUE +* +* Parse errors ignore the token. json_parser_reset() can be +* called to restart parsing from scratch, with an empty stack. */ #define BUG_ON (cond) assert(!(cond))
@@ -140,6 +146,7 @@ static void push_entry(JSONParserContext *ctxt, QObject *partial,g_queue_push_tail (ctxt->stack, entry); } +/* Drop the top entry and return the new top entry. */ static JSONParserStackEntry *pop_entry (JSONParserContext *ctxt) {JSONParserStackEntry *entry =g_queue_pop_tail (ctxt->stack);
@@ -163,7 +170,7 @@ static void G_GNUC_PRINTF(3, 4) parse_error(JSONParserContext *ctxt,va_start (ap, msg);vsnprintf (message,sizeof (message), msg, ap);va_end (ap); -error_setg (&ctxt->err,"JSON parse error at line %d, column %d, %s" , +error_setg (&ctxt->err,"%d:%d: JSON parse error, %s" , token->y, token->x, message); }
@@ -483,20 +490,21 @@ static QObject *parse_token(JSONParserContext *ctxt, const JSONToken *token)case BEFORE_KEY :/* Expecting object key */ assert (qobject_type (entry->partial) ==QTYPE_QDICT ); -if (token->type ==JSON_STRING || token->type ==JSON_INTERP ) { - key_obj =parse_begin_value (ctxt, token); -if (!key_obj) { -/* parse error happened */ -return NULL ; - } - } -if (!key_obj ||qobject_type (key_obj) !=QTYPE_QSTRING ) { -parse_error (ctxt, token,"key is not a string in object" ); +if (token->type !=JSON_STRING && token->type !=JSON_INTERP ) { +parse_error (ctxt, token,"expecting value" );return NULL ; } -/* Store key in a special entry on the stack */ -push_entry (ctxt, key_obj,END_OF_KEY ); + key_obj =parse_begin_value (ctxt, token); +if (!key_obj) { +/* Parse error already reported */ + }else if (qobject_type (key_obj) !=QTYPE_QSTRING ) { +/* An interpolation was valid syntactically but not %s */ +parse_error (ctxt, token,"key is not a string in object" ); + }else { +/* Store key in a special entry on the stack */ +push_entry (ctxt, key_obj,END_OF_KEY ); + }return NULL ;case END_OF_KEY :
@@ -565,15 +573,21 @@ static QObject *parse_token(JSONParserContext *ctxt, const JSONToken *token)assert (value);if (entry ==NULL ) { -/* The toplevel value is complete. */ +/* Parse stack now empty, the top-level value is complete. */ return value; } +/* +* Parse stack is not empty and entry->partial is the top of stack. +* It's a QString with the key (and a QDict is below it) if we're +* parsing an object, or a QList if we're parsing an array. +*/ key =qobject_to (QString, entry->partial);if (key) {const char *key_str;QDict *dict; +/* Pop off key, and store (key, value) in QDict. */ entry =pop_entry (ctxt); dict =qobject_to (QDict, entry->partial);assert (dict);
@@ -586,7 +600,7 @@ static QObject *parse_token(JSONParserContext *ctxt, const JSONToken *token)qdict_put_obj (dict, key_str, value);qobject_unref (key); }else { -/* Add to array */ +/* Array, just store value in the QList. */ qlist_append_obj (qobject_to (QList, entry->partial), value); }
@@ -622,7 +636,7 @@ void json_parser_destroy(JSONParserContext *ctxt)/* * Advance the parser based on the token that is passed. -* Return the finished toplevel value if the token completes it. +* Return the finished top-level value if the token completes it. * If an error is returned, the function must not be called without * first resetting the parser. */
@@ -634,7 +648,7 @@ QObject *json_parser_feed(JSONParserContext *ctxt, const JSONToken *token,assert (!ctxt->err);switch (token->type) {case JSON_ERROR : -parse_error (ctxt, token,"JSON parse error, stray '%s'" , token->str); +parse_error (ctxt, token,"stray '%s'" , token->str);break ;case JSON_END_OF_INPUT :
qobject/json-streamer.c +7 -6
@@ -34,7 +34,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input, parser->brace_count++;break ;case JSON_RCURLY : -if (parser->brace_count <=0 ) { +if (!parser->brace_count) { goto end_error_recovery; } parser->brace_count--;
@@ -43,7 +43,7 @@ void json_message_process_token(JSONLexer *lexer, GString *input, parser->bracket_count++;break ;case JSON_RSQUARE : -if (parser->bracket_count <=0 ) { +if (!parser->bracket_count) { goto end_error_recovery; } parser->bracket_count--;
@@ -51,9 +51,10 @@ void json_message_process_token(JSONLexer *lexer, GString *input,case JSON_ERROR : end_error_recovery:/* -* Cause error recovery to end immediately. -* If not in error recovery, the parser will raise an error -* (due to JSON_ERROR or unexpected JSON_R{CURLY,SQUARE}) +* We come here due to receiving either JSON_ERROR or a +* JSON_R{CURLY,SQUARE}) that is known to be unbalanced. +* If in error recovery, end it immediately. If not in +* error recovery, json_parser_feed() will raise an error * but error recovery won't be entered at all. */ parser->brace_count =0 ;
@@ -98,12 +99,12 @@ void json_message_process_token(JSONLexer *lexer, GString *input,if ((parser->brace_count ==0 && parser->bracket_count ==0 ) || type ==JSON_END_OF_INPUT ) { +json_parser_reset (&parser->parser); parser->error = false; parser->brace_count =0 ; parser->bracket_count =0 ; parser->token_count =0 ; parser->token_size =0 ; -json_parser_reset (&parser->parser); } }