blib/lib/Tcl.pm

filter: Statementstmt 4.0% 13 / 320 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 43 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 17.2% 5 / 29 Podpod n/a totaltotal 3.1% 18 / 568 CC 100 SCAR 61.2
CC
100
Cov
3%
call
1406.0
export_to_tcl
187.6
_code_clear
182.0
CRAP 456.3
↑ Summary Tcl.xs »
1 package Tcl;
2  
3 $Tcl::VERSION = '1.20';
4  
5 =head1 NAME
6  
7 Tcl - Tcl extension module for Perl
8  
9 =head1 SYNOPSIS
10  
11 use Tcl;
12  
13 $interp = Tcl->new;
14 $interp->Eval('puts "Hello world"');
15  
16 =head1 DESCRIPTION
17  
18 The Tcl extension module gives access to the Tcl library with
19 functionality and interface similar to the C functions of Tcl.
20 In other words, you can
21  
22 =over
23  
24 =item *
25  
26 create Tcl interpreters
27  
28 The Tcl interpreters so created are Perl objects whose destructors
29 delete the interpreters cleanly when appropriate.
30  
31 =item *
32  
33 execute Tcl code in an interpreter
34  
35 The code can come from strings, files or Perl filehandles.
36  
37 =item *
38  
39 bind in new Tcl procedures
40  
41 The new procedures can be either C code (with addresses presumably
42 obtained using I<dl_open> and I<dl_find_symbol>) or Perl subroutines
43 (by name, reference or as anonymous subs). The (optional) deleteProc
44 callback in the latter case is another perl subroutine which is called
45 when the command is explicitly deleted by name or else when the
46 destructor for the interpreter object is explicitly or implicitly called.
47  
48 =item *
49  
50 Manipulate the result field of a Tcl interpreter
51  
52 =item *
53  
54 Set and get values of variables in a Tcl interpreter
55  
56 =item *
57  
58 Tie perl variables to variables in a Tcl interpreter
59  
60 The variables can be either scalars or hashes.
61  
62 =back
63  
64 =head2 Methods in class Tcl
65  
66 To create a new Tcl interpreter, use
67  
68 $interp = Tcl->new;
69  
70 The following methods and routines can then be used on the Perl object
71 returned (the object argument omitted in each case).
72  
73 =over
74  
75 =item $interp->Init ()
76  
77 Invoke I<Tcl_Init> on the interpreter.
78  
79 =item $interp->CreateSlave (NAME, SAFE)
80  
81 Invoke I<Tcl_CreateSlave> on the interpreter. Name is arbitrary.
82 The safe variable, if true, creates a safe sandbox interpreter.
83 See: http://www.tcl.tk/software/plugin/safetcl.html
84 http://www.tcl.tk/man/tcl8.4/TclCmd/safe.htm
85  
86 This command returns a new interpreter.
87  
88 =item $interp->Eval (STRING, FLAGS)
89  
90 Evaluate script STRING in the interpreter. If the script returns
91 successfully (TCL_OK) then the Perl return value corresponds to Tcl
92 interpreter's result otherwise a I<die> exception is raised with the $@
93 variable corresponding to Tcl's interpreter result object. In each case,
94 I<corresponds> means that if the method is called in scalar context then
95 the string result is returned but if the method is called in list context
96 then the result is split as a Tcl list and returned as a Perl list.
97 The FLAGS field is optional and can be a bitwise OR of the constants
98 Tcl::EVAL_GLOBAL or Tcl::EVAL_DIRECT.
99  
100 =item $interp->GlobalEval (STRING)
101  
102 REMOVED. Evalulate script STRING at global level.
103 Call I<Eval>(STRING, Tcl::EVAL_GLOBAL) instead.
104  
105 =item $interp->EvalFile (FILENAME)
106  
107 Evaluate the contents of the file with name FILENAME. Otherwise, the
108 same as I<Eval>() above.
109  
110 =item $interp->EvalFileHandle (FILEHANDLE)
111  
112 Evaluate the contents of the Perl filehandle FILEHANDLE. Otherwise, the
113 same as I<Eval>() above. Useful when using the filehandle DATA to tack
114 on a Tcl script following an __END__ token.
115  
116 =item $interp->call (PROC, ARG, ...)
117  
118 Looks up procedure PROC in the interpreter and invokes it using Tcl's eval
119 semantics that does command tracing and will use the ::unknown (AUTOLOAD)
120 mechanism. The arguments (ARG, ...) are not passed through the Tcl parser.
121 For example, spaces embedded in any ARG will not cause it to be split into
122 two Tcl arguments before being passed to PROC.
123  
124 Before invoking procedure PROC special processing is performed on ARG list:
125  
126 1. All subroutine references within ARG will be substituted with Tcl name
127 which is responsible to invoke this subroutine. This Tcl name will be
128 created using CreateCommand subroutine (see below).
129  
130 2. All references to scalars will be substituted with names of Tcl variables
131 transformed appropriately.
132  
133 These first two items allow one to write and expect it to work properly such
134 code as:
135  
136 my $r = 'aaaa';
137 button(".d", -textvariable => \$r, -command=>sub {$r++});
138  
139 3. All references to hashes will be substituted with names of Tcl array
140 variables transformed appropriately.
141  
142 4. As a special case, there is a mechanism to deal with Tk's special event
143 variables (they are mentioned as '%x', '%y' and so on throughout Tcl).
144 When creating a subroutine reference that uses such variables, you must
145 declare the desired variables using Tcl::Ev as the first argument to the
146 subroutine. Example:
147  
148 sub textPaste {
149 my ($x,$y,$w) = @_;
150 widget($w)->insert("\@$x,$y", $interp->Eval('selection get'));
151 }
152 $widget->bind('<2>', [\&textPaste, Tcl::Ev('%x', '%y'), $widget] );
153  
154 =item $interp->return_ref (NAME)
155  
156 returns a reference corresponding to NAME, which was associated during
157 previously called C<< $interpnt->call(...) >> preprocessing. As a typical
158 example this could be variable associated with a widget.
159  
160 =item $interp->delete_ref (NAME)
161  
162 deletes and returns a reference corresponding to NAME, which was associated
163 during previously called C<< $interpnt->call(...) >> preprocessing.
164 this follows _code_dispose about if NAME is a TClNAME or a DESCNAME.
165 if NAME is a VARNAME then it is just deleted and returned.
166  
167 =item $interp->icall (PROC, ARG, ...)
168  
169 Looks up procedure PROC in the interpreter and invokes it using Tcl's eval
170 semantics that does command tracing and will use the ::unknown (AUTOLOAD)
171 mechanism. The arguments (ARG, ...) are not passed through the Tcl parser.
172 For example, spaces embedded in any ARG will not cause it to be split into
173 two Tcl arguments before being passed to PROC.
174  
175 This is the lower-level procedure that the 'call' method uses. Arguments
176 are converted efficiently from Perl SVs to Tcl_Objs. A Perl AV array
177 becomes a Tcl_ListObj, an SvIV becomes a Tcl_IntObj, etc. The reverse
178 conversion is done to the result.
179  
180 =item $interp->invoke (PROC, ARG, ...)
181  
182 Looks up procedure PROC in the interpreter and invokes it directly with
183 arguments (ARG, ...) without passing through the Tcl parser. For example,
184 spaces embedded in any ARG will not cause it to be split into two Tcl
185 arguments before being passed to PROC. This differs from icall/call in
186 that it directly invokes the command name without allowing for command
187 tracing or making use of Tcl's unknown (AUTOLOAD) mechanism. If the
188 command does not already exist in the interpreter, and error will be
189 thrown.
190  
191 Arguments are converted efficiently from Perl SVs to Tcl_Objs. A Perl AV
192 array becomes a Tcl_ListObj, an SvIV becomes a Tcl_IntObj, etc. The
193 reverse conversion is done to the result.
194  
195 =item Tcl::Ev (FIELD, ...)
196  
197 Used to declare %-substitution variables of interest to a subroutine
198 callback. FIELD is expected to be of the form "%#" where # is a single
199 character, and multiple fields may be specified. Returns a blessed object
200 that the 'call' method will recognize when it is passed as the first
201 argument to a subroutine in a callback. See description of 'call' method
202 for details.
203  
204 =item $interp->result ()
205  
206 Returns the current Tcl interpreter result. List v. scalar context is
207 handled as in I<Eval>() above.
208  
209 =item $interp->CreateCommand (CMDNAME, CMDPROC, CLIENTDATA, DELETEPROC, FLAGS)
210  
211 Binds a new procedure named CMDNAME into the interpreter. The
212 CLIENTDATA and DELETEPROC arguments are optional. There are two cases:
213  
214 (1) CMDPROC is the address of a C function
215  
216 (presumably obtained using I<dl_open> and I<dl_find_symbol>. In this case
217 CLIENTDATA and DELETEPROC are taken to be raw data of the ClientData and
218 deleteProc field presumably obtained in a similar way.
219  
220 (2) CMDPROC is a Perl subroutine
221  
222 (either a sub name, a sub reference or an anonymous sub). In this case
223 CLIENTDATA can be any perl scalar (e.g. a ref to some other data) and
224 DELETEPROC must be a perl sub too. When CMDNAME is invoked in the Tcl
225 interpreter, the arguments passed to the Perl sub CMDPROC are
226  
227 (CLIENTDATA, INTERP, LIST)
228  
229 where INTERP is a Perl object for the Tcl interpreter which called out
230 and LIST is a Perl list of the arguments CMDNAME was called with.
231 If the 1-bit of FLAGS is set then the 3 first arguments on the call
232 to CMDPROC are suppressed.
233 As usual in Tcl, the first element of the list is CMDNAME itself.
234 When CMDNAME is deleted from the interpreter (either explicitly with
235 I<DeleteCommand> or because the destructor for the interpreter object
236 is called), it is passed the single argument CLIENTDATA.
237  
238 =item $interp->DeleteCommand (CMDNAME)
239  
240 Deletes command CMDNAME from the interpreter. If the command was created
241 with a DELETEPROC (see I<CreateCommand> above), then it is invoked at
242 this point. When a Tcl interpreter object is destroyed either explicitly
243 or implicitly, an implicit I<DeleteCommand> happens on all its currently
244 registered commands.
245  
246  
247 =item (TCLNAME,GENCODE) = $interp->create_tcl_sub(CODEREF, EVENTS, TCLNAME, DESCRNAME)
248  
249 Creates a COMMAND called TCLNAME calling CODEREF in the interpreter $interp,
250 and adds it to the internal tracking structure.
251 DESCRNAME and TCLNAME should not begin
252 with =
253 or @
254 or ::perl::
255 to avoid colisions
256 If TCLNAME IS blank or undef, it is constructed from the CODEREF address.
257 GENCODE starts as TCLNAME but gets @$EVENTS which can contain %vars joined to it.
258  
259 TCLNAME and DESCRNAME get stored in an internal structure,
260 and can be used to purge things fRom the command table via code_destroy or $interp->destroy_ref;
261  
262 Returns (TCLNAME,GENCODE).
263 if you are creating code refs with this you can continue to use the same coderef and it will be converted on each call.
264 but if you save GENCODE, you can replace the anon-coderef call in the tcl command with GENCODE.
265  
266 for instance
267  
268 $interp->call('FILEEVENT',$fileref,WRITABLE=>sub {...});
269  
270 can be replaced by
271  
272 my ($tclcode,$gencode)=$interp->create_tcl_sub(sub{...}, EVENTS, TCLNAME, DESCRNAME);
273 $interp->call('FILEEVENT',$gencode,WRITABLE=>$gencode);
274  
275 or
276  
277 my $sub=sub{....};
278 $interp->call('FILEEVENT',$fileref,WRITABLE=>$sub);
279  
280 can be replaced by
281  
282 my ($tclcode,$gencode)=$interp->create_tcl_sub($sub, EVENTS, TCLNAME, DESCRNAME);
283 $interp->call('FILEEVENT',$gencode,WRITABLE=>$gencode);
284  
285 although
286  
287 $interp->call('FILEEVENT',$fileref,WRITABLE=>$sub);
288  
289 will stil work fine too.
290  
291 Then you later call
292  
293 $interp->destroy_ref($tclname);
294  
295 when you are finished with that sub to clean it from the internal tracking and command table.
296 This means no automatic cleanup will occur on the sub{...} or $sub
297  
298  
299 And after the destroy inside Tcl any triggering writable on $fileref will fail as well.
300 so it shhould be replaced first via
301 $interp->call('FILEEVENT',$fileref,WRITABLE=>'');
302  
303 =item (CODEREF) = Tcl::_code_destroy(NAME)
304  
305 Purges the internal table of a NAME
306 and may initiate destruction of something created thru call or create_tcl_sub
307  
308 TCLNAME and DESCRNAME get stored in an internal structure,
309 and can be used to purge things form the command table.
310 calling _code_destroy on a TCLNAME retruned from create_tcl_sub removes all use instances and purges the command table.
311 calling _code_destroy on a DESCRNAME passed to create_tcl_sub removes only that instace
312 Code used in a DESCRNAME may be used in other places as well,
313 only when the last usage is purged does the entry get purged from the command table
314  
315 While the internal tracking structure saves the INTERP the code was added to,
316 it itself does not keep things separated by INTERP,
317 A TCLNAME or DESCRNAMe can only exist in one INTERP at a time,
318 using a new INTERP just causes the one in the last INTERP to disapear,
319 and probably end up with the Tcl code getting deleted
320  
321 Returns (CODEREF), this is the original coderef
322  
323 =item $interp->SetResult (STRING)
324  
325 Sets Tcl interpreter result to STRING.
326  
327 =item $interp->AppendResult (LIST)
328  
329 Appends each element of LIST to Tcl's interpreter result object.
330  
331 =item $interp->AppendElement (STRING)
332  
333 Appends STRING to Tcl interpreter result object as an extra Tcl list element.
334  
335 =item $interp->ResetResult ()
336  
337 Resets Tcl interpreter result.
338  
339 =item $interp->SplitList (STRING)
340  
341 Splits STRING as a Tcl list. Returns a Perl list or the empty list if
342 there was an error (i.e. STRING was not a properly formed Tcl list).
343 In the latter case, the error message is left in Tcl's interpreter
344 result object.
345  
346 =item $interp->SetVar (VARNAME, VALUE, FLAGS)
347  
348 The FLAGS field is optional. Sets Tcl variable VARNAME in the
349 interpreter to VALUE. The FLAGS argument is the usual Tcl one and
350 can be a bitwise OR of the constants Tcl::GLOBAL_ONLY,
351 Tcl::LEAVE_ERR_MSG, Tcl::APPEND_VALUE, Tcl::LIST_ELEMENT.
352  
353 =item $interp->SetVar2 (VARNAME1, VARNAME2, VALUE, FLAGS)
354  
355 Sets the element VARNAME1(VARNAME2) of a Tcl array to VALUE. The optional
356 argument FLAGS behaves as in I<SetVar> above.
357  
358 =item $interp->GetVar (VARNAME, FLAGS)
359  
360 Returns the value of Tcl variable VARNAME. The optional argument FLAGS
361 behaves as in I<SetVar> above.
362  
363 =item $interp->GetVar2 (VARNAME1, VARNAME2, FLAGS)
364  
365 Returns the value of the element VARNAME1(VARNAME2) of a Tcl array.
366 The optional argument FLAGS behaves as in I<SetVar> above.
367  
368 =item $interp->UnsetVar (VARNAME, FLAGS)
369  
370 Unsets Tcl variable VARNAME. The optional argument FLAGS
371 behaves as in I<SetVar> above.
372  
373 =item $interp->UnsetVar2 (VARNAME1, VARNAME2, FLAGS)
374  
375 Unsets the element VARNAME1(VARNAME2) of a Tcl array.
376 The optional argument FLAGS behaves as in I<SetVar> above.
377  
378 =back
379  
380 =head2 Command table cleanup
381  
382 In V1.03 command table cleanup was intoduced.
383 This tries to keep the internal structure and command table clean.
384 In V1.02 and prior heavy use of sub { .. } in Tcl commands could polute these tables
385 as they were never cleared. Command table cleanup tries to alieviate this.
386  
387 if you call create_tcl_sub the internal reference exists until
388 you delete_ref or _code_destroy it, or you call create_tcl_sub with the same DESCRNAME.
389  
390 if the internal reference was created internaly by call(...) there are two rules
391  
392 =over
393  
394 =item 1)
395  
396 If the command is an "after" the internal references is keept at least until 1 second after the delay.
397 If there are still other "users" of the TCLNAME then it is not deleted untill the last one goes away.
398 If another call with the same CODEREF happens before this,
399 then it will get registered as a "user" without any need to delete/recreate the tcl command first.
400  
401 = item 2)
402  
403 otherwise a DESCRNAME is created with the text sections of the command, prefaced by "=".
404 Like
405 "=after 1000"
406 or "=:.m.m add command -command -label Exit"
407 or "=::button .f3.b8 -text conn -command"
408 or "=gets sock9ac2b50"
409 or "=fileevent sock9827430 writable"
410  
411  
412 the TCLCODES created for that command will be kept at least untill a command with
413 the same DESCRNAME and containing a subroutine reference is run again.
414 Since many DESCRNAMES can reference the same TCLNAME only when
415 the last DESCRNAME referencing a TCLNAME is released is the TCLNAME purged.
416  
417 NOTE:
418 Since
419 $interp->call('fileevent','sock9827430','writable');
420 does not contain a subroutine reference, it will not release/free the TCLNAME/DESCRNAME created by
421 $interp->call('fileevent','sock9827430','writable',sub{...});
422 even though that is the way you deactivate a writable/readable callback in Tcl.
423  
424 =back
425  
426 Prior to V1.06 there was also a problem with the coderef never getting cleared from sas,
427 a refcount was kept at the PVCV that prevented it from getting garbage collected,
428 but that SV itself got "lost" and could never be garbage collected,
429 thereby also keeping anything in that codes PAD.
430  
431 To assist in tracking chages to the internal table and the commands table 3 trace variables were added,
432 set them to non-blank or non-zero to add the tracking output to SYSOUT
433  
434 =over
435  
436 =item $Tcl::TRACE_SHOWCODE
437  
438 Display all generated Tcl code by call().
439 Be aware: Tkx::MainLoop runs by issueing a lot of "winfo exists ." calls, a LOT.
440 But this is a nice way to tell what your programs are doing to Tcl.
441  
442  
443 =item $Tcl::TRACE_CREATECOMMAND
444  
445 Display Tcl subroutine creation by call/create_tcl_sub
446  
447 =item $Tcl::TRACE_DELETECOMMAND
448  
449 Display Tcl subroutine deletion by cleanup/destroy_ref/_code_dispose
450  
451 =back
452  
453 =head2 Linking Perl and Tcl variables
454  
455 You can I<tie> a Perl variable (scalar or hash) into class Tcl::Var
456 so that changes to a Tcl variable automatically "change" the value
457 of the Perl variable. In fact, as usual with Perl tied variables,
458 its current value is just fetched from the Tcl variable when needed
459 and setting the Perl variable triggers the setting of the Tcl variable.
460  
461 To tie a Perl scalar I<$scalar> to the Tcl variable I<tclscalar> in
462 interpreter I<$interp> with optional flags I<$flags> (see I<SetVar>
463 above), use
464  
465 tie $scalar, "Tcl::Var", $interp, "tclscalar", $flags;
466  
467 Omit the I<$flags> argument if not wanted.
468  
469 To tie a Perl hash I<%hash> to the Tcl array variable I<array> in
470 interpreter I<$interp> with optional flags I<$flags>
471 (see I<SetVar> above), use
472  
473 tie %hash, "Tcl::Var", $interp, "array", $flags;
474  
475 Omit the I<$flags> argument if not wanted. Any alteration to Perl
476 variable I<$hash{"key"}> affects the Tcl variable I<array(key)>
477 and I<vice versa>.
478  
479 =head2 Accessing Perl from within Tcl
480  
481 After creation of Tcl interpreter, in addition to evaluation of Tcl/Tk
482 commands within Perl, other way round also instantiated. Within a special
483 namespace C< ::perl > following objects are created:
484  
485 ::perl::Eval
486  
487 So it is possible to use Perl objects from within Tcl.
488  
489 =head2 Moving Tcl/Tk around with Tcl.pm
490  
491 NOTE: explanations below is for developers managing Tcl/Tk installations
492 itself, users should skip this section.
493  
494 In order to create Tcl/Tk application with this module, you need to make
495 sure that Tcl/Tk is available within visibility of this module. There are
496 many ways to achieve this, varying on ease of starting things up and
497 providing flexible moveable archived files.
498  
499 Following list enumerates them, in order of increased possibility to change
500 location.
501  
502 =over
503  
504 =item *
505  
506 First method
507  
508 Install Tcl/Tk first, then install Perl module Tcl, so installed Tcl/Tk will
509 be used. This is most normal approach, and no care of Tcl/Tk distribution is
510 taken on Perl side (this is done on Tcl/Tk side)
511  
512 =item *
513  
514 Second method
515  
516 Copy installed Tcl/Tk binaries to some location, then install Perl module Tcl
517 with a special action to make Tcl.pm know of this location. This approach
518 makes sure that only chosen Tcl installation is used.
519  
520 =item *
521  
522 Third method
523  
524 During compiling Tcl Perl module, Tcl/Tk could be statically linked into
525 module's shared library and all other files zipped into a single archive, so
526 each file extracted when needed.
527  
528 To link Tcl/Tk binaries, prepare their libraries and then instruct Makefile.PL
529 to use these libraries in a link stage.
530 (TODO provide better detailed description)
531  
532 =back
533  
534 =cut
535  
536 20 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
537  
538 our $TRACE_SHOWCODE; # display generated code in call();
539 our $TRACE_CREATECOMMAND; # display sub creates;
540 our $TRACE_DELETECOMMAND; # display sub deletes;
541  
542 $TRACE_SHOWCODE = 0 unless defined $TRACE_SHOWCODE;
543 $TRACE_DELETECOMMAND = 0 unless defined $TRACE_DELETECOMMAND;
544 $TRACE_CREATECOMMAND = 0 unless defined $TRACE_CREATECOMMAND;
545  
546 our $SAVEALLCODES; # simulate the v1.05 way of saving only last call
547 $SAVEALLCODES = 1 unless defined $SAVEALLCODES;
548  
549 our $SAVENOCODE ; # simulate the v1.05 way of leaving any existing
550 # $anon_refs{$current_r} alone if new line has no coderefs
551 $SAVENOCODE = 1 unless defined $SAVENOCODE;
552  
553 our $DL_PATH;
554 unless (defined $DL_PATH) {
555 $DL_PATH = $ENV{PERL_TCL_DL_PATH} || $ENV{PERL_TCL_DLL} || "";
556 }
557  
558 =for ignore
559 sub Tcl::seek_tkkit {
560 # print STDERR "wohaaa!\n";
561 unless ($DL_PATH) {
562 require Config;
563 for my $inc (@INC) {
564 my $tkkit = "$inc/auto/Tcl/tkkit.$Config::Config{so}";
565 if (-f $tkkit) {
566 $DL_PATH = $tkkit;
567 last;
568 }
569 }
570 }
571 }
572 =cut
573 seek_tkkit() if defined &seek_tkkit;
574  
575  
576 my $path;
577 if ($^O eq 'darwin') {
578 # Darwin 7.9 (OS X 10.3) requires the path of the executable be prepended
579 # for #! scripts to operate properly (avoids RegisterProcess error).
580 require Config;
581 unless (grep { $_ eq $Config::Config{binexp} } split $Config::Config{path_sep}, $ENV{PATH}) {
582 $path = join $Config::Config{path_sep}, $Config::Config{binexp}, $ENV{PATH};
583 }
584 }
585  
586 require XSLoader;
587  
588 {
589 local $ENV{PATH} = $path if $path;
590 XSLoader::load('Tcl', $Tcl::VERSION);
591 }
592  
593 sub new {
594 0 ▶ my $int = _new(@_);
Subroutine new: not called CC=1 SCAR=6.9
595 0 return $int;
596 }
597  
598 END {
599 20 ▶ Tcl::_Finalize();
Subroutine END: called CC=1 SCAR=0.0
600 }
601  
602 # %anon_refs keeps track of anonymous subroutines and scalar/array/hash
603 # references which are created on the fly for tcl/tk interchange
604 # at a step when 'call' interpreter method prepares its arguments for
605 # tcl/tk call, which is invoked by 'icall' interpreter method
606 # (this argument transformation is done with "CreateCommand" method for
607 # subs and with 'tie' for other)
608  
609 my %anon_refs;
610 0 ▶sub _anon_refs_cheat { return \%anon_refs;}
Subroutine _anon_refs_cheat: not called CC=1 SCAR=6.9
611  
612 # (TODO -- find out how to check for refcounting and proper releasing of
613 # resources)
614  
615 # Subroutine "call" preprocess the arguments for special cases
616 # and then calls "icall" (implemented in Tcl.xs), which invokes
617 # the command in Tcl.
618 sub call {
619 0 ▶ my $interp = shift;
Subroutine call: not called CC=37 SCAR=72.5
620 0 my @args = @_;
621 # add = so as not to interfere with user defined DESCRNAMEs
622 0 my $current_r = '='.join ' ', grep {defined} grep {!ref} @args;
623 0 my @codes;
624  
625 0 my $lastcodes = $anon_refs{$current_r}; # could be an array, want to hold all for now so they can be reused
626 0 ▶ unless ($SAVENOCODE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Tcl::SAVENOCODE) 0 0 0
627 0 ▶ unless ($#args == 1 and $args[0] eq 'set') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($#args == 1 and $args[0] eq "set") 0 0 0
Condition0%0/3
$#args == 1 and $args[0] eq "set"
!ll&&!rl&&r
000
MC/DC0%0/2
$#args == 1 and $args[0] eq "set"
$#args == 1 $args[0] eq "set"
Truth table0%0/3
A and B
A= $#args == 1B= $args[0] eq "set"
ABresult
0X0
100
111
628 # this was to clean up things like
629 # Tkx::fileevent($remote, writable => sub {...});
630 # when this was run later
631 # Tkx::fileevent($fh, writable => '');
632 # but "set foo" doesnt clear its setting, it returns its value
633 # after busting the test in the Tkx tests for set foo
634 # i decided to disable this for now
635 0 delete $anon_refs{$current_r}; # if old one had a call and new one doesnt make sure it goes away
636 }
637 }
638 # Process arguments looking for special cases
639 0 ▶ for (my $argcnt=0; $argcnt<=$#args; $argcnt++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($argcnt <= $#args) 0 0 0
640 0 my $arg = $args[$argcnt];
641 0 my $ref = ref($arg);
642 0 ▶ next unless $ref;
Branch: 1 branch
BranchTrueFalseTotal
unless $ref 0 0 0
643 0 ▶ if ($ref eq 'CODE' || $ref eq 'Tcl::Code') {
Branch: 5 branches
BranchTrueFalseTotal
if ($ref eq 'CODE' or $ref eq 'Tcl::Code') { } 0 0 0
elsif ($ref eq 'SCALAR') { } 0 0 0
elsif ($ref eq 'HASH') { } 0 0 0
elsif ($ref eq 'ARRAY' and ref $arg->[0] eq 'CODE') { } 0 0 0
elsif ($ref eq 'REF' and ref $$arg eq 'SCALAR') { } 0 0 0
Condition0%0/3
$ref eq "CODE" or $ref eq "Tcl::Code"
l!l&&r!l&&!r
000
MC/DC0%0/2
$ref eq "CODE" or $ref eq "Tcl::Code"
$ref eq "CODE" $ref eq "Tcl::Code"
Truth table0%0/3
A or B
A= $ref eq "CODE"B= $ref eq "Tcl::Code"
ABresult
1X1
011
000
644 # We have been passed something like \&subroutine
645 # Create a proc in Tcl that invokes this subroutine (no args)
646 0 $args[$argcnt] = $interp->create_tcl_sub($arg, undef, undef, $current_r);
647 0 push @codes, $anon_refs{$current_r}; # push CODE also only to keep it from early disposal
648 }
649 elsif ($ref eq 'SCALAR') {
650 # We have been passed something like \$scalar
651 # Create a tied variable between Tcl and Perl.
652  
653 # stringify scalar ref, create in ::perl namespace on Tcl side
654 # This will be SCALAR(0xXXXXXX) - leave it to become part of a
655 # Tcl array.
656 0 my $nm = "::perl::$arg";
657 0 ▶ unless (exists $anon_refs{$nm}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $anon_refs{$nm}) 0 0 0
658 0 $anon_refs{$nm} = $arg;
659 0 my $s = $$arg;
660 0 tie $$arg, 'Tcl::Var', $interp, $nm;
661 0 ▶ $s = '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 0 0
662 0 $$arg = $s;
663 }
664 0 $args[$argcnt] = $nm; # ... and substitute its name
665 }
666 elsif ($ref eq 'HASH') {
667 # We have been passed something like \%hash
668 # Create a tied variable between Tcl and Perl.
669  
670 # stringify hash ref, create in ::perl namespace on Tcl side
671 # This will be HASH(0xXXXXXX) - leave it to become part of a
672 # Tcl array.
673 0 my $nm = $arg;
674 0 $nm =~ s/\W/_/g; # remove () from stringified name
675 0 $nm = "::perl::$nm";
676 0 ▶ unless (exists $anon_refs{$nm}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $anon_refs{$nm}) 0 0 0
677 0 $anon_refs{$nm} = $arg;
678 0 my %s = %$arg;
679 0 tie %$arg, 'Tcl::Var', $interp, $nm;
680 0 %$arg = %s;
681 }
682 0 $args[$argcnt] = $nm; # ... and substitute its name
683 }
684 ▶ elsif ($ref eq 'ARRAY' && ref($arg->[0]) eq 'CODE') {
Condition0%0/3
$ref eq "ARRAY" and ref $arg->[0] eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
$ref eq "ARRAY" and ref $arg->[0] eq "CODE"
$ref eq "ARRAY" ref $arg->[0] eq "CODE"
Truth table0%0/3
A and B
A= $ref eq "ARRAY"B= ref $arg->[0] eq "CODE"
ABresult
0X0
100
111
685 # We have been passed something like [\&subroutine, $arg1, ...]
686 # Create a proc in Tcl that invokes this subroutine with args
687 0 my $events;
688 # Look for Tcl::Ev objects as the first arg - these must be
689 # passed through for Tcl to evaluate. Used primarily for %-subs
690 # This could check for any arg ref being Tcl::Ev obj, but it
691 # currently doesn't.
692 0 ▶ if ($#$arg >= 1 && ref($arg->[1]) eq 'Tcl::Ev') {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg->$#* >= 1 and ref $arg->[1] eq "Tcl::Ev") 0 0 0
Condition0%0/3
$arg->$#* >= 1 and ref $arg->[1] eq "Tcl::Ev"
!ll&&!rl&&r
000
MC/DC0%0/2
$arg->$#* >= 1 and ref $arg->[1] eq "Tcl::Ev"
$arg->$#* >= 1 ref $arg->[1] eq "Tcl::Ev"
Truth table0%0/3
A and B
A= $arg->$#* >= 1B= ref $arg->[1] eq "Tcl::Ev"
ABresult
0X0
100
111
693 0 $events = splice(@$arg, 1, 1);
694 }
695 $args[$argcnt] =
696 $interp->create_tcl_sub(sub {
697 0 ▶ $arg->[0]->(@_, @$arg[1..$#$arg]);
Subroutine __ANON__: not called CC=1 SCAR=6.9
698 0 }, $events, undef, $current_r);
699 0 push @codes, $anon_refs{$current_r};
700 }
701 ▶ elsif ($ref eq 'REF' and ref($$arg) eq 'SCALAR') {
Condition0%0/3
$ref eq "REF" and ref $$arg eq "SCALAR"
!ll&&!rl&&r
000
MC/DC0%0/2
$ref eq "REF" and ref $$arg eq "SCALAR"
$ref eq "REF" ref $$arg eq "SCALAR"
Truth table0%0/3
A and B
A= $ref eq "REF"B= ref $$arg eq "SCALAR"
ABresult
0X0
100
111
702 # this is a very special shortcut: if we see construct like \\"xy"
703 # then place proper Tcl::Ev(...) for easier access
704 0 my $events = [map {"%$_"} split '', $$$arg];
705 0 ▶ if (ref($args[$argcnt+1]) eq 'ARRAY' &&
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args[$argcnt + 1] eq 'ARRAY' and ref $args[$argcnt + 1][0] eq 'CODE') { } 0 0 0
elsif (ref $args[$argcnt + 1] eq 'CODE') { } 0 0 0
Condition0%0/3
ref $args[$argcnt + 1] eq "ARRAY" and ref $args[$argcnt + 1][0] eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $args[$argcnt + 1] eq "ARRAY" and ref $args[$argcnt + 1][0] eq "CODE"
ref $args[$argcnt + 1] eq "ARRAY" ref $args[$argcnt + 1][0] eq "CODE"
Truth table0%0/3
A and B
A= ref $args[$argcnt + 1] eq "ARRAY"B= ref $args[$argcnt + 1][0] eq "CODE"
ABresult
0X0
100
111
706 ref($args[$argcnt+1]->[0]) eq 'CODE') {
707 0 $arg = $args[$argcnt+1];
708 $args[$argcnt] =
709 $interp->create_tcl_sub(sub {
710 0 ▶ $arg->[0]->(@_, @$arg[1..$#$arg]);
Subroutine __ANON__: not called CC=1 SCAR=6.9
711 0 }, $events, undef, $current_r);
712 0 push @codes, $anon_refs{$current_r};
713 }
714 elsif (ref($args[$argcnt+1]) eq 'CODE') {
715 0 $args[$argcnt] = $interp->create_tcl_sub($args[$argcnt+1],$events, undef, $current_r);
716 0 push @codes, $anon_refs{$current_r};
717 }
718 else {
719 0 warn "not CODE/ARRAY expected after description of event fields";
720 }
721 0 splice @args, $argcnt+1, 1;
722 }
723 }
724  
725 0 $lastcodes = []; # now let any from last use be destroyed
726  
727 0 ▶ showcode(\@args) if ($TRACE_SHOWCODE);
Branch: 1 branch
BranchTrueFalseTotal
if $Tcl::TRACE_SHOWCODE 0 0 0
728  
729 0 ▶ if ($#codes>-1 and $args[0] eq 'after') {
Branch: 1 branch
BranchTrueFalseTotal
if ($#codes > -1 and $args[0] eq "after") 0 0 0
Condition0%0/3
$#codes > -1 and $args[0] eq "after"
!ll&&!rl&&r
000
MC/DC0%0/2
$#codes > -1 and $args[0] eq "after"
$#codes > -1 $args[0] eq "after"
Truth table0%0/3
A and B
A= $#codes > -1B= $args[0] eq "after"
ABresult
0X0
100
111
730 # AFTERS can clog up the tables real quick, so plan to delete them via Tcl::Code::DESTROY
731 0 my $delay='';
732 0 ▶ if ($args[1] =~ /^\d+$/) { $delay=$args[1]+1000; }
Branch: 2 branches
BranchTrueFalseTotal
if ($args[1] =~ /^\d+$/) { } 0 0 0
elsif ($args[1] eq 'idle') { } 0 0 0
733 0 elsif ($args[1] eq 'idle') { $delay='idle'; } # just hope they run in order
734 0 ▶ if ($delay) {
Branch: 1 branch
BranchTrueFalseTotal
if ($delay) 0 0 0
735 0 my $id = $interp->icall(@args);
736 #print STDERR "rebind for $interp;$id\n";
737 # in 'after' methods, disposal of CODE REFs based on 'after' id
738 # i.e based on return value of tcl call
739 0 my $newname='@'.$interp.';'.$id;
740 0 $anon_refs{$newname} = \@codes;
741 0 for my $code (@codes) {
742 0 my $ridptr=$anon_refs{$code->[2]}[1];
743 0 $ridptr->{$newname}++ ; # save under new name
744 0 $ridptr->{$current_r}-- ; # maybe take out this name
745 0 ▶ unless ($ridptr->{$current_r}>0){
Branch: 1 branch
BranchTrueFalseTotal
unless ($ridptr->{$current_r} > 0) 0 0 0
746 0 delete $ridptr->{$current_r}; # clean up old
747 }
748 }
749 0 delete $anon_refs{$current_r}; # and now its clean
750 0 for my $code (@codes) { $code->[3]=$newname; } # save under new name
751 # this should trigger DESTROY unless a newer after or something else still holds a $tclname in the list
752 0 $interp->invoke('after',$delay, "perl::Eval {Tcl::_code_dispose('$newname')}");
753 0 ▶ showcode( ['after',$delay, "perl::Eval {Tcl::_code_dispose('$newname')}"] ) if ($TRACE_SHOWCODE); ;
Branch: 1 branch
BranchTrueFalseTotal
if $Tcl::TRACE_SHOWCODE 0 0 0
754 0 return $id;
755 } # delay
756 # if we're here - user does something wrong, but there is nothing we worry about
757 } # codes and after
758  
759  
760 # got to keep all of them alive , not just the last
761 # incase there are lines that have more than one like ===== fileevent readable=>$sub1 writable=>$sub2
762 # although that isnt legal, but this is ===== if 1 $sub1 $sub2
763 # the downside is that add/delete processing goes on for $sub1 every call if we only keep the last
764 0 ▶ if ($SAVEALLCODES) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Tcl::SAVEALLCODES) 0 0 0
765 0 ▶ if (scalar(@codes)>1) { # no reason to save an array of just 1
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @codes > 1) 0 0 0
766 0 delete $anon_refs{$current_r};
767 0 $anon_refs{$current_r}=\@codes;
768 }
769 }
770  
771 # Done with special var processing. The only processing that icall
772 # will do with the args is efficient conversion of SV to Tcl_Obj.
773 # A SvIV will become a Tcl_IntObj, ARRAY refs will become Tcl_ListObjs,
774 # and so on. The return result from icall will do the opposite,
775 # converting a Tcl_Obj to an SV.
776  
777 # we need just this:
778 # return $interp->icall(@args);
779 # a bit of complications only to allow stack trace, i.e. in case of errors
780 # user will get error pointing to his program and not in this module.
781 # and also 'after' tcl method makes bit harder
782  
783 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
784 0 my @res;
785 0 eval { @res = $interp->icall(@args); };
786 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
787 0 my $errmsg = $@; # 'require Carp' might destroy $@;
788 0 require Carp;
789 0 Carp::croak ("Tcl error '$errmsg' while invoking array result call:\n" .
790 "\t\"@args\"");
791 }
792 0 return @res;
793 } else {
794 0 my $res;
795 0 eval { $res = $interp->icall(@args); };
796 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
797 0 my $errmsg = $@; # 'require Carp' might destroy $@;
798 0 require Carp;
799 0 Carp::croak ("Tcl error '$errmsg' while invoking scalar result call:\n" .
800 "\t\"@args\"");
801 }
802 0 return $res;
803 }
804 }
805  
806 sub showcode{
807 0 ▶ return unless ($TRACE_SHOWCODE);
Subroutine showcode: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless $Tcl::TRACE_SHOWCODE 0 0 0
808 0 print 'TCL::TRACE_SHOWCODE:'.join(' ',@{$_[0]})."\n";
809 }
810  
811 # create_tcl_sub will create TCL sub that will invoke perl CODE ref
812 # If $events variable is specified then special processing will be
813 # performed to provide needed '%' variables.
814 # If $tclname is specified then procedure will have namely that name,
815 # otherwise it will have machine-readable name.
816 # Returns tcl script suitable for using in tcl events.
817 sub create_tcl_sub {
818 0 ▶ my ($interp,$sub,$events,$tclname, $rname) = @_;
Subroutine create_tcl_sub: not called CC=5 SCAR=34.0
819 # rnames and tclnames begining = or @ or ::perl:: are reserved for internal use
820 0 ▶ unless ($tclname) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tclname) 0 0 0
821 # stringify sub, becomes "CODE(0x######)" in ::perl namespace
822 0 $tclname = "::perl::$sub";
823 }
824  
825 #print STDERR "...=$rname\n";
826  
827 # the following is a bit more tricky than it seems to.
828 # because the whole intent of the Tcl:Cmdbase entries in %anon_refs hash is to have refcount
829 # of (possibly) anonymous sub that is happen to be passed,
830 # and, if passed for the same widget but arguments are same - then
831 # previous instance will be overwriten, and sub will be destroyed due
832 # to no reference count, and command table entry will also be destroyed during
833 # Tcl::Cmdbase::DESTROY
834  
835 0 ▶ unless (exists $anon_refs{$tclname}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $anon_refs{$tclname}) 0 0 0
836 0 $anon_refs{$tclname} = bless (
837 [[\$sub, $interp, $tclname,0]
838 ,{} # Tcl::Codes register here so they can get deleted
839 ],'Tcl::Cmdbase');
840 0 $interp->CreateCommand($tclname, $sub, undef, undef, 1);
841  
842 0 ▶ print "TCL::TRACE_CREATECOMMAND: $interp -> $rname ( $tclname => $sub ,undef,udef,1 )\n" if ($TRACE_CREATECOMMAND);
Branch: 1 branch
BranchTrueFalseTotal
if $Tcl::TRACE_CREATECOMMAND 0 0 0
843 0 delete $anon_refs{$rname};
844 }
845 0 my @newtcl=@{$anon_refs{$tclname}[0]};
846 0 pop @newtcl;
847 0 push @newtcl,$rname;
848  
849 0 bless( \@newtcl, 'Tcl::Code');
850 0 $anon_refs{$rname} = \@newtcl;
851 0 $anon_refs{$tclname}[0][3]++; # push ref ct
852 0 $anon_refs{$tclname}[1]{$rname}++; #register as user
853  
854 0 my $gencode = $tclname;
855  
856 0 ▶ if ($events) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events) 0 0 0
857 # Add any %-substitutions to callback
858 0 $gencode = "$tclname " . join(' ', @{$events});
859 }
860 0 return $tclname , $gencode; # return both the base and code-call
861 }
862  
863 sub _code_dispose {
864 0 ▶ my $k = shift;
Subroutine _code_dispose: not called CC=7 SCAR=40.3
865 0 ▶ return undef unless(exists $anon_refs{$k});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $anon_refs{$k} 0 0 0
866 0 my $ret = undef;
867 0 my $ref = ref($anon_refs{$k});
868 0 ▶ if ($ref eq 'Tcl::Code') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'Tcl::Code') { } 0 0 0
elsif ($ref eq 'Tcl::Cmdbase') { } 0 0 0
elsif ($ref eq 'ARRAY') { } 0 0 0
869 0 $ret = $anon_refs{$k}[0];
870 0 delete $anon_refs{$k};
871 }
872 elsif ($ref eq 'Tcl::Cmdbase') {
873 ## mainly for calling from exterior program when it is one that calls ($tclname)=create_tcl_sub().. too
874 0 my $atcl = $anon_refs{$k};
875 0 ▶ return undef unless ($atcl);
Branch: 1 branch
BranchTrueFalseTotal
unless $atcl 0 0 0
876 0 $ret = $atcl->[0][0];
877 0 my @keys=keys(%{$atcl->[1]});
878 0 for my $key (@keys) {
879 0 _code_dispose($key); # last one deletes me
880 }
881 0 delete $anon_refs{$k}; # but be sure
882 }
883 elsif ($ref eq 'ARRAY') {
884 0 my $atclarray = $anon_refs{$k};
885 0 $ret = $atclarray->[0][0]; # eh, return the first one, prob discarded anyway
886 0 delete $anon_refs{$k}; # bunch of Tcl::Code
887 }
888 0 return $$ret; # original delete_ref result, prob just discarded
889 }
890  
891 sub delete_ref {
892 0 ▶ my $interp = shift;
Subroutine delete_ref: not called CC=4 SCAR=30.0
893 0 my $name = shift;
894 0 my $iam = $anon_refs{$name};
895 0 my $ref = ref($iam);
896 0 ▶ if ($ref eq 'ARRAY') { return _code_dispose ($name);}
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'ARRAY') { } 0 0 0
elsif ($ref eq 'Tcl::Code') { } 0 0 0
elsif ($ref eq 'Tcl::Cmdbase') { } 0 0 0
897 0 elsif ($ref eq 'Tcl::Code') { return _code_dispose ($name);}
898 0 elsif ($ref eq 'Tcl::Cmdbase'){ return _code_dispose ($name);}
899 else { # these are the ties ??
900 0 $interp->UnsetVar($name); #TODO: will this delete variable in Tcl?
901 0 delete $anon_refs{$name};
902 0 untie $$iam;
903 0 return $iam;
904 }
905 }
906  
907 sub return_ref {
908 0 ▶ my $interp = shift;
Subroutine return_ref: not called CC=4 SCAR=30.0
909 0 my $name = shift;
910 0 my $iam = $anon_refs{$name};
911 0 my $ref = ref($iam);
912 0 ▶ if ($ref eq 'ARRAY') { return ${$iam->[0][0]};} # gotta pick one
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'ARRAY') { } 0 0 0
elsif ($ref eq 'Tcl::Code') { } 0 0 0
elsif ($ref eq 'Tcl::Cmdbase') { } 0 0 0
913 0 elsif ($ref eq 'Tcl::Code') { return ${$iam->[0]};}
914 0 elsif ($ref eq 'Tcl::Cmdbase'){ return ${$iam->[0][0]};}
915 0 return $anon_refs{$name};
916 }
917  
918 sub _code_clear {
919 # for testing
920 0 ▶ my $debug = shift;
Subroutine _code_clear: not called CC=13 SCAR=52.0
921 0 ▶ print "_code_clear ARRAY\n" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
922 0 for my $kk (keys %anon_refs) {
923 0 ▶ if (ref($anon_refs{$kk}) eq 'ARRAY'){ print "ARRAY $kk\n" if ($debug); delete $anon_refs{$kk};}
Branch: 2 branches
BranchTrueFalseTotal
if (ref $anon_refs{$kk} eq "ARRAY") 0 0 0
if $debug 0 0 0
924 }
925  
926 0 ▶ print "_code_clear Tcl::Code list\n" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
927 0 for my $kk (keys %anon_refs) {
928 0 ▶ if (ref($anon_refs{$kk}) eq 'Tcl::Code'){ print "Code $kk\n" if ($debug); delete $anon_refs{$kk};}
Branch: 2 branches
BranchTrueFalseTotal
if (ref $anon_refs{$kk} eq "Tcl::Code") 0 0 0
if $debug 0 0 0
929 }
930  
931 0 ▶ print "_code_clear Tcl::Cmdbase\n" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
932 0 for my $kk (keys %anon_refs) {
933 0 ▶ if (ref($anon_refs{$kk}) eq 'Tcl::Cmdbase'){ print "Code $kk\n" if ($debug); delete $anon_refs{$kk};}
Branch: 2 branches
BranchTrueFalseTotal
if (ref $anon_refs{$kk} eq "Tcl::Cmdbase") 0 0 0
if $debug 0 0 0
934 }
935 }
936  
937  
938 sub Ev {
939 0 ▶ my @events = @_;
Subroutine Ev: not called CC=1 SCAR=6.9
940 0 return bless \@events, "Tcl::Ev";
941 }
942  
943  
944 package Tcl::Code;
945  
946 # purpose is to track CODE REFs still "in use"
947 # (often these are anon subs)
948  
949 # each has ptr to the Tcl::Cmdbase entry that tracks the command table
950 # so to bless it to this package and then catch deleting it, so
951 # to do cleaning up
952  
953 sub DESTROY {
954 # my $rsub = $_[0]->[0]; # dont really need it here anymore,
955 # my $interp = $_[0]->[1];
956  
957 0 ▶ my $tclname = $_[0]->[2];
Subroutine DESTROY: not called CC=4 SCAR=30.0
958 0 my $rname = $_[0]->[3];
959 0 my $tclptr = $anon_refs{$tclname}->[0];
960  
961 0 ▶ return unless ($tclptr); # should exist but be safe
Branch: 1 branch
BranchTrueFalseTotal
unless $tclptr 0 0 0
962 0 $tclptr->[3]--;
963 0 ▶ unless($tclptr->[3]>0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tclptr->[3] > 0) { } 0 0 0
964 0 delete $anon_refs{$tclname}; # kill the Cmdbase
965 }
966 else {
967 0 $anon_refs{$tclname}->[1]{$rname}--;
968 0 ▶ unless ( $anon_refs{$tclname}->[1]{$rname}>0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($anon_refs{$tclname}[1]{$rname} > 0) 0 0 0
969 0 delete $anon_refs{$tclname}->[1]{$rname}; # unregister me
970 }
971 }
972 }
973  
974 package Tcl::Cmdbase;
975  
976 # only purpose is to track CODE REFs passed to 'call' method
977 # (often these are anon subs)
978 # so to bless it to this package and then catch deleting it, so
979 # to do cleaning up
980  
981 sub DESTROY {
982 # $_[0] points to a [Tcl::code,{$rname=>1,...}] set
983 0 ▶ my $interp = $_[0]->[0]->[1];
Subroutine DESTROY: not called CC=4 SCAR=30.0
984 0 my $tclname = $_[0]->[0]->[2];
985 0 ▶ return unless ($tclname);
Branch: 1 branch
BranchTrueFalseTotal
unless $tclname 0 0 0
986 0 ▶ if (defined $interp) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $interp) 0 0 0
987 0 $interp->DeleteCommand($tclname);
988 0 ▶ print "TCL::TRACE_DELETECOMMAND: $interp -> ( $tclname )\n" if ($Tcl::TRACE_DELETECOMMAND);
Branch: 1 branch
BranchTrueFalseTotal
if $Tcl::TRACE_DELETECOMMAND 0 0 0
989 }
990 }
991  
992 package Tcl::List;
993  
994 20 use overload '""' => \&as_string,
995 20 ▶ fallback => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
996  
997 package Tcl::Var;
998  
999 sub TIESCALAR {
1000 0 ▶ my $class = shift;
Subroutine TIESCALAR: not called CC=3 SCAR=24.8
1001 0 my @objdata = @_;
1002 0 ▶ unless (@_ == 2 || @_ == 3) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_ == 2 or @_ == 3) 0 0 0
Condition0%0/3
@_ == 2 or @_ == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@_ == 2 or @_ == 3
@_ == 2 @_ == 3
Truth table0%0/3
A or B
A= @_ == 2B= @_ == 3
ABresult
1X1
011
000
1003 0 require Carp;
1004 0 Carp::croak('Usage: tie $s, Tcl::Var, $interp, $varname [, $flags]');
1005 };
1006 0 bless \@objdata, $class;
1007 }
1008  
1009 sub TIEHASH {
1010 0 ▶ my $class = shift;
Subroutine TIEHASH: not called CC=3 SCAR=24.8
1011 0 my @objdata = @_;
1012 0 ▶ unless (@_ == 2 || @_ == 3) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_ == 2 or @_ == 3) 0 0 0
Condition0%0/3
@_ == 2 or @_ == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@_ == 2 or @_ == 3
@_ == 2 @_ == 3
Truth table0%0/3
A or B
A= @_ == 2B= @_ == 3
ABresult
1X1
011
000
1013 0 require Carp;
1014 0 Carp::croak('Usage: tie %hash, Tcl::Var, $interp, $varname [, $flags]');
1015 }
1016 0 bless \@objdata, $class;
1017 }
1018  
1019 my %arraystates;
1020 sub FIRSTKEY {
1021 0 ▶ my $obj = shift;
Subroutine FIRSTKEY: not called CC=4 SCAR=30.0
1022 0 die "STORE Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@_)"
1023 0 ▶ unless @{$obj} == 2 || @{$obj} == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$obj;} == 2 or @{$obj;} == 3 0 0 0
Condition0%0/3
@{$obj;} == 2 or @{$obj;} == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$obj;} == 2 or @{$obj;} == 3
@{$obj;} == 2 @{$obj;} == 3
Truth table0%0/3
A or B
A= @{$obj;} == 2B= @{$obj;} == 3
ABresult
1X1
011
000
1024 0 my ($interp, $varname, $flags) = @$obj;
1025 0 $arraystates{$varname} = $interp->invoke("array","startsearch",$varname);
1026 0 my $r = $interp->invoke("array","nextelement",$varname,$arraystates{$varname});
1027 0 ▶ if ($r eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "") 0 0 0
1028 0 delete $arraystates{$varname};
1029 0 return undef;
1030 }
1031 0 return $r;
1032 }
1033 sub NEXTKEY {
1034 0 ▶ my $obj = shift;
Subroutine NEXTKEY: not called CC=4 SCAR=30.0
1035 0 die "STORE Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@_)"
1036 0 ▶ unless @{$obj} == 2 || @{$obj} == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$obj;} == 2 or @{$obj;} == 3 0 0 0
Condition0%0/3
@{$obj;} == 2 or @{$obj;} == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$obj;} == 2 or @{$obj;} == 3
@{$obj;} == 2 @{$obj;} == 3
Truth table0%0/3
A or B
A= @{$obj;} == 2B= @{$obj;} == 3
ABresult
1X1
011
000
1037 0 my ($interp, $varname, $flags) = @$obj;
1038 0 my $r = $interp->invoke("array","nextelement",$varname,$arraystates{$varname});
1039 0 ▶ if ($r eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "") 0 0 0
1040 0 delete $arraystates{$varname};
1041 0 return undef;
1042 }
1043 0 return $r;
1044 }
1045 sub CLEAR {
1046 0 ▶ my $obj = shift;
Subroutine CLEAR: not called CC=3 SCAR=24.8
1047 0 die "STORE Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@_)"
1048 0 ▶ unless @{$obj} == 2 || @{$obj} == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$obj;} == 2 or @{$obj;} == 3 0 0 0
Condition0%0/3
@{$obj;} == 2 or @{$obj;} == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$obj;} == 2 or @{$obj;} == 3
@{$obj;} == 2 @{$obj;} == 3
Truth table0%0/3
A or B
A= @{$obj;} == 2B= @{$obj;} == 3
ABresult
1X1
011
000
1049 0 my ($interp, $varname, $flags) = @$obj;
1050 0 $interp->invoke("array", "unset", "$varname");
1051 #$interp->invoke("array", "set", "$varname", "");
1052 }
1053 sub DELETE {
1054 0 ▶ my $obj = shift;
Subroutine DELETE: not called CC=3 SCAR=24.8
1055 0 ▶ unless (@{$obj} == 2 || @{$obj} == 3) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$obj;} == 2 or @{$obj;} == 3) 0 0 0
Condition0%0/3
@{$obj;} == 2 or @{$obj;} == 3
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$obj;} == 2 or @{$obj;} == 3
@{$obj;} == 2 @{$obj;} == 3
Truth table0%0/3
A or B
A= @{$obj;} == 2B= @{$obj;} == 3
ABresult
1X1
011
000
1056 0 my @args = @_;
1057 0 require Carp;
1058 0 Carp::croak("STORE Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@args)");
1059 }
1060 0 my ($interp, $varname, $flags) = @{$obj};
1061 0 my ($str1) = @_;
1062 0 $interp->invoke("unset", "$varname($str1)"); # protect strings?
1063 }
1064  
1065 sub UNTIE {
1066 0 ▶ my $ref = shift;
Subroutine UNTIE: not called CC=1 SCAR=6.9
1067 #print STDERR "UNTIE:$ref(@_)\n";
1068 }
1069 sub DESTROY {
1070 0 ▶ my $ref = shift;
Subroutine DESTROY: not called CC=1 SCAR=6.9
1071 0 delete $anon_refs{$ref->[1]};
1072 }
1073  
1074 # This is the perl equiv to the C version, for reference
1075 #
1076 #sub STORE {
1077 # my $obj = shift;
1078 # croak "STORE Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@_)"
1079 # unless @{$obj} == 2 || @{$obj} == 3;
1080 # my ($interp, $varname, $flags) = @{$obj};
1081 # my ($str1, $str2) = @_;
1082 # if ($str2) {
1083 # $interp->SetVar2($varname, $str1, $str2, $flags);
1084 # } else {
1085 # $interp->SetVar($varname, $str1, $flags || 0);
1086 # }
1087 #}
1088 #
1089 #sub FETCH {
1090 # my $obj = shift;
1091 # croak "FETCH Usage: objdata @{$obj} $#{$obj}, not 2 or 3 (@_)"
1092 # unless @{$obj} == 2 || @{$obj} == 3;
1093 # my ($interp, $varname, $flags) = @{$obj};
1094 # my $key = shift;
1095 # if ($key) {
1096 # return $interp->GetVar2($varname, $key, $flags || 0);
1097 # } else {
1098 # return $interp->GetVar($varname, $flags || 0);
1099 # }
1100 #}
1101  
1102 package Tcl;
1103  
1104 =head1 Other Tcl interpreter methods
1105  
1106 =over 2
1107  
1108 =item export_to_tcl method
1109  
1110 An interpreter method, export_to_tcl, is used to expose a number of perl
1111 subroutines and variables all at once into tcl/tk.
1112  
1113 B<export_to_tcl> takes a hash as arguments, which represents named parameters,
1114 with following allowed values:
1115  
1116 =over 4
1117  
1118 =item B<namespace> => '...'
1119  
1120 tcl namespace, where commands and variables are to
1121 be created, defaults to 'perl'. If '' is specified - then global
1122 namespace is used. A possible '::' at end is stripped.
1123  
1124 =item B<subs> => { ... }
1125  
1126 anonymous hash of subs to be created in Tcl, in the form /tcl name/ => /code ref/
1127  
1128 =item B<vars> => { ... }
1129  
1130 anonymous hash of vars to be created in Tcl, in the form /tcl name/ => /code ref/
1131  
1132 =item B<subs_from> => '...'
1133  
1134 a name of Perl namespace, from where all existing subroutines will be searched
1135 and Tcl command will be created for each of them.
1136  
1137 =item B<vars_from> => '...'
1138  
1139 a name of Perl namespace, from where all existing variables will be searched,
1140 and each such variable will be tied to Tcl.
1141  
1142 =back
1143  
1144 An example:
1145  
1146 use strict;
1147 use Tcl;
1148  
1149 my $int = Tcl->new;
1150  
1151 $tcl::foo = 'qwerty';
1152 $int->export_to_tcl(subs_from=>'tcl',vars_from=>'tcl');
1153  
1154 $int->Eval(<<'EOS');
1155 package require Tk
1156  
1157 button .b1 -text {a fluffy button} -command perl::fluffy_sub
1158 button .b2 -text {a foo button} -command perl::foo
1159 entry .e -textvariable perl::foo
1160 pack .b1 .b2 .e
1161 focus .b2
1162  
1163 tkwait window .
1164 EOS
1165  
1166 sub tcl::fluffy_sub {
1167 print "Hi, I am a fluffy sub\n";
1168 }
1169 sub tcl::foo {
1170 print "Hi, I am foo\n";
1171 $tcl::foo++;
1172 }
1173  
1174 =cut
1175  
1176 sub export_to_tcl {
1177 0 ▶ my $int = shift;
Subroutine export_to_tcl: not called CC=15 SCAR=52.3
1178 0 my %args = @_;
1179  
1180 # name of Tcl package to hold tcl commands bound to perl subroutines
1181 0 ▶ my $tcl_namespace = (exists $args{namespace} ? $args{namespace} : 'perl::');
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'namespace'} ? : 0 0 0
1182 0 $tcl_namespace=~s/(?:::)?$/::/;
1183  
1184 # a batch of perl subroutines which tcl counterparts should be created
1185 0 ▶ my $subs = $args{subs} || {};
Condition0%0/2
$args{'subs'} || {}
l!l
00
MC/DC0%0/1
$args{'subs'} || {}
$args{'subs'}
Truth table0%0/2
A
A= $args{'subs'}
Aresult
11
00
1186  
1187 # a batch of perl variables which tcl counterparts should be created
1188 0 ▶ my $vars = $args{vars} || {};
Condition0%0/2
$args{'vars'} || {}
l!l
00
MC/DC0%0/1
$args{'vars'} || {}
$args{'vars'}
Truth table0%0/2
A
A= $args{'vars'}
Aresult
11
00
1189  
1190 # TBD:
1191 # only => \@list_of_names
1192 # argument to be able to limit the names to export to Tcl.
1193  
1194 0 ▶ if (exists $args{subs_from}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"subs_from"}) 0 0 0
1195 # name of Perl package, which subroutines would be bound to tcl commands
1196 0 my $subs_from = $args{subs_from};
1197 0 $subs_from =~ s/::$//;
1198 20 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1199 0 for my $name (keys %{"$subs_from\::"}) {
1200 #print STDERR "$name;\n";
1201 0 ▶ if (defined &{"$subs_from\::$name"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined &{"${subs_from}::$name";}) 0 0 0
1202 0 ▶ if (exists $subs->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $subs->{$name}) 0 0 0
1203 0 next;
1204 }
1205 #print STDERR "binding sub '$name'\n";
1206 0 $int->CreateCommand("$tcl_namespace$name", \&{"$subs_from\::$name"}, undef, undef, 1);
1207 }
1208 }
1209 }
1210 0 ▶ if (exists $args{vars_from}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"vars_from"}) 0 0 0
1211 # name of Perl package, which subroutines would be bound to tcl commands
1212 0 my $vars_from = $args{vars_from};
1213 0 $vars_from =~ s/::$//;
1214 20 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1215 0 for my $name (keys %{"$vars_from\::"}) {
1216 #print STDERR "$name;\n";
1217 0 ▶ if (defined ${"$vars_from\::$name"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined ${"${vars_from}::$name";}) 0 0 0
1218 0 ▶ if (exists $vars->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $vars->{$name}) 0 0 0
1219 0 next;
1220 }
1221 #print STDERR "binding var '$name' in '$tcl_namespace'\n";
1222 0 local $_ = ${"$vars_from\::$name"};
1223 0 tie ${"$vars_from\::$name"}, 'Tcl::Var', $int, "$tcl_namespace$name";
1224 0 ${"$vars_from\::$name"} = $_;
1225 }
1226 0 if (0) {
1227 # array, hash - no need to do anything.
1228 # (or should we?)
1229 }
1230 }
1231 }
1232  
1233 0 for my $subname (keys %$subs) {
1234 #print STDERR "binding2 sub '$subname'\n";
1235 0 $int->CreateCommand("$tcl_namespace$subname",$subs->{$subname}, undef, undef, 1);
1236 }
1237  
1238 0 for my $varname (keys %$vars) {
1239 #print STDERR "binding2 var '$varname'\n";
1240 0 ▶ unless (ref($vars->{$varname})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $vars->{$varname}) 0 0 0
1241 0 require 'Carp.pm';
1242 0 Carp::croak("should pass var ref as variable bind parameter");
1243 }
1244 0 local $_ = ${$vars->{$varname}};
1245 0 tie ${$vars->{$varname}}, 'Tcl::Var', $int, "$tcl_namespace$varname";
1246 0 ${$vars->{$varname}} = $_;
1247 }
1248 }
1249  
1250 =item B<export_tcl_namespace>
1251  
1252 extra convenience sub, binds to tcl all subs and vars from perl B<tcl::> namespace
1253  
1254 =back
1255  
1256 =cut
1257  
1258 sub export_tcl_namespace {
1259 0 ▶ my $int = shift;
Subroutine export_tcl_namespace: not called CC=1 SCAR=6.9
1260 0 $int->export_to_tcl(subs_from=>'tcl', vars_from=>'tcl');
1261 }
1262  
1263 =head1 AUTHORS
1264  
1265 Malcolm Beattie, 23 Oct 1994
1266 Vadim Konovalov, 19 May 2003
1267 Jeff Hobbs, jeff (a) activestate . com, 22 Mar 2004
1268 Gisle Aas, gisle (a) activestate . com, 14 Apr 2004
1269  
1270 Special thanks for contributions to Jan Dubois, Slaven Rezic, Paul Cochrane,
1271 Huck Finn, Christopher Chavez, SJ Luo.
1272  
1273 =head1 COPYRIGHT
1274  
1275 This program is free software; you can redistribute it and/or modify it under
1276 the same terms as Perl itself.
1277  
1278 See http://www.perl.com/perl/misc/Artistic.html
1279  
1280 =cut
1281  
1282 #use Data::Dumper; print Dumper(\@codes)."codes \n ";
1283  
1284 1;
↑ Summary Tcl.xs »