3 # utility procs formerly in init.tcl dealing with auto execution of commands
4 # and can be auto loaded themselves.
6 # Copyright (c) 1991-1993 The Regents of the University of California.
7 # Copyright (c) 1994-1998 Sun Microsystems, Inc.
9 # See the file "license.terms" for information on usage and redistribution of
10 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
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.
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]
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]
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.
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)
55 proc tcl_findLibrary {basename version patch initScript enVarName varName} {
56 upvar #0 $varName the_library
57 global auto_path env tcl_platform
62 # The C application may have hardwired a path, which we honor
64 if {[info exists the_library] && $the_library ne ""} {
65 lappend dirs $the_library
67 # Do the canonical search
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
73 if {[info exists env($enVarName)]} {
74 lappend dirs $env($enVarName)
77 # 2. In the package script directory registered within the
78 # configuration of the package itself.
81 lappend dirs [::${basename}::pkgconfig get scriptdir,runtime]
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]
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)
101 # Remaining locations are out of date (when relevant, they ought to be
102 # covered by the $::auto_path seach above) and disabled.
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)
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]
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]
122 # uniquify $dirs in order
125 # Take note that the [file normalize] below has been noted to cause
126 # difficulties for the freewrap utility. See Bug 1072136. Until
127 # freewrap resolves the matter, one might work around the problem by
128 # disabling that branch.
129 if {[interp issafe]} {
132 set norm [file normalize $i]
134 if {[info exists seen($norm)]} {
143 set file [file join $i $initScript]
145 # source everything when in a safe interpreter because we have a
146 # source command, but no file exists command
148 if {[interp issafe] || [file exists $file]} {
149 if {![catch {uplevel #0 [list source $file]} msg opts]} {
152 append errors "$file: $msg\n"
153 append errors [dict get $opts -errorinfo]\n
156 unset -nocomplain the_library
157 set msg "Can't find a usable $initScript in the following directories: \n"
158 append msg " $dirs\n\n"
159 append msg "$errors\n\n"
160 append msg "This probably means that $basename wasn't installed properly.\n"
165 # ----------------------------------------------------------------------
167 # ----------------------------------------------------------------------
168 # The following procedures are used to generate the tclIndex file from Tcl
169 # source files. They use a special safe interpreter to parse Tcl source
170 # files, writing out index entries as "proc" commands are encountered. This
171 # implementation won't work in a safe interpreter, since a safe interpreter
172 # can't create the special parser and mess with its commands.
174 if {[interp issafe]} {
175 return ;# Stop sourcing the file here
179 # Regenerate a tclIndex file from Tcl source files. Takes as argument the
180 # name of the directory in which the tclIndex file is to be placed, followed
181 # by any number of glob patterns to use in that directory to locate all of the
185 # dir - Name of the directory in which to create an index.
187 # args - Any number of additional arguments giving the names of files
188 # within dir. If no additional are given auto_mkindex will look
191 proc auto_mkindex {dir args} {
192 if {[interp issafe]} {
193 error "can't generate index within safe interpreter"
199 append index "# Tcl autoload index file, version 2.0\n"
200 append index "# This file is generated by the \"auto_mkindex\" command\n"
201 append index "# and sourced to set up indexing information for one or\n"
202 append index "# more commands. Typically each line is a command that\n"
203 append index "# sets an element in the auto_index array, where the\n"
204 append index "# element name is the name of a command and the value is\n"
205 append index "# a script that loads the command.\n\n"
206 if {![llength $args]} {
210 auto_mkindex_parser::init
211 foreach file [glob -- {*}$args] {
213 append index [auto_mkindex_parser::mkindex $file]
214 } on error {msg opts} {
216 return -options $opts $msg
219 auto_mkindex_parser::cleanup
221 set fid [open "tclIndex" w]
222 puts -nonewline $fid $index
227 # Original version of auto_mkindex that just searches the source code for
228 # "proc" at the beginning of the line.
230 proc auto_mkindex_old {dir args} {
234 append index "# Tcl autoload index file, version 2.0\n"
235 append index "# This file is generated by the \"auto_mkindex\" command\n"
236 append index "# and sourced to set up indexing information for one or\n"
237 append index "# more commands. Typically each line is a command that\n"
238 append index "# sets an element in the auto_index array, where the\n"
239 append index "# element name is the name of a command and the value is\n"
240 append index "# a script that loads the command.\n\n"
241 if {![llength $args]} {
244 foreach file [glob -- {*}$args] {
248 while {[gets $f line] >= 0} {
249 if {[regexp {^proc[ ]+([^ ]*)} $line match procName]} {
250 set procName [lindex [auto_qualify $procName "::"] 0]
251 append index "set [list auto_index($procName)]"
252 append index " \[list source \[file join \$dir [list $file]\]\]\n"
260 return -options $opts $msg
265 set f [open tclIndex w]
266 puts -nonewline $f $index
273 error $msg $info $code
274 return -options $opts $msg
278 # Create a safe interpreter that can be used to parse Tcl source files
279 # generate a tclIndex file for autoloading. This interp contains commands for
280 # things that need index entries. Each time a command is executed, it writes
281 # an entry out to the index file.
283 namespace eval auto_mkindex_parser {
284 variable parser "" ;# parser used to build index
285 variable index "" ;# maintains index as it is built
286 variable scriptFile "" ;# name of file being processed
287 variable contextStack "" ;# stack of namespace scopes
288 variable imports "" ;# keeps track of all imported cmds
289 variable initCommands ;# list of commands that create aliases
290 if {![info exists initCommands]} {
291 set initCommands [list]
296 variable initCommands
298 if {![interp issafe]} {
299 set parser [interp create -safe]
303 $parser hide namespace
306 foreach ns [$parser invokehidden namespace children ::] {
307 # MUST NOT DELETE "::tcl" OR BAD THINGS HAPPEN!
308 if {$ns eq "::tcl"} continue
309 $parser invokehidden namespace delete $ns
311 foreach cmd [$parser invokehidden info commands ::*] {
312 $parser invokehidden rename $cmd {}
314 $parser invokehidden proc unknown {args} {}
316 # We'll need access to the "namespace" command within the
317 # interp. Put it back, but move it out of the way.
319 $parser expose namespace
320 $parser invokehidden rename namespace _%@namespace
322 $parser invokehidden rename eval _%@eval
324 # Install all the registered psuedo-command implementations
326 foreach cmd $initCommands {
333 interp delete $parser
338 # auto_mkindex_parser::mkindex --
340 # Used by the "auto_mkindex" command to create a "tclIndex" file for the given
341 # Tcl source file. Executes the commands in the file, and handles things like
342 # the "proc" command by adding an entry for the index file. Returns a string
343 # that represents the index file.
346 # file Name of Tcl source file to be indexed.
348 proc auto_mkindex_parser::mkindex {file} {
352 variable contextStack
358 set contents [read $fid]
361 # There is one problem with sourcing files into the safe interpreter:
362 # references like "$x" will fail since code is not really being executed
363 # and variables do not really exist. To avoid this, we replace all $ with
364 # \0 (literally, the null char) later, when getting proc names we will
365 # have to reverse this replacement, in case there were any $ in the proc
366 # name. This will cause a problem if somebody actually tries to have a \0
367 # in their proc name. Too bad for them.
368 set contents [string map [list \$ \0] $contents]
374 $parser eval $contents
376 foreach name $imports {
377 catch {$parser eval [list _%@namespace forget $name]}
382 # auto_mkindex_parser::hook command
384 # Registers a Tcl command to evaluate when initializing the slave interpreter
385 # used by the mkindex parser. The command is evaluated in the master
386 # interpreter, and can use the variable auto_mkindex_parser::parser to get to
389 proc auto_mkindex_parser::hook {cmd} {
390 variable initCommands
392 lappend initCommands $cmd
395 # auto_mkindex_parser::slavehook command
397 # Registers a Tcl command to evaluate when initializing the slave interpreter
398 # used by the mkindex parser. The command is evaluated in the slave
401 proc auto_mkindex_parser::slavehook {cmd} {
402 variable initCommands
404 # The $parser variable is defined to be the name of the slave interpreter
405 # when this command is used later.
407 lappend initCommands "\$parser eval [list $cmd]"
410 # auto_mkindex_parser::command --
412 # Registers a new command with the "auto_mkindex_parser" interpreter that
413 # parses Tcl files. These commands are fake versions of things like the
414 # "proc" command. When you execute them, they simply write out an entry to a
415 # "tclIndex" file for auto-loading.
417 # This procedure allows extensions to register their own commands with the
418 # auto_mkindex facility. For example, a package like [incr Tcl] might
419 # register a "class" command so that class definitions could be added to a
420 # "tclIndex" file for auto-loading.
423 # name Name of command recognized in Tcl files.
424 # arglist Argument list for command.
425 # body Implementation of command to handle indexing.
427 proc auto_mkindex_parser::command {name arglist body} {
428 hook [list auto_mkindex_parser::commandInit $name $arglist $body]
431 # auto_mkindex_parser::commandInit --
433 # This does the actual work set up by auto_mkindex_parser::command. This is
434 # called when the interpreter used by the parser is created.
437 # name Name of command recognized in Tcl files.
438 # arglist Argument list for command.
439 # body Implementation of command to handle indexing.
441 proc auto_mkindex_parser::commandInit {name arglist body} {
444 set ns [namespace qualifiers $name]
445 set tail [namespace tail $name]
447 set fakeName [namespace current]::_%@fake_$tail
449 set fakeName [namespace current]::[string map {:: _} _%@fake_$name]
451 proc $fakeName $arglist $body
453 # YUK! Tcl won't let us alias fully qualified command names, so we can't
454 # handle names like "::itcl::class". Instead, we have to build procs with
455 # the fully qualified names, and have the procs point to the aliases.
457 if {[string match *::* $name]} {
458 set exportCmd [list _%@namespace export [namespace tail $name]]
459 $parser eval [list _%@namespace eval $ns $exportCmd]
461 # The following proc definition does not work if you want to tolerate
462 # space or something else diabolical in the procedure name, (i.e.,
463 # space in $alias). The following does not work:
464 # "_%@eval {$alias} \$args"
465 # because $alias gets concat'ed to $args. The following does not work
466 # because $cmd is somehow undefined
467 # "set cmd {$alias} \; _%@eval {\$cmd} \$args"
468 # A gold star to someone that can make test autoMkindex-3.3 work
471 set alias [namespace tail $fakeName]
472 $parser invokehidden proc $name {args} "_%@eval {$alias} \$args"
473 $parser alias $alias $fakeName
475 $parser alias $name $fakeName
480 # auto_mkindex_parser::fullname --
482 # Used by commands like "proc" within the auto_mkindex parser. Returns the
483 # qualified namespace name for the "name" argument. If the "name" does not
484 # start with "::", elements are added from the current namespace stack to
485 # produce a qualified name. Then, the name is examined to see whether or not
486 # it should really be qualified. If the name has more than the leading "::",
487 # it is returned as a fully qualified name. Otherwise, it is returned as a
488 # simple name. That way, the Tcl autoloader will recognize it properly.
491 # name - Name that is being added to index.
493 proc auto_mkindex_parser::fullname {name} {
494 variable contextStack
496 if {![string match ::* $name]} {
497 foreach ns $contextStack {
498 set name "${ns}::$name"
499 if {[string match ::* $name]} {
505 if {[namespace qualifiers $name] eq ""} {
506 set name [namespace tail $name]
507 } elseif {![string match ::* $name]} {
511 # Earlier, mkindex replaced all $'s with \0. Now, we have to reverse that
513 return [string map [list \0 \$] $name]
516 # auto_mkindex_parser::indexEntry --
518 # Used by commands like "proc" within the auto_mkindex parser to add a
519 # correctly-quoted entry to the index. This is shared code so it is done
520 # *right*, in one place.
523 # name - Name that is being added to index.
525 proc auto_mkindex_parser::indexEntry {name} {
529 # We convert all metacharacters to their backslashed form, and pre-split
530 # the file name that we know about (which will be a proper list, and so
533 set name [string range [list \}[fullname $name]] 2 end]
534 set filenameParts [file split $scriptFile]
536 append index [format \
537 {set auto_index(%s) [list source [file join $dir %s]]%s} \
538 $name $filenameParts \n]
542 if {[llength $::auto_mkindex_parser::initCommands]} {
546 # Register all of the procedures for the auto_mkindex parser that will build
547 # the "tclIndex" file.
549 # AUTO MKINDEX: proc name arglist body
550 # Adds an entry to the auto index list for the given procedure name.
552 auto_mkindex_parser::command proc {name args} {
556 # Conditionally add support for Tcl byte code files. There are some tricky
557 # details here. First, we need to get the tbcload library initialized in the
558 # current interpreter. We cannot load tbcload into the slave until we have
559 # done so because it needs access to the tcl_patchLevel variable. Second,
560 # because the package index file may defer loading the library until we invoke
561 # a command, we need to explicitly invoke auto_load to force it to be loaded.
562 # This should be a noop if the package has already been loaded
564 auto_mkindex_parser::hook {
566 package require tbcload
568 # OK, don't have it so do nothing
570 if {[namespace which -command tbcload::bcproc] eq ""} {
571 auto_load tbcload::bcproc
573 load {} tbcload $auto_mkindex_parser::parser
575 # AUTO MKINDEX: tbcload::bcproc name arglist body
576 # Adds an entry to the auto index list for the given pre-compiled
579 auto_mkindex_parser::commandInit tbcload::bcproc {name args} {
585 # AUTO MKINDEX: namespace eval name command ?arg arg...?
586 # Adds the namespace name onto the context stack and evaluates the associated
589 # AUTO MKINDEX: namespace import ?-force? pattern ?pattern...?
590 # Performs the "import" action in the parser interpreter. This is important
591 # for any commands contained in a namespace that affect the index. For
592 # example, a script may say "itcl::class ...", or it may import "itcl::*" and
593 # then say "class ...". This procedure does the import operation, but keeps
594 # track of imported patterns so we can remove the imports later.
596 auto_mkindex_parser::command namespace {op args} {
600 variable contextStack
602 set name [lindex $args 0]
603 set args [lrange $args 1 end]
605 set contextStack [linsert $contextStack 0 $name]
606 $parser eval [list _%@namespace eval $name] $args
607 set contextStack [lrange $contextStack 1 end]
612 foreach pattern $args {
613 if {$pattern ne "-force"} {
614 lappend imports $pattern
617 catch {$parser eval "_%@namespace import $args"}
621 variable contextStack
622 if {[lindex $args 0] eq "create"} {
623 set name ::[join [lreverse $contextStack] ::]
625 set name [dict get [lrange $args 1 end] -command]
626 if {![string match ::* $name]} {
627 set name ::[join [lreverse $contextStack] ::]$name
629 regsub -all ::+ $name :: name
631 # create artifical proc to force an entry in the tclIndex
632 $parser eval [list ::proc $name {} {}]
638 # AUTO MKINDEX: oo::class create name ?definition?
639 # Adds an entry to the auto index list for the given class name.
640 auto_mkindex_parser::command oo::class {op name {body ""}} {
641 if {$op eq "create"} {
645 auto_mkindex_parser::command class {op name {body ""}} {
646 if {$op eq "create"} {