Debian Codegraph @

library/auto.tcl

raw
1 # auto.tcl --
2 #
3 # utility procs formerly in init.tcl dealing with auto execution of commands
4 # and can be auto loaded themselves.
5 #
6 # Copyright (c) 1991-1993 The Regents of the University of California.
7 # Copyright (c) 1994-1998 Sun Microsystems, Inc.
8 #
9 # See the file "license.terms" for information on usage and redistribution of
10 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 #
12
13 # auto_reset --
14 #
15 # Destroy all cached information for auto-loading and auto-execution, so that
16 # the information gets recomputed the next time it's needed. Also delete any
17 # commands that are listed in the auto-load index.
18 #
19 # Arguments:
20 # None.
21
22 proc auto_reset {} {
23 global auto_execs auto_index auto_path
24 if {[array exists auto_index]} {
25 foreach cmdName [array names auto_index] {
26 set fqcn [namespace which $cmdName]
27 if {$fqcn eq ""} {
28 continue
29 }
30 rename $fqcn {}
31 }
32 }
33 unset -nocomplain auto_execs auto_index ::tcl::auto_oldpath
34 if {[catch {llength $auto_path}]} {
35 set auto_path [list [info library]]
36 } elseif {[info library] ni $auto_path} {
37 lappend auto_path [info library]
38 }
39 }
40
41 # tcl_findLibrary --
42 #
43 # This is a utility for extensions that searches for a library directory
44 # using a canonical searching algorithm. A side effect is to source the
45 # initialization script and set a global library variable.
46 #
47 # Arguments:
48 # basename Prefix of the directory name, (e.g., "tk")
49 # version Version number of the package, (e.g., "8.0")
50 # patch Patchlevel of the package, (e.g., "8.0.3")
51 # initScript Initialization script to source (e.g., tk.tcl)
52 # enVarName environment variable to honor (e.g., TK_LIBRARY)
53 # varName Global variable to set when done (e.g., tk_library)
54
55 proc tcl_findLibrary {basename version patch initScript enVarName varName} {
56 upvar #0 $varName the_library
57 global auto_path env tcl_platform
58
59 set dirs {}
60 set errors {}
61
62 # The C application may have hardwired a path, which we honor
63
64 if {[info exists the_library] && $the_library ne ""} {
65 lappend dirs $the_library
66 } else {
67 # Do the canonical search
68
69 # 1. From an environment variable, if it exists. Placing this first
70 # gives the end-user ultimate control to work-around any bugs, or
71 # to customize.
72
73 if {[info exists env($enVarName)]} {
74 lappend dirs $env($enVarName)
75 }
76
77 # 2. In the package script directory registered within the
78 # configuration of the package itself.
79
80 catch {
81 lappend dirs [::${basename}::pkgconfig get scriptdir,runtime]
82 }
83
84 # 3. Relative to auto_path directories. This checks relative to the
85 # Tcl library as well as allowing loading of libraries added to the
86 # auto_path that is not relative to the core library or binary paths.
87 foreach d $auto_path {
88 lappend dirs [file join $d $basename$version]
89 if {$tcl_platform(platform) eq "unix"
90 && $tcl_platform(os) eq "Darwin"} {
91 # 4. On MacOSX, check the Resources/Scripts subdir too
92 lappend dirs [file join $d $basename$version Resources Scripts]
93 }
94 }
95
96 # 3. Various locations relative to the executable
97 # ../lib/foo1.0 (From bin directory in install hierarchy)
98 # ../../lib/foo1.0 (From bin/arch directory in install hierarchy)
99 # ../library (From unix directory in build hierarchy)
100 #
101 # Remaining locations are out of date (when relevant, they ought to be
102 # covered by the $::auto_path seach above) and disabled.
103 #
104 # ../../library (From unix/arch directory in build hierarchy)
105 # ../../foo1.0.1/library
106 # (From unix directory in parallel build hierarchy)
107 # ../../../foo1.0.1/library
108 # (From unix/arch directory in parallel build hierarchy)
109
110 set parentDir [file dirname [file dirname [info nameofexecutable]]]
111 set grandParentDir [file dirname $parentDir]
112 lappend dirs [file join $parentDir lib $basename$version]
113 lappend dirs [file join $grandParentDir lib $basename$version]
114 lappend dirs [file join $parentDir library]
115 if {0} {
116 lappend dirs [file join $grandParentDir library]
117 lappend dirs [file join $grandParentDir $basename$patch library]
118 lappend dirs [file join [file dirname $grandParentDir] \
119 $basename$patch library]
120 }
121 }
122 # make $dirs unique, preserving order
123 array set seen {}
124 foreach i $dirs {
125 # Make sure $i is unique under normalization. Avoid repeated [source].
126 if {[interp issafe]} {
127 # Safe interps have no [file normalize].
128 set norm $i
129 } else {
130 set norm [file normalize $i]
131 }
132 if {[info exists seen($norm)]} {
133 continue
134 }
135 set seen($norm) {}
136
137 set the_library $i
138 set file [file join $i $initScript]
139
140 # source everything when in a safe interpreter because we have a
141 # source command, but no file exists command
142
143 if {[interp issafe] || [file exists $file]} {
144 if {![catch {uplevel #0 [list source -encoding utf-8 $file]} msg opts]} {
145 return
146 }
147 append errors "$file: $msg\n"
148 append errors [dict get $opts -errorinfo]\n
149 }
150 }
151 unset -nocomplain the_library
152 set msg "Can't find a usable $initScript in the following directories: \n"
153 append msg " $dirs\n\n"
154 append msg "$errors\n\n"
155 append msg "This probably means that $basename wasn't installed properly.\n"
156 error $msg
157 }
158
159
160 # ----------------------------------------------------------------------
161 # auto_mkindex
162 # ----------------------------------------------------------------------
163 # The following procedures are used to generate the tclIndex file from Tcl
164 # source files. They use a special safe interpreter to parse Tcl source
165 # files, writing out index entries as "proc" commands are encountered. This
166 # implementation won't work in a safe interpreter, since a safe interpreter
167 # can't create the special parser and mess with its commands.
168
169 if {[interp issafe]} {
170 return ;# Stop sourcing the file here
171 }
172
173 # auto_mkindex --
174 # Regenerate a tclIndex file from Tcl source files. Takes as argument the
175 # name of the directory in which the tclIndex file is to be placed, followed
176 # by any number of glob patterns to use in that directory to locate all of the
177 # relevant files.
178 #
179 # Arguments:
180 # dir - Name of the directory in which to create an index.
181
182 # args - Any number of additional arguments giving the names of files
183 # within dir. If no additional are given auto_mkindex will look
184 # for *.tcl.
185
186 proc auto_mkindex {dir args} {
187 if {[interp issafe]} {
188 error "can't generate index within safe interpreter"
189 }
190
191 set oldDir [pwd]
192 cd $dir
193
194 append index "# Tcl autoload index file, version 2.0\n"
195 append index "# This file is generated by the \"auto_mkindex\" command\n"
196 append index "# and sourced to set up indexing information for one or\n"
197 append index "# more commands. Typically each line is a command that\n"
198 append index "# sets an element in the auto_index array, where the\n"
199 append index "# element name is the name of a command and the value is\n"
200 append index "# a script that loads the command.\n\n"
201 if {![llength $args]} {
202 set args *.tcl
203 }
204
205 auto_mkindex_parser::init
206 foreach file [lsort [glob -- {*}$args]] {
207 try {
208 append index [auto_mkindex_parser::mkindex $file]
209 } on error {msg opts} {
210 cd $oldDir
211 return -options $opts $msg
212 }
213 }
214 auto_mkindex_parser::cleanup
215
216 set fid [open "tclIndex" w]
217 fconfigure $fid -encoding utf-8
218 puts -nonewline $fid $index
219 close $fid
220 cd $oldDir
221 }
222
223 # Original version of auto_mkindex that just searches the source code for
224 # "proc" at the beginning of the line.
225
226 proc auto_mkindex_old {dir args} {
227 set oldDir [pwd]
228 cd $dir
229 set dir [pwd]
230 append index "# Tcl autoload index file, version 2.0\n"
231 append index "# This file is generated by the \"auto_mkindex\" command\n"
232 append index "# and sourced to set up indexing information for one or\n"
233 append index "# more commands. Typically each line is a command that\n"
234 append index "# sets an element in the auto_index array, where the\n"
235 append index "# element name is the name of a command and the value is\n"
236 append index "# a script that loads the command.\n\n"
237 if {![llength $args]} {
238 set args *.tcl
239 }
240 foreach file [lsort [glob -- {*}$args]] {
241 set f ""
242 set error [catch {
243 set f [open $file]
244 fconfigure $f -eofchar "\x1A {}"
245 while {[gets $f line] >= 0} {
246 if {[regexp {^proc[ ]+([^ ]*)} $line match procName]} {
247 set procName [lindex [auto_qualify $procName "::"] 0]
248 append index "set [list auto_index($procName)]"
249 append index " \[list source -encoding utf-8 \[file join \$dir [list $file]\]\]\n"
250 }
251 }
252 close $f
253 } msg opts]
254 if {$error} {
255 catch {close $f}
256 cd $oldDir
257 return -options $opts $msg
258 }
259 }
260 set f ""
261 set error [catch {
262 set f [open tclIndex w]
263 puts -nonewline $f $index
264 close $f
265 cd $oldDir
266 } msg opts]
267 if {$error} {
268 catch {close $f}
269 cd $oldDir
270 error $msg $info $code
271 return -options $opts $msg
272 }
273 }
274
275 # Create a safe interpreter that can be used to parse Tcl source files
276 # generate a tclIndex file for autoloading. This interp contains commands for
277 # things that need index entries. Each time a command is executed, it writes
278 # an entry out to the index file.
279
280 namespace eval auto_mkindex_parser {
281 variable parser "" ;# parser used to build index
282 variable index "" ;# maintains index as it is built
283 variable scriptFile "" ;# name of file being processed
284 variable contextStack "" ;# stack of namespace scopes
285 variable imports "" ;# keeps track of all imported cmds
286 variable initCommands ;# list of commands that create aliases
287 if {![info exists initCommands]} {
288 set initCommands [list]
289 }
290
291 proc init {} {
292 variable parser
293 variable initCommands
294
295 if {![interp issafe]} {
296 set parser [interp create -safe]
297 $parser hide info
298 $parser hide rename
299 $parser hide proc
300 $parser hide namespace
301 $parser hide eval
302 $parser hide puts
303 foreach ns [$parser invokehidden namespace children ::] {
304 # MUST NOT DELETE "::tcl" OR BAD THINGS HAPPEN!
305 if {$ns eq "::tcl"} continue
306 $parser invokehidden namespace delete $ns
307 }
308 foreach cmd [$parser invokehidden info commands ::*] {
309 $parser invokehidden rename $cmd {}
310 }
311 $parser invokehidden proc unknown {args} {}
312
313 # We'll need access to the "namespace" command within the
314 # interp. Put it back, but move it out of the way.
315
316 $parser expose namespace
317 $parser invokehidden rename namespace _%@namespace
318 $parser expose eval
319 $parser invokehidden rename eval _%@eval
320
321 # Install all the registered pseudo-command implementations
322
323 foreach cmd $initCommands {
324 eval $cmd
325 }
326 }
327 }
328 proc cleanup {} {
329 variable parser
330 interp delete $parser
331 unset parser
332 }
333 }
334
335 # auto_mkindex_parser::mkindex --
336 #
337 # Used by the "auto_mkindex" command to create a "tclIndex" file for the given
338 # Tcl source file. Executes the commands in the file, and handles things like
339 # the "proc" command by adding an entry for the index file. Returns a string
340 # that represents the index file.
341 #
342 # Arguments:
343 # file Name of Tcl source file to be indexed.
344
345 proc auto_mkindex_parser::mkindex {file} {
346 variable parser
347 variable index
348 variable scriptFile
349 variable contextStack
350 variable imports
351
352 set scriptFile $file
353
354 set fid [open $file]
355 fconfigure $fid -eofchar "\x1A {}"
356 set contents [read $fid]
357 close $fid
358
359 # There is one problem with sourcing files into the safe interpreter:
360 # references like "$x" will fail since code is not really being executed
361 # and variables do not really exist. To avoid this, we replace all $ with
362 # \0 (literally, the null char) later, when getting proc names we will
363 # have to reverse this replacement, in case there were any $ in the proc
364 # name. This will cause a problem if somebody actually tries to have a \0
365 # in their proc name. Too bad for them.
366 set contents [string map [list \$ \0] $contents]
367
368 set index ""
369 set contextStack ""
370 set imports ""
371
372 $parser eval $contents
373
374 foreach name $imports {
375 catch {$parser eval [list _%@namespace forget $name]}
376 }
377 return $index
378 }
379
380 # auto_mkindex_parser::hook command
381 #
382 # Registers a Tcl command to evaluate when initializing the child interpreter
383 # used by the mkindex parser. The command is evaluated in the parent
384 # interpreter, and can use the variable auto_mkindex_parser::parser to get to
385 # the child
386
387 proc auto_mkindex_parser::hook {cmd} {
388 variable initCommands
389
390 lappend initCommands $cmd
391 }
392
393 # auto_mkindex_parser::slavehook command
394 #
395 # Registers a Tcl command to evaluate when initializing the child interpreter
396 # used by the mkindex parser. The command is evaluated in the child
397 # interpreter.
398
399 proc auto_mkindex_parser::slavehook {cmd} {
400 variable initCommands
401
402 # The $parser variable is defined to be the name of the child interpreter
403 # when this command is used later.
404
405 lappend initCommands "\$parser eval [list $cmd]"
406 }
407
408 # auto_mkindex_parser::command --
409 #
410 # Registers a new command with the "auto_mkindex_parser" interpreter that
411 # parses Tcl files. These commands are fake versions of things like the
412 # "proc" command. When you execute them, they simply write out an entry to a
413 # "tclIndex" file for auto-loading.
414 #
415 # This procedure allows extensions to register their own commands with the
416 # auto_mkindex facility. For example, a package like [incr Tcl] might
417 # register a "class" command so that class definitions could be added to a
418 # "tclIndex" file for auto-loading.
419 #
420 # Arguments:
421 # name Name of command recognized in Tcl files.
422 # arglist Argument list for command.
423 # body Implementation of command to handle indexing.
424
425 proc auto_mkindex_parser::command {name arglist body} {
426 hook [list auto_mkindex_parser::commandInit $name $arglist $body]
427 }
428
429 # auto_mkindex_parser::commandInit --
430 #
431 # This does the actual work set up by auto_mkindex_parser::command. This is
432 # called when the interpreter used by the parser is created.
433 #
434 # Arguments:
435 # name Name of command recognized in Tcl files.
436 # arglist Argument list for command.
437 # body Implementation of command to handle indexing.
438
439 proc auto_mkindex_parser::commandInit {name arglist body} {
440 variable parser
441
442 set ns [namespace qualifiers $name]
443 set tail [namespace tail $name]
444 if {$ns eq ""} {
445 set fakeName [namespace current]::_%@fake_$tail
446 } else {
447 set fakeName [namespace current]::[string map {:: _} _%@fake_$name]
448 }
449 proc $fakeName $arglist $body
450
451 # YUK! Tcl won't let us alias fully qualified command names, so we can't
452 # handle names like "::itcl::class". Instead, we have to build procs with
453 # the fully qualified names, and have the procs point to the aliases.
454
455 if {[string match *::* $name]} {
456 set exportCmd [list _%@namespace export [namespace tail $name]]
457 $parser eval [list _%@namespace eval $ns $exportCmd]
458
459 # The following proc definition does not work if you want to tolerate
460 # space or something else diabolical in the procedure name, (i.e.,
461 # space in $alias). The following does not work:
462 # "_%@eval {$alias} \$args"
463 # because $alias gets concat'ed to $args. The following does not work
464 # because $cmd is somehow undefined
465 # "set cmd {$alias} \; _%@eval {\$cmd} \$args"
466 # A gold star to someone that can make test autoMkindex-3.3 work
467 # properly
468
469 set alias [namespace tail $fakeName]
470 $parser invokehidden proc $name {args} "_%@eval {$alias} \$args"
471 $parser alias $alias $fakeName
472 } else {
473 $parser alias $name $fakeName
474 }
475 return
476 }
477
478 # auto_mkindex_parser::fullname --
479 #
480 # Used by commands like "proc" within the auto_mkindex parser. Returns the
481 # qualified namespace name for the "name" argument. If the "name" does not
482 # start with "::", elements are added from the current namespace stack to
483 # produce a qualified name. Then, the name is examined to see whether or not
484 # it should really be qualified. If the name has more than the leading "::",
485 # it is returned as a fully qualified name. Otherwise, it is returned as a
486 # simple name. That way, the Tcl autoloader will recognize it properly.
487 #
488 # Arguments:
489 # name - Name that is being added to index.
490
491 proc auto_mkindex_parser::fullname {name} {
492 variable contextStack
493
494 if {![string match ::* $name]} {
495 foreach ns $contextStack {
496 set name "${ns}::$name"
497 if {[string match ::* $name]} {
498 break
499 }
500 }
501 }
502
503 if {[namespace qualifiers $name] eq ""} {
504 set name [namespace tail $name]
505 } elseif {![string match ::* $name]} {
506 set name "::$name"
507 }
508
509 # Earlier, mkindex replaced all $'s with \0. Now, we have to reverse that
510 # replacement.
511 return [string map [list \0 \$] $name]
512 }
513
514 # auto_mkindex_parser::indexEntry --
515 #
516 # Used by commands like "proc" within the auto_mkindex parser to add a
517 # correctly-quoted entry to the index. This is shared code so it is done
518 # *right*, in one place.
519 #
520 # Arguments:
521 # name - Name that is being added to index.
522
523 proc auto_mkindex_parser::indexEntry {name} {
524 variable index
525 variable scriptFile
526
527 # We convert all metacharacters to their backslashed form, and pre-split
528 # the file name that we know about (which will be a proper list, and so
529 # correctly quoted).
530
531 set name [string range [list \}[fullname $name]] 2 end]
532 set filenameParts [file split $scriptFile]
533
534 append index [format \
535 {set auto_index(%s) [list source -encoding utf-8 [file join $dir %s]]%s} \
536 $name $filenameParts \n]
537 return
538 }
539
540 if {[llength $::auto_mkindex_parser::initCommands]} {
541 return
542 }
543
544 # Register all of the procedures for the auto_mkindex parser that will build
545 # the "tclIndex" file.
546
547 # AUTO MKINDEX: proc name arglist body
548 # Adds an entry to the auto index list for the given procedure name.
549
550 auto_mkindex_parser::command proc {name args} {
551 indexEntry $name
552 }
553
554 # Conditionally add support for Tcl byte code files. There are some tricky
555 # details here. First, we need to get the tbcload library initialized in the
556 # current interpreter. We cannot load tbcload into the child until we have
557 # done so because it needs access to the tcl_patchLevel variable. Second,
558 # because the package index file may defer loading the library until we invoke
559 # a command, we need to explicitly invoke auto_load to force it to be loaded.
560 # This should be a noop if the package has already been loaded
561
562 auto_mkindex_parser::hook {
563 try {
564 package require tbcload
565 } on error {} {
566 # OK, don't have it so do nothing
567 } on ok {} {
568 if {[namespace which -command tbcload::bcproc] eq ""} {
569 auto_load tbcload::bcproc
570 }
571 load {} tbcload $auto_mkindex_parser::parser
572
573 # AUTO MKINDEX: tbcload::bcproc name arglist body
574 # Adds an entry to the auto index list for the given precompiled
575 # procedure name.
576
577 auto_mkindex_parser::commandInit tbcload::bcproc {name args} {
578 indexEntry $name
579 }
580 }
581 }
582
583 # AUTO MKINDEX: namespace eval name command ?arg arg...?
584 # Adds the namespace name onto the context stack and evaluates the associated
585 # body of commands.
586 #
587 # AUTO MKINDEX: namespace import ?-force? pattern ?pattern...?
588 # Performs the "import" action in the parser interpreter. This is important
589 # for any commands contained in a namespace that affect the index. For
590 # example, a script may say "itcl::class ...", or it may import "itcl::*" and
591 # then say "class ...". This procedure does the import operation, but keeps
592 # track of imported patterns so we can remove the imports later.
593
594 auto_mkindex_parser::command namespace {op args} {
595 switch -- $op {
596 eval {
597 variable parser
598 variable contextStack
599
600 set name [lindex $args 0]
601 set args [lrange $args 1 end]
602
603 set contextStack [linsert $contextStack 0 $name]
604 $parser eval [list _%@namespace eval $name] $args
605 set contextStack [lrange $contextStack 1 end]
606 }
607 import {
608 variable parser
609 variable imports
610 foreach pattern $args {
611 if {$pattern ne "-force"} {
612 lappend imports $pattern
613 }
614 }
615 catch {$parser eval "_%@namespace import $args"}
616 }
617 ensemble {
618 variable parser
619 variable contextStack
620 if {[lindex $args 0] eq "create"} {
621 set name ::[join [lreverse $contextStack] ::]
622 catch {
623 set name [dict get [lrange $args 1 end] -command]
624 if {![string match ::* $name]} {
625 set name ::[join [lreverse $contextStack] ::]$name
626 }
627 regsub -all ::+ $name :: name
628 }
629 # create artificial proc to force an entry in the tclIndex
630 $parser eval [list ::proc $name {} {}]
631 }
632 }
633 }
634 }
635
636 # AUTO MKINDEX: oo::class create name ?definition?
637 # Adds an entry to the auto index list for the given class name.
638 auto_mkindex_parser::command oo::class {op name {body ""}} {
639 if {$op eq "create"} {
640 indexEntry $name
641 }
642 }
643 auto_mkindex_parser::command class {op name {body ""}} {
644 if {$op eq "create"} {
645 indexEntry $name
646 }
647 }
648
649 return