user1476056
user1476056

Reputation: 257

Tcl rename of the proc keyword doesn't work well in namespaces

I have the following procedure:

rename proc _proc
_proc proc {name args body} {
    global pass_log_trace

    set g_log_trace "0"
    if {[info exists pass_log_trace]} {
        set g_log_trace $pass_log_trace
    }

    # simple check if we have double declaration of the same procedure
    if {[info procs $name] != ""} {
        puts "\nERROR: redeclaration of procedure: $name"
    }

    _proc $name $args $body

    if {$g_log_trace != 0} {
        trace add execution $name enter trace_report_enter
        trace add execution $name leave trace_report_leave
    }
}

The purpose of this procedure, mainly, is to add entry and exit point tracers to all the procedures in the code. However, for some reason it also removes the namespace scoping. For example, a code like this:

namespace eval bob {
    namespace eval joe {
        proc proc1 {} {}
    }
    proc proc2 {} {
        puts "proc2"
    }
}

puts "Namespace calling [info procs ::bob\::*]"

Would not create procedures in the bob namespace, but in the global namespace. Calling namespace current always returns ::.

Any ideas?

Upvotes: 3

Views: 1266

Answers (1)

Eric Melski
Eric Melski

Reputation: 16790

When you call _proc, prepend the namespace of the calling context by using a combination of uplevel and namespace current:

set ns [uplevel 1 {namespace current}]
_proc ${ns}::$name $args $body

Here uplevel 1 says, "Run this snippet of code in the caller's context", and as you already know, "namespace current" gives the fully-qualified name of the namespace it is invoked in.

Upvotes: 3

Related Questions