blib/lib/Zuzu/CLI.pm untested

filter: Statementstmt 0.0% 0 / 387 Branchbran 0.0% 0 / 166 Conditioncond 0.0% 0 / 72 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 682 CC 84 SCAR 42.3
CC
84
Cov
0%
run
182.0
_repl_structural_depth
156.0
_run_repl
156.0
CRAP 69.0
1 package Zuzu::CLI;
2  
3 use utf8;
4 use strict;
5 use warnings;
6  
7 our $VERSION = '0.007001';
8  
9 use Scalar::Util qw( blessed );
10 use Getopt::Long qw(
11 Configure
12 GetOptionsFromArray
13 );
14  
15 use Zuzu;
16 use Zuzu::Lexer;
17 use Zuzu::Parser;
18 use Zuzu::Parser::_Impl;
19 use Zuzu::Runtime;
20 use Zuzu::Util;
21 use Zuzu::Value::Array;
22  
23 sub run {
24 my ( @argv ) = @_;
25 @argv = @ARGV if ! @argv;
26  
27 binmode(*STDOUT, ':utf8');
28 binmode(*STDERR, ':utf8');
29  
30 my ( $options, $args, $usage_error ) = _parse_options( \@argv );
31 if ( defined $usage_error ) {
32 _print_usage($usage_error);
33 return 2;
34 }
35  
36 my ( $deny, $deny_module_list, $preload, $disabled_visitors, $value_error )
37 = _normalize_option_lists($options);
38 if ( defined $value_error ) {
39 _print_usage($value_error);
40 return 2;
41 }
42 $options->{disabled_visitors} = $disabled_visitors;
43  
44 Zuzu::Runtime->clear_persistent_ast_cache if $options->{clear_cache};
45  
46 if ( $options->{show_version} or $options->{show_version_verbose} ) {
47 _print_version( $options, $deny, $deny_module_list );
48 return 0;
49 }
50  
51 my ( $script, $source, $script_error ) = _prepare_source(
52 $options,
53 $args,
54 $preload,
55 );
56 if ( defined $script_error ) {
57 _print_usage($script_error);
58 return 2;
59 }
60  
61 $Zuzu::Runtime::DEBUG_LEVEL = $options->{debug_level};
62 $ENV{ZUZU_DEBUG_LEVEL} = $options->{debug_level};
63  
64 my $runtime = Zuzu::Runtime->new(
65 lib => [ @{ $options->{include_dirs} }, @Zuzu::Runtime::DEFAULT_LIB ],
66 deny => $deny,
67 deny_modules => $deny_module_list,
68 persistent_ast_cache => !$options->{no_cache},
69 disabled_visitors => $disabled_visitors,
70 );
71  
72 if ( $options->{repl_mode} ) {
73 _run_repl($runtime);
74 return 0;
75 }
76  
77 my $parser = Zuzu::Parser->new( disabled_visitors => $disabled_visitors );
78 my $ok = eval {
79 my $ast = $parser->parse( $source, $script );
80 $runtime->evaluate($ast);
81  
82 if ( $runtime->has_function('__main__') ) {
83 my $call_args = Zuzu::Value::Array->new( items => [ @$args ] );
84 if ( $runtime->function_is_async('__main__') ) {
85 $runtime->call( '__main__', $call_args );
86 }
87 else {
88 $runtime->call_unawaited( '__main__', $call_args );
89 }
90 }
91 1;
92 };
93 if ( ! $ok ) {
94 my $err = $@;
95 if ( ref($err) eq 'HASH' and $err->{_zuzu_throw} ) {
96 my $value = defined $err->{value} ? $err->{value} : '';
97 my $text = _render_thrown_value( $runtime, $value );
98 print STDERR "$text\n";
99 $runtime->finish;
100 return 255;
101 }
102 $runtime->finish;
103 die $err;
104 }
105  
106 $runtime->finish;
107  
108 return 0;
109 }
110  
111 sub _parse_options {
112 my ( $argv ) = @_;
113  
114 my $options = {
115 debug_level => 0,
116 include_dirs => [],
117 deny_capabilities => [],
118 deny_modules => [],
119 inline_snippets => [],
120 preload_modules => [],
121 no_visitors => [],
122 no_cache => 0,
123 clear_cache => 0,
124 repl_mode => 0,
125 show_version => 0,
126 show_version_verbose => 0,
127 };
128 my $debug_opt;
129  
130 Configure(
131 'no_ignore_case',
132 'bundling',
133 'require_order',
134 );
135 my $ok = GetOptionsFromArray(
136 $argv,
137 'd:i' => \$debug_opt,
138 'I=s@' => $options->{include_dirs},
139 'deny=s@' => $options->{deny_capabilities},
140 'denymodule=s@' => $options->{deny_modules},
141 'no-visitor=s@' => $options->{no_visitors},
142 'e=s@' => $options->{inline_snippets},
143 'M=s@' => $options->{preload_modules},
144 'no-cache' => \$options->{no_cache},
145 'clear-cache' => \$options->{clear_cache},
146 'R|repl' => \$options->{repl_mode},
147 'h|help' => \$options->{show_help},
148 'v' => \$options->{show_version},
149 'V' => \$options->{show_version_verbose},
150 );
151 if ( ! $ok ) {
152 return ( undef, undef, undef );
153 }
154  
155 if ( $options->{show_help} ) {
156 return ( undef, undef, '' );
157 }
158  
159 if ( defined $debug_opt ) {
160 $debug_opt = 1 if $debug_opt eq '';
161 return ( undef, undef, 'Debug level must be a non-negative integer' )
162 if $debug_opt !~ /\A(?:0|[1-9][0-9]*)\z/;
163 $options->{debug_level} = 0 + $debug_opt;
164 }
165  
166 return ( $options, $argv, undef );
167 }
168  
169 sub _normalize_option_lists {
170 my ( $options ) = @_;
171  
172 my @deny = _flatten_trimmed_csv( @{ $options->{deny_capabilities} } );
173 my @deny_module_list = _flatten_trimmed_csv( @{ $options->{deny_modules} } );
174 my @preload = _flatten_trimmed_csv( @{ $options->{preload_modules} } );
175 my @disabled_visitors = _flatten_trimmed_csv( @{ $options->{no_visitors} } );
176  
177 for my $entry ( @deny, @deny_module_list, @preload, @disabled_visitors ) {
178 if ( $entry =~ /\A\s*\z/ ) {
179 return ( undef, undef, undef, undef, 'Option values may not contain whitespace only' );
180 }
181 }
182  
183 my @known_visitors;
184 eval {
185 @known_visitors = Zuzu::Parser->normalize_disabled_visitors(
186 @disabled_visitors,
187 );
188 1;
189 } or do {
190 my $error = $@;
191 chomp $error;
192 $error =~ s/ at \S+ line \d+\.?\z//;
193 return ( undef, undef, undef, undef, $error );
194 };
195  
196 return ( \@deny, \@deny_module_list, \@preload, \@known_visitors, undef );
197 }
198  
199 sub _flatten_trimmed_csv {
200 my ( @raw ) = @_;
201  
202 my @values = map {
203 s/^\s+//r =~ s/\s+$//r
204 } grep {
205 defined $_ and $_ ne ''
206 } map {
207 split /,/
208 } @raw;
209  
210 return @values;
211 }
212  
213 sub _prepare_source {
214 my ( $options, $args, $preload ) = @_;
215  
216 if ( $options->{repl_mode} ) {
217 if ( @{ $options->{inline_snippets} } ) {
218 return ( undef, undef, '-R/--repl cannot be combined with -e snippets' );
219 }
220 if ( @$args ) {
221 return ( undef, undef, '-R/--repl does not accept a script path or argv values' );
222 }
223 return ( undef, undef, undef );
224 }
225  
226 if ( @{ $options->{inline_snippets} } ) {
227 my @prelude = map {
228 "from $_ import *;"
229 } @$preload;
230 my $source = join "\n", @prelude, @{ $options->{inline_snippets} };
231 return ( '(command line)', $source, undef );
232 }
233  
234 my $script = shift @$args;
235 if ( ! defined $script ) {
236 return ( undef, undef, '' );
237 }
238  
239 open my $fh, '<:encoding(UTF-8)', $script
240 or die "Could not open '$script': $!\n";
241 my $source = do { local $/; <$fh> };
242 close $fh;
243  
244 if ( @$preload ) {
245 my @prelude = map {
246 "from $_ import *;"
247 } @$preload;
248 $source = join "\n", @prelude, $source;
249 }
250  
251 return ( $script, $source, undef );
252 }
253  
254 sub _print_usage {
255 my ( $message ) = @_;
256  
257 if ( defined $message and $message ne '' ) {
258 print STDERR $message, "\n";
259 }
260 print STDERR "Usage: zuzu.pl [options] path/to/script.zzs [arg ...]\n";
261 print STDERR " zuzu.pl [options] -e 'code' [arg ...]\n";
262 print STDERR "Options:\n";
263 print STDERR " -d[=N] set debug level (default: 1 if omitted)\n";
264 print STDERR " -I/path/to/lib add module include directory\n";
265 print STDERR " --deny=CAP deny runtime capability (repeatable)\n";
266 print STDERR " --denymodule=MODULE deny a specific module (repeatable)\n";
267 print STDERR " --no-visitor=NAME disable an AST visitor (repeatable)\n";
268 print STDERR " -e 'code' evaluate inline code (repeatable)\n";
269 print STDERR " -Mmodule preload module with wildcard import\n";
270 print STDERR " --no-cache disable the persistent module AST cache\n";
271 print STDERR " --clear-cache clear the persistent module AST cache before running\n";
272 print STDERR " -R, --repl start interactive REPL shell\n";
273 print STDERR " -h, --help show this help\n";
274 print STDERR " -v print version\n";
275 print STDERR " -V print verbose version details\n";
276  
277 return;
278 }
279  
280 sub _print_version {
281 my ( $options, $deny, $deny_module_list ) = @_;
282  
283 my $runtime = Zuzu::Runtime->new(
284 lib => [ @{ $options->{include_dirs} }, @Zuzu::Runtime::DEFAULT_LIB ],
285 deny => $deny,
286 deny_modules => $deny_module_list,
287 persistent_ast_cache => !$options->{no_cache},
288 disabled_visitors => $options->{disabled_visitors} // [],
289 );
290  
291 print "zuzu.pl version $Zuzu::VERSION\n";
292 if ( $options->{show_version_verbose} ) {
293 print "\n";
294 print "lib search paths:\n";
295 for my $path ( @{ $runtime->lib } ) {
296 print " $path\n";
297 }
298 print "\n";
299 print "builtin modules:\n";
300 for my $module ( sort keys %{ $runtime->builtin } ) {
301 print " $module\n";
302 }
303 }
304  
305 return;
306 }
307  
308 sub _repl_print_prompt {
309 my ( $continuation ) = @_;
310  
311 print STDOUT _repl_prompt_coloured($continuation);
312  
313 return;
314 }
315  
316 sub _repl_prompt_label {
317 my ( $continuation ) = @_;
318  
319 return $continuation
320 ? 'zuzu (...)> '
321 : 'zuzu (^_^)> '
322 if ! $ENV{ZUZU_EMOJI};
323  
324 return $continuation
325 ? 'zuzu 🦝 ⏳ > '
326 : 'zuzu 🦝 💤 > ';
327 }
328  
329 sub _repl_prompt_coloured {
330 my ( $continuation ) = @_;
331  
332 my $colour = $continuation ? "\e[1;35m" : "\e[1;36m";
333 return $colour . _repl_prompt_label($continuation) . "\e[0m";
334 }
335  
336 sub _repl_print_output {
337 my ( $message ) = @_;
338  
339 print STDOUT "\e[1;32m", $message, "\e[0m\n";
340  
341 return;
342 }
343  
344 sub _repl_print_error {
345 my ( $message ) = @_;
346  
347 my $colour = $message =~ /\bwarn(?:ing)?\b/i
348 ? "\e[1;33m"
349 : "\e[1;31m";
350 print STDERR $colour, $message, "\e[0m\n";
351  
352 return;
353 }
354  
355 sub _repl_render_value {
356 my ( $runtime, $value ) = @_;
357  
358 return 'Null' if ! defined $value;
359 return "$value" if ! ref($value);
360 if ( blessed($value) and $value->isa('Zuzu::Value::Boolean') ) {
361 return "$value";
362 }
363  
364 return $runtime->_type_name($value);
365 }
366  
367 sub _is_probably_incomplete_parse_error {
368 my ( $error, $source ) = @_;
369  
370 return 0 if ! blessed($error);
371 return 0 if ! $error->isa('Zuzu::Error::Compile');
372 return 1 if ( $error->message // '' ) =~ /\AUnterminated\b/;
373  
374 my $line_count = () = $source =~ /\n/g;
375 $line_count++;
376 return 0 if ! defined $error->line;
377 return 0 if $error->line < $line_count;
378  
379 return 1 if ( $error->message // '' ) =~ /\AExpected\b/;
380  
381 return 0;
382 }
383  
384 sub _try_parse_with_optional_semicolon {
385 my ( $runtime, $source ) = @_;
386  
387 my $parse_ok = eval {
388 _parse_repl_source( $runtime, $source );
389 1;
390 };
391 if ( $parse_ok ) {
392 return ( 1, undef, $source );
393 }
394 my $first_error = $@;
395  
396 my $trimmed = $source;
397 $trimmed =~ s/\s+\z//;
398 if (
399 $trimmed !~ /[;{}]\z/
400 and $trimmed =~ /\S/
401 ) {
402 my $with_semicolon = $trimmed . ';';
403 my $semicolon_ok = eval {
404 _parse_repl_source( $runtime, $with_semicolon );
405 1;
406 };
407 if ( $semicolon_ok ) {
408 return ( 1, undef, $with_semicolon );
409 }
410 }
411  
412 return ( 0, $first_error, $source );
413 }
414  
415 sub _repl_structural_depth {
416 my ( $source ) = @_;
417  
418 my $depth = 0;
419 my $in_single = 0;
420 my $in_double = 0;
421 my $escaped = 0;
422  
423 for my $ch ( split //, $source ) {
424 if ( $escaped ) {
425 $escaped = 0;
426 next;
427 }
428 if ( $in_single ) {
429 if ( $ch eq '\\' ) {
430 $escaped = 1;
431 next;
432 }
433 if ( $ch eq "'" ) {
434 $in_single = 0;
435 }
436 next;
437 }
438 if ( $in_double ) {
439 if ( $ch eq '\\' ) {
440 $escaped = 1;
441 next;
442 }
443 if ( $ch eq '"' ) {
444 $in_double = 0;
445 }
446 next;
447 }
448 if ( $ch eq "'" ) {
449 $in_single = 1;
450 next;
451 }
452 if ( $ch eq '"' ) {
453 $in_double = 1;
454 next;
455 }
456 if ( $ch eq '{' or $ch eq '(' or $ch eq '[' ) {
457 $depth++;
458 next;
459 }
460 if ( $ch eq '}' or $ch eq ')' or $ch eq ']' ) {
461 $depth--;
462 }
463 }
464  
465 return $depth;
466 }
467  
468 sub _repl_prelude_for_runtime {
469 my ( $runtime ) = @_;
470  
471 my @decls;
472 for my $name ( sort keys %{ $runtime->{_global}{slots} // {} } ) {
473 next if $runtime->{_builtin_global_names}{$name};
474 next if $name =~ /\A__/;
475 next if $name !~ /\A[_A-Za-z][_A-Za-z0-9]*\z/;
476 next if Zuzu::Util::is_keyword($name);
477 push @decls, "let $name := null;";
478 }
479  
480 return @decls;
481 }
482  
483 sub _repl_init_line_editor {
484 return if ! -t STDIN;
485 return if ! -t STDOUT;
486  
487 my $ok = eval {
488 require Term::ReadLine;
489 1;
490 };
491 return if ! $ok;
492  
493 my $term = Term::ReadLine->new('zuzu');
494 return if ! $term;
495 return $term;
496 }
497  
498 sub _repl_read_line {
499 my ( $editor, $continuation, $history_state ) = @_;
500  
501 if ($editor) {
502 my $line = $editor->readline( _repl_prompt_label($continuation) );
503 return undef if ! defined $line;
504  
505 if ( $line =~ /\S/ ) {
506 my $last = $history_state->{last_entry};
507 if ( ! defined $last or $last ne $line ) {
508 $editor->addhistory($line);
509 $history_state->{last_entry} = $line;
510 }
511 }
512 return $line;
513 }
514  
515 _repl_print_prompt($continuation);
516 my $line = readline STDIN;
517 return undef if ! defined $line;
518 chomp $line;
519 return $line;
520 }
521  
522 sub _parse_repl_source {
523 my ( $runtime, $source ) = @_;
524  
525 my @prelude = _repl_prelude_for_runtime($runtime);
526 my $combined = @prelude
527 ? join( "\n", @prelude, $source )
528 : $source;
529  
530 my $lexer = Zuzu::Lexer->new(
531 src => $combined,
532 filename => '<repl>',
533 );
534 my $impl = Zuzu::Parser::_Impl->new(
535 lexer => $lexer,
536 filename => '<repl>',
537 );
538  
539 my $ast = $impl->parse_program;
540 if ( @prelude ) {
541 my @stmts = @{ $ast->statements };
542 splice @stmts, 0, scalar @prelude;
543 $ast->statements( \@stmts );
544 }
545  
546 return $ast;
547 }
548  
549 sub _run_repl {
550 my ( $runtime ) = @_;
551  
552 my @buffer;
553 my $expecting_more = 0;
554 my $line_editor = _repl_init_line_editor();
555 my %history_state;
556  
557 while ( 1 ) {
558 my $line = _repl_read_line(
559 $line_editor,
560 $expecting_more,
561 \%history_state,
562 );
563 last if ! defined $line;
564 next if ! @buffer and $line =~ /\A\s*\z/;
565  
566 if (
567 $expecting_more
568 and @buffer
569 and $line =~ /\A\s*;\s*\z/
570 ) {
571 my $source = join "\n", @buffer;
572 my ( $ok, $err, $effective_source )
573 = _try_parse_with_optional_semicolon( $runtime, $source );
574 if ( ! $ok ) {
575 _repl_print_error("$err");
576 @buffer = ();
577 $expecting_more = 0;
578 next;
579 }
580  
581 eval {
582 my $ast = _parse_repl_source( $runtime, $effective_source );
583 my $result = $runtime->evaluate($ast);
584 _repl_print_output( _repl_render_value( $runtime, $result ) );
585 1;
586 } or do {
587 my $err_eval = $@;
588 if ( ref($err_eval) eq 'HASH' and $err_eval->{_zuzu_throw} ) {
589 my $value = defined $err_eval->{value} ? $err_eval->{value} : '';
590 _repl_print_error( _render_thrown_value( $runtime, $value ) );
591 }
592 else {
593 _repl_print_error("$err_eval");
594 }
595 };
596  
597 @buffer = ();
598 $expecting_more = 0;
599 next;
600 }
601  
602 push @buffer, $line;
603 my $source = join "\n", @buffer;
604 if ( _repl_structural_depth($source) > 0 ) {
605 $expecting_more = 1;
606 next;
607 }
608 my ( $ok, $err, $effective_source )
609 = _try_parse_with_optional_semicolon( $runtime, $source );
610 if ( ! $ok ) {
611 if ( _is_probably_incomplete_parse_error( $err, $source ) ) {
612 $expecting_more = 1;
613 next;
614 }
615  
616 _repl_print_error("$err");
617 @buffer = ();
618 $expecting_more = 0;
619 next;
620 }
621  
622 eval {
623 my $ast = _parse_repl_source( $runtime, $effective_source );
624 my $result = $runtime->evaluate($ast);
625 _repl_print_output( _repl_render_value( $runtime, $result ) );
626 1;
627 } or do {
628 my $err_eval = $@;
629 if ( ref($err_eval) eq 'HASH' and $err_eval->{_zuzu_throw} ) {
630 my $value = defined $err_eval->{value} ? $err_eval->{value} : '';
631 _repl_print_error( _render_thrown_value( $runtime, $value ) );
632 }
633 else {
634 _repl_print_error("$err_eval");
635 }
636 };
637  
638 @buffer = ();
639 $expecting_more = 0;
640 }
641  
642 print STDOUT "\n";
643 return;
644 }
645  
646 sub _render_thrown_value {
647 my ( $runtime, $value ) = @_;
648  
649 my $text = $runtime->_to_String( $value );
650 return $text if not blessed($value);
651 return $text if not $value->isa( 'Zuzu::Value::Object' );
652  
653 my $slots = $value->slots // {};
654 my $file = $slots->{file};
655 my $line = $slots->{line};
656 return $text if not defined $file or not defined $line;
657  
658 return "$text at $file, line $line";
659 }
660  
661 1;
662  
663 =pod
664  
665 =head1 COPYRIGHT AND LICENCE
666  
667 B<< Zuzu::CLI >> is copyright Toby Inkster.
668  
669 It is free software; you may redistribute it and/or modify it under
670 the terms of either the Artistic License 1.0 or the GNU General Public
671 License version 2.
672  
673 =cut