OSDN Git Service

Please enter the commit message for your changes. Lines starting
[eos/hostdependX86LINUX64.git] / util / X86LINUX64 / lib / tcl8.6 / auto.tcl
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     # uniquify $dirs in order
123     array set seen {}
124     foreach i $dirs {
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]} {
130             set norm $i
131         } else {
132             set norm [file normalize $i]
133         }
134         if {[info exists seen($norm)]} {
135             continue
136         }
137         set seen($norm) {}
138         lappend uniqdirs $i
139     }
140     set dirs $uniqdirs
141     foreach i $dirs {
142         set the_library $i
143         set file [file join $i $initScript]
144
145         # source everything when in a safe interpreter because we have a
146         # source command, but no file exists command
147
148         if {[interp issafe] || [file exists $file]} {
149             if {![catch {uplevel #0 [list source $file]} msg opts]} {
150                 return
151             }
152             append errors "$file: $msg\n"
153             append errors [dict get $opts -errorinfo]\n
154         }
155     }
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"
161     error $msg
162 }
163
164
165 # ----------------------------------------------------------------------
166 # auto_mkindex
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.
173
174 if {[interp issafe]} {
175     return      ;# Stop sourcing the file here
176 }
177
178 # auto_mkindex --
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
182 # relevant files.
183 #
184 # Arguments:
185 # dir -         Name of the directory in which to create an index.
186
187 # args -        Any number of additional arguments giving the names of files
188 #               within dir.  If no additional are given auto_mkindex will look
189 #               for *.tcl.
190
191 proc auto_mkindex {dir args} {
192     if {[interp issafe]} {
193         error "can't generate index within safe interpreter"
194     }
195
196     set oldDir [pwd]
197     cd $dir
198
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]} {
207         set args *.tcl
208     }
209
210     auto_mkindex_parser::init
211     foreach file [glob -- {*}$args] {
212         try {
213             append index [auto_mkindex_parser::mkindex $file]
214         } on error {msg opts} {
215             cd $oldDir
216             return -options $opts $msg
217         }
218     }
219     auto_mkindex_parser::cleanup
220
221     set fid [open "tclIndex" w]
222     puts -nonewline $fid $index
223     close $fid
224     cd $oldDir
225 }
226
227 # Original version of auto_mkindex that just searches the source code for
228 # "proc" at the beginning of the line.
229
230 proc auto_mkindex_old {dir args} {
231     set oldDir [pwd]
232     cd $dir
233     set dir [pwd]
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]} {
242         set args *.tcl
243     }
244     foreach file [glob -- {*}$args] {
245         set f ""
246         set error [catch {
247             set f [open $file]
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"
253                 }
254             }
255             close $f
256         } msg opts]
257         if {$error} {
258             catch {close $f}
259             cd $oldDir
260             return -options $opts $msg
261         }
262     }
263     set f ""
264     set error [catch {
265         set f [open tclIndex w]
266         puts -nonewline $f $index
267         close $f
268         cd $oldDir
269     } msg opts]
270     if {$error} {
271         catch {close $f}
272         cd $oldDir
273         error $msg $info $code
274         return -options $opts $msg
275     }
276 }
277
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.
282
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]
292     }
293
294     proc init {} {
295         variable parser
296         variable initCommands
297
298         if {![interp issafe]} {
299             set parser [interp create -safe]
300             $parser hide info
301             $parser hide rename
302             $parser hide proc
303             $parser hide namespace
304             $parser hide eval
305             $parser hide puts
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
310             }
311             foreach cmd [$parser invokehidden info commands ::*] {
312                 $parser invokehidden rename $cmd {}
313             }
314             $parser invokehidden proc unknown {args} {}
315
316             # We'll need access to the "namespace" command within the
317             # interp.  Put it back, but move it out of the way.
318
319             $parser expose namespace
320             $parser invokehidden rename namespace _%@namespace
321             $parser expose eval
322             $parser invokehidden rename eval _%@eval
323
324             # Install all the registered psuedo-command implementations
325
326             foreach cmd $initCommands {
327                 eval $cmd
328             }
329         }
330     }
331     proc cleanup {} {
332         variable parser
333         interp delete $parser
334         unset parser
335     }
336 }
337
338 # auto_mkindex_parser::mkindex --
339 #
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.
344 #
345 # Arguments:
346 #       file    Name of Tcl source file to be indexed.
347
348 proc auto_mkindex_parser::mkindex {file} {
349     variable parser
350     variable index
351     variable scriptFile
352     variable contextStack
353     variable imports
354
355     set scriptFile $file
356
357     set fid [open $file]
358     set contents [read $fid]
359     close $fid
360
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]
369
370     set index ""
371     set contextStack ""
372     set imports ""
373
374     $parser eval $contents
375
376     foreach name $imports {
377         catch {$parser eval [list _%@namespace forget $name]}
378     }
379     return $index
380 }
381
382 # auto_mkindex_parser::hook command
383 #
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
387 # the slave
388
389 proc auto_mkindex_parser::hook {cmd} {
390     variable initCommands
391
392     lappend initCommands $cmd
393 }
394
395 # auto_mkindex_parser::slavehook command
396 #
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
399 # interpreter.
400
401 proc auto_mkindex_parser::slavehook {cmd} {
402     variable initCommands
403
404     # The $parser variable is defined to be the name of the slave interpreter
405     # when this command is used later.
406
407     lappend initCommands "\$parser eval [list $cmd]"
408 }
409
410 # auto_mkindex_parser::command --
411 #
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.
416 #
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.
421 #
422 # Arguments:
423 #       name    Name of command recognized in Tcl files.
424 #       arglist Argument list for command.
425 #       body    Implementation of command to handle indexing.
426
427 proc auto_mkindex_parser::command {name arglist body} {
428     hook [list auto_mkindex_parser::commandInit $name $arglist $body]
429 }
430
431 # auto_mkindex_parser::commandInit --
432 #
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.
435 #
436 # Arguments:
437 #       name    Name of command recognized in Tcl files.
438 #       arglist Argument list for command.
439 #       body    Implementation of command to handle indexing.
440
441 proc auto_mkindex_parser::commandInit {name arglist body} {
442     variable parser
443
444     set ns [namespace qualifiers $name]
445     set tail [namespace tail $name]
446     if {$ns eq ""} {
447         set fakeName [namespace current]::_%@fake_$tail
448     } else {
449         set fakeName [namespace current]::[string map {:: _} _%@fake_$name]
450     }
451     proc $fakeName $arglist $body
452
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.
456
457     if {[string match *::* $name]} {
458         set exportCmd [list _%@namespace export [namespace tail $name]]
459         $parser eval [list _%@namespace eval $ns $exportCmd]
460
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
469         # properly
470
471         set alias [namespace tail $fakeName]
472         $parser invokehidden proc $name {args} "_%@eval {$alias} \$args"
473         $parser alias $alias $fakeName
474     } else {
475         $parser alias $name $fakeName
476     }
477     return
478 }
479
480 # auto_mkindex_parser::fullname --
481 #
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.
489 #
490 # Arguments:
491 # name -                Name that is being added to index.
492
493 proc auto_mkindex_parser::fullname {name} {
494     variable contextStack
495
496     if {![string match ::* $name]} {
497         foreach ns $contextStack {
498             set name "${ns}::$name"
499             if {[string match ::* $name]} {
500                 break
501             }
502         }
503     }
504
505     if {[namespace qualifiers $name] eq ""} {
506         set name [namespace tail $name]
507     } elseif {![string match ::* $name]} {
508         set name "::$name"
509     }
510
511     # Earlier, mkindex replaced all $'s with \0.  Now, we have to reverse that
512     # replacement.
513     return [string map [list \0 \$] $name]
514 }
515
516 # auto_mkindex_parser::indexEntry --
517 #
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.
521 #
522 # Arguments:
523 # name -                Name that is being added to index.
524
525 proc auto_mkindex_parser::indexEntry {name} {
526     variable index
527     variable scriptFile
528
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
531     # correctly quoted).
532
533     set name [string range [list \}[fullname $name]] 2 end]
534     set filenameParts [file split $scriptFile]
535
536     append index [format \
537             {set auto_index(%s) [list source [file join $dir %s]]%s} \
538             $name $filenameParts \n]
539     return
540 }
541
542 if {[llength $::auto_mkindex_parser::initCommands]} {
543     return
544 }
545
546 # Register all of the procedures for the auto_mkindex parser that will build
547 # the "tclIndex" file.
548
549 # AUTO MKINDEX:  proc name arglist body
550 # Adds an entry to the auto index list for the given procedure name.
551
552 auto_mkindex_parser::command proc {name args} {
553     indexEntry $name
554 }
555
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
563
564 auto_mkindex_parser::hook {
565     try {
566         package require tbcload
567     } on error {} {
568         # OK, don't have it so do nothing
569     } on ok {} {
570         if {[namespace which -command tbcload::bcproc] eq ""} {
571             auto_load tbcload::bcproc
572         }
573         load {} tbcload $auto_mkindex_parser::parser
574
575         # AUTO MKINDEX:  tbcload::bcproc name arglist body
576         # Adds an entry to the auto index list for the given pre-compiled
577         # procedure name.
578
579         auto_mkindex_parser::commandInit tbcload::bcproc {name args} {
580             indexEntry $name
581         }
582     }
583 }
584
585 # AUTO MKINDEX:  namespace eval name command ?arg arg...?
586 # Adds the namespace name onto the context stack and evaluates the associated
587 # body of commands.
588 #
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.
595
596 auto_mkindex_parser::command namespace {op args} {
597     switch -- $op {
598         eval {
599             variable parser
600             variable contextStack
601
602             set name [lindex $args 0]
603             set args [lrange $args 1 end]
604
605             set contextStack [linsert $contextStack 0 $name]
606             $parser eval [list _%@namespace eval $name] $args
607             set contextStack [lrange $contextStack 1 end]
608         }
609         import {
610             variable parser
611             variable imports
612             foreach pattern $args {
613                 if {$pattern ne "-force"} {
614                     lappend imports $pattern
615                 }
616             }
617             catch {$parser eval "_%@namespace import $args"}
618         }
619         ensemble {
620             variable parser
621             variable contextStack
622             if {[lindex $args 0] eq "create"} {
623                 set name ::[join [lreverse $contextStack] ::]
624                 catch {
625                     set name [dict get [lrange $args 1 end] -command]
626                     if {![string match ::* $name]} {
627                         set name ::[join [lreverse $contextStack] ::]$name
628                     }
629                     regsub -all ::+ $name :: name
630                 }
631                 # create artifical proc to force an entry in the tclIndex
632                 $parser eval [list ::proc $name {} {}]
633             }
634         }
635     }
636 }
637
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"} {
642         indexEntry $name
643     }
644 }
645 auto_mkindex_parser::command class {op name {body ""}} {
646     if {$op eq "create"} {
647         indexEntry $name
648     }
649 }
650
651 return