authorgravatar for 14938807+xackus@users.noreply.github.comxackus <14938807+xackus@users.noreply.github.com> 2019-11-11 23:25:54+01:00
committergravatar for 14938807+xackus@users.noreply.github.comxackus <14938807+xackus@users.noreply.github.com> 2019-11-11 23:25:54+01:00
logf9b7d6d75d24fa5844a6b83be312722d1a71efaf
tree73ad9202faeb6a3ad2175bc90a780b22325facdb
parent371747d8fb270c7d2f80a5e3a43ef0485332a070

Fix bugs in JSON parser

Make comments into documentation where appropriate

2 files changed, 69 insertions(+), 60 deletions(-)

lib/std/json.zig+53-40
......@@ -10,18 +10,18 @@ const maxInt = std.math.maxInt;
1010
1111pub const WriteStream = @import("json/write_stream.zig").WriteStream;
1212
13// A single token slice into the parent string.
14//
15// Use `token.slice()` on the input at the current position to get the current slice.
13/// A single token slice into the parent string.
14///
15/// Use `token.slice()` on the input at the current position to get the current slice.
1616pub const Token = struct {
1717 id: Id,
18 // How many bytes do we skip before counting
18 /// How many bytes do we skip before counting
1919 offset: u1,
20 // Whether string contains a \uXXXX sequence and cannot be zero-copied
20 /// Whether string contains an escape sequence and cannot be zero-copied
2121 string_has_escape: bool,
22 // Whether number is simple and can be represented by an integer (i.e. no `.` or `e`)
22 /// Whether number is simple and can be represented by an integer (i.e. no `.` or `e`)
2323 number_is_integer: bool,
24 // How many bytes from the current position behind the start of this token is.
24 /// How many bytes from the current position behind the start of this token is.
2525 count: usize,
2626
2727 pub const Id = enum {
......@@ -66,7 +66,7 @@ pub const Token = struct {
6666 };
6767 }
6868
69 // A marker token is a zero-length
69 /// A marker token is a zero-length
7070 pub fn initMarker(id: Id) Token {
7171 return Token{
7272 .id = id,
......@@ -77,19 +77,19 @@ pub const Token = struct {
7777 };
7878 }
7979
80 // Slice into the underlying input string.
80 /// Slice into the underlying input string.
8181 pub fn slice(self: Token, input: []const u8, i: usize) []const u8 {
8282 return input[i + self.offset - self.count .. i + self.offset];
8383 }
8484};
8585
86// A small streaming JSON parser. This accepts input one byte at a time and returns tokens as
87// they are encountered. No copies or allocations are performed during parsing and the entire
88// parsing state requires ~40-50 bytes of stack space.
89//
90// Conforms strictly to RFC8529.
91//
92// For a non-byte based wrapper, consider using TokenStream instead.
86/// A small streaming JSON parser. This accepts input one byte at a time and returns tokens as
87/// they are encountered. No copies or allocations are performed during parsing and the entire
88/// parsing state requires ~40-50 bytes of stack space.
89///
90/// Conforms strictly to RFC8529.
91///
92/// For a non-byte based wrapper, consider using TokenStream instead.
9393pub const StreamingParser = struct {
9494 // Current state
9595 state: State,
......@@ -205,10 +205,10 @@ pub const StreamingParser = struct {
205205 InvalidControlCharacter,
206206 };
207207
208 // Give another byte to the parser and obtain any new tokens. This may (rarely) return two
209 // tokens. token2 is always null if token1 is null.
210 //
211 // There is currently no error recovery on a bad stream.
208 /// Give another byte to the parser and obtain any new tokens. This may (rarely) return two
209 /// tokens. token2 is always null if token1 is null.
210 ///
211 /// There is currently no error recovery on a bad stream.
212212 pub fn feed(p: *StreamingParser, c: u8, token1: *?Token, token2: *?Token) Error!void {
213213 token1.* = null;
214214 token2.* = null;
......@@ -860,7 +860,7 @@ pub const StreamingParser = struct {
860860 }
861861};
862862
863// A small wrapper over a StreamingParser for full slices. Returns a stream of json Tokens.
863/// A small wrapper over a StreamingParser for full slices. Returns a stream of json Tokens.
864864pub const TokenStream = struct {
865865 i: usize,
866866 slice: []const u8,
......@@ -898,7 +898,13 @@ pub const TokenStream = struct {
898898 }
899899 }
900900
901 if (self.parser.complete) {
901 // Without this a bare number fails, becasue the streaming parser doesn't know it ended
902 try self.parser.feed(' ', &t1, &t2);
903 self.i += 1;
904
905 if (t1) |token| {
906 return token;
907 } else if (self.parser.complete) {
902908 return null;
903909 } else {
904910 return error.UnexpectedEndOfJson;
......@@ -1050,7 +1056,7 @@ pub const Value = union(enum) {
10501056 }
10511057};
10521058
1053// A non-stream JSON parser which constructs a tree of Value's.
1059/// A non-stream JSON parser which constructs a tree of Value's.
10541060pub const Parser = struct {
10551061 allocator: *Allocator,
10561062 state: State,
......@@ -1119,7 +1125,10 @@ pub const Parser = struct {
11191125 p.state = State.ObjectValue;
11201126 },
11211127 else => {
1122 unreachable;
1128 // The streaming parser would return an error eventually.
1129 // To prevent invalid state we return an error now.
1130 // TODO make the streaming parser return an error as soon as it encounters an invalid object key
1131 return error.InvalidLiteral;
11231132 },
11241133 },
11251134 State.ObjectValue => {
......@@ -1276,6 +1285,10 @@ pub const Parser = struct {
12761285// Only to be used on strings already validated by the parser
12771286// (note the unreachable statements and lack of bounds checking)
12781287// Optimized for arena allocators, uses Allocator.shrink
1288//
1289// Idea: count how many bytes we will need to allocate in the streaming parser and store it
1290// in the token to avoid allocating too much memory or iterating through the string again
1291// Downside: need to find how many bytes a unicode escape sequence will produce twice
12791292fn unescapeStringAlloc(alloc: *Allocator, input: []const u8) ![]u8 {
12801293 const output = try alloc.alloc(u8, input.len);
12811294 errdefer alloc.free(output);
......@@ -1290,22 +1303,22 @@ fn unescapeStringAlloc(alloc: *Allocator, input: []const u8) ![]u8 {
12901303 inIndex += 1;
12911304 outIndex += 1;
12921305 } else if(input[inIndex + 1] != 'u'){
1293 // a simple escape sequence
1294 output[outIndex] = @as(u8,
1295 switch(input[inIndex + 1]){
1296 '\\' => '\\',
1297 '/' => '/',
1298 'n' => '\n',
1299 'r' => '\r',
1300 't' => '\t',
1301 'f' => 12,
1302 'b' => 8,
1303 '"' => '"',
1304 else => unreachable
1305 }
1306 );
1307 inIndex += 2;
1308 outIndex += 1;
1306 // a simple escape sequence
1307 output[outIndex] = @as(u8,
1308 switch(input[inIndex + 1]){
1309 '\\' => '\\',
1310 '/' => '/',
1311 'n' => '\n',
1312 'r' => '\r',
1313 't' => '\t',
1314 'f' => 12,
1315 'b' => 8,
1316 '"' => '"',
1317 else => unreachable
1318 }
1319 );
1320 inIndex += 2;
1321 outIndex += 1;
13091322 } else {
13101323 // a unicode escape sequence
13111324 const firstCodeUnit = std.fmt.parseInt(u16, input[inIndex+2 .. inIndex+6], 16) catch unreachable;
lib/std/json/test.zig+16-20
......@@ -559,17 +559,15 @@ test "y_structure_lonely_false" {
559559}
560560
561561test "y_structure_lonely_int" {
562 return error.SkipZigTest;
563// ok(
564// \\42
565// );
562 ok(
563 \\42
564 );
566565}
567566
568567test "y_structure_lonely_negative_real" {
569 return error.SkipZigTest;
570// ok(
571// \\-0.1
572// );
568 ok(
569 \\-0.1
570 );
573571}
574572
575573test "y_structure_lonely_null" {
......@@ -1107,10 +1105,9 @@ test "n_object_bad_value" {
11071105}
11081106
11091107test "n_object_bracket_key" {
1110 return error.SkipZigTest;
1111// err(
1112// \\{[: "x"}
1113// );
1108 err(
1109 \\{[: "x"}
1110 );
11141111}
11151112
11161113test "n_object_comma_instead_of_colon" {
......@@ -1192,10 +1189,9 @@ test "n_object_non_string_key" {
11921189}
11931190
11941191test "n_object_repeated_null_null" {
1195 return error.SkipZigTest;
1196// err(
1197// \\{null:null,null:null}
1198// );
1192 err(
1193 \\{null:null,null:null}
1194 );
11991195}
12001196
12011197test "n_object_several_trailing_commas" {
......@@ -1618,10 +1614,9 @@ test "n_structure_open_object" {
16181614}
16191615
16201616test "n_structure_open_object_open_array" {
1621 return error.SkipZigTest;
1622 // err(
1623 // \\{[
1624 // );
1617 err(
1618 \\{[
1619 );
16251620}
16261621
16271622test "n_structure_open_object_open_string" {
......@@ -1734,6 +1729,7 @@ test "i_number_double_huge_neg_exp" {
17341729
17351730test "i_number_huge_exp" {
17361731 return error.SkipZigTest;
1732 // FIXME Integer overflow in parseFloat
17371733// any(
17381734// \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
17391735// );