Debian Codegraph @

t/sl_bracket.t

raw
1 #!/usr/bin/env 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 # This utility searches for mismatched braces --
18 # curly, square and round.
19
20 # Two not yet documented (but supported) features of Marpa::R2 are used.
21 #
22 # The 'rejection' recognizer setting causes an event to occur when all
23 # alternatives are rejected at a location. (The default is for this to
24 # be a fatal error.)
25 #
26 # The $recce->last_completed_span($symbol) method takes one argument:
27 # the name of a symbol. It returns the input stream span of the most
28 # recent instance of that symbol. If more than one begins at the most
29 # recent location, it returns the longest.
30
31 use 5.010001;
32 use strict;
33 use warnings;
34 use Marpa::R2 2.098000;
35 use Data::Dumper;
36 use English qw( -no_match_vars );
37 use Getopt::Long ();
38 use Test::More;
39
40 sub usage {
41 die "Usage: $PROGRAM_NAME < file\n",
42 "For testing: $PROGRAM_NAME --test\n";
43 }
44
45 our $TESTING = 1;
46 my $verbose = 0;
47 usage()
48 if
49 not Getopt::Long::GetOptions( verbose => \$verbose, 'test!' => \$TESTING );
50 usage() if @ARGV;
51
52 Test::More::plan tests => 5 if $TESTING;
53
54 my $grammar = << '=== GRAMMAR ===';
55 :default ::= action => [ name, value ]
56 lexeme default = action => [ name, value ] latm => 1 # to add token names to ast
57
58 text ::= pieces
59 pieces ::= piece*
60 piece ::= filler | balanced
61
62 balanced ::=
63 lparen pieces rparen
64 | lcurly pieces rcurly
65 | lsquare pieces rsquare
66
67 # x5b is left square bracket
68 # x5d is right square bracket
69 filler ~ [^(){}\x5B\x5D]+
70
71 lparen ~ '('
72 rparen ~ ')'
73 lcurly ~ '{'
74 rcurly ~ '}'
75 lsquare ~ '['
76 rsquare ~ ']'
77
78 === GRAMMAR ===
79
80 my $suffix = '(){}[]';
81 my %tokens = ();
82 for my $ix ( 0 .. ( length $suffix ) - 1 ) {
83 my $char = substr $suffix, $ix, 1;
84 $tokens{$char} = [ $ix, 1 ];
85 }
86
87 my %matching = ();
88 my %literal_match = ();
89 for my $pair (qw% () [] {} %) {
90 my ( $left, $right ) = split //xms, $pair;
91 $matching{$left} = $tokens{$right};
92 $literal_match{$left} = $right;
93 $matching{$right} = $tokens{$left};
94 $literal_match{$right} = $left;
95 } ## end for my $pair (qw% () [] {} %)
96 my %token_by_name = (
97 rcurly => $tokens{'}'},
98 rsquare => $tokens{']'},
99 rparen => $tokens{')'},
100 );
101
102 my $g = Marpa::R2::Scanless::G->new( { source => \($grammar) } );
103
104 my @tests = ();
105
106 if ($TESTING) {
107 @tests = (
108 [ 'z}ab)({[]})))(([]))zz', '1{ 4( 11( 12(' ],
109 [ '9\090]{[][][9]89]8[][]90]{[]\{}{}09[]}[', '5[ 16} 16[ 24[ 39]' ],
110 [ '([]([])([]([]', '13) 13) 13)' ],
111 [ '([([([([', '8] 8) 8] 8) 8] 8) 8] 8)' ],
112 [ '({]-[(}-[{)', '2} 2) 2[ 6) 6] 6{ 10} 10] 10(' ],
113 );
114 for my $test (@tests) {
115 my ( $string, $expected_result ) = @{$test};
116 my $fixes = q{};
117 test( $g, $string, \$fixes );
118 diagnostic( "Input: ", substr( $string, 0, 60 ) ) if $verbose;
119 my $description = qq{Result of "} . ( substr $string, 0, 60 ) . q{"};
120 Test::More::is( $fixes, $expected_result, $description );
121 } ## end for my $test (@tests)
122 } ## end if ($TESTING)
123 else {
124 local $RS = undef;
125 my $input = <>;
126 my $actual_result = test( $g, $input );
127 if ( not scalar @{$actual_result} ) {
128 say '=== All brackets balanced ===';
129 }
130 else {
131 my $divider = "\n" . ( '=' x 20 ) . "\n";
132 say join $divider, @{$actual_result};
133 }
134 } ## end else [ if ($TESTING) ]
135
136 sub diagnostic {
137 if ($TESTING) {
138 Test::More::diag(@_);
139 }
140 else {
141 say {*STDERR} @_;
142 }
143 } ## end sub diagnostic
144
145 sub marked_line {
146 my ( $string, $column1, $column2 ) = @_;
147 my $max_line_length = 60;
148 $max_line_length = $column1 if $column1 > $max_line_length;
149 $max_line_length = $column2
150 if defined $column2 and $column2 > $max_line_length;
151
152 # $pos_column is always the last of the two columns
153 my $output_line = substr $string, 0, $max_line_length;
154 my $nl_pos = index $output_line, "\n";
155 $output_line = substr $output_line, 0, $nl_pos;
156 my $pointer_line = ( q{ } x $column1 ) . q{^};
157 if ( defined $column2 ) {
158 my $further_offset = $column2 - $column1;
159 $pointer_line .= ( q{ } x ( $further_offset - 1 ) ) . q{^};
160 }
161 return join "\n", $output_line, $pointer_line;
162 } ## end sub marked_line
163
164 sub test {
165 my ( $g, $string, $fixes ) = @_;
166 my @problems = ();
167 my @fixes = ();
168 diagnostic( "Input: ", substr( $string, 0, 60 ) ) if $verbose;
169
170 # Record the length of the "real input"
171 my $input_length = length $string;
172 my $pos = 0;
173
174 # For Ruby Slippers, put a set of matching brackets into a suffix
175 # of the input.
176 # We wil carefully set our lengths when reading,
177 # so that we don't treat to accidentally read this, while reading
178 # the "real input".
179 $string .= $suffix;
180
181 # state $recce_debug_args = { trace_terminals => 1, trace_values => 1 };
182 state $recce_debug_args = {};
183
184 my $recce = Marpa::R2::Scanless::R->new(
185 { grammar => $g,
186 ## Ask Marpa to generate an event on rejection
187 rejection => 'event',
188 },
189 $recce_debug_args
190 );
191
192 # Note that we make sure only to read the "real input"
193 $pos = $recce->read( \$string, $pos, $input_length );
194
195 # For the entire input string ...
196 READ: while ( $pos < $input_length ) {
197
198 # Check if we stopped due to a rejection event.
199 # Any other event is an error.
200 my $rejection = 0;
201 EVENT:
202 for my $event ( @{ $recce->events() } ) {
203 my ($name) = @{$event};
204 if ( $name eq q{'rejected} ) {
205 $rejection = 1;
206 next EVENT;
207 }
208 die join q{ }, "Spurious event at position $pos: '$name'";
209 } ## end EVENT: for my $event ( @{ $recce->events() } )
210
211 # No rejection event?
212 # Then just start up again
213 if ( not $rejection ) {
214
215 # Note that we make sure we don't try to read the suffix
216 $pos = $recce->resume( $pos, $input_length - $pos );
217 next READ;
218
219 } ## end if ( not $rejection )
220
221 # If here, we rejected the next input token
222
223 # What terminals do we expect?
224 my @expected = @{ $recce->terminals_expected() };
225
226 # Find, at random, one of these tokens that is a closing bracket.
227 my ($token) =
228 grep {defined}
229 map { $token_by_name{$_} } @{ $recce->terminals_expected() };
230
231 # If there is no expected closing bracket, then what we need A
232 # a new opening bracket in order to continue. Find out which one.
233 my $opening = not defined $token;
234 if ($opening) {
235 my $nextchar = substr $string, $pos, 1;
236 $token = $matching{$nextchar};
237 }
238
239 # If $token is not defined, we rejected the last set of tokens;
240 # we do we not expect a closing bracket;
241 # and an opening bracket won't fix the problem either.
242 # This is something that should not happen.
243 # All we can do is abend.
244 die "Rejection at pos $pos: ", substr( $string, $pos, 10 )
245 if not defined $token;
246
247 # Concoct a "Ruby Slippers token" and read it from the
248 # suffix
249 my ( $token_start, $token_length ) = @{$token};
250 $token_start += $input_length;
251 my $token_literal = substr $string, $token_start, $token_length;
252 my $result = $recce->resume( $token_start, $token_length );
253 die "Read of Ruby slippers token failed"
254 if $result != $token_start + $token_length;
255
256 # Used for testing
257 push @fixes, "$pos$token_literal" if $fixes;
258
259 # We've done the Ruby Slippers thing, and are ready to
260 # continue reading.
261 # But first we want to report the error.
262
263 my ( $pos_line, $pos_column ) = $recce->line_column($pos);
264 my $problem;
265
266 # Report the error if it was a case of a missing open bracket.
267 if ($opening) {
268 $problem = join "\n",
269 "* Line $pos_line, column $pos_column: Missing open $token_literal",
270 marked_line(
271 ( substr $string,
272 $pos - ( $pos_column - 1 ),
273 -( length $suffix ) + 1
274 ),
275 $pos_column - 1
276 );
277 push @problems, [ $pos_line, $pos_column, $problem ];
278 diagnostic(
279 "* Line $pos_line, column $pos_column: Missing open $token_literal"
280 ) if $verbose;
281 next READ;
282 } ## end if ($opening)
283
284 # Report the error if it was a case of a missing close bracket.
285
286 # We've created a properly bracketed span of the input, using
287 # the Ruby Slippers token. Use Marpa's tables to find its
288 # beginning.
289 my ($opening_bracket) = $recce->last_completed_span('balanced');
290 my ( $line, $column ) = $recce->line_column($opening_bracket);
291 my $opening_column0 = $opening_bracket - ( $column - 1 );
292
293 if ( $line == $pos_line ) {
294
295 # Report a missing close bracket for cases contained in
296 # a single text line
297 $problem = join "\n",
298 "* Line $line, column $column: Missing close $token_literal, "
299 . "problem detected at line $pos_line, column $pos_column",
300 marked_line(
301 substr(
302 $string,
303 $pos - ( $pos_column - 1 ),
304 -( length $suffix ) + 1
305 ),
306 $column - 1,
307 $pos_column - 1
308 );
309 } ## end if ( $line == $pos_line )
310 else {
311 # Report a missing close bracket for cases that span
312 # two or more text lines
313 $problem = join "\n",
314 "* Line $line, column $column: No matching bracket for "
315 . q{'}
316 . $literal_match{$token_literal} . q{', },
317 marked_line(
318 substr( $string, $opening_column0, -( length $suffix ) + 1 ),
319 $column - 1
320 ),
321 , "* Problem detected at line $pos_line, column $pos_column:",
322 marked_line(
323 substr(
324 $string,
325 $pos - ( $pos_column - 1 ),
326 -( length $suffix ) + 1
327 ),
328 $pos_column - 1
329 );
330 } ## end else [ if ( $line == $pos_line ) ]
331
332 # Add our report to the list of problems.
333 push @problems, [ $line, $column, $problem ];
334 diagnostic(
335 "* Line $line, column $column: Missing close $token_literal, ",
336 "problem detected at line $pos_line, column $pos_column"
337 ) if $verbose;
338
339 } ## end READ: while ( $pos < $input_length )
340
341 # At this point we have finished the input.
342 # Now we must deal with opening brackets which
343 # were never closed.
344 # The logic here is a simplified version of that of the main
345 # reading loop.
346
347 TRAILER: while (1) {
348
349 # Programming note: this is so similar to the code of the
350 # main reading loop, it is tempting to combine them and use
351 # a flag.
352 # But there are quite a few small differences,
353 # so that would be much less readable.
354 # And for efficiency purposes, this is a kind of "hand-unrolling"
355 # of a loop, with optimization of the code.
356
357 my $rejection = 0;
358 EVENT:
359 for my $event ( @{ $recce->events() } ) {
360 my ($name) = @{$event};
361 if ( $name eq q{'rejected} ) {
362 $rejection = 1;
363 next EVENT;
364 }
365 die join q{ }, "Spurious event at position $pos: '$name'";
366 } ## end EVENT: for my $event ( @{ $recce->events() } )
367
368 die "Rejection at end of string" if $rejection;
369
370 my @expected = @{ $recce->terminals_expected() };
371
372 # say STDERR join " ", "terminals expected:", @expected;
373
374 my ($token) =
375 grep {defined}
376 map { $token_by_name{$_} } @{ $recce->terminals_expected() };
377
378 last TRAILER if not defined $token;
379
380 my ( $token_start, $token_length ) = @{$token};
381 $token_start += $input_length;
382 my $token_literal = substr $string, $token_start, $token_length;
383 my $result = $recce->resume( $token_start, $token_length );
384 die "Read of Ruby slippers token failed"
385 if $result != $token_start + $token_length;
386
387 # Used for testing
388 push @fixes, "$pos$token_literal" if $fixes;
389
390 my ($opening_bracket) = $recce->last_completed_span('balanced');
391 my ( $line, $column ) = $recce->line_column($opening_bracket);
392 my $opening_column0 = $opening_bracket - ( $column - 1 );
393 my $problem = join "\n",
394 "* Line $line, column $column: Opening " . q{'}
395 . $literal_match{$token_literal}
396 . q{' never closed, problem detected at end of string},
397 marked_line(
398 substr( $string, $opening_column0, -( length $suffix ) + 1 ),
399 $column - 1 );
400 push @problems, [ $line, $column, $problem ];
401
402 } ## end TRAILER: while (1)
403
404 # For testing
405 if ( ref $fixes ) {
406 ${$fixes} = join " ", @fixes;
407 }
408
409 # The problems do not necessarily occur in lexical order.
410 # Sort them so that they can be reported that way.
411 my @sorted_problems =
412 sort { $a->[0] <=> $b->[0] or $a->[1] <=> $b->[1] } @problems;
413 my @result = map { $_->[-1] } @sorted_problems;
414 return \@result;
415
416 } ## end sub test
417
418 # vim: expandtab shiftwidth=4: