blib/lib/BATsh.pm untested

filter: Statementstmt 0.0% 0 / 512 Branchbran 0.0% 0 / 276 Conditioncond 0.0% 0 / 105 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 970 SCAR 98.6
CC
138
Cov
0%
_sh_depth_delta
650.0
_process_lines
420.0
repl
380.0
CRAP 19182.0
1 package BATsh;
2 ######################################################################
3 #
4 # BATsh - Bilingual Shell for cmd.exe and bash in one script
5 #
6 # https://metacpan.org/dist/BATsh
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com>
9 #
10 # This version implements both cmd.exe and sh/bash command sets
11 # entirely in Perl. No external cmd.exe, bash, or sh is required.
12 #
13 ######################################################################
14  
15 use 5.00503;
16 use strict;
17 BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
18 use warnings; local $^W = 1;
19 BEGIN { pop @INC if $INC[-1] eq '.' }
20  
21 use File::Spec ();
22 BEGIN { eval { require Cwd } }
23 use Carp qw(croak);
24 use vars qw($VERSION);
25 $VERSION = '0.09';
26 $VERSION = $VERSION;
27  
28 require BATsh::MB;
29 require BATsh::Env;
30 require BATsh::CMD;
31 require BATsh::SH;
32  
33 ###############################################################################
34 # Architecture
35 ###############################################################################
36 #
37 # BATsh is a bilingual shell interpreter.
38 #
39 # It splits a script into CMD sections and SH sections, then executes
40 # each section using its own pure-Perl interpreter:
41 #
42 # BATsh::CMD -- cmd.exe command set (SET, ECHO, IF, FOR, GOTO, ...)
43 # BATsh::SH -- sh/bash command set (echo, export, if/fi, for/done, ...)
44 # BATsh::Env -- shared variable store (bridge between both modes)
45 #
46 # MODE DETECTION: first non-empty, non-comment token of each section.
47 # CMD: token is [A-Z 0-9 _ - \ / : . @ %]+ with at least one A-Z
48 # SH: anything else
49 #
50 # SECTION BOUNDARY:
51 # CMD: parenthesis ( ) depth returns to 0
52 # SH: keyword depth (if/fi, for/done, ...) returns to 0
53 #
54 # ENV BRIDGE:
55 # BATsh::Env::STORE is the single variable table.
56 # CMD %VAR% and SH $VAR both read/write the same store.
57 #
58 ###############################################################################
59  
60 ###############################################################################
61 # Global state
62 ###############################################################################
63 my $_TMPCOUNT = 0;
64  
65 # Subroutine registry: { LABEL => \@lines }
66 my %_SUBROUTINES = ();
67  
68 # Script-level exit state: set (to the exit code) the moment an SH "exit"
69 # or a CMD "EXIT" executes in any section, including inside a sourced file
70 # or a CALL'd subroutine. Once set, no further section is executed, and
71 # run()/run_string()/run_lines() return this code. Reset at the start of
72 # each top-level run.
73 my $_SCRIPT_EXIT = undef;
74  
75 ###############################################################################
76 # Constructor
77 ###############################################################################
78 sub new {
79 my ($class, %args) = @_;
80 BATsh::Env::init();
81 return bless { verbose => $args{verbose} || 0 }, $class;
82 }
83  
84 ###############################################################################
85 # Public run interface
86 ###############################################################################
87 sub run {
88 my ($class_or_self, $file, %args) = @_;
89 unless (-f $file) { croak "BATsh->run: file not found: $file" }
90 local *SRCFH;
91 open(SRCFH, $file) or croak "BATsh->run: cannot open $file: $!";
92 my @lines = <SRCFH>;
93 close(SRCFH);
94 _prepare_source(\@lines, $args{encoding});
95 _ensure_env_init();
96 # Set batch positional parameters: %0 = script path, %1..%9 = args, %* = all args
97 my @script_args = defined($args{args}) ? @{$args{args}} : ();
98 _set_batch_args($file, @script_args);
99 $_SCRIPT_EXIT = undef;
100 BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
101 _process_lines(@lines);
102 my $rc = _final_status();
103 BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
104 return $rc;
105 }
106  
107 sub run_string {
108 my ($class_or_self, $source, %args) = @_;
109 croak "BATsh->run_string: source required" unless defined $source;
110 my @lines = map { "$_\n" } split(/\n/, $source, -1);
111 _prepare_source(\@lines, $args{encoding});
112 _ensure_env_init();
113 # Optional positional parameters (used by "batsh - args..." and by
114 # callers that feed a script body as a string): %0 defaults to '-'.
115 if (defined $args{args}) {
116 _set_batch_args(defined $args{script_name} ? $args{script_name} : '-',
117 @{$args{args}});
118 }
119 $_SCRIPT_EXIT = undef;
120 BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
121 _process_lines(@lines);
122 my $rc = _final_status();
123 BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
124 return $rc;
125 }
126  
127 sub run_lines {
128 my ($class_or_self, @lines) = @_;
129 _prepare_source(\@lines, undef);
130 _ensure_env_init();
131 $_SCRIPT_EXIT = undef;
132 BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
133 _process_lines(@lines);
134 my $rc = _final_status();
135 BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
136 return $rc;
137 }
138  
139 # ----------------------------------------------------------------
140 # _final_status -- the exit status of the run just finished: the code of
141 # an executed exit/EXIT if any, else the last command's status. After
142 # every section flush both interpreters hold the same value (see
143 # _flush_cmd/_flush_sh), so the SH side is authoritative here.
144 # ----------------------------------------------------------------
145 sub _final_status {
146 return $_SCRIPT_EXIT if defined $_SCRIPT_EXIT;
147 return BATsh::SH::get_status();
148 }
149  
150 # ----------------------------------------------------------------
151 # last_status -- public accessor: the unified $? / %ERRORLEVEL% value.
152 # ----------------------------------------------------------------
153 sub last_status { return _final_status() }
154  
155 sub _ensure_env_init {
156 # Init only once per process
157 BATsh::Env::init() unless %BATsh::Env::STORE;
158 }
159  
160 ###############################################################################
161 # set_encoding -- select the script encoding for multibyte-safe execution
162 # BATsh->set_encoding('cp932'); # also: sjis gbk uhc big5 utf8 none auto
163 # The default is 'auto': a non-UTF-8 script containing bytes >= 0x80 is
164 # treated as CP932 and guarded (see BATsh::MB). The environment variable
165 # BATSH_ENCODING, when set, overrides the default before the first run.
166 ###############################################################################
167 my $_ENV_ENCODING_APPLIED = 0;
168  
169 sub set_encoding {
170 my ($class_or_self, $enc) = @_;
171 $enc = $class_or_self
172 if !defined($enc) && defined($class_or_self)
173 && $class_or_self !~ /\ABATsh\b/;
174 $_ENV_ENCODING_APPLIED = 1; # explicit choice beats BATSH_ENCODING
175 return BATsh::MB::set_encoding($enc);
176 }
177  
178 sub encoding { return BATsh::MB::encoding() }
179  
180 ###############################################################################
181 # _prepare_source -- per-run encoding setup on the raw script lines
182 # 1. strip a UTF-8 BOM from the first line
183 # 2. apply an explicit per-run encoding, or BATSH_ENCODING (once),
184 # or leave the current ('auto' by default) setting in place
185 # 3. under 'auto', detect the source encoding and activate the guard
186 # 4. guard-transform every line in place (identity when inactive)
187 ###############################################################################
188 sub _prepare_source {
189 my ($lines_ref, $encoding) = @_;
190 $lines_ref->[0] = BATsh::MB::strip_bom($lines_ref->[0]) if @{$lines_ref};
191 if (defined $encoding && $encoding ne '') {
192 BATsh::MB::set_encoding($encoding);
193 $_ENV_ENCODING_APPLIED = 1;
194 }
195 elsif (!$_ENV_ENCODING_APPLIED
196 && defined $ENV{BATSH_ENCODING} && $ENV{BATSH_ENCODING} ne '') {
197 BATsh::MB::set_encoding($ENV{BATSH_ENCODING});
198 $_ENV_ENCODING_APPLIED = 1;
199 }
200 BATsh::MB::activate_for(join('', @{$lines_ref}));
201 if (BATsh::MB::active()) {
202 for my $l (@{$lines_ref}) { $l = BATsh::MB::enc($l) }
203 }
204 return 1;
205 }
206  
207 ###############################################################################
208 # _set_batch_args -- populate %0..%9 and %* in the Env store
209 # %0 = script path (as passed to run())
210 # %1 = first argument, ..., %9 = ninth argument
211 # %* = all arguments joined by single space (does not include %0)
212 ###############################################################################
213 sub _set_batch_args {
214 my ($script, @args) = @_;
215 # Arguments arrive as RAW bytes from outside the interpreter
216 # (command line / caller); guard them before they enter the store.
217 @args = map { BATsh::MB::enc(defined $_ ? $_ : '') } @args;
218 # Normalise $0: resolve to absolute path using File::Spec
219 my $abs_script = defined $script ? $script : '';
220 if ($abs_script ne '' && !File::Spec->file_name_is_absolute($abs_script)) {
221 my $cwd = defined(&Cwd::cwd) ? Cwd::cwd() : '.';
222 $abs_script = File::Spec->catfile($cwd, $abs_script);
223 }
224 BATsh::Env->set('%0', BATsh::MB::enc($abs_script));
225 for my $n (1 .. 9) {
226 BATsh::Env->set("%$n", defined($args[$n - 1]) ? $args[$n - 1] : '');
227 }
228 BATsh::Env->set('%*', join(' ', @args));
229 }
230  
231 ###############################################################################
232 # classify_token
233 ###############################################################################
234 sub classify_token {
235 my ($class_or_token, $token) = @_;
236 unless (defined $token) { $token = $class_or_token }
237 if ($token =~ /\A[A-Z0-9_\-\\\/\.:@%]+\z/ && $token =~ /[A-Z]/) {
238 return 'CMD';
239 }
240 return 'SH';
241 }
242  
243 ###############################################################################
244 # Line parser
245 # Returns ($mode, $stripped_line, $first_token)
246 ###############################################################################
247 sub _parse_line {
248 my ($line) = @_;
249 (my $s = $line) =~ s/\r?\n\z//;
250 return ('EMPTY', $s, '') if $s =~ /\A\s*\z/;
251 return ('COMMENT', $s, '') if $s =~ /\A\s*(?:::|\@?REM(?:\s|\z))/i;
252 return ('COMMENT', $s, '') if $s =~ /\A\s*#(?!!)/;
253 (my $t = $s) =~ s/\A\s+//;
254 my $first = ($t =~ /\A(\S+)/) ? $1 : '';
255 return (classify_token($first), $s, $first);
256 }
257  
258 ###############################################################################
259 # CMD section depth: count unquoted ( )
260 ###############################################################################
261 sub _cmd_paren_delta {
262 my ($line) = @_;
263 my ($delta, $in_q) = (0, 0);
264 for my $ch (split //, $line) {
265 if ($ch eq '"') { $in_q = !$in_q }
266 elsif (!$in_q) {
267 $delta++ if $ch eq '(';
268 $delta-- if $ch eq ')';
269 }
270 }
271 return $delta;
272 }
273  
274 ###############################################################################
275 # SH section depth
276 ###############################################################################
277 my %_SH_OPEN = map { $_ => 1 } qw(if for while until case function select);
278 my %_SH_CLOSE = map { $_ => 1 } qw(fi done esac);
279  
280 # Net SH block-depth change for an ENTIRE line.
281 #
282 # A single physical line may both open and close a block, e.g.
283 # for i in 1 2 3; do echo $i; done (net 0)
284 # while COND; do ...; done; done (net -1, nested close)
285 # Looking only at the first token (as earlier versions did) counted the
286 # leading "for"/"while" but never the inline "done", so the SH section was
287 # left open and a following CMD line (e.g. ECHO ...%VAR%...) was wrongly
288 # absorbed into the SH section and run by the SH interpreter.
289 #
290 # Opener keywords (if for while until case function select) and "{" add 1;
291 # closer keywords (fi done esac) and "}" subtract 1, but only when they are in
292 # command position (line start, or just after ; & | ( ) { } or do/then/else/
293 # elif). Single- and double-quoted text, $( ... ) command substitutions and
294 # `...` backticks are skipped so that a "done" inside a string or substitution
295 # does not affect the depth. Perl 5.005_03 compatible (no regex features
296 # beyond character classes; substr/index style scanning).
297 sub _sh_depth_delta {
298 my ($line) = @_;
299 return 0 unless defined $line;
300  
301 # Fast path: a bare single keyword token (the common multi-line case).
302 if ($line !~ /[\s;&|(){}'"`]/) {
303 my $l = lc($line);
304 return 1 if exists $_SH_OPEN{$l};
305 return -1 if exists $_SH_CLOSE{$l};
306 return 0;
307 }
308  
309 my $delta = 0;
310 my $cmdpos = 1; # next bareword starts a new statement?
311 my $i = 0;
312 my $n = length($line);
313 while ($i < $n) {
314 my $c = substr($line, $i, 1);
315  
316 if ($c eq "'") { # single-quoted region
317 $i++;
318 $i++ while $i < $n && substr($line, $i, 1) ne "'";
319 $i++; $cmdpos = 0; next;
320 }
321 if ($c eq '"') { # double-quoted region
322 $i++;
323 while ($i < $n && substr($line, $i, 1) ne '"') {
324 if (substr($line, $i, 1) eq '\\') { $i += 2; next }
325 $i++;
326 }
327 $i++; $cmdpos = 0; next;
328 }
329 if ($c eq '`') { # backtick substitution
330 $i++;
331 $i++ while $i < $n && substr($line, $i, 1) ne '`';
332 $i++; $cmdpos = 0; next;
333 }
334 if ($c eq '$' && $i + 1 < $n && substr($line, $i + 1, 1) eq '(') {
335 $i += 2; # $( ... ) -- skip balanced parens
336 my $d = 1;
337 while ($i < $n && $d > 0) {
338 my $ch = substr($line, $i, 1);
339 $d++ if $ch eq '(';
340 $d-- if $ch eq ')';
341 $i++;
342 }
343 $cmdpos = 0; next;
344 }
345 if ($c =~ /\s/) { $i++; next }
346 if ($c eq ';' || $c eq '&' || $c eq '|') { $cmdpos = 1; $i++; next }
347 if ($c eq '(') { $cmdpos = 1; $i++; next }
348 if ($c eq ')') { $cmdpos = 1; $i++; next }
349 if ($c eq '{') { $delta++ if $cmdpos; $cmdpos = 1; $i++; next }
350 if ($c eq '}') { $delta-- if $cmdpos; $cmdpos = 1; $i++; next }
351  
352 # Bareword
353 my $word = '';
354 while ($i < $n) {
355 my $wc = substr($line, $i, 1);
356 last if $wc =~ /[\s;&|(){}'"`]/;
357 $word .= $wc; $i++;
358 }
359 if ($cmdpos) {
360 my $lw = lc($word);
361 if (exists $_SH_OPEN{$lw}) { $delta++ }
362 elsif (exists $_SH_CLOSE{$lw}) { $delta-- }
363 # do/then/else/elif keep the FOLLOWING word in command position so
364 # that an opener directly after them (e.g. "do for ...") is counted.
365 $cmdpos = ($lw eq 'do' || $lw eq 'then'
366 || $lw eq 'else' || $lw eq 'elif') ? 1 : 0;
367 }
368 else {
369 $cmdpos = 0;
370 }
371 }
372 return $delta;
373 }
374  
375 ###############################################################################
376 # Subroutine extraction
377 ###############################################################################
378 sub _extract_subroutines {
379 my (@lines) = @_;
380 my @out = (); my $in_sub = ''; my @sub_body = ();
381  
382 # Determine which :LABEL lines are subroutine ENTRY points (to be lifted
383 # out of the main stream and stored in %_SUBROUTINES) versus ordinary
384 # GOTO labels (which stay in the stream for the CMD interpreter).
385 #
386 # Two independent signals are unioned:
387 #
388 # (a) CALL targets: any label named by a "CALL :LABEL" anywhere in the
389 # script is an entry point. This is the decisive signal -- a label
390 # you CALL is a subroutine -- and it lets a subroutine contain its
391 # own internal GOTO labels without being mis-split.
392 #
393 # (b) The RET heuristic: a label whose block ends in RET/RETURN before
394 # the next label. Kept for backward compatibility so a subroutine
395 # invoked only indirectly is still recognised.
396 #
397 # A label is opened as a subroutine ONLY at the top level (not while
398 # already inside a subroutine body); once inside a body, every :LABEL is
399 # an internal label that travels with the body so that GOTO within the
400 # subroutine resolves, and only RET/RETURN closes the body.
401 my %is_sub_label = ();
402  
403 # (a) CALL targets (matched anywhere on the line, e.g. "IF .. CALL :X").
404 for my $line (@lines) {
405 (my $s = $line) =~ s/\r?\n\z//;
406 while ($s =~ /\bCALL\s+:([A-Za-z_][A-Za-z0-9_]*)/ig) {
407 $is_sub_label{uc($1)} = 1;
408 }
409 }
410  
411 # (b) RET heuristic.
412 {
413 my $cur = '';
414 for my $line (@lines) {
415 (my $s = $line) =~ s/\r?\n\z//;
416 $s =~ s/\A\s+//;
417 if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
418 $cur = uc($1);
419 }
420 elsif ($cur ne '' && $s =~ /\A(?:RET|RETURN)\s*\z/i) {
421 $is_sub_label{$cur} = 1;
422 $cur = '';
423 }
424 elsif ($cur ne '' && $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
425 # New label before RET: previous one is a GOTO label, not sub
426 $cur = uc($1);
427 }
428 }
429 }
430  
431 for my $line (@lines) {
432 (my $s = $line) =~ s/\r?\n\z//;
433 $s =~ s/\A\s+//;
434 if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
435 my $lbl = uc($1);
436 if ($in_sub ne '') {
437 # Inside a subroutine: this is an internal label of the body
438 # (a GOTO target), not a new subroutine. Keep it with the
439 # body so the CMD interpreter can resolve GOTO :internal.
440 push @sub_body, $line;
441 next;
442 }
443 if ($is_sub_label{$lbl}) {
444 # Top-level subroutine entry: lift it out of the main stream.
445 $in_sub = $lbl; @sub_body = ();
446 next; # remove the entry-label line from the stream
447 }
448 # Top-level GOTO label: keep in stream for the CMD interpreter.
449 push @out, $line;
450 next;
451 }
452 if ($in_sub ne '') {
453 if ($s =~ /\A(?:RET|RETURN)\s*\z/i) {
454 $_SUBROUTINES{$in_sub} = [@sub_body];
455 $in_sub = ''; @sub_body = ();
456 }
457 else {
458 push @sub_body, $line;
459 }
460 next;
461 }
462 push @out, $line;
463 }
464 $_SUBROUTINES{$in_sub} = [@sub_body] if $in_sub ne '';
465 return @out;
466 }
467  
468 ###############################################################################
469 # call_sub / source_file
470 ###############################################################################
471 sub call_sub {
472 my ($class_or_self, $label, @args) = @_;
473 $label = uc($label); $label =~ s/^://;
474 croak "BATsh->call_sub: undefined subroutine :$label"
475 unless exists $_SUBROUTINES{$label};
476  
477 # --- Save the caller's positional-parameter frame -----------------
478 # CALL :label is a true subroutine call: the callee gets its own
479 # %0..%9 / %* (and the SH-side BATSH_ARG* mirror), and the caller's
480 # parameters are restored on return. An undef snapshot means the key
481 # was absent and must be removed again on restore.
482 my @frame_keys = ('%0', '%1', '%2', '%3', '%4', '%5',
483 '%6', '%7', '%8', '%9', '%*',
484 'BATSH_ARGC',
485 'BATSH_ARG1', 'BATSH_ARG2', 'BATSH_ARG3',
486 'BATSH_ARG4', 'BATSH_ARG5', 'BATSH_ARG6',
487 'BATSH_ARG7', 'BATSH_ARG8', 'BATSH_ARG9');
488 my %saved;
489 for my $k (@frame_keys) {
490 $saved{$k} = exists $BATsh::Env::STORE{$k} ? $BATsh::Env::STORE{$k}
491 : undef;
492 }
493  
494 # --- Install the subroutine's own arguments -----------------------
495 # %0 is the label token (":LABEL"), matching cmd.exe, so that %~..0
496 # modifiers and %0 inside the subroutine refer to the label, not the
497 # outer script. %1..%9 are the call arguments; %* is their join.
498 BATsh::Env->set('%0', ":$label");
499 for my $n (1 .. 9) {
500 BATsh::Env->set("%$n", defined($args[$n-1]) ? $args[$n-1] : '');
501 }
502 BATsh::Env->set('%*', join(' ', @args));
503  
504 # SH-side mirror so a subroutine body written in SH mode still sees
505 # $1..$9 / $@. Keys beyond the supplied argument count are removed so
506 # a shorter call does not inherit the caller's stale BATSH_ARG* values.
507 $BATsh::Env::STORE{'BATSH_ARGC'} = scalar @args;
508 for my $n (1 .. 9) {
509 if ($n <= scalar @args) {
510 $BATsh::Env::STORE{"BATSH_ARG$n"} = $args[$n-1];
511 }
512 else {
513 delete $BATsh::Env::STORE{"BATSH_ARG$n"};
514 }
515 }
516  
517 # --- Run the body, then always restore the caller frame -----------
518 my $ok = eval { _process_lines(@{$_SUBROUTINES{$label}}); 1 };
519 my $err = $@;
520 for my $k (@frame_keys) {
521 if (defined $saved{$k}) { $BATsh::Env::STORE{$k} = $saved{$k} }
522 else { delete $BATsh::Env::STORE{$k} }
523 }
524 die $err unless $ok;
525 return 1;
526 }
527  
528 sub source_file {
529 my ($class_or_self, $file) = @_;
530 # The filename may arrive guard-transformed (from a CALL/source line
531 # inside a DBCS script); un-guard it before touching the filesystem.
532 $file = BATsh::MB::dec($file);
533 croak "BATsh->source_file: file not found: $file" unless -f $file;
534 local *SFHH;
535 open(SFHH, $file) or croak "BATsh->source_file: cannot open $file: $!";
536 my @src = <SFHH>;
537 close(SFHH);
538 _prepare_source(\@src, undef);
539 _process_lines(@src);
540 return 1;
541 }
542  
543 ###############################################################################
544 # SETLOCAL / ENDLOCAL (public API)
545 ###############################################################################
546 sub setlocal { BATsh::Env::setlocal() }
547 sub endlocal { BATsh::Env::endlocal() }
548  
549 ###############################################################################
550 # _exec_cmd_section -- run CMD lines through BATsh::CMD
551 ###############################################################################
552 sub _exec_cmd_section {
553 my (@lines) = @_;
554 return if defined $_SCRIPT_EXIT; # exit/EXIT already executed
555 # Handle BATsh-native directives before CMD interpreter
556 my @batch = ();
557 for my $line (@lines) {
558 (my $s = $line) =~ s/\r?\n\z//;
559 $s =~ s/\A\s+//;
560 if ($s =~ /\ASETLOCAL(?:\s+(.*))?\z/i) {
561 my $opts = defined $1 ? $1 : '';
562 # Pass the whole line through to CMD interpreter so it sees
563 # ENABLEDELAYEDEXPANSION etc; also update Env flags here.
564 push @batch, $line;
565 next;
566 }
567 if ($s =~ /\AENDLOCAL\s*\z/i) {
568 # Handled inside CMD.pm / _dispatch
569 push @batch, $line;
570 next;
571 }
572 # NOTE: CALL :label and CALL file.batsh are intentionally NOT
573 # intercepted here. They are handled by the CMD interpreter's
574 # _cmd_call (which delegates to call_sub / source_file). Letting
575 # CALL stay inside the batch keeps the whole CMD section in one
576 # exec_block, so a GOTO whose loop body contains a CALL still finds
577 # its label, and a subroutine body may use its own internal labels.
578 push @batch, $line;
579 }
580 _flush_cmd(\@batch) if @batch;
581 }
582  
583 sub _flush_cmd {
584 my ($lines_ref) = @_;
585 return unless @{$lines_ref};
586 return if defined $_SCRIPT_EXIT;
587 BATsh::CMD::exec_block('BATsh::CMD', $lines_ref,
588 _batsh => __PACKAGE__,
589 _pushd_stack => [],
590 );
591 # Status bridge: mirror the CMD-side ERRORLEVEL into the SH-side $?
592 # so the next SH section sees the outcome of this CMD section.
593 BATsh::SH::set_status(BATsh::CMD::_get_errorlevel());
594 # EXIT executed: terminate the whole script with ERRORLEVEL.
595 if (BATsh::CMD::_exit_requested()) {
596 BATsh::CMD::_clear_exit_requested();
597 $_SCRIPT_EXIT = BATsh::CMD::_get_errorlevel();
598 }
599 }
600  
601 ###############################################################################
602 # _exec_sh_section -- run SH lines through BATsh::SH
603 ###############################################################################
604 sub _exec_sh_section {
605 my (@lines) = @_;
606 return if defined $_SCRIPT_EXIT; # exit/EXIT already executed
607 my @batch = ();
608 for my $line (@lines) {
609 (my $s = $line) =~ s/\r?\n\z//;
610 $s =~ s/\A\s+//;
611 if ($s =~ /\A(?:source|\.)\s+(\S+\.batsh)/) {
612 my $bfile = $1;
613 _flush_sh(\@batch) if @batch; @batch = ();
614 eval { source_file('', $bfile) };
615 warn $@ if $@;
616 next;
617 }
618 push @batch, $line;
619 }
620 _flush_sh(\@batch) if @batch;
621 }
622  
623 sub _flush_sh {
624 my ($lines_ref) = @_;
625 return unless @{$lines_ref};
626 return if defined $_SCRIPT_EXIT;
627 BATsh::SH::exec_block('BATsh::SH', $lines_ref,
628 _batsh => __PACKAGE__,
629 );
630 # Status bridge: mirror the SH-side $? into the CMD-side ERRORLEVEL
631 # so the next CMD section sees the outcome of this SH section
632 # (ECHO %ERRORLEVEL%, IF ERRORLEVEL n, ...).
633 BATsh::CMD::_set_errorlevel(BATsh::SH::get_status());
634 # exit executed: terminate the whole script with its code.
635 my $ec = BATsh::SH::exit_code_pending();
636 $_SCRIPT_EXIT = $ec if defined $ec;
637 }
638  
639 ###############################################################################
640 # _process_lines -- main dispatcher
641 ###############################################################################
642 sub _process_lines {
643 my (@source) = @_;
644 @source = _extract_subroutines(@source);
645  
646 my @pending = (); my $cur_mode = ''; my $depth = 0;
647  
648 # Here-document tracking: while a here-document body is being collected,
649 # body lines are appended to the current section verbatim and are NOT
650 # reclassified (so an uppercase-leading body line is not misrouted to CMD).
651 # Activation is deferred by one line so the trigger line itself is
652 # classified normally.
653 my $hd_delim = undef; # active delimiter (collecting body)
654 my $hd_dash = 0;
655 my $pending_hd_delim = undef; # set on the trigger line, activated next iter
656 my $pending_hd_dash = 0;
657  
658 for my $raw (@source) {
659 chomp $raw;
660  
661 # Promote a pending here-document to active (trigger line already pushed)
662 if (defined $pending_hd_delim) {
663 $hd_delim = $pending_hd_delim;
664 $hd_dash = $pending_hd_dash;
665 $pending_hd_delim = undef;
666 }
667  
668 # Collecting a here-document body: pass through unclassified.
669 if (defined $hd_delim) {
670 push @pending, $raw;
671 my $probe = $raw;
672 $probe =~ s/\A\t+// if $hd_dash;
673 $hd_delim = undef if $probe eq $hd_delim;
674 next;
675 }
676  
677 my ($mode, $line, $first) = _parse_line($raw);
678  
679 # Detect a here-document opener on an SH line; defer activation so the
680 # trigger line is classified normally this iteration.
681 if ($mode eq 'SH') {
682 my @hd = BATsh::SH::_hd_detect($raw);
683 if (@hd) {
684 $pending_hd_delim = $hd[2];
685 $pending_hd_dash = $hd[1];
686 }
687 }
688  
689 if ($mode eq 'EMPTY' || $mode eq 'COMMENT') {
690 # A comment carries no execution effect, so it must never be handed
691 # to an interpreter verbatim. A CMD-style comment (":: ..." or
692 # "REM ...") carried into an SH section would be dispatched to the
693 # external shell (SH treats only "#" as a comment), and any "( )" or
694 # other shell metacharacter in the comment then makes /bin/sh fail
695 # with a syntax error. The reverse ("# ..." into CMD) is likewise
696 # not a CMD comment. Routing it as a BLANK line is skipped
697 # identically by both interpreters and in every nesting depth, and
698 # avoids the real cmd.exe quirk of "::" inside a "( )" block.
699 push @pending, '' if $cur_mode ne '';
700 next;
701 }
702  
703 if ($cur_mode eq '') {
704 $cur_mode = $mode; $depth = 0;
705 push @pending, $line;
706 $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
707 }
708 elsif ($mode eq $cur_mode) {
709 push @pending, $line;
710 $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
711 $depth = 0 if $depth < 0;
712 }
713 else {
714 if ($depth > 0) {
715 push @pending, $line;
716 $depth += ($cur_mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
717 $depth = 0 if $depth < 0;
718 }
719 else {
720 _flush_section($cur_mode, @pending) if @pending;
721 @pending = ($line); $cur_mode = $mode; $depth = 0;
722 $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
723 }
724 }
725 }
726 _flush_section($cur_mode, @pending) if @pending;
727 }
728  
729 sub _flush_section {
730 my ($mode, @lines) = @_;
731 return unless @lines;
732 if ($mode eq 'CMD') { _exec_cmd_section(@lines) }
733 else { _exec_sh_section(@lines) }
734 }
735  
736 ###############################################################################
737 # REPL
738 ###############################################################################
739 sub repl {
740 my ($class_or_self) = @_;
741 _ensure_env_init();
742 $_SCRIPT_EXIT = undef;
743 BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
744 print "BATsh $VERSION - Bilingual Shell\n";
745 print "Uppercase => CMD mode, lowercase => SH mode. EXIT/exit to quit.\n\n";
746  
747 my (@buf, $depth, $cur_mode) = ((), 0, '');
748 my ($hd_delim, $hd_dash, $pending_hd_delim, $pending_hd_dash)
749 = (undef, 0, undef, 0);
750 while (1) {
751 print $depth > 0 || defined($hd_delim) ? ' +> ' : 'BATsh> ';
752 my $line = <STDIN>;
753 last unless defined $line;
754 chomp $line;
755  
756 # Guard-transform DBCS input (auto-activates on first DBCS line)
757 BATsh::MB::activate_for($line);
758 $line = BATsh::MB::enc($line);
759  
760 # Promote pending here-document (trigger already buffered)
761 if (defined $pending_hd_delim) {
762 $hd_delim = $pending_hd_delim; $hd_dash = $pending_hd_dash;
763 $pending_hd_delim = undef;
764 }
765 # Collecting here-document body: buffer verbatim, do not flush/classify
766 if (defined $hd_delim) {
767 push @buf, $line;
768 my $probe = $line;
769 $probe =~ s/\A\t+// if $hd_dash;
770 $hd_delim = undef if $probe eq $hd_delim;
771 if (!defined($hd_delim) && $depth == 0) {
772 _flush_section($cur_mode, @buf);
773 @buf = (); $cur_mode = ''; $depth = 0;
774 last if defined $_SCRIPT_EXIT; # "exit N" ends the REPL
775 }
776 next;
777 }
778  
779 if ($line =~ /\A\s*(?:EXIT|exit)\s*\z/) { print "Bye.\n"; last }
780 next if $depth == 0 && $line =~ /\A\s*\z/;
781 push @buf, $line;
782 # (undef, ...) in a my list is a Perl 5.10 spelling; the list is
783 # taken as a whole and indexed instead, for 5.005_03.
784 my @parsed = _parse_line($line);
785 my $first = $parsed[2];
786 $cur_mode = classify_token($first) if $depth == 0 && $cur_mode eq '';
787 # Detect here-document opener (SH only); defer activation one line
788 if ($cur_mode eq 'SH') {
789 my @hd = BATsh::SH::_hd_detect($line);
790 if (@hd) { $pending_hd_delim = $hd[2]; $pending_hd_dash = $hd[1] }
791 }
792 $depth += ($cur_mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
793 $depth = 0 if $depth < 0;
794 if ($depth == 0 && !defined($pending_hd_delim)) {
795 _flush_section($cur_mode, @buf);
796 @buf = (); $cur_mode = ''; $depth = 0;
797 last if defined $_SCRIPT_EXIT; # "exit N" / "EXIT N" ends the REPL
798 }
799 }
800 return _final_status();
801 }
802  
803 ###############################################################################
804 # Accessors
805 ###############################################################################
806 sub version { return $VERSION }
807 sub sh_available { return 1 } # always: built-in SH interpreter
808  
809 ###############################################################################
810 # main -- command-line entry point (used by bin/batsh.pl and the modulino).
811 # Returns the process exit code.
812 ###############################################################################
813 sub main {
814 my ($class_or_self, @argv) = @_;
815 BATsh::Env::init();
816 # --encoding=ENC / --encoding ENC : cp932 sjis gbk uhc big5 utf8 none auto
817 while (@argv && $argv[0] =~ /\A--encoding(?:=(.*))?\z/) {
818 my $e = $1;
819 shift @argv;
820 $e = shift @argv if !defined $e && @argv;
821 BATsh->set_encoding($e) if defined $e;
822 }
823 if (@argv && ($argv[0] eq '--version' || $argv[0] eq '-v')) {
824 print "BATsh $VERSION\n";
825 return 0;
826 }
827 if (@argv && ($argv[0] eq '--help' || $argv[0] eq '-h')) {
828 print <<"END_OF_USAGE";
829 usage: batsh [--encoding=ENC] script.batsh [args...]
830 batsh [--encoding=ENC] - (read the script from STDIN)
831 batsh [--encoding=ENC] -e 'source' (run inline source)
832 batsh (interactive REPL)
833 batsh --version | --help
834  
835 ENC: cp932 sjis gbk uhc big5 utf8 none auto (default: auto)
836 The process exit code is the script's exit code (exit N / EXIT [/B] N,
837 or the status of the last command).
838 END_OF_USAGE
839 return 0;
840 }
841 if (@argv == 0) { return BATsh->repl() }
842 if ($argv[0] eq '-e') {
843 shift @argv;
844 return BATsh->run_string(join("\n", @argv));
845 }
846 if ($argv[0] eq '-') {
847 shift @argv;
848 my @lines = <STDIN>;
849 return BATsh->run_string(join('', @lines),
850 script_name => '-', args => [@argv]);
851 }
852 my $f = shift @argv;
853 return BATsh->run($f, args => [@argv]);
854 }
855  
856 ###############################################################################
857 # Run as script
858 ###############################################################################
859 unless (caller) {
860 exit(BATsh->main(@ARGV));
861 }
862  
863 1;
864  
865 __END__