Updated 2018-07-09 18:19:50 by pooryorick

How to make an alias for a proc

See Also  edit

interp alias
proc
ycl
includes this alias in its proc module

Description  edit

The common idiom for making an alias for a procedure is interp alias, but the byte-compiled versions of commands (not user procedures, but built-in commands) will not be used in that case. Below is an implementation of an idea suggested by MS for making aliases without missing out on that byte-compiled command goodness.

PYK 2014-06-23: I just noticed that kruzalex had already provided a similar command on the namespace page. I've taken some inspiration from his implementation and modified the code below.
proc alias {alias target} {
    set fulltarget [uplevel [list namespace which $target]]
    if {$fulltarget eq {}} {
        return -code error [list {no such command} $target]
    }
    set save [namespace eval [namespace qualifiers $fulltarget] {
        namespace export}]
    namespace eval [namespace qualifiers $fulltarget] {namespace export *}
    while {[namespace exists [
        set tmpns [namespace current]::[info cmdcount]]]} {}
    set code [catch {set newcmd [namespace eval $tmpns [
        string map [list @{fulltarget} [list $fulltarget]] {
        namespace import @{fulltarget}
    }]]} cres copts]
    namespace eval [namespace qualifiers $fulltarget] [
        list namespace export {*}$save]
    if {$code} {
        return -options $copts $cres
    }
    uplevel [list rename ${tmpns}::[namespace tail $target] $alias]
    namespace delete $tmpns 
    return [uplevel [list namespace which $alias]]
}

Example:
alias pset set
pset answer 42
puts $answer
rename ::pset {}

Larry Smith This doesn't work for ensemble aliases - "target" only takes the base name (e.g. "string") but quoting the ensemble (e.g. "info commands") yields:
{no such command} {info commands}
    while executing
"alias cmds "info commands""

alias cmds info commands (without quoting) just gets the usual mismatched arg list error.

PYK 2017-05-31: This mechanism is not designed for feature-parity with interp alias or other higher-level dispatch-mechanisms for such as namespace ensembles or methods of object systems. Rather, it targets the same things that namespace import targets: actual routines located in their respective namespaces.