Debian Codegraph @

t/sl_json.t

raw
1 #!/usr/bin/perl
2 # Copyright 2022 Jeffrey Kegler
3 # This file is part of Marpa::R2. Marpa::R2 is free software: you can
4 # redistribute it and/or modify it under the terms of the GNU Lesser
5 # General Public License as published by the Free Software Foundation,
6 # either version 3 of the License, or (at your option) any later version.
7 #
8 # Marpa::R2 is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser
14 # General Public License along with Marpa::R2. If not, see
15 # http://www.gnu.org/licenses/.
16
17 # Test using a JSON parser
18 # Inspired by a parser written by Peter Stuifzand
19
20 use 5.010001;
21 use strict;
22 use warnings;
23 use Test::More tests => 14;
24 use English qw( -no_match_vars );
25 use Scalar::Util qw(blessed);
26
27 use lib 'inc';
28 use Marpa::R2::Test;
29
30 ## no critic (ErrorHandling::RequireCarping);
31
32 use Marpa::R2;
33
34 my $p = MarpaX::JSON->new();
35
36 my $data = $p->parse_json(q${"test":"1"}$);
37 is($data->{test}, 1);
38
39 {
40 my $test = q${"test":[1,2,3]}$;
41 $data = $p->parse_json(q${"test":[1,2,3]}$);
42 is_deeply( $data->{test}, [ 1, 2, 3 ], $test );
43 }
44
45 $data = $p->parse_json(q${"test":true}$);
46 is($data->{test}, 1);
47
48 $data = $p->parse_json(q${"test":false}$);
49 is($data->{test}, '');
50
51 $data = $p->parse_json(q${"test":null}$);
52 is($data->{test}, undef);
53
54 $data = $p->parse_json(q${"test":null, "test2":"hello world"}$);
55 is($data->{test}, undef);
56 is($data->{test2}, "hello world");
57
58 $data = $p->parse_json(q${"test":"1.25"}$);
59 is($data->{test}, '1.25', '1.25');
60
61 $data = $p->parse_json(q${"test":"1.25e4"}$);
62 is($data->{test}, '1.25e4', '1.25e4');
63
64 $data = $p->parse_json(q$[]$);
65 is_deeply($data, [], '[]');
66
67 $data = $p->parse_json(<<'JSON');
68 [
69 {
70 "precision": "zip",
71 "Latitude": 37.7668,
72 "Longitude": -122.3959,
73 "Address": "",
74 "City": "SAN FRANCISCO",
75 "State": "CA",
76 "Zip": "94107",
77 "Country": "US"
78 },
79 {
80 "precision": "zip",
81 "Latitude": 37.371991,
82 "Longitude": -122.026020,
83 "Address": "",
84 "City": "SUNNYVALE",
85 "State": "CA",
86 "Zip": "94085",
87 "Country": "US"
88 }
89 ]
90 JSON
91 is_deeply($data, [
92 { "precision"=>"zip", Latitude => "37.7668", Longitude=>"-122.3959",
93 "Country" => "US", Zip => 94107, Address => '',
94 City => "SAN FRANCISCO", State => 'CA' },
95 { "precision" => "zip", Longitude => "-122.026020", Address => "",
96 City => "SUNNYVALE", Country => "US", Latitude => "37.371991",
97 Zip => 94085, State => "CA" }
98 ], 'Geo data');
99
100 $data = $p->parse_json(<<'JSON');
101 {
102 "Image": {
103 "Width": 800,
104 "Height": 600,
105 "Title": "View from 15th Floor",
106 "Thumbnail": {
107 "Url": "http://www.example.com/image/481989943",
108 "Height": 125,
109 "Width": "100"
110 },
111 "IDs": [116, 943, 234, 38793]
112 }
113 }
114 JSON
115 is_deeply($data, {
116 "Image" => {
117 "Width" => 800, "Height" => 600,
118 "Title" => "View from 15th Floor",
119 "Thumbnail" => {
120 "Url" => "http://www.example.com/image/481989943",
121 "Height" => 125,
122 "Width" => 100,
123 },
124 "IDs" => [ 116, 943, 234, 38793 ],
125 }
126 }, 'is_deeply test');
127
128 my $big_test = <<'JSON';
129 {
130 "source" : "<a href=\"http://janetter.net/\" rel=\"nofollow\">Janetter</a>",
131 "entities" : {
132 "user_mentions" : [ {
133 "name" : "James Governor",
134 "screen_name" : "moankchips",
135 "indices" : [ 0, 10 ],
136 "id_str" : "61233",
137 "id" : 61233
138 } ],
139 "media" : [ ],
140 "hashtags" : [ ],
141 "urls" : [ ]
142 },
143 "in_reply_to_status_id_str" : "281400879465238529",
144 "geo" : {
145 },
146 "id_str" : "281405942321532929",
147 "in_reply_to_user_id" : 61233,
148 "text" : "@monkchips Ouch. Some regrets are harsher than others.",
149 "id" : 281405942321532929,
150 "in_reply_to_status_id" : 281400879465238529,
151 "created_at" : "Wed Dec 19 14:29:39 +0000 2012",
152 "in_reply_to_screen_name" : "monkchips",
153 "in_reply_to_user_id_str" : "61233",
154 "user" : {
155 "name" : "Sarah Bourne",
156 "screen_name" : "sarahebourne",
157 "protected" : false,
158 "id_str" : "16010789",
159 "profile_image_url_https" : "https://si0.twimg.com/profile_images/638441870/Snapshot-of-sb_normal.jpg",
160 "id" : 16010789,
161 "verified" : false
162 }
163 }
164 JSON
165 $data = $p->parse_json($big_test);
166
167 my $trace = $p->trace_json($big_test);
168 is($trace, <<'END_OF_EXPECTED_TRACE', 'big test trace');
169 Line 2, column 5, lexeme <lstring>, literal ""source""
170 Line 2, column 16, lexeme <lstring>, literal ""<a href=\"http://janetter.net/\" rel=\"nofollow\">Janetter</a>""
171 Line 3, column 5, lexeme <lstring>, literal ""entities""
172 Line 4, column 9, lexeme <lstring>, literal ""user_mentions""
173 Line 5, column 17, lexeme <lstring>, literal ""name""
174 Line 5, column 26, lexeme <lstring>, literal ""James Governor""
175 Line 6, column 17, lexeme <lstring>, literal ""screen_name""
176 Line 6, column 33, lexeme <lstring>, literal ""moankchips""
177 Line 7, column 17, lexeme <lstring>, literal ""indices""
178 Line 8, column 17, lexeme <lstring>, literal ""id_str""
179 Line 8, column 28, lexeme <lstring>, literal ""61233""
180 Line 9, column 17, lexeme <lstring>, literal ""id""
181 Line 11, column 9, lexeme <lstring>, literal ""media""
182 Line 12, column 9, lexeme <lstring>, literal ""hashtags""
183 Line 13, column 9, lexeme <lstring>, literal ""urls""
184 Line 15, column 5, lexeme <lstring>, literal ""in_reply_to_status_id_str""
185 Line 15, column 35, lexeme <lstring>, literal ""281400879465238529""
186 Line 16, column 5, lexeme <lstring>, literal ""geo""
187 Line 18, column 5, lexeme <lstring>, literal ""id_str""
188 Line 18, column 16, lexeme <lstring>, literal ""281405942321532929""
189 Line 19, column 5, lexeme <lstring>, literal ""in_reply_to_user_id""
190 Line 20, column 5, lexeme <lstring>, literal ""text""
191 Line 20, column 14, lexeme <lstring>, literal ""@monkchips Ouch. Some regrets are harsher than others.""
192 Line 21, column 5, lexeme <lstring>, literal ""id""
193 Line 22, column 5, lexeme <lstring>, literal ""in_reply_to_status_id""
194 Line 23, column 5, lexeme <lstring>, literal ""created_at""
195 Line 23, column 20, lexeme <lstring>, literal ""Wed Dec 19 14:29:39 +0000 2012""
196 Line 24, column 5, lexeme <lstring>, literal ""in_reply_to_screen_name""
197 Line 24, column 33, lexeme <lstring>, literal ""monkchips""
198 Line 25, column 5, lexeme <lstring>, literal ""in_reply_to_user_id_str""
199 Line 25, column 33, lexeme <lstring>, literal ""61233""
200 Line 26, column 5, lexeme <lstring>, literal ""user""
201 Line 27, column 9, lexeme <lstring>, literal ""name""
202 Line 27, column 18, lexeme <lstring>, literal ""Sarah Bourne""
203 Line 28, column 9, lexeme <lstring>, literal ""screen_name""
204 Line 28, column 25, lexeme <lstring>, literal ""sarahebourne""
205 Line 29, column 9, lexeme <lstring>, literal ""protected""
206 Line 30, column 9, lexeme <lstring>, literal ""id_str""
207 Line 30, column 20, lexeme <lstring>, literal ""16010789""
208 Line 31, column 9, lexeme <lstring>, literal ""profile_image_url_https""
209 Line 31, column 37, lexeme <lstring>, literal ""https://si0.twimg.com/profile_images/638441870/Snapshot-of-sb_normal.jpg""
210 Line 32, column 9, lexeme <lstring>, literal ""id""
211 Line 33, column 9, lexeme <lstring>, literal ""verified""
212 END_OF_EXPECTED_TRACE
213
214
215 $data = $p->parse_json(<<'JSON');
216 { "test": "\u2603" }
217 JSON
218 is($data->{test}, "\x{2603}", 'Unicode char');
219
220 package MarpaX::JSON;
221
222 sub new {
223 my ($class) = @_;
224
225 my $parser = bless {}, $class;
226
227 $parser->{grammar} = Marpa::R2::Scanless::G->new(
228 {
229 source => \(<<'END_OF_SOURCE'),
230 :default ::= action => ::first
231
232 :start ::= json
233
234 json ::= object
235 | array
236
237 object ::= ('{') members ('}') action => do_object
238
239 # comma is provided as a char class here, to ensure that char classes
240 # as separators are in the test suite.
241 members ::= pair* action => ::array separator => [,]
242
243 pair ::= string (':') value action => ::array
244
245 value ::= string
246 | object
247 | number
248 | array
249 | 'true' action => do_true
250 | 'false' action => do_true
251 | 'null' action => ::undef
252
253
254 array ::= ('[' ']') action => []
255 | ('[') elements (']')
256
257 # comma is provided as a char class here, to ensure that char classes
258 # as separators are in the test suite.
259 elements ::= value+ action => ::array separator => [,]
260
261 number ~ int
262 | int frac
263 | int exp
264 | int frac exp
265
266 int ~ digits
267 | '-' digits
268
269 digits ~ [\d]+
270
271 frac ~ '.' digits
272
273 exp ~ e digits
274
275 e ~ 'e'
276 | 'e+'
277 | 'e-'
278 | 'E'
279 | 'E+'
280 | 'E-'
281
282 string ::= lstring
283
284 :lexeme ~ lstring pause => before
285
286 lstring ~ quote in_string quote
287 quote ~ ["]
288 in_string ~ in_string_char*
289 in_string_char ~ [^"] | '\"'
290
291 :discard ~ whitespace
292 whitespace ~ [\s]+
293
294 END_OF_SOURCE
295
296 }
297 );
298 return $parser;
299 }
300
301 sub parse {
302 my ( $parser, $string ) = @_;
303
304 # Marpa::R2::Display
305 # name: SLIF read/resume example
306
307 my $re = Marpa::R2::Scanless::R->new(
308 { grammar => $parser->{grammar},
309 semantics_package => 'MarpaX::JSON::Actions'
310 }
311 );
312 my $length = length $string;
313 for (
314 my $pos = $re->read( \$string );
315 $pos < $length;
316 $pos = $re->resume()
317 )
318 {
319 my ( $start, $length ) = $re->pause_span();
320 my $value = substr $string, $start + 1, $length - 2;
321 $value = decode_string($value) if -1 != index $value, '\\';
322 $re->lexeme_read( 'lstring', $start, $length, $value ) // die;
323 } ## end for ( my $pos = $re->read( \$string ); $pos < $length...)
324 my $per_parse_arg = bless {}, 'MarpaX::JSON::Actions';
325 my $value_ref = $re->value($per_parse_arg);
326 return ${$value_ref};
327
328 # Marpa::R2::Display::End
329
330 } ## end sub parse
331
332 sub parse_json {
333 my ($parser, $string) = @_;
334 return $parser->parse($string);
335 }
336
337 sub trace_json {
338 my ($parser, $string) = @_;
339 my $trace_desc = q{};
340
341 # Marpa::R2::Display
342 # name: SLIF trace example
343
344 my $re = Marpa::R2::Scanless::R->new( { grammar => $parser->{grammar} } );
345 my $length = length $string;
346 for (
347 my $pos = $re->read( \$string );
348 $pos < $length;
349 $pos = $re->resume()
350 )
351 {
352 my ( $start, $span_length ) = $re->pause_span();
353 my ( $line, $column ) = $re->line_column($start);
354 my $lexeme = $re->pause_lexeme();
355 my $literal_string = $re->literal( $start, $span_length );
356 $trace_desc
357 .= qq{Line $line, column $column, lexeme <$lexeme>, literal "$literal_string"\n};
358 my $value = substr $string, $start + 1, $span_length - 2;
359 $value = decode_string($value) if -1 != index $value, q{\\};
360 $re->lexeme_read( 'lstring', $start, $span_length, $value ) // die;
361 } ## end for ( my $pos = $re->read( \$string ); $pos < $length...)
362 return $trace_desc;
363
364 # Marpa::R2::Display::End
365
366 }
367
368 sub decode_string {
369 my ($s) = @_;
370
371 $s =~ s/\\u([0-9A-Fa-f]{4})/chr(hex($1))/egxms;
372 $s =~ s/\\n/\n/gxms;
373 $s =~ s/\\r/\r/gxms;
374 $s =~ s/\\b/\b/gxms;
375 $s =~ s/\\f/\f/gxms;
376 $s =~ s/\\t/\t/gxms;
377 $s =~ s/\\\\/\\/gxms;
378 $s =~ s{\\/}{/}gxms;
379 $s =~ s{\\"}{"}gxms;
380
381 return $s;
382 } ## end sub decode_string
383
384 use strict;
385
386 sub MarpaX::JSON::Actions::do_object {
387 my (undef, $members) = @_;
388 use Data::Dumper;
389 return { map { @{$_} } @{$members} };
390 }
391
392 sub MarpaX::JSON::Actions::do_true {
393 shift;
394 return $_[0] eq 'true';
395 }
396
397 1;