ad_proc (public)

 ad_proc [ -public ] [ -private ] [ -deprecated ] [ -warn ] \
    [ -callback callback ] [ -impl impl ] arg_list [doc_string] body

Defined in packages/acs-bootstrap-installer/tcl/00-proc-procs.tcl

Declare a procedure with the following enhancements over regular Tcl "proc":

  • A procedure can be declared as public, private, deprecated, and warn.
  • Procedures can be declared with regular positional parameters (where you pass parameters in the order they were declared), or with named parameters, where the order doesn't matter because parameter names are specified explicitly when calling the parameter. Named parameters are preferred.
  • If you use named parameters, you can specify which ones are required, optional, (including default values), and boolean. See the examples below.
  • Positional parameters are always required, unless they provide with a default value, making them optional. If the parameter follows another positional parameter with a default value, a default value for it is also required.
  • As well as in the original Tcl "proc", if the last parameter is called "args", the proc will accept a variable number of arguments, which will be assigned to the variable "args" as elements of a list.
  • There is now a callback facility. See below.
  • The declaration can (and should!) include documentation. This documentation may contain tags which are parsed for display by the API browser. Some tags are @param, @return, @error, @see, @author (probably this should be better documented).

When a parameter is declared as boolean, it creates a variable $param_name_p. For example: -foo:boolean will create a variable $foo_p. If the parameter is passed, $foo_p will have value 1. Otherwise, $foo_p will have value 0.

Boolean named parameters can optionally take a boolean value than can make your code cleaner. The following example by Michael Cleverly shows why: If you had a procedure declared as ad_proc foobar {-foo:boolean} { ... }, it could be invoked as foobar -foo, which could yield some code like the following in your procedure:

if {$flush_p} {
    some_proc -flush $key
} else {
    some_proc $key
}
    

However, you could invoke the procedure as foobar -foo=$some_boolean_value (where some_boolean_value can be 0, 1, t, f, true, false), which could make your procedure cleaner because you could write instead: some_proc -flush=$foo_p $key.

With named parameters, the same rule as the Tcl switch statement apply, meaning that -- marks the end of the parameters. This is important if your named parameter contains a value of something starting with a "-".

Here's an example with named and positional parameters, and also namespaces (notice the preferred way of declaring namespaces and namespaced procedures). Ignore the \ in "\@param", I had to use it so the API browser wouldn't think the parameter docs were for ad_proc itself:

namespace eval ::foobar {}

ad_proc -public ::foobar::new {
    {-oacs_user:boolean}
    {-shazam:required}
    {-foo}
    {-user_id ""}
    {pos}
    {pos_opt ""}
} {
    The documentation for this procedure should have a brief description of the
    purpose of the procedure (the WHAT), but most importantly, WHY it does what it
    does. One can read the code and see what it does (but it's quicker to see a
    description), but one cannot read the mind of the original programmer to find out
    what s/he had in mind.

    \@author Roberto Mello 
    \@creation-date 2002-01-21

    \@param oacs_user   If this user is already an OpenACS user. oacs_user_p is defined
                        per default as "false", when specified as "true". The parameter is optional.
    \@param shazam      Magical incantation that calls Captain Marvel. Required parameter.
    \@param foo         Parameter, which can be omitted. Check with [info exists ...] if was given.
    \@param user_id     The id for the user to process. Optional with default "".
                        (api-browser shows the default).
    \@param pos         Positional parameter. Required, as it does not provide a default value.
    \@param pos_opt     Positional parameter. Optional with default "".
                        (api-browser shows the default).
    \@return empty list

    \@see ::foobar::related_proc
} {
    if { $user_id eq "" } {
        # Do something if this is not an empty string
    }
    if { [info exists foo] } {
        # Do something if we got a value for "foo"
    }

    if { $oacs_user_p } {
        # Do something if this is an OpenACS user
    }

    # return empty list anyway...
    return [list]
}

(note, most of the info on callbacks here due to leeldn)

