This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #45133] -0.0 has variable Boolean value
[perl5.git] / dist / Locale-Maketext / lib / Locale / Maketext.pm
CommitLineData
e9c9ffca 1
9378c581
JH
2package Locale::Maketext;
3use strict;
4use vars qw( @ISA $VERSION $MATCH_SUPERS $USING_LANGUAGE_TAGS
f666394a 5$USE_LITERALS $MATCH_SUPERS_TIGHTLY);
9378c581 6use Carp ();
ed897e29
TR
7use I18N::LangTags ();
8use I18N::LangTags::Detect ();
9378c581
JH
9
10#--------------------------------------------------------------------------
11
12BEGIN { unless(defined &DEBUG) { *DEBUG = sub () {0} } }
f666394a 13# define the constant 'DEBUG' at compile-time
9378c581 14
87d86da5
TR
15# turn on utf8 if we have it (this is what GutsLoader.pm used to do essentially )
16# use if (exists $INC{'utf8.pm'} || eval 'use utf8'), 'utf8';
17BEGIN {
18
19 # if we have it || we can load it
20 if ( exists $INC{'utf8.pm'} || eval { local $SIG{'__DIE__'};require utf8; } ) {
21 utf8->import();
22 DEBUG and warn " utf8 on for _compile()\n";
23 }
24 else {
25 DEBUG and warn " utf8 not available for _compile() ($INC{'utf8.pm'})\n$@\n";
26 }
27}
28
29
9607a449 30$VERSION = '1.16';
9378c581
JH
31@ISA = ();
32
33$MATCH_SUPERS = 1;
14be35aa
AMS
34$MATCH_SUPERS_TIGHTLY = 1;
35$USING_LANGUAGE_TAGS = 1;
f666394a
RGS
36# Turning this off is somewhat of a security risk in that little or no
37# checking will be done on the legality of tokens passed to the
38# eval("use $module_name") in _try_use. If you turn this off, you have
39# to do your own taint checking.
9378c581
JH
40
41$USE_LITERALS = 1 unless defined $USE_LITERALS;
f666394a 42# a hint for compiling bracket-notation things.
9378c581
JH
43
44my %isa_scan = ();
45
46###########################################################################
47
48sub quant {
f666394a 49 my($handle, $num, @forms) = @_;
9378c581 50
f666394a
RGS
51 return $num if @forms == 0; # what should this mean?
52 return $forms[2] if @forms > 2 and $num == 0; # special zeroth case
9378c581 53
f666394a
RGS
54 # Normal case:
55 # Note that the formatting of $num is preserved.
56 return( $handle->numf($num) . ' ' . $handle->numerate($num, @forms) );
57 # Most human languages put the number phrase before the qualified phrase.
9378c581
JH
58}
59
60
61sub numerate {
f666394a
RGS
62 # return this lexical item in a form appropriate to this number
63 my($handle, $num, @forms) = @_;
64 my $s = ($num == 1);
65
66 return '' unless @forms;
67 if(@forms == 1) { # only the headword form specified
68 return $s ? $forms[0] : ($forms[0] . 's'); # very cheap hack.
69 }
70 else { # sing and plural were specified
71 return $s ? $forms[0] : $forms[1];
72 }
9378c581
JH
73}
74
75#--------------------------------------------------------------------------
76
77sub numf {
f666394a
RGS
78 my($handle, $num) = @_[0,1];
79 if($num < 10_000_000_000 and $num > -10_000_000_000 and $num == int($num)) {
80 $num += 0; # Just use normal integer stringification.
81 # Specifically, don't let %G turn ten million into 1E+007
82 }
83 else {
84 $num = CORE::sprintf('%G', $num);
85 # "CORE::" is there to avoid confusion with the above sub sprintf.
86 }
87 while( $num =~ s/^([-+]?\d+)(\d{3})/$1,$2/s ) {1} # right from perlfaq5
88 # The initial \d+ gobbles as many digits as it can, and then we
89 # backtrack so it un-eats the rightmost three, and then we
90 # insert the comma there.
91
92 $num =~ tr<.,><,.> if ref($handle) and $handle->{'numf_comma'};
93 # This is just a lame hack instead of using Number::Format
94 return $num;
9378c581
JH
95}
96
97sub sprintf {
f666394a
RGS
98 no integer;
99 my($handle, $format, @params) = @_;
100 return CORE::sprintf($format, @params);
9378c581
JH
101 # "CORE::" is there to avoid confusion with myself!
102}
103
104#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
105
106use integer; # vroom vroom... applies to the whole rest of the module
107
108sub language_tag {
f666394a
RGS
109 my $it = ref($_[0]) || $_[0];
110 return undef unless $it =~ m/([^':]+)(?:::)?$/s;
111 $it = lc($1);
112 $it =~ tr<_><->;
113 return $it;
9378c581
JH
114}
115
116sub encoding {
f666394a
RGS
117 my $it = $_[0];
118 return(
119 (ref($it) && $it->{'encoding'})
120 || 'iso-8859-1' # Latin-1
121 );
122}
9378c581
JH
123
124#--------------------------------------------------------------------------
125
126sub fallback_languages { return('i-default', 'en', 'en-US') }
127
128sub fallback_language_classes { return () }
129
130#--------------------------------------------------------------------------
131
132sub fail_with { # an actual attribute method!
f666394a
RGS
133 my($handle, @params) = @_;
134 return unless ref($handle);
135 $handle->{'fail'} = $params[0] if @params;
136 return $handle->{'fail'};
9378c581
JH
137}
138
139#--------------------------------------------------------------------------
140
141sub failure_handler_auto {
f666394a
RGS
142 # Meant to be used like:
143 # $handle->fail_with('failure_handler_auto')
144
145 my $handle = shift;
146 my $phrase = shift;
147
148 $handle->{'failure_lex'} ||= {};
149 my $lex = $handle->{'failure_lex'};
150
f7d5028f 151 my $value ||= ($lex->{$phrase} ||= $handle->_compile($phrase));
f666394a
RGS
152
153 # Dumbly copied from sub maketext:
154 return ${$value} if ref($value) eq 'SCALAR';
155 return $value if ref($value) ne 'CODE';
156 {
157 local $SIG{'__DIE__'};
158 eval { $value = &$value($handle, @_) };
159 }
160 # If we make it here, there was an exception thrown in the
161 # call to $value, and so scream:
162 if($@) {
163 my $err = $@;
164 # pretty up the error message
165 $err =~ s{\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?}
166 {\n in bracket code [compiled line $1],}s;
167 #$err =~ s/\n?$/\n/s;
168 Carp::croak "Error in maketexting \"$phrase\":\n$err as used";
169 # Rather unexpected, but suppose that the sub tried calling
170 # a method that didn't exist.
171 }
172 else {
173 return $value;
174 }
9378c581
JH
175}
176
177#==========================================================================
178
179sub new {
f666394a
RGS
180 # Nothing fancy!
181 my $class = ref($_[0]) || $_[0];
182 my $handle = bless {}, $class;
183 $handle->init;
184 return $handle;
9378c581
JH
185}
186
187sub init { return } # no-op
188
189###########################################################################
190
191sub maketext {
f666394a
RGS
192 # Remember, this can fail. Failure is controllable many ways.
193 Carp::croak 'maketext requires at least one parameter' unless @_ > 1;
194
195 my($handle, $phrase) = splice(@_,0,2);
196 Carp::confess('No handle/phrase') unless (defined($handle) && defined($phrase));
197
198
199 # Don't interefere with $@ in case that's being interpolated into the msg.
200 local $@;
201
202 # Look up the value:
203
204 my $value;
ace47d68
TR
205 if (exists $handle->{'_external_lex_cache'}{$phrase}) {
206 DEBUG and warn "* Using external lex cache version of \"$phrase\"\n";
207 $value = $handle->{'_external_lex_cache'}{$phrase};
208 }
209 else {
210 foreach my $h_r (
211 @{ $isa_scan{ref($handle) || $handle} || $handle->_lex_refs }
212 ) {
213 DEBUG and warn "* Looking up \"$phrase\" in $h_r\n";
214 if(exists $h_r->{$phrase}) {
215 DEBUG and warn " Found \"$phrase\" in $h_r\n";
216 unless(ref($value = $h_r->{$phrase})) {
217 # Nonref means it's not yet compiled. Compile and replace.
218 if ($handle->{'use_external_lex_cache'}) {
219 $value = $handle->{'_external_lex_cache'}{$phrase} = $handle->_compile($value);
220 }
221 else {
222 $value = $h_r->{$phrase} = $handle->_compile($value);
223 }
224 }
225 last;
f666394a 226 }
ace47d68
TR
227 # extending packages need to be able to localize _AUTO and if readonly can't "local $h_r->{'_AUTO'} = 1;"
228 # but they can "local $handle->{'_external_lex_cache'}{'_AUTO'} = 1;"
229 elsif($phrase !~ m/^_/s and ($handle->{'use_external_lex_cache'} ? ( exists $handle->{'_external_lex_cache'}{'_AUTO'} ? $handle->{'_external_lex_cache'}{'_AUTO'} : $h_r->{'_AUTO'} ) : $h_r->{'_AUTO'})) {
230 # it's an auto lex, and this is an autoable key!
231 DEBUG and warn " Automaking \"$phrase\" into $h_r\n";
232 if ($handle->{'use_external_lex_cache'}) {
233 $value = $handle->{'_external_lex_cache'}{$phrase} = $handle->_compile($phrase);
234 }
235 else {
236 $value = $h_r->{$phrase} = $handle->_compile($phrase);
237 }
238 last;
239 }
240 DEBUG>1 and print " Not found in $h_r, nor automakable\n";
241 # else keep looking
f666394a 242 }
9378c581 243 }
f666394a
RGS
244
245 unless(defined($value)) {
ad56049d 246 DEBUG and warn "! Lookup of \"$phrase\" in/under ", ref($handle) || $handle, " fails.\n";
f666394a 247 if(ref($handle) and $handle->{'fail'}) {
ad56049d 248 DEBUG and warn "WARNING0: maketext fails looking for <$phrase>\n";
f666394a
RGS
249 my $fail;
250 if(ref($fail = $handle->{'fail'}) eq 'CODE') { # it's a sub reference
251 return &{$fail}($handle, $phrase, @_);
252 # If it ever returns, it should return a good value.
253 }
254 else { # It's a method name
255 return $handle->$fail($phrase, @_);
256 # If it ever returns, it should return a good value.
257 }
258 }
259 else {
260 # All we know how to do is this;
261 Carp::croak("maketext doesn't know how to say:\n$phrase\nas needed");
262 }
263 }
264
265 return $$value if ref($value) eq 'SCALAR';
266 return $value unless ref($value) eq 'CODE';
267
268 {
269 local $SIG{'__DIE__'};
270 eval { $value = &$value($handle, @_) };
271 }
272 # If we make it here, there was an exception thrown in the
273 # call to $value, and so scream:
274 if ($@) {
275 my $err = $@;
276 # pretty up the error message
277 $err =~ s{\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?}
278 {\n in bracket code [compiled line $1],}s;
279 #$err =~ s/\n?$/\n/s;
280 Carp::croak "Error in maketexting \"$phrase\":\n$err as used";
281 # Rather unexpected, but suppose that the sub tried calling
282 # a method that didn't exist.
283 }
284 else {
285 return $value;
9378c581 286 }
9378c581
JH
287}
288
289###########################################################################
290
291sub get_handle { # This is a constructor and, yes, it CAN FAIL.
f666394a
RGS
292 # Its class argument has to be the base class for the current
293 # application's l10n files.
294
295 my($base_class, @languages) = @_;
296 $base_class = ref($base_class) || $base_class;
297 # Complain if they use __PACKAGE__ as a project base class?
298
299 if( @languages ) {
ad56049d 300 DEBUG and warn 'Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
f666394a
RGS
301 if($USING_LANGUAGE_TAGS) { # An explicit language-list was given!
302 @languages =
303 map {; $_, I18N::LangTags::alternate_language_tags($_) }
304 # Catch alternation
305 map I18N::LangTags::locale2language_tag($_),
306 # If it's a lg tag, fine, pass thru (untainted)
307 # If it's a locale ID, try converting to a lg tag (untainted),
308 # otherwise nix it.
309 @languages;
ad56049d 310 DEBUG and warn 'Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
f666394a
RGS
311 }
312 }
313 else {
314 @languages = $base_class->_ambient_langprefs;
1189c245 315 }
f666394a
RGS
316
317 @languages = $base_class->_langtag_munging(@languages);
318
319 my %seen;
320 foreach my $module_name ( map { $base_class . '::' . $_ } @languages ) {
321 next unless length $module_name; # sanity
322 next if $seen{$module_name}++ # Already been here, and it was no-go
323 || !&_try_use($module_name); # Try to use() it, but can't it.
324 return($module_name->new); # Make it!
325 }
326
327 return undef; # Fail!
14be35aa
AMS
328}
329
330###########################################################################
331
332sub _langtag_munging {
f666394a
RGS
333 my($base_class, @languages) = @_;
334
335 # We have all these DEBUG statements because otherwise it's hard as hell
336 # to diagnose ifwhen something goes wrong.
337
ad56049d 338 DEBUG and warn 'Lgs1: ', map("<$_>", @languages), "\n";
f666394a
RGS
339
340 if($USING_LANGUAGE_TAGS) {
ad56049d 341 DEBUG and warn 'Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
f666394a
RGS
342 @languages = $base_class->_add_supers( @languages );
343
344 push @languages, I18N::LangTags::panic_languages(@languages);
ad56049d 345 DEBUG and warn "After adding panic languages:\n",
f666394a
RGS
346 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
347
348 push @languages, $base_class->fallback_languages;
349 # You are free to override fallback_languages to return empty-list!
ad56049d 350 DEBUG and warn 'Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
f666394a
RGS
351
352 @languages = # final bit of processing to turn them into classname things
353 map {
354 my $it = $_; # copy
355 $it =~ tr<-A-Z><_a-z>; # lc, and turn - to _
356 $it =~ tr<_a-z0-9><>cd; # remove all but a-z0-9_
357 $it;
358 } @languages
359 ;
ad56049d 360 DEBUG and warn "Nearing end of munging:\n",
f666394a
RGS
361 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
362 }
363 else {
ad56049d 364 DEBUG and warn "Bypassing language-tags.\n",
f666394a
RGS
365 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
366 }
367
ad56049d 368 DEBUG and warn "Before adding fallback classes:\n",
f666394a
RGS
369 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
370
371 push @languages, $base_class->fallback_language_classes;
372 # You are free to override that to return whatever.
373
ad56049d 374 DEBUG and warn "Finally:\n",
f666394a
RGS
375 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
376
377 return @languages;
14be35aa
AMS
378}
379
380###########################################################################
381
382sub _ambient_langprefs {
f666394a 383 return I18N::LangTags::Detect::detect();
14be35aa
AMS
384}
385
386###########################################################################
387
388sub _add_supers {
f666394a
RGS
389 my($base_class, @languages) = @_;
390
391 if (!$MATCH_SUPERS) {
392 # Nothing
ad56049d 393 DEBUG and warn "Bypassing any super-matching.\n",
f666394a
RGS
394 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
395
396 }
397 elsif( $MATCH_SUPERS_TIGHTLY ) {
ad56049d 398 DEBUG and warn "Before adding new supers tightly:\n",
f666394a
RGS
399 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
400 @languages = I18N::LangTags::implicate_supers( @languages );
ad56049d 401 DEBUG and warn "After adding new supers tightly:\n",
f666394a
RGS
402 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
403
404 }
405 else {
ad56049d 406 DEBUG and warn "Before adding supers to end:\n",
f666394a
RGS
407 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
408 @languages = I18N::LangTags::implicate_supers_strictly( @languages );
ad56049d 409 DEBUG and warn "After adding supers to end:\n",
f666394a
RGS
410 ' Lgs@', __LINE__, ': ', map("<$_>", @languages), "\n";
411 }
412
413 return @languages;
9378c581
JH
414}
415
416###########################################################################
417#
418# This is where most people should stop reading.
419#
420###########################################################################
421
9378c581 422my %tried = ();
f666394a 423# memoization of whether we've used this module, or found it unusable.
9378c581
JH
424
425sub _try_use { # Basically a wrapper around "require Modulename"
f666394a
RGS
426 # "Many men have tried..." "They tried and failed?" "They tried and died."
427 return $tried{$_[0]} if exists $tried{$_[0]}; # memoization
428
429 my $module = $_[0]; # ASSUME sane module name!
430 { no strict 'refs';
431 return($tried{$module} = 1)
9e20cf84 432 if %{$module . '::Lexicon'} or @{$module . '::ISA'};
f666394a
RGS
433 # weird case: we never use'd it, but there it is!
434 }
435
ad56049d 436 DEBUG and warn " About to use $module ...\n";
f666394a
RGS
437 {
438 local $SIG{'__DIE__'};
439 eval "require $module"; # used to be "use $module", but no point in that.
440 }
441 if($@) {
ad56049d 442 DEBUG and warn "Error using $module \: $@\n";
f666394a
RGS
443 return $tried{$module} = 0;
444 }
445 else {
ad56049d 446 DEBUG and warn " OK, $module is used\n";
f666394a
RGS
447 return $tried{$module} = 1;
448 }
9378c581
JH
449}
450
451#--------------------------------------------------------------------------
452
453sub _lex_refs { # report the lexicon references for this handle's class
f666394a
RGS
454 # returns an arrayREF!
455 no strict 'refs';
456 no warnings 'once';
457 my $class = ref($_[0]) || $_[0];
ad56049d 458 DEBUG and warn "Lex refs lookup on $class\n";
f666394a
RGS
459 return $isa_scan{$class} if exists $isa_scan{$class}; # memoization!
460
461 my @lex_refs;
462 my $seen_r = ref($_[1]) ? $_[1] : {};
463
464 if( defined( *{$class . '::Lexicon'}{'HASH'} )) {
465 push @lex_refs, *{$class . '::Lexicon'}{'HASH'};
ad56049d 466 DEBUG and warn '%' . $class . '::Lexicon contains ',
f666394a
RGS
467 scalar(keys %{$class . '::Lexicon'}), " entries\n";
468 }
469
470 # Implements depth(height?)-first recursive searching of superclasses.
471 # In hindsight, I suppose I could have just used Class::ISA!
472 foreach my $superclass (@{$class . '::ISA'}) {
ad56049d 473 DEBUG and warn " Super-class search into $superclass\n";
f666394a
RGS
474 next if $seen_r->{$superclass}++;
475 push @lex_refs, @{&_lex_refs($superclass, $seen_r)}; # call myself
476 }
477
478 $isa_scan{$class} = \@lex_refs; # save for next time
479 return \@lex_refs;
9378c581
JH
480}
481
482sub clear_isa_scan { %isa_scan = (); return; } # end on a note of simplicity!
483
87d86da5
TR
484#--------------------------------------------------------------------------
485
486sub _compile {
487 # This big scary routine compiles an entry.
488 # It returns either a coderef if there's brackety bits in this, or
489 # otherwise a ref to a scalar.
490
152eae84
TR
491 my $string_to_compile = $_[1]; # There are taint issues using regex on @_ - perlbug 60378,27344
492
493 # The while() regex is more expensive than this check on strings that don't need a compile.
494 # this op causes a ~2% speed hit for strings that need compile and a 250% speed improvement
495 # on strings that don't need compiling.
496 return \"$string_to_compile" if($string_to_compile !~ m/[\[~\]]/ms); # return a string ref if chars [~] are not in the string
497
87d86da5
TR
498 my $target = ref($_[0]) || $_[0];
499
500 my(@code);
501 my(@c) = (''); # "chunks" -- scratch.
502 my $call_count = 0;
503 my $big_pile = '';
504 {
505 my $in_group = 0; # start out outside a group
506 my($m, @params); # scratch
507
e9c9ffca 508 while($string_to_compile =~ # Iterate over chunks.
152eae84
TR
509 m/(
510 [^\~\[\]]+ # non-~[] stuff (Capture everything else here)
87d86da5
TR
511 |
512 ~. # ~[, ~], ~~, ~other
513 |
514 \[ # [ presumably opening a group
515 |
516 \] # ] presumably closing a group
517 |
518 ~ # terminal ~ ?
519 |
520 $
521 )/xgs
522 ) {
523 DEBUG>2 and warn qq{ "$1"\n};
524
525 if($1 eq '[' or $1 eq '') { # "[" or end
526 # Whether this is "[" or end, force processing of any
527 # preceding literal.
528 if($in_group) {
529 if($1 eq '') {
e9c9ffca 530 $target->_die_pointing($string_to_compile, 'Unterminated bracket group');
87d86da5
TR
531 }
532 else {
e9c9ffca 533 $target->_die_pointing($string_to_compile, 'You can\'t nest bracket groups');
87d86da5
TR
534 }
535 }
536 else {
537 if ($1 eq '') {
538 DEBUG>2 and warn " [end-string]\n";
539 }
540 else {
541 $in_group = 1;
542 }
e9c9ffca 543 die "How come \@c is empty?? in <$string_to_compile>" unless @c; # sanity
87d86da5
TR
544 if(length $c[-1]) {
545 # Now actually processing the preceding literal
546 $big_pile .= $c[-1];
547 if($USE_LITERALS and (
548 (ord('A') == 65)
549 ? $c[-1] !~ m/[^\x20-\x7E]/s
550 # ASCII very safe chars
551 : $c[-1] !~ m/[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/s
552 # EBCDIC very safe chars
553 )) {
554 # normal case -- all very safe chars
555 $c[-1] =~ s/'/\\'/g;
556 push @code, q{ '} . $c[-1] . "',\n";
557 $c[-1] = ''; # reuse this slot
558 }
559 else {
560 push @code, ' $c[' . $#c . "],\n";
561 push @c, ''; # new chunk
562 }
563 }
564 # else just ignore the empty string.
565 }
566
567 }
568 elsif($1 eq ']') { # "]"
569 # close group -- go back in-band
570 if($in_group) {
571 $in_group = 0;
572
573 DEBUG>2 and warn " --Closing group [$c[-1]]\n";
574
575 # And now process the group...
576
577 if(!length($c[-1]) or $c[-1] =~ m/^\s+$/s) {
578 DEBUG>2 and warn " -- (Ignoring)\n";
579 $c[-1] = ''; # reset out chink
580 next;
581 }
582
583 #$c[-1] =~ s/^\s+//s;
584 #$c[-1] =~ s/\s+$//s;
585 ($m,@params) = split(/,/, $c[-1], -1); # was /\s*,\s*/
586
587 # A bit of a hack -- we've turned "~,"'s into DELs, so turn
588 # 'em into real commas here.
589 if (ord('A') == 65) { # ASCII, etc
590 foreach($m, @params) { tr/\x7F/,/ }
591 }
592 else { # EBCDIC (1047, 0037, POSIX-BC)
593 # Thanks to Peter Prymmer for the EBCDIC handling
594 foreach($m, @params) { tr/\x07/,/ }
595 }
596
597 # Special-case handling of some method names:
598 if($m eq '_*' or $m =~ m/^_(-?\d+)$/s) {
599 # Treat [_1,...] as [,_1,...], etc.
600 unshift @params, $m;
601 $m = '';
602 }
603 elsif($m eq '*') {
604 $m = 'quant'; # "*" for "times": "4 cars" is 4 times "cars"
605 }
606 elsif($m eq '#') {
607 $m = 'numf'; # "#" for "number": [#,_1] for "the number _1"
608 }
609
610 # Most common case: a simple, legal-looking method name
611 if($m eq '') {
612 # 0-length method name means to just interpolate:
613 push @code, ' (';
614 }
615 elsif($m =~ /^\w+(?:\:\:\w+)*$/s
616 and $m !~ m/(?:^|\:)\d/s
617 # exclude starting a (sub)package or symbol with a digit
618 ) {
619 # Yes, it even supports the demented (and undocumented?)
620 # $obj->Foo::bar(...) syntax.
621 $target->_die_pointing(
e9c9ffca 622 $string_to_compile, q{Can't use "SUPER::" in a bracket-group method},
87d86da5
TR
623 2 + length($c[-1])
624 )
625 if $m =~ m/^SUPER::/s;
626 # Because for SUPER:: to work, we'd have to compile this into
627 # the right package, and that seems just not worth the bother,
628 # unless someone convinces me otherwise.
629
630 push @code, ' $_[0]->' . $m . '(';
631 }
632 else {
633 # TODO: implement something? or just too icky to consider?
634 $target->_die_pointing(
e9c9ffca 635 $string_to_compile,
87d86da5
TR
636 "Can't use \"$m\" as a method name in bracket group",
637 2 + length($c[-1])
638 );
639 }
640
641 pop @c; # we don't need that chunk anymore
642 ++$call_count;
643
644 foreach my $p (@params) {
645 if($p eq '_*') {
646 # Meaning: all parameters except $_[0]
647 $code[-1] .= ' @_[1 .. $#_], ';
648 # and yes, that does the right thing for all @_ < 3
649 }
650 elsif($p =~ m/^_(-?\d+)$/s) {
651 # _3 meaning $_[3]
652 $code[-1] .= '$_[' . (0 + $1) . '], ';
653 }
654 elsif($USE_LITERALS and (
655 (ord('A') == 65)
656 ? $p !~ m/[^\x20-\x7E]/s
657 # ASCII very safe chars
658 : $p !~ m/[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~\x07]/s
659 # EBCDIC very safe chars
660 )) {
661 # Normal case: a literal containing only safe characters
662 $p =~ s/'/\\'/g;
663 $code[-1] .= q{'} . $p . q{', };
664 }
665 else {
666 # Stow it on the chunk-stack, and just refer to that.
667 push @c, $p;
668 push @code, ' $c[' . $#c . '], ';
669 }
670 }
671 $code[-1] .= "),\n";
672
673 push @c, '';
674 }
675 else {
e9c9ffca 676 $target->_die_pointing($string_to_compile, q{Unbalanced ']'});
87d86da5
TR
677 }
678
679 }
680 elsif(substr($1,0,1) ne '~') {
681 # it's stuff not containing "~" or "[" or "]"
682 # i.e., a literal blob
683 $c[-1] .= $1;
684
685 }
686 elsif($1 eq '~~') { # "~~"
687 $c[-1] .= '~';
688
689 }
690 elsif($1 eq '~[') { # "~["
691 $c[-1] .= '[';
692
693 }
694 elsif($1 eq '~]') { # "~]"
695 $c[-1] .= ']';
696
697 }
698 elsif($1 eq '~,') { # "~,"
699 if($in_group) {
700 # This is a hack, based on the assumption that no-one will actually
701 # want a DEL inside a bracket group. Let's hope that's it's true.
702 if (ord('A') == 65) { # ASCII etc
703 $c[-1] .= "\x7F";
704 }
705 else { # EBCDIC (cp 1047, 0037, POSIX-BC)
706 $c[-1] .= "\x07";
707 }
708 }
709 else {
710 $c[-1] .= '~,';
711 }
712
713 }
714 elsif($1 eq '~') { # possible only at string-end, it seems.
715 $c[-1] .= '~';
716
717 }
718 else {
719 # It's a "~X" where X is not a special character.
720 # Consider it a literal ~ and X.
721 $c[-1] .= $1;
722 }
723 }
724 }
725
726 if($call_count) {
727 undef $big_pile; # Well, nevermind that.
728 }
729 else {
730 # It's all literals! Ahwell, that can happen.
731 # So don't bother with the eval. Return a SCALAR reference.
732 return \$big_pile;
733 }
734
735 die q{Last chunk isn't null??} if @c and length $c[-1]; # sanity
736 DEBUG and warn scalar(@c), " chunks under closure\n";
737 if(@code == 0) { # not possible?
738 DEBUG and warn "Empty code\n";
739 return \'';
740 }
741 elsif(@code > 1) { # most cases, presumably!
742 unshift @code, "join '',\n";
743 }
744 unshift @code, "use strict; sub {\n";
745 push @code, "}\n";
746
747 DEBUG and warn @code;
748 my $sub = eval(join '', @code);
749 die "$@ while evalling" . join('', @code) if $@; # Should be impossible.
750 return $sub;
751}
752
753#--------------------------------------------------------------------------
754
755sub _die_pointing {
756 # This is used by _compile to throw a fatal error
757 my $target = shift; # class name
758 # ...leaving $_[0] the error-causing text, and $_[1] the error message
759
760 my $i = index($_[0], "\n");
761
762 my $pointy;
763 my $pos = pos($_[0]) - (defined($_[2]) ? $_[2] : 0) - 1;
764 if($pos < 1) {
765 $pointy = "^=== near there\n";
766 }
767 else { # we need to space over
768 my $first_tab = index($_[0], "\t");
769 if($pos > 2 and ( -1 == $first_tab or $first_tab > pos($_[0]))) {
770 # No tabs, or the first tab is harmlessly after where we will point to,
771 # AND we're far enough from the margin that we can draw a proper arrow.
772 $pointy = ('=' x $pos) . "^ near there\n";
773 }
774 else {
775 # tabs screw everything up!
776 $pointy = substr($_[0],0,$pos);
777 $pointy =~ tr/\t //cd;
778 # make everything into whitespace, but preseving tabs
779 $pointy .= "^=== near there\n";
780 }
781 }
782
783 my $errmsg = "$_[1], in\:\n$_[0]";
784
785 if($i == -1) {
786 # No newline.
787 $errmsg .= "\n" . $pointy;
788 }
789 elsif($i == (length($_[0]) - 1) ) {
790 # Already has a newline at end.
791 $errmsg .= $pointy;
792 }
793 else {
794 # don't bother with the pointy bit, I guess.
795 }
796 Carp::croak( "$errmsg via $target, as used" );
797}
798
9378c581 7991;