blib/lib/Zuzu/Tidy.pm untested

filter: Statementstmt 0.0% 0 / 959 Branchbran 0.0% 0 / 700 Conditioncond 0.0% 0 / 917 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 50 Podpod 0.0% 0 / 44 totaltotal 0.0% 0 / 2670 CC 351 SCAR 66.9
CC
351
Cov
0%
_tidy_code_chunk
2970.0
_need_space_before
2070.0
_apply_vertical_spacing_rules
992.0
CRAP 800.6
1 package Zuzu::Tidy;
2  
3 use utf8;
4 use strict;
5 use warnings;
6  
7 our $VERSION = '0.007000';
8  
9 use Zuzu::Lexer;
10 use Zuzu::Parser;
11 use Zuzu::Token;
12  
13 my %BINARY_OP = map { $_ => 1 } qw(
14 + - * / × ÷ ** mod
15 _ ~
16 = == != < > <= >= <=> eq ne gt ge lt le cmp eqi nei gti gei lti lei cmpi
17 and and? or or? xor xor? nand nand? nor nor? xnor xnor? onlyif onlyif? butnot butnot?
18 × ÷ ≠ ≤ ≥ ≡ ≢ ≶ ≷ ⋀ ⋀? ⋁ ⋁? ⊻ ⊻? ⊼ ⊼? ⊽ ⊽? ↔ ↔? ⊨ ⊨? ⊭ ⊭?
19 in ∈ ∉ union ⋃ intersection ⋂ subsetof ⊂ supersetof ⊃ equivalentof ⊂⊃ ∖
20 instanceof does can
21 default
22 & | ^
23 << >> « »
24 ∣ ∤ divides
25 @ @? @@
26 ▷ ◁ |> <|
27 := ~= += -= *= /= ×= ÷= **= _= ?:=
28 =
29 );
30 $BINARY_OP{'\\'} = 1;
31  
32 my %UNARY_PREFIX_OP = map { $_ => 1 } qw(
33 + - ! not ¬ ~ √ \ ++ --
34 abs sqrt floor ceil round int uc lc length typeof new
35 );
36 $UNARY_PREFIX_OP{'#'} = 1;
37 my %NO_SPACE_BEFORE = map { $_ => 1 } ( ',', ';', ')', ']', '}', '⌋', '⌉', '.', ':' );
38 my %NO_SPACE_AFTER = map { $_ => 1 } ( '(', '[', '{', '⌊', '⌈', '.' );
39 my %CONTROL_KW = map { $_ => 1 } qw( if else while for switch catch unless );
40  
41 # Delimiter types that can open/close a comma-separated sequence body
42 # (array/dict/pairlist literal, set/bag/guillemet-set literal, or a
43 # call/parameter argument list). << and « are ambiguous with the binary
44 # "shift" operator of the same spelling, so they (and their closes >> and
45 # ») only engage this tracking when _build_pair_map judged them to be a
46 # genuine literal delimiter -- i.e. when they have an entry in %pair_for.
47 my %_SEQUENCE_OPEN = ( '(' => 1, '[' => 1, '{' => 1, '<<' => 1, '<<<' => 1, '«' => 1 );
48 my %_SEQUENCE_CLOSE = ( ')' => 1, ']' => 1, '>>' => 1, '>>>' => 1, '»' => 1 );
49 my %_AMBIGUOUS_ANGLE = ( '<<' => 1, '«' => 1, '>>' => 1, '»' => 1 );
50 my %CANONICAL_OPERATOR_SPELLING = (
51 '*' => '×',
52 '/' => '÷',
53 '<=' => '≤',
54 '>=' => '≥',
55 '<=>' => '≶',
56 '≷' => '≶',
57 '==' => '≡',
58 '!=' => '≢',
59 'not' => '¬',
60 'sqrt' => '√',
61 'divides' => '∣',
62 'and' => '⋀',
63 'and?' => '⋀?',
64 'nand' => '⊼',
65 'nand?' => '⊼?',
66 'nor' => '⊽',
67 'nor?' => '⊽?',
68 'xor' => '⊻',
69 'xor?' => '⊻?',
70 'xnor' => '↔',
71 'xnor?' => '↔?',
72 'or' => '⋁',
73 'or?' => '⋁?',
74 'onlyif' => '⊨',
75 'onlyif?' => '⊨?',
76 'butnot' => '⊭',
77 'butnot?' => '⊭?',
78 'union' => '⋃',
79 'intersection' => '⋂',
80 '\\' => '∖',
81 'in' => '∈',
82 'subsetof' => '⊂',
83 'supersetof' => '⊃',
84 'equivalentof' => '⊂⊃',
85 '|>' => '▷',
86 '<|' => '◁',
87 '*=' => '×=',
88 '/=' => '÷=',
89 );
90  
91 sub tidy {
92 my ( $class, $src, %opts ) = @_;
93 $src //= '';
94 my $comment_map = {};
95 $src = _stash_multiline_comments( $src, $comment_map );
96  
97 my @segments = _split_pod_segments($src);
98 my @out;
99 for my $segment ( @segments ) {
100 if ( $segment->{is_pod} ) {
101 push @out, { is_pod => 1, text => $segment->{text} };
102 next;
103 }
104  
105 my $chunk = $segment->{text};
106 next if $chunk eq '';
107  
108 my $tidied = _tidy_code_chunk( $chunk, %opts );
109 $tidied = _restore_multiline_comments( $tidied, $comment_map );
110 $tidied = _apply_vertical_spacing_rules($tidied);
111 $tidied = _normalize_split_sequence_literals($tidied);
112 my $parser = Zuzu::Parser->new;
113 eval {
114 $parser->parse(
115 _strip_multiline_comments_for_parse($tidied),
116 $opts{filename} // '<tidy>'
117 );
118 1;
119 };
120 push @out, { is_pod => 0, text => $tidied };
121 }
122  
123 return _join_segments_with_pod_spacing(@out);
124 }
125  
126 sub _join_segments_with_pod_spacing {
127 my ( @segments ) = @_;
128 my $out = '';
129  
130 for ( my $i = 0; $i <= $#segments; $i++ ) {
131 my $segment = $segments[$i];
132 my $text = $segment->{text} // '';
133 next if $text eq '';
134  
135 if ( $i > 0 ) {
136 my $prev = $segments[$i - 1];
137 my $crosses_pod_boundary
138 = ( ( $prev->{is_pod} and ! $segment->{is_pod} )
139 or ( ! $prev->{is_pod} and $segment->{is_pod} ) );
140 if ( $crosses_pod_boundary ) {
141 $out =~ s/\n*\z/\n\n/s;
142 $text =~ s/\A\n+//s;
143 }
144 }
145  
146 $out .= $text;
147 }
148  
149 return $out;
150 }
151  
152 sub _tidy_code_chunk {
153 my ( $src, %opts ) = @_;
154  
155 my $lexer = Zuzu::Lexer->new( src => $src, filename => $opts{filename} // '<tidy>' );
156 my @tokens;
157 while (1) {
158 my $tok = $lexer->next_token;
159 last if $tok->is_EOF;
160 push @tokens, $tok;
161 }
162 @tokens = _normalize_tokens(@tokens);
163 _tag_declaration_block_braces( \@tokens );
164  
165 my %pair_for = _build_pair_map( \@tokens );
166 _tag_trailing_comma_sequences( \@tokens, \%pair_for );
167  
168 my $indent = 0;
169 my $paren_depth = 0;
170 my $bracket_depth = 0;
171 my $brace_depth = 0;
172 my $inline_brace_depth = 0;
173 my $angle_depth = 0;
174 my @brace_kind_stack;
175 my @sequence_stack;
176 my $line = '';
177 my @out_lines;
178 my $pending_indent = 1;
179 my $continuation_indent = 0;
180  
181 for ( my $i = 0; $i <= $#tokens; $i++ ) {
182 my $tok = $tokens[$i];
183 my $val = _token_text($tok);
184 my $emit_val = _display_token_text( \@tokens, $i, %opts );
185 my $prev = $i > 0 ? $tokens[$i - 1] : undef;
186 my $next = $i < $#tokens ? $tokens[$i + 1] : undef;
187 my $just_closed_inline = 0;
188  
189 my $close_kind = ( $val eq '}' and @brace_kind_stack ) ? $brace_kind_stack[-1] : 'block';
190 my $is_other_sequence_close = (
191 $_SEQUENCE_CLOSE{$val}
192 and $val ne '}'
193 and ( ! $_AMBIGUOUS_ANGLE{$val} or exists $pair_for{$i} )
194 and @sequence_stack
195 and $sequence_stack[-1]
196 );
197  
198 if (
199 ( $val eq '}' and ( $close_kind eq 'block' or $close_kind eq 'expr_block' ) )
200 or $is_other_sequence_close
201 ) {
202 if ( @sequence_stack and $sequence_stack[-1] and $line =~ /\S/ and $line !~ /,\s*\z/ ) {
203 # Every entry, including the last, gets a trailing comma
204 # when the body is split one-entry-per-line below.
205 $line .= ',';
206 }
207 if ( $line =~ /\S/ ) {
208 push @out_lines, _rstrip($line);
209 $line = '';
210 }
211 $indent-- if $indent > 0;
212 $pending_indent = 1;
213 }
214  
215 if ( $pending_indent ) {
216 $line .= ("\t" x $indent);
217 $line .= (' ' x $continuation_indent) if $continuation_indent > 0;
218 $pending_indent = 0;
219 }
220  
221 if ( _is_chain_op($val) and $line =~ /\S/ ) {
222 push @out_lines, _rstrip($line);
223 $line = ("\t" x ( $indent + 1 ));
224 }
225  
226 my $need_before = _need_space_before( \@tokens, $i, \%pair_for );
227 $line .= ' ' if $need_before and $line =~ /\S/ and $line !~ /[ \t]\z/;
228 $line .= $emit_val;
229  
230 if ( $_SEQUENCE_OPEN{$val} and ( ! $_AMBIGUOUS_ANGLE{$val} or exists $pair_for{$i} ) ) {
231 my $is_inline = 1;
232 my $kind = 'inline';
233 if ( $val eq '{' ) {
234 $is_inline = _is_inline_brace( \@tokens, $i, \%pair_for );
235 $kind = $is_inline ? 'inline'
236 : _is_expression_block_brace( \@tokens, $i ) ? 'expr_block'
237 : 'block';
238 push @brace_kind_stack, $kind;
239 }
240  
241 my $is_pairlist_body = ( $val eq '{' and defined $tok->{_pairlist_half} and $tok->{_pairlist_half} eq 'open2' ) ? 1 : 0;
242 my $is_sequence_body = $is_pairlist_body || ( $tok->{_force_sequence} ? 1 : 0 );
243 push @sequence_stack, $is_sequence_body;
244  
245 if ( $val eq '(' ) {
246 $paren_depth++;
247 }
248 elsif ( $val eq '[' ) {
249 $bracket_depth++;
250 }
251 elsif ( $val eq '{' ) {
252 $brace_depth++;
253 $inline_brace_depth++ if $is_inline;
254 }
255 else {
256 # << <<< «
257 $angle_depth++;
258 }
259  
260 my $forces_newline = ( $val eq '{' ) ? ( ! $is_inline ) : ( $is_sequence_body ? 1 : 0 );
261 if ( $forces_newline ) {
262 push @out_lines, _rstrip($line);
263 $line = '';
264 $indent++;
265 $pending_indent = 1;
266 $continuation_indent = 0;
267 next;
268 }
269 }
270 if ( $val eq ';' ) {
271 push @out_lines, _rstrip($line);
272 $line = '';
273 $pending_indent = 1;
274 $continuation_indent = 0;
275 next;
276 }
277 if ( $val eq ',' and @sequence_stack and $sequence_stack[-1] ) {
278 # Inside any sequence body (pairlist, dict, array, set, bag,
279 # guillemet-set, or argument/parameter list) that must be
280 # rendered one-item-per-line, each entry -- including the
281 # last -- is placed on its own line, separated by the literal
282 # commas already present in the source.
283 push @out_lines, _rstrip($line);
284 $line = '';
285 $pending_indent = 1;
286 $continuation_indent = 0;
287 next;
288 }
289 if ( $val eq '}' ) {
290 my $kind = @brace_kind_stack ? pop @brace_kind_stack : 'block';
291 my $is_sequence_body = @sequence_stack ? pop @sequence_stack : 0;
292 # A forced dict literal's } ends a value, not a statement
293 # block, so (like pairlist close2, which is already 'inline'
294 # kind) it must remain eligible for the same generic
295 # end-of-value auto-semicolon treatment that _needs_auto_semicolon
296 # otherwise blanket-excludes for 'block'/'expr_block' closes.
297 $just_closed_inline = 1 if $kind eq 'inline' or $is_sequence_body;
298 $brace_depth-- if $brace_depth > 0;
299 $inline_brace_depth-- if $kind eq 'inline' and $inline_brace_depth > 0;
300 my $is_pairlist_close1 = ( defined $tok->{_pairlist_half} && $tok->{_pairlist_half} eq 'close1' ) ? 1 : 0;
301 if ( ( $kind eq 'block' or $kind eq 'expr_block' ) and ! $is_pairlist_close1 and ! $is_sequence_body ) {
302 if ( $kind eq 'expr_block' ) {
303 if ( $next and $next->is_OP(';') ) {
304 $line .= ';';
305 $i++;
306 }
307 elsif (
308 !$next
309 or ( $next->is_OP and $next->value eq '}' )
310 or _can_start_statement($next)
311 ) {
312 $line .= ';';
313 }
314 }
315 if ( $next and $next->is_KW('else') ) {
316 push @out_lines, _rstrip($line);
317 $line = '';
318 $pending_indent = 1;
319 next;
320 }
321 if (
322 ( $kind eq 'block' or $kind eq 'expr_block' )
323 and ( $paren_depth > 0 or $bracket_depth > 0 )
324 and $next
325 and $next->is_OP
326 and ( $next->value eq ',' or $next->value eq ')' or $next->value eq ']' )
327 ) {
328 # A callback/anonymous-function body that is itself a
329 # call argument or array item: keep its closing } glued
330 # to the `,`, `)`, or `]` that follows, instead of
331 # stranding the rest of the argument list or array on
332 # its own line (`}, 4 );` rather than `}\n, 4, );`).
333 # Falling through without flushing here, rather than
334 # consuming $next directly, lets that token's own
335 # normal handling run on the next iteration -- so if
336 # the enclosing sequence is itself forced
337 # one-item-per-line, the generic comma separator (or
338 # the enclosing close's own pre-emission flush) still
339 # fires for it exactly as for every other item.
340 next;
341 }
342 if ( $kind eq 'block' and $next and $next->is_OP(';') and ! ( @sequence_stack and $sequence_stack[-1] ) ) {
343 # A control construct (e.g. try/catch) used as an
344 # expression value, terminated by an explicit `;`:
345 # glue the semicolon to the closing } instead of
346 # stranding it alone on the next line.
347 $line .= ';';
348 $i++;
349 }
350 push @out_lines, _rstrip($line);
351 $line = '';
352 $pending_indent = 1;
353 next;
354 }
355 }
356 elsif ( $_SEQUENCE_CLOSE{$val} and ( ! $_AMBIGUOUS_ANGLE{$val} or exists $pair_for{$i} ) ) {
357 # A forced sequence's own closing delimiter never forces a new
358 # line to start for whatever follows it (unlike the pre-emission
359 # flush above, which only dedents the close itself onto its own
360 # line). Falling through lets the close glue naturally to a
361 # following `,`/`)`/`;` exactly as an ordinary, non-forced close
362 # already does, and lets the bottom-of-loop auto-semicolon check
363 # supply a `;` when this is the last token of a statement.
364 pop @sequence_stack if @sequence_stack;
365 if ( $val eq ')' ) {
366 $paren_depth-- if $paren_depth > 0;
367 }
368 elsif ( $val eq ']' ) {
369 $bracket_depth-- if $bracket_depth > 0;
370 }
371 else {
372 # >> >>> »
373 $angle_depth-- if $angle_depth > 0;
374 }
375 }
376  
377 # wrap long lines conservatively at commas and binary operators.
378 my $col = _visual_length($line);
379 my $wrap_limit = $continuation_indent > 0 ? 80 : 100;
380 if ( $col > $wrap_limit and ( $val eq ',' or _is_binary_op( \@tokens, $i ) ) ) {
381 push @out_lines, _rstrip($line);
382 $line = '';
383 $pending_indent = 1;
384 $continuation_indent = 4;
385 }
386  
387 if ( $next and _needs_auto_semicolon( $tok, $next, $paren_depth, $bracket_depth, $brace_depth, $inline_brace_depth, $just_closed_inline, $angle_depth ) ) {
388 $line .= ';';
389 push @out_lines, _rstrip($line);
390 $line = '';
391 $pending_indent = 1;
392 $continuation_indent = 0;
393 }
394 }
395  
396 if ( $line =~ /\S/ ) {
397 if ( $line !~ /;\z/ and @tokens and _can_end_statement( $tokens[-1] ) ) {
398 $line .= ';';
399 }
400 push @out_lines, _rstrip($line);
401 }
402  
403 return join( "\n", @out_lines ) . "\n";
404 }
405  
406 sub _split_pod_segments {
407 my ( $src ) = @_;
408 my @lines = split /(?<=\n)/, $src;
409 my @segments;
410 my $buf = '';
411 my $in_pod = 0;
412  
413 for my $line ( @lines ) {
414 if ( ! $in_pod and $line =~ /^=(\w+)/ ) {
415 my $word = $1;
416 if ( $word ne 'cut' ) {
417 if ( $buf ne '' ) {
418 push @segments, { is_pod => 0, text => $buf };
419 $buf = '';
420 }
421 $in_pod = 1;
422 }
423 }
424  
425 $buf .= $line;
426  
427 if ( $in_pod and $line =~ /^=cut(?:\r?\n)?\z/ ) {
428 push @segments, { is_pod => 1, text => $buf };
429 $buf = '';
430 $in_pod = 0;
431 }
432 }
433  
434 if ( $buf ne '' ) {
435 push @segments, { is_pod => ( $in_pod ? 1 : 0 ), text => $buf };
436 }
437  
438 return @segments;
439 }
440  
441 sub _is_chain_op {
442 my ( $val ) = @_;
443  
444 return $val eq '▷' || $val eq '◁' || $val eq '|>' || $val eq '<|';
445 }
446  
447 sub _normalize_tokens {
448 my ( @tokens ) = @_;
449 my @out;
450  
451 for my $tok ( @tokens ) {
452 if ( $tok->is_OP('{{') ) {
453 my $open1 = Zuzu::Token->new(
454 type => 'OP',
455 value => '{',
456 file => $tok->file,
457 line => $tok->line,
458 col => $tok->col,
459 );
460 my $open2 = Zuzu::Token->new(
461 type => 'OP',
462 value => '{',
463 file => $tok->file,
464 line => $tok->line,
465 col => $tok->col,
466 );
467 # Pairlist delimiter halves are tagged so formatting decisions
468 # (inline-vs-block brace classification) never depend on
469 # guessing from surrounding context, which previously broke
470 # down for contexts such as `...{{ ... }}` spreads.
471 $open1->{_pairlist_half} = 'open1';
472 $open2->{_pairlist_half} = 'open2';
473 push @out, $open1, $open2;
474 next;
475 }
476 if ( $tok->is_OP('}}') ) {
477 my $close1 = Zuzu::Token->new(
478 type => 'OP',
479 value => '}',
480 file => $tok->file,
481 line => $tok->line,
482 col => $tok->col,
483 );
484 my $close2 = Zuzu::Token->new(
485 type => 'OP',
486 value => '}',
487 file => $tok->file,
488 line => $tok->line,
489 col => $tok->col,
490 );
491 $close1->{_pairlist_half} = 'close1';
492 $close2->{_pairlist_half} = 'close2';
493 push @out, $close1, $close2;
494 next;
495 }
496 push @out, $tok;
497 }
498  
499 return @out;
500 }
501  
502 sub _tag_declaration_block_braces {
503 # Marks the `{` that opens a class/trait/function/method body, even
504 # when separated from the keyword by a variable-length clause such as
505 # a return-type arrow (`-> Type`) or a trait list (`with A, B`). A
506 # fixed-distance backward look from the brace can't see far enough
507 # back to find the keyword in those cases, which used to leave
508 # declaration bodies classified as inline. This scans forward from
509 # each keyword instead, so the gap can be any length.
510 my ( $tokens ) = @_;
511  
512 for my $i ( 0 .. $#$tokens ) {
513 my $tok = $tokens->[$i];
514 next if ! $tok->is_KW;
515 my $kw = $tok->value;
516  
517 if ( $kw eq 'class' or $kw eq 'trait' ) {
518 my $k = $i + 1;
519 next if $k > $#$tokens or ! $tokens->[$k]->is_IDENT;
520 $k++;
521  
522 my $changed = 1;
523 while ( $changed ) {
524 $changed = 0;
525 if (
526 $k <= $#$tokens and $tokens->[$k]->is_KW('extends')
527 and $k + 1 <= $#$tokens and $tokens->[ $k + 1 ]->is_IDENT
528 ) {
529 $k += 2;
530 $changed = 1;
531 }
532 if ( $k <= $#$tokens and ( $tokens->[$k]->is_KW('with') or $tokens->[$k]->is_KW('but') ) ) {
533 my $j = $k + 1;
534 if ( $j <= $#$tokens and $tokens->[$j]->is_IDENT ) {
535 $j++;
536 while (
537 $j + 1 <= $#$tokens
538 and $tokens->[$j]->is_OP(',')
539 and $tokens->[ $j + 1 ]->is_IDENT
540 ) {
541 $j += 2;
542 }
543 $k = $j;
544 $changed = 1;
545 }
546 }
547 }
548  
549 $tokens->[$k]{_forced_block} = 1 if $k <= $#$tokens and $tokens->[$k]->is_OP('{');
550 next;
551 }
552  
553 if ( $kw eq 'function' or $kw eq 'method' ) {
554 my $k = $i + 1;
555 $k++ if $k <= $#$tokens and $tokens->[$k]->is_IDENT;
556 next if $k > $#$tokens or ! $tokens->[$k]->is_OP('(');
557  
558 my $depth = 0;
559 my $j = $k;
560 while ( $j <= $#$tokens ) {
561 $depth++ if $tokens->[$j]->is_OP('(');
562 if ( $tokens->[$j]->is_OP(')') ) {
563 $depth--;
564 last if $depth == 0;
565 }
566 $j++;
567 }
568 next if $j > $#$tokens;
569 $k = $j + 1;
570  
571 if (
572 $k <= $#$tokens and $tokens->[$k]->is_OP
573 and ( $tokens->[$k]->value eq '->' or $tokens->[$k]->value eq '→' )
574 ) {
575 $k++;
576 $k++ if $k <= $#$tokens and $tokens->[$k]->is_IDENT;
577 }
578  
579 $tokens->[$k]{_forced_block} = 1 if $k <= $#$tokens and $tokens->[$k]->is_OP('{');
580 }
581 }
582  
583 return;
584 }
585  
586 my %_PAIR_CLOSE_FOR_OPEN = (
587 '(' => ')', '[' => ']', '{' => '}', '⌊' => '⌋', '⌈' => '⌉',
588 '<<' => '>>', '<<<' => '>>>', '«' => '»',
589 );
590 my %_PAIR_OPEN_FOR_CLOSE = reverse %_PAIR_CLOSE_FOR_OPEN;
591  
592 sub _build_pair_map {
593 my ( $tokens ) = @_;
594 my @stack;
595 my %pair;
596  
597 for my $i ( 0 .. $#$tokens ) {
598 # Guarded by is_OP so a string/binary-string literal whose decoded
599 # content happens to equal a bracket character (e.g. the literal
600 # string "(" in `left:"("`) isn't mistaken for that bracket.
601 next if ! $tokens->[$i]->is_OP;
602 my $v = $tokens->[$i]->value;
603  
604 # << and « are genuinely dual-use: the real parser treats them as a
605 # set/guillemet-set literal opener in primary/operand position, but
606 # they also have real binary-operator ("shift") precedence in infix
607 # position (see _Impl.pm's precedence table). Only push them as
608 # pairable openers when they're in operand position -- i.e. NOT
609 # immediately after a token that could end an expression -- so a
610 # shift expression never corrupts the stack for surrounding
611 # brackets. <<< (bag) has no such binary-operator meaning and is
612 # always pushed.
613 if ( ( $v eq '<<' or $v eq '«' ) and $i > 0 and _can_end_statement( $tokens->[ $i - 1 ] ) ) {
614 next;
615 }
616  
617 if ( $_PAIR_CLOSE_FOR_OPEN{$v} ) {
618 push @stack, [ $v, $i ];
619 next;
620 }
621 if ( $_PAIR_OPEN_FOR_CLOSE{$v} ) {
622 next if ! @stack;
623 my ( $open, $open_i ) = @{ $stack[-1] };
624 next if $_PAIR_CLOSE_FOR_OPEN{$open} ne $v;
625 pop @stack;
626 $pair{$open_i} = $i;
627 $pair{$i} = $open_i;
628 }
629 }
630  
631 return %pair;
632 }
633  
634 sub _tag_trailing_comma_sequences {
635 # Marks an open delimiter of a comma-separated sequence (call/parameter
636 # argument list, array, dict, set, bag, or guillemet-set literal) when
637 # the token immediately before its matching close is a literal comma.
638 # A literal trailing comma is a strong signal that the sequence should
639 # be rendered one item per line, so this is decided once up front (like
640 # _tag_declaration_block_braces) rather than guessed at format time.
641 # Bare { is included for dict literals; pairlist {{ ... }} is left
642 # alone since it is already unconditionally forced via _pairlist_half.
643 my ( $tokens, $pair_for ) = @_;
644  
645 for my $i ( 0 .. $#$tokens ) {
646 my $tok = $tokens->[$i];
647 next if ! $tok->is_OP;
648 my $v = $tok->value;
649 next if $v ne '(' and $v ne '[' and $v ne '<<' and $v ne '<<<' and $v ne '«' and $v ne '{';
650 next if $v eq '{' and defined $tok->{_pairlist_half};
651  
652 next if ! exists $pair_for->{$i};
653 my $close_i = $pair_for->{$i};
654 next if $close_i <= $i + 1;
655  
656 my $before_close = $tokens->[ $close_i - 1 ];
657 next if ! $before_close->is_OP(',');
658  
659 $tok->{_force_sequence} = 1;
660 }
661  
662 return;
663 }
664  
665 sub _need_space_before {
666 my ( $tokens, $i, $pair_for ) = @_;
667 my $tok = $tokens->[$i];
668 my $v = defined $tok->value ? $tok->value : '';
669 return 0 if $i == 0;
670  
671 my $prev = $tokens->[ $i - 1 ];
672 my $pv = defined $prev->value ? $prev->value : '';
673  
674 if ( _is_module_path_slash( $tokens, $i ) ) {
675 return 0;
676 }
677 if ( _is_module_path_slash( $tokens, $i - 1 ) ) {
678 return 0;
679 }
680  
681 if ( $v eq '...' and _is_call_spread_operator( $tokens, $i ) ) {
682 return 0;
683 }
684 if ( $pv eq '...' and _is_call_spread_operator( $tokens, $i - 1 ) ) {
685 return 0;
686 }
687  
688 if ( $v eq '{' and $pv eq '{' ) {
689 return 0;
690 }
691 if ( $v eq '}' and $pv eq '}' ) {
692 # Two genuinely independent adjacent closing braces (e.g. nested
693 # dict literals) need a space, since re-lexing "}}" with no space
694 # would produce a single pairlist-close token instead. The two
695 # halves of an actual split {{ ... }} pairlist delimiter must stay
696 # tight, since that is what they were before splitting.
697 return 0 if defined $tok->{_pairlist_half} and $tok->{_pairlist_half} eq 'close2'
698 and defined $prev->{_pairlist_half} and $prev->{_pairlist_half} eq 'close1';
699 return 1;
700 }
701  
702 if ( $v eq '?' and $prev->is_IDENT ) {
703 my $next = $i < $#$tokens ? $tokens->[ $i + 1 ] : undef;
704 if ( $next and $next->is_OP and ( $next->value eq ',' or $next->value eq ')' ) ) {
705 return 0;
706 }
707 }
708  
709 return 0 if _is_unary_punct_operator( $tokens, $i - 1 );
710 if (
711 ( $v eq '++' or $v eq '--' )
712 and (
713 $prev->is_IDENT
714 or ( $prev->is_OP and ( $pv eq ')' or $pv eq ']' or $pv eq '}' ) )
715 )
716 ) {
717 return 0;
718 }
719  
720 if (
721 $v eq '{'
722 and _is_inline_brace( $tokens, $i, $pair_for )
723 and (
724 $prev->is_IDENT
725 or ( $prev->is_OP and ( $pv eq ')' or $pv eq ']' or $pv eq '}' ) )
726 )
727 ) {
728 return 0;
729 }
730  
731 if ( $pv eq '{' ) {
732 my $open_i = $i - 1;
733 if (
734 defined $pair_for->{$open_i}
735 and _is_inline_brace( $tokens, $open_i, $pair_for )
736 and ! _brace_needs_inner_space( $tokens, $open_i, $pair_for->{$open_i} )
737 ) {
738 return 0;
739 }
740 return 1;
741 }
742  
743 if ( $v eq '}' ) {
744 my $open_i = $pair_for->{$i};
745 if (
746 defined $open_i
747 and _is_inline_brace( $tokens, $open_i, $pair_for )
748 and ! _brace_needs_inner_space( $tokens, $open_i, $i )
749 ) {
750 return 0;
751 }
752 return 1;
753 }
754  
755 if ( $v eq ':' and _is_switch_comparator_colon( $tokens, $i ) ) {
756 return 1;
757 }
758 if ( $pv eq ':' and _is_slice_colon( $tokens, $i - 1, $pair_for ) ) {
759 return 0;
760 }
761  
762 # Guarded by is_OP so a string/binary-string literal whose decoded
763 # content happens to equal a punctuation operator (e.g. the literal
764 # string ":" in `text _ ":" _ item`) isn't mistaken for that
765 # operator and tightened against its neighbour.
766 return 0 if $tok->is_OP and $NO_SPACE_BEFORE{$v} and $v ne ')' and $v ne ']';
767 return 0 if $prev->is_OP and $NO_SPACE_AFTER{$pv} and $pv ne '(' and $pv ne '[';
768  
769 if ( $v eq '(' or $v eq '[' ) {
770 if ( $pv eq ',' ) {
771 return 1;
772 }
773 if ( _is_binary_op( $tokens, $i - 1 ) ) {
774 return 1;
775 }
776 if ( $prev->is_KW and $CONTROL_KW{ $prev->value } ) {
777 return 1;
778 }
779 if ( $v eq '[' and $prev->is_OP and $pv ne '.' and $pv ne ')' and $pv ne ']' and $pv ne '}' ) {
780 return 1;
781 }
782 if ( $v eq '(' and $prev->is_IDENT and $i >= 2 ) {
783 my $before_prev = $tokens->[ $i - 2 ];
784 if ( $before_prev->is_KW('function') or $before_prev->is_KW('method') ) {
785 return 1;
786 }
787 }
788 if ( defined $pair_for->{$i} and ! _paren_needs_inner_space( $tokens, $i, $pair_for->{$i} ) ) {
789 return 0;
790 }
791 if ( $pv eq ')' or $pv eq ']' ) {
792 return 0;
793 }
794 if ( $pv eq '}' or $pv eq '.' ) {
795 return 0;
796 }
797 return 0;
798 }
799  
800 if ( $pv eq '(' or $pv eq '[' ) {
801 my $open_i = $i - 1;
802 if ( defined $pair_for->{$open_i} and ! _paren_needs_inner_space( $tokens, $open_i, $pair_for->{$open_i} ) ) {
803 return 0;
804 }
805 return 1;
806 }
807  
808 if ( $v eq ')' or $v eq ']' ) {
809 my $open_i = $pair_for->{$i};
810 if ( defined $open_i and ! _paren_needs_inner_space( $tokens, $open_i, $i ) ) {
811 return 0;
812 }
813 return 1;
814 }
815  
816 if ( $pv eq '⌊' or $pv eq '⌈' ) {
817 my $open_i = $i - 1;
818 if ( defined $pair_for->{$open_i} and ! _paren_needs_inner_space( $tokens, $open_i, $pair_for->{$open_i} ) ) {
819 return 0;
820 }
821 return 1;
822 }
823  
824 if ( $v eq '⌋' or $v eq '⌉' ) {
825 my $open_i = $pair_for->{$i};
826 if ( defined $open_i and ! _paren_needs_inner_space( $tokens, $open_i, $i ) ) {
827 return 0;
828 }
829 return 1;
830 }
831  
832 if ( _is_binary_op( $tokens, $i ) ) {
833 return 1;
834 }
835 if ( _is_binary_op( $tokens, $i - 1 ) ) {
836 return 1;
837 }
838  
839 return 1;
840 }
841  
842 sub _enclosing_open_index {
843 # Returns the token index of the nearest enclosing unmatched
844 # `(`/`[`/`{` before position $i, or undef at the top level.
845 my ( $tokens, $i ) = @_;
846  
847 my @stack;
848 for my $k ( 0 .. $i - 1 ) {
849 my $v = defined $tokens->[$k]->value ? $tokens->[$k]->value : '';
850 if ( $v eq '(' or $v eq '[' or $v eq '{' ) {
851 push @stack, $k;
852 }
853 elsif ( $v eq ')' or $v eq ']' or $v eq '}' ) {
854 pop @stack if @stack;
855 }
856 }
857  
858 return @stack ? $stack[-1] : undef;
859 }
860  
861 sub _is_switch_comparator_colon {
862 # The `:` that separates a switch subject expression from its
863 # comparator operator, e.g. `switch ( n mod 4 : = )`, reads better
864 # with a space on both sides, unlike every other use of `:` (case
865 # labels, dict keys, ternaries, slices), which stay tight. Detected
866 # by finding the nearest enclosing unmatched bracket: it must be a
867 # `(` opened directly by the `switch` keyword, not some deeper
868 # bracket (e.g. a slice inside the switch subject).
869 my ( $tokens, $i ) = @_;
870 return 0 if !$tokens->[$i]->is_OP(':');
871  
872 my $open_i = _enclosing_open_index( $tokens, $i );
873 return 0 if !defined $open_i;
874 return 0 if !$tokens->[$open_i]->is_OP('(');
875 return 0 if $open_i == 0;
876 return 1 if $tokens->[ $open_i - 1 ]->is_KW('switch');
877  
878 return 0;
879 }
880  
881 sub _is_simple_slice_inner {
882 # True if the tokens between `[` and `]` look like a slice:
883 # zero or more `:`-separated parts, each either empty (an omitted
884 # bound, e.g. `[:2]`) or a single simple token.
885 my ( @inner ) = @_;
886  
887 my @parts = ( [] );
888 for my $tok ( @inner ) {
889 if ( $tok->is_OP(':') ) {
890 push @parts, [];
891 next;
892 }
893 push @{ $parts[-1] }, $tok;
894 }
895 return 0 if @parts < 2;
896  
897 for my $part ( @parts ) {
898 return 0 if @$part > 1;
899 return 0 if @$part == 1 and !_is_simple_token( $part->[0] );
900 }
901  
902 return 1;
903 }
904  
905 sub _is_slice_colon {
906 # A `:` directly inside `[ ... ]` that separates simple slice bounds,
907 # e.g. `text[1:2]`, stays tight on both sides, unlike a dict key's
908 # `:` (`{ a: 1 }`) or the switch comparator's `:`.
909 my ( $tokens, $i, $pair_for ) = @_;
910 return 0 if !$tokens->[$i]->is_OP(':');
911  
912 my $open_i = _enclosing_open_index( $tokens, $i );
913 return 0 if !defined $open_i;
914 return 0 if !$tokens->[$open_i]->is_OP('[');
915 my $close_i = $pair_for->{$open_i};
916 return 0 if !defined $close_i;
917  
918 my @inner = @{$tokens}[ $open_i + 1 .. $close_i - 1 ];
919 return _is_simple_slice_inner(@inner);
920 }
921  
922 sub _is_module_path_slash {
923 my ( $tokens, $i ) = @_;
924 return 0 if $i < 0 or $i > $#$tokens;
925 my $tok = $tokens->[$i];
926 return 0 if ! $tok->is_OP or $tok->value ne '/';
927  
928 my $stmt_start = 0;
929 for ( my $k = $i - 1; $k >= 0; $k-- ) {
930 my $v = defined $tokens->[$k]->value ? $tokens->[$k]->value : '';
931 if ( $v eq ';' or $v eq '{' or $v eq '}' ) {
932 $stmt_start = $k + 1;
933 last;
934 }
935 }
936  
937 my $from_i = -1;
938 for ( my $k = $i - 1; $k >= $stmt_start; $k-- ) {
939 if ( $tokens->[$k]->is_KW('from') ) {
940 $from_i = $k;
941 last;
942 }
943 }
944 return 0 if $from_i < 0;
945  
946 my $stmt_end = $#$tokens;
947 for ( my $k = $i + 1; $k <= $#$tokens; $k++ ) {
948 my $v = defined $tokens->[$k]->value ? $tokens->[$k]->value : '';
949 if ( $v eq ';' or $v eq '{' or $v eq '}' ) {
950 $stmt_end = $k - 1;
951 last;
952 }
953 }
954  
955 my $import_i = -1;
956 for ( my $k = $from_i + 1; $k <= $stmt_end; $k++ ) {
957 if ( $tokens->[$k]->is_KW('import') ) {
958 $import_i = $k;
959 last;
960 }
961 }
962 return 0 if $import_i < 0;
963 return 0 if $i <= $from_i or $i >= $import_i;
964  
965 for my $k ( $from_i + 1 .. $import_i - 1 ) {
966 my $t = $tokens->[$k];
967 next if $t->is_IDENT;
968 next if $t->is_KW('try');
969 next if $t->is_OP and $t->value eq '/';
970 return 0;
971 }
972  
973 return 1;
974 }
975  
976 sub _display_token_text {
977 my ( $tokens, $i, %opts ) = @_;
978 my $tok = $tokens->[$i];
979 my $raw = _token_text($tok);
980  
981 return $raw if !$opts{canonical_operators};
982 return $raw if !exists $CANONICAL_OPERATOR_SPELLING{$raw};
983 return $raw if !_can_canonicalize_operator( $tokens, $i );
984  
985 return $CANONICAL_OPERATOR_SPELLING{$raw};
986 }
987  
988 sub _can_canonicalize_operator {
989 my ( $tokens, $i ) = @_;
990 my $tok = $tokens->[$i];
991 my $raw = _token_text($tok);
992  
993 return 0 if !$tok->is_OP and !$tok->is_KW;
994 return 0 if _is_module_path_slash( $tokens, $i );
995 return 0 if _is_import_wildcard( $tokens, $i );
996 return 0 if $raw eq 'in' and _is_for_loop_in_keyword( $tokens, $i );
997 return 1 if $raw eq '*=' or $raw eq '/=';
998 return 1 if _is_chain_op($raw);
999 return 1 if _is_unary_operator( $tokens, $i );
1000 return 1 if _is_binary_op( $tokens, $i );
1001  
1002 return 0;
1003 }
1004  
1005 sub _is_import_wildcard {
1006 my ( $tokens, $i ) = @_;
1007 return 0 if $i < 0 or $i > $#$tokens;
1008 return 0 if !$tokens->[$i]->is_OP('*');
1009  
1010 for ( my $k = $i - 1; $k >= 0; $k-- ) {
1011 my $v = defined $tokens->[$k]->value ? $tokens->[$k]->value : '';
1012 return 0 if $v eq ';' or $v eq '{' or $v eq '}';
1013 return 1 if $tokens->[$k]->is_KW('import');
1014 }
1015  
1016 return 0;
1017 }
1018  
1019 sub _is_for_loop_in_keyword {
1020 my ( $tokens, $i ) = @_;
1021 return 0 if $i < 0 or $i > $#$tokens;
1022 return 0 if !$tokens->[$i]->is_KW('in');
1023  
1024 my @stack;
1025 for my $k ( 0 .. $i - 1 ) {
1026 my $v = defined $tokens->[$k]->value ? $tokens->[$k]->value : '';
1027 if ( $v eq '(' ) {
1028 push @stack, $k;
1029 next;
1030 }
1031 if ( $v eq ')' ) {
1032 pop @stack if @stack;
1033 }
1034 }
1035 return 0 if !@stack;
1036  
1037 my $open_i = $stack[-1];
1038 return 0 if $open_i == 0;
1039 return 1 if $tokens->[ $open_i - 1 ]->is_KW('for');
1040  
1041 return 0;
1042 }
1043  
1044 sub _is_binary_op {
1045 my ( $tokens, $i ) = @_;
1046 return 0 if $i < 0 or $i > $#$tokens;
1047 my $tok = $tokens->[$i];
1048 return 0 if ! $tok->is_OP and ! $tok->is_KW;
1049 my $v = $tok->value;
1050 return 0 if ! $BINARY_OP{$v};
1051 return 0 if _is_unary_operator( $tokens, $i );
1052  
1053 return 1;
1054 }
1055  
1056 sub _is_call_spread_operator {
1057 my ( $tokens, $i ) = @_;
1058 return 0 if $i < 0 or $i > $#$tokens;
1059 my $tok = $tokens->[$i];
1060 return 0 if ! $tok->is_OP or $tok->value ne '...';
1061  
1062 my $prev = $i > 0 ? $tokens->[ $i - 1 ] : undef;
1063 return 0 if !$prev;
1064 return 1 if $prev->is_OP and ( $prev->value eq '(' or $prev->value eq ',' );
1065  
1066 return 0;
1067 }
1068  
1069 sub _is_unary_operator {
1070 my ( $tokens, $i ) = @_;
1071 my $tok = $tokens->[$i];
1072 return 0 if ! $tok->is_OP and ! $tok->is_KW;
1073 my $v = $tok->value;
1074 return 0 if ! $UNARY_PREFIX_OP{$v};
1075  
1076 return 1 if $i == 0;
1077 my $prev = $tokens->[ $i - 1 ];
1078 if ( $prev->is_OP ) {
1079 my $pv = defined $prev->value ? $prev->value : '';
1080 return 1 if $pv ne ')'
1081 and $pv ne ']'
1082 and $pv ne '}'
1083 and $pv ne '⌋'
1084 and $pv ne '⌉'
1085 and $pv ne '»'
1086 and $pv ne '>>'
1087 and $pv ne '>>>';
1088 }
1089 return 1 if $prev->is_KW and $prev->value ne 'true' and $prev->value ne 'false' and $prev->value ne 'null';
1090  
1091 return 0;
1092 }
1093  
1094 sub _is_unary_punct_operator {
1095 my ( $tokens, $i ) = @_;
1096 return 0 if $i < 0 or $i > $#$tokens;
1097 my $tok = $tokens->[$i];
1098 return 0 if ! $tok->is_OP;
1099 return 0 if ! _is_unary_operator( $tokens, $i );
1100 return $tok->value =~ /[[:alpha:]]/ ? 0 : 1;
1101 }
1102  
1103 sub _paren_needs_inner_space {
1104 my ( $tokens, $open_i, $close_i ) = @_;
1105 return 0 if $close_i == $open_i + 1;
1106  
1107 my @inner = @{$tokens}[ $open_i + 1 .. $close_i - 1 ];
1108 if ( @inner == 1 ) {
1109 return _is_simple_token( $inner[0] ) ? 0 : 1;
1110 }
1111 if (
1112 @inner == 2
1113 and $inner[0]->is_OP
1114 and $inner[0]->value eq '...'
1115 and _is_simple_token( $inner[1] )
1116 ) {
1117 return 0;
1118 }
1119 if ( $tokens->[$open_i]->is_OP('[') and _is_simple_slice_inner(@inner) ) {
1120 return 0;
1121 }
1122  
1123 return 1;
1124 }
1125  
1126 sub _brace_needs_inner_space {
1127 my ( $tokens, $open_i, $close_i ) = @_;
1128 return 0 if $close_i == $open_i + 1;
1129 my $before = $open_i > 0 ? $tokens->[ $open_i - 1 ] : undef;
1130 my $before_val = ( $before and defined $before->value ) ? $before->value : '';
1131 my $is_accessor = 0;
1132 if ($before) {
1133 $is_accessor = 1 if $before->is_IDENT;
1134 $is_accessor = 1 if $before->is_OP and ( $before_val eq ')' or $before_val eq ']' or $before_val eq '}' );
1135 }
1136  
1137 my @inner = @{$tokens}[ $open_i + 1 .. $close_i - 1 ];
1138 if ( $is_accessor ) {
1139 return _is_simple_token( $inner[0] ) ? 0 : 1 if @inner == 1;
1140 return 1;
1141 }
1142  
1143 return 1;
1144 }
1145  
1146 sub _is_simple_token {
1147 my ( $tok ) = @_;
1148 return 1 if $tok->is_IDENT;
1149 return 1 if $tok->is_NUMBER;
1150 return 1 if $tok->is_BOOL;
1151 return 1 if $tok->is_NULL;
1152 if ( $tok->is_STRING or $tok->is_type('BINARY_STRING') or $tok->is_type('TEMPLATE') ) {
1153 my $value = defined $tok->value ? $tok->value : '';
1154 return length($value) <= 12 ? 1 : 0;
1155 }
1156  
1157 return 0;
1158 }
1159  
1160 sub _needs_auto_semicolon {
1161 my ( $tok, $next, $paren_depth, $bracket_depth, $brace_depth, $inline_brace_depth, $just_closed_inline, $angle_depth ) = @_;
1162 return 0 if $tok->is_OP and ( $tok->value eq ';' or $tok->value eq '{' );
1163 return 0 if $tok->is_OP and $tok->value eq '}' and ! $just_closed_inline;
1164 return 0 if $tok->is_OP and $tok->value eq ':';
1165 return 0 if $tok->is_KW('else');
1166 if ( $next->is_KW and ( $next->value eq 'if' or $next->value eq 'unless' ) ) {
1167 return 0;
1168 }
1169 return 0 if $next->is_OP and ( $next->value eq ';' or $next->value eq ')' or $next->value eq ']' or $next->value eq '⌋' or $next->value eq '⌉' or $next->value eq ',' or $next->value eq ':' );
1170 return 0 if $paren_depth > 0 or $bracket_depth > 0 or ( $angle_depth // 0 ) > 0;
1171 return 0 if $inline_brace_depth > 0;
1172 return 1 if $next->is_OP and $next->value eq '}' and _can_end_statement($tok);
1173 return 1 if $next->is_KW('else');
1174 return 1 if $tok->line < $next->line and _can_end_statement($tok) and _can_start_statement($next);
1175  
1176 return 0;
1177 }
1178  
1179 sub _is_inline_brace {
1180 my ( $tokens, $i, $pair_for ) = @_;
1181 return 0 if $i <= 0;
1182  
1183 return 0 if $tokens->[$i]{_forced_block};
1184 return 0 if $tokens->[$i]{_force_sequence};
1185  
1186 my $pairlist_half = $tokens->[$i]{_pairlist_half};
1187 if ( defined $pairlist_half ) {
1188 # The first half of a split {{ is always inline, so it never
1189 # triggers its own newline/indent; the second half is always
1190 # block-kind, which is what produces the indented pairlist body.
1191 # This is independent of whatever token precedes the pairlist
1192 # (e.g. a spread `...`), unlike the heuristics below.
1193 return 1 if $pairlist_half eq 'open1';
1194 return 0 if $pairlist_half eq 'open2';
1195 }
1196  
1197 my $prev = $tokens->[ $i - 1 ];
1198 my $pv = defined $prev->value ? $prev->value : '';
1199  
1200 if ( $prev->is_IDENT ) {
1201 if ( $i >= 2 and $tokens->[ $i - 2 ]->is_KW ) {
1202 my $kw = $tokens->[ $i - 2 ]->value;
1203 return 0 if $kw eq 'class' or $kw eq 'trait';
1204 }
1205 return 1;
1206 }
1207  
1208 if ( $prev->is_KW ) {
1209 my $kw = $prev->value;
1210 return 0 if $CONTROL_KW{$kw}
1211 or $kw eq 'class'
1212 or $kw eq 'trait'
1213 or $kw eq 'else'
1214 or $kw eq 'try'
1215 or $kw eq 'do'
1216 or $kw eq 'await'
1217 or $kw eq 'spawn'
1218 or $kw eq 'function'
1219 or $kw eq 'method';
1220 return 1;
1221 }
1222  
1223 if ( $prev->is_OP and ( $pv eq ':=' or $pv eq '=' or $pv eq ',' or $pv eq '(' or $pv eq '[' or $pv eq ':' ) ) {
1224 return 1;
1225 }
1226  
1227 if ( $prev->is_OP and $pv eq ')' ) {
1228 my $open_i = defined $pair_for->{ $i - 1 } ? $pair_for->{ $i - 1 } : undef;
1229 if ( defined $open_i and $open_i > 0 ) {
1230 my $before_open = $tokens->[ $open_i - 1 ];
1231 if ( $before_open->is_KW ) {
1232 my $kw = $before_open->value;
1233 return 0 if $CONTROL_KW{$kw} or $kw eq 'function' or $kw eq 'method' or $kw eq 'while';
1234 }
1235 if ( $before_open->is_IDENT and $open_i > 1 and $tokens->[ $open_i - 2 ]->is_KW ) {
1236 my $kw = $tokens->[ $open_i - 2 ]->value;
1237 return 0 if $kw eq 'function' or $kw eq 'method';
1238 }
1239 }
1240 return 1;
1241 }
1242  
1243 if ( $prev->is_OP and ( $pv eq ']' or $pv eq '}' ) ) {
1244 return 1;
1245 }
1246  
1247 return 0;
1248 }
1249  
1250 sub _is_expression_block_brace {
1251 my ( $tokens, $i ) = @_;
1252 return 0 if $i <= 0;
1253  
1254 my $prev = $tokens->[ $i - 1 ];
1255 return 0 if !$prev->is_KW;
1256  
1257 my $kw = $prev->value;
1258 return 1 if $kw eq 'await' or $kw eq 'spawn' or $kw eq 'do';
1259  
1260 return 0;
1261 }
1262  
1263 sub _can_end_statement {
1264 my ( $tok ) = @_;
1265 return 1 if $tok->is_IDENT or $tok->is_NUMBER or $tok->is_STRING or $tok->is_BOOL or $tok->is_NULL;
1266 return 1 if $tok->is_type('BINARY_STRING');
1267 return 1 if $tok->is_REGEXP or $tok->is_type('TEMPLATE') or $tok->is_EMPTY_SET;
1268 return 1 if $tok->is_OP and (
1269 $tok->value eq ')'
1270 or $tok->value eq ']'
1271 or $tok->value eq '}'
1272 or $tok->value eq '⌋'
1273 or $tok->value eq '⌉'
1274 or $tok->value eq '»'
1275 or $tok->value eq '>>'
1276 or $tok->value eq '>>>'
1277 or $tok->value eq '++'
1278 or $tok->value eq '--'
1279 );
1280  
1281 return 0;
1282 }
1283  
1284 sub _can_start_statement {
1285 my ( $tok ) = @_;
1286 return 1 if $tok->is_IDENT or $tok->is_KW;
1287 return 1 if $tok->is_NUMBER or $tok->is_STRING or $tok->is_BOOL or $tok->is_NULL;
1288 return 1 if $tok->is_REGEXP or $tok->is_EMPTY_SET;
1289 return 1 if $tok->is_type('BINARY_STRING') or $tok->is_type('TEMPLATE');
1290 return 1 if $tok->is_OP and (
1291 $tok->value eq '('
1292 or $tok->value eq '['
1293 or $tok->value eq '{'
1294 or $tok->value eq '<<'
1295 or $tok->value eq '<<<'
1296 or $tok->value eq '«'
1297 or $tok->value eq '⌊'
1298 or $tok->value eq '⌈'
1299 );
1300  
1301 return 0;
1302 }
1303  
1304 sub _token_text {
1305 my ( $tok ) = @_;
1306  
1307 if ( $tok->is_STRING ) {
1308 my $value = defined $tok->value ? $tok->value : '';
1309 return '"' . _escape_literal( $value, '"' ) . '"';
1310 }
1311 if ( $tok->is_type('BINARY_STRING') ) {
1312 my $value = defined $tok->value ? $tok->value : '';
1313 return "'" . _escape_literal( $value, "'" ) . "'";
1314 }
1315 if ( $tok->is_BOOL ) {
1316 return $tok->value ? 'true' : 'false';
1317 }
1318 if ( $tok->is_NULL ) {
1319 return 'null';
1320 }
1321 if ( $tok->is_REGEXP ) {
1322 my $re = $tok->value;
1323 my $flags = $re->{flags} // '';
1324 my $pattern = exists $re->{parts}
1325 ? _flatten_interpolated_parts( $re->{parts} )
1326 : ( $re->{pattern} // '' );
1327 return '/' . $pattern . '/' . $flags;
1328 }
1329 if ( $tok->is_type('TEMPLATE') ) {
1330 my $value = defined $tok->value ? $tok->value : '';
1331 return '`' . _flatten_interpolated_parts( $value, 1 ) . '`'
1332 if ref $value eq 'ARRAY';
1333 return '`' . _escape_literal( $value, '`' ) . '`';
1334 }
1335 if ( $tok->is_EMPTY_SET ) {
1336 return '∅';
1337 }
1338  
1339 return defined $tok->value ? $tok->value : '';
1340 }
1341  
1342 sub _flatten_interpolated_parts {
1343 my ( $parts, $escape_text ) = @_;
1344  
1345 return '' if ref $parts ne 'ARRAY';
1346  
1347 my $out = '';
1348 for my $part ( @$parts ) {
1349 if ( exists $part->{text} ) {
1350 my $text = $part->{text} // '';
1351 $text = _escape_literal( $text, '`' ) if $escape_text;
1352 $out .= $text;
1353 }
1354 elsif ( exists $part->{expr} ) {
1355 $out .= '${' . ( $part->{expr} // '' ) . '}';
1356 }
1357 }
1358  
1359 return $out;
1360 }
1361  
1362 sub _escape_literal {
1363 my ( $value, $quote ) = @_;
1364 $value =~ s/\\/\\\\/g;
1365 $value =~ s/\Q$quote\E/\\$quote/g;
1366 $value =~ s/\n/\\n/g;
1367 $value =~ s/\r/\\r/g;
1368 $value =~ s/\t/\\t/g;
1369  
1370 return $value;
1371 }
1372  
1373 sub _visual_length {
1374 my ( $line ) = @_;
1375 my $len = 0;
1376 for my $ch ( split //, $line ) {
1377 $len += ( $ch eq "\t" ) ? 4 : 1;
1378 }
1379  
1380 return $len;
1381 }
1382  
1383 sub _rstrip {
1384 my ( $value ) = @_;
1385 $value =~ s/[ \t]+\z//;
1386  
1387 return $value;
1388 }
1389  
1390 sub _stash_multiline_comments {
1391 my ( $src, $comment_map ) = @_;
1392 my $counter = 0;
1393  
1394 $src =~ s{
1395 /\* .*? \*/
1396 }{
1397 my $placeholder = '__ZUZU_TIDY_COMMENT_' . $counter . '__';
1398 $comment_map->{$placeholder} = $&;
1399 $counter++;
1400 "\n$placeholder\n";
1401 }egsx;
1402  
1403 return $src;
1404 }
1405  
1406 sub _restore_multiline_comments {
1407 my ( $src, $comment_map ) = @_;
1408 my @lines = split /\n/, $src, -1;
1409 my @out;
1410  
1411 for my $line ( @lines ) {
1412 if (
1413 $line =~ /^([ \t]*)(__ZUZU_TIDY_COMMENT_\d+__)(?:;)?\z/
1414 and exists $comment_map->{$2}
1415 ) {
1416 my $indent = $1;
1417 my $comment = $comment_map->{$2};
1418 my @comment_lines = split /\n/, $comment, -1;
1419 for my $comment_line ( @comment_lines ) {
1420 push @out, $indent . $comment_line;
1421 }
1422 next;
1423 }
1424  
1425 push @out, $line;
1426 }
1427  
1428 return join "\n", @out;
1429 }
1430  
1431 sub _strip_multiline_comments_for_parse {
1432 my ( $src ) = @_;
1433 $src =~ s{/\* .*? \*/}{}gsx;
1434  
1435 return $src;
1436 }
1437  
1438 sub _apply_vertical_spacing_rules {
1439 my ( $src ) = @_;
1440 my @lines = split /\n/, $src, -1;
1441 pop @lines if @lines and $lines[-1] eq '';
1442 return $src if ! @lines;
1443  
1444 my ( @open_for_line, @close_for_line );
1445 my @stack;
1446 my $paren_bracket_depth = 0;
1447  
1448 for my $i ( 0 .. $#lines ) {
1449 my $trimmed = $lines[$i];
1450 $trimmed =~ s/^\s+//;
1451 $trimmed =~ s/\s+\z//;
1452  
1453 # Track paren/bracket nesting across lines (approximate: doesn't
1454 # account for parens inside string literals) so a brace opened
1455 # while still inside an unclosed `(`/`[` -- e.g. a callback body
1456 # passed as a call argument -- can be told apart from a real
1457 # top-level statement block below.
1458 my $opens = () = $trimmed =~ /[(\[]/g;
1459 my $closes = () = $trimmed =~ /[)\]]/g;
1460  
1461 if ( $trimmed =~ /\{\z/ ) {
1462 my $kind = 'block';
1463 if ( $trimmed =~ /^(function|method)\b/ ) {
1464 $kind = $1;
1465 }
1466 elsif ( $trimmed =~ /^(if|else|while|for|try|catch|switch|unless)\b/ ) {
1467 $kind = 'statement_block';
1468 }
1469 push @stack, {
1470 kind => $kind,
1471 start => $i,
1472 is_call_argument => ( $paren_bracket_depth + $opens - $closes > 0 ) ? 1 : 0,
1473 };
1474 $open_for_line[$i] = $stack[-1];
1475 }
1476  
1477 $paren_bracket_depth += $opens - $closes;
1478  
1479 if ( $trimmed =~ /^\}/ ) {
1480 next if ! @stack;
1481 my $block = pop @stack;
1482 $block->{end} = $i;
1483 $close_for_line[$i] = $block;
1484 }
1485 }
1486  
1487 my %blank_before;
1488 my %blank_after;
1489  
1490 for my $i ( 0 .. $#lines ) {
1491 my $open_block = $open_for_line[$i];
1492 if ($open_block) {
1493 my $kind = $open_block->{kind};
1494 if ( ( $kind eq 'function' or $kind eq 'method' ) and ! $open_block->{is_call_argument} ) {
1495 $blank_before{$i} = 1;
1496 }
1497 }
1498  
1499 my $close_block = $close_for_line[$i];
1500 if ($close_block) {
1501 my $kind = $close_block->{kind};
1502 my $len = $close_block->{end} - $close_block->{start} + 1;
1503 if ( ( $kind eq 'function' or $kind eq 'method' ) and ! $close_block->{is_call_argument} ) {
1504 my $next_nonblank = _next_nonblank_line( \@lines, $i + 1 );
1505 if ( defined $next_nonblank and $lines[$next_nonblank] !~ /^\s*\}/ ) {
1506 $blank_after{$i} = 1;
1507 }
1508 }
1509 if ( $len >= 5 and ! $close_block->{is_call_argument} ) {
1510 $blank_before{ $close_block->{start} } = 1;
1511 my $next_nonblank = _next_nonblank_line( \@lines, $i + 1 );
1512 my $cuddles = defined $next_nonblank
1513 && $lines[$next_nonblank] =~ /^\s*(?:catch|else)\b/;
1514 $blank_after{$i} = 1 if ! $cuddles;
1515 }
1516 }
1517  
1518 if ( $lines[$i] =~ /^\s*\/\*/ ) {
1519 my $is_multiline = $lines[$i] !~ /\*\/\s*\z/ ? 1 : 0;
1520 $blank_before{$i} = 1 if $is_multiline;
1521 }
1522 }
1523  
1524 for my $i ( 0 .. $#lines ) {
1525 my $trimmed = $lines[$i];
1526 $trimmed =~ s/^\s+//;
1527 $trimmed =~ s/\s+\z//;
1528 next if $trimmed !~ /^return\b/;
1529  
1530 my $next_nonblank = _next_nonblank_line( \@lines, $i + 1 );
1531 next if ! defined $next_nonblank;
1532 next if $lines[$next_nonblank] !~ /^\s*\}/;
1533  
1534 my $closing_block = $close_for_line[$next_nonblank];
1535 next if ! $closing_block;
1536 next if $closing_block->{kind} ne 'function'
1537 and $closing_block->{kind} ne 'method';
1538 my $function_lines = $closing_block->{end} - $closing_block->{start} - 1;
1539 next if $function_lines <= 2;
1540 $blank_before{$i} = 1;
1541 }
1542  
1543 my @out;
1544 for my $i ( 0 .. $#lines ) {
1545 if (
1546 $blank_before{$i}
1547 and @out
1548 and $out[-1] =~ /\S/
1549 ) {
1550 push @out, '';
1551 }
1552  
1553 push @out, $lines[$i];
1554  
1555 if ( $blank_after{$i} ) {
1556 my $next_nonblank = _next_nonblank_line( \@lines, $i + 1 );
1557 if ( defined $next_nonblank ) {
1558 push @out, '' if $out[-1] =~ /\S/;
1559 }
1560 }
1561 }
1562  
1563 my @collapsed;
1564 my $previous_blank = 0;
1565 for my $line ( @out ) {
1566 if ( $line !~ /\S/ ) {
1567 next if $previous_blank;
1568 $previous_blank = 1;
1569 push @collapsed, '';
1570 next;
1571 }
1572 $previous_blank = 0;
1573 push @collapsed, $line;
1574 }
1575  
1576 return join( "\n", @collapsed ) . "\n";
1577 }
1578  
1579 sub _next_nonblank_line {
1580 my ( $lines, $start ) = @_;
1581 for my $i ( $start .. $#$lines ) {
1582 return $i if $lines->[$i] =~ /\S/;
1583 }
1584  
1585 return undef;
1586 }
1587  
1588 sub _find_matching_sequence_close {
1589 # Depth-aware search for the close delimiter matching the open
1590 # delimiter already consumed at the start of $after_open. Unlike a
1591 # plain textual scan for the first occurrence of $close, this tracks
1592 # nesting so an inner occurrence of the same bracket type (e.g. the
1593 # index brackets in `async_lambdas[0]` nested inside an outer `[ ... ]`
1594 # array literal) is not mistaken for the outer literal's close.
1595 my ( $lines, $start_i, $after_open, $open, $close ) = @_;
1596 my $depth = 1;
1597  
1598 for my $j ( $start_i .. $#$lines ) {
1599 my $text = $j == $start_i ? $after_open : $lines->[$j];
1600 while ( $text =~ /(\Q$open\E|\Q$close\E)/g ) {
1601 if ( $1 eq $open ) {
1602 $depth++;
1603 }
1604 else {
1605 $depth--;
1606 if ( $depth == 0 ) {
1607 my $end = pos($text);
1608 my $before = substr( $text, 0, $end - length($1) );
1609 my $after = substr( $text, $end );
1610 return ( $j, $before, $after );
1611 }
1612 }
1613 }
1614 }
1615  
1616 return ();
1617 }
1618  
1619 sub _split_top_level_commas {
1620 # Splits already-joined inner sequence content on commas, but only at
1621 # bracket depth 0 -- a comma inside a nested array/call/set/etc item
1622 # (e.g. reconstructing a sequence whose items are themselves bracketed
1623 # sub-expressions) must stay with that item rather than being treated
1624 # as another top-level separator.
1625 my ( $text ) = @_;
1626 my @parts;
1627 my $depth = 0;
1628 my $current = '';
1629 my $pos = 0;
1630 my $len = length $text;
1631  
1632 while ( $pos < $len ) {
1633 my $three = substr( $text, $pos, 3 );
1634 if ( $three eq '<<<' or $three eq '>>>' ) {
1635 $depth += $three eq '<<<' ? 1 : -1;
1636 $current .= $three;
1637 $pos += 3;
1638 next;
1639 }
1640 my $two = substr( $text, $pos, 2 );
1641 if ( $two eq '<<' or $two eq '>>' ) {
1642 $depth += $two eq '<<' ? 1 : -1;
1643 $current .= $two;
1644 $pos += 2;
1645 next;
1646 }
1647 my $ch = substr( $text, $pos, 1 );
1648 if ( $ch eq '(' or $ch eq '[' or $ch eq '{' or $ch eq '«' or $ch eq '⌊' or $ch eq '⌈' ) {
1649 $depth++;
1650 }
1651 elsif ( $ch eq ')' or $ch eq ']' or $ch eq '}' or $ch eq '»' or $ch eq '⌋' or $ch eq '⌉' ) {
1652 $depth--;
1653 }
1654 elsif ( $ch eq ',' and $depth == 0 ) {
1655 push @parts, $current;
1656 $current = '';
1657 $pos++;
1658 next;
1659 }
1660 $current .= $ch;
1661 $pos++;
1662 }
1663 push @parts, $current if $current ne '';
1664  
1665 return @parts;
1666 }
1667  
1668 sub _normalize_split_sequence_literals {
1669 my ( $src ) = @_;
1670 my @lines = split /\n/, $src, -1;
1671 my @out;
1672  
1673 my %close_for = (
1674 '[' => ']',
1675 '<<' => '>>',
1676 '<<<' => '>>>',
1677 '«' => '»',
1678 );
1679  
1680 for ( my $i = 0; $i <= $#lines; $i++ ) {
1681 my $line = $lines[$i];
1682 my ( $prefix, $open, $after_open ) = $line =~ /^(.*?(?::=|[\(\[,])\s*)(<<<|<<|«|\[)(.*)\z/;
1683 if ( ! defined $open or $after_open !~ /\S/ ) {
1684 # Nothing after the open delimiter on this line means it was
1685 # already split (e.g. by the trailing-comma-forces-multi-line
1686 # mechanism in _tidy_code_chunk); reprocessing it would flatten
1687 # the already-correct nested structure onto fewer lines.
1688 push @out, $line;
1689 next;
1690 }
1691  
1692 my $close = $close_for{$open};
1693 my ( $j, $before_close, $after_close )
1694 = _find_matching_sequence_close( \@lines, $i, $after_open, $open, $close );
1695 if ( ! defined $j ) {
1696 push @out, $line;
1697 next;
1698 }
1699 if ( $j == $i ) {
1700 push @out, $line;
1701 next;
1702 }
1703  
1704 my @inner_chunks = ( $after_open );
1705 push @inner_chunks, @lines[ $i + 1 .. $j - 1 ] if $j > $i + 1;
1706 push @inner_chunks, $before_close;
1707  
1708 my $inner_joined = join ' ', map {
1709 my $t = $_ // '';
1710 $t =~ s/^\s+//;
1711 $t =~ s/\s+\z//;
1712 $t;
1713 } @inner_chunks;
1714 my @parts = grep { $_ ne '' } map {
1715 my $p = $_;
1716 $p =~ s/^\s+//;
1717 $p =~ s/\s+\z//;
1718 $p;
1719 } _split_top_level_commas($inner_joined);
1720 if ( ! @parts ) {
1721 push @out, $line;
1722 next;
1723 }
1724  
1725 my ( $base_indent ) = $line =~ /^(\s*)/;
1726 my $inner_indent = $base_indent . "\t";
1727 push @out, $prefix . $open;
1728 for my $part ( @parts ) {
1729 push @out, $inner_indent . $part . ',';
1730 }
1731 my $tail = defined $after_close ? $after_close : '';
1732 $tail =~ s/^\s+//;
1733 my $extra_skip = 0;
1734 if ( $tail eq '' and $j + 1 <= $#lines and $lines[ $j + 1 ] =~ /^\s*;\s*\z/ ) {
1735 $tail = ';';
1736 $extra_skip = 1;
1737 }
1738 push @out, $base_indent . $close . $tail;
1739 $i = $j + $extra_skip;
1740 }
1741  
1742 return join "\n", @out;
1743 }
1744  
1745 =pod
1746  
1747 =head1 NAME
1748  
1749 Zuzu::Tidy - format ZuzuScript source with consistent style
1750  
1751 =head1 SYNOPSIS
1752  
1753 use Zuzu::Tidy;
1754  
1755 my $tidied = Zuzu::Tidy->tidy( $source, filename => 'main.zzs' );
1756 my $canonical = Zuzu::Tidy->tidy(
1757 $source,
1758 filename => 'main.zzs',
1759 canonical_operators => 1,
1760 );
1761  
1762 =head1 DESCRIPTION
1763  
1764 C<Zuzu::Tidy> rewrites ZuzuScript text into a consistent house style.
1765 It tokenizes with C<Zuzu::Lexer> and validates syntax with C<Zuzu::Parser>
1766 before rewriting. Pod sections are passed through unchanged.
1767  
1768 The tidier applies indentation, brace placement, operator spacing,
1769 parenthesis/bracket spacing, and adds trailing statement semicolons when
1770 needed.
1771  
1772 =head1 METHODS
1773  
1774 =head2 tidy
1775  
1776 Returns tidied source text as a single UTF-8 string.
1777  
1778 Pass C<canonical_operators =E<gt> 1> to rewrite non-canonical operator
1779 spellings such as C<*> and C<< |> >> to canonical forms such as C<×> and
1780 C<▷>. This option is disabled by default.
1781  
1782 =head1 SEE ALSO
1783  
1784 L<Zuzu::Lexer>, L<Zuzu::Parser>, L<Zuzu::Tidy::CLI>.
1785  
1786 =head1 COPYRIGHT AND LICENCE
1787  
1788 B<< Zuzu::Tidy >> is copyright Toby Inkster.
1789  
1790 It is free software; you may redistribute it and/or modify it under
1791 the terms of either the Artistic License 1.0 or the GNU General Public
1792 License version 2.
1793  
1794 =cut
1795  
1796 1;