You can define callbacks, both generally (which you would do first) and specific to a particular implementation. The way you do so is:

  • you have to first define the callback contract with ad_proc -callback foo::bar::zip { arg1 arg2 } { docs } -

    This defines the callback generally. (Note! Don't define a body here!)

  • then define an implementation with ad_proc -callback foo::bar::zip -impl myimpl { } { } { #code }
  • Two ways to call:
    • then you can call _all_ implementations (i.e. in an event / event handler type arrangement) with callback foo::bar::zip $arg1 $arg2
    • or you can call a specific implementation (i.e. in a service contract type arrangement) with callback -impl myimpl foo::bar::zip $arg1 $arg2
  • in both cases the result is a list of the results of each called implementation (with empty results removed), so in the case of calling a specific implementation you get a list of one element as the result
  • See callback for more info.

Switches:
-public (boolean) (optional)
specifies that the procedure is part of a public API.
-private (boolean) (optional)
specifies that the procedure is package-private.
-deprecated (boolean) (optional)
specifies that the procedure should not be used.
-warn (boolean) (optional)
specifies that the procedure should generate a warning when invoked (requires that -deprecated also be set)
-callback (optional)
the name of the callback contract being defined or implemented
-impl (optional)
the name of the callback implementation for the specified contract
Parameters:
arg_list - the list of switches and positional parameters which can be provided to the procedure.
[doc_string] - documentation for the procedure (optional, but greatly desired).
body - the procedure body. Documentation may be provided for an arbitrary function by passing the body as a "-".

Partial Call Graph (max 5 caller/called nodes):
%3 test_ad_proc_create_callback ad_proc_create_callback (test acs-tcl) ad_proc ad_proc test_ad_proc_create_callback->ad_proc ad_parse_documentation_string ad_parse_documentation_string ad_proc->ad_parse_documentation_string ad_proc_valid_switch_p ad_proc_valid_switch_p (public) ad_proc->ad_proc_valid_switch_p callback callback (public) ad_proc->callback Class ::xo::db::Class Class ::xo::db::Class (public) Class ::xo::db::Class->ad_proc aa_register_case aa_register_case (public) aa_register_case->ad_proc aa_register_component aa_register_component (public) aa_register_component->ad_proc aa_register_init_class aa_register_init_class (public) aa_register_init_class->ad_proc acs_sc_proc acs_sc_proc (private) acs_sc_proc->ad_proc

Testcases:
ad_proc_create_callback
Source code:
    set public_p 0
    set private_p 0
    set deprecated_p 0
    set warn_p 0
    set debug_p 0
    set callback ""
    set impl ""

    # Loop through args, stopping at the first argument which is
    # not a switch.
    for { set i 0 } { $i < [llength $args] } { incr i } {
        set arg [lindex $args $i]

        # If the argument doesn't begin with a hyphen, break.
        if { ![ad_proc_valid_switch_p $arg] } {
            break
        }

        # If the argument is "--", stop parsing for switches (but
        # bump up $i to the next argument, which is the first
        # argument which is not a switch).
        if {$arg eq "--"} {
            incr i
            break
        }

        switch -- $arg {
            -public { set public_p 1 }
            -private { set private_p 1 }
            -deprecated { set deprecated_p 1 }
            -warn { set warn_p 1 }
            -debug { set debug_p 1 }
            -callback {
                incr i
                set callback [lindex $args $i]
                if { [ad_proc_valid_switch_p $callback] } {
                    return -code error "Missing callback name: -callback <name>"
                }
            }
            -impl {
                incr i
                set impl [lindex $args $i]
                if { [ad_proc_valid_switch_p $impl] } {
                    return -code error "Missing implementation name: -impl <name>"
                }
            }
            default {
                return -code error "Invalid switch [lindex $args $i] passed to ad_proc"
            }
        }
    }

    if { $public_p && $private_p } {
        return -code error "Mutually exclusive switches -public and -private passed to ad_proc"
    }

    if { !$public_p && !$private_p } {
        set public_p 1
    }
    if {$public_p} {
        set protection public
    } else {
        set protection private
    }

    if { $warn_p && !$deprecated_p } {
        return -code error "Switch -warn can be provided to ad_proc only if -deprecated is also provided"
    }

    if { $deprecated_p } {
        set warn_p 1
    }

    if { $impl ne "" && $callback eq "" } {
        return -code error "A callback contract name must be specified with -callback when defining an implementation with -impl"
    }

    if { $impl eq "impl" || [string match $impl "impl::*"] } {
        return -code error "Callback implementations may not be named impl"
    }

    if { $callback eq "contract" || [string match $callback "contract::*"] } {
        return -code error "Callbacks may not be named contract"
    }

    # Now $i is set to the index of the first non-switch argument.
    # There must be either three or four arguments remaining.
    set n_args_remaining [expr { [llength $args] - $i }]

    if {$callback eq ""} {
        #
        # We are creating an ordinary proc so the proc name is an
        # argument
        #
        if { $n_args_remaining < 3 || $n_args_remaining > 4} {
            return -code error "Wrong number of arguments passed to ad_proc"
        }

        # Set up the remaining arguments.
        set proc_name [lindex $args $i]
    } else {
        if {$impl ne "" } {
            #
            # We are creating a callback implementation
            #
            if {$n_args_remaining != 3} {
                return -code error "ad_proc callback implementation must have: arguments (can be empty) docs code_body"
            }
        }
        if {$impl eq ""} {
            #
            # We are creating a contract for a callback
            #
            if {!( $n_args_remaining == 3 || $n_args_remaining == 2 ) } {
                return -code error "ad_proc callback contract must have: arguments docs \[empty_code_body\]"
            } elseif {$n_args_remaining == 3
                      && [lindex $args end] ne ""
                      && [lindex $args end] ne "-" } {
                return -code error "ad_proc callback contract must have an empty code_body"
            }
        }

        set callback [string trimleft $callback ::]
        set proc_name ::callback::${callback}

        if {$impl eq ""} {
            append proc_name ::contract
        } else {
            append proc_name ::impl::${impl}
        }

        # pretend to the rest of the proc that we were passed the proc name
        incr n_args_remaining
        set args [linsert $args 0 $proc_name]
    }

    # (SDW - OpenACS). If proc_name is being defined inside a namespace, we
    # want to use the fully qualified name. Except for actually defining the
    # proc where we want to use the name as passed to us. We always set
    # proc_name_as_passed and conditionally make proc_name fully qualified
    # if we were called from inside a namespace eval.

    #
    # RBM: 2003-01-26:
    # With the help of Michael Cleverly, fixed the namespace code so procs
    # declared like ::foo::bar would work, by only trimming the first ::
    # Also moved the uplevel'd call to namespace current to the if statement,
    # to avoid it being called unnecessarily.
    #

    set proc_name_as_passed $proc_name
    set parent_namespace [string trimleft [uplevel 1 {::namespace current}] ::]

    if { ![string match "::*" $proc_name] } {
        set proc_name ${parent_namespace}::$proc_name
    }
    if {$parent_namespace ne {} && ![string match "::*" $proc_name]} {
        ns_log Debug "proc $proc_name_as_passed declared in namespace $parent_namespace via namespace eval; coding standard is to declare as $proc_name"
    }
    set proc_name [string trimleft $proc_name ::]


    if { $callback ne "" } {
        # Do a namespace eval of each namespace to ensure it exists
        set namespaces [lrange [split $proc_name ::] 0 end-1]

        set curr_ns ""
        foreach ns $namespaces {
            if {$ns ne "" } {
                append curr_ns "::$ns"
                namespace eval $curr_ns {}
            }
        }
    }

    set arg_list [lindex $args $i+1]
    if { $n_args_remaining == 3 } {
        # No doc string provided.
        #ns_log notice "missing doc string for ad_proc $proc_name ([info script])"
        array set doc_elements [list]
        set doc_elements(main) ""
    } else {
        # Doc string was provided.
        ad_parse_documentation_string [lindex $args end-1] doc_elements
    }

    #
    # Preserve pre-existing values, e.g. from testcases, which might
    # be loaded in a different order.
    #
    if {[nsv_exists api_proc_doc $proc_name]} {
        set old_doc_elements [nsv_get api_proc_doc $proc_name]
        #array set doc_elements $old_doc_elements
        if {[dict exist $old_doc_elements testcase]} {
            #ns_log notice "PRESERVE TESTCASES: $proc_name"
            set doc_elements(testcase) [dict get $old_doc_elements testcase]
        }
    }

    set code_block [lindex $args end]

    if {$callback ne "" && $impl ne "" } {
        if {[info exists doc_elements(see)]} {
            lappend doc_elements(see) "callback::${callback}::contract"
        } else {
            set doc_elements(see) "callback::${callback}::contract"
        }
    }

    #####
    #
    #  Parse the argument list.
    #
    #####

    set switches [list]
    set positionals [list]
    set seen_positional_with_default_p 0
    set n_positionals_with_defaults 0
    array set default_values [list]
    array set flags [list]
    set varargs_p 0
    set switch_code ""

    # If the first element contains 0 or more than 2 elements, then it must
    # be an old-style ad_proc. Mangle effective_arg_list accordingly.
    if { [llength $arg_list] > 0 } {
        set first_arg [lindex $arg_list 0]
        if { [llength $first_arg] == 0 || [llength $first_arg] > 2 } {
            ns_log Warning "Convert old (deprecated) style proc: $proc_name"
            set new_arg_list [list]
            foreach { switch default_value } $first_arg {
                lappend new_arg_list [list $switch $default_value]
            }
            set arg_list [concat $new_arg_list [lrange $arg_list 1 end]]
        }
    }

    set effective_arg_list $arg_list

    set last_arg [lindex $effective_arg_list end]
    if { [llength $last_arg] == 1 && [lindex $last_arg 0] eq "args" } {
        set varargs_p 1
        set effective_arg_list [lrange $effective_arg_list 0 [llength $effective_arg_list]-2]
    }

    set check_code ""
    foreach arg $effective_arg_list {
        if { [llength $arg] == 2 } {
            set default_p 1
            lassign $arg arg default_value
        } else {
            if { [llength $arg] != 1 } {
                return -code error "Invalid element \"$arg\" in argument list"
            }
            set default_p 0
        }

        set arg_flags [list]
        set arg_split [split $arg ":"]
        if { [llength $arg_split] == 2 } {
            set arg [lindex $arg_split 0]
            foreach flag [split [lindex $arg_split 1] ","] {
                set flag [string trim $flag]
                if { $flag ne "required" && $flag ne "boolean" } {
                    return -code error "Invalid flag \"$flag\""
                }
                lappend arg_flags $flag
            }
        } elseif { [llength $arg_split] != 1 } {
            return -code error "Invalid element \"$arg\" in argument list"
        }

        if {[string index $arg 0] eq "-"} {
            if { [llength $positionals] > 0 } {
                return -code error "Switch -$arg specified after positional parameter"
            }

            set switch_p 1
            set arg [string range $arg 1 end]
            lappend switches $arg

            if {"boolean" in $arg_flags} {
                set default_values(${arg}_p) 0
                append switch_code "            -$arg - -$arg=1 - -$arg=t - -$arg=true {
                        ::uplevel ::set ${arg}_p 1
                    }
                    -$arg=0 - -$arg=f - -$arg=false {
                        ::uplevel ::set ${arg}_p 0
                    }
                "
            } else {
                append switch_code "            -$arg {
                    if { \$i >= \[llength \$args\] - 1 } {
                        ::return -code error \"No argument to switch -$arg\"
                    }
                    ::upvar ${arg} val ; ::set val \[::lindex \$args \[::incr i\]\]\n"
                append switch_code "            }\n"
            }

            if {"required" in $arg_flags} {
                append check_code "    ::if { !\[::uplevel ::info exists $arg\] } {
                    ::return -code error \"Required switch -$arg not provided\"
                    }
                "
            }
        } else {
            set switch_p 0
            if { $default_p } {
                incr n_positionals_with_defaults
            }
            if { !$default_p && $n_positionals_with_defaults != 0 } {
                return -code error "Positional parameter $arg needs a default value (since it follows another positional parameter with a default value)"
            }
            lappend positionals $arg
        }

        set flags($arg$arg_flags

        if { $default_p } {
            set default_values($arg$default_value
        }

        if { [llength $arg_split] > 2 } {
            return -code error "Invalid format for parameter name: \"$arg\""
        }
    }

    foreach element { protection deprecated_p warn_p varargs_p arg_list switches positionals } {
        set doc_elements($element) [set $element]
    }
    foreach element { default_values flags } {
        set doc_elements($element) [array get $element]
    }

    set script [info script]
    set root_length [string length $::acs::rootdir]
    if { $::acs::rootdir eq [string range $script 0 $root_length-1] } {
        set script [string range $script $root_length+1 end]
    }

    set doc_elements(script) $script
    #
    # As acs-automated-testing/tcl/aa-test-procs.tcl is loaded on startup before
    # acs-bootstrap-installer/tcl/00-proc-procs.tcl, it is possible that the
    # testcase element of the api_proc_doc nsv has been already populated,
    # therefore creating the key for that proc on the nsv.
    #
    # Previously, some procs where not included in the api_proc_doc_scripts nsv
    # because of that, as the nsv lappend was skipped if the key existed.
    #
    # For example:
    # - file_storage::twt::delete_file
    # - file_storage::twt::create_url_in_folder
    # - file_storage::twt::create_url
    # - ...
    #
    # We avoid this by checking as well if the testcase element is the only one
    # for that particular proc in the nsv.
    #
    if { ![nsv_exists api_proc_doc $proc_name] ||
         ([dict exists [nsv_get api_proc_doc $proc_name] testcase] &&
          [dict size [nsv_get api_proc_doc $proc_name]] eq "1")
    } {
        nsv_lappend api_proc_doc_scripts $script $proc_name
    }

    nsv_set api_proc_doc $proc_name [array get doc_elements]

    # Backward compatibility: set proc_doc and proc_source_file
    nsv_set proc_doc $proc_name [lindex $doc_elements(main) 0]
    if { [nsv_exists proc_source_file $proc_name]
      && [nsv_get proc_source_file $proc_name] ne [info script]
     } {
        ns_log Warning "Multiple definition of $proc_name in [nsv_get proc_source_file $proc_name] and [info script]"
    }
    nsv_set proc_source_file $proc_name [info script]

    if {$code_block eq "-"} {
        if {$callback eq ""} {
            return
        } else {
            # we are creating a callback so create an empty body
            set code_block {
            # this is a callback contract which only invokes its arg parser for input validation
            }
        }
    }

    set log_code ""
    if { $warn_p } {
        set log_code "ns_log Notice \"Deprecated proc $proc_name used:\\n\[ad_get_tcl_call_stack\]\"\n"
    }

    if { $callback ne "" && $impl ne "" } {

        if { [info commands "::callback::${callback}::contract__arg_parser"] eq "" } {
            # We create a dummy arg parser for the contract in case
            # the contract hasn't been defined yet.  We need this
            # because the implementation doesn't tell us what the
            # args of the contract should be.
            uplevel [::list proc ::callback::${callback}::contract__arg_parser {} {}]
        }

        # We are creating a callback implementation so we invoke the
        # arg parser of the contract proc

        if {$::acs::useNsfProc} {
            uplevel [::list proc $proc_name_as_passed args  "    ::callback::${callback}::contract__arg_parser {*}\$args\n${log_code}$code_block"]
        } else {
            uplevel [::list proc $proc_name_as_passed args  "    ::callback::${callback}::contract__arg_parser\n${log_code}$code_block"]
        }

    } elseif$callback eq "" && [llength $switches] == 0 } {
        #
        # Nothing special is used in the argument definition, create a
        # plain proc
        #
        #set ___ [::list proc $proc_name_as_passed $arg_list "${log_code}$code_block"]
        #ns_log notice "ad_proc NOTHING SPECIAL uplevel $___"
        uplevel [::list proc $proc_name_as_passed $arg_list "${log_code}$code_block"]

    } else {
        #
        # Default case, plain Tcl can't handle these cases
        #

        if {$::acs::useNsfProc} {
            #
            # nsf::proc can handle these cases. Just in case of the
            # callback implementations we have to provide an
            # arg_parser of the contract, since OpenACS uses always
            # the argument definition of the contract to pass
            # arguments in the implementation (which can be very
            # confusing).
            #
            if {$callback ne ""} {
                uplevel [::list ::nsf::proc -ad ::callback::${callback}::contract__arg_parser $arg_list {
                    foreach _ [info vars] {
                        uplevel [::list set $_ [set $_]]
                    }
                }]
            }
            #ns_log notice "---- define nsf::proc for [::list proc $proc_name_as_passed $arg_list $code_block]"
            uplevel [::list ::nsf::proc -ad $proc_name_as_passed $arg_list ${log_code}$code_block]
            return
        }

        #
        # There is no nsf::proc available. Define for every remaining
        # function two procs, one for argument parsing, and one for
        # the invocation. The latter one is defined with "args" and
        # calls as first step the argument parser.
        #
        set parser_code "    ::upvar args args\n"
        foreach { name value } [array get default_values] {
            append parser_code "    ::upvar $name val ; ::set val [::list $value]\n"
        }

        append parser_code "
            ::for { ::set i 0 } { \$i < \[::llength \$args\] } { ::incr i } {
                ::set arg \[::lindex \$args \$i\]
                ::if { !\[::ad_proc_valid_switch_p \$arg\] } {
                    ::break
                }
                ::if { \[::string equal \$arg \"--\"\] } {
                    ::incr i
                    ::break
                }
                ::switch -- \$arg {
        $switch_code
                    default { ::return -code error \"Invalid switch: \\\"\$arg\\\"\" }
                }
            }
        "

        set n_required_positionals [expr { [llength $positionals] - $n_positionals_with_defaults }]
        append parser_code "
            ::set n_args_remaining \[::expr { \[::llength \$args\] - \$i }\]
            ::if { \$n_args_remaining < $n_required_positionals } {
                ::return -code error \"No value specified for argument \[::lindex { [::lrange $positionals 0 [::expr { $n_required_positionals - 1 }]] } \$n_args_remaining\]\"
            }
        "
        for { set i 0 } { $i < $n_required_positionals } { incr i } {
                append parser_code "    ::upvar [::lindex $positionals $i] val ; ::set val \[::lindex \$args \[::expr { \$i + $i }\]\]\n"
        }
        for {} { $i < [llength $positionals] } { incr i } {
            append parser_code "    ::if { \$n_args_remaining > $i } {
                    ::upvar [::lindex $positionals $i] val ; ::set val \[::lindex \$args \[::expr { \$i + $i }\]\]
                }
            "
        }

        if { $varargs_p } {
            append parser_code "    ::set args \[::lrange \$args \[::expr { \$i + [::llength $positionals] }\] end\]\n"
        } else {
            append parser_code "    ::if { \$n_args_remaining > [::llength $positionals] } {
                    return -code error \"Too many positional parameters specified\"
                }
                ::unset args
            "
        }

        append parser_code $check_code

        if { $debug_p } {
            ns_write "PARSER CODE:\n\n$parser_code\n\n"
        }

        #
        # old style proc
        # for a function foo, define "foo $args" and "foo__arg_parser"
        #
        #ns_log notice "=== old style proc $proc_name_as_passed"

        uplevel [::list proc ${proc_name_as_passed}__arg_parser {} $parser_code]
        uplevel [::list proc $proc_name_as_passed args "    ${proc_name_as_passed}__arg_parser\n${log_code}$code_block"]
    }
XQL Not present:
Generic, PostgreSQL, Oracle
[ hide source ] | [ make this the default ]
Show another procedure: